diff options
Diffstat (limited to 'contrib/llvm/tools/clang/lib/Frontend')
23 files changed, 707 insertions, 587 deletions
diff --git a/contrib/llvm/tools/clang/lib/Frontend/ASTConsumers.cpp b/contrib/llvm/tools/clang/lib/Frontend/ASTConsumers.cpp index f53c614..52776b6 100644 --- a/contrib/llvm/tools/clang/lib/Frontend/ASTConsumers.cpp +++ b/contrib/llvm/tools/clang/lib/Frontend/ASTConsumers.cpp @@ -21,7 +21,6 @@ #include "clang/Basic/Diagnostic.h" #include "clang/Basic/FileManager.h" #include "clang/Basic/SourceManager.h" -#include "llvm/IR/Module.h" #include "llvm/Support/Path.h" #include "llvm/Support/Timer.h" #include "llvm/Support/raw_ostream.h" diff --git a/contrib/llvm/tools/clang/lib/Frontend/ASTMerge.cpp b/contrib/llvm/tools/clang/lib/Frontend/ASTMerge.cpp index 216ac6a..b84df94 100644 --- a/contrib/llvm/tools/clang/lib/Frontend/ASTMerge.cpp +++ b/contrib/llvm/tools/clang/lib/Frontend/ASTMerge.cpp @@ -57,6 +57,7 @@ void ASTMergeAction::ExecuteAction() { /*MinimalImport=*/false); TranslationUnitDecl *TU = Unit->getASTContext().getTranslationUnitDecl(); + CI.getASTConsumer().Initialize(CI.getASTContext()); for (auto *D : TU->decls()) { // Don't re-import __va_list_tag, __builtin_va_list. if (const auto *ND = dyn_cast<NamedDecl>(D)) @@ -64,7 +65,12 @@ void ASTMergeAction::ExecuteAction() { if (II->isStr("__va_list_tag") || II->isStr("__builtin_va_list")) continue; - Importer.Import(D); + Decl *ToD = Importer.Import(D); + + if (ToD) { + DeclGroupRef DGR(ToD); + CI.getASTConsumer().HandleTopLevelDecl(DGR); + } } } diff --git a/contrib/llvm/tools/clang/lib/Frontend/ASTUnit.cpp b/contrib/llvm/tools/clang/lib/Frontend/ASTUnit.cpp index a3998fa..7226344 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,24 @@ 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) { + + 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, *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 +395,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 +412,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 +421,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, *CachedCompletionAllocator, CCTUInfo, + IncludeBriefCommentsInCodeCompletion); CachedResult.ShowInContexts = RemainingContexts; CachedResult.Priority = CCP_NestedNameSpecifier; CachedResult.TypeClass = STC_Void; @@ -448,11 +443,9 @@ void ASTUnit::CacheCodeCompletionResults() { case Result::RK_Macro: { CachedCodeCompletionResult CachedResult; - CachedResult.Completion - = Results[I].CreateCodeCompletionString(*TheSema, - *CachedCompletionAllocator, - CCTUInfo, - IncludeBriefCommentsInCodeCompletion); + CachedResult.Completion = R.CreateCodeCompletionString( + *TheSema, *CachedCompletionAllocator, CCTUInfo, + IncludeBriefCommentsInCodeCompletion); CachedResult.ShowInContexts = (1LL << CodeCompletionContext::CCC_TopLevel) | (1LL << CodeCompletionContext::CCC_ObjCInterface) @@ -466,10 +459,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 +513,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; @@ -689,8 +682,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. @@ -721,6 +714,13 @@ std::unique_ptr<ASTUnit> ASTUnit::LoadFromASTFile( *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 +740,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 +848,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 +857,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 { @@ -931,9 +926,8 @@ public: 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 @@ -953,8 +947,7 @@ public: // 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 +966,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 +1002,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); } } } @@ -1300,14 +1293,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; } @@ -1634,11 +1623,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(); @@ -1943,9 +1931,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; @@ -2015,9 +2003,9 @@ 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 @@ -2375,10 +2363,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 @@ -2446,7 +2433,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 +2447,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 +2496,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 +2512,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 +2719,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 +2728,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 +2802,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; } diff --git a/contrib/llvm/tools/clang/lib/Frontend/CacheTokens.cpp b/contrib/llvm/tools/clang/lib/Frontend/CacheTokens.cpp index d909d52..7d2a09c 100644 --- a/contrib/llvm/tools/clang/lib/Frontend/CacheTokens.cpp +++ b/contrib/llvm/tools/clang/lib/Frontend/CacheTokens.cpp @@ -183,7 +183,7 @@ class PTHWriter { typedef llvm::StringMap<OffsetOpt, llvm::BumpPtrAllocator> CachedStrsTy; IDMap IM; - llvm::raw_fd_ostream& Out; + raw_pwrite_stream &Out; Preprocessor& PP; uint32_t idcount; PTHMap PM; @@ -236,8 +236,8 @@ class PTHWriter { Offset EmitCachedSpellings(); public: - PTHWriter(llvm::raw_fd_ostream& out, Preprocessor& pp) - : Out(out), PP(pp), idcount(0), CurStrOffset(0) {} + PTHWriter(raw_pwrite_stream &out, Preprocessor &pp) + : Out(out), PP(pp), idcount(0), CurStrOffset(0) {} PTHMap &getPM() { return PM; } void GeneratePTH(const std::string &MainFile); @@ -468,6 +468,16 @@ Offset PTHWriter::EmitCachedSpellings() { return SpellingsOff; } +static uint32_t swap32le(uint32_t X) { + return llvm::support::endian::byte_swap<uint32_t, llvm::support::little>(X); +} + +static void pwrite32le(raw_pwrite_stream &OS, uint32_t Val, uint64_t &Off) { + uint32_t LEVal = swap32le(Val); + OS.pwrite(reinterpret_cast<const char *>(&LEVal), 4, Off); + Off += 4; +} + void PTHWriter::GeneratePTH(const std::string &MainFile) { // Generate the prologue. Out << "cfe-pth" << '\0'; @@ -520,11 +530,11 @@ void PTHWriter::GeneratePTH(const std::string &MainFile) { Offset FileTableOff = EmitFileTable(); // Finally, write the prologue. - Out.seek(PrologueOffset); - Emit32(IdTableOff.first); - Emit32(IdTableOff.second); - Emit32(FileTableOff); - Emit32(SpellingOff); + uint64_t Off = PrologueOffset; + pwrite32le(Out, IdTableOff.first, Off); + pwrite32le(Out, IdTableOff.second, Off); + pwrite32le(Out, FileTableOff, Off); + pwrite32le(Out, SpellingOff, Off); } namespace { @@ -537,7 +547,7 @@ class StatListener : public FileSystemStatCache { PTHMap &PM; public: StatListener(PTHMap &pm) : PM(pm) {} - ~StatListener() {} + ~StatListener() override {} LookupResult getStat(const char *Path, FileData &Data, bool isFile, std::unique_ptr<vfs::File> *F, @@ -559,8 +569,7 @@ public: }; } // end anonymous namespace - -void clang::CacheTokens(Preprocessor &PP, llvm::raw_fd_ostream* OS) { +void clang::CacheTokens(Preprocessor &PP, raw_pwrite_stream *OS) { // Get the name of the main file. const SourceManager &SrcMgr = PP.getSourceManager(); const FileEntry *MainFile = SrcMgr.getFileEntryForID(SrcMgr.getMainFileID()); diff --git a/contrib/llvm/tools/clang/lib/Frontend/ChainedIncludesSource.cpp b/contrib/llvm/tools/clang/lib/Frontend/ChainedIncludesSource.cpp index cb260b4..f3677f8 100644 --- a/contrib/llvm/tools/clang/lib/Frontend/ChainedIncludesSource.cpp +++ b/contrib/llvm/tools/clang/lib/Frontend/ChainedIncludesSource.cpp @@ -27,7 +27,7 @@ using namespace clang; namespace { class ChainedIncludesSource : public ExternalSemaSource { public: - virtual ~ChainedIncludesSource(); + ~ChainedIncludesSource() override; ExternalSemaSource &getFinalReader() const { return *FinalReader; } @@ -43,6 +43,7 @@ protected: Selector GetExternalSelector(uint32_t ID) override; uint32_t GetNumExternalSelectors() override; Stmt *GetExternalDeclStmt(uint64_t Offset) override; + CXXCtorInitializer **GetExternalCXXCtorInitializers(uint64_t Offset) override; CXXBaseSpecifier *GetExternalCXXBaseSpecifiers(uint64_t Offset) override; bool FindExternalVisibleDeclsByName(const DeclContext *DC, DeclarationName Name) override; @@ -232,6 +233,10 @@ CXXBaseSpecifier * ChainedIncludesSource::GetExternalCXXBaseSpecifiers(uint64_t Offset) { return getFinalReader().GetExternalCXXBaseSpecifiers(Offset); } +CXXCtorInitializer ** +ChainedIncludesSource::GetExternalCXXCtorInitializers(uint64_t Offset) { + return getFinalReader().GetExternalCXXCtorInitializers(Offset); +} bool ChainedIncludesSource::FindExternalVisibleDeclsByName(const DeclContext *DC, DeclarationName Name) { diff --git a/contrib/llvm/tools/clang/lib/Frontend/CompilerInstance.cpp b/contrib/llvm/tools/clang/lib/Frontend/CompilerInstance.cpp index 93a34b7..9e01727 100644 --- a/contrib/llvm/tools/clang/lib/Frontend/CompilerInstance.cpp +++ b/contrib/llvm/tools/clang/lib/Frontend/CompilerInstance.cpp @@ -329,14 +329,8 @@ void CompilerInstance::createPreprocessor(TranslationUnitKind TUKind) { PP->setPreprocessedOutput(getPreprocessorOutputOpts().ShowCPP); - // Set up the module path, including the hash for the - // module-creation options. - SmallString<256> SpecificModuleCache( - getHeaderSearchOpts().ModuleCachePath); - if (!getHeaderSearchOpts().DisableModuleHash) - llvm::sys::path::append(SpecificModuleCache, - getInvocation().getModuleHash()); - PP->getHeaderSearchInfo().setModuleCachePath(SpecificModuleCache); + if (PP->getLangOpts().Modules) + PP->getHeaderSearchInfo().setModuleCachePath(getSpecificModuleCachePath()); // Handle generating dependencies, if requested. const DependencyOutputOptions &DepOpts = getDependencyOutputOpts(); @@ -371,14 +365,17 @@ void CompilerInstance::createPreprocessor(TranslationUnitKind TUKind) { AttachHeaderIncludeGen(*PP, /*ShowAllHeaders=*/false, /*OutputPath=*/"", /*ShowDepth=*/true, /*MSStyle=*/true); } +} - // Load all explictly-specified module map files. - for (const auto &Filename : getFrontendOpts().ModuleMapFiles) { - if (auto *File = getFileManager().getFile(Filename)) - PP->getHeaderSearchInfo().loadModuleMapFile(File, /*IsSystem*/false); - else - getDiagnostics().Report(diag::err_module_map_not_found) << Filename; - } +std::string CompilerInstance::getSpecificModuleCachePath() { + // Set up the module path, including the hash for the + // module-creation options. + SmallString<256> SpecificModuleCache( + getHeaderSearchOpts().ModuleCachePath); + if (!getHeaderSearchOpts().DisableModuleHash) + llvm::sys::path::append(SpecificModuleCache, + getInvocation().getModuleHash()); + return SpecificModuleCache.str(); } // ASTContext @@ -396,32 +393,30 @@ void CompilerInstance::createASTContext() { void CompilerInstance::createPCHExternalASTSource( StringRef Path, bool DisablePCHValidation, bool AllowPCHWithCompilerErrors, void *DeserializationListener, bool OwnDeserializationListener) { - IntrusiveRefCntPtr<ExternalASTSource> Source; bool Preamble = getPreprocessorOpts().PrecompiledPreambleBytes.first != 0; - Source = createPCHExternalASTSource( + ModuleManager = createPCHExternalASTSource( Path, getHeaderSearchOpts().Sysroot, DisablePCHValidation, AllowPCHWithCompilerErrors, getPreprocessor(), getASTContext(), DeserializationListener, OwnDeserializationListener, Preamble, getFrontendOpts().UseGlobalModuleIndex); - ModuleManager = static_cast<ASTReader*>(Source.get()); - getASTContext().setExternalSource(Source); } -ExternalASTSource *CompilerInstance::createPCHExternalASTSource( +IntrusiveRefCntPtr<ASTReader> CompilerInstance::createPCHExternalASTSource( StringRef Path, const std::string &Sysroot, bool DisablePCHValidation, bool AllowPCHWithCompilerErrors, Preprocessor &PP, ASTContext &Context, void *DeserializationListener, bool OwnDeserializationListener, bool Preamble, bool UseGlobalModuleIndex) { HeaderSearchOptions &HSOpts = PP.getHeaderSearchInfo().getHeaderSearchOpts(); - std::unique_ptr<ASTReader> Reader; - Reader.reset(new ASTReader(PP, Context, - Sysroot.empty() ? "" : Sysroot.c_str(), - DisablePCHValidation, - AllowPCHWithCompilerErrors, - /*AllowConfigurationMismatch*/false, - HSOpts.ModulesValidateSystemHeaders, - UseGlobalModuleIndex)); + IntrusiveRefCntPtr<ASTReader> Reader( + new ASTReader(PP, Context, Sysroot.empty() ? "" : Sysroot.c_str(), + DisablePCHValidation, AllowPCHWithCompilerErrors, + /*AllowConfigurationMismatch*/ false, + HSOpts.ModulesValidateSystemHeaders, UseGlobalModuleIndex)); + + // We need the external source to be set up before we read the AST, because + // eagerly-deserialized declarations may use it. + Context.setExternalSource(Reader.get()); Reader->setDeserializationListener( static_cast<ASTDeserializationListener *>(DeserializationListener), @@ -435,7 +430,7 @@ ExternalASTSource *CompilerInstance::createPCHExternalASTSource( // Set the predefines buffer as suggested by the PCH reader. Typically, the // predefines buffer will be empty. PP.setPredefines(Reader->getSuggestedPredefines()); - return Reader.release(); + return Reader; case ASTReader::Failure: // Unrecoverable failure: don't even try to process the input file. @@ -450,6 +445,7 @@ ExternalASTSource *CompilerInstance::createPCHExternalASTSource( break; } + Context.setExternalSource(nullptr); return nullptr; } @@ -522,42 +518,43 @@ void CompilerInstance::createSema(TranslationUnitKind TUKind, // Output Files -void CompilerInstance::addOutputFile(const OutputFile &OutFile) { +void CompilerInstance::addOutputFile(OutputFile &&OutFile) { assert(OutFile.OS && "Attempt to add empty stream to output list!"); - OutputFiles.push_back(OutFile); + OutputFiles.push_back(std::move(OutFile)); } void CompilerInstance::clearOutputFiles(bool EraseFiles) { - for (std::list<OutputFile>::iterator - it = OutputFiles.begin(), ie = OutputFiles.end(); it != ie; ++it) { - delete it->OS; - if (!it->TempFilename.empty()) { + for (OutputFile &OF : OutputFiles) { + // Manually close the stream before we rename it. + OF.OS.reset(); + + if (!OF.TempFilename.empty()) { if (EraseFiles) { - llvm::sys::fs::remove(it->TempFilename); + llvm::sys::fs::remove(OF.TempFilename); } else { - SmallString<128> NewOutFile(it->Filename); + SmallString<128> NewOutFile(OF.Filename); // If '-working-directory' was passed, the output filename should be // relative to that. FileMgr->FixupRelativePath(NewOutFile); if (std::error_code ec = - llvm::sys::fs::rename(it->TempFilename, NewOutFile.str())) { + llvm::sys::fs::rename(OF.TempFilename, NewOutFile)) { getDiagnostics().Report(diag::err_unable_to_rename_temp) - << it->TempFilename << it->Filename << ec.message(); + << OF.TempFilename << OF.Filename << ec.message(); - llvm::sys::fs::remove(it->TempFilename); + llvm::sys::fs::remove(OF.TempFilename); } } - } else if (!it->Filename.empty() && EraseFiles) - llvm::sys::fs::remove(it->Filename); + } else if (!OF.Filename.empty() && EraseFiles) + llvm::sys::fs::remove(OF.Filename); } OutputFiles.clear(); + NonSeekStream.reset(); } -llvm::raw_fd_ostream * -CompilerInstance::createDefaultOutputFile(bool Binary, - StringRef InFile, +raw_pwrite_stream * +CompilerInstance::createDefaultOutputFile(bool Binary, StringRef InFile, StringRef Extension) { return createOutputFile(getFrontendOpts().OutputFile, Binary, /*RemoveFileOnSignal=*/true, InFile, Extension, @@ -565,21 +562,20 @@ CompilerInstance::createDefaultOutputFile(bool Binary, } llvm::raw_null_ostream *CompilerInstance::createNullOutputFile() { - llvm::raw_null_ostream *OS = new llvm::raw_null_ostream(); - addOutputFile(OutputFile("", "", OS)); - return OS; + auto OS = llvm::make_unique<llvm::raw_null_ostream>(); + llvm::raw_null_ostream *Ret = OS.get(); + addOutputFile(OutputFile("", "", std::move(OS))); + return Ret; } -llvm::raw_fd_ostream * -CompilerInstance::createOutputFile(StringRef OutputPath, - bool Binary, bool RemoveFileOnSignal, - StringRef InFile, - StringRef Extension, - bool UseTemporary, +raw_pwrite_stream * +CompilerInstance::createOutputFile(StringRef OutputPath, bool Binary, + bool RemoveFileOnSignal, StringRef InFile, + StringRef Extension, bool UseTemporary, bool CreateMissingDirectories) { std::string OutputPathName, TempPathName; std::error_code EC; - llvm::raw_fd_ostream *OS = createOutputFile( + std::unique_ptr<raw_pwrite_stream> OS = createOutputFile( OutputPath, EC, Binary, RemoveFileOnSignal, InFile, Extension, UseTemporary, CreateMissingDirectories, &OutputPathName, &TempPathName); if (!OS) { @@ -588,15 +584,16 @@ CompilerInstance::createOutputFile(StringRef OutputPath, return nullptr; } + raw_pwrite_stream *Ret = OS.get(); // Add the output file -- but don't try to remove "-", since this means we are // using stdin. addOutputFile(OutputFile((OutputPathName != "-") ? OutputPathName : "", - TempPathName, OS)); + TempPathName, std::move(OS))); - return OS; + return Ret; } -llvm::raw_fd_ostream *CompilerInstance::createOutputFile( +std::unique_ptr<llvm::raw_pwrite_stream> CompilerInstance::createOutputFile( StringRef OutputPath, std::error_code &Error, bool Binary, bool RemoveFileOnSignal, StringRef InFile, StringRef Extension, bool UseTemporary, bool CreateMissingDirectories, @@ -646,14 +643,14 @@ llvm::raw_fd_ostream *CompilerInstance::createOutputFile( TempPath += "-%%%%%%%%"; int fd; std::error_code EC = - llvm::sys::fs::createUniqueFile(TempPath.str(), fd, TempPath); + llvm::sys::fs::createUniqueFile(TempPath, fd, TempPath); if (CreateMissingDirectories && EC == llvm::errc::no_such_file_or_directory) { StringRef Parent = llvm::sys::path::parent_path(OutputPath); EC = llvm::sys::fs::create_directories(Parent); if (!EC) { - EC = llvm::sys::fs::createUniqueFile(TempPath.str(), fd, TempPath); + EC = llvm::sys::fs::createUniqueFile(TempPath, fd, TempPath); } } @@ -684,7 +681,13 @@ llvm::raw_fd_ostream *CompilerInstance::createOutputFile( if (TempPathName) *TempPathName = TempFile; - return OS.release(); + if (!Binary || OS->supportsSeeking()) + return std::move(OS); + + auto B = llvm::make_unique<llvm::buffer_ostream>(*OS); + assert(!NonSeekStream); + NonSeekStream = std::move(OS); + return std::move(B); } // Initialization Utilities @@ -946,16 +949,18 @@ static bool compileModuleImpl(CompilerInstance &ImportingInstance, FrontendOpts.Inputs.push_back( FrontendInputFile(ModuleMapFile->getName(), IK)); } else { + SmallString<128> FakeModuleMapFile(Module->Directory->getName()); + llvm::sys::path::append(FakeModuleMapFile, "__inferred_module.map"); + FrontendOpts.Inputs.push_back(FrontendInputFile(FakeModuleMapFile, IK)); + llvm::raw_string_ostream OS(InferredModuleMapContent); Module->print(OS); OS.flush(); - FrontendOpts.Inputs.push_back( - FrontendInputFile("__inferred_module.map", IK)); std::unique_ptr<llvm::MemoryBuffer> ModuleMapBuffer = llvm::MemoryBuffer::getMemBuffer(InferredModuleMapContent); ModuleMapFile = Instance.getFileManager().getVirtualFile( - "__inferred_module.map", InferredModuleMapContent.size(), 0); + FakeModuleMapFile, InferredModuleMapContent.size(), 0); SourceMgr.overrideFileContents(ModuleMapFile, std::move(ModuleMapBuffer)); } @@ -1031,9 +1036,19 @@ static bool compileAndLoadModule(CompilerInstance &ImportingInstance, case llvm::LockFileManager::LFS_Shared: // Someone else is responsible for building the module. Wait for them to // finish. - if (Locked.waitForUnlock() == llvm::LockFileManager::Res_OwnerDied) + switch (Locked.waitForUnlock()) { + case llvm::LockFileManager::Res_Success: + ModuleLoadCapabilities |= ASTReader::ARR_OutOfDate; + break; + case llvm::LockFileManager::Res_OwnerDied: continue; // try again to get the lock. - ModuleLoadCapabilities |= ASTReader::ARR_OutOfDate; + case llvm::LockFileManager::Res_Timeout: + Diags.Report(ModuleNameLoc, diag::err_module_lock_timeout) + << Module->Name; + // Clear the lock file so that future invokations can make progress. + Locked.unsafeRemoveLockFile(); + return false; + } break; } @@ -1071,79 +1086,51 @@ static void checkConfigMacro(Preprocessor &PP, StringRef ConfigMacro, // not have changed. if (!Id->hadMacroDefinition()) return; + auto *LatestLocalMD = PP.getLocalMacroDirectiveHistory(Id); - // If this identifier does not currently have a macro definition, - // check whether it had one on the command line. - if (!Id->hasMacroDefinition()) { - MacroDirective::DefInfo LatestDef = - PP.getMacroDirectiveHistory(Id)->getDefinition(); - for (MacroDirective::DefInfo Def = LatestDef; Def; - Def = Def.getPreviousDefinition()) { - FileID FID = SourceMgr.getFileID(Def.getLocation()); - if (FID.isInvalid()) - continue; - - // We only care about the predefines buffer. - if (FID != PP.getPredefinesFileID()) - continue; - - // This macro was defined on the command line, then #undef'd later. - // Complain. - PP.Diag(ImportLoc, diag::warn_module_config_macro_undef) - << true << ConfigMacro << Mod->getFullModuleName(); - if (LatestDef.isUndefined()) - PP.Diag(LatestDef.getUndefLocation(), diag::note_module_def_undef_here) - << true; - return; - } - - // Okay: no definition in the predefines buffer. - return; - } - - // This identifier has a macro definition. Check whether we had a definition - // on the command line. - MacroDirective::DefInfo LatestDef = - PP.getMacroDirectiveHistory(Id)->getDefinition(); - MacroDirective::DefInfo PredefinedDef; - for (MacroDirective::DefInfo Def = LatestDef; Def; - Def = Def.getPreviousDefinition()) { - FileID FID = SourceMgr.getFileID(Def.getLocation()); - if (FID.isInvalid()) - continue; - + // Find the macro definition from the command line. + MacroInfo *CmdLineDefinition = nullptr; + for (auto *MD = LatestLocalMD; MD; MD = MD->getPrevious()) { // We only care about the predefines buffer. - if (FID != PP.getPredefinesFileID()) + FileID FID = SourceMgr.getFileID(MD->getLocation()); + if (FID.isInvalid() || FID != PP.getPredefinesFileID()) continue; - - PredefinedDef = Def; + if (auto *DMD = dyn_cast<DefMacroDirective>(MD)) + CmdLineDefinition = DMD->getMacroInfo(); break; } - // If there was no definition for this macro in the predefines buffer, - // complain. - if (!PredefinedDef || - (!PredefinedDef.getLocation().isValid() && - PredefinedDef.getUndefLocation().isValid())) { + auto *CurrentDefinition = PP.getMacroInfo(Id); + if (CurrentDefinition == CmdLineDefinition) { + // Macro matches. Nothing to do. + } else if (!CurrentDefinition) { + // This macro was defined on the command line, then #undef'd later. + // Complain. + PP.Diag(ImportLoc, diag::warn_module_config_macro_undef) + << true << ConfigMacro << Mod->getFullModuleName(); + auto LatestDef = LatestLocalMD->getDefinition(); + assert(LatestDef.isUndefined() && + "predefined macro went away with no #undef?"); + PP.Diag(LatestDef.getUndefLocation(), diag::note_module_def_undef_here) + << true; + return; + } else if (!CmdLineDefinition) { + // There was no definition for this macro in the predefines buffer, + // but there was a local definition. Complain. PP.Diag(ImportLoc, diag::warn_module_config_macro_undef) << false << ConfigMacro << Mod->getFullModuleName(); - PP.Diag(LatestDef.getLocation(), diag::note_module_def_undef_here) + PP.Diag(CurrentDefinition->getDefinitionLoc(), + diag::note_module_def_undef_here) + << false; + } else if (!CurrentDefinition->isIdenticalTo(*CmdLineDefinition, PP, + /*Syntactically=*/true)) { + // The macro definitions differ. + PP.Diag(ImportLoc, diag::warn_module_config_macro_undef) + << false << ConfigMacro << Mod->getFullModuleName(); + PP.Diag(CurrentDefinition->getDefinitionLoc(), + diag::note_module_def_undef_here) << false; - return; } - - // If the current macro definition is the same as the predefined macro - // definition, it's okay. - if (LatestDef.getMacroInfo() == PredefinedDef.getMacroInfo() || - LatestDef.getMacroInfo()->isIdenticalTo(*PredefinedDef.getMacroInfo(),PP, - /*Syntactically=*/true)) - return; - - // The macro definitions differ. - PP.Diag(ImportLoc, diag::warn_module_config_macro_undef) - << false << ConfigMacro << Mod->getFullModuleName(); - PP.Diag(LatestDef.getLocation(), diag::note_module_def_undef_here) - << false; } /// \brief Write a new timestamp file with the given path. @@ -1186,8 +1173,7 @@ static void pruneModuleCache(const HeaderSearchOptions &HSOpts) { std::error_code EC; SmallString<128> ModuleCachePathNative; llvm::sys::path::native(HSOpts.ModuleCachePath, ModuleCachePathNative); - for (llvm::sys::fs::directory_iterator - Dir(ModuleCachePathNative.str(), EC), DirEnd; + for (llvm::sys::fs::directory_iterator Dir(ModuleCachePathNative, EC), DirEnd; Dir != DirEnd && !EC; Dir.increment(EC)) { // If we don't have a directory, there's nothing to look into. if (!llvm::sys::fs::is_directory(Dir->path())) @@ -1235,9 +1221,10 @@ void CompilerInstance::createModuleManager() { if (!hasASTContext()) createASTContext(); - // If we're not recursively building a module, check whether we - // need to prune the module cache. - if (getSourceManager().getModuleBuildStack().empty() && + // If we're implicitly building modules but not currently recursively + // building a module, check whether we need to prune the module cache. + if (getLangOpts().ImplicitModules && + getSourceManager().getModuleBuildStack().empty() && getHeaderSearchOpts().ModuleCachePruneInterval > 0 && getHeaderSearchOpts().ModuleCachePruneAfter > 0) { pruneModuleCache(getHeaderSearchOpts()); @@ -1274,6 +1261,7 @@ bool CompilerInstance::loadModuleFile(StringRef FileName) { struct ReadModuleNames : ASTReaderListener { CompilerInstance &CI; std::vector<StringRef> ModuleFileStack; + std::vector<StringRef> ModuleNameStack; bool Failed; bool TopFileIsModule; @@ -1283,21 +1271,36 @@ bool CompilerInstance::loadModuleFile(StringRef FileName) { bool needsImportVisitation() const override { return true; } void visitImport(StringRef FileName) override { + if (!CI.ExplicitlyLoadedModuleFiles.insert(FileName).second) { + if (ModuleFileStack.size() == 0) + TopFileIsModule = true; + return; + } + ModuleFileStack.push_back(FileName); + ModuleNameStack.push_back(StringRef()); if (ASTReader::readASTFileControlBlock(FileName, CI.getFileManager(), *this)) { - CI.getDiagnostics().Report(SourceLocation(), - diag::err_module_file_not_found) + CI.getDiagnostics().Report( + SourceLocation(), CI.getFileManager().getBufferForFile(FileName) + ? diag::err_module_file_invalid + : diag::err_module_file_not_found) << FileName; - // FIXME: Produce a note stack explaining how we got here. + for (int I = ModuleFileStack.size() - 2; I >= 0; --I) + CI.getDiagnostics().Report(SourceLocation(), + diag::note_module_file_imported_by) + << ModuleFileStack[I] + << !ModuleNameStack[I].empty() << ModuleNameStack[I]; Failed = true; } + ModuleNameStack.pop_back(); ModuleFileStack.pop_back(); } void ReadModuleName(StringRef ModuleName) override { if (ModuleFileStack.size() == 1) TopFileIsModule = true; + ModuleNameStack.back() = ModuleName; auto &ModuleFile = CI.ModuleFileOverrides[ModuleName]; if (!ModuleFile.empty() && @@ -1310,6 +1313,19 @@ bool CompilerInstance::loadModuleFile(StringRef FileName) { } } RMN(*this); + // If we don't already have an ASTReader, create one now. + if (!ModuleManager) + createModuleManager(); + + // Tell the module manager about this module file. + if (getModuleManager()->getModuleManager().addKnownModuleFile(FileName)) { + getDiagnostics().Report(SourceLocation(), diag::err_module_file_not_found) + << FileName; + return false; + } + + // Build our mapping of module names to module files from this file + // and its imports. RMN.visitImport(FileName); if (RMN.Failed) @@ -1343,7 +1359,7 @@ CompilerInstance::loadModule(SourceLocation ImportLoc, if (LastModuleImportResult && ModuleName != getLangOpts().CurrentModule && ModuleName != getLangOpts().ImplementationOfModule) ModuleManager->makeModuleVisible(LastModuleImportResult, Visibility, - ImportLoc, /*Complain=*/false); + ImportLoc); return LastModuleImportResult; } @@ -1373,6 +1389,12 @@ CompilerInstance::loadModule(SourceLocation ImportLoc, auto Override = ModuleFileOverrides.find(ModuleName); bool Explicit = Override != ModuleFileOverrides.end(); + if (!Explicit && !getLangOpts().ImplicitModules) { + getDiagnostics().Report(ModuleNameLoc, diag::err_module_build_disabled) + << ModuleName; + ModuleBuildFailed = true; + return ModuleLoadResult(); + } std::string ModuleFileName = Explicit ? Override->second @@ -1580,8 +1602,7 @@ CompilerInstance::loadModule(SourceLocation ImportLoc, return ModuleLoadResult(); } - ModuleManager->makeModuleVisible(Module, Visibility, ImportLoc, - /*Complain=*/true); + ModuleManager->makeModuleVisible(Module, Visibility, ImportLoc); } // Check for any configuration macros that have changed. @@ -1591,25 +1612,6 @@ CompilerInstance::loadModule(SourceLocation ImportLoc, Module, ImportLoc); } - // Determine whether we're in the #include buffer for a module. The #includes - // in that buffer do not qualify as module imports; they're just an - // implementation detail of us building the module. - bool IsInModuleIncludes = !getLangOpts().CurrentModule.empty() && - getSourceManager().getFileID(ImportLoc) == - getSourceManager().getMainFileID(); - - // If this module import was due to an inclusion directive, create an - // implicit import declaration to capture it in the AST. - if (IsInclusionDirective && hasASTContext() && !IsInModuleIncludes) { - TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl(); - ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU, - ImportLoc, Module, - Path.back().second); - TU->addDecl(ImportD); - if (Consumer) - Consumer->HandleImplicitImportDecl(ImportD); - } - LastModuleImportLoc = ImportLoc; LastModuleImportResult = ModuleLoadResult(Module, false); return LastModuleImportResult; @@ -1617,9 +1619,13 @@ CompilerInstance::loadModule(SourceLocation ImportLoc, void CompilerInstance::makeModuleVisible(Module *Mod, Module::NameVisibilityKind Visibility, - SourceLocation ImportLoc, - bool Complain){ - ModuleManager->makeModuleVisible(Mod, Visibility, ImportLoc, Complain); + SourceLocation ImportLoc) { + if (!ModuleManager) + createModuleManager(); + if (!ModuleManager) + return; + + ModuleManager->makeModuleVisible(Mod, Visibility, ImportLoc); } GlobalModuleIndex *CompilerInstance::loadGlobalModuleIndex( diff --git a/contrib/llvm/tools/clang/lib/Frontend/CompilerInvocation.cpp b/contrib/llvm/tools/clang/lib/Frontend/CompilerInvocation.cpp index 54025b0..8d3d312 100644 --- a/contrib/llvm/tools/clang/lib/Frontend/CompilerInvocation.cpp +++ b/contrib/llvm/tools/clang/lib/Frontend/CompilerInvocation.cpp @@ -253,7 +253,7 @@ static bool ParseAnalyzerArgs(AnalyzerOptions &Opts, ArgList &Args, for (unsigned i = 0, e = checkers.size(); i != e; ++i) Opts.CheckersControlList.push_back(std::make_pair(checkers[i], enable)); } - + // Go through the analyzer configuration options. for (arg_iterator it = Args.filtered_begin(OPT_analyzer_config), ie = Args.filtered_end(); it != ie; ++it) { @@ -329,11 +329,8 @@ static void parseSanitizerKinds(StringRef FlagName, const std::vector<std::string> &Sanitizers, DiagnosticsEngine &Diags, SanitizerSet &S) { for (const auto &Sanitizer : Sanitizers) { - SanitizerKind K = llvm::StringSwitch<SanitizerKind>(Sanitizer) -#define SANITIZER(NAME, ID) .Case(NAME, SanitizerKind::ID) -#include "clang/Basic/Sanitizers.def" - .Default(SanitizerKind::Unknown); - if (K == SanitizerKind::Unknown) + SanitizerMask K = parseSanitizerValue(Sanitizer, /*AllowGroups=*/false); + if (K == 0) Diags.Report(diag::err_drv_invalid_value) << FlagName << Sanitizer; else S.set(K, true); @@ -367,6 +364,16 @@ static bool ParseCodeGenArgs(CodeGenOptions &Opts, ArgList &Args, InputKind IK, Opts.setInlining(Args.hasArg(OPT_fno_inline_functions) ? CodeGenOptions::OnlyAlwaysInlining : Opts.getInlining()); + if (Arg *A = Args.getLastArg(OPT_fveclib)) { + StringRef Name = A->getValue(); + if (Name == "Accelerate") + Opts.setVecLib(CodeGenOptions::Accelerate); + else if (Name == "none") + Opts.setVecLib(CodeGenOptions::NoLibrary); + else + Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Name; + } + if (Args.hasArg(OPT_gline_tables_only)) { Opts.setDebugInfo(CodeGenOptions::DebugLineTablesOnly); } else if (Args.hasArg(OPT_g_Flag) || Args.hasArg(OPT_gdwarf_2) || @@ -395,6 +402,10 @@ static bool ParseCodeGenArgs(CodeGenOptions &Opts, ArgList &Args, InputKind IK, // Default Dwarf version is 4 if we are generating debug information. Opts.DwarfVersion = 4; + if (const Arg *A = + Args.getLastArg(OPT_emit_llvm_uselists, OPT_no_emit_llvm_uselists)) + Opts.EmitLLVMUseLists = A->getOption().getID() == OPT_emit_llvm_uselists; + Opts.DisableLLVMOpts = Args.hasArg(OPT_disable_llvm_optzns); Opts.DisableRedZone = Args.hasArg(OPT_disable_red_zone); Opts.ForbidGuardVariables = Args.hasArg(OPT_fforbid_guard_variables); @@ -417,13 +428,14 @@ static bool ParseCodeGenArgs(CodeGenOptions &Opts, ArgList &Args, InputKind IK, Opts.DisableIntegratedAS = Args.hasArg(OPT_fno_integrated_as); Opts.Autolink = !Args.hasArg(OPT_fno_autolink); Opts.SampleProfileFile = Args.getLastArgValue(OPT_fprofile_sample_use_EQ); - Opts.ProfileInstrGenerate = Args.hasArg(OPT_fprofile_instr_generate); + Opts.ProfileInstrGenerate = Args.hasArg(OPT_fprofile_instr_generate) || + Args.hasArg(OPT_fprofile_instr_generate_EQ);; + Opts.InstrProfileOutput = Args.getLastArgValue(OPT_fprofile_instr_generate_EQ); Opts.InstrProfileInput = Args.getLastArgValue(OPT_fprofile_instr_use_EQ); Opts.CoverageMapping = Args.hasArg(OPT_fcoverage_mapping); Opts.DumpCoverageMapping = Args.hasArg(OPT_dump_coverage_mapping); Opts.AsmVerbose = Args.hasArg(OPT_masm_verbose); Opts.ObjCAutoRefCountExceptions = Args.hasArg(OPT_fobjc_arc_exceptions); - Opts.CUDAIsDevice = Args.hasArg(OPT_fcuda_is_device); Opts.CXAAtExit = !Args.hasArg(OPT_fno_use_cxa_atexit); Opts.CXXCtorDtorAliases = Args.hasArg(OPT_mconstructor_aliases); Opts.CodeModel = getCodeModel(Args, Diags); @@ -441,11 +453,11 @@ static bool ParseCodeGenArgs(CodeGenOptions &Opts, ArgList &Args, InputKind IK, Args.hasArg(OPT_cl_unsafe_math_optimizations) || Args.hasArg(OPT_cl_finite_math_only) || Args.hasArg(OPT_cl_fast_relaxed_math)); - Opts.NoSignedZeros = Args.hasArg(OPT_cl_no_signed_zeros); + Opts.NoSignedZeros = Args.hasArg(OPT_fno_signed_zeros); + Opts.ReciprocalMath = Args.hasArg(OPT_freciprocal_math); Opts.NoZeroInitializedInBSS = Args.hasArg(OPT_mno_zero_initialized_in_bss); Opts.BackendOptions = Args.getAllArgValues(OPT_backend_option); Opts.NumRegisterParameters = getLastArgIntValue(Args, OPT_mregparm, 0, Diags); - Opts.NoGlobalMerge = Args.hasArg(OPT_mno_global_merge); Opts.NoExecStack = Args.hasArg(OPT_mno_exec_stack); Opts.FatalWarnings = Args.hasArg(OPT_massembler_fatal_warnings); Opts.EnableSegmentedStacks = Args.hasArg(OPT_split_stacks); @@ -472,8 +484,13 @@ static bool ParseCodeGenArgs(CodeGenOptions &Opts, ArgList &Args, InputKind IK, OPT_fno_function_sections, false); Opts.DataSections = Args.hasFlag(OPT_fdata_sections, OPT_fno_data_sections, false); + Opts.UniqueSectionNames = Args.hasFlag(OPT_funique_section_names, + OPT_fno_unique_section_names, true); + Opts.MergeFunctions = Args.hasArg(OPT_fmerge_functions); + Opts.MSVolatile = Args.hasArg(OPT_fms_volatile); + Opts.VectorizeBB = Args.hasArg(OPT_vectorize_slp_aggressive); Opts.VectorizeLoop = Args.hasArg(OPT_vectorize_loops); Opts.VectorizeSLP = Args.hasArg(OPT_vectorize_slp); @@ -489,6 +506,8 @@ static bool ParseCodeGenArgs(CodeGenOptions &Opts, ArgList &Args, InputKind IK, Opts.CoverageExtraChecksum = Args.hasArg(OPT_coverage_cfg_checksum); Opts.CoverageNoFunctionNamesInData = Args.hasArg(OPT_coverage_no_function_names_in_data); + Opts.CoverageExitBlockBeforeBody = + Args.hasArg(OPT_coverage_exit_block_before_body); if (Args.hasArg(OPT_coverage_version_EQ)) { StringRef CoverageVersion = Args.getLastArgValue(OPT_coverage_version_EQ); if (CoverageVersion.size() != 4) { @@ -507,8 +526,14 @@ static bool ParseCodeGenArgs(CodeGenOptions &Opts, ArgList &Args, InputKind IK, Opts.CompressDebugSections = Args.hasArg(OPT_compress_debug_sections); Opts.DebugCompilationDir = Args.getLastArgValue(OPT_fdebug_compilation_dir); Opts.LinkBitcodeFile = Args.getLastArgValue(OPT_mlink_bitcode_file); - Opts.SanitizeCoverage = - getLastArgIntValue(Args, OPT_fsanitize_coverage, 0, Diags); + Opts.SanitizeCoverageType = + getLastArgIntValue(Args, OPT_fsanitize_coverage_type, 0, Diags); + Opts.SanitizeCoverageIndirectCalls = + Args.hasArg(OPT_fsanitize_coverage_indirect_calls); + Opts.SanitizeCoverageTraceBB = Args.hasArg(OPT_fsanitize_coverage_trace_bb); + Opts.SanitizeCoverageTraceCmp = Args.hasArg(OPT_fsanitize_coverage_trace_cmp); + Opts.SanitizeCoverage8bitCounters = + Args.hasArg(OPT_fsanitize_coverage_8bit_counters); Opts.SanitizeMemoryTrackOrigins = getLastArgIntValue(Args, OPT_fsanitize_memory_track_origins_EQ, 0, Diags); Opts.SanitizeUndefinedTrapOnError = @@ -523,6 +548,13 @@ static bool ParseCodeGenArgs(CodeGenOptions &Opts, ArgList &Args, InputKind IK, Opts.StackAlignment = StackAlignment; } + if (Arg *A = Args.getLastArg(OPT_mstack_probe_size)) { + StringRef Val = A->getValue(); + unsigned StackProbeSize = Opts.StackProbeSize; + Val.getAsInteger(0, StackProbeSize); + Opts.StackProbeSize = StackProbeSize; + } + if (Arg *A = Args.getLastArg(OPT_fobjc_dispatch_method_EQ)) { StringRef Name = A->getValue(); unsigned Method = llvm::StringSwitch<unsigned>(Name) @@ -616,6 +648,9 @@ static bool ParseCodeGenArgs(CodeGenOptions &Opts, ArgList &Args, InputKind IK, Args.getAllArgValues(OPT_fsanitize_recover_EQ), Diags, Opts.SanitizeRecover); + Opts.CudaGpuBinaryFileNames = + Args.getAllArgValues(OPT_fcuda_include_gpubinary); + return Success; } @@ -634,6 +669,8 @@ static void ParseDependencyOutputArgs(DependencyOutputOptions &Opts, Opts.DOTOutputFile = Args.getLastArgValue(OPT_dependency_dot); Opts.ModuleDependencyOutputDir = Args.getLastArgValue(OPT_module_dependency_dir); + if (Args.hasArg(OPT_MV)) + Opts.OutputFormat = DependencyOutputFormat::NMake; } bool clang::ParseDiagnosticArgs(DiagnosticOptions &Opts, ArgList &Args, @@ -702,9 +739,9 @@ bool clang::ParseDiagnosticArgs(DiagnosticOptions &Opts, ArgList &Args, if (Format == "clang") Opts.setFormat(DiagnosticOptions::Clang); else if (Format == "msvc") - Opts.setFormat(DiagnosticOptions::Msvc); + Opts.setFormat(DiagnosticOptions::MSVC); else if (Format == "msvc-fallback") { - Opts.setFormat(DiagnosticOptions::Msvc); + Opts.setFormat(DiagnosticOptions::MSVC); Opts.CLFallbackMode = true; } else if (Format == "vi") Opts.setFormat(DiagnosticOptions::Vi); @@ -966,6 +1003,7 @@ static InputKind ParseFrontendArgs(FrontendOptions &Opts, ArgList &Args, .Case("cpp-output", IK_PreprocessedC) .Case("assembler-with-cpp", IK_Asm) .Case("c++-cpp-output", IK_PreprocessedCXX) + .Case("cuda-cpp-output", IK_PreprocessedCuda) .Case("objective-c-cpp-output", IK_PreprocessedObjC) .Case("objc-cpp-output", IK_PreprocessedObjC) .Case("objective-c++-cpp-output", IK_PreprocessedObjCXX) @@ -1169,6 +1207,7 @@ void CompilerInvocation::setLangDefaults(LangOptions &Opts, InputKind IK, LangStd = LangStandard::lang_opencl; break; case IK_CUDA: + case IK_PreprocessedCuda: LangStd = LangStandard::lang_cuda; break; case IK_Asm: @@ -1197,7 +1236,7 @@ void CompilerInvocation::setLangDefaults(LangOptions &Opts, InputKind IK, Opts.CPlusPlus1z = Std.isCPlusPlus1z(); Opts.Digraphs = Std.hasDigraphs(); Opts.GNUMode = Std.isGNUMode(); - Opts.GNUInline = !Std.isC99(); + Opts.GNUInline = Std.isC89(); Opts.HexFloats = Std.hasHexFloats(); Opts.ImplicitInt = Std.hasImplicitInt(); @@ -1221,7 +1260,8 @@ void CompilerInvocation::setLangDefaults(LangOptions &Opts, InputKind IK, Opts.NativeHalfType = 1; } - Opts.CUDA = LangStd == LangStandard::lang_cuda || IK == IK_CUDA; + Opts.CUDA = IK == IK_CUDA || IK == IK_PreprocessedCuda || + LangStd == LangStandard::lang_cuda; // OpenCL and C++ both have bool, true, false keywords. Opts.Bool = Opts.OpenCL || Opts.CPlusPlus; @@ -1236,9 +1276,6 @@ void CompilerInvocation::setLangDefaults(LangOptions &Opts, InputKind IK, Opts.CXXOperatorNames = Opts.CPlusPlus; Opts.DollarIdents = !Opts.AsmPreprocessor; - - // C++14 onwards has sized global deallocation functions. - Opts.SizedDeallocation = Opts.CPlusPlus14; } /// Attempt to parse a visibility value out of the given argument. @@ -1259,43 +1296,6 @@ static Visibility parseVisibility(Arg *arg, ArgList &args, return DefaultVisibility; } -static unsigned parseMSCVersion(ArgList &Args, DiagnosticsEngine &Diags) { - auto Arg = Args.getLastArg(OPT_fms_compatibility_version); - if (!Arg) - return 0; - - // The MSC versioning scheme involves four versioning components: - // - Major - // - Minor - // - Build - // - Patch - // - // We accept either the old style (_MSC_VER) value, or a _MSC_FULL_VER value. - // Additionally, the value may be provided in the form of a more readable - // MM.mm.bbbbb.pp version. - // - // Unfortunately, due to the bit-width limitations, we cannot currently encode - // the value for the patch level. - - unsigned VC[4] = {0}; - StringRef Value = Arg->getValue(); - SmallVector<StringRef, 4> Components; - - Value.split(Components, ".", llvm::array_lengthof(VC)); - for (unsigned CI = 0, - CE = std::min(Components.size(), llvm::array_lengthof(VC)); - CI < CE; ++CI) { - if (Components[CI].getAsInteger(10, VC[CI])) { - Diags.Report(diag::err_drv_invalid_value) - << Arg->getAsString(Args) << Value; - return 0; - } - } - - // FIXME we cannot encode the patch level - return VC[0] * 10000000 + VC[1] * 100000 + VC[2]; -} - static void ParseLangArgs(LangOptions &Opts, ArgList &Args, InputKind IK, DiagnosticsEngine &Diags) { // FIXME: Cleanup per-file based stuff. @@ -1336,6 +1336,7 @@ static void ParseLangArgs(LangOptions &Opts, ArgList &Args, InputKind IK, << A->getAsString(Args) << "OpenCL"; break; case IK_CUDA: + case IK_PreprocessedCuda: if (!Std.isCPlusPlus()) Diags.Report(diag::err_drv_argument_not_allowed_with) << A->getAsString(Args) << "CUDA"; @@ -1381,6 +1382,12 @@ static void ParseLangArgs(LangOptions &Opts, ArgList &Args, InputKind IK, if (Args.hasArg(OPT_fcuda_is_device)) Opts.CUDAIsDevice = 1; + if (Args.hasArg(OPT_fcuda_allow_host_calls_from_host_device)) + Opts.CUDAAllowHostCallsFromHostDevice = 1; + + if (Args.hasArg(OPT_fcuda_disable_target_call_checks)) + Opts.CUDADisableTargetCallChecks = 1; + if (Opts.ObjC1) { if (Arg *arg = Args.getLastArg(OPT_fobjc_runtime_EQ)) { StringRef value = arg->getValue(); @@ -1412,8 +1419,13 @@ static void ParseLangArgs(LangOptions &Opts, ArgList &Args, InputKind IK, (Opts.ObjCRuntime.getKind() == ObjCRuntime::FragileMacOSX); } - if (Args.hasArg(OPT_fgnu89_inline)) - Opts.GNUInline = 1; + if (Args.hasArg(OPT_fgnu89_inline)) { + if (Opts.CPlusPlus) + Diags.Report(diag::err_drv_argument_not_allowed_with) << "-fgnu89-inline" + << "C++/ObjC++"; + else + Opts.GNUInline = 1; + } if (Args.hasArg(OPT_fapple_kext)) { if (!Opts.CPlusPlus) @@ -1462,7 +1474,16 @@ static void ParseLangArgs(LangOptions &Opts, ArgList &Args, InputKind IK, Opts.MSVCCompat = Args.hasArg(OPT_fms_compatibility); Opts.MicrosoftExt = Opts.MSVCCompat || Args.hasArg(OPT_fms_extensions); Opts.AsmBlocks = Args.hasArg(OPT_fasm_blocks) || Opts.MicrosoftExt; - Opts.MSCompatibilityVersion = parseMSCVersion(Args, Diags); + Opts.MSCompatibilityVersion = 0; + if (const Arg *A = Args.getLastArg(OPT_fms_compatibility_version)) { + VersionTuple VT; + if (VT.tryParse(A->getValue())) + Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) + << A->getValue(); + Opts.MSCompatibilityVersion = VT.getMajor() * 10000000 + + VT.getMinor().getValueOr(0) * 100000 + + VT.getSubminor().getValueOr(0); + } // Mimicing gcc's behavior, trigraphs are only enabled if -trigraphs // is specified, or -std is set to a conforming mode. @@ -1498,12 +1519,15 @@ static void ParseLangArgs(LangOptions &Opts, ArgList &Args, InputKind IK, Opts.ModulesStrictDeclUse = Args.hasArg(OPT_fmodules_strict_decluse); Opts.ModulesDeclUse = Args.hasArg(OPT_fmodules_decluse) || Opts.ModulesStrictDeclUse; + Opts.ModulesLocalVisibility = + Args.hasArg(OPT_fmodules_local_submodule_visibility); Opts.ModulesSearchAll = Opts.Modules && !Args.hasArg(OPT_fno_modules_search_all) && Args.hasArg(OPT_fmodules_search_all); Opts.ModulesErrorRecovery = !Args.hasArg(OPT_fno_modules_error_recovery); Opts.ModulesImplicitMaps = Args.hasFlag(OPT_fmodules_implicit_maps, OPT_fno_modules_implicit_maps, true); + Opts.ImplicitModules = !Args.hasArg(OPT_fno_implicit_modules); Opts.CharIsSigned = Opts.OpenCL || !Args.hasArg(OPT_fno_signed_char); Opts.WChar = Opts.CPlusPlus && !Args.hasArg(OPT_fno_wchar); Opts.ShortWChar = Args.hasFlag(OPT_fshort_wchar, OPT_fno_short_wchar, false); @@ -1512,7 +1536,8 @@ static void ParseLangArgs(LangOptions &Opts, ArgList &Args, InputKind IK, Opts.NoBuiltin = Args.hasArg(OPT_fno_builtin) || Opts.Freestanding; Opts.NoMathBuiltin = Args.hasArg(OPT_fno_math_builtin); Opts.AssumeSaneOperatorNew = !Args.hasArg(OPT_fno_assume_sane_operator_new); - Opts.SizedDeallocation |= Args.hasArg(OPT_fsized_deallocation); + Opts.SizedDeallocation = Args.hasArg(OPT_fsized_deallocation); + Opts.ConceptsTS = Args.hasArg(OPT_fconcepts_ts); Opts.HeinousExtensions = Args.hasArg(OPT_fheinous_gnu_extensions); Opts.AccessControl = !Args.hasArg(OPT_fno_access_control); Opts.ElideConstructors = !Args.hasArg(OPT_fno_elide_constructors); @@ -1559,10 +1584,13 @@ static void ParseLangArgs(LangOptions &Opts, ArgList &Args, InputKind IK, Opts.DebuggerObjCLiteral = Args.hasArg(OPT_fdebugger_objc_literal); Opts.ApplePragmaPack = Args.hasArg(OPT_fapple_pragma_pack); Opts.CurrentModule = Args.getLastArgValue(OPT_fmodule_name); + Opts.AppExt = Args.hasArg(OPT_fapplication_extension); Opts.ImplementationOfModule = Args.getLastArgValue(OPT_fmodule_implementation_of); - Opts.NativeHalfType = Opts.NativeHalfType; + Opts.ModuleFeatures = Args.getAllArgValues(OPT_fmodule_feature); + Opts.NativeHalfType |= Args.hasArg(OPT_fnative_half_type); Opts.HalfArgsAndReturns = Args.hasArg(OPT_fallow_half_arguments_and_returns); + Opts.GNUAsm = !Args.hasArg(OPT_fno_gnu_inline_asm); if (!Opts.CurrentModule.empty() && !Opts.ImplementationOfModule.empty() && Opts.CurrentModule != Opts.ImplementationOfModule) { @@ -1570,6 +1598,12 @@ static void ParseLangArgs(LangOptions &Opts, ArgList &Args, InputKind IK, << Opts.CurrentModule << Opts.ImplementationOfModule; } + // For now, we only support local submodule visibility in C++ (because we + // heavily depend on the ODR for merging redefinitions). + if (Opts.ModulesLocalVisibility && !Opts.CPlusPlus) + Diags.Report(diag::err_drv_argument_not_allowed_with) + << "-fmodules-local-submodule-visibility" << "C"; + if (Arg *A = Args.getLastArg(OPT_faddress_space_map_mangling_EQ)) { switch (llvm::StringSwitch<unsigned>(A->getValue()) .Case("target", LangOptions::ASMM_Target) @@ -1610,12 +1644,8 @@ static void ParseLangArgs(LangOptions &Opts, ArgList &Args, InputKind IK, Opts.setMSPointerToMemberRepresentationMethod(InheritanceModel); } - // Check if -fopenmp= is specified. - if (const Arg *A = Args.getLastArg(options::OPT_fopenmp_EQ)) { - Opts.OpenMP = llvm::StringSwitch<bool>(A->getValue()) - .Case("libiomp5", true) - .Default(false); - } + // Check if -fopenmp is specified. + Opts.OpenMP = Args.hasArg(options::OPT_fopenmp); // Record whether the __DEPRECATED define was requested. Opts.Deprecated = Args.hasFlag(OPT_fdeprecated_macro, @@ -1660,7 +1690,7 @@ static void ParseLangArgs(LangOptions &Opts, ArgList &Args, InputKind IK, // -fsanitize-address-field-padding=N has to be a LangOpt, parse it here. Opts.SanitizeAddressFieldPadding = getLastArgIntValue(Args, OPT_fsanitize_address_field_padding, 0, Diags); - Opts.SanitizerBlacklistFile = Args.getLastArgValue(OPT_fsanitize_blacklist); + Opts.SanitizerBlacklistFiles = Args.getAllArgValues(OPT_fsanitize_blacklist); } static void ParsePreprocessorArgs(PreprocessorOptions &Opts, ArgList &Args, @@ -1805,6 +1835,7 @@ static void ParsePreprocessorOutputArgs(PreprocessorOutputOptions &Opts, Opts.ShowMacroComments = Args.hasArg(OPT_CC); Opts.ShowMacros = Args.hasArg(OPT_dM) || Args.hasArg(OPT_dD); Opts.RewriteIncludes = Args.hasArg(OPT_frewrite_includes); + Opts.UseLineDirectives = Args.hasArg(OPT_fuse_line_directives); } static void ParseTargetArgs(TargetOptions &Opts, ArgList &Args) { @@ -2002,7 +2033,7 @@ std::string CompilerInvocation::getModuleHash() const { llvm::sys::path::append(systemVersionFile, "SystemVersion.plist"); llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> buffer = - llvm::MemoryBuffer::getFile(systemVersionFile.str()); + llvm::MemoryBuffer::getFile(systemVersionFile); if (buffer) { code = hash_combine(code, buffer.get()->getBuffer()); diff --git a/contrib/llvm/tools/clang/lib/Frontend/DependencyFile.cpp b/contrib/llvm/tools/clang/lib/Frontend/DependencyFile.cpp index 6ea8f51..0995ab4 100644 --- a/contrib/llvm/tools/clang/lib/Frontend/DependencyFile.cpp +++ b/contrib/llvm/tools/clang/lib/Frontend/DependencyFile.cpp @@ -150,6 +150,8 @@ class DFGImpl : public PPCallbacks { bool AddMissingHeaderDeps; bool SeenMissingHeader; bool IncludeModuleFiles; + DependencyOutputFormat OutputFormat; + private: bool FileMatchesDepCriteria(const char *Filename, SrcMgr::CharacteristicKind FileType); @@ -162,7 +164,8 @@ public: PhonyTarget(Opts.UsePhonyTargets), AddMissingHeaderDeps(Opts.AddMissingHeaderDeps), SeenMissingHeader(false), - IncludeModuleFiles(Opts.IncludeModuleFiles) {} + IncludeModuleFiles(Opts.IncludeModuleFiles), + OutputFormat(Opts.OutputFormat) {} void FileChanged(SourceLocation Loc, FileChangeReason Reason, SrcMgr::CharacteristicKind FileType, @@ -289,13 +292,76 @@ void DFGImpl::AddFilename(StringRef Filename) { Files.push_back(Filename); } -/// PrintFilename - GCC escapes spaces, # and $, but apparently not ' or " or -/// other scary characters. -static void PrintFilename(raw_ostream &OS, StringRef Filename) { +/// Print the filename, with escaping or quoting that accommodates the three +/// most likely tools that use dependency files: GNU Make, BSD Make, and +/// NMake/Jom. +/// +/// BSD Make is the simplest case: It does no escaping at all. This means +/// characters that are normally delimiters, i.e. space and # (the comment +/// character) simply aren't supported in filenames. +/// +/// GNU Make does allow space and # in filenames, but to avoid being treated +/// as a delimiter or comment, these must be escaped with a backslash. Because +/// backslash is itself the escape character, if a backslash appears in a +/// filename, it should be escaped as well. (As a special case, $ is escaped +/// as $$, which is the normal Make way to handle the $ character.) +/// For compatibility with BSD Make and historical practice, if GNU Make +/// un-escapes characters in a filename but doesn't find a match, it will +/// retry with the unmodified original string. +/// +/// GCC tries to accommodate both Make formats by escaping any space or # +/// characters in the original filename, but not escaping backslashes. The +/// apparent intent is so that filenames with backslashes will be handled +/// correctly by BSD Make, and by GNU Make in its fallback mode of using the +/// unmodified original string; filenames with # or space characters aren't +/// supported by BSD Make at all, but will be handled correctly by GNU Make +/// due to the escaping. +/// +/// A corner case that GCC gets only partly right is when the original filename +/// has a backslash immediately followed by space or #. GNU Make would expect +/// this backslash to be escaped; however GCC escapes the original backslash +/// only when followed by space, not #. It will therefore take a dependency +/// from a directive such as +/// #include "a\ b\#c.h" +/// and emit it as +/// a\\\ b\\#c.h +/// which GNU Make will interpret as +/// a\ b\ +/// followed by a comment. Failing to find this file, it will fall back to the +/// original string, which probably doesn't exist either; in any case it won't +/// find +/// a\ b\#c.h +/// which is the actual filename specified by the include directive. +/// +/// Clang does what GCC does, rather than what GNU Make expects. +/// +/// NMake/Jom has a different set of scary characters, but wraps filespecs in +/// double-quotes to avoid misinterpreting them; see +/// https://msdn.microsoft.com/en-us/library/dd9y37ha.aspx for NMake info, +/// https://msdn.microsoft.com/en-us/library/windows/desktop/aa365247(v=vs.85).aspx +/// for Windows file-naming info. +static void PrintFilename(raw_ostream &OS, StringRef Filename, + DependencyOutputFormat OutputFormat) { + if (OutputFormat == DependencyOutputFormat::NMake) { + // Add quotes if needed. These are the characters listed as "special" to + // NMake, that are legal in a Windows filespec, and that could cause + // misinterpretation of the dependency string. + if (Filename.find_first_of(" #${}^!") != StringRef::npos) + OS << '\"' << Filename << '\"'; + else + OS << Filename; + return; + } + assert(OutputFormat == DependencyOutputFormat::Make); for (unsigned i = 0, e = Filename.size(); i != e; ++i) { - if (Filename[i] == ' ' || Filename[i] == '#') + if (Filename[i] == '#') // Handle '#' the broken gcc way. + OS << '\\'; + else if (Filename[i] == ' ') { // Handle space correctly. OS << '\\'; - else if (Filename[i] == '$') // $ is escaped by $$. + unsigned j = i; + while (j > 0 && Filename[--j] == '\\') + OS << '\\'; + } else if (Filename[i] == '$') // $ is escaped by $$. OS << '$'; OS << Filename[i]; } @@ -354,7 +420,7 @@ void DFGImpl::OutputDependencyFile() { Columns = 2; } OS << ' '; - PrintFilename(OS, *I); + PrintFilename(OS, *I, OutputFormat); Columns += N + 1; } OS << '\n'; @@ -365,7 +431,7 @@ void DFGImpl::OutputDependencyFile() { for (std::vector<std::string>::iterator I = Files.begin() + 1, E = Files.end(); I != E; ++I) { OS << '\n'; - PrintFilename(OS, *I); + PrintFilename(OS, *I, OutputFormat); OS << ":\n"; } } diff --git a/contrib/llvm/tools/clang/lib/Frontend/FrontendAction.cpp b/contrib/llvm/tools/clang/lib/Frontend/FrontendAction.cpp index c81c81a..9bba755 100644 --- a/contrib/llvm/tools/clang/lib/Frontend/FrontendAction.cpp +++ b/contrib/llvm/tools/clang/lib/Frontend/FrontendAction.cpp @@ -44,7 +44,7 @@ public: explicit DelegatingDeserializationListener( ASTDeserializationListener *Previous, bool DeletePrevious) : Previous(Previous), DeletePrevious(DeletePrevious) {} - virtual ~DelegatingDeserializationListener() { + ~DelegatingDeserializationListener() override { if (DeletePrevious) delete Previous; } @@ -71,7 +71,7 @@ public: Previous->SelectorRead(ID, Sel); } void MacroDefinitionRead(serialization::PreprocessedEntityID PPID, - MacroDefinition *MD) override { + MacroDefinitionRecord *MD) override { if (Previous) Previous->MacroDefinitionRead(PPID, MD); } @@ -262,18 +262,20 @@ bool FrontendAction::BeginSourceFile(CompilerInstance &CI, FileManager &FileMgr = CI.getFileManager(); PreprocessorOptions &PPOpts = CI.getPreprocessorOpts(); StringRef PCHInclude = PPOpts.ImplicitPCHInclude; + std::string SpecificModuleCachePath = CI.getSpecificModuleCachePath(); if (const DirectoryEntry *PCHDir = FileMgr.getDirectory(PCHInclude)) { std::error_code EC; SmallString<128> DirNative; llvm::sys::path::native(PCHDir->getName(), DirNative); bool Found = false; - for (llvm::sys::fs::directory_iterator Dir(DirNative.str(), EC), DirEnd; + for (llvm::sys::fs::directory_iterator Dir(DirNative, EC), DirEnd; Dir != DirEnd && !EC; Dir.increment(EC)) { // Check whether this is an acceptable AST file. if (ASTReader::isAcceptableASTFile(Dir->path(), FileMgr, CI.getLangOpts(), CI.getTargetOpts(), - CI.getPreprocessorOpts())) { + CI.getPreprocessorOpts(), + SpecificModuleCachePath)) { PPOpts.ImplicitPCHInclude = Dir->path(); Found = true; break; @@ -383,6 +385,15 @@ bool FrontendAction::BeginSourceFile(CompilerInstance &CI, "doesn't support modules"); } + // If we were asked to load any module map files, do so now. + for (const auto &Filename : CI.getFrontendOpts().ModuleMapFiles) { + if (auto *File = CI.getFileManager().getFile(Filename)) + CI.getPreprocessor().getHeaderSearchInfo().loadModuleMapFile( + File, /*IsSystem*/false); + else + CI.getDiagnostics().Report(diag::err_module_map_not_found) << Filename; + } + // If we were asked to load any module files, do so now. for (const auto &ModuleFile : CI.getFrontendOpts().ModuleFiles) if (!CI.loadModuleFile(ModuleFile)) @@ -457,16 +468,12 @@ void FrontendAction::EndSourceFile() { // FIXME: There is more per-file stuff we could just drop here? bool DisableFree = CI.getFrontendOpts().DisableFree; if (DisableFree) { - if (!isCurrentFileAST()) { - CI.resetAndLeakSema(); - CI.resetAndLeakASTContext(); - } + CI.resetAndLeakSema(); + CI.resetAndLeakASTContext(); BuryPointer(CI.takeASTConsumer().get()); } else { - if (!isCurrentFileAST()) { - CI.setSema(nullptr); - CI.setASTContext(nullptr); - } + CI.setSema(nullptr); + CI.setASTContext(nullptr); CI.setASTConsumer(nullptr); } @@ -483,13 +490,16 @@ void FrontendAction::EndSourceFile() { // FrontendAction. CI.clearOutputFiles(/*EraseFiles=*/shouldEraseOutputFiles()); - // FIXME: Only do this if DisableFree is set. if (isCurrentFileAST()) { - CI.resetAndLeakSema(); - CI.resetAndLeakASTContext(); - CI.resetAndLeakPreprocessor(); - CI.resetAndLeakSourceManager(); - CI.resetAndLeakFileManager(); + if (DisableFree) { + CI.resetAndLeakPreprocessor(); + CI.resetAndLeakSourceManager(); + CI.resetAndLeakFileManager(); + } else { + CI.setPreprocessor(nullptr); + CI.setSourceManager(nullptr); + CI.setFileManager(nullptr); + } } setCompilerInstance(nullptr); diff --git a/contrib/llvm/tools/clang/lib/Frontend/FrontendActions.cpp b/contrib/llvm/tools/clang/lib/Frontend/FrontendActions.cpp index 701ef02..46cdeeb 100644 --- a/contrib/llvm/tools/clang/lib/Frontend/FrontendActions.cpp +++ b/contrib/llvm/tools/clang/lib/Frontend/FrontendActions.cpp @@ -79,8 +79,9 @@ std::unique_ptr<ASTConsumer> GeneratePCHAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) { std::string Sysroot; std::string OutputFile; - raw_ostream *OS = nullptr; - if (ComputeASTConsumerArguments(CI, InFile, Sysroot, OutputFile, OS)) + raw_ostream *OS = + ComputeASTConsumerArguments(CI, InFile, Sysroot, OutputFile); + if (!OS) return nullptr; if (!CI.getFrontendOpts().RelocatablePCH) @@ -89,28 +90,27 @@ GeneratePCHAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) { nullptr, Sysroot, OS); } -bool GeneratePCHAction::ComputeASTConsumerArguments(CompilerInstance &CI, - StringRef InFile, - std::string &Sysroot, - std::string &OutputFile, - raw_ostream *&OS) { +raw_ostream *GeneratePCHAction::ComputeASTConsumerArguments( + CompilerInstance &CI, StringRef InFile, std::string &Sysroot, + std::string &OutputFile) { Sysroot = CI.getHeaderSearchOpts().Sysroot; if (CI.getFrontendOpts().RelocatablePCH && Sysroot.empty()) { CI.getDiagnostics().Report(diag::err_relocatable_without_isysroot); - return true; + return nullptr; } // We use createOutputFile here because this is exposed via libclang, and we // must disable the RemoveFileOnSignal behavior. // We use a temporary to avoid race conditions. - OS = CI.createOutputFile(CI.getFrontendOpts().OutputFile, /*Binary=*/true, - /*RemoveFileOnSignal=*/false, InFile, - /*Extension=*/"", /*useTemporary=*/true); + raw_ostream *OS = + CI.createOutputFile(CI.getFrontendOpts().OutputFile, /*Binary=*/true, + /*RemoveFileOnSignal=*/false, InFile, + /*Extension=*/"", /*useTemporary=*/true); if (!OS) - return true; + return nullptr; OutputFile = CI.getFrontendOpts().OutputFile; - return false; + return OS; } std::unique_ptr<ASTConsumer> @@ -118,8 +118,9 @@ GenerateModuleAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) { std::string Sysroot; std::string OutputFile; - raw_ostream *OS = nullptr; - if (ComputeASTConsumerArguments(CI, InFile, Sysroot, OutputFile, OS)) + raw_ostream *OS = + ComputeASTConsumerArguments(CI, InFile, Sysroot, OutputFile); + if (!OS) return nullptr; return llvm::make_unique<PCHGenerator>(CI.getPreprocessor(), OutputFile, @@ -151,22 +152,6 @@ static std::error_code addHeaderInclude(StringRef HeaderName, return std::error_code(); } -static std::error_code addHeaderInclude(const FileEntry *Header, - SmallVectorImpl<char> &Includes, - const LangOptions &LangOpts, - bool IsExternC) { - // Use an absolute path if we don't have a filename as written in the module - // map file; this ensures that we will identify the right file independent of - // header search paths. - if (llvm::sys::path::is_absolute(Header->getName())) - return addHeaderInclude(Header->getName(), Includes, LangOpts, IsExternC); - - SmallString<256> AbsName(Header->getName()); - if (std::error_code Err = llvm::sys::fs::make_absolute(AbsName)) - return Err; - return addHeaderInclude(AbsName, Includes, LangOpts, IsExternC); -} - /// \brief Collect the set of header includes needed to construct the given /// module and update the TopHeaders file set of the module. /// @@ -195,21 +180,21 @@ collectModuleHeaderIncludes(const LangOptions &LangOpts, FileManager &FileMgr, } // Note that Module->PrivateHeaders will not be a TopHeader. - if (const FileEntry *UmbrellaHeader = Module->getUmbrellaHeader()) { - // FIXME: Track the name as written here. - Module->addTopHeader(UmbrellaHeader); + if (Module::Header UmbrellaHeader = Module->getUmbrellaHeader()) { + Module->addTopHeader(UmbrellaHeader.Entry); if (Module->Parent) { // Include the umbrella header for submodules. - if (std::error_code Err = addHeaderInclude(UmbrellaHeader, Includes, - LangOpts, Module->IsExternC)) + if (std::error_code Err = addHeaderInclude(UmbrellaHeader.NameAsWritten, + Includes, LangOpts, + Module->IsExternC)) return Err; } - } else if (const DirectoryEntry *UmbrellaDir = Module->getUmbrellaDir()) { + } else if (Module::DirectoryName UmbrellaDir = Module->getUmbrellaDir()) { // Add all of the headers we find in this subdirectory. std::error_code EC; SmallString<128> DirNative; - llvm::sys::path::native(UmbrellaDir->getName(), DirNative); - for (llvm::sys::fs::recursive_directory_iterator Dir(DirNative.str(), EC), + llvm::sys::path::native(UmbrellaDir.Entry->getName(), DirNative); + for (llvm::sys::fs::recursive_directory_iterator Dir(DirNative, EC), DirEnd; Dir != DirEnd && !EC; Dir.increment(EC)) { // Check whether this entry has an extension typically associated with @@ -230,11 +215,20 @@ collectModuleHeaderIncludes(const LangOptions &LangOpts, FileManager &FileMgr, if (ModMap.isHeaderUnavailableInModule(Header, Module)) continue; + // Compute the relative path from the directory to this file. + SmallVector<StringRef, 16> Components; + auto PathIt = llvm::sys::path::rbegin(Dir->path()); + for (int I = 0; I != Dir.level() + 1; ++I, ++PathIt) + Components.push_back(*PathIt); + SmallString<128> RelativeHeader(UmbrellaDir.NameAsWritten); + for (auto It = Components.rbegin(), End = Components.rend(); It != End; + ++It) + llvm::sys::path::append(RelativeHeader, *It); + // Include this header as part of the umbrella directory. - // FIXME: Track the name as written through to here. Module->addTopHeader(Header); - if (std::error_code Err = - addHeaderInclude(Header, Includes, LangOpts, Module->IsExternC)) + if (std::error_code Err = addHeaderInclude(RelativeHeader, Includes, + LangOpts, Module->IsExternC)) return Err; } @@ -326,10 +320,9 @@ bool GenerateModuleAction::BeginSourceFileAction(CompilerInstance &CI, // Collect the set of #includes we need to build the module. SmallString<256> HeaderContents; std::error_code Err = std::error_code(); - if (const FileEntry *UmbrellaHeader = Module->getUmbrellaHeader()) - // FIXME: Track the file name as written. - Err = addHeaderInclude(UmbrellaHeader, HeaderContents, CI.getLangOpts(), - Module->IsExternC); + if (Module::Header UmbrellaHeader = Module->getUmbrellaHeader()) + Err = addHeaderInclude(UmbrellaHeader.NameAsWritten, HeaderContents, + CI.getLangOpts(), Module->IsExternC); if (!Err) Err = collectModuleHeaderIncludes( CI.getLangOpts(), FileMgr, @@ -355,11 +348,9 @@ bool GenerateModuleAction::BeginSourceFileAction(CompilerInstance &CI, return true; } -bool GenerateModuleAction::ComputeASTConsumerArguments(CompilerInstance &CI, - StringRef InFile, - std::string &Sysroot, - std::string &OutputFile, - raw_ostream *&OS) { +raw_ostream *GenerateModuleAction::ComputeASTConsumerArguments( + CompilerInstance &CI, StringRef InFile, std::string &Sysroot, + std::string &OutputFile) { // If no output file was provided, figure out where this module would go // in the module cache. if (CI.getFrontendOpts().OutputFile.empty()) { @@ -368,19 +359,20 @@ bool GenerateModuleAction::ComputeASTConsumerArguments(CompilerInstance &CI, HS.getModuleFileName(CI.getLangOpts().CurrentModule, ModuleMapForUniquing->getName()); } - + // We use createOutputFile here because this is exposed via libclang, and we // must disable the RemoveFileOnSignal behavior. // We use a temporary to avoid race conditions. - OS = CI.createOutputFile(CI.getFrontendOpts().OutputFile, /*Binary=*/true, - /*RemoveFileOnSignal=*/false, InFile, - /*Extension=*/"", /*useTemporary=*/true, - /*CreateMissingDirectories=*/true); + raw_ostream *OS = + CI.createOutputFile(CI.getFrontendOpts().OutputFile, /*Binary=*/true, + /*RemoveFileOnSignal=*/false, InFile, + /*Extension=*/"", /*useTemporary=*/true, + /*CreateMissingDirectories=*/true); if (!OS) - return true; - + return nullptr; + OutputFile = CI.getFrontendOpts().OutputFile; - return false; + return OS; } std::unique_ptr<ASTConsumer> @@ -462,8 +454,8 @@ namespace { return false; } - bool ReadTargetOptions(const TargetOptions &TargetOpts, - bool Complain) override { + bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain, + bool AllowCompatibleDifferences) override { Out.indent(2) << "Target options:\n"; Out.indent(4) << " Triple: " << TargetOpts.Triple << "\n"; Out.indent(4) << " CPU: " << TargetOpts.CPU << "\n"; @@ -480,9 +472,8 @@ namespace { return false; } - virtual bool - ReadDiagnosticOptions(IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, - bool Complain) override { + bool ReadDiagnosticOptions(IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, + bool Complain) override { Out.indent(2) << "Diagnostic options:\n"; #define DIAGOPT(Name, Bits, Default) DUMP_BOOLEAN(DiagOpts->Name, #Name); #define ENUM_DIAGOPT(Name, Type, Bits, Default) \ @@ -501,9 +492,11 @@ namespace { } bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts, + StringRef SpecificModuleCachePath, bool Complain) override { Out.indent(2) << "Header search options:\n"; Out.indent(4) << "System root [-isysroot=]: '" << HSOpts.Sysroot << "'\n"; + Out.indent(4) << "Module Cache: '" << SpecificModuleCachePath << "'\n"; DUMP_BOOLEAN(HSOpts.UseBuiltinIncludes, "Use builtin include directories [-nobuiltininc]"); DUMP_BOOLEAN(HSOpts.UseStandardSystemIncludes, @@ -598,15 +591,9 @@ void DumpTokensAction::ExecuteAction() { void GeneratePTHAction::ExecuteAction() { CompilerInstance &CI = getCompilerInstance(); - if (CI.getFrontendOpts().OutputFile.empty() || - CI.getFrontendOpts().OutputFile == "-") { - // FIXME: Don't fail this way. - // FIXME: Verify that we can actually seek in the given file. - llvm::report_fatal_error("PTH requires a seekable file for output!"); - } - llvm::raw_fd_ostream *OS = - CI.createDefaultOutputFile(true, getCurrentFile()); - if (!OS) return; + raw_pwrite_stream *OS = CI.createDefaultOutputFile(true, getCurrentFile()); + if (!OS) + return; CacheTokens(CI.getPreprocessor(), OS); } @@ -688,6 +675,7 @@ void PrintPreambleAction::ExecuteAction() { case IK_None: case IK_Asm: case IK_PreprocessedC: + case IK_PreprocessedCuda: case IK_PreprocessedCXX: case IK_PreprocessedObjC: case IK_PreprocessedObjCXX: diff --git a/contrib/llvm/tools/clang/lib/Frontend/FrontendOptions.cpp b/contrib/llvm/tools/clang/lib/Frontend/FrontendOptions.cpp index 1869d0c..9ede674 100644 --- a/contrib/llvm/tools/clang/lib/Frontend/FrontendOptions.cpp +++ b/contrib/llvm/tools/clang/lib/Frontend/FrontendOptions.cpp @@ -18,6 +18,7 @@ InputKind FrontendOptions::getInputKindForExtension(StringRef Extension) { .Cases("S", "s", IK_Asm) .Case("i", IK_PreprocessedC) .Case("ii", IK_PreprocessedCXX) + .Case("cui", IK_PreprocessedCuda) .Case("m", IK_ObjC) .Case("mi", IK_PreprocessedObjC) .Cases("mm", "M", IK_ObjCXX) diff --git a/contrib/llvm/tools/clang/lib/Frontend/HeaderIncludeGen.cpp b/contrib/llvm/tools/clang/lib/Frontend/HeaderIncludeGen.cpp index 2701194..5732e5b 100644 --- a/contrib/llvm/tools/clang/lib/Frontend/HeaderIncludeGen.cpp +++ b/contrib/llvm/tools/clang/lib/Frontend/HeaderIncludeGen.cpp @@ -35,7 +35,7 @@ public: OwnsOutputFile(OwnsOutputFile_), ShowAllHeaders(ShowAllHeaders_), ShowDepth(ShowDepth_), MSStyle(MSStyle_) {} - ~HeaderIncludesCallback() { + ~HeaderIncludesCallback() override { if (OwnsOutputFile) delete OutputFile; } diff --git a/contrib/llvm/tools/clang/lib/Frontend/InitHeaderSearch.cpp b/contrib/llvm/tools/clang/lib/Frontend/InitHeaderSearch.cpp index a518a0a..2bd999e 100644 --- a/contrib/llvm/tools/clang/lib/Frontend/InitHeaderSearch.cpp +++ b/contrib/llvm/tools/clang/lib/Frontend/InitHeaderSearch.cpp @@ -227,10 +227,12 @@ void InitHeaderSearch::AddDefaultCIncludePaths(const llvm::Triple &triple, if (HSOpts.UseStandardSystemIncludes) { switch (os) { + case llvm::Triple::CloudABI: case llvm::Triple::FreeBSD: case llvm::Triple::NetBSD: case llvm::Triple::OpenBSD: case llvm::Triple::Bitrig: + case llvm::Triple::NaCl: break; default: // FIXME: temporary hack: hard-coded paths. @@ -246,7 +248,7 @@ void InitHeaderSearch::AddDefaultCIncludePaths(const llvm::Triple &triple, // supplied path. SmallString<128> P = StringRef(HSOpts.ResourceDir); llvm::sys::path::append(P, "include"); - AddUnmappedPath(P.str(), ExternCSystem, false); + AddUnmappedPath(P, ExternCSystem, false); } // All remaining additions are for system include directories, early exit if @@ -270,6 +272,14 @@ void InitHeaderSearch::AddDefaultCIncludePaths(const llvm::Triple &triple, case llvm::Triple::Linux: llvm_unreachable("Include management is handled in the driver."); + case llvm::Triple::CloudABI: { + // <sysroot>/<triple>/include + SmallString<128> P = StringRef(HSOpts.ResourceDir); + llvm::sys::path::append(P, "../../..", triple.str(), "include"); + AddPath(P, System, false); + break; + } + case llvm::Triple::Haiku: AddPath("/boot/common/include", System, false); AddPath("/boot/develop/headers/os", System, false); @@ -317,18 +327,18 @@ void InitHeaderSearch::AddDefaultCIncludePaths(const llvm::Triple &triple, // <sysroot>/i686-w64-mingw32/include SmallString<128> P = StringRef(HSOpts.ResourceDir); llvm::sys::path::append(P, "../../../i686-w64-mingw32/include"); - AddPath(P.str(), System, false); + AddPath(P, System, false); // <sysroot>/x86_64-w64-mingw32/include P.resize(HSOpts.ResourceDir.size()); llvm::sys::path::append(P, "../../../x86_64-w64-mingw32/include"); - AddPath(P.str(), System, false); + AddPath(P, System, false); // mingw.org crt include paths // <sysroot>/include P.resize(HSOpts.ResourceDir.size()); llvm::sys::path::append(P, "../../../include"); - AddPath(P.str(), System, false); + AddPath(P, System, false); AddPath("/mingw/include", System, false); #if defined(LLVM_ON_WIN32) AddPath("c:/mingw/include", System, false); @@ -340,8 +350,15 @@ void InitHeaderSearch::AddDefaultCIncludePaths(const llvm::Triple &triple, break; } - if ( os != llvm::Triple::RTEMS ) + switch (os) { + case llvm::Triple::CloudABI: + case llvm::Triple::RTEMS: + case llvm::Triple::NaCl: + break; + default: AddPath("/usr/include", ExternCSystem, false); + break; + } } void InitHeaderSearch:: @@ -488,7 +505,7 @@ void InitHeaderSearch::AddDefaultIncludePaths(const LangOptions &Lang, // Get foo/include/c++/v1 llvm::sys::path::append(P, "include", "c++", "v1"); - AddUnmappedPath(P.str(), CXXSystem, false); + AddUnmappedPath(P, CXXSystem, false); } } // On Solaris, include the support directory for things like xlocale and @@ -699,7 +716,7 @@ void clang::ApplyHeaderSearchOptions(HeaderSearch &HS, // Set up the builtin include directory in the module map. SmallString<128> P = StringRef(HSOpts.ResourceDir); llvm::sys::path::append(P, "include"); - if (const DirectoryEntry *Dir = HS.getFileMgr().getDirectory(P.str())) + if (const DirectoryEntry *Dir = HS.getFileMgr().getDirectory(P)) HS.getModuleMap().setBuiltinIncludeDir(Dir); } diff --git a/contrib/llvm/tools/clang/lib/Frontend/InitPreprocessor.cpp b/contrib/llvm/tools/clang/lib/Frontend/InitPreprocessor.cpp index 3550ac2..dfc46f4 100644 --- a/contrib/llvm/tools/clang/lib/Frontend/InitPreprocessor.cpp +++ b/contrib/llvm/tools/clang/lib/Frontend/InitPreprocessor.cpp @@ -133,6 +133,7 @@ static void DefineFloatMacros(MacroBuilder &Builder, StringRef Prefix, "4.94065645841246544176568792868221e-324", "6.47517511943802511092443895822764655e-4966"); int Digits = PickFP(Sem, 6, 15, 18, 31, 33); + int DecimalDigits = PickFP(Sem, 9, 17, 21, 33, 36); Epsilon = PickFP(Sem, "1.19209290e-7", "2.2204460492503131e-16", "1.08420217248550443401e-19", "4.94065645841246544176568792868221e-324", @@ -159,6 +160,7 @@ static void DefineFloatMacros(MacroBuilder &Builder, StringRef Prefix, Builder.defineMacro(DefPrefix + "DENORM_MIN__", Twine(DenormMin)+Ext); Builder.defineMacro(DefPrefix + "HAS_DENORM__"); Builder.defineMacro(DefPrefix + "DIG__", Twine(Digits)); + Builder.defineMacro(DefPrefix + "DECIMAL_DIG__", Twine(DecimalDigits)); Builder.defineMacro(DefPrefix + "EPSILON__", Twine(Epsilon)+Ext); Builder.defineMacro(DefPrefix + "HAS_INFINITY__"); Builder.defineMacro(DefPrefix + "HAS_QUIET_NAN__"); @@ -451,6 +453,8 @@ static void InitializeCPlusPlusFeatureTestMacros(const LangOptions &LangOpts, } if (LangOpts.SizedDeallocation) Builder.defineMacro("__cpp_sized_deallocation", "201309"); + if (LangOpts.ConceptsTS) + Builder.defineMacro("__cpp_experimental_concepts", "1"); } static void InitializePredefinedMacros(const TargetInfo &TI, @@ -705,6 +709,10 @@ static void InitializePredefinedMacros(const TargetInfo &TI, Builder.defineMacro("__POINTER_WIDTH__", Twine((int)TI.getPointerWidth(0))); + // Define __BIGGEST_ALIGNMENT__ to be compatible with gcc. + Builder.defineMacro("__BIGGEST_ALIGNMENT__", + Twine(TI.getSuitableAlign() / TI.getCharWidth()) ); + if (!LangOpts.CharIsSigned) Builder.defineMacro("__CHAR_UNSIGNED__"); @@ -784,7 +792,7 @@ static void InitializePredefinedMacros(const TargetInfo &TI, Builder.defineMacro("__FINITE_MATH_ONLY__", "0"); if (!LangOpts.MSVCCompat) { - if (LangOpts.GNUInline) + if (LangOpts.GNUInline || LangOpts.CPlusPlus) Builder.defineMacro("__GNUC_GNU_INLINE__"); else Builder.defineMacro("__GNUC_STDC_INLINE__"); @@ -831,8 +839,7 @@ static void InitializePredefinedMacros(const TargetInfo &TI, // Macros to control C99 numerics and <float.h> Builder.defineMacro("__FLT_EVAL_METHOD__", Twine(TI.getFloatEvalMethod())); Builder.defineMacro("__FLT_RADIX__", "2"); - int Dig = PickFP(&TI.getLongDoubleFormat(), -1/*FIXME*/, 17, 21, 33, 36); - Builder.defineMacro("__DECIMAL_DIG__", Twine(Dig)); + Builder.defineMacro("__DECIMAL_DIG__", "__LDBL_DECIMAL_DIG__"); if (LangOpts.getStackProtector() == LangOptions::SSPOn) Builder.defineMacro("__SSP__"); diff --git a/contrib/llvm/tools/clang/lib/Frontend/ModuleDependencyCollector.cpp b/contrib/llvm/tools/clang/lib/Frontend/ModuleDependencyCollector.cpp index 62865e9..67852dc 100644 --- a/contrib/llvm/tools/clang/lib/Frontend/ModuleDependencyCollector.cpp +++ b/contrib/llvm/tools/clang/lib/Frontend/ModuleDependencyCollector.cpp @@ -77,10 +77,10 @@ std::error_code ModuleDependencyListener::copyToRoot(StringRef Src) { if (std::error_code EC = fs::create_directories(path::parent_path(Dest), /*IgnoreExisting=*/true)) return EC; - if (std::error_code EC = fs::copy_file(AbsoluteSrc.str(), Dest.str())) + if (std::error_code EC = fs::copy_file(AbsoluteSrc, Dest)) return EC; // Use the absolute path under the root for the file mapping. - Collector.addFileMapping(AbsoluteSrc.str(), Dest.str()); + Collector.addFileMapping(AbsoluteSrc, Dest); return std::error_code(); } diff --git a/contrib/llvm/tools/clang/lib/Frontend/MultiplexConsumer.cpp b/contrib/llvm/tools/clang/lib/Frontend/MultiplexConsumer.cpp index 0198828..219e949 100644 --- a/contrib/llvm/tools/clang/lib/Frontend/MultiplexConsumer.cpp +++ b/contrib/llvm/tools/clang/lib/Frontend/MultiplexConsumer.cpp @@ -37,9 +37,10 @@ public: void DeclRead(serialization::DeclID ID, const Decl *D) override; void SelectorRead(serialization::SelectorID iD, Selector Sel) override; void MacroDefinitionRead(serialization::PreprocessedEntityID, - MacroDefinition *MD) override; + MacroDefinitionRecord *MD) override; + private: - std::vector<ASTDeserializationListener*> Listeners; + std::vector<ASTDeserializationListener *> Listeners; }; MultiplexASTDeserializationListener::MultiplexASTDeserializationListener( @@ -78,7 +79,7 @@ void MultiplexASTDeserializationListener::SelectorRead( } void MultiplexASTDeserializationListener::MacroDefinitionRead( - serialization::PreprocessedEntityID ID, MacroDefinition *MD) { + serialization::PreprocessedEntityID ID, MacroDefinitionRecord *MD) { for (size_t i = 0, e = Listeners.size(); i != e; ++i) Listeners[i]->MacroDefinitionRead(ID, MD); } @@ -99,6 +100,8 @@ public: void AddedCXXTemplateSpecialization(const FunctionTemplateDecl *TD, const FunctionDecl *D) override; void DeducedReturnType(const FunctionDecl *FD, QualType ReturnType) override; + void ResolvedOperatorDelete(const CXXDestructorDecl *DD, + const FunctionDecl *Delete) override; void CompletedImplicitDefinition(const FunctionDecl *D) override; void StaticDataMemberInstantiated(const VarDecl *D) override; void AddedObjCCategoryToInterface(const ObjCCategoryDecl *CatD, @@ -108,6 +111,7 @@ public: const ObjCCategoryDecl *ClassExt) override; void DeclarationMarkedUsed(const Decl *D) override; void DeclarationMarkedOpenMPThreadPrivate(const Decl *D) override; + void RedefinedHiddenDefinition(const NamedDecl *D, Module *M) override; private: std::vector<ASTMutationListener*> Listeners; @@ -154,6 +158,11 @@ void MultiplexASTMutationListener::DeducedReturnType(const FunctionDecl *FD, for (size_t i = 0, e = Listeners.size(); i != e; ++i) Listeners[i]->DeducedReturnType(FD, ReturnType); } +void MultiplexASTMutationListener::ResolvedOperatorDelete( + const CXXDestructorDecl *DD, const FunctionDecl *Delete) { + for (auto *L : Listeners) + L->ResolvedOperatorDelete(DD, Delete); +} void MultiplexASTMutationListener::CompletedImplicitDefinition( const FunctionDecl *D) { for (size_t i = 0, e = Listeners.size(); i != e; ++i) @@ -186,6 +195,11 @@ void MultiplexASTMutationListener::DeclarationMarkedOpenMPThreadPrivate( for (size_t i = 0, e = Listeners.size(); i != e; ++i) Listeners[i]->DeclarationMarkedOpenMPThreadPrivate(D); } +void MultiplexASTMutationListener::RedefinedHiddenDefinition(const NamedDecl *D, + Module *M) { + for (auto *L : Listeners) + L->RedefinedHiddenDefinition(D, M); +} } // end namespace clang @@ -292,10 +306,9 @@ void MultiplexConsumer::CompleteTentativeDefinition(VarDecl *D) { Consumer->CompleteTentativeDefinition(D); } -void MultiplexConsumer::HandleVTable( - CXXRecordDecl *RD, bool DefinitionRequired) { +void MultiplexConsumer::HandleVTable(CXXRecordDecl *RD) { for (auto &Consumer : Consumers) - Consumer->HandleVTable(RD, DefinitionRequired); + Consumer->HandleVTable(RD); } ASTMutationListener *MultiplexConsumer::GetASTMutationListener() { diff --git a/contrib/llvm/tools/clang/lib/Frontend/PrintPreprocessedOutput.cpp b/contrib/llvm/tools/clang/lib/Frontend/PrintPreprocessedOutput.cpp index 7c1d9a5..037a6a5 100644 --- a/contrib/llvm/tools/clang/lib/Frontend/PrintPreprocessedOutput.cpp +++ b/contrib/llvm/tools/clang/lib/Frontend/PrintPreprocessedOutput.cpp @@ -64,12 +64,11 @@ static void PrintMacroDefinition(const IdentifierInfo &II, const MacroInfo &MI, OS << ' '; SmallString<128> SpellingBuffer; - for (MacroInfo::tokens_iterator I = MI.tokens_begin(), E = MI.tokens_end(); - I != E; ++I) { - if (I->hasLeadingSpace()) + for (const auto &T : MI.tokens()) { + if (T.hasLeadingSpace()) OS << ' '; - OS << PP.getSpelling(*I, SpellingBuffer); + OS << PP.getSpelling(T, SpellingBuffer); } } @@ -94,14 +93,14 @@ private: bool Initialized; bool DisableLineMarkers; bool DumpDefines; - bool UseLineDirective; + bool UseLineDirectives; bool IsFirstFileEntered; public: - PrintPPOutputPPCallbacks(Preprocessor &pp, raw_ostream &os, - bool lineMarkers, bool defines) - : PP(pp), SM(PP.getSourceManager()), - ConcatInfo(PP), OS(os), DisableLineMarkers(lineMarkers), - DumpDefines(defines) { + PrintPPOutputPPCallbacks(Preprocessor &pp, raw_ostream &os, bool lineMarkers, + bool defines, bool UseLineDirectives) + : PP(pp), SM(PP.getSourceManager()), ConcatInfo(PP), OS(os), + DisableLineMarkers(lineMarkers), DumpDefines(defines), + UseLineDirectives(UseLineDirectives) { CurLine = 0; CurFilename += "<uninit>"; EmittedTokensOnThisLine = false; @@ -109,9 +108,6 @@ public: FileType = SrcMgr::C_User; Initialized = false; IsFirstFileEntered = false; - - // If we're in microsoft mode, use normal #line instead of line markers. - UseLineDirective = PP.getLangOpts().MicrosoftExt; } void setEmittedTokensOnThisLine() { EmittedTokensOnThisLine = true; } @@ -173,7 +169,7 @@ public: /// MacroUndefined - This hook is called whenever a macro #undef is seen. void MacroUndefined(const Token &MacroNameTok, - const MacroDirective *MD) override; + const MacroDefinition &MD) override; }; } // end anonymous namespace @@ -183,7 +179,7 @@ void PrintPPOutputPPCallbacks::WriteLineInfo(unsigned LineNo, startNewLineIfNeeded(/*ShouldUpdateCurrentLine=*/false); // Emit #line directives or GNU line markers depending on what mode we're in. - if (UseLineDirective) { + if (UseLineDirectives) { OS << "#line" << ' ' << LineNo << ' ' << '"'; OS.write_escaped(CurFilename); OS << '"'; @@ -364,7 +360,7 @@ void PrintPPOutputPPCallbacks::MacroDefined(const Token &MacroNameTok, } void PrintPPOutputPPCallbacks::MacroUndefined(const Token &MacroNameTok, - const MacroDirective *MD) { + const MacroDefinition &MD) { // Only print out macro definitions in -dD mode. if (!DumpDefines) return; @@ -689,8 +685,9 @@ static void DoPrintMacros(Preprocessor &PP, raw_ostream *OS) { SmallVector<id_macro_pair, 128> MacrosByID; for (Preprocessor::macro_iterator I = PP.macro_begin(), E = PP.macro_end(); I != E; ++I) { - if (I->first->hasMacroDefinition()) - MacrosByID.push_back(id_macro_pair(I->first, I->second->getMacroInfo())); + auto *MD = I->second.getLatest(); + if (MD && MD->isDefined()) + MacrosByID.push_back(id_macro_pair(I->first, MD->getMacroInfo())); } llvm::array_pod_sort(MacrosByID.begin(), MacrosByID.end(), MacroIDCompare); @@ -719,9 +716,8 @@ void clang::DoPrintPreprocessedInput(Preprocessor &PP, raw_ostream *OS, // to -C or -CC. PP.SetCommentRetentionState(Opts.ShowComments, Opts.ShowMacroComments); - PrintPPOutputPPCallbacks *Callbacks = - new PrintPPOutputPPCallbacks(PP, *OS, !Opts.ShowLineMarkers, - Opts.ShowMacros); + PrintPPOutputPPCallbacks *Callbacks = new PrintPPOutputPPCallbacks( + PP, *OS, !Opts.ShowLineMarkers, Opts.ShowMacros, Opts.UseLineDirectives); PP.AddPragmaHandler(new UnknownPragmaHandler("#pragma", Callbacks)); PP.AddPragmaHandler("GCC", new UnknownPragmaHandler("#pragma GCC",Callbacks)); PP.AddPragmaHandler("clang", diff --git a/contrib/llvm/tools/clang/lib/Frontend/Rewrite/InclusionRewriter.cpp b/contrib/llvm/tools/clang/lib/Frontend/Rewrite/InclusionRewriter.cpp index 1400557..b9ea051 100644 --- a/contrib/llvm/tools/clang/lib/Frontend/Rewrite/InclusionRewriter.cpp +++ b/contrib/llvm/tools/clang/lib/Frontend/Rewrite/InclusionRewriter.cpp @@ -43,14 +43,15 @@ class InclusionRewriter : public PPCallbacks { StringRef MainEOL; ///< The line ending marker to use. const llvm::MemoryBuffer *PredefinesBuffer; ///< The preprocessor predefines. bool ShowLineMarkers; ///< Show #line markers. - bool UseLineDirective; ///< Use of line directives or line markers. + bool UseLineDirectives; ///< Use of line directives or line markers. typedef std::map<unsigned, FileChange> FileChangeMap; FileChangeMap FileChanges; ///< Tracks which files were included where. /// Used transitively for building up the FileChanges mapping over the /// various \c PPCallbacks callbacks. FileChangeMap::iterator LastInsertedFileChange; public: - InclusionRewriter(Preprocessor &PP, raw_ostream &OS, bool ShowLineMarkers); + InclusionRewriter(Preprocessor &PP, raw_ostream &OS, bool ShowLineMarkers, + bool UseLineDirectives); bool Process(FileID FileId, SrcMgr::CharacteristicKind FileType); void setPredefinesBuffer(const llvm::MemoryBuffer *Buf) { PredefinesBuffer = Buf; @@ -60,7 +61,7 @@ private: void FileChanged(SourceLocation Loc, FileChangeReason Reason, SrcMgr::CharacteristicKind FileType, FileID PrevFID) override; - void FileSkipped(const FileEntry &ParentFile, const Token &FilenameTok, + void FileSkipped(const FileEntry &SkippedFile, const Token &FilenameTok, SrcMgr::CharacteristicKind FileType) override; void InclusionDirective(SourceLocation HashLoc, const Token &IncludeTok, StringRef FileName, bool IsAngled, @@ -89,13 +90,12 @@ private: /// Initializes an InclusionRewriter with a \p PP source and \p OS destination. InclusionRewriter::InclusionRewriter(Preprocessor &PP, raw_ostream &OS, - bool ShowLineMarkers) + bool ShowLineMarkers, + bool UseLineDirectives) : PP(PP), SM(PP.getSourceManager()), OS(OS), MainEOL("\n"), PredefinesBuffer(nullptr), ShowLineMarkers(ShowLineMarkers), - LastInsertedFileChange(FileChanges.end()) { - // If we're in microsoft mode, use normal #line instead of line markers. - UseLineDirective = PP.getLangOpts().MicrosoftExt; -} + UseLineDirectives(UseLineDirectives), + LastInsertedFileChange(FileChanges.end()) {} /// Write appropriate line information as either #line directives or GNU line /// markers depending on what mode we're in, including the \p Filename and @@ -106,7 +106,7 @@ void InclusionRewriter::WriteLineInfo(const char *Filename, int Line, StringRef Extra) { if (!ShowLineMarkers) return; - if (UseLineDirective) { + if (UseLineDirectives) { OS << "#line" << ' ' << Line << ' ' << '"'; OS.write_escaped(Filename); OS << '"'; @@ -153,7 +153,7 @@ void InclusionRewriter::FileChanged(SourceLocation Loc, /// Called whenever an inclusion is skipped due to canonical header protection /// macros. -void InclusionRewriter::FileSkipped(const FileEntry &/*ParentFile*/, +void InclusionRewriter::FileSkipped(const FileEntry &/*SkippedFile*/, const Token &/*FilenameTok*/, SrcMgr::CharacteristicKind /*FileType*/) { assert(LastInsertedFileChange != FileChanges.end() && "A file, that wasn't " @@ -561,8 +561,8 @@ bool InclusionRewriter::Process(FileID FileId, void clang::RewriteIncludesInInput(Preprocessor &PP, raw_ostream *OS, const PreprocessorOutputOptions &Opts) { SourceManager &SM = PP.getSourceManager(); - InclusionRewriter *Rewrite = new InclusionRewriter(PP, *OS, - Opts.ShowLineMarkers); + InclusionRewriter *Rewrite = new InclusionRewriter( + PP, *OS, Opts.ShowLineMarkers, Opts.UseLineDirectives); Rewrite->detectMainFileEOL(); PP.addPPCallbacks(std::unique_ptr<PPCallbacks>(Rewrite)); diff --git a/contrib/llvm/tools/clang/lib/Frontend/Rewrite/RewriteModernObjC.cpp b/contrib/llvm/tools/clang/lib/Frontend/Rewrite/RewriteModernObjC.cpp index 47f8189..e13cdb3 100644 --- a/contrib/llvm/tools/clang/lib/Frontend/Rewrite/RewriteModernObjC.cpp +++ b/contrib/llvm/tools/clang/lib/Frontend/Rewrite/RewriteModernObjC.cpp @@ -243,8 +243,8 @@ namespace { RewriteModernObjC(std::string inFile, raw_ostream *OS, DiagnosticsEngine &D, const LangOptions &LOpts, bool silenceMacroWarn, bool LineInfo); - - ~RewriteModernObjC() {} + + ~RewriteModernObjC() override {} void HandleTranslationUnit(ASTContext &C) override; @@ -889,9 +889,9 @@ RewriteModernObjC::getIvarAccessString(ObjCIvarDecl *D) { IvarT, nullptr, /*BitWidth=*/nullptr, /*Mutable=*/true, ICIS_NoInit); - MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(), - FD->getType(), VK_LValue, - OK_Ordinary); + MemberExpr *ME = new (Context) + MemberExpr(PE, true, SourceLocation(), FD, SourceLocation(), + FD->getType(), VK_LValue, OK_Ordinary); IvarT = Context->getDecltypeType(ME, ME->getType()); } } @@ -2689,7 +2689,7 @@ Stmt *RewriteModernObjC::RewriteObjCBoxedExpr(ObjCBoxedExpr *Exp) { MsgExprs.push_back(subExpr); SmallVector<QualType, 4> ArgTypes; - ArgTypes.push_back(Context->getObjCIdType()); + ArgTypes.push_back(Context->getObjCClassType()); ArgTypes.push_back(Context->getObjCSelType()); for (const auto PI : BoxingMethod->parameters()) ArgTypes.push_back(PI->getType()); @@ -2767,11 +2767,9 @@ Stmt *RewriteModernObjC::RewriteObjCArrayLiteralExpr(ObjCArrayLiteral *Exp) { Context->getPointerType(Context->VoidPtrTy), nullptr, /*BitWidth=*/nullptr, /*Mutable=*/true, ICIS_NoInit); - MemberExpr *ArrayLiteralME = - new (Context) MemberExpr(NSArrayCallExpr, false, ARRFD, - SourceLocation(), - ARRFD->getType(), VK_LValue, - OK_Ordinary); + MemberExpr *ArrayLiteralME = new (Context) + MemberExpr(NSArrayCallExpr, false, SourceLocation(), ARRFD, + SourceLocation(), ARRFD->getType(), VK_LValue, OK_Ordinary); QualType ConstIdT = Context->getObjCIdType().withConst(); CStyleCastExpr * ArrayLiteralObjects = NoTypeInfoCStyleCastExpr(Context, @@ -2818,7 +2816,7 @@ Stmt *RewriteModernObjC::RewriteObjCArrayLiteralExpr(ObjCArrayLiteral *Exp) { SmallVector<QualType, 4> ArgTypes; - ArgTypes.push_back(Context->getObjCIdType()); + ArgTypes.push_back(Context->getObjCClassType()); ArgTypes.push_back(Context->getObjCSelType()); for (const auto *PI : ArrayMethod->params()) ArgTypes.push_back(PI->getType()); @@ -2904,11 +2902,9 @@ Stmt *RewriteModernObjC::RewriteObjCDictionaryLiteralExpr(ObjCDictionaryLiteral Context->getPointerType(Context->VoidPtrTy), nullptr, /*BitWidth=*/nullptr, /*Mutable=*/true, ICIS_NoInit); - MemberExpr *DictLiteralValueME = - new (Context) MemberExpr(NSValueCallExpr, false, ARRFD, - SourceLocation(), - ARRFD->getType(), VK_LValue, - OK_Ordinary); + MemberExpr *DictLiteralValueME = new (Context) + MemberExpr(NSValueCallExpr, false, SourceLocation(), ARRFD, + SourceLocation(), ARRFD->getType(), VK_LValue, OK_Ordinary); QualType ConstIdT = Context->getObjCIdType().withConst(); CStyleCastExpr * DictValueObjects = NoTypeInfoCStyleCastExpr(Context, @@ -2919,13 +2915,11 @@ Stmt *RewriteModernObjC::RewriteObjCDictionaryLiteralExpr(ObjCDictionaryLiteral Expr *NSKeyCallExpr = new (Context) CallExpr(*Context, NSDictDRE, KeyExprs, NSDictFType, VK_LValue, SourceLocation()); - - MemberExpr *DictLiteralKeyME = - new (Context) MemberExpr(NSKeyCallExpr, false, ARRFD, - SourceLocation(), - ARRFD->getType(), VK_LValue, - OK_Ordinary); - + + MemberExpr *DictLiteralKeyME = new (Context) + MemberExpr(NSKeyCallExpr, false, SourceLocation(), ARRFD, + SourceLocation(), ARRFD->getType(), VK_LValue, OK_Ordinary); + CStyleCastExpr * DictKeyObjects = NoTypeInfoCStyleCastExpr(Context, Context->getPointerType(ConstIdT), @@ -2975,7 +2969,7 @@ Stmt *RewriteModernObjC::RewriteObjCDictionaryLiteralExpr(ObjCDictionaryLiteral SmallVector<QualType, 8> ArgTypes; - ArgTypes.push_back(Context->getObjCIdType()); + ArgTypes.push_back(Context->getObjCClassType()); ArgTypes.push_back(Context->getObjCSelType()); for (const auto *PI : DictMethod->params()) { QualType T = PI->getType(); @@ -3234,9 +3228,9 @@ Expr *RewriteModernObjC::SynthMsgSendStretCallExpr(FunctionDecl *MsgSendStretFla returnType, nullptr, /*BitWidth=*/nullptr, /*Mutable=*/true, ICIS_NoInit); - MemberExpr *ME = new (Context) MemberExpr(STCE, false, FieldD, SourceLocation(), - FieldD->getType(), VK_LValue, - OK_Ordinary); + MemberExpr *ME = new (Context) + MemberExpr(STCE, false, SourceLocation(), FieldD, SourceLocation(), + FieldD->getType(), VK_LValue, OK_Ordinary); return ME; } @@ -4732,11 +4726,10 @@ Stmt *RewriteModernObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp Context->VoidPtrTy, nullptr, /*BitWidth=*/nullptr, /*Mutable=*/true, ICIS_NoInit); - MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(), - FD->getType(), VK_LValue, - OK_Ordinary); + MemberExpr *ME = + new (Context) MemberExpr(PE, true, SourceLocation(), FD, SourceLocation(), + FD->getType(), VK_LValue, OK_Ordinary); - CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType, CK_BitCast, ME); PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast); @@ -4781,10 +4774,9 @@ Stmt *RewriteModernObjC::RewriteBlockDeclRefExpr(DeclRefExpr *DeclRefExp) { Context->VoidPtrTy, nullptr, /*BitWidth=*/nullptr, /*Mutable=*/true, ICIS_NoInit); - MemberExpr *ME = new (Context) MemberExpr(DeclRefExp, isArrow, - FD, SourceLocation(), - FD->getType(), VK_LValue, - OK_Ordinary); + MemberExpr *ME = new (Context) + MemberExpr(DeclRefExp, isArrow, SourceLocation(), FD, SourceLocation(), + FD->getType(), VK_LValue, OK_Ordinary); StringRef Name = VD->getName(); FD = FieldDecl::Create(*Context, nullptr, SourceLocation(), SourceLocation(), @@ -4792,11 +4784,10 @@ Stmt *RewriteModernObjC::RewriteBlockDeclRefExpr(DeclRefExpr *DeclRefExp) { Context->VoidPtrTy, nullptr, /*BitWidth=*/nullptr, /*Mutable=*/true, ICIS_NoInit); - ME = new (Context) MemberExpr(ME, true, FD, SourceLocation(), - DeclRefExp->getType(), VK_LValue, OK_Ordinary); - - - + ME = + new (Context) MemberExpr(ME, true, SourceLocation(), FD, SourceLocation(), + DeclRefExp->getType(), VK_LValue, OK_Ordinary); + // Need parens to enforce precedence. ParenExpr *PE = new (Context) ParenExpr(DeclRefExp->getExprLoc(), DeclRefExp->getExprLoc(), @@ -7694,9 +7685,9 @@ Stmt *RewriteModernObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) { IvarT, nullptr, /*BitWidth=*/nullptr, /*Mutable=*/true, ICIS_NoInit); - MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(), - FD->getType(), VK_LValue, - OK_Ordinary); + MemberExpr *ME = new (Context) + MemberExpr(PE, true, SourceLocation(), FD, SourceLocation(), + FD->getType(), VK_LValue, OK_Ordinary); IvarT = Context->getDecltypeType(ME, ME->getType()); } } @@ -7723,9 +7714,9 @@ Stmt *RewriteModernObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) { D->getType(), nullptr, /*BitWidth=*/D->getBitWidth(), /*Mutable=*/true, ICIS_NoInit); - MemberExpr *ME = new (Context) MemberExpr(PE, /*isArrow*/false, FD, SourceLocation(), - FD->getType(), VK_LValue, - OK_Ordinary); + MemberExpr *ME = new (Context) + MemberExpr(PE, /*isArrow*/ false, SourceLocation(), FD, + SourceLocation(), FD->getType(), VK_LValue, OK_Ordinary); Replacement = ME; } diff --git a/contrib/llvm/tools/clang/lib/Frontend/Rewrite/RewriteObjC.cpp b/contrib/llvm/tools/clang/lib/Frontend/Rewrite/RewriteObjC.cpp index 5196810..b2a45b4 100644 --- a/contrib/llvm/tools/clang/lib/Frontend/Rewrite/RewriteObjC.cpp +++ b/contrib/llvm/tools/clang/lib/Frontend/Rewrite/RewriteObjC.cpp @@ -193,7 +193,7 @@ namespace { DiagnosticsEngine &D, const LangOptions &LOpts, bool silenceMacroWarn); - ~RewriteObjC() {} + ~RewriteObjC() override {} void HandleTranslationUnit(ASTContext &C) override; @@ -511,8 +511,8 @@ namespace { bool silenceMacroWarn) : RewriteObjC(inFile, OS, D, LOpts, silenceMacroWarn) {} - - ~RewriteObjCFragileABI() {} + + ~RewriteObjCFragileABI() override {} void Initialize(ASTContext &context) override; // Rewriting metadata @@ -3821,11 +3821,10 @@ Stmt *RewriteObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) { Context->VoidPtrTy, nullptr, /*BitWidth=*/nullptr, /*Mutable=*/true, ICIS_NoInit); - MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(), - FD->getType(), VK_LValue, - OK_Ordinary); + MemberExpr *ME = + new (Context) MemberExpr(PE, true, SourceLocation(), FD, SourceLocation(), + FD->getType(), VK_LValue, OK_Ordinary); - CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType, CK_BitCast, ME); PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast); @@ -3870,10 +3869,9 @@ Stmt *RewriteObjC::RewriteBlockDeclRefExpr(DeclRefExpr *DeclRefExp) { Context->VoidPtrTy, nullptr, /*BitWidth=*/nullptr, /*Mutable=*/true, ICIS_NoInit); - MemberExpr *ME = new (Context) MemberExpr(DeclRefExp, isArrow, - FD, SourceLocation(), - FD->getType(), VK_LValue, - OK_Ordinary); + MemberExpr *ME = new (Context) + MemberExpr(DeclRefExp, isArrow, SourceLocation(), FD, SourceLocation(), + FD->getType(), VK_LValue, OK_Ordinary); StringRef Name = VD->getName(); FD = FieldDecl::Create(*Context, nullptr, SourceLocation(), SourceLocation(), @@ -3881,11 +3879,10 @@ Stmt *RewriteObjC::RewriteBlockDeclRefExpr(DeclRefExpr *DeclRefExp) { Context->VoidPtrTy, nullptr, /*BitWidth=*/nullptr, /*Mutable=*/true, ICIS_NoInit); - ME = new (Context) MemberExpr(ME, true, FD, SourceLocation(), - DeclRefExp->getType(), VK_LValue, OK_Ordinary); - - - + ME = + new (Context) MemberExpr(ME, true, SourceLocation(), FD, SourceLocation(), + DeclRefExp->getType(), VK_LValue, OK_Ordinary); + // Need parens to enforce precedence. ParenExpr *PE = new (Context) ParenExpr(DeclRefExp->getExprLoc(), DeclRefExp->getExprLoc(), @@ -5880,10 +5877,9 @@ Stmt *RewriteObjCFragileABI::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) { castExpr); if (IV->isFreeIvar() && declaresSameEntity(CurMethodDef->getClassInterface(), iFaceDecl->getDecl())) { - MemberExpr *ME = new (Context) MemberExpr(PE, true, D, - IV->getLocation(), - D->getType(), - VK_LValue, OK_Ordinary); + MemberExpr *ME = new (Context) + MemberExpr(PE, true, SourceLocation(), D, IV->getLocation(), + D->getType(), VK_LValue, OK_Ordinary); Replacement = ME; } else { IV->setBase(PE); diff --git a/contrib/llvm/tools/clang/lib/Frontend/SerializedDiagnosticPrinter.cpp b/contrib/llvm/tools/clang/lib/Frontend/SerializedDiagnosticPrinter.cpp index f701f72..d31b12e 100644 --- a/contrib/llvm/tools/clang/lib/Frontend/SerializedDiagnosticPrinter.cpp +++ b/contrib/llvm/tools/clang/lib/Frontend/SerializedDiagnosticPrinter.cpp @@ -20,6 +20,7 @@ #include "clang/Frontend/TextDiagnosticPrinter.h" #include "clang/Lex/Lexer.h" #include "llvm/ADT/DenseSet.h" +#include "llvm/ADT/STLExtras.h" #include "llvm/ADT/SmallString.h" #include "llvm/ADT/StringRef.h" #include "llvm/Support/raw_ostream.h" @@ -60,8 +61,8 @@ public: DiagnosticOptions *DiagOpts) : DiagnosticNoteRenderer(LangOpts, DiagOpts), Writer(Writer) {} - virtual ~SDiagsRenderer() {} - + ~SDiagsRenderer() override {} + protected: void emitDiagnosticMessage(SourceLocation Loc, PresumedLoc PLoc, @@ -157,7 +158,7 @@ public: EmitPreamble(); } - ~SDiagsWriter() {} + ~SDiagsWriter() override {} void HandleDiagnostic(DiagnosticsEngine::Level DiagLevel, const Diagnostic &Info) override; @@ -631,7 +632,7 @@ void SDiagsWriter::HandleDiagnostic(DiagnosticsEngine::Level DiagLevel, "Unexpected diagnostic with valid location outside of a source file"); SDiagsRenderer Renderer(*this, *LangOpts, &*State->DiagOpts); Renderer.emitDiagnostic(Info.getLocation(), DiagLevel, - State->diagBuf.str(), + State->diagBuf, Info.getRanges(), Info.getFixItHints(), &Info.getSourceManager(), diff --git a/contrib/llvm/tools/clang/lib/Frontend/TextDiagnostic.cpp b/contrib/llvm/tools/clang/lib/Frontend/TextDiagnostic.cpp index bbc9914..aaf17a9 100644 --- a/contrib/llvm/tools/clang/lib/Frontend/TextDiagnostic.cpp +++ b/contrib/llvm/tools/clang/lib/Frontend/TextDiagnostic.cpp @@ -799,18 +799,18 @@ void TextDiagnostic::emitDiagnosticLoc(SourceLocation Loc, PresumedLoc PLoc, OS << PLoc.getFilename(); switch (DiagOpts->getFormat()) { case DiagnosticOptions::Clang: OS << ':' << LineNo; break; - case DiagnosticOptions::Msvc: OS << '(' << LineNo; break; + case DiagnosticOptions::MSVC: OS << '(' << LineNo; break; case DiagnosticOptions::Vi: OS << " +" << LineNo; break; } if (DiagOpts->ShowColumn) // Compute the column number. if (unsigned ColNo = PLoc.getColumn()) { - if (DiagOpts->getFormat() == DiagnosticOptions::Msvc) { + if (DiagOpts->getFormat() == DiagnosticOptions::MSVC) { OS << ','; // Visual Studio 2010 or earlier expects column number to be off by one if (LangOpts.MSCompatibilityVersion && - LangOpts.MSCompatibilityVersion < 170000000) + !LangOpts.isCompatibleWithMSVC(LangOptions::MSVC2012)) ColNo--; } else OS << ':'; @@ -819,7 +819,7 @@ void TextDiagnostic::emitDiagnosticLoc(SourceLocation Loc, PresumedLoc PLoc, switch (DiagOpts->getFormat()) { case DiagnosticOptions::Clang: case DiagnosticOptions::Vi: OS << ':'; break; - case DiagnosticOptions::Msvc: OS << ") : "; break; + case DiagnosticOptions::MSVC: OS << ") : "; break; } if (DiagOpts->ShowSourceRanges && !Ranges.empty()) { diff --git a/contrib/llvm/tools/clang/lib/Frontend/VerifyDiagnosticConsumer.cpp b/contrib/llvm/tools/clang/lib/Frontend/VerifyDiagnosticConsumer.cpp index 3ff6b18..910e394 100644 --- a/contrib/llvm/tools/clang/lib/Frontend/VerifyDiagnosticConsumer.cpp +++ b/contrib/llvm/tools/clang/lib/Frontend/VerifyDiagnosticConsumer.cpp @@ -58,9 +58,9 @@ public: /// \brief Hook into the preprocessor and update the list of parsed /// files when the preprocessor indicates a new file is entered. - virtual void FileChanged(SourceLocation Loc, FileChangeReason Reason, - SrcMgr::CharacteristicKind FileType, - FileID PrevFID) { + void FileChanged(SourceLocation Loc, FileChangeReason Reason, + SrcMgr::CharacteristicKind FileType, + FileID PrevFID) override { Verify.UpdateParsedFileStatus(SM, SM.getFileID(Loc), VerifyDiagnosticConsumer::IsParsed); } |