diff options
Diffstat (limited to 'lib/Frontend')
24 files changed, 893 insertions, 1767 deletions
diff --git a/lib/Frontend/ASTConsumers.cpp b/lib/Frontend/ASTConsumers.cpp index 2a8bfef68eb9..28834a2de8a2 100644 --- a/lib/Frontend/ASTConsumers.cpp +++ b/lib/Frontend/ASTConsumers.cpp @@ -193,365 +193,3 @@ void ASTViewer::HandleTopLevelSingleDecl(Decl *D) { std::unique_ptr<ASTConsumer> clang::CreateASTViewer() { return llvm::make_unique<ASTViewer>(); } - -//===----------------------------------------------------------------------===// -/// DeclContextPrinter - Decl and DeclContext Visualization - -namespace { - -class DeclContextPrinter : public ASTConsumer { - raw_ostream& Out; -public: - DeclContextPrinter() : Out(llvm::errs()) {} - - void HandleTranslationUnit(ASTContext &C) override { - PrintDeclContext(C.getTranslationUnitDecl(), 4); - } - - void PrintDeclContext(const DeclContext* DC, unsigned Indentation); -}; -} // end anonymous namespace - -void DeclContextPrinter::PrintDeclContext(const DeclContext* DC, - unsigned Indentation) { - // Print DeclContext name. - switch (DC->getDeclKind()) { - case Decl::TranslationUnit: - Out << "[translation unit] " << DC; - break; - case Decl::Namespace: { - Out << "[namespace] "; - const NamespaceDecl* ND = cast<NamespaceDecl>(DC); - Out << *ND; - break; - } - case Decl::Enum: { - const EnumDecl* ED = cast<EnumDecl>(DC); - if (ED->isCompleteDefinition()) - Out << "[enum] "; - else - Out << "<enum> "; - Out << *ED; - break; - } - case Decl::Record: { - const RecordDecl* RD = cast<RecordDecl>(DC); - if (RD->isCompleteDefinition()) - Out << "[struct] "; - else - Out << "<struct> "; - Out << *RD; - break; - } - case Decl::CXXRecord: { - const CXXRecordDecl* RD = cast<CXXRecordDecl>(DC); - if (RD->isCompleteDefinition()) - Out << "[class] "; - else - Out << "<class> "; - Out << *RD << ' ' << DC; - break; - } - case Decl::ObjCMethod: - Out << "[objc method]"; - break; - case Decl::ObjCInterface: - Out << "[objc interface]"; - break; - case Decl::ObjCCategory: - Out << "[objc category]"; - break; - case Decl::ObjCProtocol: - Out << "[objc protocol]"; - break; - case Decl::ObjCImplementation: - Out << "[objc implementation]"; - break; - case Decl::ObjCCategoryImpl: - Out << "[objc categoryimpl]"; - break; - case Decl::LinkageSpec: - Out << "[linkage spec]"; - break; - case Decl::Block: - Out << "[block]"; - break; - case Decl::Function: { - const FunctionDecl* FD = cast<FunctionDecl>(DC); - if (FD->doesThisDeclarationHaveABody()) - Out << "[function] "; - else - Out << "<function> "; - Out << *FD; - // Print the parameters. - Out << "("; - bool PrintComma = false; - for (auto I : FD->parameters()) { - if (PrintComma) - Out << ", "; - else - PrintComma = true; - Out << *I; - } - Out << ")"; - break; - } - case Decl::CXXMethod: { - const CXXMethodDecl* D = cast<CXXMethodDecl>(DC); - if (D->isOutOfLine()) - Out << "[c++ method] "; - else if (D->isImplicit()) - Out << "(c++ method) "; - else - Out << "<c++ method> "; - Out << *D; - // Print the parameters. - Out << "("; - bool PrintComma = false; - for (ParmVarDecl *Parameter : D->parameters()) { - if (PrintComma) - Out << ", "; - else - PrintComma = true; - Out << *Parameter; - } - Out << ")"; - - // Check the semantic DeclContext. - const DeclContext* SemaDC = D->getDeclContext(); - const DeclContext* LexicalDC = D->getLexicalDeclContext(); - if (SemaDC != LexicalDC) - Out << " [[" << SemaDC << "]]"; - - break; - } - case Decl::CXXConstructor: { - const CXXConstructorDecl* D = cast<CXXConstructorDecl>(DC); - if (D->isOutOfLine()) - Out << "[c++ ctor] "; - else if (D->isImplicit()) - Out << "(c++ ctor) "; - else - Out << "<c++ ctor> "; - Out << *D; - // Print the parameters. - Out << "("; - bool PrintComma = false; - for (ParmVarDecl *Parameter : D->parameters()) { - if (PrintComma) - Out << ", "; - else - PrintComma = true; - Out << *Parameter; - } - Out << ")"; - - // Check the semantic DC. - const DeclContext* SemaDC = D->getDeclContext(); - const DeclContext* LexicalDC = D->getLexicalDeclContext(); - if (SemaDC != LexicalDC) - Out << " [[" << SemaDC << "]]"; - break; - } - case Decl::CXXDestructor: { - const CXXDestructorDecl* D = cast<CXXDestructorDecl>(DC); - if (D->isOutOfLine()) - Out << "[c++ dtor] "; - else if (D->isImplicit()) - Out << "(c++ dtor) "; - else - Out << "<c++ dtor> "; - Out << *D; - // Check the semantic DC. - const DeclContext* SemaDC = D->getDeclContext(); - const DeclContext* LexicalDC = D->getLexicalDeclContext(); - if (SemaDC != LexicalDC) - Out << " [[" << SemaDC << "]]"; - break; - } - case Decl::CXXConversion: { - const CXXConversionDecl* D = cast<CXXConversionDecl>(DC); - if (D->isOutOfLine()) - Out << "[c++ conversion] "; - else if (D->isImplicit()) - Out << "(c++ conversion) "; - else - Out << "<c++ conversion> "; - Out << *D; - // Check the semantic DC. - const DeclContext* SemaDC = D->getDeclContext(); - const DeclContext* LexicalDC = D->getLexicalDeclContext(); - if (SemaDC != LexicalDC) - Out << " [[" << SemaDC << "]]"; - break; - } - - case Decl::ClassTemplateSpecialization: { - const auto *CTSD = cast<ClassTemplateSpecializationDecl>(DC); - if (CTSD->isCompleteDefinition()) - Out << "[class template specialization] "; - else - Out << "<class template specialization> "; - Out << *CTSD; - break; - } - - case Decl::ClassTemplatePartialSpecialization: { - const auto *CTPSD = cast<ClassTemplatePartialSpecializationDecl>(DC); - if (CTPSD->isCompleteDefinition()) - Out << "[class template partial specialization] "; - else - Out << "<class template partial specialization> "; - Out << *CTPSD; - break; - } - - default: - llvm_unreachable("a decl that inherits DeclContext isn't handled"); - } - - Out << "\n"; - - // Print decls in the DeclContext. - for (auto *I : DC->decls()) { - for (unsigned i = 0; i < Indentation; ++i) - Out << " "; - - Decl::Kind DK = I->getKind(); - switch (DK) { - case Decl::Namespace: - case Decl::Enum: - case Decl::Record: - case Decl::CXXRecord: - case Decl::ObjCMethod: - case Decl::ObjCInterface: - case Decl::ObjCCategory: - case Decl::ObjCProtocol: - case Decl::ObjCImplementation: - case Decl::ObjCCategoryImpl: - case Decl::LinkageSpec: - case Decl::Block: - case Decl::Function: - case Decl::CXXMethod: - case Decl::CXXConstructor: - case Decl::CXXDestructor: - case Decl::CXXConversion: - case Decl::ClassTemplateSpecialization: - case Decl::ClassTemplatePartialSpecialization: { - DeclContext* DC = cast<DeclContext>(I); - PrintDeclContext(DC, Indentation+2); - break; - } - case Decl::IndirectField: { - IndirectFieldDecl* IFD = cast<IndirectFieldDecl>(I); - Out << "<IndirectField> " << *IFD << '\n'; - break; - } - case Decl::Label: { - LabelDecl *LD = cast<LabelDecl>(I); - Out << "<Label> " << *LD << '\n'; - break; - } - case Decl::Field: { - FieldDecl *FD = cast<FieldDecl>(I); - Out << "<field> " << *FD << '\n'; - break; - } - case Decl::Typedef: - case Decl::TypeAlias: { - TypedefNameDecl* TD = cast<TypedefNameDecl>(I); - Out << "<typedef> " << *TD << '\n'; - break; - } - case Decl::EnumConstant: { - EnumConstantDecl* ECD = cast<EnumConstantDecl>(I); - Out << "<enum constant> " << *ECD << '\n'; - break; - } - case Decl::Var: { - VarDecl* VD = cast<VarDecl>(I); - Out << "<var> " << *VD << '\n'; - break; - } - case Decl::ImplicitParam: { - ImplicitParamDecl* IPD = cast<ImplicitParamDecl>(I); - Out << "<implicit parameter> " << *IPD << '\n'; - break; - } - case Decl::ParmVar: { - ParmVarDecl* PVD = cast<ParmVarDecl>(I); - Out << "<parameter> " << *PVD << '\n'; - break; - } - case Decl::ObjCProperty: { - ObjCPropertyDecl* OPD = cast<ObjCPropertyDecl>(I); - Out << "<objc property> " << *OPD << '\n'; - break; - } - case Decl::FunctionTemplate: { - FunctionTemplateDecl* FTD = cast<FunctionTemplateDecl>(I); - Out << "<function template> " << *FTD << '\n'; - break; - } - case Decl::FileScopeAsm: { - Out << "<file-scope asm>\n"; - break; - } - case Decl::UsingDirective: { - Out << "<using directive>\n"; - break; - } - case Decl::NamespaceAlias: { - NamespaceAliasDecl* NAD = cast<NamespaceAliasDecl>(I); - Out << "<namespace alias> " << *NAD << '\n'; - break; - } - case Decl::ClassTemplate: { - ClassTemplateDecl *CTD = cast<ClassTemplateDecl>(I); - Out << "<class template> " << *CTD << '\n'; - break; - } - case Decl::OMPThreadPrivate: { - Out << "<omp threadprivate> " << '"' << I << "\"\n"; - break; - } - case Decl::Friend: { - Out << "<friend>"; - if (const NamedDecl *ND = cast<FriendDecl>(I)->getFriendDecl()) - Out << ' ' << *ND; - Out << "\n"; - break; - } - case Decl::Using: { - Out << "<using> " << *cast<UsingDecl>(I) << "\n"; - break; - } - case Decl::UsingShadow: { - Out << "<using shadow> " << *cast<UsingShadowDecl>(I) << "\n"; - break; - } - case Decl::Empty: { - Out << "<empty>\n"; - break; - } - case Decl::AccessSpec: { - Out << "<access specifier>\n"; - break; - } - case Decl::VarTemplate: { - Out << "<var template> " << *cast<VarTemplateDecl>(I) << "\n"; - break; - } - case Decl::StaticAssert: { - Out << "<static assert>\n"; - break; - } - default: - Out << "DeclKind: " << DK << '"' << I << "\"\n"; - llvm_unreachable("decl unhandled"); - } - } -} -std::unique_ptr<ASTConsumer> clang::CreateDeclContextPrinter() { - return llvm::make_unique<DeclContextPrinter>(); -} diff --git a/lib/Frontend/ASTMerge.cpp b/lib/Frontend/ASTMerge.cpp index 2434113ab0db..4f622da118c5 100644 --- a/lib/Frontend/ASTMerge.cpp +++ b/lib/Frontend/ASTMerge.cpp @@ -10,6 +10,7 @@ #include "clang/AST/ASTContext.h" #include "clang/AST/ASTDiagnostic.h" #include "clang/AST/ASTImporter.h" +#include "clang/AST/ASTImporterLookupTable.h" #include "clang/Basic/Diagnostic.h" #include "clang/Frontend/CompilerInstance.h" #include "clang/Frontend/FrontendActions.h" @@ -38,6 +39,8 @@ void ASTMergeAction::ExecuteAction() { &CI.getASTContext()); IntrusiveRefCntPtr<DiagnosticIDs> DiagIDs(CI.getDiagnostics().getDiagnosticIDs()); + ASTImporterLookupTable LookupTable( + *CI.getASTContext().getTranslationUnitDecl()); for (unsigned I = 0, N = ASTFiles.size(); I != N; ++I) { IntrusiveRefCntPtr<DiagnosticsEngine> Diags(new DiagnosticsEngine(DiagIDs, &CI.getDiagnosticOpts(), @@ -51,11 +54,9 @@ void ASTMergeAction::ExecuteAction() { if (!Unit) continue; - ASTImporter Importer(CI.getASTContext(), - CI.getFileManager(), - Unit->getASTContext(), - Unit->getFileManager(), - /*MinimalImport=*/false); + ASTImporter Importer(CI.getASTContext(), CI.getFileManager(), + Unit->getASTContext(), Unit->getFileManager(), + /*MinimalImport=*/false, &LookupTable); TranslationUnitDecl *TU = Unit->getASTContext().getTranslationUnitDecl(); for (auto *D : TU->decls()) { diff --git a/lib/Frontend/ASTUnit.cpp b/lib/Frontend/ASTUnit.cpp index e4c313fed30f..c7b2551cb8d7 100644 --- a/lib/Frontend/ASTUnit.cpp +++ b/lib/Frontend/ASTUnit.cpp @@ -37,7 +37,6 @@ #include "clang/Basic/SourceManager.h" #include "clang/Basic/TargetInfo.h" #include "clang/Basic/TargetOptions.h" -#include "clang/Basic/VirtualFileSystem.h" #include "clang/Frontend/CompilerInstance.h" #include "clang/Frontend/CompilerInvocation.h" #include "clang/Frontend/FrontendAction.h" @@ -45,7 +44,6 @@ #include "clang/Frontend/FrontendDiagnostic.h" #include "clang/Frontend/FrontendOptions.h" #include "clang/Frontend/MultiplexConsumer.h" -#include "clang/Frontend/PCHContainerOperations.h" #include "clang/Frontend/PrecompiledPreamble.h" #include "clang/Frontend/Utils.h" #include "clang/Lex/HeaderSearch.h" @@ -64,6 +62,7 @@ #include "clang/Serialization/ASTWriter.h" #include "clang/Serialization/ContinuousRangeMap.h" #include "clang/Serialization/Module.h" +#include "clang/Serialization/PCHContainerOperations.h" #include "llvm/ADT/ArrayRef.h" #include "llvm/ADT/DenseMap.h" #include "llvm/ADT/IntrusiveRefCntPtr.h" @@ -88,6 +87,7 @@ #include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/Mutex.h" #include "llvm/Support/Timer.h" +#include "llvm/Support/VirtualFileSystem.h" #include "llvm/Support/raw_ostream.h" #include <algorithm> #include <atomic> @@ -155,9 +155,8 @@ static bool moveOnNoError(llvm::ErrorOr<T> Val, T &Output) { /// and file-to-buffer remappings inside \p Invocation. static std::unique_ptr<llvm::MemoryBuffer> getBufferForFileHandlingRemapping(const CompilerInvocation &Invocation, - vfs::FileSystem *VFS, - StringRef FilePath, - bool isVolatile) { + llvm::vfs::FileSystem *VFS, + StringRef FilePath, bool isVolatile) { const auto &PreprocessorOpts = Invocation.getPreprocessorOpts(); // Try to determine if the main file has been remapped, either from the @@ -283,7 +282,7 @@ void ASTUnit::enableSourceFileDiagnostics() { /// Determine the set of code-completion contexts in which this /// declaration should be shown. -static unsigned getDeclShowContexts(const NamedDecl *ND, +static uint64_t getDeclShowContexts(const NamedDecl *ND, const LangOptions &LangOpts, bool &IsNestedNameSpecifier) { IsNestedNameSpecifier = false; @@ -437,14 +436,15 @@ void ASTUnit::CacheCodeCompletionResults() { | (1LL << CodeCompletionContext::CCC_UnionTag) | (1LL << CodeCompletionContext::CCC_ClassOrStructTag) | (1LL << CodeCompletionContext::CCC_Type) - | (1LL << CodeCompletionContext::CCC_PotentiallyQualifiedName) + | (1LL << CodeCompletionContext::CCC_Symbol) + | (1LL << CodeCompletionContext::CCC_SymbolOrNewName) | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression); if (isa<NamespaceDecl>(R.Declaration) || isa<NamespaceAliasDecl>(R.Declaration)) NNSContexts |= (1LL << CodeCompletionContext::CCC_Namespace); - if (unsigned RemainingContexts + if (uint64_t RemainingContexts = NNSContexts & ~CachedResult.ShowInContexts) { // If there any contexts where this completion can be a // nested-name-specifier but isn't already an option, create a @@ -752,7 +752,8 @@ std::unique_ptr<ASTUnit> ASTUnit::LoadFromASTFile( AST->OnlyLocalDecls = OnlyLocalDecls; AST->CaptureDiagnostics = CaptureDiagnostics; AST->Diagnostics = Diags; - IntrusiveRefCntPtr<vfs::FileSystem> VFS = vfs::getRealFileSystem(); + IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS = + llvm::vfs::getRealFileSystem(); AST->FileMgr = new FileManager(FileSystemOpts, VFS); AST->UserFilesAreVolatile = UserFilesAreVolatile; AST->SourceMgr = new SourceManager(AST->getDiagnostics(), @@ -1074,7 +1075,7 @@ static void checkAndSanitizeDiags(SmallVectorImpl<StoredDiagnostic> & /// contain any translation-unit information, false otherwise. bool ASTUnit::Parse(std::shared_ptr<PCHContainerOperations> PCHContainerOps, std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer, - IntrusiveRefCntPtr<vfs::FileSystem> VFS) { + IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS) { if (!Invocation) return true; @@ -1082,7 +1083,7 @@ bool ASTUnit::Parse(std::shared_ptr<PCHContainerOperations> PCHContainerOps, if (OverrideMainBuffer) { assert(Preamble && "No preamble was built, but OverrideMainBuffer is not null"); - IntrusiveRefCntPtr<vfs::FileSystem> OldVFS = VFS; + IntrusiveRefCntPtr<llvm::vfs::FileSystem> OldVFS = VFS; Preamble->AddImplicitPreamble(*CCInvocation, VFS, OverrideMainBuffer.get()); if (OldVFS != VFS && FileMgr) { assert(OldVFS == FileMgr->getVirtualFileSystem() && @@ -1279,7 +1280,7 @@ std::unique_ptr<llvm::MemoryBuffer> ASTUnit::getMainBufferWithPrecompiledPreamble( std::shared_ptr<PCHContainerOperations> PCHContainerOps, CompilerInvocation &PreambleInvocationIn, - IntrusiveRefCntPtr<vfs::FileSystem> VFS, bool AllowRebuild, + IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS, bool AllowRebuild, unsigned MaxLines) { auto MainFilePath = PreambleInvocationIn.getFrontendOpts().Inputs[0].getFile(); @@ -1363,7 +1364,6 @@ ASTUnit::getMainBufferWithPrecompiledPreamble( } else { switch (static_cast<BuildPreambleError>(NewPreamble.getError().value())) { case BuildPreambleError::CouldntCreateTempFile: - case BuildPreambleError::PreambleIsEmpty: // Try again next time. PreambleRebuildCounter = 1; return nullptr; @@ -1469,7 +1469,7 @@ ASTUnit::create(std::shared_ptr<CompilerInvocation> CI, bool CaptureDiagnostics, bool UserFilesAreVolatile) { std::unique_ptr<ASTUnit> AST(new ASTUnit(false)); ConfigureDiags(Diags, *AST, CaptureDiagnostics); - IntrusiveRefCntPtr<vfs::FileSystem> VFS = + IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS = createVFSFromCompilerInvocation(*CI, *Diags); AST->Diagnostics = Diags; AST->FileSystemOpts = CI->getFileSystemOpts(); @@ -1631,7 +1631,7 @@ ASTUnit *ASTUnit::LoadFromCompilerInvocationAction( bool ASTUnit::LoadFromCompilerInvocation( std::shared_ptr<PCHContainerOperations> PCHContainerOps, unsigned PrecompilePreambleAfterNParses, - IntrusiveRefCntPtr<vfs::FileSystem> VFS) { + IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS) { if (!Invocation) return true; @@ -1710,7 +1710,7 @@ ASTUnit *ASTUnit::LoadFromCommandLine( bool AllowPCHWithCompilerErrors, SkipFunctionBodiesScope SkipFunctionBodies, bool SingleFileParse, bool UserFilesAreVolatile, bool ForSerialization, llvm::Optional<StringRef> ModuleFormat, std::unique_ptr<ASTUnit> *ErrAST, - IntrusiveRefCntPtr<vfs::FileSystem> VFS) { + IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS) { assert(Diags.get() && "no DiagnosticsEngine was provided"); SmallVector<StoredDiagnostic, 4> StoredDiagnostics; @@ -1755,7 +1755,7 @@ ASTUnit *ASTUnit::LoadFromCommandLine( AST->Diagnostics = Diags; AST->FileSystemOpts = CI->getFileSystemOpts(); if (!VFS) - VFS = vfs::getRealFileSystem(); + VFS = llvm::vfs::getRealFileSystem(); VFS = createVFSFromCompilerInvocation(*CI, *Diags, VFS); AST->FileMgr = new FileManager(AST->FileSystemOpts, VFS); AST->PCMCache = new MemoryBufferCache; @@ -1795,7 +1795,7 @@ ASTUnit *ASTUnit::LoadFromCommandLine( bool ASTUnit::Reparse(std::shared_ptr<PCHContainerOperations> PCHContainerOps, ArrayRef<RemappedFile> RemappedFiles, - IntrusiveRefCntPtr<vfs::FileSystem> VFS) { + IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS) { if (!Invocation) return true; @@ -1912,8 +1912,10 @@ namespace { void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg, OverloadCandidate *Candidates, - unsigned NumCandidates) override { - Next.ProcessOverloadCandidates(S, CurrentArg, Candidates, NumCandidates); + unsigned NumCandidates, + SourceLocation OpenParLoc) override { + Next.ProcessOverloadCandidates(S, CurrentArg, Candidates, NumCandidates, + OpenParLoc); } CodeCompletionAllocator &getAllocator() override { @@ -1950,8 +1952,8 @@ static void CalculateHiddenNames(const CodeCompletionContext &Context, case CodeCompletionContext::CCC_ObjCPropertyAccess: case CodeCompletionContext::CCC_Namespace: case CodeCompletionContext::CCC_Type: - case CodeCompletionContext::CCC_Name: - case CodeCompletionContext::CCC_PotentiallyQualifiedName: + case CodeCompletionContext::CCC_Symbol: + case CodeCompletionContext::CCC_SymbolOrNewName: case CodeCompletionContext::CCC_ParenthesizedExpression: case CodeCompletionContext::CCC_ObjCInterfaceName: break; @@ -1975,6 +1977,8 @@ static void CalculateHiddenNames(const CodeCompletionContext &Context, case CodeCompletionContext::CCC_ObjCInstanceMessage: case CodeCompletionContext::CCC_ObjCClassMessage: case CodeCompletionContext::CCC_ObjCCategoryName: + case CodeCompletionContext::CCC_IncludedFile: + case CodeCompletionContext::CCC_NewName: // We're looking for nothing, or we're looking for names that cannot // be hidden. return; @@ -2644,9 +2648,9 @@ InputKind ASTUnit::getInputKind() const { else if (LangOpts.RenderScript) Lang = InputKind::RenderScript; else if (LangOpts.CPlusPlus) - Lang = LangOpts.ObjC1 ? InputKind::ObjCXX : InputKind::CXX; + Lang = LangOpts.ObjC ? InputKind::ObjCXX : InputKind::CXX; else - Lang = LangOpts.ObjC1 ? InputKind::ObjC : InputKind::C; + Lang = LangOpts.ObjC ? InputKind::ObjC : InputKind::C; InputKind::Format Fmt = InputKind::Source; if (LangOpts.getCompilingModule() == LangOptions::CMK_ModuleMap) diff --git a/lib/Frontend/CMakeLists.txt b/lib/Frontend/CMakeLists.txt index 6161b46a9dc5..3bd159537b6a 100644 --- a/lib/Frontend/CMakeLists.txt +++ b/lib/Frontend/CMakeLists.txt @@ -16,10 +16,8 @@ add_clang_library(clangFrontend ASTConsumers.cpp ASTMerge.cpp ASTUnit.cpp - CacheTokens.cpp ChainedDiagnosticConsumer.cpp ChainedIncludesSource.cpp - CodeGenOptions.cpp CompilerInstance.cpp CompilerInvocation.cpp CreateInvocationFromCommandLine.cpp @@ -38,7 +36,6 @@ add_clang_library(clangFrontend LogDiagnosticPrinter.cpp ModuleDependencyCollector.cpp MultiplexConsumer.cpp - PCHContainerOperations.cpp PrecompiledPreamble.cpp PrintPreprocessedOutput.cpp SerializedDiagnosticPrinter.cpp diff --git a/lib/Frontend/CacheTokens.cpp b/lib/Frontend/CacheTokens.cpp deleted file mode 100644 index c4504a14456d..000000000000 --- a/lib/Frontend/CacheTokens.cpp +++ /dev/null @@ -1,700 +0,0 @@ -//===--- CacheTokens.cpp - Caching of lexer tokens for PTH support --------===// -// -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. -// -//===----------------------------------------------------------------------===// -// -// This provides a possible implementation of PTH support for Clang that is -// based on caching lexed tokens and identifiers. -// -//===----------------------------------------------------------------------===// - -#include "clang/Basic/Diagnostic.h" -#include "clang/Basic/FileManager.h" -#include "clang/Basic/FileSystemStatCache.h" -#include "clang/Basic/IdentifierTable.h" -#include "clang/Basic/SourceManager.h" -#include "clang/Frontend/Utils.h" -#include "clang/Lex/Lexer.h" -#include "clang/Lex/PTHManager.h" -#include "clang/Lex/Preprocessor.h" -#include "llvm/ADT/StringMap.h" -#include "llvm/Support/DJB.h" -#include "llvm/Support/EndianStream.h" -#include "llvm/Support/FileSystem.h" -#include "llvm/Support/MemoryBuffer.h" -#include "llvm/Support/OnDiskHashTable.h" -#include "llvm/Support/Path.h" - -// FIXME: put this somewhere else? -#ifndef S_ISDIR -#define S_ISDIR(x) (((x)&_S_IFDIR)!=0) -#endif - -using namespace clang; - -//===----------------------------------------------------------------------===// -// PTH-specific stuff. -//===----------------------------------------------------------------------===// - -typedef uint32_t Offset; - -namespace { -class PTHEntry { - Offset TokenData, PPCondData; - -public: - PTHEntry() {} - - PTHEntry(Offset td, Offset ppcd) - : TokenData(td), PPCondData(ppcd) {} - - Offset getTokenOffset() const { return TokenData; } - Offset getPPCondTableOffset() const { return PPCondData; } -}; - - -class PTHEntryKeyVariant { - union { - const FileEntry *FE; - // FIXME: Use "StringRef Path;" when MSVC 2013 is dropped. - const char *PathPtr; - }; - size_t PathSize; - enum { IsFE = 0x1, IsDE = 0x2, IsNoExist = 0x0 } Kind; - FileData *Data; - -public: - PTHEntryKeyVariant(const FileEntry *fe) : FE(fe), Kind(IsFE), Data(nullptr) {} - - PTHEntryKeyVariant(FileData *Data, StringRef Path) - : PathPtr(Path.data()), PathSize(Path.size()), Kind(IsDE), - Data(new FileData(*Data)) {} - - explicit PTHEntryKeyVariant(StringRef Path) - : PathPtr(Path.data()), PathSize(Path.size()), Kind(IsNoExist), - Data(nullptr) {} - - bool isFile() const { return Kind == IsFE; } - - StringRef getString() const { - return Kind == IsFE ? FE->getName() : StringRef(PathPtr, PathSize); - } - - unsigned getKind() const { return (unsigned) Kind; } - - void EmitData(raw_ostream& Out) { - using namespace llvm::support; - endian::Writer LE(Out, little); - switch (Kind) { - case IsFE: { - // Emit stat information. - llvm::sys::fs::UniqueID UID = FE->getUniqueID(); - LE.write<uint64_t>(UID.getFile()); - LE.write<uint64_t>(UID.getDevice()); - LE.write<uint64_t>(FE->getModificationTime()); - LE.write<uint64_t>(FE->getSize()); - } break; - case IsDE: - // Emit stat information. - LE.write<uint64_t>(Data->UniqueID.getFile()); - LE.write<uint64_t>(Data->UniqueID.getDevice()); - LE.write<uint64_t>(Data->ModTime); - LE.write<uint64_t>(Data->Size); - delete Data; - break; - default: - break; - } - } - - unsigned getRepresentationLength() const { - return Kind == IsNoExist ? 0 : 4 * 8; - } -}; - -class FileEntryPTHEntryInfo { -public: - typedef PTHEntryKeyVariant key_type; - typedef key_type key_type_ref; - - typedef PTHEntry data_type; - typedef const PTHEntry& data_type_ref; - - typedef unsigned hash_value_type; - typedef unsigned offset_type; - - static hash_value_type ComputeHash(PTHEntryKeyVariant V) { - return llvm::djbHash(V.getString()); - } - - static std::pair<unsigned,unsigned> - EmitKeyDataLength(raw_ostream& Out, PTHEntryKeyVariant V, - const PTHEntry& E) { - using namespace llvm::support; - endian::Writer LE(Out, little); - - unsigned n = V.getString().size() + 1 + 1; - LE.write<uint16_t>(n); - - unsigned m = V.getRepresentationLength() + (V.isFile() ? 4 + 4 : 0); - LE.write<uint8_t>(m); - - return std::make_pair(n, m); - } - - static void EmitKey(raw_ostream& Out, PTHEntryKeyVariant V, unsigned n){ - using namespace llvm::support; - // Emit the entry kind. - Out << char(V.getKind()); - // Emit the string. - Out.write(V.getString().data(), n - 1); - } - - static void EmitData(raw_ostream& Out, PTHEntryKeyVariant V, - const PTHEntry& E, unsigned) { - using namespace llvm::support; - endian::Writer LE(Out, little); - - // For file entries emit the offsets into the PTH file for token data - // and the preprocessor blocks table. - if (V.isFile()) { - LE.write<uint32_t>(E.getTokenOffset()); - LE.write<uint32_t>(E.getPPCondTableOffset()); - } - - // Emit any other data associated with the key (i.e., stat information). - V.EmitData(Out); - } -}; - -class OffsetOpt { - bool valid; - Offset off; -public: - OffsetOpt() : valid(false) {} - bool hasOffset() const { return valid; } - Offset getOffset() const { assert(valid); return off; } - void setOffset(Offset o) { off = o; valid = true; } -}; -} // end anonymous namespace - -typedef llvm::OnDiskChainedHashTableGenerator<FileEntryPTHEntryInfo> PTHMap; - -namespace { -class PTHWriter { - typedef llvm::DenseMap<const IdentifierInfo*,uint32_t> IDMap; - typedef llvm::StringMap<OffsetOpt, llvm::BumpPtrAllocator> CachedStrsTy; - - raw_pwrite_stream &Out; - Preprocessor& PP; - IDMap IM; - std::vector<llvm::StringMapEntry<OffsetOpt>*> StrEntries; - PTHMap PM; - CachedStrsTy CachedStrs; - uint32_t idcount; - Offset CurStrOffset; - - //// Get the persistent id for the given IdentifierInfo*. - uint32_t ResolveID(const IdentifierInfo* II); - - /// Emit a token to the PTH file. - void EmitToken(const Token& T); - - void Emit8(uint32_t V) { - Out << char(V); - } - - void Emit16(uint32_t V) { - using namespace llvm::support; - endian::write<uint16_t>(Out, V, little); - } - - void Emit32(uint32_t V) { - using namespace llvm::support; - endian::write<uint32_t>(Out, V, little); - } - - void EmitBuf(const char *Ptr, unsigned NumBytes) { - Out.write(Ptr, NumBytes); - } - - void EmitString(StringRef V) { - using namespace llvm::support; - endian::write<uint16_t>(Out, V.size(), little); - EmitBuf(V.data(), V.size()); - } - - /// EmitIdentifierTable - Emits two tables to the PTH file. The first is - /// a hashtable mapping from identifier strings to persistent IDs. - /// The second is a straight table mapping from persistent IDs to string data - /// (the keys of the first table). - std::pair<Offset, Offset> EmitIdentifierTable(); - - /// EmitFileTable - Emit a table mapping from file name strings to PTH - /// token data. - Offset EmitFileTable() { return PM.Emit(Out); } - - PTHEntry LexTokens(Lexer& L); - Offset EmitCachedSpellings(); - -public: - PTHWriter(raw_pwrite_stream &out, Preprocessor &pp) - : Out(out), PP(pp), idcount(0), CurStrOffset(0) {} - - PTHMap &getPM() { return PM; } - void GeneratePTH(StringRef MainFile); -}; -} // end anonymous namespace - -uint32_t PTHWriter::ResolveID(const IdentifierInfo* II) { - // Null IdentifierInfo's map to the persistent ID 0. - if (!II) - return 0; - - IDMap::iterator I = IM.find(II); - if (I != IM.end()) - return I->second; // We've already added 1. - - IM[II] = ++idcount; // Pre-increment since '0' is reserved for NULL. - return idcount; -} - -void PTHWriter::EmitToken(const Token& T) { - // Emit the token kind, flags, and length. - Emit32(((uint32_t) T.getKind()) | ((((uint32_t) T.getFlags())) << 8)| - (((uint32_t) T.getLength()) << 16)); - - if (!T.isLiteral()) { - Emit32(ResolveID(T.getIdentifierInfo())); - } else { - // We cache *un-cleaned* spellings. This gives us 100% fidelity with the - // source code. - StringRef s(T.getLiteralData(), T.getLength()); - - // Get the string entry. - auto &E = *CachedStrs.insert(std::make_pair(s, OffsetOpt())).first; - - // If this is a new string entry, bump the PTH offset. - if (!E.second.hasOffset()) { - E.second.setOffset(CurStrOffset); - StrEntries.push_back(&E); - CurStrOffset += s.size() + 1; - } - - // Emit the relative offset into the PTH file for the spelling string. - Emit32(E.second.getOffset()); - } - - // Emit the offset into the original source file of this token so that we - // can reconstruct its SourceLocation. - Emit32(PP.getSourceManager().getFileOffset(T.getLocation())); -} - -PTHEntry PTHWriter::LexTokens(Lexer& L) { - // Pad 0's so that we emit tokens to a 4-byte alignment. - // This speed up reading them back in. - using namespace llvm::support; - endian::Writer LE(Out, little); - uint32_t TokenOff = Out.tell(); - for (uint64_t N = llvm::OffsetToAlignment(TokenOff, 4); N; --N, ++TokenOff) - LE.write<uint8_t>(0); - - // Keep track of matching '#if' ... '#endif'. - typedef std::vector<std::pair<Offset, unsigned> > PPCondTable; - PPCondTable PPCond; - std::vector<unsigned> PPStartCond; - bool ParsingPreprocessorDirective = false; - Token Tok; - - do { - L.LexFromRawLexer(Tok); - NextToken: - - if ((Tok.isAtStartOfLine() || Tok.is(tok::eof)) && - ParsingPreprocessorDirective) { - // Insert an eod token into the token cache. It has the same - // position as the next token that is not on the same line as the - // preprocessor directive. Observe that we continue processing - // 'Tok' when we exit this branch. - Token Tmp = Tok; - Tmp.setKind(tok::eod); - Tmp.clearFlag(Token::StartOfLine); - Tmp.setIdentifierInfo(nullptr); - EmitToken(Tmp); - ParsingPreprocessorDirective = false; - } - - if (Tok.is(tok::raw_identifier)) { - PP.LookUpIdentifierInfo(Tok); - EmitToken(Tok); - continue; - } - - if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) { - // Special processing for #include. Store the '#' token and lex - // the next token. - assert(!ParsingPreprocessorDirective); - Offset HashOff = (Offset) Out.tell(); - - // Get the next token. - Token NextTok; - L.LexFromRawLexer(NextTok); - - // If we see the start of line, then we had a null directive "#". In - // this case, discard both tokens. - if (NextTok.isAtStartOfLine()) - goto NextToken; - - // The token is the start of a directive. Emit it. - EmitToken(Tok); - Tok = NextTok; - - // Did we see 'include'/'import'/'include_next'? - if (Tok.isNot(tok::raw_identifier)) { - EmitToken(Tok); - continue; - } - - IdentifierInfo* II = PP.LookUpIdentifierInfo(Tok); - tok::PPKeywordKind K = II->getPPKeywordID(); - - ParsingPreprocessorDirective = true; - - switch (K) { - case tok::pp_not_keyword: - // Invalid directives "#foo" can occur in #if 0 blocks etc, just pass - // them through. - default: - break; - - case tok::pp_include: - case tok::pp_import: - case tok::pp_include_next: { - // Save the 'include' token. - EmitToken(Tok); - // Lex the next token as an include string. - L.setParsingPreprocessorDirective(true); - L.LexIncludeFilename(Tok); - L.setParsingPreprocessorDirective(false); - assert(!Tok.isAtStartOfLine()); - if (Tok.is(tok::raw_identifier)) - PP.LookUpIdentifierInfo(Tok); - - break; - } - case tok::pp_if: - case tok::pp_ifdef: - case tok::pp_ifndef: { - // Add an entry for '#if' and friends. We initially set the target - // index to 0. This will get backpatched when we hit #endif. - PPStartCond.push_back(PPCond.size()); - PPCond.push_back(std::make_pair(HashOff, 0U)); - break; - } - case tok::pp_endif: { - // Add an entry for '#endif'. We set the target table index to itself. - // This will later be set to zero when emitting to the PTH file. We - // use 0 for uninitialized indices because that is easier to debug. - unsigned index = PPCond.size(); - // Backpatch the opening '#if' entry. - assert(!PPStartCond.empty()); - assert(PPCond.size() > PPStartCond.back()); - assert(PPCond[PPStartCond.back()].second == 0); - PPCond[PPStartCond.back()].second = index; - PPStartCond.pop_back(); - // Add the new entry to PPCond. - PPCond.push_back(std::make_pair(HashOff, index)); - EmitToken(Tok); - - // Some files have gibberish on the same line as '#endif'. - // Discard these tokens. - do - L.LexFromRawLexer(Tok); - while (Tok.isNot(tok::eof) && !Tok.isAtStartOfLine()); - // We have the next token in hand. - // Don't immediately lex the next one. - goto NextToken; - } - case tok::pp_elif: - case tok::pp_else: { - // Add an entry for #elif or #else. - // This serves as both a closing and opening of a conditional block. - // This means that its entry will get backpatched later. - unsigned index = PPCond.size(); - // Backpatch the previous '#if' entry. - assert(!PPStartCond.empty()); - assert(PPCond.size() > PPStartCond.back()); - assert(PPCond[PPStartCond.back()].second == 0); - PPCond[PPStartCond.back()].second = index; - PPStartCond.pop_back(); - // Now add '#elif' as a new block opening. - PPCond.push_back(std::make_pair(HashOff, 0U)); - PPStartCond.push_back(index); - break; - } - } - } - - EmitToken(Tok); - } - while (Tok.isNot(tok::eof)); - - assert(PPStartCond.empty() && "Error: imblanced preprocessor conditionals."); - - // Next write out PPCond. - Offset PPCondOff = (Offset) Out.tell(); - - // Write out the size of PPCond so that clients can identifer empty tables. - Emit32(PPCond.size()); - - for (unsigned i = 0, e = PPCond.size(); i!=e; ++i) { - Emit32(PPCond[i].first - TokenOff); - uint32_t x = PPCond[i].second; - assert(x != 0 && "PPCond entry not backpatched."); - // Emit zero for #endifs. This allows us to do checking when - // we read the PTH file back in. - Emit32(x == i ? 0 : x); - } - - return PTHEntry(TokenOff, PPCondOff); -} - -Offset PTHWriter::EmitCachedSpellings() { - // Write each cached strings to the PTH file. - Offset SpellingsOff = Out.tell(); - - for (std::vector<llvm::StringMapEntry<OffsetOpt>*>::iterator - I = StrEntries.begin(), E = StrEntries.end(); I!=E; ++I) - EmitBuf((*I)->getKeyData(), (*I)->getKeyLength()+1 /*nul included*/); - - 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(StringRef MainFile) { - // Generate the prologue. - Out << "cfe-pth" << '\0'; - Emit32(PTHManager::Version); - - // Leave 4 words for the prologue. - Offset PrologueOffset = Out.tell(); - for (unsigned i = 0; i < 4; ++i) - Emit32(0); - - // Write the name of the MainFile. - if (!MainFile.empty()) { - EmitString(MainFile); - } else { - // String with 0 bytes. - Emit16(0); - } - Emit8(0); - - // Iterate over all the files in SourceManager. Create a lexer - // for each file and cache the tokens. - SourceManager &SM = PP.getSourceManager(); - const LangOptions &LOpts = PP.getLangOpts(); - - for (SourceManager::fileinfo_iterator I = SM.fileinfo_begin(), - E = SM.fileinfo_end(); I != E; ++I) { - const SrcMgr::ContentCache &C = *I->second; - const FileEntry *FE = C.OrigEntry; - - // FIXME: Handle files with non-absolute paths. - if (llvm::sys::path::is_relative(FE->getName())) - continue; - - const llvm::MemoryBuffer *B = C.getBuffer(PP.getDiagnostics(), SM); - if (!B) continue; - - FileID FID = SM.createFileID(FE, SourceLocation(), SrcMgr::C_User); - const llvm::MemoryBuffer *FromFile = SM.getBuffer(FID); - Lexer L(FID, FromFile, SM, LOpts); - PM.insert(FE, LexTokens(L)); - } - - // Write out the identifier table. - const std::pair<Offset,Offset> &IdTableOff = EmitIdentifierTable(); - - // Write out the cached strings table. - Offset SpellingOff = EmitCachedSpellings(); - - // Write out the file table. - Offset FileTableOff = EmitFileTable(); - - // Finally, write the prologue. - uint64_t Off = PrologueOffset; - pwrite32le(Out, IdTableOff.first, Off); - pwrite32le(Out, IdTableOff.second, Off); - pwrite32le(Out, FileTableOff, Off); - pwrite32le(Out, SpellingOff, Off); -} - -namespace { -/// StatListener - A simple "interpose" object used to monitor stat calls -/// invoked by FileManager while processing the original sources used -/// as input to PTH generation. StatListener populates the PTHWriter's -/// file map with stat information for directories as well as negative stats. -/// Stat information for files are populated elsewhere. -class StatListener : public FileSystemStatCache { - PTHMap &PM; -public: - StatListener(PTHMap &pm) : PM(pm) {} - ~StatListener() override {} - - LookupResult getStat(StringRef Path, FileData &Data, bool isFile, - std::unique_ptr<vfs::File> *F, - vfs::FileSystem &FS) override { - LookupResult Result = statChained(Path, Data, isFile, F, FS); - - if (Result == CacheMissing) // Failed 'stat'. - PM.insert(PTHEntryKeyVariant(Path), PTHEntry()); - else if (Data.IsDirectory) { - // Only cache directories with absolute paths. - if (llvm::sys::path::is_relative(Path)) - return Result; - - PM.insert(PTHEntryKeyVariant(&Data, Path), PTHEntry()); - } - - return Result; - } -}; -} // end anonymous namespace - -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()); - SmallString<128> MainFilePath(MainFile->getName()); - - llvm::sys::fs::make_absolute(MainFilePath); - - // Create the PTHWriter. - PTHWriter PW(*OS, PP); - - // Install the 'stat' system call listener in the FileManager. - auto StatCacheOwner = llvm::make_unique<StatListener>(PW.getPM()); - StatListener *StatCache = StatCacheOwner.get(); - PP.getFileManager().addStatCache(std::move(StatCacheOwner), - /*AtBeginning=*/true); - - // Lex through the entire file. This will populate SourceManager with - // all of the header information. - Token Tok; - PP.EnterMainSourceFile(); - do { PP.Lex(Tok); } while (Tok.isNot(tok::eof)); - - // Generate the PTH file. - PP.getFileManager().removeStatCache(StatCache); - PW.GeneratePTH(MainFilePath.str()); -} - -//===----------------------------------------------------------------------===// - -namespace { -class PTHIdKey { -public: - const IdentifierInfo* II; - uint32_t FileOffset; -}; - -class PTHIdentifierTableTrait { -public: - typedef PTHIdKey* key_type; - typedef key_type key_type_ref; - - typedef uint32_t data_type; - typedef data_type data_type_ref; - - typedef unsigned hash_value_type; - typedef unsigned offset_type; - - static hash_value_type ComputeHash(PTHIdKey* key) { - return llvm::djbHash(key->II->getName()); - } - - static std::pair<unsigned,unsigned> - EmitKeyDataLength(raw_ostream& Out, const PTHIdKey* key, uint32_t) { - using namespace llvm::support; - unsigned n = key->II->getLength() + 1; - endian::write<uint16_t>(Out, n, little); - return std::make_pair(n, sizeof(uint32_t)); - } - - static void EmitKey(raw_ostream& Out, PTHIdKey* key, unsigned n) { - // Record the location of the key data. This is used when generating - // the mapping from persistent IDs to strings. - key->FileOffset = Out.tell(); - Out.write(key->II->getNameStart(), n); - } - - static void EmitData(raw_ostream& Out, PTHIdKey*, uint32_t pID, - unsigned) { - using namespace llvm::support; - endian::write<uint32_t>(Out, pID, little); - } -}; -} // end anonymous namespace - -/// EmitIdentifierTable - Emits two tables to the PTH file. The first is -/// a hashtable mapping from identifier strings to persistent IDs. The second -/// is a straight table mapping from persistent IDs to string data (the -/// keys of the first table). -/// -std::pair<Offset,Offset> PTHWriter::EmitIdentifierTable() { - // Build two maps: - // (1) an inverse map from persistent IDs -> (IdentifierInfo*,Offset) - // (2) a map from (IdentifierInfo*, Offset)* -> persistent IDs - - // Note that we use 'calloc', so all the bytes are 0. - PTHIdKey *IIDMap = static_cast<PTHIdKey*>( - llvm::safe_calloc(idcount, sizeof(PTHIdKey))); - - // Create the hashtable. - llvm::OnDiskChainedHashTableGenerator<PTHIdentifierTableTrait> IIOffMap; - - // Generate mapping from persistent IDs -> IdentifierInfo*. - for (IDMap::iterator I = IM.begin(), E = IM.end(); I != E; ++I) { - // Decrement by 1 because we are using a vector for the lookup and - // 0 is reserved for NULL. - assert(I->second > 0); - assert(I->second-1 < idcount); - unsigned idx = I->second-1; - - // Store the mapping from persistent ID to IdentifierInfo* - IIDMap[idx].II = I->first; - - // Store the reverse mapping in a hashtable. - IIOffMap.insert(&IIDMap[idx], I->second); - } - - // Write out the inverse map first. This causes the PCIDKey entries to - // record PTH file offsets for the string data. This is used to write - // the second table. - Offset StringTableOffset = IIOffMap.Emit(Out); - - // Now emit the table mapping from persistent IDs to PTH file offsets. - Offset IDOff = Out.tell(); - Emit32(idcount); // Emit the number of identifiers. - for (unsigned i = 0 ; i < idcount; ++i) - Emit32(IIDMap[i].FileOffset); - - // Finally, release the inverse map. - free(IIDMap); - - return std::make_pair(IDOff, StringTableOffset); -} diff --git a/lib/Frontend/ChainedIncludesSource.cpp b/lib/Frontend/ChainedIncludesSource.cpp index 4e8eb32121dc..1bfc25c4c778 100644 --- a/lib/Frontend/ChainedIncludesSource.cpp +++ b/lib/Frontend/ChainedIncludesSource.cpp @@ -129,7 +129,6 @@ IntrusiveRefCntPtr<ExternalSemaSource> clang::createChainedIncludesSource( CInvok->getPreprocessorOpts().ChainedIncludes.clear(); CInvok->getPreprocessorOpts().ImplicitPCHInclude.clear(); - CInvok->getPreprocessorOpts().ImplicitPTHInclude.clear(); CInvok->getPreprocessorOpts().DisablePCHValidation = true; CInvok->getPreprocessorOpts().Includes.clear(); CInvok->getPreprocessorOpts().MacroIncludes.clear(); diff --git a/lib/Frontend/CodeGenOptions.cpp b/lib/Frontend/CodeGenOptions.cpp deleted file mode 100644 index 84a39f2d570d..000000000000 --- a/lib/Frontend/CodeGenOptions.cpp +++ /dev/null @@ -1,32 +0,0 @@ -//===--- CodeGenOptions.cpp -----------------------------------------------===// -// -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. -// -//===----------------------------------------------------------------------===// - -#include "clang/Frontend/CodeGenOptions.h" -#include <string.h> - -namespace clang { - -CodeGenOptions::CodeGenOptions() { -#define CODEGENOPT(Name, Bits, Default) Name = Default; -#define ENUM_CODEGENOPT(Name, Type, Bits, Default) set##Name(Default); -#include "clang/Frontend/CodeGenOptions.def" - - RelocationModel = llvm::Reloc::PIC_; - memcpy(CoverageVersion, "402*", 4); -} - -bool CodeGenOptions::isNoBuiltinFunc(const char *Name) const { - StringRef FuncName(Name); - for (unsigned i = 0, e = NoBuiltinFuncs.size(); i != e; ++i) - if (FuncName.equals(NoBuiltinFuncs[i])) - return true; - return false; -} - -} // end namespace clang diff --git a/lib/Frontend/CompilerInstance.cpp b/lib/Frontend/CompilerInstance.cpp index ecb09da3c1ef..f66674535423 100644 --- a/lib/Frontend/CompilerInstance.cpp +++ b/lib/Frontend/CompilerInstance.cpp @@ -30,7 +30,6 @@ #include "clang/Frontend/Utils.h" #include "clang/Frontend/VerifyDiagnosticConsumer.h" #include "clang/Lex/HeaderSearch.h" -#include "clang/Lex/PTHManager.h" #include "clang/Lex/Preprocessor.h" #include "clang/Lex/PreprocessorOptions.h" #include "clang/Sema/CodeCompleteConsumer.h" @@ -38,6 +37,7 @@ #include "clang/Serialization/ASTReader.h" #include "clang/Serialization/GlobalModuleIndex.h" #include "llvm/ADT/Statistic.h" +#include "llvm/Support/BuryPointer.h" #include "llvm/Support/CrashRecoveryContext.h" #include "llvm/Support/Errc.h" #include "llvm/Support/FileSystem.h" @@ -177,18 +177,18 @@ static void collectIncludePCH(CompilerInstance &CI, std::error_code EC; SmallString<128> DirNative; llvm::sys::path::native(PCHDir->getName(), DirNative); - vfs::FileSystem &FS = *FileMgr.getVirtualFileSystem(); + llvm::vfs::FileSystem &FS = *FileMgr.getVirtualFileSystem(); SimpleASTReaderListener Validator(CI.getPreprocessor()); - for (vfs::directory_iterator Dir = FS.dir_begin(DirNative, EC), DirEnd; + for (llvm::vfs::directory_iterator Dir = FS.dir_begin(DirNative, EC), DirEnd; Dir != DirEnd && !EC; Dir.increment(EC)) { // Check whether this is an AST file. ASTReader::isAcceptableASTFile is not // used here since we're not interested in validating the PCH at this time, // but only to check whether this is a file containing an AST. if (!ASTReader::readASTFileControlBlock( - Dir->getName(), FileMgr, CI.getPCHContainerReader(), + Dir->path(), FileMgr, CI.getPCHContainerReader(), /*FindModuleFileExtensions=*/false, Validator, /*ValidateDiagnosticOptions=*/false)) - MDC->addFile(Dir->getName()); + MDC->addFile(Dir->path()); } } @@ -198,14 +198,14 @@ static void collectVFSEntries(CompilerInstance &CI, return; // Collect all VFS found. - SmallVector<vfs::YAMLVFSEntry, 16> VFSEntries; + SmallVector<llvm::vfs::YAMLVFSEntry, 16> VFSEntries; for (const std::string &VFSFile : CI.getHeaderSearchOpts().VFSOverlayFiles) { llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> Buffer = llvm::MemoryBuffer::getFile(VFSFile); if (!Buffer) return; - vfs::collectVFSFromYAML(std::move(Buffer.get()), /*DiagHandler*/ nullptr, - VFSFile, VFSEntries); + llvm::vfs::collectVFSFromYAML(std::move(Buffer.get()), + /*DiagHandler*/ nullptr, VFSFile, VFSEntries); } for (auto &E : VFSEntries) @@ -303,7 +303,7 @@ CompilerInstance::createDiagnostics(DiagnosticOptions *Opts, FileManager *CompilerInstance::createFileManager() { if (!hasVirtualFileSystem()) { - IntrusiveRefCntPtr<vfs::FileSystem> VFS = + IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS = createVFSFromCompilerInvocation(getInvocation(), getDiagnostics()); setVirtualFileSystem(VFS); } @@ -372,10 +372,8 @@ static void InitializeFileRemapping(DiagnosticsEngine &Diags, void CompilerInstance::createPreprocessor(TranslationUnitKind TUKind) { const PreprocessorOptions &PPOpts = getPreprocessorOpts(); - // Create a PTH manager if we are using some form of a token cache. - PTHManager *PTHMgr = nullptr; - if (!PPOpts.TokenCache.empty()) - PTHMgr = PTHManager::Create(PPOpts.TokenCache, getDiagnostics()); + // The module manager holds a reference to the old preprocessor (if any). + ModuleManager.reset(); // Create the Preprocessor. HeaderSearch *HeaderInfo = @@ -383,19 +381,12 @@ void CompilerInstance::createPreprocessor(TranslationUnitKind TUKind) { getDiagnostics(), getLangOpts(), &getTarget()); PP = std::make_shared<Preprocessor>( Invocation->getPreprocessorOptsPtr(), getDiagnostics(), getLangOpts(), - getSourceManager(), getPCMCache(), *HeaderInfo, *this, PTHMgr, + getSourceManager(), getPCMCache(), *HeaderInfo, *this, + /*IdentifierInfoLookup=*/nullptr, /*OwnsHeaderSearch=*/true, TUKind); getTarget().adjust(getLangOpts()); PP->Initialize(getTarget(), getAuxTarget()); - // Note that this is different then passing PTHMgr to Preprocessor's ctor. - // That argument is used as the IdentifierInfoLookup argument to - // IdentifierTable's ctor. - if (PTHMgr) { - PTHMgr->setPreprocessor(&*PP); - PP->setPTHManager(PTHMgr); - } - if (PPOpts.DetailedRecord) PP->createPreprocessingRecord(); @@ -911,6 +902,9 @@ bool CompilerInstance::ExecuteAction(FrontendAction &Act) { // taking it as an input instead of hard-coding llvm::errs. raw_ostream &OS = llvm::errs(); + if (!Act.PrepareToExecute(*this)) + return false; + // Create the target instance. setTarget(TargetInfo::CreateTargetInfo(getDiagnostics(), getInvocation().TargetOpts)); @@ -921,7 +915,7 @@ bool CompilerInstance::ExecuteAction(FrontendAction &Act) { if ((getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) && !getFrontendOpts().AuxTriple.empty()) { auto TO = std::make_shared<TargetOptions>(); - TO->Triple = getFrontendOpts().AuxTriple; + TO->Triple = llvm::Triple::normalize(getFrontendOpts().AuxTriple); TO->HostTriple = getTarget().getTriple().str(); setAuxTarget(TargetInfo::CreateTargetInfo(getDiagnostics(), TO)); } @@ -1021,7 +1015,7 @@ static InputKind::Language getLanguageFromOptions(const LangOptions &LangOpts) { return InputKind::OpenCL; if (LangOpts.CUDA) return InputKind::CUDA; - if (LangOpts.ObjC1) + if (LangOpts.ObjC) return LangOpts.CPlusPlus ? InputKind::ObjCXX : InputKind::ObjC; return LangOpts.CPlusPlus ? InputKind::CXX : InputKind::C; } @@ -1266,7 +1260,7 @@ static bool compileAndLoadModule(CompilerInstance &ImportingInstance, << Module->Name << Locked.getErrorMessage(); // Clear out any potential leftover. Locked.unsafeRemoveLockFile(); - // FALLTHROUGH + LLVM_FALLTHROUGH; case llvm::LockFileManager::LFS_Owned: // We're responsible for building the module ourselves. if (!compileModuleImpl(ImportingInstance, ModuleNameLoc, Module, @@ -1615,22 +1609,7 @@ CompilerInstance::loadModule(SourceLocation ImportLoc, Module::NameVisibilityKind Visibility, bool IsInclusionDirective) { // Determine what file we're searching from. - // FIXME: Should we be deciding whether this is a submodule (here and - // below) based on -fmodules-ts or should we pass a flag and make the - // caller decide? - std::string ModuleName; - if (getLangOpts().ModulesTS) { - // FIXME: Same code as Sema::ActOnModuleDecl() so there is probably a - // better place/way to do this. - for (auto &Piece : Path) { - if (!ModuleName.empty()) - ModuleName += "."; - ModuleName += Piece.first->getName(); - } - } - else - ModuleName = Path[0].first->getName(); - + StringRef ModuleName = Path[0].first->getName(); SourceLocation ModuleNameLoc = Path[0].second; // If we've already handled this import, just return the cached result. @@ -1736,7 +1715,9 @@ CompilerInstance::loadModule(SourceLocation ImportLoc, // module cache, we don't know how to rebuild modules. unsigned ARRFlags = Source == ModuleCache ? ASTReader::ARR_OutOfDate | ASTReader::ARR_Missing : - ASTReader::ARR_ConfigurationMismatch; + Source == PrebuiltModulePath ? + 0 : + ASTReader::ARR_ConfigurationMismatch; switch (ModuleManager->ReadAST(ModuleFileName, Source == PrebuiltModulePath ? serialization::MK_PrebuiltModule @@ -1859,7 +1840,7 @@ CompilerInstance::loadModule(SourceLocation ImportLoc, // Verify that the rest of the module path actually corresponds to // a submodule. bool MapPrivateSubModToTopLevel = false; - if (!getLangOpts().ModulesTS && Path.size() > 1) { + if (Path.size() > 1) { for (unsigned I = 1, N = Path.size(); I != N; ++I) { StringRef Name = Path[I].first->getName(); clang::Module *Sub = Module->findSubmodule(Name); @@ -2139,7 +2120,7 @@ CompilerInstance::lookupMissingImports(StringRef Name, return false; } -void CompilerInstance::resetAndLeakSema() { BuryPointer(takeSema()); } +void CompilerInstance::resetAndLeakSema() { llvm::BuryPointer(takeSema()); } void CompilerInstance::setExternalSemaSource( IntrusiveRefCntPtr<ExternalSemaSource> ESS) { diff --git a/lib/Frontend/CompilerInvocation.cpp b/lib/Frontend/CompilerInvocation.cpp index 78e6babd0251..3e6528c25982 100644 --- a/lib/Frontend/CompilerInvocation.cpp +++ b/lib/Frontend/CompilerInvocation.cpp @@ -11,6 +11,7 @@ #include "TestModuleFileExtension.h" #include "clang/Basic/Builtins.h" #include "clang/Basic/CharInfo.h" +#include "clang/Basic/CodeGenOptions.h" #include "clang/Basic/CommentOptions.h" #include "clang/Basic/DebugInfoOptions.h" #include "clang/Basic/Diagnostic.h" @@ -23,17 +24,16 @@ #include "clang/Basic/SourceLocation.h" #include "clang/Basic/TargetOptions.h" #include "clang/Basic/Version.h" -#include "clang/Basic/VirtualFileSystem.h" #include "clang/Basic/Visibility.h" #include "clang/Basic/XRayInstr.h" #include "clang/Config/config.h" #include "clang/Driver/DriverDiagnostic.h" #include "clang/Driver/Options.h" -#include "clang/Frontend/CodeGenOptions.h" #include "clang/Frontend/CommandLineSourceLoc.h" #include "clang/Frontend/DependencyOutputOptions.h" #include "clang/Frontend/FrontendDiagnostic.h" #include "clang/Frontend/FrontendOptions.h" +#include "clang/Frontend/FrontendPluginRegistry.h" #include "clang/Frontend/LangStandard.h" #include "clang/Frontend/MigratorOptions.h" #include "clang/Frontend/PreprocessorOutputOptions.h" @@ -55,6 +55,7 @@ #include "llvm/ADT/StringSwitch.h" #include "llvm/ADT/Triple.h" #include "llvm/ADT/Twine.h" +#include "llvm/IR/DebugInfoMetadata.h" #include "llvm/Linker/Linker.h" #include "llvm/MC/MCTargetOptions.h" #include "llvm/Option/Arg.h" @@ -76,6 +77,7 @@ #include "llvm/Support/Process.h" #include "llvm/Support/Regex.h" #include "llvm/Support/VersionTuple.h" +#include "llvm/Support/VirtualFileSystem.h" #include "llvm/Support/raw_ostream.h" #include "llvm/Target/TargetOptions.h" #include <algorithm> @@ -119,25 +121,25 @@ CompilerInvocationBase::~CompilerInvocationBase() = default; static unsigned getOptimizationLevel(ArgList &Args, InputKind IK, DiagnosticsEngine &Diags) { - unsigned DefaultOpt = 0; + unsigned DefaultOpt = llvm::CodeGenOpt::None; if (IK.getLanguage() == InputKind::OpenCL && !Args.hasArg(OPT_cl_opt_disable)) - DefaultOpt = 2; + DefaultOpt = llvm::CodeGenOpt::Default; if (Arg *A = Args.getLastArg(options::OPT_O_Group)) { if (A->getOption().matches(options::OPT_O0)) - return 0; + return llvm::CodeGenOpt::None; if (A->getOption().matches(options::OPT_Ofast)) - return 3; + return llvm::CodeGenOpt::Aggressive; assert(A->getOption().matches(options::OPT_O)); StringRef S(A->getValue()); if (S == "s" || S == "z" || S.empty()) - return 2; + return llvm::CodeGenOpt::Default; if (S == "g") - return 1; + return llvm::CodeGenOpt::Less; return getLastArgIntValue(Args, OPT_O, DefaultOpt, Diags); } @@ -180,6 +182,11 @@ static void addDiagnosticArgs(ArgList &Args, OptSpecifier Group, } } +// Parse the Static Analyzer configuration. If \p Diags is set to nullptr, +// it won't verify the input. +static void parseAnalyzerConfigs(AnalyzerOptions &AnOpts, + DiagnosticsEngine *Diags); + static void getAllNoBuiltinFuncValues(ArgList &Args, std::vector<std::string> &Funcs) { SmallVector<const char *, 8> Values; @@ -278,19 +285,24 @@ static bool ParseAnalyzerArgs(AnalyzerOptions &Opts, ArgList &Args, } Opts.ShowCheckerHelp = Args.hasArg(OPT_analyzer_checker_help); + Opts.ShowConfigOptionsList = Args.hasArg(OPT_analyzer_config_help); Opts.ShowEnabledCheckerList = Args.hasArg(OPT_analyzer_list_enabled_checkers); + Opts.ShouldEmitErrorsOnInvalidConfigValue = + /* negated */!llvm::StringSwitch<bool>( + Args.getLastArgValue(OPT_analyzer_config_compatibility_mode)) + .Case("true", true) + .Case("false", false) + .Default(false); Opts.DisableAllChecks = Args.hasArg(OPT_analyzer_disable_all_checks); Opts.visualizeExplodedGraphWithGraphViz = Args.hasArg(OPT_analyzer_viz_egraph_graphviz); - Opts.visualizeExplodedGraphWithUbiGraph = - Args.hasArg(OPT_analyzer_viz_egraph_ubigraph); + Opts.DumpExplodedGraphTo = Args.getLastArgValue(OPT_analyzer_dump_egraph); Opts.NoRetryExhausted = Args.hasArg(OPT_analyzer_disable_retry_exhausted); Opts.AnalyzeAll = Args.hasArg(OPT_analyzer_opt_analyze_headers); Opts.AnalyzerDisplayProgress = Args.hasArg(OPT_analyzer_display_progress); Opts.AnalyzeNestedBlocks = Args.hasArg(OPT_analyzer_opt_analyze_nested_blocks); - Opts.eagerlyAssumeBinOpBifurcation = Args.hasArg(OPT_analyzer_eagerly_assume); Opts.AnalyzeSpecificFunction = Args.getLastArgValue(OPT_analyze_function); Opts.UnoptimizedCFG = Args.hasArg(OPT_analysis_UnoptimizedCFG); Opts.TrimGraph = Args.hasArg(OPT_trim_egraph); @@ -317,7 +329,7 @@ static bool ParseAnalyzerArgs(AnalyzerOptions &Opts, ArgList &Args, // Go through the analyzer configuration options. for (const auto *A : Args.filtered(OPT_analyzer_config)) { - A->claim(); + // We can have a list of comma separated config names, e.g: // '-analyzer-config key1=val1,key2=val2' StringRef configList = A->getValue(); @@ -339,10 +351,25 @@ static bool ParseAnalyzerArgs(AnalyzerOptions &Opts, ArgList &Args, Success = false; break; } + + // TODO: Check checker options too, possibly in CheckerRegistry. + // Leave unknown non-checker configs unclaimed. + if (!key.contains(":") && Opts.isUnknownAnalyzerConfig(key)) { + if (Opts.ShouldEmitErrorsOnInvalidConfigValue) + Diags.Report(diag::err_analyzer_config_unknown) << key; + continue; + } + + A->claim(); Opts.Config[key] = val; } } + if (Opts.ShouldEmitErrorsOnInvalidConfigValue) + parseAnalyzerConfigs(Opts, &Diags); + else + parseAnalyzerConfigs(Opts, nullptr); + llvm::raw_string_ostream os(Opts.FullCompilerInvocation); for (unsigned i = 0; i < Args.getNumInputArgStrings(); ++i) { if (i != 0) @@ -354,6 +381,91 @@ static bool ParseAnalyzerArgs(AnalyzerOptions &Opts, ArgList &Args, return Success; } +static StringRef getStringOption(AnalyzerOptions::ConfigTable &Config, + StringRef OptionName, StringRef DefaultVal) { + return Config.insert({OptionName, DefaultVal}).first->second; +} + +static void initOption(AnalyzerOptions::ConfigTable &Config, + DiagnosticsEngine *Diags, + StringRef &OptionField, StringRef Name, + StringRef DefaultVal) { + // String options may be known to invalid (e.g. if the expected string is a + // file name, but the file does not exist), those will have to be checked in + // parseConfigs. + OptionField = getStringOption(Config, Name, DefaultVal); +} + +static void initOption(AnalyzerOptions::ConfigTable &Config, + DiagnosticsEngine *Diags, + bool &OptionField, StringRef Name, bool DefaultVal) { + auto PossiblyInvalidVal = llvm::StringSwitch<Optional<bool>>( + getStringOption(Config, Name, (DefaultVal ? "true" : "false"))) + .Case("true", true) + .Case("false", false) + .Default(None); + + if (!PossiblyInvalidVal) { + if (Diags) + Diags->Report(diag::err_analyzer_config_invalid_input) + << Name << "a boolean"; + else + OptionField = DefaultVal; + } else + OptionField = PossiblyInvalidVal.getValue(); +} + +static void initOption(AnalyzerOptions::ConfigTable &Config, + DiagnosticsEngine *Diags, + unsigned &OptionField, StringRef Name, + unsigned DefaultVal) { + + OptionField = DefaultVal; + bool HasFailed = getStringOption(Config, Name, std::to_string(DefaultVal)) + .getAsInteger(10, OptionField); + if (Diags && HasFailed) + Diags->Report(diag::err_analyzer_config_invalid_input) + << Name << "an unsigned"; +} + +static void parseAnalyzerConfigs(AnalyzerOptions &AnOpts, + DiagnosticsEngine *Diags) { + // TODO: There's no need to store the entire configtable, it'd be plenty + // enough tostore checker options. + +#define ANALYZER_OPTION(TYPE, NAME, CMDFLAG, DESC, DEFAULT_VAL) \ + initOption(AnOpts.Config, Diags, AnOpts.NAME, CMDFLAG, DEFAULT_VAL); + +#define ANALYZER_OPTION_DEPENDS_ON_USER_MODE(TYPE, NAME, CMDFLAG, DESC, \ + SHALLOW_VAL, DEEP_VAL) \ + switch (AnOpts.getUserMode()) { \ + case UMK_Shallow: \ + initOption(AnOpts.Config, Diags, AnOpts.NAME, CMDFLAG, SHALLOW_VAL); \ + break; \ + case UMK_Deep: \ + initOption(AnOpts.Config, Diags, AnOpts.NAME, CMDFLAG, DEEP_VAL); \ + break; \ + } \ + +#include "clang/StaticAnalyzer/Core/AnalyzerOptions.def" +#undef ANALYZER_OPTION +#undef ANALYZER_OPTION_DEPENDS_ON_USER_MODE + + // At this point, AnalyzerOptions is configured. Let's validate some options. + + if (!Diags) + return; + + if (!AnOpts.CTUDir.empty() && !llvm::sys::fs::is_directory(AnOpts.CTUDir)) + Diags->Report(diag::err_analyzer_config_invalid_input) << "ctu-dir" + << "a filename"; + + if (!AnOpts.ModelPath.empty() && + !llvm::sys::fs::is_directory(AnOpts.ModelPath)) + Diags->Report(diag::err_analyzer_config_invalid_input) << "model-path" + << "a filename"; +} + static bool ParseMigratorArgs(MigratorOptions &Opts, ArgList &Args) { Opts.NoNSAllocReallocError = Args.hasArg(OPT_migrator_no_nsalloc_error); Opts.NoFinalizeRemoval = Args.hasArg(OPT_migrator_no_finalize_removal); @@ -369,7 +481,7 @@ static StringRef getCodeModel(ArgList &Args, DiagnosticsEngine &Diags) { if (Arg *A = Args.getLastArg(OPT_mcode_model)) { StringRef Value = A->getValue(); if (Value == "small" || Value == "kernel" || Value == "medium" || - Value == "large") + Value == "large" || Value == "tiny") return Value; Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Value; } @@ -568,6 +680,7 @@ static bool ParseCodeGenArgs(CodeGenOptions &Opts, ArgList &Args, InputKind IK, unsigned Val = llvm::StringSwitch<unsigned>(A->getValue()) .Case("line-tables-only", codegenoptions::DebugLineTablesOnly) + .Case("line-directives-only", codegenoptions::DebugDirectivesOnly) .Case("limited", codegenoptions::LimitedDebugInfo) .Case("standalone", codegenoptions::FullDebugInfo) .Default(~0U); @@ -592,12 +705,29 @@ static bool ParseCodeGenArgs(CodeGenOptions &Opts, ArgList &Args, InputKind IK, Opts.DwarfVersion = getLastArgIntValue(Args, OPT_dwarf_version_EQ, 0, Diags); Opts.DebugColumnInfo = Args.hasArg(OPT_dwarf_column_info); Opts.EmitCodeView = Args.hasArg(OPT_gcodeview); + Opts.CodeViewGHash = Args.hasArg(OPT_gcodeview_ghash); Opts.MacroDebugInfo = Args.hasArg(OPT_debug_info_macro); Opts.WholeProgramVTables = Args.hasArg(OPT_fwhole_program_vtables); Opts.LTOVisibilityPublicStd = Args.hasArg(OPT_flto_visibility_public_std); - Opts.EnableSplitDwarf = Args.hasArg(OPT_enable_split_dwarf); Opts.SplitDwarfFile = Args.getLastArgValue(OPT_split_dwarf_file); Opts.SplitDwarfInlining = !Args.hasArg(OPT_fno_split_dwarf_inlining); + + if (Arg *A = + Args.getLastArg(OPT_enable_split_dwarf, OPT_enable_split_dwarf_EQ)) { + if (A->getOption().matches(options::OPT_enable_split_dwarf)) { + Opts.setSplitDwarfMode(CodeGenOptions::SplitFileFission); + } else { + StringRef Name = A->getValue(); + if (Name == "single") + Opts.setSplitDwarfMode(CodeGenOptions::SingleFileFission); + else if (Name == "split") + Opts.setSplitDwarfMode(CodeGenOptions::SplitFileFission); + else + Diags.Report(diag::err_drv_invalid_value) + << A->getAsString(Args) << Name; + } + } + Opts.DebugTypeExtRefs = Args.hasArg(OPT_dwarf_ext_refs); Opts.DebugExplicitImport = Args.hasArg(OPT_dwarf_explicit_import); Opts.DebugFwdTemplateParams = Args.hasArg(OPT_debug_forward_template_params); @@ -614,6 +744,7 @@ static bool ParseCodeGenArgs(CodeGenOptions &Opts, ArgList &Args, InputKind IK, Opts.DisableLifetimeMarkers = Args.hasArg(OPT_disable_lifetimemarkers); Opts.DisableO0ImplyOptNone = Args.hasArg(OPT_disable_O0_optnone); Opts.DisableRedZone = Args.hasArg(OPT_disable_red_zone); + Opts.IndirectTlsSegRefs = Args.hasArg(OPT_mno_tls_direct_seg_refs); Opts.ForbidGuardVariables = Args.hasArg(OPT_fforbid_guard_variables); Opts.UseRegisterSizedBitfieldAccess = Args.hasArg( OPT_fuse_register_sized_bitfield_access); @@ -625,6 +756,7 @@ static bool ParseCodeGenArgs(CodeGenOptions &Opts, ArgList &Args, InputKind IK, Args.hasFlag(OPT_ffine_grained_bitfield_accesses, OPT_fno_fine_grained_bitfield_accesses, false); Opts.DwarfDebugFlags = Args.getLastArgValue(OPT_dwarf_debug_flags); + Opts.RecordCommandLine = Args.getLastArgValue(OPT_record_command_line); Opts.MergeAllConstants = Args.hasArg(OPT_fmerge_all_constants); Opts.NoCommon = Args.hasArg(OPT_fno_common); Opts.NoImplicitFloat = Args.hasArg(OPT_no_implicit_float); @@ -643,7 +775,13 @@ static bool ParseCodeGenArgs(CodeGenOptions &Opts, ArgList &Args, InputKind IK, Opts.SampleProfileFile = Args.getLastArgValue(OPT_fprofile_sample_use_EQ); Opts.DebugInfoForProfiling = Args.hasFlag( OPT_fdebug_info_for_profiling, OPT_fno_debug_info_for_profiling, false); - Opts.GnuPubnames = Args.hasArg(OPT_ggnu_pubnames); + Opts.DebugNameTable = static_cast<unsigned>( + Args.hasArg(OPT_ggnu_pubnames) + ? llvm::DICompileUnit::DebugNameTableKind::GNU + : Args.hasArg(OPT_gpubnames) + ? llvm::DICompileUnit::DebugNameTableKind::Default + : llvm::DICompileUnit::DebugNameTableKind::None); + Opts.DebugRangesBaseAddress = Args.hasArg(OPT_fdebug_ranges_base_address); setPGOInstrumentor(Opts, Args, Diags); Opts.InstrProfileOutput = @@ -652,6 +790,13 @@ static bool ParseCodeGenArgs(CodeGenOptions &Opts, ArgList &Args, InputKind IK, Args.getLastArgValue(OPT_fprofile_instrument_use_path_EQ); if (!Opts.ProfileInstrumentUsePath.empty()) setPGOUseInstrumentor(Opts, Opts.ProfileInstrumentUsePath); + Opts.ProfileRemappingFile = + Args.getLastArgValue(OPT_fprofile_remapping_file_EQ); + if (!Opts.ProfileRemappingFile.empty() && !Opts.ExperimentalNewPassManager) { + Diags.Report(diag::err_drv_argument_only_allowed_with) + << Args.getLastArg(OPT_fprofile_remapping_file_EQ)->getAsString(Args) + << "-fexperimental-new-pass-manager"; + } Opts.CoverageMapping = Args.hasFlag(OPT_fcoverage_mapping, OPT_fno_coverage_mapping, false); @@ -664,7 +809,7 @@ static bool ParseCodeGenArgs(CodeGenOptions &Opts, ArgList &Args, InputKind IK, Opts.RegisterGlobalDtorsWithAtExit = Args.hasArg(OPT_fregister_global_dtors_with_atexit); Opts.CXXCtorDtorAliases = Args.hasArg(OPT_mconstructor_aliases); - Opts.CodeModel = getCodeModel(Args, Diags); + Opts.CodeModel = TargetOpts.CodeModel; Opts.DebugPass = Args.getLastArgValue(OPT_mdebug_pass); Opts.DisableFPElim = (Args.hasArg(OPT_mdisable_fp_elim) || Args.hasArg(OPT_pg)); @@ -762,6 +907,7 @@ static bool ParseCodeGenArgs(CodeGenOptions &Opts, ArgList &Args, InputKind IK, Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << S; } Opts.LTOUnit = Args.hasFlag(OPT_flto_unit, OPT_fno_lto_unit, false); + Opts.EnableSplitLTOUnit = Args.hasArg(OPT_fsplit_lto_unit); if (Arg *A = Args.getLastArg(OPT_fthinlto_index_EQ)) { if (IK.getLanguage() != InputKind::LLVM_IR) Diags.Report(diag::err_drv_argument_only_allowed_with) @@ -797,6 +943,10 @@ 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.ProfileFilterFiles = + Args.getLastArgValue(OPT_fprofile_filter_files_EQ); + Opts.ProfileExcludeFiles = + Args.getLastArgValue(OPT_fprofile_exclude_files_EQ); Opts.CoverageExitBlockBeforeBody = Args.hasArg(OPT_coverage_exit_block_before_body); if (Args.hasArg(OPT_coverage_version_EQ)) { @@ -844,7 +994,7 @@ static bool ParseCodeGenArgs(CodeGenOptions &Opts, ArgList &Args, InputKind IK, for (const auto &arg : ASL) { StringRef ArgStr(arg); Opts.CmdArgs.insert(Opts.CmdArgs.end(), ArgStr.begin(), ArgStr.end()); - // using \00 to seperate each commandline options. + // using \00 to separate each commandline options. Opts.CmdArgs.push_back('\0'); } } @@ -912,10 +1062,10 @@ static bool ParseCodeGenArgs(CodeGenOptions &Opts, ArgList &Args, InputKind IK, Opts.RelaxELFRelocations = Args.hasArg(OPT_mrelax_relocations); Opts.DebugCompilationDir = Args.getLastArgValue(OPT_fdebug_compilation_dir); for (auto *A : - Args.filtered(OPT_mlink_bitcode_file, OPT_mlink_cuda_bitcode)) { + Args.filtered(OPT_mlink_bitcode_file, OPT_mlink_builtin_bitcode)) { CodeGenOptions::BitcodeFileToLink F; F.Filename = A->getValue(); - if (A->getOption().matches(OPT_mlink_cuda_bitcode)) { + if (A->getOption().matches(OPT_mlink_builtin_bitcode)) { F.LinkFlags = llvm::Linker::Flags::LinkOnlyNeeded; // When linking CUDA bitcode, propagate function attributes so that // e.g. libdevice gets fast-math attrs if we're building with fast-math. @@ -955,11 +1105,11 @@ static bool ParseCodeGenArgs(CodeGenOptions &Opts, ArgList &Args, InputKind IK, Args.hasArg(OPT_fsanitize_cfi_icall_generalize_pointers); Opts.SanitizeStats = Args.hasArg(OPT_fsanitize_stats); if (Arg *A = Args.getLastArg( - OPT_fsanitize_address_poison_class_member_array_new_cookie, - OPT_fno_sanitize_address_poison_class_member_array_new_cookie)) { - Opts.SanitizeAddressPoisonClassMemberArrayNewCookie = + OPT_fsanitize_address_poison_custom_array_cookie, + OPT_fno_sanitize_address_poison_custom_array_cookie)) { + Opts.SanitizeAddressPoisonCustomArrayCookie = A->getOption().getID() == - OPT_fsanitize_address_poison_class_member_array_new_cookie; + OPT_fsanitize_address_poison_custom_array_cookie; } if (Arg *A = Args.getLastArg(OPT_fsanitize_address_use_after_scope, OPT_fno_sanitize_address_use_after_scope)) { @@ -968,6 +1118,11 @@ static bool ParseCodeGenArgs(CodeGenOptions &Opts, ArgList &Args, InputKind IK, } Opts.SanitizeAddressGlobalsDeadStripping = Args.hasArg(OPT_fsanitize_address_globals_dead_stripping); + if (Arg *A = Args.getLastArg(OPT_fsanitize_address_use_odr_indicator, + OPT_fno_sanitize_address_use_odr_indicator)) { + Opts.SanitizeAddressUseOdrIndicator = + A->getOption().getID() == OPT_fsanitize_address_use_odr_indicator; + } Opts.SSPBufferSize = getLastArgIntValue(Args, OPT_stack_protector_buffer_size, 8, Diags); Opts.StackRealignment = Args.hasArg(OPT_mstackrealign); @@ -1003,6 +1158,10 @@ static bool ParseCodeGenArgs(CodeGenOptions &Opts, ArgList &Args, InputKind IK, } } + + if (Args.hasArg(OPT_fno_objc_convert_messages_to_runtime_calls)) + Opts.ObjCConvertMessagesToRuntimeCalls = 0; + if (Args.getLastArg(OPT_femulated_tls) || Args.getLastArg(OPT_fno_emulated_tls)) { Opts.ExplicitEmulatedTLS = true; @@ -1125,6 +1284,44 @@ static bool ParseCodeGenArgs(CodeGenOptions &Opts, ArgList &Args, InputKind IK, Opts.Addrsig = Args.hasArg(OPT_faddrsig); + if (Arg *A = Args.getLastArg(OPT_msign_return_address_EQ)) { + StringRef SignScope = A->getValue(); + + if (SignScope.equals_lower("none")) + Opts.setSignReturnAddress(CodeGenOptions::SignReturnAddressScope::None); + else if (SignScope.equals_lower("all")) + Opts.setSignReturnAddress(CodeGenOptions::SignReturnAddressScope::All); + else if (SignScope.equals_lower("non-leaf")) + Opts.setSignReturnAddress( + CodeGenOptions::SignReturnAddressScope::NonLeaf); + else + Diags.Report(diag::err_drv_invalid_value) + << A->getAsString(Args) << SignScope; + + if (Arg *A = Args.getLastArg(OPT_msign_return_address_key_EQ)) { + StringRef SignKey = A->getValue(); + if (!SignScope.empty() && !SignKey.empty()) { + if (SignKey.equals_lower("a_key")) + Opts.setSignReturnAddressKey( + CodeGenOptions::SignReturnAddressKeyValue::AKey); + else if (SignKey.equals_lower("b_key")) + Opts.setSignReturnAddressKey( + CodeGenOptions::SignReturnAddressKeyValue::BKey); + else + Diags.Report(diag::err_drv_invalid_value) + << A->getAsString(Args) << SignKey; + } + } + } + + Opts.BranchTargetEnforcement = Args.hasArg(OPT_mbranch_target_enforce); + + Opts.KeepStaticConsts = Args.hasArg(OPT_fkeep_static_consts); + + Opts.SpeculativeLoadHardening = Args.hasArg(OPT_mspeculative_load_hardening); + + Opts.DefaultFunctionAttrs = Args.getAllArgValues(OPT_default_function_attr); + return Success; } @@ -1316,7 +1513,7 @@ bool clang::ParseDiagnosticArgs(DiagnosticOptions &Opts, ArgList &Args, Success = false; } else - llvm::sort(Opts.VerifyPrefixes.begin(), Opts.VerifyPrefixes.end()); + llvm::sort(Opts.VerifyPrefixes); DiagnosticLevelMask DiagMask = DiagnosticLevelMask::None; Success &= parseDiagnosticLevelMask("-verify-ignore-unexpected=", Args.getAllArgValues(OPT_verify_ignore_unexpected_EQ), @@ -1425,17 +1622,17 @@ static InputKind ParseFrontendArgs(FrontendOptions &Opts, ArgList &Args, Opts.ProgramAction = frontend::EmitObj; break; case OPT_fixit_EQ: Opts.FixItSuffix = A->getValue(); - // fall-through! + LLVM_FALLTHROUGH; case OPT_fixit: Opts.ProgramAction = frontend::FixIt; break; case OPT_emit_module: Opts.ProgramAction = frontend::GenerateModule; break; case OPT_emit_module_interface: Opts.ProgramAction = frontend::GenerateModuleInterface; break; + case OPT_emit_header_module: + Opts.ProgramAction = frontend::GenerateHeaderModule; break; case OPT_emit_pch: Opts.ProgramAction = frontend::GeneratePCH; break; - case OPT_emit_pth: - Opts.ProgramAction = frontend::GeneratePTH; break; case OPT_init_only: Opts.ProgramAction = frontend::InitOnly; break; case OPT_fsyntax_only: @@ -1444,8 +1641,6 @@ static InputKind ParseFrontendArgs(FrontendOptions &Opts, ArgList &Args, Opts.ProgramAction = frontend::ModuleFileInfo; break; case OPT_verify_pch: Opts.ProgramAction = frontend::VerifyPCH; break; - case OPT_print_decl_contexts: - Opts.ProgramAction = frontend::PrintDeclContext; break; case OPT_print_preamble: Opts.ProgramAction = frontend::PrintPreamble; break; case OPT_E: @@ -1550,8 +1745,7 @@ static InputKind ParseFrontendArgs(FrontendOptions &Opts, ArgList &Args, Opts.OverrideRecordLayoutsFile = Args.getLastArgValue(OPT_foverride_record_layout_EQ); - Opts.AuxTriple = - llvm::Triple::normalize(Args.getLastArgValue(OPT_aux_triple)); + Opts.AuxTriple = Args.getLastArgValue(OPT_aux_triple); Opts.StatsFile = Args.getLastArgValue(OPT_stats_file); if (const Arg *A = Args.getLastArg(OPT_arcmt_check, @@ -1867,7 +2061,7 @@ void CompilerInvocation::setLangDefaults(LangOptions &Opts, InputKind IK, if (IK.getLanguage() == InputKind::Asm) { Opts.AsmPreprocessor = 1; } else if (IK.isObjectiveC()) { - Opts.ObjC1 = Opts.ObjC2 = 1; + Opts.ObjC = 1; } if (LangStd == LangStandard::lang_unspecified) { @@ -2130,6 +2324,9 @@ static void ParseLangArgs(LangOptions &Opts, ArgList &Args, InputKind IK, } } + if (Args.hasArg(OPT_fno_dllexport_inlines)) + Opts.DllExportInlines = false; + if (const Arg *A = Args.getLastArg(OPT_fcf_protection_EQ)) { StringRef Name = A->getValue(); if (Name == "full" || Name == "branch") { @@ -2196,9 +2393,9 @@ static void ParseLangArgs(LangOptions &Opts, ArgList &Args, InputKind IK, if (Opts.CUDAIsDevice && Args.hasArg(OPT_fcuda_approx_transcendentals)) Opts.CUDADeviceApproxTranscendentals = 1; - Opts.CUDARelocatableDeviceCode = Args.hasArg(OPT_fcuda_rdc); + Opts.GPURelocatableDeviceCode = Args.hasArg(OPT_fgpu_rdc); - if (Opts.ObjC1) { + if (Opts.ObjC) { if (Arg *arg = Args.getLastArg(OPT_fobjc_runtime_EQ)) { StringRef value = arg->getValue(); if (Opts.ObjCRuntime.tryParse(value)) @@ -2265,8 +2462,19 @@ static void ParseLangArgs(LangOptions &Opts, ArgList &Args, InputKind IK, if (Args.hasArg(OPT_print_ivar_layout)) Opts.ObjCGCBitmapPrint = 1; + if (Args.hasArg(OPT_fno_constant_cfstrings)) Opts.NoConstantCFStrings = 1; + if (const auto *A = Args.getLastArg(OPT_fcf_runtime_abi_EQ)) + Opts.CFRuntime = + llvm::StringSwitch<LangOptions::CoreFoundationABI>(A->getValue()) + .Cases("unspecified", "standalone", "objc", + LangOptions::CoreFoundationABI::ObjectiveC) + .Cases("swift", "swift-5.0", + LangOptions::CoreFoundationABI::Swift5_0) + .Case("swift-4.2", LangOptions::CoreFoundationABI::Swift4_2) + .Case("swift-4.1", LangOptions::CoreFoundationABI::Swift4_1) + .Default(LangOptions::CoreFoundationABI::ObjectiveC); if (Args.hasArg(OPT_fzvector)) Opts.ZVector = 1; @@ -2291,6 +2499,9 @@ static void ParseLangArgs(LangOptions &Opts, ArgList &Args, InputKind IK, if (Args.hasArg(OPT_fvisibility_inlines_hidden)) Opts.InlineVisibilityHidden = 1; + if (Args.hasArg(OPT_fvisibility_global_new_delete_hidden)) + Opts.GlobalAllocationFunctionVisibilityHidden = 1; + if (Args.hasArg(OPT_ftrapv)) { Opts.setSignedOverflowBehavior(LangOptions::SOB_Trapping); // Set the handler, if one is specified. @@ -2314,7 +2525,7 @@ static void ParseLangArgs(LangOptions &Opts, ArgList &Args, InputKind IK, VT.getSubminor().getValueOr(0); } - // Mimicing gcc's behavior, trigraphs are only enabled if -trigraphs + // Mimicking gcc's behavior, trigraphs are only enabled if -trigraphs // is specified, or -std is set to a conforming mode. // Trigraphs are disabled by default in c++1z onwards. Opts.Trigraphs = !Opts.GNUMode && !Opts.MSVCCompat && !Opts.CPlusPlus17; @@ -2395,7 +2606,7 @@ static void ParseLangArgs(LangOptions &Opts, ArgList &Args, InputKind IK, 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.Char8 = Args.hasArg(OPT_fchar8__t); + Opts.Char8 = Args.hasFlag(OPT_fchar8__t, OPT_fno_char8__t, Opts.CPlusPlus2a); if (const Arg *A = Args.getLastArg(OPT_fwchar_type_EQ)) { Opts.WCharSize = llvm::StringSwitch<unsigned>(A->getValue()) .Case("char", 1) @@ -2478,7 +2689,7 @@ static void ParseLangArgs(LangOptions &Opts, ArgList &Args, InputKind IK, Opts.CurrentModule = Opts.ModuleName; Opts.AppExt = Args.hasArg(OPT_fapplication_extension); Opts.ModuleFeatures = Args.getAllArgValues(OPT_fmodule_feature); - llvm::sort(Opts.ModuleFeatures.begin(), Opts.ModuleFeatures.end()); + llvm::sort(Opts.ModuleFeatures); Opts.NativeHalfType |= Args.hasArg(OPT_fnative_half_type); Opts.NativeHalfArgsAndReturns |= Args.hasArg(OPT_fnative_half_arguments_and_returns); // Enable HalfArgsAndReturns if present in Args or if NativeHalfArgsAndReturns @@ -2627,6 +2838,19 @@ static void ParseLangArgs(LangOptions &Opts, ArgList &Args, InputKind IK, Opts.Exceptions = 0; Opts.CXXExceptions = 0; } + if (Opts.OpenMPIsDevice && T.isNVPTX()) { + Opts.OpenMPCUDANumSMs = + getLastArgIntValue(Args, options::OPT_fopenmp_cuda_number_of_sm_EQ, + Opts.OpenMPCUDANumSMs, Diags); + Opts.OpenMPCUDABlocksPerSM = + getLastArgIntValue(Args, options::OPT_fopenmp_cuda_blocks_per_sm_EQ, + Opts.OpenMPCUDABlocksPerSM, Diags); + } + + // Prevent auto-widening the representation of loop counters during an + // OpenMP collapse clause. + Opts.OpenMPOptimisticCollapse = + Args.hasArg(options::OPT_fopenmp_optimistic_collapse) ? 1 : 0; // Get the OpenMP target triples if any. if (Arg *A = Args.getLastArg(options::OPT_fopenmp_targets_EQ)) { @@ -2657,10 +2881,15 @@ static void ParseLangArgs(LangOptions &Opts, ArgList &Args, InputKind IK, << Opts.OMPHostIRFile; } - // set CUDA mode for OpenMP target NVPTX if specified in options + // Set CUDA mode for OpenMP target NVPTX if specified in options Opts.OpenMPCUDAMode = Opts.OpenMPIsDevice && T.isNVPTX() && Args.hasArg(options::OPT_fopenmp_cuda_mode); + // Set CUDA mode for OpenMP target NVPTX if specified in options + Opts.OpenMPCUDAForceFullRuntime = + Opts.OpenMPIsDevice && T.isNVPTX() && + Args.hasArg(options::OPT_fopenmp_cuda_force_full_runtime); + // Record whether the __DEPRECATED define was requested. Opts.Deprecated = Args.hasFlag(OPT_fdeprecated_macro, OPT_fno_deprecated_macro, @@ -2718,6 +2947,19 @@ static void ParseLangArgs(LangOptions &Opts, ArgList &Args, InputKind IK, case 3: Opts.setStackProtector(LangOptions::SSPReq); break; } + if (Arg *A = Args.getLastArg(OPT_ftrivial_auto_var_init)) { + StringRef Val = A->getValue(); + if (Val == "uninitialized") + Opts.setTrivialAutoVarInit( + LangOptions::TrivialAutoVarInitKind::Uninitialized); + else if (Val == "zero") + Opts.setTrivialAutoVarInit(LangOptions::TrivialAutoVarInitKind::Zero); + else if (Val == "pattern") + Opts.setTrivialAutoVarInit(LangOptions::TrivialAutoVarInitKind::Pattern); + else + Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Val; + } + // Parse -fsanitize= arguments. parseSanitizerKinds("-fsanitize=", Args.getAllArgValues(OPT_fsanitize_EQ), Diags, Opts.Sanitize); @@ -2753,6 +2995,8 @@ static void ParseLangArgs(LangOptions &Opts, ArgList &Args, InputKind IK, // -fallow-editor-placeholders Opts.AllowEditorPlaceholders = Args.hasArg(OPT_fallow_editor_placeholders); + Opts.RegisterStaticDestructors = !Args.hasArg(OPT_fno_cxx_static_destructors); + if (Arg *A = Args.getLastArg(OPT_fclang_abi_compat_EQ)) { Opts.setClangABICompat(LangOptions::ClangABI::Latest); @@ -2776,6 +3020,8 @@ static void ParseLangArgs(LangOptions &Opts, ArgList &Args, InputKind IK, Opts.setClangABICompat(LangOptions::ClangABI::Ver4); else if (Major <= 6) Opts.setClangABICompat(LangOptions::ClangABI::Ver6); + else if (Major <= 7) + Opts.setClangABICompat(LangOptions::ClangABI::Ver7); } else if (Ver != "latest") { Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << A->getValue(); @@ -2802,13 +3048,12 @@ static bool isStrictlyPreprocessorAction(frontend::ActionKind Action) { case frontend::FixIt: case frontend::GenerateModule: case frontend::GenerateModuleInterface: + case frontend::GenerateHeaderModule: case frontend::GeneratePCH: - case frontend::GeneratePTH: case frontend::ParseSyntaxOnly: case frontend::ModuleFileInfo: case frontend::VerifyPCH: case frontend::PluginAction: - case frontend::PrintDeclContext: case frontend::RewriteObjC: case frontend::RewriteTest: case frontend::RunAnalysis: @@ -2833,12 +3078,10 @@ static void ParsePreprocessorArgs(PreprocessorOptions &Opts, ArgList &Args, DiagnosticsEngine &Diags, frontend::ActionKind Action) { Opts.ImplicitPCHInclude = Args.getLastArgValue(OPT_include_pch); - Opts.ImplicitPTHInclude = Args.getLastArgValue(OPT_include_pth); + Opts.PCHWithHdrStop = Args.hasArg(OPT_pch_through_hdrstop_create) || + Args.hasArg(OPT_pch_through_hdrstop_use); + Opts.PCHWithHdrStopCreate = Args.hasArg(OPT_pch_through_hdrstop_create); Opts.PCHThroughHeader = Args.getLastArgValue(OPT_pch_through_header_EQ); - if (const Arg *A = Args.getLastArg(OPT_token_cache)) - Opts.TokenCache = A->getValue(); - else - Opts.TokenCache = Opts.ImplicitPTHInclude; Opts.UsePredefines = !Args.hasArg(OPT_undef); Opts.DetailedRecord = Args.hasArg(OPT_detailed_preprocessing_record); Opts.DisablePCHValidation = Args.hasArg(OPT_fno_validate_pch); @@ -2943,6 +3186,7 @@ static void ParsePreprocessorOutputArgs(PreprocessorOutputOptions &Opts, static void ParseTargetArgs(TargetOptions &Opts, ArgList &Args, DiagnosticsEngine &Diags) { + Opts.CodeModel = getCodeModel(Args, Diags); Opts.ABI = Args.getLastArgValue(OPT_target_abi); if (Arg *A = Args.getLastArg(OPT_meabi)) { StringRef Value = A->getValue(); @@ -2971,6 +3215,14 @@ static void ParseTargetArgs(TargetOptions &Opts, ArgList &Args, Opts.ForceEnableInt128 = Args.hasArg(OPT_fforce_enable_int128); Opts.NVPTXUseShortPointers = Args.hasFlag( options::OPT_fcuda_short_ptr, options::OPT_fno_cuda_short_ptr, false); + if (Arg *A = Args.getLastArg(options::OPT_target_sdk_version_EQ)) { + llvm::VersionTuple Version; + if (Version.tryParse(A->getValue())) + Diags.Report(diag::err_drv_invalid_value) + << A->getAsString(Args) << A->getValue(); + else + Opts.SDKVersion = Version; + } } bool CompilerInvocation::CreateFromArgs(CompilerInvocation &Res, @@ -3023,6 +3275,7 @@ bool CompilerInvocation::CreateFromArgs(CompilerInvocation &Res, Res.getTargetOpts(), Res.getFrontendOpts()); ParseHeaderSearchArgs(Res.getHeaderSearchOpts(), Args, Res.getFileSystemOpts().WorkingDir); + llvm::Triple T(Res.getTargetOpts().Triple); if (DashX.getFormat() == InputKind::Precompiled || DashX.getLanguage() == InputKind::LLVM_IR) { // ObjCAAutoRefCount and Sanitize LangOpts are used to setup the @@ -3037,12 +3290,18 @@ bool CompilerInvocation::CreateFromArgs(CompilerInvocation &Res, parseSanitizerKinds("-fsanitize=", Args.getAllArgValues(OPT_fsanitize_EQ), Diags, LangOpts.Sanitize); } else { - // Other LangOpts are only initialzed when the input is not AST or LLVM IR. + // Other LangOpts are only initialized when the input is not AST or LLVM IR. // FIXME: Should we really be calling this for an InputKind::Asm input? ParseLangArgs(LangOpts, Args, DashX, Res.getTargetOpts(), Res.getPreprocessorOpts(), Diags); if (Res.getFrontendOpts().ProgramAction == frontend::RewriteObjC) LangOpts.ObjCExceptions = 1; + if (T.isOSDarwin() && DashX.isPreprocessed()) { + // Supress the darwin-specific 'stdlibcxx-not-found' diagnostic for + // preprocessed input as we don't expect it to be used with -std=libc++ + // anyway. + Res.getDiagnosticOpts().Warnings.push_back("no-stdlibcxx-not-found"); + } } LangOpts.FunctionAlignment = @@ -3064,7 +3323,9 @@ bool CompilerInvocation::CreateFromArgs(CompilerInvocation &Res, // names. Res.getCodeGenOpts().DiscardValueNames &= !LangOpts.Sanitize.has(SanitizerKind::Address) && - !LangOpts.Sanitize.has(SanitizerKind::Memory); + !LangOpts.Sanitize.has(SanitizerKind::KernelAddress) && + !LangOpts.Sanitize.has(SanitizerKind::Memory) && + !LangOpts.Sanitize.has(SanitizerKind::KernelMemory); ParsePreprocessorArgs(Res.getPreprocessorOpts(), Args, Diags, Res.getFrontendOpts().ProgramAction); @@ -3072,7 +3333,6 @@ bool CompilerInvocation::CreateFromArgs(CompilerInvocation &Res, Res.getFrontendOpts().ProgramAction); // Turn on -Wspir-compat for SPIR target. - llvm::Triple T(Res.getTargetOpts().Triple); auto Arch = T.getArch(); if (Arch == llvm::Triple::spir || Arch == llvm::Triple::spir64) { Res.getDiagnosticOpts().Warnings.push_back("spir-compat"); @@ -3156,6 +3416,12 @@ std::string CompilerInvocation::getModuleHash() const { code = ext->hashExtension(code); } + // When compiling with -gmodules, also hash -fdebug-prefix-map as it + // affects the debug info in the PCM. + if (getCodeGenOpts().DebugTypeExtRefs) + for (const auto &KeyValue : getCodeGenOpts().DebugPrefixMap) + code = hash_combine(code, KeyValue.first, KeyValue.second); + // Extend the signature with the enabled sanitizers, if at least one is // enabled. Sanitizers which cannot affect AST generation aren't hashed. SanitizerSet SanHash = LangOpts->Sanitize; @@ -3195,53 +3461,40 @@ uint64_t getLastArgUInt64Value(const ArgList &Args, OptSpecifier Id, return getLastArgIntValueImpl<uint64_t>(Args, Id, Default, Diags); } -void BuryPointer(const void *Ptr) { - // This function may be called only a small fixed amount of times per each - // invocation, otherwise we do actually have a leak which we want to report. - // If this function is called more than kGraveYardMaxSize times, the pointers - // will not be properly buried and a leak detector will report a leak, which - // is what we want in such case. - static const size_t kGraveYardMaxSize = 16; - LLVM_ATTRIBUTE_UNUSED static const void *GraveYard[kGraveYardMaxSize]; - static std::atomic<unsigned> GraveYardSize; - unsigned Idx = GraveYardSize++; - if (Idx >= kGraveYardMaxSize) - return; - GraveYard[Idx] = Ptr; -} - -IntrusiveRefCntPtr<vfs::FileSystem> +IntrusiveRefCntPtr<llvm::vfs::FileSystem> createVFSFromCompilerInvocation(const CompilerInvocation &CI, DiagnosticsEngine &Diags) { - return createVFSFromCompilerInvocation(CI, Diags, vfs::getRealFileSystem()); + return createVFSFromCompilerInvocation(CI, Diags, + llvm::vfs::getRealFileSystem()); } -IntrusiveRefCntPtr<vfs::FileSystem> -createVFSFromCompilerInvocation(const CompilerInvocation &CI, - DiagnosticsEngine &Diags, - IntrusiveRefCntPtr<vfs::FileSystem> BaseFS) { +IntrusiveRefCntPtr<llvm::vfs::FileSystem> createVFSFromCompilerInvocation( + const CompilerInvocation &CI, DiagnosticsEngine &Diags, + IntrusiveRefCntPtr<llvm::vfs::FileSystem> BaseFS) { if (CI.getHeaderSearchOpts().VFSOverlayFiles.empty()) return BaseFS; - IntrusiveRefCntPtr<vfs::OverlayFileSystem> Overlay( - new vfs::OverlayFileSystem(BaseFS)); + IntrusiveRefCntPtr<llvm::vfs::FileSystem> Result = BaseFS; // earlier vfs files are on the bottom for (const auto &File : CI.getHeaderSearchOpts().VFSOverlayFiles) { llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> Buffer = - BaseFS->getBufferForFile(File); + Result->getBufferForFile(File); if (!Buffer) { Diags.Report(diag::err_missing_vfs_overlay_file) << File; continue; } - IntrusiveRefCntPtr<vfs::FileSystem> FS = vfs::getVFSFromYAML( - std::move(Buffer.get()), /*DiagHandler*/ nullptr, File); - if (FS) - Overlay->pushOverlay(FS); - else + IntrusiveRefCntPtr<llvm::vfs::FileSystem> FS = llvm::vfs::getVFSFromYAML( + std::move(Buffer.get()), /*DiagHandler*/ nullptr, File, + /*DiagContext*/ nullptr, Result); + if (!FS) { Diags.Report(diag::err_invalid_vfs_overlay) << File; + continue; + } + + Result = FS; } - return Overlay; + return Result; } } // namespace clang diff --git a/lib/Frontend/CreateInvocationFromCommandLine.cpp b/lib/Frontend/CreateInvocationFromCommandLine.cpp index c3ce7ce2b742..2d4c40f8b9f1 100644 --- a/lib/Frontend/CreateInvocationFromCommandLine.cpp +++ b/lib/Frontend/CreateInvocationFromCommandLine.cpp @@ -32,7 +32,7 @@ using namespace llvm::opt; /// argument vector. std::unique_ptr<CompilerInvocation> clang::createInvocationFromCommandLine( ArrayRef<const char *> ArgList, IntrusiveRefCntPtr<DiagnosticsEngine> Diags, - IntrusiveRefCntPtr<vfs::FileSystem> VFS) { + IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS) { if (!Diags.get()) { // No diagnostics engine was provided, so create our own diagnostics object // with the default options. diff --git a/lib/Frontend/DependencyFile.cpp b/lib/Frontend/DependencyFile.cpp index e6e07190e1ff..a03d4b79c8b9 100644 --- a/lib/Frontend/DependencyFile.cpp +++ b/lib/Frontend/DependencyFile.cpp @@ -17,7 +17,6 @@ #include "clang/Frontend/DependencyOutputOptions.h" #include "clang/Frontend/FrontendDiagnostic.h" #include "clang/Lex/DirectoryLookup.h" -#include "clang/Lex/LexDiagnostic.h" #include "clang/Lex/ModuleMap.h" #include "clang/Lex/PPCallbacks.h" #include "clang/Lex/Preprocessor.h" @@ -200,6 +199,10 @@ public: const Module *Imported, SrcMgr::CharacteristicKind FileType) override; + void HasInclude(SourceLocation Loc, StringRef SpelledFilename, bool IsAngled, + const FileEntry *File, + SrcMgr::CharacteristicKind FileType) override; + void EndOfMainFile() override { OutputDependencyFile(); } @@ -328,6 +331,17 @@ void DFGImpl::InclusionDirective(SourceLocation HashLoc, } } +void DFGImpl::HasInclude(SourceLocation Loc, StringRef SpelledFilename, + bool IsAngled, const FileEntry *File, + SrcMgr::CharacteristicKind FileType) { + if (!File) + return; + StringRef Filename = File->getName(); + if (!FileMatchesDepCriteria(Filename.data(), FileType)) + return; + AddFilename(llvm::sys::path::remove_leading_dotslash(Filename)); +} + bool DFGImpl::AddFilename(StringRef Filename) { if (FilesSet.insert(Filename).second) { Files.push_back(Filename); @@ -386,28 +400,32 @@ bool DFGImpl::AddFilename(StringRef Filename) { /// for Windows file-naming info. static void PrintFilename(raw_ostream &OS, StringRef Filename, DependencyOutputFormat OutputFormat) { + // Convert filename to platform native path + llvm::SmallString<256> NativePath; + llvm::sys::path::native(Filename.str(), NativePath); + 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 << '\"'; + if (NativePath.find_first_of(" #${}^!") != StringRef::npos) + OS << '\"' << NativePath << '\"'; else - OS << Filename; + OS << NativePath; return; } assert(OutputFormat == DependencyOutputFormat::Make); - for (unsigned i = 0, e = Filename.size(); i != e; ++i) { - if (Filename[i] == '#') // Handle '#' the broken gcc way. + for (unsigned i = 0, e = NativePath.size(); i != e; ++i) { + if (NativePath[i] == '#') // Handle '#' the broken gcc way. OS << '\\'; - else if (Filename[i] == ' ') { // Handle space correctly. + else if (NativePath[i] == ' ') { // Handle space correctly. OS << '\\'; unsigned j = i; - while (j > 0 && Filename[--j] == '\\') + while (j > 0 && NativePath[--j] == '\\') OS << '\\'; - } else if (Filename[i] == '$') // $ is escaped by $$. + } else if (NativePath[i] == '$') // $ is escaped by $$. OS << '$'; - OS << Filename[i]; + OS << NativePath[i]; } } diff --git a/lib/Frontend/DiagnosticRenderer.cpp b/lib/Frontend/DiagnosticRenderer.cpp index 757ceec7ec9d..3bd86dc5beaa 100644 --- a/lib/Frontend/DiagnosticRenderer.cpp +++ b/lib/Frontend/DiagnosticRenderer.cpp @@ -337,8 +337,8 @@ static void computeCommonMacroArgExpansionFileIDs( SmallVector<FileID, 4> EndArgExpansions; getMacroArgExpansionFileIDs(Begin, BeginArgExpansions, /*IsBegin=*/true, SM); getMacroArgExpansionFileIDs(End, EndArgExpansions, /*IsBegin=*/false, SM); - llvm::sort(BeginArgExpansions.begin(), BeginArgExpansions.end()); - llvm::sort(EndArgExpansions.begin(), EndArgExpansions.end()); + llvm::sort(BeginArgExpansions); + llvm::sort(EndArgExpansions); std::set_intersection(BeginArgExpansions.begin(), BeginArgExpansions.end(), EndArgExpansions.begin(), EndArgExpansions.end(), std::back_inserter(CommonArgExpansions)); diff --git a/lib/Frontend/FrontendAction.cpp b/lib/Frontend/FrontendAction.cpp index 74550c410396..f5226380b4dd 100644 --- a/lib/Frontend/FrontendAction.cpp +++ b/lib/Frontend/FrontendAction.cpp @@ -26,6 +26,7 @@ #include "clang/Serialization/ASTDeserializationListener.h" #include "clang/Serialization/ASTReader.h" #include "clang/Serialization/GlobalModuleIndex.h" +#include "llvm/Support/BuryPointer.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/FileSystem.h" #include "llvm/Support/Path.h" @@ -151,6 +152,24 @@ FrontendAction::CreateWrappedASTConsumer(CompilerInstance &CI, if (!Consumer) return nullptr; + // Validate -add-plugin args. + bool FoundAllPlugins = true; + for (const std::string &Arg : CI.getFrontendOpts().AddPluginActions) { + bool Found = false; + for (FrontendPluginRegistry::iterator it = FrontendPluginRegistry::begin(), + ie = FrontendPluginRegistry::end(); + it != ie; ++it) { + if (it->getName() == Arg) + Found = true; + } + if (!Found) { + CI.getDiagnostics().Report(diag::err_fe_invalid_plugin_name) << Arg; + FoundAllPlugins = false; + } + } + if (!FoundAllPlugins) + return nullptr; + // If there are no registered plugins we don't need to wrap the consumer if (FrontendPluginRegistry::begin() == FrontendPluginRegistry::end()) return Consumer; @@ -276,7 +295,7 @@ static void addHeaderInclude(StringRef HeaderName, bool IsExternC) { if (IsExternC && LangOpts.CPlusPlus) Includes += "extern \"C\" {\n"; - if (LangOpts.ObjC1) + if (LangOpts.ObjC) Includes += "#import \""; else Includes += "#include \""; @@ -342,17 +361,17 @@ static std::error_code collectModuleHeaderIncludes( SmallString<128> DirNative; llvm::sys::path::native(UmbrellaDir.Entry->getName(), DirNative); - vfs::FileSystem &FS = *FileMgr.getVirtualFileSystem(); - for (vfs::recursive_directory_iterator Dir(FS, DirNative, EC), End; + llvm::vfs::FileSystem &FS = *FileMgr.getVirtualFileSystem(); + for (llvm::vfs::recursive_directory_iterator Dir(FS, DirNative, EC), End; Dir != End && !EC; Dir.increment(EC)) { // Check whether this entry has an extension typically associated with // headers. - if (!llvm::StringSwitch<bool>(llvm::sys::path::extension(Dir->getName())) - .Cases(".h", ".H", ".hh", ".hpp", true) - .Default(false)) + if (!llvm::StringSwitch<bool>(llvm::sys::path::extension(Dir->path())) + .Cases(".h", ".H", ".hh", ".hpp", true) + .Default(false)) continue; - const FileEntry *Header = FileMgr.getFile(Dir->getName()); + const FileEntry *Header = FileMgr.getFile(Dir->path()); // FIXME: This shouldn't happen unless there is a file system race. Is // that worth diagnosing? if (!Header) @@ -365,7 +384,7 @@ static std::error_code collectModuleHeaderIncludes( // Compute the relative path from the directory to this file. SmallVector<StringRef, 16> Components; - auto PathIt = llvm::sys::path::rbegin(Dir->getName()); + 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); @@ -523,7 +542,6 @@ bool FrontendAction::BeginSourceFile(CompilerInstance &CI, setCurrentInput(Input); setCompilerInstance(&CI); - StringRef InputFile = Input.getFile(); bool HasBegunSourceFile = false; bool ReplayASTFile = Input.getKind().getFormat() == InputKind::Precompiled && usesPreprocessorOnly(); @@ -541,6 +559,9 @@ bool FrontendAction::BeginSourceFile(CompilerInstance &CI, &Diags->getDiagnosticOptions())); ASTDiags->setClient(Diags->getClient(), /*OwnsClient*/false); + // FIXME: What if the input is a memory buffer? + StringRef InputFile = Input.getFile(); + std::unique_ptr<ASTUnit> AST = ASTUnit::LoadFromASTFile( InputFile, CI.getPCHContainerReader(), ASTUnit::LoadPreprocessorOnly, ASTDiags, CI.getFileSystemOpts(), CI.getCodeGenOpts().DebugTypeExtRefs); @@ -566,7 +587,7 @@ bool FrontendAction::BeginSourceFile(CompilerInstance &CI, auto &MM = ASTReader->getModuleManager(); auto &PrimaryModule = MM.getPrimaryModule(); - for (ModuleFile &MF : MM) + for (serialization::ModuleFile &MF : MM) if (&MF != &PrimaryModule) CI.getFrontendOpts().ModuleFiles.push_back(MF.FileName); @@ -585,12 +606,12 @@ bool FrontendAction::BeginSourceFile(CompilerInstance &CI, assert(ASTModule && "module file does not define its own module"); Input = FrontendInputFile(ASTModule->PresumedModuleMapFile, Kind); } else { - auto &SM = CI.getSourceManager(); - FileID ID = SM.getMainFileID(); - if (auto *File = SM.getFileEntryForID(ID)) + auto &OldSM = AST->getSourceManager(); + FileID ID = OldSM.getMainFileID(); + if (auto *File = OldSM.getFileEntryForID(ID)) Input = FrontendInputFile(File->getName(), Kind); else - Input = FrontendInputFile(SM.getBuffer(ID), Kind); + Input = FrontendInputFile(OldSM.getBuffer(ID), Kind); } setCurrentInput(Input, std::move(AST)); } @@ -604,6 +625,9 @@ bool FrontendAction::BeginSourceFile(CompilerInstance &CI, IntrusiveRefCntPtr<DiagnosticsEngine> Diags(&CI.getDiagnostics()); + // FIXME: What if the input is a memory buffer? + StringRef InputFile = Input.getFile(); + std::unique_ptr<ASTUnit> AST = ASTUnit::LoadFromASTFile( InputFile, CI.getPCHContainerReader(), ASTUnit::LoadEverything, Diags, CI.getFileSystemOpts(), CI.getCodeGenOpts().DebugTypeExtRefs); @@ -691,15 +715,16 @@ bool FrontendAction::BeginSourceFile(CompilerInstance &CI, SmallString<128> DirNative; llvm::sys::path::native(PCHDir->getName(), DirNative); bool Found = false; - vfs::FileSystem &FS = *FileMgr.getVirtualFileSystem(); - for (vfs::directory_iterator Dir = FS.dir_begin(DirNative, EC), DirEnd; + llvm::vfs::FileSystem &FS = *FileMgr.getVirtualFileSystem(); + for (llvm::vfs::directory_iterator Dir = FS.dir_begin(DirNative, EC), + DirEnd; Dir != DirEnd && !EC; Dir.increment(EC)) { // Check whether this is an acceptable AST file. if (ASTReader::isAcceptableASTFile( - Dir->getName(), FileMgr, CI.getPCHContainerReader(), + Dir->path(), FileMgr, CI.getPCHContainerReader(), CI.getLangOpts(), CI.getTargetOpts(), CI.getPreprocessorOpts(), SpecificModuleCachePath)) { - PPOpts.ImplicitPCHInclude = Dir->getName(); + PPOpts.ImplicitPCHInclude = Dir->path(); Found = true; break; } @@ -791,7 +816,7 @@ bool FrontendAction::BeginSourceFile(CompilerInstance &CI, // For preprocessed files, check if the first line specifies the original // source file name with a linemarker. - std::string PresumedInputFile = InputFile; + std::string PresumedInputFile = getCurrentFileOrBufferName(); if (Input.isPreprocessed()) ReadOriginalFileName(CI, PresumedInputFile); @@ -943,7 +968,7 @@ void FrontendAction::EndSourceFile() { if (DisableFree) { CI.resetAndLeakSema(); CI.resetAndLeakASTContext(); - BuryPointer(CI.takeASTConsumer().get()); + llvm::BuryPointer(CI.takeASTConsumer().get()); } else { CI.setSema(nullptr); CI.setASTContext(nullptr); @@ -968,7 +993,7 @@ void FrontendAction::EndSourceFile() { CI.resetAndLeakPreprocessor(); CI.resetAndLeakSourceManager(); CI.resetAndLeakFileManager(); - BuryPointer(CurrentASTUnit.release()); + llvm::BuryPointer(std::move(CurrentASTUnit)); } else { CI.setPreprocessor(nullptr); CI.setSourceManager(nullptr); diff --git a/lib/Frontend/FrontendActions.cpp b/lib/Frontend/FrontendActions.cpp index 8a8354c7d4c9..a407dfc162bb 100644 --- a/lib/Frontend/FrontendActions.cpp +++ b/lib/Frontend/FrontendActions.cpp @@ -92,12 +92,6 @@ ASTViewAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) { } std::unique_ptr<ASTConsumer> -DeclContextPrintAction::CreateASTConsumer(CompilerInstance &CI, - StringRef InFile) { - return CreateDeclContextPrinter(); -} - -std::unique_ptr<ASTConsumer> GeneratePCHAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) { std::string Sysroot; if (!ComputeASTConsumerArguments(CI, /*ref*/ Sysroot)) @@ -242,6 +236,76 @@ GenerateModuleInterfaceAction::CreateOutputFile(CompilerInstance &CI, return CI.createDefaultOutputFile(/*Binary=*/true, InFile, "pcm"); } +bool GenerateHeaderModuleAction::PrepareToExecuteAction( + CompilerInstance &CI) { + if (!CI.getLangOpts().Modules && !CI.getLangOpts().ModulesTS) { + CI.getDiagnostics().Report(diag::err_header_module_requires_modules); + return false; + } + + auto &Inputs = CI.getFrontendOpts().Inputs; + if (Inputs.empty()) + return GenerateModuleAction::BeginInvocation(CI); + + auto Kind = Inputs[0].getKind(); + + // Convert the header file inputs into a single module input buffer. + SmallString<256> HeaderContents; + ModuleHeaders.reserve(Inputs.size()); + for (const FrontendInputFile &FIF : Inputs) { + // FIXME: We should support re-compiling from an AST file. + if (FIF.getKind().getFormat() != InputKind::Source || !FIF.isFile()) { + CI.getDiagnostics().Report(diag::err_module_header_file_not_found) + << (FIF.isFile() ? FIF.getFile() + : FIF.getBuffer()->getBufferIdentifier()); + return true; + } + + HeaderContents += "#include \""; + HeaderContents += FIF.getFile(); + HeaderContents += "\"\n"; + ModuleHeaders.push_back(FIF.getFile()); + } + Buffer = llvm::MemoryBuffer::getMemBufferCopy( + HeaderContents, Module::getModuleInputBufferName()); + + // Set that buffer up as our "real" input. + Inputs.clear(); + Inputs.push_back(FrontendInputFile(Buffer.get(), Kind, /*IsSystem*/false)); + + return GenerateModuleAction::PrepareToExecuteAction(CI); +} + +bool GenerateHeaderModuleAction::BeginSourceFileAction( + CompilerInstance &CI) { + CI.getLangOpts().setCompilingModule(LangOptions::CMK_HeaderModule); + + // Synthesize a Module object for the given headers. + auto &HS = CI.getPreprocessor().getHeaderSearchInfo(); + SmallVector<Module::Header, 16> Headers; + for (StringRef Name : ModuleHeaders) { + const DirectoryLookup *CurDir = nullptr; + const FileEntry *FE = HS.LookupFile( + Name, SourceLocation(), /*Angled*/ false, nullptr, CurDir, + None, nullptr, nullptr, nullptr, nullptr, nullptr); + if (!FE) { + CI.getDiagnostics().Report(diag::err_module_header_file_not_found) + << Name; + continue; + } + Headers.push_back({Name, FE}); + } + HS.getModuleMap().createHeaderModule(CI.getLangOpts().CurrentModule, Headers); + + return GenerateModuleAction::BeginSourceFileAction(CI); +} + +std::unique_ptr<raw_pwrite_stream> +GenerateHeaderModuleAction::CreateOutputFile(CompilerInstance &CI, + StringRef InFile) { + return CI.createDefaultOutputFile(/*Binary=*/true, InFile, "pcm"); +} + SyntaxOnlyAction::~SyntaxOnlyAction() { } @@ -341,6 +405,8 @@ private: return "PriorTemplateArgumentSubstitution"; case CodeSynthesisContext::DefaultTemplateArgumentChecking: return "DefaultTemplateArgumentChecking"; + case CodeSynthesisContext::ExceptionSpecEvaluation: + return "ExceptionSpecEvaluation"; case CodeSynthesisContext::ExceptionSpecInstantiation: return "ExceptionSpecInstantiation"; case CodeSynthesisContext::DeclaringSpecialMember: @@ -599,6 +665,17 @@ namespace { return true; } + + /// Returns true if this \c ASTReaderListener wants to receive the + /// imports of the AST file via \c visitImport, false otherwise. + bool needsImportVisitation() const override { return true; } + + /// If needsImportVisitation returns \c true, this is called for each + /// AST file imported by this AST file. + void visitImport(StringRef ModuleName, StringRef Filename) override { + Out.indent(2) << "Imports module '" << ModuleName + << "': " << Filename.str() << "\n"; + } #undef DUMP_BOOLEAN }; } @@ -673,16 +750,6 @@ void DumpTokensAction::ExecuteAction() { } while (Tok.isNot(tok::eof)); } -void GeneratePTHAction::ExecuteAction() { - CompilerInstance &CI = getCompilerInstance(); - std::unique_ptr<raw_pwrite_stream> OS = - CI.createDefaultOutputFile(true, getCurrentFile()); - if (!OS) - return; - - CacheTokens(CI.getPreprocessor(), OS.get()); -} - void PreprocessOnlyAction::ExecuteAction() { Preprocessor &PP = getCompilerInstance().getPreprocessor(); @@ -742,7 +809,7 @@ void PrintPreprocessedAction::ExecuteAction() { } std::unique_ptr<raw_ostream> OS = - CI.createDefaultOutputFile(BinaryMode, getCurrentFile()); + CI.createDefaultOutputFile(BinaryMode, getCurrentFileOrBufferName()); if (!OS) return; // If we're preprocessing a module map, start by dumping the contents of the @@ -754,8 +821,6 @@ void PrintPreprocessedAction::ExecuteAction() { OS->write_escaped(Input.getFile()); (*OS) << "\"\n"; } - // FIXME: Include additional information here so that we don't need the - // original source files to exist on disk. getCurrentModule()->print(*OS); (*OS) << "#pragma clang module contents\n"; } diff --git a/lib/Frontend/InitHeaderSearch.cpp b/lib/Frontend/InitHeaderSearch.cpp index 8a70404629d3..ac3bb713ddcc 100644 --- a/lib/Frontend/InitHeaderSearch.cpp +++ b/lib/Frontend/InitHeaderSearch.cpp @@ -260,6 +260,7 @@ void InitHeaderSearch::AddDefaultCIncludePaths(const llvm::Triple &triple, switch (os) { case llvm::Triple::Linux: + case llvm::Triple::Hurd: case llvm::Triple::Solaris: llvm_unreachable("Include management is handled in the driver."); @@ -412,6 +413,7 @@ void InitHeaderSearch::AddDefaultCPlusPlusIncludePaths( switch (os) { case llvm::Triple::Linux: + case llvm::Triple::Hurd: case llvm::Triple::Solaris: llvm_unreachable("Include management is handled in the driver."); break; @@ -460,6 +462,7 @@ void InitHeaderSearch::AddDefaultIncludePaths(const LangOptions &Lang, break; // Everything else continues to use this routine's logic. case llvm::Triple::Linux: + case llvm::Triple::Hurd: case llvm::Triple::Solaris: return; @@ -473,22 +476,6 @@ void InitHeaderSearch::AddDefaultIncludePaths(const LangOptions &Lang, if (Lang.CPlusPlus && !Lang.AsmPreprocessor && HSOpts.UseStandardCXXIncludes && HSOpts.UseStandardSystemIncludes) { if (HSOpts.UseLibcxx) { - if (triple.isOSDarwin()) { - // On Darwin, libc++ may be installed alongside the compiler in - // include/c++/v1. - if (!HSOpts.ResourceDir.empty()) { - // Remove version from foo/lib/clang/version - StringRef NoVer = llvm::sys::path::parent_path(HSOpts.ResourceDir); - // Remove clang from foo/lib/clang - StringRef Lib = llvm::sys::path::parent_path(NoVer); - // Remove lib from foo/lib - SmallString<128> P = llvm::sys::path::parent_path(Lib); - - // Get foo/include/c++/v1 - llvm::sys::path::append(P, "include", "c++", "v1"); - AddUnmappedPath(P, CXXSystem, false); - } - } AddPath("/usr/include/c++/v1", CXXSystem, false); } else { AddDefaultCPlusPlusIncludePaths(Lang, triple, HSOpts); @@ -616,11 +603,11 @@ void InitHeaderSearch::Realize(const LangOptions &Lang) { for (auto &Include : IncludePath) if (Include.first == System || Include.first == ExternCSystem || - (!Lang.ObjC1 && !Lang.CPlusPlus && Include.first == CSystem) || - (/*FIXME !Lang.ObjC1 && */ Lang.CPlusPlus && + (!Lang.ObjC && !Lang.CPlusPlus && Include.first == CSystem) || + (/*FIXME !Lang.ObjC && */ Lang.CPlusPlus && Include.first == CXXSystem) || - (Lang.ObjC1 && !Lang.CPlusPlus && Include.first == ObjCSystem) || - (Lang.ObjC1 && Lang.CPlusPlus && Include.first == ObjCXXSystem)) + (Lang.ObjC && !Lang.CPlusPlus && Include.first == ObjCSystem) || + (Lang.ObjC && Lang.CPlusPlus && Include.first == ObjCXXSystem)) SearchList.push_back(Include.second); for (auto &Include : IncludePath) diff --git a/lib/Frontend/InitPreprocessor.cpp b/lib/Frontend/InitPreprocessor.cpp index e3f4f92b9d1e..66807b097d40 100644 --- a/lib/Frontend/InitPreprocessor.cpp +++ b/lib/Frontend/InitPreprocessor.cpp @@ -21,7 +21,6 @@ #include "clang/Frontend/FrontendOptions.h" #include "clang/Frontend/Utils.h" #include "clang/Lex/HeaderSearch.h" -#include "clang/Lex/PTHManager.h" #include "clang/Lex/Preprocessor.h" #include "clang/Lex/PreprocessorOptions.h" #include "clang/Serialization/ASTReader.h" @@ -76,23 +75,6 @@ static void AddImplicitIncludeMacros(MacroBuilder &Builder, StringRef File) { Builder.append("##"); // ##? } -/// AddImplicitIncludePTH - Add an implicit \#include using the original file -/// used to generate a PTH cache. -static void AddImplicitIncludePTH(MacroBuilder &Builder, Preprocessor &PP, - StringRef ImplicitIncludePTH) { - PTHManager *P = PP.getPTHManager(); - // Null check 'P' in the corner case where it couldn't be created. - const char *OriginalFile = P ? P->getOriginalSourceFile() : nullptr; - - if (!OriginalFile) { - PP.getDiagnostics().Report(diag::err_fe_pth_file_has_no_source_header) - << ImplicitIncludePTH; - return; - } - - AddImplicitInclude(Builder, OriginalFile); -} - /// Add an implicit \#include using the original file used to generate /// a PCH file. static void AddImplicitIncludePCH(MacroBuilder &Builder, Preprocessor &PP, @@ -421,7 +403,7 @@ static void InitializeStandardPredefinedMacros(const TargetInfo &TI, Builder.defineMacro("__STDC_UTF_16__", "1"); Builder.defineMacro("__STDC_UTF_32__", "1"); - if (LangOpts.ObjC1) + if (LangOpts.ObjC) Builder.defineMacro("__OBJC__"); // OpenCL v1.0/1.1 s6.9, v1.2/2.0 s6.10: Preprocessor Directives and Macros. @@ -553,20 +535,21 @@ static void InitializeCPlusPlusFeatureTestMacros(const LangOptions &LangOpts, Builder.defineMacro("__cpp_guaranteed_copy_elision", "201606L"); Builder.defineMacro("__cpp_nontype_template_parameter_auto", "201606L"); } - if (LangOpts.AlignedAllocation) + if (LangOpts.AlignedAllocation && !LangOpts.AlignedAllocationUnavailable) Builder.defineMacro("__cpp_aligned_new", "201606L"); if (LangOpts.RelaxedTemplateTemplateArgs) Builder.defineMacro("__cpp_template_template_args", "201611L"); + // C++20 features. + if (LangOpts.Char8) + Builder.defineMacro("__cpp_char8_t", "201811L"); + Builder.defineMacro("__cpp_impl_destroying_delete", "201806L"); + // TS features. if (LangOpts.ConceptsTS) Builder.defineMacro("__cpp_experimental_concepts", "1L"); if (LangOpts.CoroutinesTS) Builder.defineMacro("__cpp_coroutines", "201703L"); - - // Potential future breaking changes. - if (LangOpts.Char8) - Builder.defineMacro("__cpp_char8_t", "201803L"); } static void InitializePredefinedMacros(const TargetInfo &TI, @@ -635,7 +618,7 @@ static void InitializePredefinedMacros(const TargetInfo &TI, if (!LangOpts.MSVCCompat && LangOpts.CPlusPlus11) Builder.defineMacro("__GXX_EXPERIMENTAL_CXX0X__"); - if (LangOpts.ObjC1) { + if (LangOpts.ObjC) { if (LangOpts.ObjCRuntime.isNonFragile()) { Builder.defineMacro("__OBJC2__"); @@ -699,7 +682,7 @@ static void InitializePredefinedMacros(const TargetInfo &TI, if (!LangOpts.NoConstantCFStrings) Builder.defineMacro("__CONSTANT_CFSTRINGS__"); - if (LangOpts.ObjC2) + if (LangOpts.ObjC) Builder.defineMacro("OBJC_NEW_PROPERTIES"); if (LangOpts.PascalStrings) @@ -1016,7 +999,7 @@ static void InitializePredefinedMacros(const TargetInfo &TI, Builder.defineMacro("__strong", "__attribute__((objc_gc(strong)))"); Builder.defineMacro("__autoreleasing", ""); Builder.defineMacro("__unsafe_unretained", ""); - } else if (LangOpts.ObjC1) { + } else if (LangOpts.ObjC) { Builder.defineMacro("__weak", "__attribute__((objc_ownership(weak)))"); Builder.defineMacro("__strong", "__attribute__((objc_ownership(strong)))"); Builder.defineMacro("__autoreleasing", @@ -1130,7 +1113,7 @@ void clang::InitializePreprocessor( // Install definitions to make Objective-C++ ARC work well with various // C++ Standard Library implementations. - if (LangOpts.ObjC1 && LangOpts.CPlusPlus && + if (LangOpts.ObjC && LangOpts.CPlusPlus && (LangOpts.ObjCAutoRefCount || LangOpts.ObjCWeak)) { switch (InitOpts.ObjCXXARCStandardLibrary) { case ARCXX_nolib: @@ -1177,8 +1160,6 @@ void clang::InitializePreprocessor( if (!InitOpts.ImplicitPCHInclude.empty()) AddImplicitIncludePCH(Builder, PP, PCHContainerRdr, InitOpts.ImplicitPCHInclude); - if (!InitOpts.ImplicitPTHInclude.empty()) - AddImplicitIncludePTH(Builder, PP, InitOpts.ImplicitPTHInclude); // Process -include directives. for (unsigned i = 0, e = InitOpts.Includes.size(); i != e; ++i) { diff --git a/lib/Frontend/ModuleDependencyCollector.cpp b/lib/Frontend/ModuleDependencyCollector.cpp index 25cad8be6d00..fa8efcc3b53c 100644 --- a/lib/Frontend/ModuleDependencyCollector.cpp +++ b/lib/Frontend/ModuleDependencyCollector.cpp @@ -156,10 +156,6 @@ void ModuleDependencyCollector::writeFileMap() { // allows crash reproducer scripts to work across machines. VFSWriter.setOverlayDir(VFSDir); - // Do not ignore non existent contents otherwise we might skip something - // that should have been collected here. - VFSWriter.setIgnoreNonExistentContents(false); - // Explicitly set case sensitivity for the YAML writer. For that, find out // the sensitivity at the path where the headers all collected to. VFSWriter.setCaseSensitivity(isCaseSensitivePath(VFSDir)); diff --git a/lib/Frontend/PCHContainerOperations.cpp b/lib/Frontend/PCHContainerOperations.cpp deleted file mode 100644 index 340e8ce63ff4..000000000000 --- a/lib/Frontend/PCHContainerOperations.cpp +++ /dev/null @@ -1,69 +0,0 @@ -//===--- Frontend/PCHContainerOperations.cpp - PCH Containers ---*- C++ -*-===// -// -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. -// -//===----------------------------------------------------------------------===// -// -// This file defines PCHContainerOperations and RawPCHContainerOperation. -// -//===----------------------------------------------------------------------===// - -#include "clang/Frontend/PCHContainerOperations.h" -#include "clang/AST/ASTConsumer.h" -#include "clang/Lex/ModuleLoader.h" -#include "llvm/Bitcode/BitstreamReader.h" -#include "llvm/Support/raw_ostream.h" -#include <utility> - -using namespace clang; - -PCHContainerWriter::~PCHContainerWriter() {} -PCHContainerReader::~PCHContainerReader() {} - -namespace { - -/// A PCHContainerGenerator that writes out the PCH to a flat file. -class RawPCHContainerGenerator : public ASTConsumer { - std::shared_ptr<PCHBuffer> Buffer; - std::unique_ptr<raw_pwrite_stream> OS; - -public: - RawPCHContainerGenerator(std::unique_ptr<llvm::raw_pwrite_stream> OS, - std::shared_ptr<PCHBuffer> Buffer) - : Buffer(std::move(Buffer)), OS(std::move(OS)) {} - - ~RawPCHContainerGenerator() override = default; - - void HandleTranslationUnit(ASTContext &Ctx) override { - if (Buffer->IsComplete) { - // Make sure it hits disk now. - *OS << Buffer->Data; - OS->flush(); - } - // Free the space of the temporary buffer. - llvm::SmallVector<char, 0> Empty; - Buffer->Data = std::move(Empty); - } -}; - -} // anonymous namespace - -std::unique_ptr<ASTConsumer> RawPCHContainerWriter::CreatePCHContainerGenerator( - CompilerInstance &CI, const std::string &MainFileName, - const std::string &OutputFileName, std::unique_ptr<llvm::raw_pwrite_stream> OS, - std::shared_ptr<PCHBuffer> Buffer) const { - return llvm::make_unique<RawPCHContainerGenerator>(std::move(OS), Buffer); -} - -StringRef -RawPCHContainerReader::ExtractPCH(llvm::MemoryBufferRef Buffer) const { - return Buffer.getBuffer(); -} - -PCHContainerOperations::PCHContainerOperations() { - registerWriter(llvm::make_unique<RawPCHContainerWriter>()); - registerReader(llvm::make_unique<RawPCHContainerReader>()); -} diff --git a/lib/Frontend/PrecompiledPreamble.cpp b/lib/Frontend/PrecompiledPreamble.cpp index 30ae2db26d86..1930af187e7a 100644 --- a/lib/Frontend/PrecompiledPreamble.cpp +++ b/lib/Frontend/PrecompiledPreamble.cpp @@ -14,7 +14,6 @@ #include "clang/Frontend/PrecompiledPreamble.h" #include "clang/AST/DeclObjC.h" #include "clang/Basic/TargetInfo.h" -#include "clang/Basic/VirtualFileSystem.h" #include "clang/Frontend/CompilerInstance.h" #include "clang/Frontend/CompilerInvocation.h" #include "clang/Frontend/FrontendActions.h" @@ -30,6 +29,7 @@ #include "llvm/Support/Mutex.h" #include "llvm/Support/MutexGuard.h" #include "llvm/Support/Process.h" +#include "llvm/Support/VirtualFileSystem.h" #include <limits> #include <utility> @@ -48,17 +48,17 @@ StringRef getInMemoryPreamblePath() { #endif } -IntrusiveRefCntPtr<vfs::FileSystem> +IntrusiveRefCntPtr<llvm::vfs::FileSystem> createVFSOverlayForPreamblePCH(StringRef PCHFilename, std::unique_ptr<llvm::MemoryBuffer> PCHBuffer, - IntrusiveRefCntPtr<vfs::FileSystem> VFS) { + IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS) { // We want only the PCH file from the real filesystem to be available, // so we create an in-memory VFS with just that and overlay it on top. - IntrusiveRefCntPtr<vfs::InMemoryFileSystem> PCHFS( - new vfs::InMemoryFileSystem()); + IntrusiveRefCntPtr<llvm::vfs::InMemoryFileSystem> PCHFS( + new llvm::vfs::InMemoryFileSystem()); PCHFS->addFile(PCHFilename, 0, std::move(PCHBuffer)); - IntrusiveRefCntPtr<vfs::OverlayFileSystem> Overlay( - new vfs::OverlayFileSystem(VFS)); + IntrusiveRefCntPtr<llvm::vfs::OverlayFileSystem> Overlay( + new llvm::vfs::OverlayFileSystem(VFS)); Overlay->pushOverlay(PCHFS); return Overlay; } @@ -232,14 +232,12 @@ PreambleBounds clang::ComputePreambleBounds(const LangOptions &LangOpts, llvm::ErrorOr<PrecompiledPreamble> PrecompiledPreamble::Build( const CompilerInvocation &Invocation, const llvm::MemoryBuffer *MainFileBuffer, PreambleBounds Bounds, - DiagnosticsEngine &Diagnostics, IntrusiveRefCntPtr<vfs::FileSystem> VFS, + DiagnosticsEngine &Diagnostics, + IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS, std::shared_ptr<PCHContainerOperations> PCHContainerOps, bool StoreInMemory, PreambleCallbacks &Callbacks) { assert(VFS && "VFS is null"); - if (!Bounds.Size) - return BuildPreambleError::PreambleIsEmpty; - auto PreambleInvocation = std::make_shared<CompilerInvocation>(Invocation); FrontendOptions &FrontendOpts = PreambleInvocation->getFrontendOpts(); PreprocessorOptions &PreprocessorOpts = @@ -413,7 +411,7 @@ std::size_t PrecompiledPreamble::getSize() const { bool PrecompiledPreamble::CanReuse(const CompilerInvocation &Invocation, const llvm::MemoryBuffer *MainFileBuffer, PreambleBounds Bounds, - vfs::FileSystem *VFS) const { + llvm::vfs::FileSystem *VFS) const { assert( Bounds.Size <= MainFileBuffer->getBufferSize() && @@ -423,17 +421,14 @@ bool PrecompiledPreamble::CanReuse(const CompilerInvocation &Invocation, PreprocessorOptions &PreprocessorOpts = PreambleInvocation->getPreprocessorOpts(); - if (!Bounds.Size) - return false; - // We've previously computed a preamble. Check whether we have the same // preamble now that we did before, and that there's enough space in // the main-file buffer within the precompiled preamble to fit the // new main file. if (PreambleBytes.size() != Bounds.Size || PreambleEndsAtStartOfLine != Bounds.PreambleEndsAtStartOfLine || - memcmp(PreambleBytes.data(), MainFileBuffer->getBufferStart(), - Bounds.Size) != 0) + !std::equal(PreambleBytes.begin(), PreambleBytes.end(), + MainFileBuffer->getBuffer().begin())) return false; // The preamble has not changed. We may be able to re-use the precompiled // preamble. @@ -443,7 +438,7 @@ bool PrecompiledPreamble::CanReuse(const CompilerInvocation &Invocation, // remapping or unsaved_files. std::map<llvm::sys::fs::UniqueID, PreambleFileHash> OverriddenFiles; for (const auto &R : PreprocessorOpts.RemappedFiles) { - vfs::Status Status; + llvm::vfs::Status Status; if (!moveOnNoError(VFS->status(R.second), Status)) { // If we can't stat the file we're remapping to, assume that something // horrible happened. @@ -455,7 +450,7 @@ bool PrecompiledPreamble::CanReuse(const CompilerInvocation &Invocation, } for (const auto &RB : PreprocessorOpts.RemappedFileBuffers) { - vfs::Status Status; + llvm::vfs::Status Status; if (!moveOnNoError(VFS->status(RB.first), Status)) return false; @@ -465,7 +460,7 @@ bool PrecompiledPreamble::CanReuse(const CompilerInvocation &Invocation, // Check whether anything has changed. for (const auto &F : FilesInPreamble) { - vfs::Status Status; + llvm::vfs::Status Status; if (!moveOnNoError(VFS->status(F.first()), Status)) { // If we can't stat the file, assume that something horrible happened. return false; @@ -491,14 +486,14 @@ bool PrecompiledPreamble::CanReuse(const CompilerInvocation &Invocation, } void PrecompiledPreamble::AddImplicitPreamble( - CompilerInvocation &CI, IntrusiveRefCntPtr<vfs::FileSystem> &VFS, + CompilerInvocation &CI, IntrusiveRefCntPtr<llvm::vfs::FileSystem> &VFS, llvm::MemoryBuffer *MainFileBuffer) const { PreambleBounds Bounds(PreambleBytes.size(), PreambleEndsAtStartOfLine); configurePreamble(Bounds, CI, VFS, MainFileBuffer); } void PrecompiledPreamble::OverridePreamble( - CompilerInvocation &CI, IntrusiveRefCntPtr<vfs::FileSystem> &VFS, + CompilerInvocation &CI, IntrusiveRefCntPtr<llvm::vfs::FileSystem> &VFS, llvm::MemoryBuffer *MainFileBuffer) const { auto Bounds = ComputePreambleBounds(*CI.getLangOpts(), MainFileBuffer, 0); configurePreamble(Bounds, CI, VFS, MainFileBuffer); @@ -686,7 +681,7 @@ PrecompiledPreamble::PreambleFileHash::createForMemoryBuffer( void PrecompiledPreamble::configurePreamble( PreambleBounds Bounds, CompilerInvocation &CI, - IntrusiveRefCntPtr<vfs::FileSystem> &VFS, + IntrusiveRefCntPtr<llvm::vfs::FileSystem> &VFS, llvm::MemoryBuffer *MainFileBuffer) const { assert(VFS); @@ -707,13 +702,14 @@ void PrecompiledPreamble::configurePreamble( void PrecompiledPreamble::setupPreambleStorage( const PCHStorage &Storage, PreprocessorOptions &PreprocessorOpts, - IntrusiveRefCntPtr<vfs::FileSystem> &VFS) { + IntrusiveRefCntPtr<llvm::vfs::FileSystem> &VFS) { if (Storage.getKind() == PCHStorage::Kind::TempFile) { const TempPCHFile &PCHFile = Storage.asFile(); PreprocessorOpts.ImplicitPCHInclude = PCHFile.getFilePath(); // Make sure we can access the PCH file even if we're using a VFS - IntrusiveRefCntPtr<vfs::FileSystem> RealFS = vfs::getRealFileSystem(); + IntrusiveRefCntPtr<llvm::vfs::FileSystem> RealFS = + llvm::vfs::getRealFileSystem(); auto PCHPath = PCHFile.getFilePath(); if (VFS == RealFS || VFS->exists(PCHPath)) return; @@ -748,8 +744,10 @@ std::unique_ptr<PPCallbacks> PreambleCallbacks::createPPCallbacks() { return nullptr; } +static llvm::ManagedStatic<BuildPreambleErrorCategory> BuildPreambleErrCategory; + std::error_code clang::make_error_code(BuildPreambleError Error) { - return std::error_code(static_cast<int>(Error), BuildPreambleErrorCategory()); + return std::error_code(static_cast<int>(Error), *BuildPreambleErrCategory); } const char *BuildPreambleErrorCategory::name() const noexcept { @@ -758,8 +756,6 @@ const char *BuildPreambleErrorCategory::name() const noexcept { std::string BuildPreambleErrorCategory::message(int condition) const { switch (static_cast<BuildPreambleError>(condition)) { - case BuildPreambleError::PreambleIsEmpty: - return "Preamble is empty"; case BuildPreambleError::CouldntCreateTempFile: return "Could not create temporary file for PCH"; case BuildPreambleError::CouldntCreateTargetInfo: diff --git a/lib/Frontend/PrintPreprocessedOutput.cpp b/lib/Frontend/PrintPreprocessedOutput.cpp index 69cd072ea57f..3b835985a54c 100644 --- a/lib/Frontend/PrintPreprocessedOutput.cpp +++ b/lib/Frontend/PrintPreprocessedOutput.cpp @@ -750,6 +750,11 @@ static void PrintPreprocessedTokens(Preprocessor &PP, Token &Tok, reinterpret_cast<Module *>(Tok.getAnnotationValue())); PP.Lex(Tok); continue; + } else if (Tok.isAnnotation()) { + // Ignore annotation tokens created by pragmas - the pragmas themselves + // will be reproduced in the preprocessed output. + PP.Lex(Tok); + continue; } else if (IdentifierInfo *II = Tok.getIdentifierInfo()) { OS << II->getName(); } else if (Tok.isLiteral() && !Tok.needsCleaning() && diff --git a/lib/Frontend/Rewrite/FrontendActions.cpp b/lib/Frontend/Rewrite/FrontendActions.cpp index fa17b3e7cb3f..bcf6d215c998 100644 --- a/lib/Frontend/Rewrite/FrontendActions.cpp +++ b/lib/Frontend/Rewrite/FrontendActions.cpp @@ -181,7 +181,7 @@ RewriteObjCAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) { void RewriteMacrosAction::ExecuteAction() { CompilerInstance &CI = getCompilerInstance(); std::unique_ptr<raw_ostream> OS = - CI.createDefaultOutputFile(true, getCurrentFile()); + CI.createDefaultOutputFile(true, getCurrentFileOrBufferName()); if (!OS) return; RewriteMacrosInInput(CI.getPreprocessor(), OS.get()); @@ -190,7 +190,7 @@ void RewriteMacrosAction::ExecuteAction() { void RewriteTestAction::ExecuteAction() { CompilerInstance &CI = getCompilerInstance(); std::unique_ptr<raw_ostream> OS = - CI.createDefaultOutputFile(false, getCurrentFile()); + CI.createDefaultOutputFile(false, getCurrentFileOrBufferName()); if (!OS) return; DoRewriteTest(CI.getPreprocessor(), OS.get()); @@ -265,7 +265,8 @@ public: bool RewriteIncludesAction::BeginSourceFileAction(CompilerInstance &CI) { if (!OutputStream) { - OutputStream = CI.createDefaultOutputFile(true, getCurrentFile()); + OutputStream = + CI.createDefaultOutputFile(true, getCurrentFileOrBufferName()); if (!OutputStream) return false; } diff --git a/lib/Frontend/Rewrite/InclusionRewriter.cpp b/lib/Frontend/Rewrite/InclusionRewriter.cpp index 1631eccd7013..2e7baa3d9581 100644 --- a/lib/Frontend/Rewrite/InclusionRewriter.cpp +++ b/lib/Frontend/Rewrite/InclusionRewriter.cpp @@ -586,6 +586,7 @@ void InclusionRewriter::Process(FileID FileId, LocalEOL, Line, /*EnsureNewline=*/ true); WriteLineInfo(FileName, Line, FileType); RawLex.SetKeepWhitespaceMode(false); + break; } default: break; diff --git a/lib/Frontend/Rewrite/RewriteModernObjC.cpp b/lib/Frontend/Rewrite/RewriteModernObjC.cpp index 36382e1438d5..10ca9a785699 100644 --- a/lib/Frontend/Rewrite/RewriteModernObjC.cpp +++ b/lib/Frontend/Rewrite/RewriteModernObjC.cpp @@ -265,8 +265,8 @@ namespace { // Measure the old text. int Size = Rewrite.getRangeSize(SrcRange); if (Size == -1) { - Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag) - << Old->getSourceRange(); + Diags.Report(Context->getFullLoc(Old->getBeginLoc()), RewriteFailedDiag) + << Old->getSourceRange(); return; } // Get the new text. @@ -282,8 +282,8 @@ namespace { } if (SilenceRewriteMacroWarning) return; - Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag) - << Old->getSourceRange(); + Diags.Report(Context->getFullLoc(Old->getBeginLoc()), RewriteFailedDiag) + << Old->getSourceRange(); } void InsertText(SourceLocation Loc, StringRef Str, @@ -541,7 +541,7 @@ namespace { // FIXME: This predicate seems like it would be useful to add to ASTContext. bool isObjCType(QualType T) { - if (!LangOpts.ObjC1 && !LangOpts.ObjC2) + if (!LangOpts.ObjC) return false; QualType OCT = Context->getCanonicalType(T).getUnqualifiedType(); @@ -748,11 +748,11 @@ void RewriteModernObjC::HandleTopLevelSingleDecl(Decl *D) { if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>((*DI))) { if (!IFace->isThisDeclarationADefinition()) { SmallVector<Decl *, 8> DG; - SourceLocation StartLoc = IFace->getLocStart(); + SourceLocation StartLoc = IFace->getBeginLoc(); do { if (isa<ObjCInterfaceDecl>(*DI) && !cast<ObjCInterfaceDecl>(*DI)->isThisDeclarationADefinition() && - StartLoc == (*DI)->getLocStart()) + StartLoc == (*DI)->getBeginLoc()) DG.push_back(*DI); else break; @@ -773,11 +773,11 @@ void RewriteModernObjC::HandleTopLevelSingleDecl(Decl *D) { if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>((*DI))) { if (!Proto->isThisDeclarationADefinition()) { SmallVector<Decl *, 8> DG; - SourceLocation StartLoc = Proto->getLocStart(); + SourceLocation StartLoc = Proto->getBeginLoc(); do { if (isa<ObjCProtocolDecl>(*DI) && !cast<ObjCProtocolDecl>(*DI)->isThisDeclarationADefinition() && - StartLoc == (*DI)->getLocStart()) + StartLoc == (*DI)->getBeginLoc()) DG.push_back(*DI); else break; @@ -923,17 +923,16 @@ void RewriteModernObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID, static bool objcSetPropertyDefined = false; SourceLocation startGetterSetterLoc; - if (PID->getLocStart().isValid()) { - SourceLocation startLoc = PID->getLocStart(); + if (PID->getBeginLoc().isValid()) { + SourceLocation startLoc = PID->getBeginLoc(); InsertText(startLoc, "// "); const char *startBuf = SM->getCharacterData(startLoc); assert((*startBuf == '@') && "bogus @synthesize location"); const char *semiBuf = strchr(startBuf, ';'); assert((*semiBuf == ';') && "@synthesize: can't find ';'"); startGetterSetterLoc = startLoc.getLocWithOffset(semiBuf-startBuf+1); - } - else - startGetterSetterLoc = IMD ? IMD->getLocEnd() : CID->getLocEnd(); + } else + startGetterSetterLoc = IMD ? IMD->getEndLoc() : CID->getEndLoc(); if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic) return; // FIXME: is this correct? @@ -1061,7 +1060,7 @@ static void RewriteOneForwardClassDecl(ObjCInterfaceDecl *ForwardDecl, void RewriteModernObjC::RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl, const std::string &typedefString) { - SourceLocation startLoc = ClassDecl->getLocStart(); + SourceLocation startLoc = ClassDecl->getBeginLoc(); const char *startBuf = SM->getCharacterData(startLoc); const char *semiPtr = strchr(startBuf, ';'); // Replace the @class with typedefs corresponding to the classes. @@ -1109,8 +1108,8 @@ void RewriteModernObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) { // nothing to rewrite. if (Method->isImplicit()) return; - SourceLocation LocStart = Method->getLocStart(); - SourceLocation LocEnd = Method->getLocEnd(); + SourceLocation LocStart = Method->getBeginLoc(); + SourceLocation LocEnd = Method->getEndLoc(); if (SM->getExpansionLineNumber(LocEnd) > SM->getExpansionLineNumber(LocStart)) { @@ -1129,7 +1128,7 @@ void RewriteModernObjC::RewriteProperty(ObjCPropertyDecl *prop) { } void RewriteModernObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) { - SourceLocation LocStart = CatDecl->getLocStart(); + SourceLocation LocStart = CatDecl->getBeginLoc(); // FIXME: handle category headers that are declared across multiple lines. if (CatDecl->getIvarRBraceLoc().isValid()) { @@ -1154,7 +1153,7 @@ void RewriteModernObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) { } void RewriteModernObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) { - SourceLocation LocStart = PDecl->getLocStart(); + SourceLocation LocStart = PDecl->getBeginLoc(); assert(PDecl->isThisDeclarationADefinition()); // FIXME: handle protocol headers that are declared across multiple lines. @@ -1189,7 +1188,7 @@ void RewriteModernObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) { } void RewriteModernObjC::RewriteForwardProtocolDecl(DeclGroupRef D) { - SourceLocation LocStart = (*D.begin())->getLocStart(); + SourceLocation LocStart = (*D.begin())->getBeginLoc(); if (LocStart.isInvalid()) llvm_unreachable("Invalid SourceLocation"); // FIXME: handle forward protocol that are declared across multiple lines. @@ -1198,7 +1197,7 @@ void RewriteModernObjC::RewriteForwardProtocolDecl(DeclGroupRef D) { void RewriteModernObjC::RewriteForwardProtocolDecl(const SmallVectorImpl<Decl *> &DG) { - SourceLocation LocStart = DG[0]->getLocStart(); + SourceLocation LocStart = DG[0]->getBeginLoc(); if (LocStart.isInvalid()) llvm_unreachable("Invalid SourceLocation"); // FIXME: handle forward protocol that are declared across multiple lines. @@ -1338,21 +1337,21 @@ void RewriteModernObjC::RewriteImplementationDecl(Decl *OID) { if (IMD) { if (IMD->getIvarRBraceLoc().isValid()) { - ReplaceText(IMD->getLocStart(), 1, "/** "); + ReplaceText(IMD->getBeginLoc(), 1, "/** "); ReplaceText(IMD->getIvarRBraceLoc(), 1, "**/ "); } else { - InsertText(IMD->getLocStart(), "// "); + InsertText(IMD->getBeginLoc(), "// "); } } else - InsertText(CID->getLocStart(), "// "); + InsertText(CID->getBeginLoc(), "// "); for (auto *OMD : IMD ? IMD->instance_methods() : CID->instance_methods()) { std::string ResultStr; RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr); - SourceLocation LocStart = OMD->getLocStart(); - SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart(); + SourceLocation LocStart = OMD->getBeginLoc(); + SourceLocation LocEnd = OMD->getCompoundBody()->getBeginLoc(); const char *startBuf = SM->getCharacterData(LocStart); const char *endBuf = SM->getCharacterData(LocEnd); @@ -1362,8 +1361,8 @@ void RewriteModernObjC::RewriteImplementationDecl(Decl *OID) { for (auto *OMD : IMD ? IMD->class_methods() : CID->class_methods()) { std::string ResultStr; RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr); - SourceLocation LocStart = OMD->getLocStart(); - SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart(); + SourceLocation LocStart = OMD->getBeginLoc(); + SourceLocation LocEnd = OMD->getCompoundBody()->getBeginLoc(); const char *startBuf = SM->getCharacterData(LocStart); const char *endBuf = SM->getCharacterData(LocEnd); @@ -1372,7 +1371,7 @@ void RewriteModernObjC::RewriteImplementationDecl(Decl *OID) { for (auto *I : IMD ? IMD->property_impls() : CID->property_impls()) RewritePropertyImplDecl(I, IMD, CID); - InsertText(IMD ? IMD->getLocEnd() : CID->getLocEnd(), "// "); + InsertText(IMD ? IMD->getEndLoc() : CID->getEndLoc(), "// "); } void RewriteModernObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) { @@ -1608,7 +1607,7 @@ Stmt *RewriteModernObjC::RewriteBreakStmt(BreakStmt *S) { // replace break with goto __break_label std::string buf; - SourceLocation startLoc = S->getLocStart(); + SourceLocation startLoc = S->getBeginLoc(); buf = "goto __break_label_"; buf += utostr(ObjCBcLabelNo.back()); ReplaceText(startLoc, strlen("break"), buf); @@ -1638,7 +1637,7 @@ Stmt *RewriteModernObjC::RewriteContinueStmt(ContinueStmt *S) { // replace continue with goto __continue_label std::string buf; - SourceLocation startLoc = S->getLocStart(); + SourceLocation startLoc = S->getBeginLoc(); buf = "goto __continue_label_"; buf += utostr(ObjCBcLabelNo.back()); ReplaceText(startLoc, strlen("continue"), buf); @@ -1686,7 +1685,7 @@ Stmt *RewriteModernObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S, assert(!ObjCBcLabelNo.empty() && "ObjCForCollectionStmt - Label No stack empty"); - SourceLocation startLoc = S->getLocStart(); + SourceLocation startLoc = S->getBeginLoc(); const char *startBuf = SM->getCharacterData(startLoc); StringRef elementName; std::string elementTypeAsString; @@ -1860,7 +1859,7 @@ static void Write_RethrowObject(std::string &buf) { /// Stmt *RewriteModernObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) { // Get the start location and compute the semi location. - SourceLocation startLoc = S->getLocStart(); + SourceLocation startLoc = S->getBeginLoc(); const char *startBuf = SM->getCharacterData(startLoc); assert((*startBuf == '@') && "bogus @synchronized location"); @@ -1880,20 +1879,20 @@ Stmt *RewriteModernObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) buf += "\n\tid sync_exit;"; buf += "\n\t} _sync_exit(_sync_obj);\n"; - // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since + // We can't use S->getSynchExpr()->getEndLoc() to find the end location, since // the sync expression is typically a message expression that's already // been rewritten! (which implies the SourceLocation's are invalid). - SourceLocation RParenExprLoc = S->getSynchBody()->getLocStart(); + SourceLocation RParenExprLoc = S->getSynchBody()->getBeginLoc(); const char *RParenExprLocBuf = SM->getCharacterData(RParenExprLoc); while (*RParenExprLocBuf != ')') RParenExprLocBuf--; RParenExprLoc = startLoc.getLocWithOffset(RParenExprLocBuf-startBuf); - SourceLocation LBranceLoc = S->getSynchBody()->getLocStart(); + SourceLocation LBranceLoc = S->getSynchBody()->getBeginLoc(); const char *LBraceLocBuf = SM->getCharacterData(LBranceLoc); assert (*LBraceLocBuf == '{'); ReplaceText(RParenExprLoc, (LBraceLocBuf - SM->getCharacterData(RParenExprLoc) + 1), buf); - SourceLocation startRBraceLoc = S->getSynchBody()->getLocEnd(); + SourceLocation startRBraceLoc = S->getSynchBody()->getEndLoc(); assert((*SM->getCharacterData(startRBraceLoc) == '}') && "bogus @synchronized block"); @@ -1915,7 +1914,7 @@ void RewriteModernObjC::WarnAboutReturnGotoStmts(Stmt *S) WarnAboutReturnGotoStmts(SubStmt); if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) { - Diags.Report(Context->getFullLoc(S->getLocStart()), + Diags.Report(Context->getFullLoc(S->getBeginLoc()), TryFinallyContainsReturnDiag); } } @@ -1923,7 +1922,7 @@ void RewriteModernObjC::WarnAboutReturnGotoStmts(Stmt *S) Stmt *RewriteModernObjC::RewriteObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S) { SourceLocation startLoc = S->getAtLoc(); ReplaceText(startLoc, strlen("@autoreleasepool"), "/* @autoreleasepool */"); - ReplaceText(S->getSubStmt()->getLocStart(), 1, + ReplaceText(S->getSubStmt()->getBeginLoc(), 1, "{ __AtAutoreleasePool __autoreleasepool; "); return nullptr; @@ -1944,7 +1943,7 @@ Stmt *RewriteModernObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) { } } // Get the start location and compute the semi location. - SourceLocation startLoc = S->getLocStart(); + SourceLocation startLoc = S->getBeginLoc(); const char *startBuf = SM->getCharacterData(startLoc); assert((*startBuf == '@') && "bogus @try location"); @@ -1958,7 +1957,7 @@ Stmt *RewriteModernObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) { ObjCAtCatchStmt *Catch = S->getCatchStmt(I); VarDecl *catchDecl = Catch->getCatchParamDecl(); - startLoc = Catch->getLocStart(); + startLoc = Catch->getBeginLoc(); bool AtRemoved = false; if (catchDecl) { QualType t = catchDecl->getType(); @@ -1967,7 +1966,7 @@ Stmt *RewriteModernObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) { ObjCInterfaceDecl *IDecl = Ptr->getObjectType()->getInterface(); if (IDecl) { std::string Result; - ConvertSourceLocationToLineDirective(Catch->getLocStart(), Result); + ConvertSourceLocationToLineDirective(Catch->getBeginLoc(), Result); startBuf = SM->getCharacterData(startLoc); assert((*startBuf == '@') && "bogus @catch location"); @@ -1988,7 +1987,7 @@ Stmt *RewriteModernObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) { Result += "_"; Result += catchDecl->getNameAsString(); Result += "; "; - SourceLocation lBraceLoc = Catch->getCatchBody()->getLocStart(); + SourceLocation lBraceLoc = Catch->getCatchBody()->getBeginLoc(); ReplaceText(lBraceLoc, 1, Result); AtRemoved = true; } @@ -2001,7 +2000,7 @@ Stmt *RewriteModernObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) { } if (finalStmt) { buf.clear(); - SourceLocation FinallyLoc = finalStmt->getLocStart(); + SourceLocation FinallyLoc = finalStmt->getBeginLoc(); if (noCatch) { ConvertSourceLocationToLineDirective(FinallyLoc, buf); @@ -2013,15 +2012,15 @@ Stmt *RewriteModernObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) { buf += "catch (id e) {_rethrow = e;}\n"; } - SourceLocation startFinalLoc = finalStmt->getLocStart(); + SourceLocation startFinalLoc = finalStmt->getBeginLoc(); ReplaceText(startFinalLoc, 8, buf); Stmt *body = finalStmt->getFinallyBody(); - SourceLocation startFinalBodyLoc = body->getLocStart(); + SourceLocation startFinalBodyLoc = body->getBeginLoc(); buf.clear(); Write_RethrowObject(buf); ReplaceText(startFinalBodyLoc, 1, buf); - SourceLocation endFinalBodyLoc = body->getLocEnd(); + SourceLocation endFinalBodyLoc = body->getEndLoc(); ReplaceText(endFinalBodyLoc, 1, "}\n}"); // Now check for any return/continue/go statements within the @try. WarnAboutReturnGotoStmts(S->getTryBody()); @@ -2035,7 +2034,7 @@ Stmt *RewriteModernObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) { // been rewritten! (which implies the SourceLocation's are invalid). Stmt *RewriteModernObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) { // Get the start location and compute the semi location. - SourceLocation startLoc = S->getLocStart(); + SourceLocation startLoc = S->getBeginLoc(); const char *startBuf = SM->getCharacterData(startLoc); assert((*startBuf == '@') && "bogus @throw location"); @@ -2052,7 +2051,7 @@ Stmt *RewriteModernObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) { assert((*wBuf == 'w') && "@throw: can't find 'w'"); ReplaceText(startLoc, wBuf-startBuf+1, buf); - SourceLocation endLoc = S->getLocEnd(); + SourceLocation endLoc = S->getEndLoc(); const char *endBuf = SM->getCharacterData(endLoc); const char *semiBuf = strchr(endBuf, ';'); assert((*semiBuf == ';') && "@throw: can't find ';'"); @@ -2097,8 +2096,8 @@ RewriteModernObjC::SynthesizeCallToFunctionDecl(FunctionDecl *FD, QualType msgSendType = FD->getType(); // Create a reference to the objc_msgSend() declaration. - DeclRefExpr *DRE = - new (Context) DeclRefExpr(FD, false, msgSendType, VK_LValue, SourceLocation()); + DeclRefExpr *DRE = new (Context) DeclRefExpr(*Context, FD, false, msgSendType, + VK_LValue, SourceLocation()); // Now, we cast the reference to a pointer to the objc_msgSend type. QualType pToFunc = Context->getPointerType(msgSendType); @@ -2108,9 +2107,8 @@ RewriteModernObjC::SynthesizeCallToFunctionDecl(FunctionDecl *FD, const FunctionType *FT = msgSendType->getAs<FunctionType>(); - CallExpr *Exp = new (Context) CallExpr(*Context, ICE, Args, - FT->getCallResultType(*Context), - VK_RValue, EndLoc); + CallExpr *Exp = CallExpr::Create( + *Context, ICE, Args, FT->getCallResultType(*Context), VK_RValue, EndLoc); return Exp; } @@ -2170,8 +2168,8 @@ void RewriteModernObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) { Loc = ECE->getLParenLoc(); EndLoc = ECE->getRParenLoc(); } else { - Loc = E->getLocStart(); - EndLoc = E->getLocEnd(); + Loc = E->getBeginLoc(); + EndLoc = E->getEndLoc(); } // This will defend against trying to rewrite synthesized expressions. if (Loc.isInvalid() || EndLoc.isInvalid()) @@ -2296,13 +2294,13 @@ void RewriteModernObjC::RewriteTypeOfDecl(VarDecl *ND) { if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) startLoc = ECE->getLParenLoc(); else - startLoc = E->getLocStart(); + startLoc = E->getBeginLoc(); startLoc = SM->getExpansionLoc(startLoc); const char *endBuf = SM->getCharacterData(startLoc); ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString); } else { - SourceLocation X = ND->getLocEnd(); + SourceLocation X = ND->getEndLoc(); X = SM->getExpansionLoc(X); const char *endBuf = SM->getCharacterData(X); ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString); @@ -2585,12 +2583,11 @@ Stmt *RewriteModernObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) { VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(), SourceLocation(), &Context->Idents.get(S), strType, nullptr, SC_Static); - DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, false, strType, VK_LValue, - SourceLocation()); - Expr *Unop = new (Context) UnaryOperator(DRE, UO_AddrOf, - Context->getPointerType(DRE->getType()), - VK_RValue, OK_Ordinary, - SourceLocation(), false); + DeclRefExpr *DRE = new (Context) + DeclRefExpr(*Context, NewVD, false, strType, VK_LValue, SourceLocation()); + Expr *Unop = new (Context) + UnaryOperator(DRE, UO_AddrOf, Context->getPointerType(DRE->getType()), + VK_RValue, OK_Ordinary, SourceLocation(), false); // cast to NSConstantString * CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(), CK_CPointerToObjCPointerCast, Unop); @@ -2625,8 +2622,8 @@ Stmt *RewriteModernObjC::RewriteObjCBoxedExpr(ObjCBoxedExpr *Exp) { SynthGetClassFunctionDecl(); FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl; - SourceLocation StartLoc = Exp->getLocStart(); - SourceLocation EndLoc = Exp->getLocEnd(); + SourceLocation StartLoc = Exp->getBeginLoc(); + SourceLocation EndLoc = Exp->getEndLoc(); // Synthesize a call to objc_msgSend(). SmallVector<Expr*, 4> MsgExprs; @@ -2674,12 +2671,11 @@ Stmt *RewriteModernObjC::RewriteObjCBoxedExpr(ObjCBoxedExpr *Exp) { QualType msgSendType = MsgSendFlavor->getType(); // Create a reference to the objc_msgSend() declaration. - DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType, - VK_LValue, SourceLocation()); + DeclRefExpr *DRE = new (Context) DeclRefExpr( + *Context, MsgSendFlavor, false, msgSendType, VK_LValue, SourceLocation()); - CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, - Context->getPointerType(Context->VoidTy), - CK_BitCast, DRE); + CastExpr *cast = NoTypeInfoCStyleCastExpr( + Context, Context->getPointerType(Context->VoidTy), CK_BitCast, DRE); // Now do the "normal" pointer to function cast. QualType castType = @@ -2692,8 +2688,8 @@ Stmt *RewriteModernObjC::RewriteObjCBoxedExpr(ObjCBoxedExpr *Exp) { ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast); const FunctionType *FT = msgSendType->getAs<FunctionType>(); - CallExpr *CE = new (Context) - CallExpr(*Context, PE, MsgExprs, FT->getReturnType(), VK_RValue, EndLoc); + CallExpr *CE = CallExpr::Create(*Context, PE, MsgExprs, FT->getReturnType(), + VK_RValue, EndLoc); ReplaceStmt(Exp, CE); return CE; } @@ -2709,8 +2705,8 @@ Stmt *RewriteModernObjC::RewriteObjCArrayLiteralExpr(ObjCArrayLiteral *Exp) { SynthGetClassFunctionDecl(); FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl; - SourceLocation StartLoc = Exp->getLocStart(); - SourceLocation EndLoc = Exp->getLocEnd(); + SourceLocation StartLoc = Exp->getBeginLoc(); + SourceLocation EndLoc = Exp->getEndLoc(); // Build the expression: __NSContainer_literal(int, ...).arr QualType IntQT = Context->IntTy; @@ -2718,9 +2714,8 @@ Stmt *RewriteModernObjC::RewriteObjCArrayLiteralExpr(ObjCArrayLiteral *Exp) { getSimpleFunctionType(Context->VoidTy, IntQT, true); std::string NSArrayFName("__NSContainer_literal"); FunctionDecl *NSArrayFD = SynthBlockInitFunctionDecl(NSArrayFName); - DeclRefExpr *NSArrayDRE = - new (Context) DeclRefExpr(NSArrayFD, false, NSArrayFType, VK_RValue, - SourceLocation()); + DeclRefExpr *NSArrayDRE = new (Context) DeclRefExpr( + *Context, NSArrayFD, false, NSArrayFType, VK_RValue, SourceLocation()); SmallVector<Expr*, 16> InitExprs; unsigned NumElements = Exp->getNumElements(); @@ -2733,8 +2728,8 @@ Stmt *RewriteModernObjC::RewriteObjCArrayLiteralExpr(ObjCArrayLiteral *Exp) { for (unsigned i = 0; i < NumElements; i++) InitExprs.push_back(Exp->getElement(i)); Expr *NSArrayCallExpr = - new (Context) CallExpr(*Context, NSArrayDRE, InitExprs, - NSArrayFType, VK_LValue, SourceLocation()); + CallExpr::Create(*Context, NSArrayDRE, InitExprs, NSArrayFType, VK_LValue, + SourceLocation()); FieldDecl *ARRFD = FieldDecl::Create(*Context, nullptr, SourceLocation(), SourceLocation(), @@ -2797,12 +2792,11 @@ Stmt *RewriteModernObjC::RewriteObjCArrayLiteralExpr(ObjCArrayLiteral *Exp) { QualType msgSendType = MsgSendFlavor->getType(); // Create a reference to the objc_msgSend() declaration. - DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType, - VK_LValue, SourceLocation()); + DeclRefExpr *DRE = new (Context) DeclRefExpr( + *Context, MsgSendFlavor, false, msgSendType, VK_LValue, SourceLocation()); - CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, - Context->getPointerType(Context->VoidTy), - CK_BitCast, DRE); + CastExpr *cast = NoTypeInfoCStyleCastExpr( + Context, Context->getPointerType(Context->VoidTy), CK_BitCast, DRE); // Now do the "normal" pointer to function cast. QualType castType = @@ -2815,8 +2809,8 @@ Stmt *RewriteModernObjC::RewriteObjCArrayLiteralExpr(ObjCArrayLiteral *Exp) { ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast); const FunctionType *FT = msgSendType->getAs<FunctionType>(); - CallExpr *CE = new (Context) - CallExpr(*Context, PE, MsgExprs, FT->getReturnType(), VK_RValue, EndLoc); + CallExpr *CE = CallExpr::Create(*Context, PE, MsgExprs, FT->getReturnType(), + VK_RValue, EndLoc); ReplaceStmt(Exp, CE); return CE; } @@ -2832,8 +2826,8 @@ Stmt *RewriteModernObjC::RewriteObjCDictionaryLiteralExpr(ObjCDictionaryLiteral SynthGetClassFunctionDecl(); FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl; - SourceLocation StartLoc = Exp->getLocStart(); - SourceLocation EndLoc = Exp->getLocEnd(); + SourceLocation StartLoc = Exp->getBeginLoc(); + SourceLocation EndLoc = Exp->getEndLoc(); // Build the expression: __NSContainer_literal(int, ...).arr QualType IntQT = Context->IntTy; @@ -2841,9 +2835,8 @@ Stmt *RewriteModernObjC::RewriteObjCDictionaryLiteralExpr(ObjCDictionaryLiteral getSimpleFunctionType(Context->VoidTy, IntQT, true); std::string NSDictFName("__NSContainer_literal"); FunctionDecl *NSDictFD = SynthBlockInitFunctionDecl(NSDictFName); - DeclRefExpr *NSDictDRE = - new (Context) DeclRefExpr(NSDictFD, false, NSDictFType, VK_RValue, - SourceLocation()); + DeclRefExpr *NSDictDRE = new (Context) DeclRefExpr( + *Context, NSDictFD, false, NSDictFType, VK_RValue, SourceLocation()); SmallVector<Expr*, 16> KeyExprs; SmallVector<Expr*, 16> ValueExprs; @@ -2864,8 +2857,8 @@ Stmt *RewriteModernObjC::RewriteObjCDictionaryLiteralExpr(ObjCDictionaryLiteral // (const id [])objects Expr *NSValueCallExpr = - new (Context) CallExpr(*Context, NSDictDRE, ValueExprs, - NSDictFType, VK_LValue, SourceLocation()); + CallExpr::Create(*Context, NSDictDRE, ValueExprs, NSDictFType, VK_LValue, + SourceLocation()); FieldDecl *ARRFD = FieldDecl::Create(*Context, nullptr, SourceLocation(), SourceLocation(), @@ -2883,9 +2876,8 @@ Stmt *RewriteModernObjC::RewriteObjCDictionaryLiteralExpr(ObjCDictionaryLiteral CK_BitCast, DictLiteralValueME); // (const id <NSCopying> [])keys - Expr *NSKeyCallExpr = - new (Context) CallExpr(*Context, NSDictDRE, KeyExprs, - NSDictFType, VK_LValue, SourceLocation()); + Expr *NSKeyCallExpr = CallExpr::Create( + *Context, NSDictDRE, KeyExprs, NSDictFType, VK_LValue, SourceLocation()); MemberExpr *DictLiteralKeyME = new (Context) MemberExpr(NSKeyCallExpr, false, SourceLocation(), ARRFD, @@ -2951,12 +2943,11 @@ Stmt *RewriteModernObjC::RewriteObjCDictionaryLiteralExpr(ObjCDictionaryLiteral QualType msgSendType = MsgSendFlavor->getType(); // Create a reference to the objc_msgSend() declaration. - DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType, - VK_LValue, SourceLocation()); + DeclRefExpr *DRE = new (Context) DeclRefExpr( + *Context, MsgSendFlavor, false, msgSendType, VK_LValue, SourceLocation()); - CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, - Context->getPointerType(Context->VoidTy), - CK_BitCast, DRE); + CastExpr *cast = NoTypeInfoCStyleCastExpr( + Context, Context->getPointerType(Context->VoidTy), CK_BitCast, DRE); // Now do the "normal" pointer to function cast. QualType castType = @@ -2969,8 +2960,8 @@ Stmt *RewriteModernObjC::RewriteObjCDictionaryLiteralExpr(ObjCDictionaryLiteral ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast); const FunctionType *FT = msgSendType->getAs<FunctionType>(); - CallExpr *CE = new (Context) - CallExpr(*Context, PE, MsgExprs, FT->getReturnType(), VK_RValue, EndLoc); + CallExpr *CE = CallExpr::Create(*Context, PE, MsgExprs, FT->getReturnType(), + VK_RValue, EndLoc); ReplaceStmt(Exp, CE); return CE; } @@ -3070,7 +3061,7 @@ void RewriteModernObjC::RewriteLineDirective(const Decl *D) { LineString += "\""; else LineString += "\"\n"; - Location = D->getLocStart(); + Location = D->getBeginLoc(); if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { if (FD->isExternC() && !FD->isMain()) { const DeclContext *DC = FD->getDeclContext(); @@ -3100,10 +3091,9 @@ Expr *RewriteModernObjC::SynthMsgSendStretCallExpr(FunctionDecl *MsgSendStretFla SmallVectorImpl<Expr*> &MsgExprs, ObjCMethodDecl *Method) { // Now do the "normal" pointer to function cast. - QualType castType = getSimpleFunctionType(returnType, ArgTypes, - Method ? Method->isVariadic() - : false); - castType = Context->getPointerType(castType); + QualType FuncType = getSimpleFunctionType( + returnType, ArgTypes, Method ? Method->isVariadic() : false); + QualType castType = Context->getPointerType(FuncType); // build type for containing the objc_msgSend_stret object. static unsigned stretCount=0; @@ -3169,7 +3159,7 @@ Expr *RewriteModernObjC::SynthMsgSendStretCallExpr(FunctionDecl *MsgSendStretFla FunLocStart = getFunctionSourceLocation(*this, CurFunctionDef); else { assert(CurMethodDef && "SynthMsgSendStretCallExpr - CurMethodDef is null"); - FunLocStart = CurMethodDef->getLocStart(); + FunLocStart = CurMethodDef->getBeginLoc(); } InsertText(FunLocStart, str); @@ -3177,13 +3167,13 @@ Expr *RewriteModernObjC::SynthMsgSendStretCallExpr(FunctionDecl *MsgSendStretFla // AST for __Stretn(receiver, args).s; IdentifierInfo *ID = &Context->Idents.get(name); - FunctionDecl *FD = FunctionDecl::Create(*Context, TUDecl, SourceLocation(), - SourceLocation(), ID, castType, - nullptr, SC_Extern, false, false); - DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, false, castType, VK_RValue, - SourceLocation()); - CallExpr *STCE = new (Context) CallExpr(*Context, DRE, MsgExprs, - castType, VK_LValue, SourceLocation()); + FunctionDecl *FD = + FunctionDecl::Create(*Context, TUDecl, SourceLocation(), SourceLocation(), + ID, FuncType, nullptr, SC_Extern, false, false); + DeclRefExpr *DRE = new (Context) + DeclRefExpr(*Context, FD, false, castType, VK_RValue, SourceLocation()); + CallExpr *STCE = CallExpr::Create(*Context, DRE, MsgExprs, castType, + VK_LValue, SourceLocation()); FieldDecl *FieldD = FieldDecl::Create(*Context, nullptr, SourceLocation(), SourceLocation(), @@ -3249,7 +3239,8 @@ Stmt *RewriteModernObjC::SynthMessageExpr(ObjCMessageExpr *Exp, InitExprs.push_back( NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(), CK_BitCast, - new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(), + new (Context) DeclRefExpr(*Context, + CurMethodDef->getSelfDecl(), false, Context->getObjCIdType(), VK_RValue, @@ -3280,12 +3271,11 @@ Stmt *RewriteModernObjC::SynthMessageExpr(ObjCMessageExpr *Exp, if (LangOpts.MicrosoftExt) { SynthSuperConstructorFunctionDecl(); // Simulate a constructor call... - DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperConstructorFunctionDecl, - false, superType, VK_LValue, - SourceLocation()); - SuperRep = new (Context) CallExpr(*Context, DRE, InitExprs, - superType, VK_LValue, - SourceLocation()); + DeclRefExpr *DRE = new (Context) + DeclRefExpr(*Context, SuperConstructorFunctionDecl, false, superType, + VK_LValue, SourceLocation()); + SuperRep = CallExpr::Create(*Context, DRE, InitExprs, superType, + VK_LValue, SourceLocation()); // The code for super is a little tricky to prevent collision with // the structure definition in the header. The rewriter has it's own // internal definition (__rw_objc_super) that is uses. This is why @@ -3345,7 +3335,8 @@ Stmt *RewriteModernObjC::SynthMessageExpr(ObjCMessageExpr *Exp, InitExprs.push_back( NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(), CK_BitCast, - new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(), + new (Context) DeclRefExpr(*Context, + CurMethodDef->getSelfDecl(), false, Context->getObjCIdType(), VK_RValue, SourceLocation())) @@ -3375,11 +3366,11 @@ Stmt *RewriteModernObjC::SynthMessageExpr(ObjCMessageExpr *Exp, if (LangOpts.MicrosoftExt) { SynthSuperConstructorFunctionDecl(); // Simulate a constructor call... - DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperConstructorFunctionDecl, - false, superType, VK_LValue, - SourceLocation()); - SuperRep = new (Context) CallExpr(*Context, DRE, InitExprs, - superType, VK_LValue, SourceLocation()); + DeclRefExpr *DRE = new (Context) + DeclRefExpr(*Context, SuperConstructorFunctionDecl, false, superType, + VK_LValue, SourceLocation()); + SuperRep = CallExpr::Create(*Context, DRE, InitExprs, superType, + VK_LValue, SourceLocation()); // The code for super is a little tricky to prevent collision with // the structure definition in the header. The rewriter has it's own // internal definition (__rw_objc_super) that is uses. This is why @@ -3519,8 +3510,8 @@ Stmt *RewriteModernObjC::SynthMessageExpr(ObjCMessageExpr *Exp, QualType msgSendType = MsgSendFlavor->getType(); // Create a reference to the objc_msgSend() declaration. - DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType, - VK_LValue, SourceLocation()); + DeclRefExpr *DRE = new (Context) DeclRefExpr( + *Context, MsgSendFlavor, false, msgSendType, VK_LValue, SourceLocation()); // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid). // If we don't do this cast, we get the following bizarre warning/note: @@ -3543,8 +3534,8 @@ Stmt *RewriteModernObjC::SynthMessageExpr(ObjCMessageExpr *Exp, ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast); const FunctionType *FT = msgSendType->getAs<FunctionType>(); - CallExpr *CE = new (Context) - CallExpr(*Context, PE, MsgExprs, FT->getReturnType(), VK_RValue, EndLoc); + CallExpr *CE = CallExpr::Create(*Context, PE, MsgExprs, FT->getReturnType(), + VK_RValue, EndLoc); Stmt *ReplacingStmt = CE; if (MsgSendStretFlavor) { // We have the method which returns a struct/union. Must also generate @@ -3563,8 +3554,8 @@ Stmt *RewriteModernObjC::SynthMessageExpr(ObjCMessageExpr *Exp, } Stmt *RewriteModernObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) { - Stmt *ReplacingStmt = SynthMessageExpr(Exp, Exp->getLocStart(), - Exp->getLocEnd()); + Stmt *ReplacingStmt = + SynthMessageExpr(Exp, Exp->getBeginLoc(), Exp->getEndLoc()); // Now do the actual rewrite. ReplaceStmt(Exp, ReplacingStmt); @@ -3597,10 +3588,9 @@ Stmt *RewriteModernObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) { VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(), SourceLocation(), ID, getProtocolType(), nullptr, SC_Extern); - DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, false, getProtocolType(), - VK_LValue, SourceLocation()); - CastExpr *castExpr = - NoTypeInfoCStyleCastExpr( + DeclRefExpr *DRE = new (Context) DeclRefExpr( + *Context, VD, false, getProtocolType(), VK_LValue, SourceLocation()); + CastExpr *castExpr = NoTypeInfoCStyleCastExpr( Context, Context->getPointerType(DRE->getType()), CK_BitCast, DRE); ReplaceStmt(Exp, castExpr); ProtocolExprDecls.insert(Exp->getProtocol()->getCanonicalDecl()); @@ -3896,7 +3886,7 @@ void RewriteModernObjC::RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl, IVD; IVD = IVD->getNextIvar()) IVars.push_back(IVD); - SourceLocation LocStart = CDecl->getLocStart(); + SourceLocation LocStart = CDecl->getBeginLoc(); SourceLocation LocEnd = CDecl->getEndOfDefinitionLoc(); const char *startBuf = SM->getCharacterData(LocStart); @@ -4461,9 +4451,9 @@ static void BuildUniqueMethodName(std::string &Name, } void RewriteModernObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) { - //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n"); - //SourceLocation FunLocStart = MD->getLocStart(); - SourceLocation FunLocStart = MD->getLocStart(); + // fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n"); + // SourceLocation FunLocStart = MD->getBeginLoc(); + SourceLocation FunLocStart = MD->getBeginLoc(); std::string FuncName; BuildUniqueMethodName(FuncName, MD); SynthesizeBlockLiterals(FunLocStart, FuncName); @@ -4656,9 +4646,8 @@ Stmt *RewriteModernObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp E = Exp->arg_end(); I != E; ++I) { BlkExprs.push_back(*I); } - CallExpr *CE = new (Context) CallExpr(*Context, PE, BlkExprs, - Exp->getType(), VK_RValue, - SourceLocation()); + CallExpr *CE = CallExpr::Create(*Context, PE, BlkExprs, Exp->getType(), + VK_RValue, SourceLocation()); return CE; } @@ -4778,7 +4767,7 @@ void RewriteModernObjC::RewriteImplicitCastObjCExpr(CastExpr *IC) { std::string Str = "("; Str += TypeString; Str += ")"; - InsertText(IC->getSubExpr()->getLocStart(), Str); + InsertText(IC->getSubExpr()->getBeginLoc(), Str); } void RewriteModernObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) { @@ -5036,7 +5025,7 @@ void RewriteModernObjC::RewriteByRefVar(VarDecl *ND, bool firstDecl, // Use variable's location which is good for this case. DeclLoc = ND->getLocation(); const char *startBuf = SM->getCharacterData(DeclLoc); - SourceLocation X = ND->getLocEnd(); + SourceLocation X = ND->getEndLoc(); X = SM->getExpansionLoc(X); const char *endBuf = SM->getCharacterData(X); std::string Name(ND->getNameAsString()); @@ -5069,7 +5058,7 @@ void RewriteModernObjC::RewriteByRefVar(VarDecl *ND, bool firstDecl, FunLocStart = getFunctionSourceLocation(*this, CurFunctionDef); else { assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null"); - FunLocStart = CurMethodDef->getLocStart(); + FunLocStart = CurMethodDef->getBeginLoc(); } InsertText(FunLocStart, ByrefType); @@ -5156,7 +5145,7 @@ void RewriteModernObjC::RewriteByRefVar(VarDecl *ND, bool firstDecl, if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) startLoc = ECE->getLParenLoc(); else - startLoc = E->getLocStart(); + startLoc = E->getBeginLoc(); startLoc = SM->getExpansionLoc(startLoc); endBuf = SM->getCharacterData(startLoc); ReplaceText(DeclLoc, endBuf-startBuf, ByrefType); @@ -5287,15 +5276,15 @@ Stmt *RewriteModernObjC::SynthBlockInitExpr(BlockExpr *Exp, Tag += FuncName + "_block_impl_" + BlockNumber; FD = SynthBlockInitFunctionDecl(Tag); - DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, false, FType, VK_RValue, - SourceLocation()); + DeclRefExpr *DRE = new (Context) + DeclRefExpr(*Context, FD, false, FType, VK_RValue, SourceLocation()); SmallVector<Expr*, 4> InitExprs; // Initialize the block function. FD = SynthBlockInitFunctionDecl(Func); - DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, false, FD->getType(), - VK_LValue, SourceLocation()); + DeclRefExpr *Arg = new (Context) DeclRefExpr( + *Context, FD, false, FD->getType(), VK_LValue, SourceLocation()); CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy, CK_BitCast, Arg); InitExprs.push_back(castExpr); @@ -5306,15 +5295,11 @@ Stmt *RewriteModernObjC::SynthBlockInitExpr(BlockExpr *Exp, VarDecl *NewVD = VarDecl::Create( *Context, TUDecl, SourceLocation(), SourceLocation(), &Context->Idents.get(DescData), Context->VoidPtrTy, nullptr, SC_Static); - UnaryOperator *DescRefExpr = - new (Context) UnaryOperator(new (Context) DeclRefExpr(NewVD, false, - Context->VoidPtrTy, - VK_LValue, - SourceLocation()), - UO_AddrOf, - Context->getPointerType(Context->VoidPtrTy), - VK_RValue, OK_Ordinary, - SourceLocation(), false); + UnaryOperator *DescRefExpr = new (Context) UnaryOperator( + new (Context) DeclRefExpr(*Context, NewVD, false, Context->VoidPtrTy, + VK_LValue, SourceLocation()), + UO_AddrOf, Context->getPointerType(Context->VoidPtrTy), VK_RValue, + OK_Ordinary, SourceLocation(), false); InitExprs.push_back(DescRefExpr); // Add initializers for any closure decl refs. @@ -5326,7 +5311,7 @@ Stmt *RewriteModernObjC::SynthBlockInitExpr(BlockExpr *Exp, if (isObjCType((*I)->getType())) { // FIXME: Conform to ABI ([[obj retain] autorelease]). FD = SynthBlockInitFunctionDecl((*I)->getName()); - Exp = new (Context) DeclRefExpr(FD, false, FD->getType(), + Exp = new (Context) DeclRefExpr(*Context, FD, false, FD->getType(), VK_LValue, SourceLocation()); if (HasLocalVariableExternalStorage(*I)) { QualType QT = (*I)->getType(); @@ -5337,13 +5322,13 @@ Stmt *RewriteModernObjC::SynthBlockInitExpr(BlockExpr *Exp, } } else if (isTopLevelBlockPointerType((*I)->getType())) { FD = SynthBlockInitFunctionDecl((*I)->getName()); - Arg = new (Context) DeclRefExpr(FD, false, FD->getType(), + Arg = new (Context) DeclRefExpr(*Context, FD, false, FD->getType(), VK_LValue, SourceLocation()); Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy, CK_BitCast, Arg); } else { FD = SynthBlockInitFunctionDecl((*I)->getName()); - Exp = new (Context) DeclRefExpr(FD, false, FD->getType(), + Exp = new (Context) DeclRefExpr(*Context, FD, false, FD->getType(), VK_LValue, SourceLocation()); if (HasLocalVariableExternalStorage(*I)) { QualType QT = (*I)->getType(); @@ -5372,8 +5357,8 @@ Stmt *RewriteModernObjC::SynthBlockInitExpr(BlockExpr *Exp, QualType castT = Context->getPointerType(Context->getTagDeclType(RD)); FD = SynthBlockInitFunctionDecl((*I)->getName()); - Exp = new (Context) DeclRefExpr(FD, false, FD->getType(), VK_LValue, - SourceLocation()); + Exp = new (Context) DeclRefExpr(*Context, FD, false, FD->getType(), + VK_LValue, SourceLocation()); bool isNestedCapturedVar = false; if (block) for (const auto &CI : block->captures()) { @@ -5405,8 +5390,8 @@ Stmt *RewriteModernObjC::SynthBlockInitExpr(BlockExpr *Exp, Context->IntTy, SourceLocation()); InitExprs.push_back(FlagExp); } - NewRep = new (Context) CallExpr(*Context, DRE, InitExprs, - FType, VK_LValue, SourceLocation()); + NewRep = CallExpr::Create(*Context, DRE, InitExprs, FType, VK_LValue, + SourceLocation()); if (GlobalBlockExpr) { assert (!GlobalConstructionExp && @@ -5537,8 +5522,8 @@ Stmt *RewriteModernObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) { if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) { #if 0 // Before we rewrite it, put the original message expression in a comment. - SourceLocation startLoc = MessExpr->getLocStart(); - SourceLocation endLoc = MessExpr->getLocEnd(); + SourceLocation startLoc = MessExpr->getBeginLoc(); + SourceLocation endLoc = MessExpr->getEndLoc(); const char *startBuf = SM->getCharacterData(startLoc); const char *endBuf = SM->getCharacterData(endLoc); @@ -5676,7 +5661,7 @@ Stmt *RewriteModernObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) { const std::string &Str = Buf.str(); printf("CAST = %s\n", &Str[0]); - InsertText(ICE->getSubExpr()->getLocStart(), Str); + InsertText(ICE->getSubExpr()->getBeginLoc(), Str); delete S; return Replacement; } @@ -7499,9 +7484,9 @@ Stmt *RewriteModernObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) { SourceLocation(), &Context->Idents.get(IvarOffsetName), Context->UnsignedLongTy, nullptr, SC_Extern); - DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, false, - Context->UnsignedLongTy, VK_LValue, - SourceLocation()); + DeclRefExpr *DRE = new (Context) + DeclRefExpr(*Context, NewVD, false, Context->UnsignedLongTy, + VK_LValue, SourceLocation()); BinaryOperator *addExpr = new (Context) BinaryOperator(castExpr, DRE, BO_Add, Context->getPointerType(Context->CharTy), diff --git a/lib/Frontend/Rewrite/RewriteObjC.cpp b/lib/Frontend/Rewrite/RewriteObjC.cpp index 6229351e8f54..3e018800b909 100644 --- a/lib/Frontend/Rewrite/RewriteObjC.cpp +++ b/lib/Frontend/Rewrite/RewriteObjC.cpp @@ -216,8 +216,8 @@ namespace { // Measure the old text. int Size = Rewrite.getRangeSize(SrcRange); if (Size == -1) { - Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag) - << Old->getSourceRange(); + Diags.Report(Context->getFullLoc(Old->getBeginLoc()), RewriteFailedDiag) + << Old->getSourceRange(); return; } // Get the new text. @@ -233,8 +233,8 @@ namespace { } if (SilenceRewriteMacroWarning) return; - Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag) - << Old->getSourceRange(); + Diags.Report(Context->getFullLoc(Old->getBeginLoc()), RewriteFailedDiag) + << Old->getSourceRange(); } void InsertText(SourceLocation Loc, StringRef Str, @@ -448,7 +448,7 @@ namespace { // FIXME: This predicate seems like it would be useful to add to ASTContext. bool isObjCType(QualType T) { - if (!LangOpts.ObjC1 && !LangOpts.ObjC2) + if (!LangOpts.ObjC) return false; QualType OCT = Context->getCanonicalType(T).getUnqualifiedType(); @@ -680,11 +680,11 @@ void RewriteObjC::HandleTopLevelSingleDecl(Decl *D) { if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>((*DI))) { if (!IFace->isThisDeclarationADefinition()) { SmallVector<Decl *, 8> DG; - SourceLocation StartLoc = IFace->getLocStart(); + SourceLocation StartLoc = IFace->getBeginLoc(); do { if (isa<ObjCInterfaceDecl>(*DI) && !cast<ObjCInterfaceDecl>(*DI)->isThisDeclarationADefinition() && - StartLoc == (*DI)->getLocStart()) + StartLoc == (*DI)->getBeginLoc()) DG.push_back(*DI); else break; @@ -699,11 +699,11 @@ void RewriteObjC::HandleTopLevelSingleDecl(Decl *D) { if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>((*DI))) { if (!Proto->isThisDeclarationADefinition()) { SmallVector<Decl *, 8> DG; - SourceLocation StartLoc = Proto->getLocStart(); + SourceLocation StartLoc = Proto->getBeginLoc(); do { if (isa<ObjCProtocolDecl>(*DI) && !cast<ObjCProtocolDecl>(*DI)->isThisDeclarationADefinition() && - StartLoc == (*DI)->getLocStart()) + StartLoc == (*DI)->getBeginLoc()) DG.push_back(*DI); else break; @@ -769,7 +769,7 @@ void RewriteObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID, ObjCCategoryImplDecl *CID) { static bool objcGetPropertyDefined = false; static bool objcSetPropertyDefined = false; - SourceLocation startLoc = PID->getLocStart(); + SourceLocation startLoc = PID->getBeginLoc(); InsertText(startLoc, "// "); const char *startBuf = SM->getCharacterData(startLoc); assert((*startBuf == '@') && "bogus @synthesize location"); @@ -901,11 +901,11 @@ static void RewriteOneForwardClassDecl(ObjCInterfaceDecl *ForwardDecl, void RewriteObjC::RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl, const std::string &typedefString) { - SourceLocation startLoc = ClassDecl->getLocStart(); - const char *startBuf = SM->getCharacterData(startLoc); - const char *semiPtr = strchr(startBuf, ';'); - // Replace the @class with typedefs corresponding to the classes. - ReplaceText(startLoc, semiPtr-startBuf+1, typedefString); + SourceLocation startLoc = ClassDecl->getBeginLoc(); + const char *startBuf = SM->getCharacterData(startLoc); + const char *semiPtr = strchr(startBuf, ';'); + // Replace the @class with typedefs corresponding to the classes. + ReplaceText(startLoc, semiPtr - startBuf + 1, typedefString); } void RewriteObjC::RewriteForwardClassDecl(DeclGroupRef D) { @@ -945,8 +945,8 @@ void RewriteObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) { // nothing to rewrite. if (Method->isImplicit()) return; - SourceLocation LocStart = Method->getLocStart(); - SourceLocation LocEnd = Method->getLocEnd(); + SourceLocation LocStart = Method->getBeginLoc(); + SourceLocation LocEnd = Method->getEndLoc(); if (SM->getExpansionLineNumber(LocEnd) > SM->getExpansionLineNumber(LocStart)) { @@ -965,7 +965,7 @@ void RewriteObjC::RewriteProperty(ObjCPropertyDecl *prop) { } void RewriteObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) { - SourceLocation LocStart = CatDecl->getLocStart(); + SourceLocation LocStart = CatDecl->getBeginLoc(); // FIXME: handle category headers that are declared across multiple lines. ReplaceText(LocStart, 0, "// "); @@ -983,7 +983,7 @@ void RewriteObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) { } void RewriteObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) { - SourceLocation LocStart = PDecl->getLocStart(); + SourceLocation LocStart = PDecl->getBeginLoc(); assert(PDecl->isThisDeclarationADefinition()); // FIXME: handle protocol headers that are declared across multiple lines. @@ -1018,7 +1018,7 @@ void RewriteObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) { } void RewriteObjC::RewriteForwardProtocolDecl(DeclGroupRef D) { - SourceLocation LocStart = (*D.begin())->getLocStart(); + SourceLocation LocStart = (*D.begin())->getBeginLoc(); if (LocStart.isInvalid()) llvm_unreachable("Invalid SourceLocation"); // FIXME: handle forward protocol that are declared across multiple lines. @@ -1027,7 +1027,7 @@ void RewriteObjC::RewriteForwardProtocolDecl(DeclGroupRef D) { void RewriteObjC::RewriteForwardProtocolDecl(const SmallVectorImpl<Decl *> &DG) { - SourceLocation LocStart = DG[0]->getLocStart(); + SourceLocation LocStart = DG[0]->getBeginLoc(); if (LocStart.isInvalid()) llvm_unreachable("Invalid SourceLocation"); // FIXME: handle forward protocol that are declared across multiple lines. @@ -1165,13 +1165,13 @@ void RewriteObjC::RewriteImplementationDecl(Decl *OID) { ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID); ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID); - InsertText(IMD ? IMD->getLocStart() : CID->getLocStart(), "// "); + InsertText(IMD ? IMD->getBeginLoc() : CID->getBeginLoc(), "// "); for (auto *OMD : IMD ? IMD->instance_methods() : CID->instance_methods()) { std::string ResultStr; RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr); - SourceLocation LocStart = OMD->getLocStart(); - SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart(); + SourceLocation LocStart = OMD->getBeginLoc(); + SourceLocation LocEnd = OMD->getCompoundBody()->getBeginLoc(); const char *startBuf = SM->getCharacterData(LocStart); const char *endBuf = SM->getCharacterData(LocEnd); @@ -1181,8 +1181,8 @@ void RewriteObjC::RewriteImplementationDecl(Decl *OID) { for (auto *OMD : IMD ? IMD->class_methods() : CID->class_methods()) { std::string ResultStr; RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr); - SourceLocation LocStart = OMD->getLocStart(); - SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart(); + SourceLocation LocStart = OMD->getBeginLoc(); + SourceLocation LocEnd = OMD->getCompoundBody()->getBeginLoc(); const char *startBuf = SM->getCharacterData(LocStart); const char *endBuf = SM->getCharacterData(LocEnd); @@ -1191,7 +1191,7 @@ void RewriteObjC::RewriteImplementationDecl(Decl *OID) { for (auto *I : IMD ? IMD->property_impls() : CID->property_impls()) RewritePropertyImplDecl(I, IMD, CID); - InsertText(IMD ? IMD->getLocEnd() : CID->getLocEnd(), "// "); + InsertText(IMD ? IMD->getEndLoc() : CID->getEndLoc(), "// "); } void RewriteObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) { @@ -1412,7 +1412,7 @@ Stmt *RewriteObjC::RewriteBreakStmt(BreakStmt *S) { // replace break with goto __break_label std::string buf; - SourceLocation startLoc = S->getLocStart(); + SourceLocation startLoc = S->getBeginLoc(); buf = "goto __break_label_"; buf += utostr(ObjCBcLabelNo.back()); ReplaceText(startLoc, strlen("break"), buf); @@ -1429,7 +1429,7 @@ Stmt *RewriteObjC::RewriteContinueStmt(ContinueStmt *S) { // replace continue with goto __continue_label std::string buf; - SourceLocation startLoc = S->getLocStart(); + SourceLocation startLoc = S->getBeginLoc(); buf = "goto __continue_label_"; buf += utostr(ObjCBcLabelNo.back()); ReplaceText(startLoc, strlen("continue"), buf); @@ -1477,7 +1477,7 @@ Stmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S, assert(!ObjCBcLabelNo.empty() && "ObjCForCollectionStmt - Label No stack empty"); - SourceLocation startLoc = S->getLocStart(); + SourceLocation startLoc = S->getBeginLoc(); const char *startBuf = SM->getCharacterData(startLoc); StringRef elementName; std::string elementTypeAsString; @@ -1641,7 +1641,7 @@ Stmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S, /// Stmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) { // Get the start location and compute the semi location. - SourceLocation startLoc = S->getLocStart(); + SourceLocation startLoc = S->getBeginLoc(); const char *startBuf = SM->getCharacterData(startLoc); assert((*startBuf == '@') && "bogus @synchronized location"); @@ -1651,10 +1651,10 @@ Stmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) { const char *lparenBuf = startBuf; while (*lparenBuf != '(') lparenBuf++; ReplaceText(startLoc, lparenBuf-startBuf+1, buf); - // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since + // We can't use S->getSynchExpr()->getEndLoc() to find the end location, since // the sync expression is typically a message expression that's already // been rewritten! (which implies the SourceLocation's are invalid). - SourceLocation endLoc = S->getSynchBody()->getLocStart(); + SourceLocation endLoc = S->getSynchBody()->getBeginLoc(); const char *endBuf = SM->getCharacterData(endLoc); while (*endBuf != ')') endBuf--; SourceLocation rparenLoc = startLoc.getLocWithOffset(endBuf-startBuf); @@ -1667,7 +1667,7 @@ Stmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) { buf += "objc_exception_try_enter(&_stack);\n"; buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n"; ReplaceText(rparenLoc, 1, buf); - startLoc = S->getSynchBody()->getLocEnd(); + startLoc = S->getSynchBody()->getEndLoc(); startBuf = SM->getCharacterData(startLoc); assert((*startBuf == '}') && "bogus @synchronized block"); @@ -1719,7 +1719,7 @@ void RewriteObjC::WarnAboutReturnGotoStmts(Stmt *S) WarnAboutReturnGotoStmts(SubStmt); if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) { - Diags.Report(Context->getFullLoc(S->getLocStart()), + Diags.Report(Context->getFullLoc(S->getBeginLoc()), TryFinallyContainsReturnDiag); } } @@ -1742,7 +1742,7 @@ void RewriteObjC::RewriteTryReturnStmts(Stmt *S) { RewriteTryReturnStmts(SubStmt); } if (isa<ReturnStmt>(S)) { - SourceLocation startLoc = S->getLocStart(); + SourceLocation startLoc = S->getBeginLoc(); const char *startBuf = SM->getCharacterData(startLoc); const char *semiBuf = strchr(startBuf, ';'); assert((*semiBuf == ';') && "RewriteTryReturnStmts: can't find ';'"); @@ -1763,7 +1763,7 @@ void RewriteObjC::RewriteSyncReturnStmts(Stmt *S, std::string syncExitBuf) { RewriteSyncReturnStmts(SubStmt, syncExitBuf); } if (isa<ReturnStmt>(S)) { - SourceLocation startLoc = S->getLocStart(); + SourceLocation startLoc = S->getBeginLoc(); const char *startBuf = SM->getCharacterData(startLoc); const char *semiBuf = strchr(startBuf, ';'); @@ -1782,7 +1782,7 @@ void RewriteObjC::RewriteSyncReturnStmts(Stmt *S, std::string syncExitBuf) { Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) { // Get the start location and compute the semi location. - SourceLocation startLoc = S->getLocStart(); + SourceLocation startLoc = S->getBeginLoc(); const char *startBuf = SM->getCharacterData(startLoc); assert((*startBuf == '@') && "bogus @try location"); @@ -1798,7 +1798,7 @@ Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) { ReplaceText(startLoc, 4, buf); - startLoc = S->getTryBody()->getLocEnd(); + startLoc = S->getTryBody()->getEndLoc(); startBuf = SM->getCharacterData(startLoc); assert((*startBuf == '}') && "bogus @try block"); @@ -1829,7 +1829,7 @@ Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) { buf = "if ("; // we are generating code for the first catch clause else buf = "else if ("; - startLoc = Catch->getLocStart(); + startLoc = Catch->getBeginLoc(); startBuf = SM->getCharacterData(startLoc); assert((*startBuf == '@') && "bogus @catch location"); @@ -1839,7 +1839,7 @@ Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) { if (Catch->hasEllipsis()) { // Now rewrite the body... lastCatchBody = Catch->getCatchBody(); - SourceLocation bodyLoc = lastCatchBody->getLocStart(); + SourceLocation bodyLoc = lastCatchBody->getBeginLoc(); const char *bodyBuf = SM->getCharacterData(bodyLoc); assert(*SM->getCharacterData(Catch->getRParenLoc()) == ')' && "bogus @catch paren location"); @@ -1866,7 +1866,7 @@ Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) { // Now rewrite the body... lastCatchBody = Catch->getCatchBody(); SourceLocation rParenLoc = Catch->getRParenLoc(); - SourceLocation bodyLoc = lastCatchBody->getLocStart(); + SourceLocation bodyLoc = lastCatchBody->getBeginLoc(); const char *bodyBuf = SM->getCharacterData(bodyLoc); const char *rParenBuf = SM->getCharacterData(rParenLoc); assert((*rParenBuf == ')') && "bogus @catch paren location"); @@ -1881,7 +1881,7 @@ Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) { } // Complete the catch list... if (lastCatchBody) { - SourceLocation bodyLoc = lastCatchBody->getLocEnd(); + SourceLocation bodyLoc = lastCatchBody->getEndLoc(); assert(*SM->getCharacterData(bodyLoc) == '}' && "bogus @catch body location"); @@ -1897,18 +1897,18 @@ Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) { InsertText(bodyLoc, buf); // Set lastCurlyLoc - lastCurlyLoc = lastCatchBody->getLocEnd(); + lastCurlyLoc = lastCatchBody->getEndLoc(); } if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) { - startLoc = finalStmt->getLocStart(); + startLoc = finalStmt->getBeginLoc(); startBuf = SM->getCharacterData(startLoc); assert((*startBuf == '@') && "bogus @finally start"); ReplaceText(startLoc, 8, "/* @finally */"); Stmt *body = finalStmt->getFinallyBody(); - SourceLocation startLoc = body->getLocStart(); - SourceLocation endLoc = body->getLocEnd(); + SourceLocation startLoc = body->getBeginLoc(); + SourceLocation endLoc = body->getEndLoc(); assert(*SM->getCharacterData(startLoc) == '{' && "bogus @finally body location"); assert(*SM->getCharacterData(endLoc) == '}' && @@ -1920,7 +1920,7 @@ Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) { InsertText(endLoc, " if (_rethrow) objc_exception_throw(_rethrow);\n"); // Set lastCurlyLoc - lastCurlyLoc = body->getLocEnd(); + lastCurlyLoc = body->getEndLoc(); // Now check for any return/continue/go statements within the @try. WarnAboutReturnGotoStmts(S->getTryBody()); @@ -1950,7 +1950,7 @@ Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) { // been rewritten! (which implies the SourceLocation's are invalid). Stmt *RewriteObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) { // Get the start location and compute the semi location. - SourceLocation startLoc = S->getLocStart(); + SourceLocation startLoc = S->getBeginLoc(); const char *startBuf = SM->getCharacterData(startLoc); assert((*startBuf == '@') && "bogus @throw location"); @@ -2009,7 +2009,7 @@ RewriteObjC::SynthesizeCallToFunctionDecl(FunctionDecl *FD, QualType msgSendType = FD->getType(); // Create a reference to the objc_msgSend() declaration. - DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, false, msgSendType, + DeclRefExpr *DRE = new (Context) DeclRefExpr(*Context, FD, false, msgSendType, VK_LValue, SourceLocation()); // Now, we cast the reference to a pointer to the objc_msgSend type. @@ -2020,9 +2020,8 @@ RewriteObjC::SynthesizeCallToFunctionDecl(FunctionDecl *FD, const FunctionType *FT = msgSendType->getAs<FunctionType>(); - CallExpr *Exp = new (Context) CallExpr(*Context, ICE, Args, - FT->getCallResultType(*Context), - VK_RValue, EndLoc); + CallExpr *Exp = CallExpr::Create( + *Context, ICE, Args, FT->getCallResultType(*Context), VK_RValue, EndLoc); return Exp; } @@ -2082,8 +2081,8 @@ void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) { Loc = ECE->getLParenLoc(); EndLoc = ECE->getRParenLoc(); } else { - Loc = E->getLocStart(); - EndLoc = E->getLocEnd(); + Loc = E->getBeginLoc(); + EndLoc = E->getEndLoc(); } // This will defend against trying to rewrite synthesized expressions. if (Loc.isInvalid() || EndLoc.isInvalid()) @@ -2204,13 +2203,13 @@ void RewriteObjC::RewriteTypeOfDecl(VarDecl *ND) { if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) startLoc = ECE->getLParenLoc(); else - startLoc = E->getLocStart(); + startLoc = E->getBeginLoc(); startLoc = SM->getExpansionLoc(startLoc); const char *endBuf = SM->getCharacterData(startLoc); ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString); } else { - SourceLocation X = ND->getLocEnd(); + SourceLocation X = ND->getEndLoc(); X = SM->getExpansionLoc(X); const char *endBuf = SM->getCharacterData(X); ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString); @@ -2506,12 +2505,11 @@ Stmt *RewriteObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) { VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(), SourceLocation(), &Context->Idents.get(S), strType, nullptr, SC_Static); - DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, false, strType, VK_LValue, - SourceLocation()); - Expr *Unop = new (Context) UnaryOperator(DRE, UO_AddrOf, - Context->getPointerType(DRE->getType()), - VK_RValue, OK_Ordinary, - SourceLocation(), false); + DeclRefExpr *DRE = new (Context) + DeclRefExpr(*Context, NewVD, false, strType, VK_LValue, SourceLocation()); + Expr *Unop = new (Context) + UnaryOperator(DRE, UO_AddrOf, Context->getPointerType(DRE->getType()), + VK_RValue, OK_Ordinary, SourceLocation(), false); // cast to NSConstantString * CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(), CK_CPointerToObjCPointerCast, Unop); @@ -2589,9 +2587,9 @@ CallExpr *RewriteObjC::SynthMsgSendStretCallExpr(FunctionDecl *MsgSendStretFlavo SmallVectorImpl<Expr*> &MsgExprs, ObjCMethodDecl *Method) { // Create a reference to the objc_msgSend_stret() declaration. - DeclRefExpr *STDRE = new (Context) DeclRefExpr(MsgSendStretFlavor, - false, msgSendType, - VK_LValue, SourceLocation()); + DeclRefExpr *STDRE = + new (Context) DeclRefExpr(*Context, MsgSendStretFlavor, false, + msgSendType, VK_LValue, SourceLocation()); // Need to cast objc_msgSend_stret to "void *" (see above comment). CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Context->getPointerType(Context->VoidTy), @@ -2608,8 +2606,8 @@ CallExpr *RewriteObjC::SynthMsgSendStretCallExpr(FunctionDecl *MsgSendStretFlavo ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast); const FunctionType *FT = msgSendType->getAs<FunctionType>(); - CallExpr *STCE = new (Context) CallExpr( - *Context, PE, MsgExprs, FT->getReturnType(), VK_RValue, SourceLocation()); + CallExpr *STCE = CallExpr::Create(*Context, PE, MsgExprs, FT->getReturnType(), + VK_RValue, SourceLocation()); return STCE; } @@ -2664,7 +2662,8 @@ Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp, InitExprs.push_back( NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(), CK_BitCast, - new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(), + new (Context) DeclRefExpr(*Context, + CurMethodDef->getSelfDecl(), false, Context->getObjCIdType(), VK_RValue, @@ -2697,12 +2696,11 @@ Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp, if (LangOpts.MicrosoftExt) { SynthSuperConstructorFunctionDecl(); // Simulate a constructor call... - DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperConstructorFunctionDecl, - false, superType, VK_LValue, - SourceLocation()); - SuperRep = new (Context) CallExpr(*Context, DRE, InitExprs, - superType, VK_LValue, - SourceLocation()); + DeclRefExpr *DRE = new (Context) + DeclRefExpr(*Context, SuperConstructorFunctionDecl, false, superType, + VK_LValue, SourceLocation()); + SuperRep = CallExpr::Create(*Context, DRE, InitExprs, superType, + VK_LValue, SourceLocation()); // The code for super is a little tricky to prevent collision with // the structure definition in the header. The rewriter has it's own // internal definition (__rw_objc_super) that is uses. This is why @@ -2759,7 +2757,8 @@ Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp, InitExprs.push_back( NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(), CK_BitCast, - new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(), + new (Context) DeclRefExpr(*Context, + CurMethodDef->getSelfDecl(), false, Context->getObjCIdType(), VK_RValue, SourceLocation())) @@ -2792,11 +2791,11 @@ Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp, if (LangOpts.MicrosoftExt) { SynthSuperConstructorFunctionDecl(); // Simulate a constructor call... - DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperConstructorFunctionDecl, - false, superType, VK_LValue, - SourceLocation()); - SuperRep = new (Context) CallExpr(*Context, DRE, InitExprs, - superType, VK_LValue, SourceLocation()); + DeclRefExpr *DRE = new (Context) + DeclRefExpr(*Context, SuperConstructorFunctionDecl, false, superType, + VK_LValue, SourceLocation()); + SuperRep = CallExpr::Create(*Context, DRE, InitExprs, superType, + VK_LValue, SourceLocation()); // The code for super is a little tricky to prevent collision with // the structure definition in the header. The rewriter has it's own // internal definition (__rw_objc_super) that is uses. This is why @@ -2936,8 +2935,8 @@ Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp, QualType msgSendType = MsgSendFlavor->getType(); // Create a reference to the objc_msgSend() declaration. - DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType, - VK_LValue, SourceLocation()); + DeclRefExpr *DRE = new (Context) DeclRefExpr( + *Context, MsgSendFlavor, false, msgSendType, VK_LValue, SourceLocation()); // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid). // If we don't do this cast, we get the following bizarre warning/note: @@ -2960,8 +2959,8 @@ Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp, ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast); const FunctionType *FT = msgSendType->getAs<FunctionType>(); - CallExpr *CE = new (Context) - CallExpr(*Context, PE, MsgExprs, FT->getReturnType(), VK_RValue, EndLoc); + CallExpr *CE = CallExpr::Create(*Context, PE, MsgExprs, FT->getReturnType(), + VK_RValue, EndLoc); Stmt *ReplacingStmt = CE; if (MsgSendStretFlavor) { // We have the method which returns a struct/union. Must also generate @@ -3008,8 +3007,8 @@ Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp, } Stmt *RewriteObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) { - Stmt *ReplacingStmt = SynthMessageExpr(Exp, Exp->getLocStart(), - Exp->getLocEnd()); + Stmt *ReplacingStmt = + SynthMessageExpr(Exp, Exp->getBeginLoc(), Exp->getEndLoc()); // Now do the actual rewrite. ReplaceStmt(Exp, ReplacingStmt); @@ -3041,8 +3040,8 @@ Stmt *RewriteObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) { VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(), SourceLocation(), ID, getProtocolType(), nullptr, SC_Extern); - DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, false, getProtocolType(), - VK_LValue, SourceLocation()); + DeclRefExpr *DRE = new (Context) DeclRefExpr( + *Context, VD, false, getProtocolType(), VK_LValue, SourceLocation()); Expr *DerefExpr = new (Context) UnaryOperator(DRE, UO_AddrOf, Context->getPointerType(DRE->getType()), VK_RValue, OK_Ordinary, SourceLocation(), false); @@ -3093,7 +3092,7 @@ void RewriteObjC::RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl, return; ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass(); int NumIvars = CDecl->ivar_size(); - SourceLocation LocStart = CDecl->getLocStart(); + SourceLocation LocStart = CDecl->getBeginLoc(); SourceLocation LocEnd = CDecl->getEndOfDefinitionLoc(); const char *startBuf = SM->getCharacterData(LocStart); @@ -3635,9 +3634,9 @@ static void BuildUniqueMethodName(std::string &Name, } void RewriteObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) { - //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n"); - //SourceLocation FunLocStart = MD->getLocStart(); - SourceLocation FunLocStart = MD->getLocStart(); + // fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n"); + // SourceLocation FunLocStart = MD->getBeginLoc(); + SourceLocation FunLocStart = MD->getBeginLoc(); std::string FuncName; BuildUniqueMethodName(FuncName, MD); SynthesizeBlockLiterals(FunLocStart, FuncName); @@ -3811,9 +3810,8 @@ Stmt *RewriteObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) { E = Exp->arg_end(); I != E; ++I) { BlkExprs.push_back(*I); } - CallExpr *CE = new (Context) CallExpr(*Context, PE, BlkExprs, - Exp->getType(), VK_RValue, - SourceLocation()); + CallExpr *CE = CallExpr::Create(*Context, PE, BlkExprs, Exp->getType(), + VK_RValue, SourceLocation()); return CE; } @@ -4179,7 +4177,7 @@ void RewriteObjC::RewriteByRefVar(VarDecl *ND) { // Use variable's location which is good for this case. DeclLoc = ND->getLocation(); const char *startBuf = SM->getCharacterData(DeclLoc); - SourceLocation X = ND->getLocEnd(); + SourceLocation X = ND->getEndLoc(); X = SM->getExpansionLoc(X); const char *endBuf = SM->getCharacterData(X); std::string Name(ND->getNameAsString()); @@ -4212,7 +4210,7 @@ void RewriteObjC::RewriteByRefVar(VarDecl *ND) { FunLocStart = CurFunctionDef->getTypeSpecStartLoc(); else { assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null"); - FunLocStart = CurMethodDef->getLocStart(); + FunLocStart = CurMethodDef->getBeginLoc(); } InsertText(FunLocStart, ByrefType); if (Ty.isObjCGCWeak()) { @@ -4274,7 +4272,7 @@ void RewriteObjC::RewriteByRefVar(VarDecl *ND) { if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) startLoc = ECE->getLParenLoc(); else - startLoc = E->getLocStart(); + startLoc = E->getBeginLoc(); startLoc = SM->getExpansionLoc(startLoc); endBuf = SM->getCharacterData(startLoc); ByrefType += " " + Name; @@ -4411,17 +4409,17 @@ Stmt *RewriteObjC::SynthBlockInitExpr(BlockExpr *Exp, // Simulate a constructor call... FD = SynthBlockInitFunctionDecl(Tag); - DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, false, FType, VK_RValue, - SourceLocation()); + DeclRefExpr *DRE = new (Context) + DeclRefExpr(*Context, FD, false, FType, VK_RValue, SourceLocation()); SmallVector<Expr*, 4> InitExprs; // Initialize the block function. FD = SynthBlockInitFunctionDecl(Func); - DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, false, FD->getType(), - VK_LValue, SourceLocation()); - CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy, - CK_BitCast, Arg); + DeclRefExpr *Arg = new (Context) DeclRefExpr( + *Context, FD, false, FD->getType(), VK_LValue, SourceLocation()); + CastExpr *castExpr = + NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy, CK_BitCast, Arg); InitExprs.push_back(castExpr); // Initialize the block descriptor. @@ -4430,15 +4428,11 @@ Stmt *RewriteObjC::SynthBlockInitExpr(BlockExpr *Exp, VarDecl *NewVD = VarDecl::Create( *Context, TUDecl, SourceLocation(), SourceLocation(), &Context->Idents.get(DescData), Context->VoidPtrTy, nullptr, SC_Static); - UnaryOperator *DescRefExpr = - new (Context) UnaryOperator(new (Context) DeclRefExpr(NewVD, false, - Context->VoidPtrTy, - VK_LValue, - SourceLocation()), - UO_AddrOf, - Context->getPointerType(Context->VoidPtrTy), - VK_RValue, OK_Ordinary, - SourceLocation(), false); + UnaryOperator *DescRefExpr = new (Context) UnaryOperator( + new (Context) DeclRefExpr(*Context, NewVD, false, Context->VoidPtrTy, + VK_LValue, SourceLocation()), + UO_AddrOf, Context->getPointerType(Context->VoidPtrTy), VK_RValue, + OK_Ordinary, SourceLocation(), false); InitExprs.push_back(DescRefExpr); // Add initializers for any closure decl refs. @@ -4450,8 +4444,8 @@ Stmt *RewriteObjC::SynthBlockInitExpr(BlockExpr *Exp, if (isObjCType((*I)->getType())) { // FIXME: Conform to ABI ([[obj retain] autorelease]). FD = SynthBlockInitFunctionDecl((*I)->getName()); - Exp = new (Context) DeclRefExpr(FD, false, FD->getType(), VK_LValue, - SourceLocation()); + Exp = new (Context) DeclRefExpr(*Context, FD, false, FD->getType(), + VK_LValue, SourceLocation()); if (HasLocalVariableExternalStorage(*I)) { QualType QT = (*I)->getType(); QT = Context->getPointerType(QT); @@ -4461,14 +4455,14 @@ Stmt *RewriteObjC::SynthBlockInitExpr(BlockExpr *Exp, } } else if (isTopLevelBlockPointerType((*I)->getType())) { FD = SynthBlockInitFunctionDecl((*I)->getName()); - Arg = new (Context) DeclRefExpr(FD, false, FD->getType(), VK_LValue, - SourceLocation()); - Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy, - CK_BitCast, Arg); + Arg = new (Context) DeclRefExpr(*Context, FD, false, FD->getType(), + VK_LValue, SourceLocation()); + Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy, CK_BitCast, + Arg); } else { FD = SynthBlockInitFunctionDecl((*I)->getName()); - Exp = new (Context) DeclRefExpr(FD, false, FD->getType(), VK_LValue, - SourceLocation()); + Exp = new (Context) DeclRefExpr(*Context, FD, false, FD->getType(), + VK_LValue, SourceLocation()); if (HasLocalVariableExternalStorage(*I)) { QualType QT = (*I)->getType(); QT = Context->getPointerType(QT); @@ -4495,8 +4489,8 @@ Stmt *RewriteObjC::SynthBlockInitExpr(BlockExpr *Exp, QualType castT = Context->getPointerType(Context->getTagDeclType(RD)); FD = SynthBlockInitFunctionDecl((*I)->getName()); - Exp = new (Context) DeclRefExpr(FD, false, FD->getType(), VK_LValue, - SourceLocation()); + Exp = new (Context) DeclRefExpr(*Context, FD, false, FD->getType(), + VK_LValue, SourceLocation()); bool isNestedCapturedVar = false; if (block) for (const auto &CI : block->captures()) { @@ -4527,11 +4521,11 @@ Stmt *RewriteObjC::SynthBlockInitExpr(BlockExpr *Exp, Context->IntTy, SourceLocation()); InitExprs.push_back(FlagExp); } - NewRep = new (Context) CallExpr(*Context, DRE, InitExprs, - FType, VK_LValue, SourceLocation()); - NewRep = new (Context) UnaryOperator(NewRep, UO_AddrOf, - Context->getPointerType(NewRep->getType()), - VK_RValue, OK_Ordinary, SourceLocation(), false); + NewRep = CallExpr::Create(*Context, DRE, InitExprs, FType, VK_LValue, + SourceLocation()); + NewRep = new (Context) UnaryOperator( + NewRep, UO_AddrOf, Context->getPointerType(NewRep->getType()), VK_RValue, + OK_Ordinary, SourceLocation(), false); NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CK_BitCast, NewRep); BlockDeclRefs.clear(); @@ -4632,8 +4626,8 @@ Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) { if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) { #if 0 // Before we rewrite it, put the original message expression in a comment. - SourceLocation startLoc = MessExpr->getLocStart(); - SourceLocation endLoc = MessExpr->getLocEnd(); + SourceLocation startLoc = MessExpr->getBeginLoc(); + SourceLocation endLoc = MessExpr->getEndLoc(); const char *startBuf = SM->getCharacterData(startLoc); const char *endBuf = SM->getCharacterData(endLoc); @@ -4760,7 +4754,7 @@ Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) { const std::string &Str = Buf.str(); printf("CAST = %s\n", &Str[0]); - InsertText(ICE->getSubExpr()->getLocStart(), Str); + InsertText(ICE->getSubExpr()->getBeginLoc(), Str); delete S; return Replacement; } @@ -5873,8 +5867,8 @@ Stmt *RewriteObjCFragileABI::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) { CK_BitCast, IV->getBase()); // Don't forget the parens to enforce the proper binding. - ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(), - IV->getBase()->getLocEnd(), castExpr); + ParenExpr *PE = new (Context) ParenExpr( + IV->getBase()->getBeginLoc(), IV->getBase()->getEndLoc(), castExpr); // Cannot delete IV->getBase(), since PE points to it. // Replace the old base with the cast. This is important when doing // embedded rewrites. For example, [newInv->_container addObject:0]. |