aboutsummaryrefslogtreecommitdiffstats
path: root/lib/Frontend
diff options
context:
space:
mode:
Diffstat (limited to 'lib/Frontend')
-rw-r--r--lib/Frontend/ASTConsumers.cpp8
-rw-r--r--lib/Frontend/ASTUnit.cpp74
-rw-r--r--lib/Frontend/ChainedIncludesSource.cpp2
-rw-r--r--lib/Frontend/CompilerInstance.cpp117
-rw-r--r--lib/Frontend/CompilerInvocation.cpp376
-rw-r--r--lib/Frontend/CreateInvocationFromCommandLine.cpp16
-rw-r--r--lib/Frontend/DependencyFile.cpp25
-rw-r--r--lib/Frontend/DependencyGraph.cpp4
-rw-r--r--lib/Frontend/FrontendAction.cpp29
-rw-r--r--lib/Frontend/FrontendActions.cpp61
-rw-r--r--lib/Frontend/FrontendOptions.cpp37
-rw-r--r--lib/Frontend/HeaderIncludeGen.cpp5
-rw-r--r--lib/Frontend/InitHeaderSearch.cpp19
-rw-r--r--lib/Frontend/InitPreprocessor.cpp79
-rw-r--r--lib/Frontend/InterfaceStubFunctionsConsumer.cpp106
-rw-r--r--lib/Frontend/LangStandards.cpp42
-rw-r--r--lib/Frontend/ModuleDependencyCollector.cpp8
-rw-r--r--lib/Frontend/MultiplexConsumer.cpp4
-rw-r--r--lib/Frontend/PrecompiledPreamble.cpp24
-rw-r--r--lib/Frontend/PrintPreprocessedOutput.cpp2
-rw-r--r--lib/Frontend/Rewrite/FixItRewriter.cpp2
-rw-r--r--lib/Frontend/Rewrite/FrontendActions.cpp15
-rw-r--r--lib/Frontend/Rewrite/HTMLPrint.cpp2
-rw-r--r--lib/Frontend/Rewrite/InclusionRewriter.cpp180
-rw-r--r--lib/Frontend/Rewrite/RewriteModernObjC.cpp45
-rw-r--r--lib/Frontend/Rewrite/RewriteObjC.cpp23
-rw-r--r--lib/Frontend/SerializedDiagnosticPrinter.cpp8
-rw-r--r--lib/Frontend/TextDiagnostic.cpp11
-rw-r--r--lib/Frontend/VerifyDiagnosticConsumer.cpp11
29 files changed, 664 insertions, 671 deletions
diff --git a/lib/Frontend/ASTConsumers.cpp b/lib/Frontend/ASTConsumers.cpp
index 26154ee2e856..043b2541b8f8 100644
--- a/lib/Frontend/ASTConsumers.cpp
+++ b/lib/Frontend/ASTConsumers.cpp
@@ -139,7 +139,7 @@ namespace {
std::unique_ptr<ASTConsumer>
clang::CreateASTPrinter(std::unique_ptr<raw_ostream> Out,
StringRef FilterString) {
- return llvm::make_unique<ASTPrinter>(std::move(Out), ASTPrinter::Print,
+ return std::make_unique<ASTPrinter>(std::move(Out), ASTPrinter::Print,
ADOF_Default, FilterString);
}
@@ -148,7 +148,7 @@ clang::CreateASTDumper(std::unique_ptr<raw_ostream> Out, StringRef FilterString,
bool DumpDecls, bool Deserialize, bool DumpLookups,
ASTDumpOutputFormat Format) {
assert((DumpDecls || Deserialize || DumpLookups) && "nothing to dump");
- return llvm::make_unique<ASTPrinter>(std::move(Out),
+ return std::make_unique<ASTPrinter>(std::move(Out),
Deserialize ? ASTPrinter::DumpFull :
DumpDecls ? ASTPrinter::Dump :
ASTPrinter::None, Format,
@@ -156,7 +156,7 @@ clang::CreateASTDumper(std::unique_ptr<raw_ostream> Out, StringRef FilterString,
}
std::unique_ptr<ASTConsumer> clang::CreateASTDeclNodeLister() {
- return llvm::make_unique<ASTDeclNodeLister>(nullptr);
+ return std::make_unique<ASTDeclNodeLister>(nullptr);
}
//===----------------------------------------------------------------------===//
@@ -193,5 +193,5 @@ void ASTViewer::HandleTopLevelSingleDecl(Decl *D) {
}
std::unique_ptr<ASTConsumer> clang::CreateASTViewer() {
- return llvm::make_unique<ASTViewer>();
+ return std::make_unique<ASTViewer>();
}
diff --git a/lib/Frontend/ASTUnit.cpp b/lib/Frontend/ASTUnit.cpp
index 7445a94cfe59..f5e291b7fe17 100644
--- a/lib/Frontend/ASTUnit.cpp
+++ b/lib/Frontend/ASTUnit.cpp
@@ -30,6 +30,7 @@
#include "clang/Basic/IdentifierTable.h"
#include "clang/Basic/LLVM.h"
#include "clang/Basic/LangOptions.h"
+#include "clang/Basic/LangStandard.h"
#include "clang/Basic/Module.h"
#include "clang/Basic/SourceLocation.h"
#include "clang/Basic/SourceManager.h"
@@ -83,8 +84,8 @@
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/ErrorOr.h"
#include "llvm/Support/FileSystem.h"
+#include "llvm/Support/FileUtilities.h"
#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"
@@ -95,6 +96,7 @@
#include <cstdio>
#include <cstdlib>
#include <memory>
+#include <mutex>
#include <string>
#include <tuple>
#include <utility>
@@ -435,7 +437,6 @@ void ASTUnit::CacheCodeCompletionResults() {
| (1LL << CodeCompletionContext::CCC_UnionTag)
| (1LL << CodeCompletionContext::CCC_ClassOrStructTag)
| (1LL << CodeCompletionContext::CCC_Type)
- | (1LL << CodeCompletionContext::CCC_Symbol)
| (1LL << CodeCompletionContext::CCC_SymbolOrNewName)
| (1LL << CodeCompletionContext::CCC_ParenthesizedExpression);
@@ -819,7 +820,7 @@ std::unique_ptr<ASTUnit> ASTUnit::LoadFromASTFile(
/*isysroot=*/"",
/*DisableValidation=*/disableValid, AllowPCHWithCompilerErrors);
- AST->Reader->setListener(llvm::make_unique<ASTInfoCollector>(
+ AST->Reader->setListener(std::make_unique<ASTInfoCollector>(
*AST->PP, AST->Ctx.get(), *AST->HSOpts, *AST->PPOpts, *AST->LangOpts,
AST->TargetOpts, AST->Target, Counter));
@@ -999,9 +1000,9 @@ public:
std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &CI,
StringRef InFile) override {
CI.getPreprocessor().addPPCallbacks(
- llvm::make_unique<MacroDefinitionTrackerPPCallbacks>(
+ std::make_unique<MacroDefinitionTrackerPPCallbacks>(
Unit.getCurrentTopLevelHashValue()));
- return llvm::make_unique<TopLevelDeclTrackerConsumer>(
+ return std::make_unique<TopLevelDeclTrackerConsumer>(
Unit, Unit.getCurrentTopLevelHashValue());
}
@@ -1049,7 +1050,7 @@ public:
}
std::unique_ptr<PPCallbacks> createPPCallbacks() override {
- return llvm::make_unique<MacroDefinitionTrackerPPCallbacks>(Hash);
+ return std::make_unique<MacroDefinitionTrackerPPCallbacks>(Hash);
}
private:
@@ -1154,7 +1155,7 @@ bool ASTUnit::Parse(std::shared_ptr<PCHContainerOperations> PCHContainerOps,
InputKind::Source &&
"FIXME: AST inputs not yet supported here!");
assert(Clang->getFrontendOpts().Inputs[0].getKind().getLanguage() !=
- InputKind::LLVM_IR &&
+ Language::LLVM_IR &&
"IR inputs not support here!");
// Configure the various subsystems.
@@ -1587,7 +1588,7 @@ ASTUnit *ASTUnit::LoadFromCompilerInvocationAction(
InputKind::Source &&
"FIXME: AST inputs not yet supported here!");
assert(Clang->getFrontendOpts().Inputs[0].getKind().getLanguage() !=
- InputKind::LLVM_IR &&
+ Language::LLVM_IR &&
"IR inputs not support here!");
// Configure the various subsystems.
@@ -1624,15 +1625,15 @@ ASTUnit *ASTUnit::LoadFromCompilerInvocationAction(
if (Persistent && !TrackerAct) {
Clang->getPreprocessor().addPPCallbacks(
- llvm::make_unique<MacroDefinitionTrackerPPCallbacks>(
+ std::make_unique<MacroDefinitionTrackerPPCallbacks>(
AST->getCurrentTopLevelHashValue()));
std::vector<std::unique_ptr<ASTConsumer>> Consumers;
if (Clang->hasASTConsumer())
Consumers.push_back(Clang->takeASTConsumer());
- Consumers.push_back(llvm::make_unique<TopLevelDeclTrackerConsumer>(
+ Consumers.push_back(std::make_unique<TopLevelDeclTrackerConsumer>(
*AST, AST->getCurrentTopLevelHashValue()));
Clang->setASTConsumer(
- llvm::make_unique<MultiplexConsumer>(std::move(Consumers)));
+ std::make_unique<MultiplexConsumer>(std::move(Consumers)));
}
if (llvm::Error Err = Act->Execute()) {
consumeError(std::move(Err)); // FIXME this drops errors on the floor.
@@ -1735,6 +1736,7 @@ ASTUnit *ASTUnit::LoadFromCommandLine(
bool CacheCodeCompletionResults, bool IncludeBriefCommentsInCodeCompletion,
bool AllowPCHWithCompilerErrors, SkipFunctionBodiesScope SkipFunctionBodies,
bool SingleFileParse, bool UserFilesAreVolatile, bool ForSerialization,
+ bool RetainExcludedConditionalBlocks,
llvm::Optional<StringRef> ModuleFormat, std::unique_ptr<ASTUnit> *ErrAST,
IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS) {
assert(Diags.get() && "no DiagnosticsEngine was provided");
@@ -1762,6 +1764,7 @@ ASTUnit *ASTUnit::LoadFromCommandLine(
PPOpts.RemappedFilesKeepOriginalName = RemappedFilesKeepOriginalName;
PPOpts.AllowPCHWithCompilerErrors = AllowPCHWithCompilerErrors;
PPOpts.SingleFileParseMode = SingleFileParse;
+ PPOpts.RetainExcludedConditionalBlocks = RetainExcludedConditionalBlocks;
// Override the resources path.
CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
@@ -2211,7 +2214,7 @@ void ASTUnit::CodeComplete(
InputKind::Source &&
"FIXME: AST inputs not yet supported here!");
assert(Clang->getFrontendOpts().Inputs[0].getKind().getLanguage() !=
- InputKind::LLVM_IR &&
+ Language::LLVM_IR &&
"IR inputs not support here!");
// Use the source and file managers that we were given.
@@ -2299,26 +2302,19 @@ bool ASTUnit::Save(StringRef File) {
SmallString<128> TempPath;
TempPath = File;
TempPath += "-%%%%%%%%";
- int fd;
- if (llvm::sys::fs::createUniqueFile(TempPath, fd, TempPath))
- return true;
-
// FIXME: Can we somehow regenerate the stat cache here, or do we need to
// unconditionally create a stat cache when we parse the file?
- llvm::raw_fd_ostream Out(fd, /*shouldClose=*/true);
-
- serialize(Out);
- Out.close();
- if (Out.has_error()) {
- Out.clear_error();
- return true;
- }
- if (llvm::sys::fs::rename(TempPath, File)) {
- llvm::sys::fs::remove(TempPath);
+ if (llvm::Error Err = llvm::writeFileAtomically(
+ TempPath, File, [this](llvm::raw_ostream &Out) {
+ return serialize(Out) ? llvm::make_error<llvm::StringError>(
+ "ASTUnit serialization failed",
+ llvm::inconvertibleErrorCode())
+ : llvm::Error::success();
+ })) {
+ consumeError(std::move(Err));
return true;
}
-
return false;
}
@@ -2369,13 +2365,13 @@ void ASTUnit::TranslateStoredDiagnostics(
// Rebuild the StoredDiagnostic.
if (SD.Filename.empty())
continue;
- const FileEntry *FE = FileMgr.getFile(SD.Filename);
+ auto FE = FileMgr.getFile(SD.Filename);
if (!FE)
continue;
SourceLocation FileLoc;
auto ItFileID = PreambleSrcLocCache.find(SD.Filename);
if (ItFileID == PreambleSrcLocCache.end()) {
- FileID FID = SrcMgr.translateFile(FE);
+ FileID FID = SrcMgr.translateFile(*FE);
FileLoc = SrcMgr.getLocForStartOfFile(FID);
PreambleSrcLocCache[SD.Filename] = FileLoc;
} else {
@@ -2668,17 +2664,17 @@ bool ASTUnit::isModuleFile() const {
InputKind ASTUnit::getInputKind() const {
auto &LangOpts = getLangOpts();
- InputKind::Language Lang;
+ Language Lang;
if (LangOpts.OpenCL)
- Lang = InputKind::OpenCL;
+ Lang = Language::OpenCL;
else if (LangOpts.CUDA)
- Lang = InputKind::CUDA;
+ Lang = Language::CUDA;
else if (LangOpts.RenderScript)
- Lang = InputKind::RenderScript;
+ Lang = Language::RenderScript;
else if (LangOpts.CPlusPlus)
- Lang = LangOpts.ObjC ? InputKind::ObjCXX : InputKind::CXX;
+ Lang = LangOpts.ObjC ? Language::ObjCXX : Language::CXX;
else
- Lang = LangOpts.ObjC ? InputKind::ObjC : InputKind::C;
+ Lang = LangOpts.ObjC ? Language::ObjC : Language::C;
InputKind::Format Fmt = InputKind::Source;
if (LangOpts.getCompilingModule() == LangOptions::CMK_ModuleMap)
@@ -2692,20 +2688,20 @@ InputKind ASTUnit::getInputKind() const {
#ifndef NDEBUG
ASTUnit::ConcurrencyState::ConcurrencyState() {
- Mutex = new llvm::sys::MutexImpl(/*recursive=*/true);
+ Mutex = new std::recursive_mutex;
}
ASTUnit::ConcurrencyState::~ConcurrencyState() {
- delete static_cast<llvm::sys::MutexImpl *>(Mutex);
+ delete static_cast<std::recursive_mutex *>(Mutex);
}
void ASTUnit::ConcurrencyState::start() {
- bool acquired = static_cast<llvm::sys::MutexImpl *>(Mutex)->tryacquire();
+ bool acquired = static_cast<std::recursive_mutex *>(Mutex)->try_lock();
assert(acquired && "Concurrent access to ASTUnit!");
}
void ASTUnit::ConcurrencyState::finish() {
- static_cast<llvm::sys::MutexImpl *>(Mutex)->release();
+ static_cast<std::recursive_mutex *>(Mutex)->unlock();
}
#else // NDEBUG
diff --git a/lib/Frontend/ChainedIncludesSource.cpp b/lib/Frontend/ChainedIncludesSource.cpp
index 48154ecf4742..29fee7246d14 100644
--- a/lib/Frontend/ChainedIncludesSource.cpp
+++ b/lib/Frontend/ChainedIncludesSource.cpp
@@ -158,7 +158,7 @@ IntrusiveRefCntPtr<ExternalSemaSource> clang::createChainedIncludesSource(
auto Buffer = std::make_shared<PCHBuffer>();
ArrayRef<std::shared_ptr<ModuleFileExtension>> Extensions;
- auto consumer = llvm::make_unique<PCHGenerator>(
+ auto consumer = std::make_unique<PCHGenerator>(
Clang->getPreprocessor(), Clang->getModuleCache(), "-", /*isysroot=*/"",
Buffer, Extensions, /*AllowASTWithErrors=*/true);
Clang->getASTContext().setASTMutationListener(
diff --git a/lib/Frontend/CompilerInstance.cpp b/lib/Frontend/CompilerInstance.cpp
index cf0267549e75..c409c07ff133 100644
--- a/lib/Frontend/CompilerInstance.cpp
+++ b/lib/Frontend/CompilerInstance.cpp
@@ -13,6 +13,7 @@
#include "clang/Basic/CharInfo.h"
#include "clang/Basic/Diagnostic.h"
#include "clang/Basic/FileManager.h"
+#include "clang/Basic/LangStandard.h"
#include "clang/Basic/SourceManager.h"
#include "clang/Basic/Stack.h"
#include "clang/Basic/TargetInfo.h"
@@ -49,8 +50,6 @@
#include "llvm/Support/TimeProfiler.h"
#include "llvm/Support/Timer.h"
#include "llvm/Support/raw_ostream.h"
-#include <sys/stat.h>
-#include <system_error>
#include <time.h>
#include <utility>
@@ -85,6 +84,16 @@ void CompilerInstance::setDiagnostics(DiagnosticsEngine *Value) {
Diagnostics = Value;
}
+void CompilerInstance::setVerboseOutputStream(raw_ostream &Value) {
+ OwnedVerboseOutputStream.release();
+ VerboseOutputStream = &Value;
+}
+
+void CompilerInstance::setVerboseOutputStream(std::unique_ptr<raw_ostream> Value) {
+ OwnedVerboseOutputStream.swap(Value);
+ VerboseOutputStream = OwnedVerboseOutputStream.get();
+}
+
void CompilerInstance::setTarget(TargetInfo *Value) { Target = Value; }
void CompilerInstance::setAuxTarget(TargetInfo *Value) { AuxTarget = Value; }
@@ -161,7 +170,7 @@ static void collectIncludePCH(CompilerInstance &CI,
StringRef PCHInclude = PPOpts.ImplicitPCHInclude;
FileManager &FileMgr = CI.getFileManager();
- const DirectoryEntry *PCHDir = FileMgr.getDirectory(PCHInclude);
+ auto PCHDir = FileMgr.getDirectory(PCHInclude);
if (!PCHDir) {
MDC->addFile(PCHInclude);
return;
@@ -169,7 +178,7 @@ static void collectIncludePCH(CompilerInstance &CI,
std::error_code EC;
SmallString<128> DirNative;
- llvm::sys::path::native(PCHDir->getName(), DirNative);
+ llvm::sys::path::native((*PCHDir)->getName(), DirNative);
llvm::vfs::FileSystem &FS = FileMgr.getVirtualFileSystem();
SimpleASTReaderListener Validator(CI.getPreprocessor());
for (llvm::vfs::directory_iterator Dir = FS.dir_begin(DirNative, EC), DirEnd;
@@ -214,9 +223,9 @@ static void SetUpDiagnosticLog(DiagnosticOptions *DiagOpts,
raw_ostream *OS = &llvm::errs();
if (DiagOpts->DiagnosticLogFile != "-") {
// Create the output stream.
- auto FileOS = llvm::make_unique<llvm::raw_fd_ostream>(
+ auto FileOS = std::make_unique<llvm::raw_fd_ostream>(
DiagOpts->DiagnosticLogFile, EC,
- llvm::sys::fs::F_Append | llvm::sys::fs::F_Text);
+ llvm::sys::fs::OF_Append | llvm::sys::fs::OF_Text);
if (EC) {
Diags.Report(diag::warn_fe_cc_log_diagnostics_failure)
<< DiagOpts->DiagnosticLogFile << EC.message();
@@ -228,7 +237,7 @@ static void SetUpDiagnosticLog(DiagnosticOptions *DiagOpts,
}
// Chain in the diagnostic client which will log the diagnostics.
- auto Logger = llvm::make_unique<LogDiagnosticPrinter>(*OS, DiagOpts,
+ auto Logger = std::make_unique<LogDiagnosticPrinter>(*OS, DiagOpts,
std::move(StreamOwner));
if (CodeGenOpts)
Logger->setDwarfDebugFlags(CodeGenOpts->DwarfDebugFlags);
@@ -342,7 +351,7 @@ static void InitializeFileRemapping(DiagnosticsEngine &Diags,
// Remap files in the source manager (with other files).
for (const auto &RF : InitOpts.RemappedFiles) {
// Find the file that we're mapping to.
- const FileEntry *ToFile = FileMgr.getFile(RF.second);
+ auto ToFile = FileMgr.getFile(RF.second);
if (!ToFile) {
Diags.Report(diag::err_fe_remap_missing_to_file) << RF.first << RF.second;
continue;
@@ -350,7 +359,7 @@ static void InitializeFileRemapping(DiagnosticsEngine &Diags,
// Create the file entry for the file that we're mapping from.
const FileEntry *FromFile =
- FileMgr.getVirtualFile(RF.first, ToFile->getSize(), 0);
+ FileMgr.getVirtualFile(RF.first, (*ToFile)->getSize(), 0);
if (!FromFile) {
Diags.Report(diag::err_fe_remap_missing_from_file) << RF.first;
continue;
@@ -358,7 +367,7 @@ static void InitializeFileRemapping(DiagnosticsEngine &Diags,
// Override the contents of the "from" file with the contents of
// the "to" file.
- SourceMgr.overrideFileContents(FromFile, ToFile);
+ SourceMgr.overrideFileContents(FromFile, *ToFile);
}
SourceMgr.setOverridenFilesKeepOriginalName(
@@ -509,7 +518,8 @@ IntrusiveRefCntPtr<ASTReader> CompilerInstance::createPCHExternalASTSource(
PP, ModuleCache, &Context, PCHContainerRdr, Extensions,
Sysroot.empty() ? "" : Sysroot.data(), DisablePCHValidation,
AllowPCHWithCompilerErrors, /*AllowConfigurationMismatch*/ false,
- HSOpts.ModulesValidateSystemHeaders, UseGlobalModuleIndex));
+ HSOpts.ModulesValidateSystemHeaders, HSOpts.ValidateASTInputFilesContent,
+ UseGlobalModuleIndex));
// We need the external source to be set up before we read the AST, because
// eagerly-deserialized declarations may use it.
@@ -558,7 +568,7 @@ static bool EnableCodeCompletion(Preprocessor &PP,
unsigned Column) {
// Tell the source manager to chop off the given file at a specific
// line and column.
- const FileEntry *Entry = PP.getFileManager().getFile(Filename);
+ auto Entry = PP.getFileManager().getFile(Filename);
if (!Entry) {
PP.getDiagnostics().Report(diag::err_fe_invalid_code_complete_file)
<< Filename;
@@ -566,7 +576,7 @@ static bool EnableCodeCompletion(Preprocessor &PP,
}
// Truncate the named file at the given line/column.
- PP.SetCodeCompletionPoint(Entry, Line, Column);
+ PP.SetCodeCompletionPoint(*Entry, Line, Column);
return false;
}
@@ -666,7 +676,7 @@ CompilerInstance::createDefaultOutputFile(bool Binary, StringRef InFile,
}
std::unique_ptr<raw_pwrite_stream> CompilerInstance::createNullOutputFile() {
- return llvm::make_unique<llvm::raw_null_ostream>();
+ return std::make_unique<llvm::raw_null_ostream>();
}
std::unique_ptr<raw_pwrite_stream>
@@ -775,7 +785,7 @@ std::unique_ptr<llvm::raw_pwrite_stream> CompilerInstance::createOutputFile(
OSFile = OutFile;
OS.reset(new llvm::raw_fd_ostream(
OSFile, Error,
- (Binary ? llvm::sys::fs::F_None : llvm::sys::fs::F_Text)));
+ (Binary ? llvm::sys::fs::OF_None : llvm::sys::fs::OF_Text)));
if (Error)
return nullptr;
}
@@ -792,7 +802,7 @@ std::unique_ptr<llvm::raw_pwrite_stream> CompilerInstance::createOutputFile(
if (!Binary || OS->supportsSeeking())
return std::move(OS);
- auto B = llvm::make_unique<llvm::buffer_ostream>(*OS);
+ auto B = std::make_unique<llvm::buffer_ostream>(*OS);
assert(!NonSeekStream);
NonSeekStream = std::move(OS);
return std::move(B);
@@ -830,32 +840,39 @@ bool CompilerInstance::InitializeSourceManager(
// Figure out where to get and map in the main file.
if (InputFile != "-") {
- const FileEntry *File = FileMgr.getFile(InputFile, /*OpenFile=*/true);
- if (!File) {
+ auto FileOrErr = FileMgr.getFileRef(InputFile, /*OpenFile=*/true);
+ if (!FileOrErr) {
+ // FIXME: include the error in the diagnostic.
+ consumeError(FileOrErr.takeError());
Diags.Report(diag::err_fe_error_reading) << InputFile;
return false;
}
+ FileEntryRef File = *FileOrErr;
// The natural SourceManager infrastructure can't currently handle named
// pipes, but we would at least like to accept them for the main
// file. Detect them here, read them with the volatile flag so FileMgr will
// pick up the correct size, and simply override their contents as we do for
// STDIN.
- if (File->isNamedPipe()) {
- auto MB = FileMgr.getBufferForFile(File, /*isVolatile=*/true);
+ if (File.getFileEntry().isNamedPipe()) {
+ auto MB =
+ FileMgr.getBufferForFile(&File.getFileEntry(), /*isVolatile=*/true);
if (MB) {
// Create a new virtual file that will have the correct size.
- File = FileMgr.getVirtualFile(InputFile, (*MB)->getBufferSize(), 0);
- SourceMgr.overrideFileContents(File, std::move(*MB));
+ const FileEntry *FE =
+ FileMgr.getVirtualFile(InputFile, (*MB)->getBufferSize(), 0);
+ SourceMgr.overrideFileContents(FE, std::move(*MB));
+ SourceMgr.setMainFileID(
+ SourceMgr.createFileID(FE, SourceLocation(), Kind));
} else {
Diags.Report(diag::err_cannot_open_file) << InputFile
<< MB.getError().message();
return false;
}
+ } else {
+ SourceMgr.setMainFileID(
+ SourceMgr.createFileID(File, SourceLocation(), Kind));
}
-
- SourceMgr.setMainFileID(
- SourceMgr.createFileID(File, SourceLocation(), Kind));
} else {
llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> SBOrErr =
llvm::MemoryBuffer::getSTDIN();
@@ -884,9 +901,12 @@ bool CompilerInstance::ExecuteAction(FrontendAction &Act) {
assert(!getFrontendOpts().ShowHelp && "Client must handle '-help'!");
assert(!getFrontendOpts().ShowVersion && "Client must handle '-version'!");
- // FIXME: Take this as an argument, once all the APIs we used have moved to
- // taking it as an input instead of hard-coding llvm::errs.
- raw_ostream &OS = llvm::errs();
+ // Mark this point as the bottom of the stack if we don't have somewhere
+ // better. We generally expect frontend actions to be invoked with (nearly)
+ // DesiredStackSpace available.
+ noteBottomOfStack();
+
+ raw_ostream &OS = getVerboseOutputStream();
if (!Act.PrepareToExecute(*this))
return false;
@@ -986,8 +1006,8 @@ bool CompilerInstance::ExecuteAction(FrontendAction &Act) {
StringRef StatsFile = getFrontendOpts().StatsFile;
if (!StatsFile.empty()) {
std::error_code EC;
- auto StatS = llvm::make_unique<llvm::raw_fd_ostream>(StatsFile, EC,
- llvm::sys::fs::F_Text);
+ auto StatS = std::make_unique<llvm::raw_fd_ostream>(
+ StatsFile, EC, llvm::sys::fs::OF_Text);
if (EC) {
getDiagnostics().Report(diag::warn_fe_unable_to_open_stats_file)
<< StatsFile << EC.message();
@@ -1001,14 +1021,14 @@ bool CompilerInstance::ExecuteAction(FrontendAction &Act) {
/// Determine the appropriate source input kind based on language
/// options.
-static InputKind::Language getLanguageFromOptions(const LangOptions &LangOpts) {
+static Language getLanguageFromOptions(const LangOptions &LangOpts) {
if (LangOpts.OpenCL)
- return InputKind::OpenCL;
+ return Language::OpenCL;
if (LangOpts.CUDA)
- return InputKind::CUDA;
+ return Language::CUDA;
if (LangOpts.ObjC)
- return LangOpts.CPlusPlus ? InputKind::ObjCXX : InputKind::ObjC;
- return LangOpts.CPlusPlus ? InputKind::CXX : InputKind::C;
+ return LangOpts.CPlusPlus ? Language::ObjCXX : Language::ObjC;
+ return LangOpts.CPlusPlus ? Language::CXX : Language::C;
}
/// Compile a module file for the given module, using the options
@@ -1154,7 +1174,9 @@ static const FileEntry *getPublicModuleMap(const FileEntry *File,
llvm::sys::path::append(PublicFilename, "module.modulemap");
else
return nullptr;
- return FileMgr.getFile(PublicFilename);
+ if (auto FE = FileMgr.getFile(PublicFilename))
+ return *FE;
+ return nullptr;
}
/// Compile a module file for the given module, using the options
@@ -1367,22 +1389,22 @@ static void checkConfigMacro(Preprocessor &PP, StringRef ConfigMacro,
/// Write a new timestamp file with the given path.
static void writeTimestampFile(StringRef TimestampFile) {
std::error_code EC;
- llvm::raw_fd_ostream Out(TimestampFile.str(), EC, llvm::sys::fs::F_None);
+ llvm::raw_fd_ostream Out(TimestampFile.str(), EC, llvm::sys::fs::OF_None);
}
/// Prune the module cache of modules that haven't been accessed in
/// a long time.
static void pruneModuleCache(const HeaderSearchOptions &HSOpts) {
- struct stat StatBuf;
+ llvm::sys::fs::file_status StatBuf;
llvm::SmallString<128> TimestampFile;
TimestampFile = HSOpts.ModuleCachePath;
assert(!TimestampFile.empty());
llvm::sys::path::append(TimestampFile, "modules.timestamp");
// Try to stat() the timestamp file.
- if (::stat(TimestampFile.c_str(), &StatBuf)) {
+ if (std::error_code EC = llvm::sys::fs::status(TimestampFile, StatBuf)) {
// If the timestamp file wasn't there, create one now.
- if (errno == ENOENT) {
+ if (EC == std::errc::no_such_file_or_directory) {
writeTimestampFile(TimestampFile);
}
return;
@@ -1390,7 +1412,8 @@ static void pruneModuleCache(const HeaderSearchOptions &HSOpts) {
// Check whether the time stamp is older than our pruning interval.
// If not, do nothing.
- time_t TimeStampModTime = StatBuf.st_mtime;
+ time_t TimeStampModTime =
+ llvm::sys::toTimeT(StatBuf.getLastModificationTime());
time_t CurrentTime = time(nullptr);
if (CurrentTime - TimeStampModTime <= time_t(HSOpts.ModuleCachePruneInterval))
return;
@@ -1422,11 +1445,11 @@ static void pruneModuleCache(const HeaderSearchOptions &HSOpts) {
// Look at this file. If we can't stat it, there's nothing interesting
// there.
- if (::stat(File->path().c_str(), &StatBuf))
+ if (llvm::sys::fs::status(File->path(), StatBuf))
continue;
// If the file has been used recently enough, leave it there.
- time_t FileAccessTime = StatBuf.st_atime;
+ time_t FileAccessTime = llvm::sys::toTimeT(StatBuf.getLastAccessedTime());
if (CurrentTime - FileAccessTime <=
time_t(HSOpts.ModuleCachePruneAfter)) {
continue;
@@ -1467,7 +1490,7 @@ void CompilerInstance::createModuleManager() {
const PreprocessorOptions &PPOpts = getPreprocessorOpts();
std::unique_ptr<llvm::Timer> ReadTimer;
if (FrontendTimerGroup)
- ReadTimer = llvm::make_unique<llvm::Timer>("reading_modules",
+ ReadTimer = std::make_unique<llvm::Timer>("reading_modules",
"Reading modules",
*FrontendTimerGroup);
ModuleManager = new ASTReader(
@@ -1477,6 +1500,7 @@ void CompilerInstance::createModuleManager() {
/*AllowASTWithCompilerErrors=*/false,
/*AllowConfigurationMismatch=*/false,
HSOpts.ModulesValidateSystemHeaders,
+ HSOpts.ValidateASTInputFilesContent,
getFrontendOpts().UseGlobalModuleIndex, std::move(ReadTimer));
if (hasASTConsumer()) {
ModuleManager->setDeserializationListener(
@@ -1562,7 +1586,7 @@ bool CompilerInstance::loadModuleFile(StringRef FileName) {
SourceLocation())
<= DiagnosticsEngine::Warning;
- auto Listener = llvm::make_unique<ReadModuleNames>(*this);
+ auto Listener = std::make_unique<ReadModuleNames>(*this);
auto &ListenerRef = *Listener;
ASTReader::ListenerScope ReadModuleNamesListener(*ModuleManager,
std::move(Listener));
@@ -1718,8 +1742,9 @@ CompilerInstance::loadModule(SourceLocation ImportLoc,
if (Source != ModuleCache && !Module) {
Module = PP->getHeaderSearchInfo().lookupModule(ModuleName, true,
!IsInclusionDirective);
+ auto ModuleFile = FileMgr->getFile(ModuleFileName);
if (!Module || !Module->getASTFile() ||
- FileMgr->getFile(ModuleFileName) != Module->getASTFile()) {
+ !ModuleFile || (*ModuleFile != Module->getASTFile())) {
// Error out if Module does not refer to the file in the prebuilt
// module path.
getDiagnostics().Report(ModuleNameLoc, diag::err_module_prebuilt)
diff --git a/lib/Frontend/CompilerInvocation.cpp b/lib/Frontend/CompilerInvocation.cpp
index 8a9844096f08..665695ec3b18 100644
--- a/lib/Frontend/CompilerInvocation.cpp
+++ b/lib/Frontend/CompilerInvocation.cpp
@@ -18,6 +18,7 @@
#include "clang/Basic/FileSystemOptions.h"
#include "clang/Basic/LLVM.h"
#include "clang/Basic/LangOptions.h"
+#include "clang/Basic/LangStandard.h"
#include "clang/Basic/ObjCRuntime.h"
#include "clang/Basic/Sanitizers.h"
#include "clang/Basic/SourceLocation.h"
@@ -34,7 +35,6 @@
#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"
#include "clang/Frontend/Utils.h"
@@ -122,7 +122,7 @@ CompilerInvocationBase::~CompilerInvocationBase() = default;
static unsigned getOptimizationLevel(ArgList &Args, InputKind IK,
DiagnosticsEngine &Diags) {
unsigned DefaultOpt = llvm::CodeGenOpt::None;
- if (IK.getLanguage() == InputKind::OpenCL && !Args.hasArg(OPT_cl_opt_disable))
+ if (IK.getLanguage() == Language::OpenCL && !Args.hasArg(OPT_cl_opt_disable))
DefaultOpt = llvm::CodeGenOpt::Default;
if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
@@ -303,7 +303,7 @@ static bool ParseAnalyzerArgs(AnalyzerOptions &Opts, ArgList &Args,
.Case("true", true)
.Case("false", false)
.Default(false);
- Opts.DisableAllChecks = Args.hasArg(OPT_analyzer_disable_all_checks);
+ Opts.DisableAllCheckers = Args.hasArg(OPT_analyzer_disable_all_checks);
Opts.visualizeExplodedGraphWithGraphViz =
Args.hasArg(OPT_analyzer_viz_egraph_graphviz);
@@ -324,18 +324,18 @@ static bool ParseAnalyzerArgs(AnalyzerOptions &Opts, ArgList &Args,
getLastArgIntValue(Args, OPT_analyzer_inline_max_stack_depth,
Opts.InlineMaxStackDepth, Diags);
- Opts.CheckersControlList.clear();
+ Opts.CheckersAndPackages.clear();
for (const Arg *A :
Args.filtered(OPT_analyzer_checker, OPT_analyzer_disable_checker)) {
A->claim();
- bool enable = (A->getOption().getID() == OPT_analyzer_checker);
+ bool IsEnabled = A->getOption().getID() == OPT_analyzer_checker;
// We can have a list of comma separated checker names, e.g:
// '-analyzer-checker=cocoa,unix'
- StringRef checkerList = A->getValue();
- SmallVector<StringRef, 4> checkers;
- checkerList.split(checkers, ",");
- for (auto checker : checkers)
- Opts.CheckersControlList.emplace_back(checker, enable);
+ StringRef CheckerAndPackageList = A->getValue();
+ SmallVector<StringRef, 16> CheckersAndPackages;
+ CheckerAndPackageList.split(CheckersAndPackages, ",");
+ for (const StringRef CheckerOrPackage : CheckersAndPackages)
+ Opts.CheckersAndPackages.emplace_back(CheckerOrPackage, IsEnabled);
}
// Go through the analyzer configuration options.
@@ -464,6 +464,35 @@ static void parseAnalyzerConfigs(AnalyzerOptions &AnOpts,
// At this point, AnalyzerOptions is configured. Let's validate some options.
+ // FIXME: Here we try to validate the silenced checkers or packages are valid.
+ // The current approach only validates the registered checkers which does not
+ // contain the runtime enabled checkers and optimally we would validate both.
+ if (!AnOpts.RawSilencedCheckersAndPackages.empty()) {
+ std::vector<StringRef> Checkers =
+ AnOpts.getRegisteredCheckers(/*IncludeExperimental=*/true);
+ std::vector<StringRef> Packages =
+ AnOpts.getRegisteredPackages(/*IncludeExperimental=*/true);
+
+ SmallVector<StringRef, 16> CheckersAndPackages;
+ AnOpts.RawSilencedCheckersAndPackages.split(CheckersAndPackages, ";");
+
+ for (const StringRef CheckerOrPackage : CheckersAndPackages) {
+ if (Diags) {
+ bool IsChecker = CheckerOrPackage.contains('.');
+ bool IsValidName =
+ IsChecker
+ ? llvm::find(Checkers, CheckerOrPackage) != Checkers.end()
+ : llvm::find(Packages, CheckerOrPackage) != Packages.end();
+
+ if (!IsValidName)
+ Diags->Report(diag::err_unknown_analyzer_checker_or_package)
+ << CheckerOrPackage;
+ }
+
+ AnOpts.SilencedCheckersAndPackages.emplace_back(CheckerOrPackage);
+ }
+ }
+
if (!Diags)
return;
@@ -729,6 +758,8 @@ static bool ParseCodeGenArgs(CodeGenOptions &Opts, ArgList &Args, InputKind IK,
Opts.CodeViewGHash = Args.hasArg(OPT_gcodeview_ghash);
Opts.MacroDebugInfo = Args.hasArg(OPT_debug_info_macro);
Opts.WholeProgramVTables = Args.hasArg(OPT_fwhole_program_vtables);
+ Opts.VirtualFunctionElimination =
+ Args.hasArg(OPT_fvirtual_function_elimination);
Opts.LTOVisibilityPublicStd = Args.hasArg(OPT_flto_visibility_public_std);
Opts.SplitDwarfFile = Args.getLastArgValue(OPT_split_dwarf_file);
Opts.SplitDwarfOutput = Args.getLastArgValue(OPT_split_dwarf_output);
@@ -748,10 +779,14 @@ static bool ParseCodeGenArgs(CodeGenOptions &Opts, ArgList &Args, InputKind IK,
Opts.DisableLLVMPasses = Args.hasArg(OPT_disable_llvm_passes);
Opts.DisableLifetimeMarkers = Args.hasArg(OPT_disable_lifetimemarkers);
+ const llvm::Triple::ArchType DebugEntryValueArchs[] = {
+ llvm::Triple::x86, llvm::Triple::x86_64, llvm::Triple::aarch64,
+ llvm::Triple::arm, llvm::Triple::armeb};
+
llvm::Triple T(TargetOpts.Triple);
- llvm::Triple::ArchType Arch = T.getArch();
if (Opts.OptimizationLevel > 0 &&
- (Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64))
+ Opts.getDebugInfo() >= codegenoptions::LimitedDebugInfo &&
+ llvm::is_contained(DebugEntryValueArchs, T.getArch()))
Opts.EnableDebugEntryValues = Args.hasArg(OPT_femit_debug_entry_values);
Opts.DisableO0ImplyOptNone = Args.hasArg(OPT_disable_O0_optnone);
@@ -823,8 +858,32 @@ static bool ParseCodeGenArgs(CodeGenOptions &Opts, ArgList &Args, InputKind IK,
Opts.CXXCtorDtorAliases = Args.hasArg(OPT_mconstructor_aliases);
Opts.CodeModel = TargetOpts.CodeModel;
Opts.DebugPass = Args.getLastArgValue(OPT_mdebug_pass);
- Opts.DisableFPElim =
- (Args.hasArg(OPT_mdisable_fp_elim) || Args.hasArg(OPT_pg));
+
+ // Handle -mframe-pointer option.
+ if (Arg *A = Args.getLastArg(OPT_mframe_pointer_EQ)) {
+ CodeGenOptions::FramePointerKind FP;
+ StringRef Name = A->getValue();
+ bool ValidFP = true;
+ if (Name == "none")
+ FP = CodeGenOptions::FramePointerKind::None;
+ else if (Name == "non-leaf")
+ FP = CodeGenOptions::FramePointerKind::NonLeaf;
+ else if (Name == "all")
+ FP = CodeGenOptions::FramePointerKind::All;
+ else {
+ Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Name;
+ Success = false;
+ ValidFP = false;
+ }
+ if (ValidFP)
+ Opts.setFramePointer(FP);
+ }
+
+ // -pg may override -mframe-pointer
+ // TODO: This should be merged into getFramePointerKind in Clang.cpp.
+ if (Args.hasArg(OPT_pg))
+ Opts.setFramePointer(CodeGenOptions::FramePointerKind::All);
+
Opts.DisableFree = Args.hasArg(OPT_disable_free);
Opts.DiscardValueNames = Args.hasArg(OPT_discard_value_names);
Opts.DisableTailCalls = Args.hasArg(OPT_mdisable_tail_calls);
@@ -864,6 +923,7 @@ static bool ParseCodeGenArgs(CodeGenOptions &Opts, ArgList &Args, InputKind IK,
Opts.NumRegisterParameters = getLastArgIntValue(Args, OPT_mregparm, 0, Diags);
Opts.NoExecStack = Args.hasArg(OPT_mno_exec_stack);
Opts.FatalWarnings = Args.hasArg(OPT_massembler_fatal_warnings);
+ Opts.NoWarn = Args.hasArg(OPT_massembler_no_warn);
Opts.EnableSegmentedStacks = Args.hasArg(OPT_split_stacks);
Opts.RelaxAll = Args.hasArg(OPT_mrelax_all);
Opts.IncrementalLinkerCompatible =
@@ -871,7 +931,6 @@ static bool ParseCodeGenArgs(CodeGenOptions &Opts, ArgList &Args, InputKind IK,
Opts.PIECopyRelocations =
Args.hasArg(OPT_mpie_copy_relocations);
Opts.NoPLT = Args.hasArg(OPT_fno_plt);
- Opts.OmitLeafFramePointer = Args.hasArg(OPT_momit_leaf_frame_pointer);
Opts.SaveTempLabels = Args.hasArg(OPT_msave_temp_labels);
Opts.NoDwarfDirectoryAsm = Args.hasArg(OPT_fno_dwarf_directory_asm);
Opts.SoftFloat = Args.hasArg(OPT_msoft_float);
@@ -921,7 +980,7 @@ static bool ParseCodeGenArgs(CodeGenOptions &Opts, ArgList &Args, InputKind IK,
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)
+ if (IK.getLanguage() != Language::LLVM_IR)
Diags.Report(diag::err_drv_argument_only_allowed_with)
<< A->getAsString(Args) << "-x ir";
Opts.ThinLTOIndexFile = Args.getLastArgValue(OPT_fthinlto_index_EQ);
@@ -1115,6 +1174,8 @@ static bool ParseCodeGenArgs(CodeGenOptions &Opts, ArgList &Args, InputKind IK,
Opts.SanitizeCfiCrossDso = Args.hasArg(OPT_fsanitize_cfi_cross_dso);
Opts.SanitizeCfiICallGeneralizePointers =
Args.hasArg(OPT_fsanitize_cfi_icall_generalize_pointers);
+ Opts.SanitizeCfiCanonicalJumpTables =
+ Args.hasArg(OPT_fsanitize_cfi_canonical_jump_tables);
Opts.SanitizeStats = Args.hasArg(OPT_fsanitize_stats);
if (Arg *A = Args.getLastArg(
OPT_fsanitize_address_poison_custom_array_cookie,
@@ -1262,7 +1323,7 @@ static bool ParseCodeGenArgs(CodeGenOptions &Opts, ArgList &Args, InputKind IK,
if (Opts.DiagnosticsWithHotness && !UsingProfile &&
// An IR file will contain PGO as metadata
- IK.getLanguage() != InputKind::LLVM_IR)
+ IK.getLanguage() != Language::LLVM_IR)
Diags.Report(diag::warn_drv_diagnostics_hotness_requires_pgo)
<< "-fdiagnostics-show-hotness";
@@ -1675,23 +1736,30 @@ static InputKind ParseFrontendArgs(FrontendOptions &Opts, ArgList &Args,
Opts.ProgramAction = frontend::GenerateHeaderModule; break;
case OPT_emit_pch:
Opts.ProgramAction = frontend::GeneratePCH; break;
- case OPT_emit_iterface_stubs: {
- llvm::Optional<frontend::ActionKind> ProgramAction =
- llvm::StringSwitch<llvm::Optional<frontend::ActionKind>>(
- Args.hasArg(OPT_iterface_stub_version_EQ)
- ? Args.getLastArgValue(OPT_iterface_stub_version_EQ)
- : "")
- .Case("experimental-yaml-elf-v1",
- frontend::GenerateInterfaceYAMLExpV1)
- .Case("experimental-tapi-elf-v1",
- frontend::GenerateInterfaceTBEExpV1)
- .Default(llvm::None);
- if (!ProgramAction)
+ case OPT_emit_interface_stubs: {
+ StringRef ArgStr =
+ Args.hasArg(OPT_interface_stub_version_EQ)
+ ? Args.getLastArgValue(OPT_interface_stub_version_EQ)
+ : "experimental-ifs-v1";
+ if (ArgStr == "experimental-yaml-elf-v1" ||
+ ArgStr == "experimental-tapi-elf-v1") {
+ std::string ErrorMessage =
+ "Invalid interface stub format: " + ArgStr.str() +
+ " is deprecated.";
+ Diags.Report(diag::err_drv_invalid_value)
+ << "Must specify a valid interface stub format type, ie: "
+ "-interface-stub-version=experimental-ifs-v1"
+ << ErrorMessage;
+ } else if (ArgStr != "experimental-ifs-v1") {
+ std::string ErrorMessage =
+ "Invalid interface stub format: " + ArgStr.str() + ".";
Diags.Report(diag::err_drv_invalid_value)
- << "Must specify a valid interface stub format type using "
- << "-interface-stub-version=<experimental-tapi-elf-v1 | "
- "experimental-yaml-elf-v1>";
- Opts.ProgramAction = *ProgramAction;
+ << "Must specify a valid interface stub format type, ie: "
+ "-interface-stub-version=experimental-ifs-v1"
+ << ErrorMessage;
+ } else {
+ Opts.ProgramAction = frontend::GenerateInterfaceIfsExpV1;
+ }
break;
}
case OPT_init_only:
@@ -1773,6 +1841,8 @@ static InputKind ParseFrontendArgs(FrontendOptions &Opts, ArgList &Args,
Opts.ShowTimers = Args.hasArg(OPT_ftime_report);
Opts.PrintSupportedCPUs = Args.hasArg(OPT_print_supported_cpus);
Opts.TimeTrace = Args.hasArg(OPT_ftime_trace);
+ Opts.TimeTraceGranularity = getLastArgIntValue(
+ Args, OPT_ftime_trace_granularity_EQ, Opts.TimeTraceGranularity, Diags);
Opts.ShowVersion = Args.hasArg(OPT_version);
Opts.ASTMergeFiles = Args.getAllArgValues(OPT_ast_merge);
Opts.LLVMArgs = Args.getAllArgValues(OPT_mllvm);
@@ -1877,7 +1947,7 @@ static InputKind ParseFrontendArgs(FrontendOptions &Opts, ArgList &Args,
<< "ARC migration" << "ObjC migration";
}
- InputKind DashX(InputKind::Unknown);
+ InputKind DashX(Language::Unknown);
if (const Arg *A = Args.getLastArg(OPT_x)) {
StringRef XValue = A->getValue();
@@ -1890,33 +1960,33 @@ static InputKind ParseFrontendArgs(FrontendOptions &Opts, ArgList &Args,
// Principal languages.
DashX = llvm::StringSwitch<InputKind>(XValue)
- .Case("c", InputKind::C)
- .Case("cl", InputKind::OpenCL)
- .Case("cuda", InputKind::CUDA)
- .Case("hip", InputKind::HIP)
- .Case("c++", InputKind::CXX)
- .Case("objective-c", InputKind::ObjC)
- .Case("objective-c++", InputKind::ObjCXX)
- .Case("renderscript", InputKind::RenderScript)
- .Default(InputKind::Unknown);
+ .Case("c", Language::C)
+ .Case("cl", Language::OpenCL)
+ .Case("cuda", Language::CUDA)
+ .Case("hip", Language::HIP)
+ .Case("c++", Language::CXX)
+ .Case("objective-c", Language::ObjC)
+ .Case("objective-c++", Language::ObjCXX)
+ .Case("renderscript", Language::RenderScript)
+ .Default(Language::Unknown);
// "objc[++]-cpp-output" is an acceptable synonym for
// "objective-c[++]-cpp-output".
if (DashX.isUnknown() && Preprocessed && !IsHeaderFile && !ModuleMap)
DashX = llvm::StringSwitch<InputKind>(XValue)
- .Case("objc", InputKind::ObjC)
- .Case("objc++", InputKind::ObjCXX)
- .Default(InputKind::Unknown);
+ .Case("objc", Language::ObjC)
+ .Case("objc++", Language::ObjCXX)
+ .Default(Language::Unknown);
// Some special cases cannot be combined with suffixes.
if (DashX.isUnknown() && !Preprocessed && !ModuleMap && !IsHeaderFile)
DashX = llvm::StringSwitch<InputKind>(XValue)
- .Case("cpp-output", InputKind(InputKind::C).getPreprocessed())
- .Case("assembler-with-cpp", InputKind::Asm)
+ .Case("cpp-output", InputKind(Language::C).getPreprocessed())
+ .Case("assembler-with-cpp", Language::Asm)
.Cases("ast", "pcm",
- InputKind(InputKind::Unknown, InputKind::Precompiled))
- .Case("ir", InputKind::LLVM_IR)
- .Default(InputKind::Unknown);
+ InputKind(Language::Unknown, InputKind::Precompiled))
+ .Case("ir", Language::LLVM_IR)
+ .Default(Language::Unknown);
if (DashX.isUnknown())
Diags.Report(diag::err_drv_invalid_value)
@@ -1940,7 +2010,7 @@ static InputKind ParseFrontendArgs(FrontendOptions &Opts, ArgList &Args,
StringRef(Inputs[i]).rsplit('.').second);
// FIXME: Warn on this?
if (IK.isUnknown())
- IK = InputKind::C;
+ IK = Language::C;
// FIXME: Remove this hack.
if (i == 0)
DashX = IK;
@@ -1997,6 +2067,7 @@ static void ParseHeaderSearchArgs(HeaderSearchOptions &Opts, ArgList &Args,
Opts.AddPrebuiltModulePath(A->getValue());
Opts.DisableModuleHash = Args.hasArg(OPT_fdisable_module_hash);
Opts.ModulesHashContent = Args.hasArg(OPT_fmodules_hash_content);
+ Opts.ModulesStrictContextHash = Args.hasArg(OPT_fmodules_strict_context_hash);
Opts.ModulesValidateDiagnosticOptions =
!Args.hasArg(OPT_fmodules_disable_diagnostic_validation);
Opts.ImplicitModuleMaps = Args.hasArg(OPT_fimplicit_module_maps);
@@ -2011,6 +2082,8 @@ static void ParseHeaderSearchArgs(HeaderSearchOptions &Opts, ArgList &Args,
getLastArgUInt64Value(Args, OPT_fbuild_session_timestamp, 0);
Opts.ModulesValidateSystemHeaders =
Args.hasArg(OPT_fmodules_validate_system_headers);
+ Opts.ValidateASTInputFilesContent =
+ Args.hasArg(OPT_fvalidate_ast_input_files_content);
if (const Arg *A = Args.getLastArg(OPT_fmodule_format_EQ))
Opts.ModuleFormat = A->getValue();
@@ -2114,7 +2187,7 @@ void CompilerInvocation::setLangDefaults(LangOptions &Opts, InputKind IK,
// FIXME: Perhaps a better model would be for a single source file to have
// multiple language standards (C / C++ std, ObjC std, OpenCL std, OpenMP std)
// simultaneously active?
- if (IK.getLanguage() == InputKind::Asm) {
+ if (IK.getLanguage() == Language::Asm) {
Opts.AsmPreprocessor = 1;
} else if (IK.isObjectiveC()) {
Opts.ObjC = 1;
@@ -2123,17 +2196,17 @@ void CompilerInvocation::setLangDefaults(LangOptions &Opts, InputKind IK,
if (LangStd == LangStandard::lang_unspecified) {
// Based on the base language, pick one.
switch (IK.getLanguage()) {
- case InputKind::Unknown:
- case InputKind::LLVM_IR:
+ case Language::Unknown:
+ case Language::LLVM_IR:
llvm_unreachable("Invalid input kind!");
- case InputKind::OpenCL:
+ case Language::OpenCL:
LangStd = LangStandard::lang_opencl10;
break;
- case InputKind::CUDA:
+ case Language::CUDA:
LangStd = LangStandard::lang_cuda;
break;
- case InputKind::Asm:
- case InputKind::C:
+ case Language::Asm:
+ case Language::C:
#if defined(CLANG_DEFAULT_STD_C)
LangStd = CLANG_DEFAULT_STD_C;
#else
@@ -2144,25 +2217,25 @@ void CompilerInvocation::setLangDefaults(LangOptions &Opts, InputKind IK,
LangStd = LangStandard::lang_gnu11;
#endif
break;
- case InputKind::ObjC:
+ case Language::ObjC:
#if defined(CLANG_DEFAULT_STD_C)
LangStd = CLANG_DEFAULT_STD_C;
#else
LangStd = LangStandard::lang_gnu11;
#endif
break;
- case InputKind::CXX:
- case InputKind::ObjCXX:
+ case Language::CXX:
+ case Language::ObjCXX:
#if defined(CLANG_DEFAULT_STD_CXX)
LangStd = CLANG_DEFAULT_STD_CXX;
#else
LangStd = LangStandard::lang_gnucxx14;
#endif
break;
- case InputKind::RenderScript:
+ case Language::RenderScript:
LangStd = LangStandard::lang_c99;
break;
- case InputKind::HIP:
+ case Language::HIP:
LangStd = LangStandard::lang_hip;
break;
}
@@ -2182,6 +2255,7 @@ void CompilerInvocation::setLangDefaults(LangOptions &Opts, InputKind IK,
Opts.Digraphs = Std.hasDigraphs();
Opts.GNUMode = Std.isGNUMode();
Opts.GNUInline = !Opts.C99 && !Opts.CPlusPlus;
+ Opts.GNUCVersion = 0;
Opts.HexFloats = Std.hasHexFloats();
Opts.ImplicitInt = Std.hasImplicitInt();
@@ -2202,7 +2276,7 @@ void CompilerInvocation::setLangDefaults(LangOptions &Opts, InputKind IK,
if (Opts.OpenCL) {
Opts.AltiVec = 0;
Opts.ZVector = 0;
- Opts.LaxVectorConversions = 0;
+ Opts.setLaxVectorConversions(LangOptions::LaxVectorConversionKind::None);
Opts.setDefaultFPContractMode(LangOptions::FPC_On);
Opts.NativeHalfType = 1;
Opts.NativeHalfArgsAndReturns = 1;
@@ -2219,13 +2293,13 @@ void CompilerInvocation::setLangDefaults(LangOptions &Opts, InputKind IK,
}
}
- Opts.HIP = IK.getLanguage() == InputKind::HIP;
- Opts.CUDA = IK.getLanguage() == InputKind::CUDA || Opts.HIP;
+ Opts.HIP = IK.getLanguage() == Language::HIP;
+ Opts.CUDA = IK.getLanguage() == Language::CUDA || Opts.HIP;
if (Opts.CUDA)
// Set default FP_CONTRACT to FAST.
Opts.setDefaultFPContractMode(LangOptions::FPC_Fast);
- Opts.RenderScript = IK.getLanguage() == InputKind::RenderScript;
+ Opts.RenderScript = IK.getLanguage() == Language::RenderScript;
if (Opts.RenderScript) {
Opts.NativeHalfType = 1;
Opts.NativeHalfArgsAndReturns = 1;
@@ -2273,32 +2347,31 @@ static Visibility parseVisibility(Arg *arg, ArgList &args,
static bool IsInputCompatibleWithStandard(InputKind IK,
const LangStandard &S) {
switch (IK.getLanguage()) {
- case InputKind::Unknown:
- case InputKind::LLVM_IR:
+ case Language::Unknown:
+ case Language::LLVM_IR:
llvm_unreachable("should not parse language flags for this input");
- case InputKind::C:
- case InputKind::ObjC:
- case InputKind::RenderScript:
- return S.getLanguage() == InputKind::C;
+ case Language::C:
+ case Language::ObjC:
+ case Language::RenderScript:
+ return S.getLanguage() == Language::C;
- case InputKind::OpenCL:
- return S.getLanguage() == InputKind::OpenCL;
+ case Language::OpenCL:
+ return S.getLanguage() == Language::OpenCL;
- case InputKind::CXX:
- case InputKind::ObjCXX:
- return S.getLanguage() == InputKind::CXX;
+ case Language::CXX:
+ case Language::ObjCXX:
+ return S.getLanguage() == Language::CXX;
- case InputKind::CUDA:
+ case Language::CUDA:
// FIXME: What -std= values should be permitted for CUDA compilations?
- return S.getLanguage() == InputKind::CUDA ||
- S.getLanguage() == InputKind::CXX;
+ return S.getLanguage() == Language::CUDA ||
+ S.getLanguage() == Language::CXX;
- case InputKind::HIP:
- return S.getLanguage() == InputKind::CXX ||
- S.getLanguage() == InputKind::HIP;
+ case Language::HIP:
+ return S.getLanguage() == Language::CXX || S.getLanguage() == Language::HIP;
- case InputKind::Asm:
+ case Language::Asm:
// Accept (and ignore) all -std= values.
// FIXME: The -std= value is not ignored; it affects the tokenization
// and preprocessing rules if we're preprocessing this asm input.
@@ -2311,29 +2384,29 @@ static bool IsInputCompatibleWithStandard(InputKind IK,
/// Get language name for given input kind.
static const StringRef GetInputKindName(InputKind IK) {
switch (IK.getLanguage()) {
- case InputKind::C:
+ case Language::C:
return "C";
- case InputKind::ObjC:
+ case Language::ObjC:
return "Objective-C";
- case InputKind::CXX:
+ case Language::CXX:
return "C++";
- case InputKind::ObjCXX:
+ case Language::ObjCXX:
return "Objective-C++";
- case InputKind::OpenCL:
+ case Language::OpenCL:
return "OpenCL";
- case InputKind::CUDA:
+ case Language::CUDA:
return "CUDA";
- case InputKind::RenderScript:
+ case Language::RenderScript:
return "RenderScript";
- case InputKind::HIP:
+ case Language::HIP:
return "HIP";
- case InputKind::Asm:
+ case Language::Asm:
return "Asm";
- case InputKind::LLVM_IR:
+ case Language::LLVM_IR:
return "LLVM IR";
- case InputKind::Unknown:
+ case Language::Unknown:
break;
}
llvm_unreachable("unknown input language");
@@ -2346,13 +2419,7 @@ static void ParseLangArgs(LangOptions &Opts, ArgList &Args, InputKind IK,
// FIXME: Cleanup per-file based stuff.
LangStandard::Kind LangStd = LangStandard::lang_unspecified;
if (const Arg *A = Args.getLastArg(OPT_std_EQ)) {
- LangStd = llvm::StringSwitch<LangStandard::Kind>(A->getValue())
-#define LANGSTANDARD(id, name, lang, desc, features) \
- .Case(name, LangStandard::lang_##id)
-#define LANGSTANDARD_ALIAS(id, alias) \
- .Case(alias, LangStandard::lang_##id)
-#include "clang/Frontend/LangStandards.def"
- .Default(LangStandard::lang_unspecified);
+ LangStd = LangStandard::getLangKind(A->getValue());
if (LangStd == LangStandard::lang_unspecified) {
Diags.Report(diag::err_drv_invalid_value)
<< A->getAsString(Args) << A->getValue();
@@ -2370,13 +2437,13 @@ static void ParseLangArgs(LangOptions &Opts, ArgList &Args, InputKind IK,
#define LANGSTANDARD_ALIAS(id, alias) \
if (KindValue == LangStandard::lang_##id) ++NumAliases;
#define LANGSTANDARD_ALIAS_DEPR(id, alias)
-#include "clang/Frontend/LangStandards.def"
+#include "clang/Basic/LangStandards.def"
Diag << NumAliases;
#define LANGSTANDARD(id, name, lang, desc, features)
#define LANGSTANDARD_ALIAS(id, alias) \
if (KindValue == LangStandard::lang_##id) Diag << alias;
#define LANGSTANDARD_ALIAS_DEPR(id, alias)
-#include "clang/Frontend/LangStandards.def"
+#include "clang/Basic/LangStandards.def"
}
}
} else {
@@ -2408,7 +2475,7 @@ static void ParseLangArgs(LangOptions &Opts, ArgList &Args, InputKind IK,
.Cases("cl1.1", "CL1.1", LangStandard::lang_opencl11)
.Cases("cl1.2", "CL1.2", LangStandard::lang_opencl12)
.Cases("cl2.0", "CL2.0", LangStandard::lang_opencl20)
- .Case("c++", LangStandard::lang_openclcpp)
+ .Cases("clc++", "CLC++", LangStandard::lang_openclcpp)
.Default(LangStandard::lang_unspecified);
if (OpenCLLangStd == LangStandard::lang_unspecified) {
@@ -2461,6 +2528,7 @@ static void ParseLangArgs(LangOptions &Opts, ArgList &Args, InputKind IK,
Opts.CUDADeviceApproxTranscendentals = 1;
Opts.GPURelocatableDeviceCode = Args.hasArg(OPT_fgpu_rdc);
+ Opts.HIPUseNewLaunchAPI = Args.hasArg(OPT_fhip_new_launch_api);
if (Opts.ObjC) {
if (Arg *arg = Args.getLastArg(OPT_fobjc_runtime_EQ)) {
@@ -2512,6 +2580,21 @@ static void ParseLangArgs(LangOptions &Opts, ArgList &Args, InputKind IK,
(Opts.ObjCRuntime.getKind() == ObjCRuntime::FragileMacOSX);
}
+ if (Arg *A = Args.getLastArg(options::OPT_fgnuc_version_EQ)) {
+ // Check that the version has 1 to 3 components and the minor and patch
+ // versions fit in two decimal digits.
+ VersionTuple GNUCVer;
+ bool Invalid = GNUCVer.tryParse(A->getValue());
+ unsigned Major = GNUCVer.getMajor();
+ unsigned Minor = GNUCVer.getMinor().getValueOr(0);
+ unsigned Patch = GNUCVer.getSubminor().getValueOr(0);
+ if (Invalid || GNUCVer.getBuild() || Minor >= 100 || Patch >= 100) {
+ Diags.Report(diag::err_drv_invalid_value)
+ << A->getAsString(Args) << A->getValue();
+ }
+ Opts.GNUCVersion = Major * 100 * 100 + Minor * 100 + Patch;
+ }
+
if (Args.hasArg(OPT_fgnu89_inline)) {
if (Opts.CPlusPlus)
Diags.Report(diag::err_drv_argument_not_allowed_with)
@@ -2611,8 +2694,18 @@ static void ParseLangArgs(LangOptions &Opts, ArgList &Args, InputKind IK,
Opts.WritableStrings = Args.hasArg(OPT_fwritable_strings);
Opts.ConstStrings = Args.hasFlag(OPT_fconst_strings, OPT_fno_const_strings,
Opts.ConstStrings);
- if (Args.hasArg(OPT_fno_lax_vector_conversions))
- Opts.LaxVectorConversions = 0;
+ if (Arg *A = Args.getLastArg(OPT_flax_vector_conversions_EQ)) {
+ using LaxKind = LangOptions::LaxVectorConversionKind;
+ if (auto Kind = llvm::StringSwitch<Optional<LaxKind>>(A->getValue())
+ .Case("none", LaxKind::None)
+ .Case("integer", LaxKind::Integer)
+ .Case("all", LaxKind::All)
+ .Default(llvm::None))
+ Opts.setLaxVectorConversions(*Kind);
+ else
+ Diags.Report(diag::err_drv_invalid_value)
+ << A->getAsString(Args) << A->getValue();
+ }
if (Args.hasArg(OPT_fno_threadsafe_statics))
Opts.ThreadsafeStatics = 0;
Opts.Exceptions = Args.hasArg(OPT_fexceptions);
@@ -2630,9 +2723,9 @@ static void ParseLangArgs(LangOptions &Opts, ArgList &Args, InputKind IK,
Opts.FixedPoint;
// Handle exception personalities
- Arg *A = Args.getLastArg(options::OPT_fsjlj_exceptions,
- options::OPT_fseh_exceptions,
- options::OPT_fdwarf_exceptions);
+ Arg *A = Args.getLastArg(
+ options::OPT_fsjlj_exceptions, options::OPT_fseh_exceptions,
+ options::OPT_fdwarf_exceptions, options::OPT_fwasm_exceptions);
if (A) {
const Option &Opt = A->getOption();
llvm::Triple T(TargetOpts.Triple);
@@ -2643,6 +2736,7 @@ static void ParseLangArgs(LangOptions &Opts, ArgList &Args, InputKind IK,
Opts.SjLjExceptions = Opt.matches(options::OPT_fsjlj_exceptions);
Opts.SEHExceptions = Opt.matches(options::OPT_fseh_exceptions);
Opts.DWARFExceptions = Opt.matches(options::OPT_fdwarf_exceptions);
+ Opts.WasmExceptions = Opt.matches(options::OPT_fwasm_exceptions);
}
Opts.ExternCNoUnwind = Args.hasArg(OPT_fexternc_nounwind);
@@ -2727,6 +2821,10 @@ static void ParseLangArgs(LangOptions &Opts, ArgList &Args, InputKind IK,
getLastArgIntValue(Args, OPT_fconstexpr_depth, 512, Diags);
Opts.ConstexprStepLimit =
getLastArgIntValue(Args, OPT_fconstexpr_steps, 1048576, Diags);
+ Opts.EnableNewConstInterp =
+ Args.hasArg(OPT_fexperimental_new_constant_interpreter);
+ Opts.ForceNewConstInterp =
+ Args.hasArg(OPT_fforce_experimental_new_constant_interpreter);
Opts.BracketDepth = getLastArgIntValue(Args, OPT_fbracket_depth, 256, Diags);
Opts.DelayedTemplateParsing = Args.hasArg(OPT_fdelayed_template_parsing);
Opts.NumLargeByValueCopy =
@@ -2876,8 +2974,8 @@ static void ParseLangArgs(LangOptions &Opts, ArgList &Args, InputKind IK,
}
}
- // Check if -fopenmp is specified.
- Opts.OpenMP = Args.hasArg(options::OPT_fopenmp) ? 1 : 0;
+ // Check if -fopenmp is specified and set default version to 4.5.
+ Opts.OpenMP = Args.hasArg(options::OPT_fopenmp) ? 45 : 0;
// Check if -fopenmp-simd is specified.
bool IsSimdSpecified =
Args.hasFlag(options::OPT_fopenmp_simd, options::OPT_fno_openmp_simd,
@@ -3108,6 +3206,8 @@ static void ParseLangArgs(LangOptions &Opts, ArgList &Args, InputKind IK,
Opts.setClangABICompat(LangOptions::ClangABI::Ver6);
else if (Major <= 7)
Opts.setClangABICompat(LangOptions::ClangABI::Ver7);
+ else if (Major <= 9)
+ Opts.setClangABICompat(LangOptions::ClangABI::Ver9);
} else if (Ver != "latest") {
Diags.Report(diag::err_drv_invalid_value)
<< A->getAsString(Args) << A->getValue();
@@ -3136,8 +3236,7 @@ static bool isStrictlyPreprocessorAction(frontend::ActionKind Action) {
case frontend::GenerateModuleInterface:
case frontend::GenerateHeaderModule:
case frontend::GeneratePCH:
- case frontend::GenerateInterfaceYAMLExpV1:
- case frontend::GenerateInterfaceTBEExpV1:
+ case frontend::GenerateInterfaceIfsExpV1:
case frontend::ParseSyntaxOnly:
case frontend::ModuleFileInfo:
case frontend::VerifyPCH:
@@ -3253,6 +3352,8 @@ static void ParsePreprocessorArgs(PreprocessorOptions &Opts, ArgList &Args,
// "editor placeholder in source file" error in PP only mode.
if (isStrictlyPreprocessorAction(Action))
Opts.LexEditorPlaceholders = false;
+
+ Opts.SetUpStaticAnalyzer = Args.hasArg(OPT_setup_static_analyzer);
}
static void ParsePreprocessorOutputArgs(PreprocessorOutputOptions &Opts,
@@ -3315,18 +3416,16 @@ static void ParseTargetArgs(TargetOptions &Opts, ArgList &Args,
}
bool CompilerInvocation::CreateFromArgs(CompilerInvocation &Res,
- const char *const *ArgBegin,
- const char *const *ArgEnd,
+ ArrayRef<const char *> CommandLineArgs,
DiagnosticsEngine &Diags) {
bool Success = true;
// Parse the arguments.
- std::unique_ptr<OptTable> Opts = createDriverOptTable();
+ const OptTable &Opts = getDriverOptTable();
const unsigned IncludedFlagsBitmask = options::CC1Option;
unsigned MissingArgIndex, MissingArgCount;
- InputArgList Args =
- Opts->ParseArgs(llvm::makeArrayRef(ArgBegin, ArgEnd), MissingArgIndex,
- MissingArgCount, IncludedFlagsBitmask);
+ InputArgList Args = Opts.ParseArgs(CommandLineArgs, MissingArgIndex,
+ MissingArgCount, IncludedFlagsBitmask);
LangOptions &LangOpts = *Res.getLangOpts();
// Check for missing argument error.
@@ -3340,7 +3439,7 @@ bool CompilerInvocation::CreateFromArgs(CompilerInvocation &Res,
for (const auto *A : Args.filtered(OPT_UNKNOWN)) {
auto ArgString = A->getAsString(Args);
std::string Nearest;
- if (Opts->findNearest(ArgString, Nearest, IncludedFlagsBitmask) > 1)
+ if (Opts.findNearest(ArgString, Nearest, IncludedFlagsBitmask) > 1)
Diags.Report(diag::err_drv_unknown_argument) << ArgString;
else
Diags.Report(diag::err_drv_unknown_argument_with_suggestion)
@@ -3351,6 +3450,11 @@ bool CompilerInvocation::CreateFromArgs(CompilerInvocation &Res,
Success &= ParseAnalyzerArgs(*Res.getAnalyzerOpts(), Args, Diags);
Success &= ParseMigratorArgs(Res.getMigratorOpts(), Args);
ParseDependencyOutputArgs(Res.getDependencyOutputOpts(), Args);
+ if (!Res.getDependencyOutputOpts().OutputFile.empty() &&
+ Res.getDependencyOutputOpts().Targets.empty()) {
+ Diags.Report(diag::err_fe_dependency_file_requires_MT);
+ Success = false;
+ }
Success &=
ParseDiagnosticArgs(Res.getDiagnosticOpts(), Args, &Diags,
false /*DefaultDiagColor*/, false /*DefaultShowOpt*/);
@@ -3366,7 +3470,7 @@ bool CompilerInvocation::CreateFromArgs(CompilerInvocation &Res,
Res.getFileSystemOpts().WorkingDir);
llvm::Triple T(Res.getTargetOpts().Triple);
if (DashX.getFormat() == InputKind::Precompiled ||
- DashX.getLanguage() == InputKind::LLVM_IR) {
+ DashX.getLanguage() == Language::LLVM_IR) {
// ObjCAAutoRefCount and Sanitize LangOpts are used to setup the
// PassManager in BackendUtil.cpp. They need to be initializd no matter
// what the input type is.
@@ -3380,7 +3484,7 @@ bool CompilerInvocation::CreateFromArgs(CompilerInvocation &Res,
Diags, LangOpts.Sanitize);
} else {
// 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?
+ // FIXME: Should we really be calling this for an Language::Asm input?
ParseLangArgs(LangOpts, Args, DashX, Res.getTargetOpts(),
Res.getPreprocessorOpts(), Diags);
if (Res.getFrontendOpts().ProgramAction == frontend::RewriteObjC)
@@ -3393,6 +3497,9 @@ bool CompilerInvocation::CreateFromArgs(CompilerInvocation &Res,
}
}
+ if (Diags.isIgnored(diag::warn_profile_data_misexpect, SourceLocation()))
+ Res.FrontendOpts.LLVMArgs.push_back("-pgo-warn-misexpect");
+
LangOpts.FunctionAlignment =
getLastArgIntValue(Args, OPT_function_alignment, 0, Diags);
@@ -3440,6 +3547,7 @@ std::string CompilerInvocation::getModuleHash() const {
using llvm::hash_code;
using llvm::hash_value;
using llvm::hash_combine;
+ using llvm::hash_combine_range;
// Start the signature with the compiler version.
// FIXME: We'd rather use something more cryptographically sound than
@@ -3494,6 +3602,24 @@ std::string CompilerInvocation::getModuleHash() const {
hsOpts.ModulesValidateDiagnosticOptions);
code = hash_combine(code, hsOpts.ResourceDir);
+ if (hsOpts.ModulesStrictContextHash) {
+ hash_code SHPC = hash_combine_range(hsOpts.SystemHeaderPrefixes.begin(),
+ hsOpts.SystemHeaderPrefixes.end());
+ hash_code UEC = hash_combine_range(hsOpts.UserEntries.begin(),
+ hsOpts.UserEntries.end());
+ code = hash_combine(code, hsOpts.SystemHeaderPrefixes.size(), SHPC,
+ hsOpts.UserEntries.size(), UEC);
+
+ const DiagnosticOptions &diagOpts = getDiagnosticOpts();
+ #define DIAGOPT(Name, Bits, Default) \
+ code = hash_combine(code, diagOpts.Name);
+ #define ENUM_DIAGOPT(Name, Type, Bits, Default) \
+ code = hash_combine(code, diagOpts.get##Name());
+ #include "clang/Basic/DiagnosticOptions.def"
+ #undef DIAGOPT
+ #undef ENUM_DIAGOPT
+ }
+
// Extend the signature with the user build path.
code = hash_combine(code, hsOpts.ModuleUserBuildPath);
diff --git a/lib/Frontend/CreateInvocationFromCommandLine.cpp b/lib/Frontend/CreateInvocationFromCommandLine.cpp
index b62416ffd9e7..ab62b633cda3 100644
--- a/lib/Frontend/CreateInvocationFromCommandLine.cpp
+++ b/lib/Frontend/CreateInvocationFromCommandLine.cpp
@@ -24,14 +24,9 @@
using namespace clang;
using namespace llvm::opt;
-/// createInvocationFromCommandLine - Construct a compiler invocation object for
-/// a command line argument vector.
-///
-/// \return A CompilerInvocation, or 0 if none was built for the given
-/// argument vector.
std::unique_ptr<CompilerInvocation> clang::createInvocationFromCommandLine(
ArrayRef<const char *> ArgList, IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
- IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS) {
+ IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS, bool ShouldRecoverOnErorrs) {
if (!Diags.get()) {
// No diagnostics engine was provided, so create our own diagnostics object
// with the default options.
@@ -94,12 +89,9 @@ std::unique_ptr<CompilerInvocation> clang::createInvocationFromCommandLine(
}
const ArgStringList &CCArgs = Cmd.getArguments();
- auto CI = llvm::make_unique<CompilerInvocation>();
- if (!CompilerInvocation::CreateFromArgs(*CI,
- const_cast<const char **>(CCArgs.data()),
- const_cast<const char **>(CCArgs.data()) +
- CCArgs.size(),
- *Diags))
+ auto CI = std::make_unique<CompilerInvocation>();
+ if (!CompilerInvocation::CreateFromArgs(*CI, CCArgs, *Diags) &&
+ !ShouldRecoverOnErorrs)
return nullptr;
return CI;
}
diff --git a/lib/Frontend/DependencyFile.cpp b/lib/Frontend/DependencyFile.cpp
index 375eb91ae366..4bb0167bd597 100644
--- a/lib/Frontend/DependencyFile.cpp
+++ b/lib/Frontend/DependencyFile.cpp
@@ -46,20 +46,20 @@ struct DepCollectorPPCallbacks : public PPCallbacks {
// Dependency generation really does want to go all the way to the
// file entry for a source location to find out what is depended on.
// We do not want #line markers to affect dependency generation!
- const FileEntry *FE =
- SM.getFileEntryForID(SM.getFileID(SM.getExpansionLoc(Loc)));
- if (!FE)
+ Optional<FileEntryRef> File =
+ SM.getFileEntryRefForID(SM.getFileID(SM.getExpansionLoc(Loc)));
+ if (!File)
return;
StringRef Filename =
- llvm::sys::path::remove_leading_dotslash(FE->getName());
+ llvm::sys::path::remove_leading_dotslash(File->getName());
DepCollector.maybeAddDependency(Filename, /*FromModule*/false,
isSystem(FileType),
/*IsModuleFile*/false, /*IsMissing*/false);
}
- void FileSkipped(const FileEntry &SkippedFile, const Token &FilenameTok,
+ void FileSkipped(const FileEntryRef &SkippedFile, const Token &FilenameTok,
SrcMgr::CharacteristicKind FileType) override {
StringRef Filename =
llvm::sys::path::remove_leading_dotslash(SkippedFile.getName());
@@ -83,7 +83,7 @@ struct DepCollectorPPCallbacks : public PPCallbacks {
}
void HasInclude(SourceLocation Loc, StringRef SpelledFilename, bool IsAngled,
- const FileEntry *File,
+ Optional<FileEntryRef> File,
SrcMgr::CharacteristicKind FileType) override {
if (!File)
return;
@@ -168,13 +168,13 @@ bool DependencyCollector::sawDependency(StringRef Filename, bool FromModule,
DependencyCollector::~DependencyCollector() { }
void DependencyCollector::attachToPreprocessor(Preprocessor &PP) {
- PP.addPPCallbacks(llvm::make_unique<DepCollectorPPCallbacks>(
+ PP.addPPCallbacks(std::make_unique<DepCollectorPPCallbacks>(
*this, PP.getSourceManager(), PP.getDiagnostics()));
PP.getHeaderSearchInfo().getModuleMap().addModuleMapCallbacks(
- llvm::make_unique<DepCollectorMMCallbacks>(*this));
+ std::make_unique<DepCollectorMMCallbacks>(*this));
}
void DependencyCollector::attachToASTReader(ASTReader &R) {
- R.addListener(llvm::make_unique<DepCollectorASTListener>(*this));
+ R.addListener(std::make_unique<DepCollectorASTListener>(*this));
}
DependencyFileGenerator::DependencyFileGenerator(
@@ -192,11 +192,6 @@ DependencyFileGenerator::DependencyFileGenerator(
}
void DependencyFileGenerator::attachToPreprocessor(Preprocessor &PP) {
- if (Targets.empty()) {
- PP.getDiagnostics().Report(diag::err_fe_dependency_file_requires_MT);
- return;
- }
-
// Disable the "file not found" diagnostic if the -MG option was given.
if (AddMissingHeaderDeps)
PP.SetSuppressIncludeNotFoundError(true);
@@ -316,7 +311,7 @@ void DependencyFileGenerator::outputDependencyFile(DiagnosticsEngine &Diags) {
}
std::error_code EC;
- llvm::raw_fd_ostream OS(OutputFile, EC, llvm::sys::fs::F_Text);
+ llvm::raw_fd_ostream OS(OutputFile, EC, llvm::sys::fs::OF_Text);
if (EC) {
Diags.Report(diag::err_fe_error_opening) << OutputFile << EC.message();
return;
diff --git a/lib/Frontend/DependencyGraph.cpp b/lib/Frontend/DependencyGraph.cpp
index 90624323a000..ccf7a2785510 100644
--- a/lib/Frontend/DependencyGraph.cpp
+++ b/lib/Frontend/DependencyGraph.cpp
@@ -61,7 +61,7 @@ public:
void clang::AttachDependencyGraphGen(Preprocessor &PP, StringRef OutputFile,
StringRef SysRoot) {
- PP.addPPCallbacks(llvm::make_unique<DependencyGraphCallback>(&PP, OutputFile,
+ PP.addPPCallbacks(std::make_unique<DependencyGraphCallback>(&PP, OutputFile,
SysRoot));
}
@@ -100,7 +100,7 @@ DependencyGraphCallback::writeNodeReference(raw_ostream &OS,
void DependencyGraphCallback::OutputGraphFile() {
std::error_code EC;
- llvm::raw_fd_ostream OS(OutputFile, EC, llvm::sys::fs::F_Text);
+ llvm::raw_fd_ostream OS(OutputFile, EC, llvm::sys::fs::OF_Text);
if (EC) {
PP->getDiagnostics().Report(diag::err_fe_error_opening) << OutputFile
<< EC.message();
diff --git a/lib/Frontend/FrontendAction.cpp b/lib/Frontend/FrontendAction.cpp
index d724bbce3749..b3b7976f8f3e 100644
--- a/lib/Frontend/FrontendAction.cpp
+++ b/lib/Frontend/FrontendAction.cpp
@@ -10,6 +10,7 @@
#include "clang/AST/ASTConsumer.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/DeclGroup.h"
+#include "clang/Basic/LangStandard.h"
#include "clang/Frontend/ASTUnit.h"
#include "clang/Frontend/CompilerInstance.h"
#include "clang/Frontend/FrontendDiagnostic.h"
@@ -215,7 +216,7 @@ FrontendAction::CreateWrappedASTConsumer(CompilerInstance &CI,
Consumers.push_back(std::move(C));
}
- return llvm::make_unique<MultiplexConsumer>(std::move(Consumers));
+ return std::make_unique<MultiplexConsumer>(std::move(Consumers));
}
/// For preprocessed files, if the first line is the linemarker and specifies
@@ -370,7 +371,7 @@ static std::error_code collectModuleHeaderIncludes(
.Default(false))
continue;
- const FileEntry *Header = FileMgr.getFile(Dir->path());
+ auto Header = FileMgr.getFile(Dir->path());
// FIXME: This shouldn't happen unless there is a file system race. Is
// that worth diagnosing?
if (!Header)
@@ -378,7 +379,7 @@ static std::error_code collectModuleHeaderIncludes(
// If this header is marked 'unavailable' in this module, don't include
// it.
- if (ModMap.isHeaderUnavailableInModule(Header, Module))
+ if (ModMap.isHeaderUnavailableInModule(*Header, Module))
continue;
// Compute the relative path from the directory to this file.
@@ -392,7 +393,7 @@ static std::error_code collectModuleHeaderIncludes(
llvm::sys::path::append(RelativeHeader, *It);
// Include this header as part of the umbrella directory.
- Module->addTopHeader(Header);
+ Module->addTopHeader(*Header);
addHeaderInclude(RelativeHeader, Includes, LangOpts, Module->IsExternC);
}
@@ -481,7 +482,7 @@ static Module *prepareToBuildModule(CompilerInstance &CI,
// the module map, rather than adding it after the fact.
StringRef OriginalModuleMapName = CI.getFrontendOpts().OriginalModuleMap;
if (!OriginalModuleMapName.empty()) {
- auto *OriginalModuleMap =
+ auto OriginalModuleMap =
CI.getFileManager().getFile(OriginalModuleMapName,
/*openFile*/ true);
if (!OriginalModuleMap) {
@@ -489,11 +490,11 @@ static Module *prepareToBuildModule(CompilerInstance &CI,
<< OriginalModuleMapName;
return nullptr;
}
- if (OriginalModuleMap != CI.getSourceManager().getFileEntryForID(
+ if (*OriginalModuleMap != CI.getSourceManager().getFileEntryForID(
CI.getSourceManager().getMainFileID())) {
M->IsInferred = true;
CI.getPreprocessor().getHeaderSearchInfo().getModuleMap()
- .setInferredModuleAllowedBy(M, OriginalModuleMap);
+ .setInferredModuleAllowedBy(M, *OriginalModuleMap);
}
}
@@ -674,8 +675,8 @@ bool FrontendAction::BeginSourceFile(CompilerInstance &CI,
// Set up embedding for any specified files. Do this before we load any
// source files, including the primary module map for the compilation.
for (const auto &F : CI.getFrontendOpts().ModulesEmbedFiles) {
- if (const auto *FE = CI.getFileManager().getFile(F, /*openFile*/true))
- CI.getSourceManager().setFileIsTransient(FE);
+ if (auto FE = CI.getFileManager().getFile(F, /*openFile*/true))
+ CI.getSourceManager().setFileIsTransient(*FE);
else
CI.getDiagnostics().Report(diag::err_modules_embed_file_not_found) << F;
}
@@ -683,7 +684,7 @@ bool FrontendAction::BeginSourceFile(CompilerInstance &CI,
CI.getSourceManager().setAllFilesAreTransient(true);
// IR files bypass the rest of initialization.
- if (Input.getKind().getLanguage() == InputKind::LLVM_IR) {
+ if (Input.getKind().getLanguage() == Language::LLVM_IR) {
assert(hasIRSupport() &&
"This action does not have IR file support!");
@@ -709,10 +710,10 @@ bool FrontendAction::BeginSourceFile(CompilerInstance &CI,
PreprocessorOptions &PPOpts = CI.getPreprocessorOpts();
StringRef PCHInclude = PPOpts.ImplicitPCHInclude;
std::string SpecificModuleCachePath = CI.getSpecificModuleCachePath();
- if (const DirectoryEntry *PCHDir = FileMgr.getDirectory(PCHInclude)) {
+ if (auto PCHDir = FileMgr.getDirectory(PCHInclude)) {
std::error_code EC;
SmallString<128> DirNative;
- llvm::sys::path::native(PCHDir->getName(), DirNative);
+ llvm::sys::path::native((*PCHDir)->getName(), DirNative);
bool Found = false;
llvm::vfs::FileSystem &FS = FileMgr.getVirtualFileSystem();
for (llvm::vfs::directory_iterator Dir = FS.dir_begin(DirNative, EC),
@@ -792,9 +793,9 @@ bool FrontendAction::BeginSourceFile(CompilerInstance &CI,
// If we were asked to load any module map files, do so now.
for (const auto &Filename : CI.getFrontendOpts().ModuleMapFiles) {
- if (auto *File = CI.getFileManager().getFile(Filename))
+ if (auto File = CI.getFileManager().getFile(Filename))
CI.getPreprocessor().getHeaderSearchInfo().loadModuleMapFile(
- File, /*IsSystem*/false);
+ *File, /*IsSystem*/false);
else
CI.getDiagnostics().Report(diag::err_module_map_not_found) << Filename;
}
diff --git a/lib/Frontend/FrontendActions.cpp b/lib/Frontend/FrontendActions.cpp
index e37afae5332a..4d47c768ad3c 100644
--- a/lib/Frontend/FrontendActions.cpp
+++ b/lib/Frontend/FrontendActions.cpp
@@ -9,6 +9,7 @@
#include "clang/Frontend/FrontendActions.h"
#include "clang/AST/ASTConsumer.h"
#include "clang/Basic/FileManager.h"
+#include "clang/Basic/LangStandard.h"
#include "clang/Frontend/ASTConsumers.h"
#include "clang/Frontend/CompilerInstance.h"
#include "clang/Frontend/FrontendDiagnostic.h"
@@ -54,7 +55,7 @@ void EnsureSemaIsCreated(CompilerInstance &CI, FrontendAction &Action) {
std::unique_ptr<ASTConsumer>
InitOnlyAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
- return llvm::make_unique<ASTConsumer>();
+ return std::make_unique<ASTConsumer>();
}
void InitOnlyAction::ExecuteAction() {
@@ -108,7 +109,7 @@ GeneratePCHAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
const auto &FrontendOpts = CI.getFrontendOpts();
auto Buffer = std::make_shared<PCHBuffer>();
std::vector<std::unique_ptr<ASTConsumer>> Consumers;
- Consumers.push_back(llvm::make_unique<PCHGenerator>(
+ Consumers.push_back(std::make_unique<PCHGenerator>(
CI.getPreprocessor(), CI.getModuleCache(), OutputFile, Sysroot, Buffer,
FrontendOpts.ModuleFileExtensions,
CI.getPreprocessorOpts().AllowPCHWithCompilerErrors,
@@ -116,7 +117,7 @@ GeneratePCHAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
Consumers.push_back(CI.getPCHContainerWriter().CreatePCHContainerGenerator(
CI, InFile, OutputFile, std::move(OS), Buffer));
- return llvm::make_unique<MultiplexConsumer>(std::move(Consumers));
+ return std::make_unique<MultiplexConsumer>(std::move(Consumers));
}
bool GeneratePCHAction::ComputeASTConsumerArguments(CompilerInstance &CI,
@@ -171,7 +172,7 @@ GenerateModuleAction::CreateASTConsumer(CompilerInstance &CI,
auto Buffer = std::make_shared<PCHBuffer>();
std::vector<std::unique_ptr<ASTConsumer>> Consumers;
- Consumers.push_back(llvm::make_unique<PCHGenerator>(
+ Consumers.push_back(std::make_unique<PCHGenerator>(
CI.getPreprocessor(), CI.getModuleCache(), OutputFile, Sysroot, Buffer,
CI.getFrontendOpts().ModuleFileExtensions,
/*AllowASTWithErrors=*/false,
@@ -181,7 +182,7 @@ GenerateModuleAction::CreateASTConsumer(CompilerInstance &CI,
+CI.getFrontendOpts().BuildingImplicitModule));
Consumers.push_back(CI.getPCHContainerWriter().CreatePCHContainerGenerator(
CI, InFile, OutputFile, std::move(OS), Buffer));
- return llvm::make_unique<MultiplexConsumer>(std::move(Consumers));
+ return std::make_unique<MultiplexConsumer>(std::move(Consumers));
}
bool GenerateModuleFromModuleMapAction::BeginSourceFileAction(
@@ -286,15 +287,15 @@ bool GenerateHeaderModuleAction::BeginSourceFileAction(
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, nullptr);
+ Optional<FileEntryRef> FE = HS.LookupFile(
+ Name, SourceLocation(), /*Angled*/ false, nullptr, CurDir, None,
+ nullptr, nullptr, nullptr, nullptr, nullptr, nullptr);
if (!FE) {
CI.getDiagnostics().Report(diag::err_module_header_file_not_found)
<< Name;
continue;
}
- Headers.push_back({Name, FE});
+ Headers.push_back({Name, &FE->getFileEntry()});
}
HS.getModuleMap().createHeaderModule(CI.getLangOpts().CurrentModule, Headers);
@@ -312,18 +313,18 @@ SyntaxOnlyAction::~SyntaxOnlyAction() {
std::unique_ptr<ASTConsumer>
SyntaxOnlyAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
- return llvm::make_unique<ASTConsumer>();
+ return std::make_unique<ASTConsumer>();
}
std::unique_ptr<ASTConsumer>
DumpModuleInfoAction::CreateASTConsumer(CompilerInstance &CI,
StringRef InFile) {
- return llvm::make_unique<ASTConsumer>();
+ return std::make_unique<ASTConsumer>();
}
std::unique_ptr<ASTConsumer>
VerifyPCHAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
- return llvm::make_unique<ASTConsumer>();
+ return std::make_unique<ASTConsumer>();
}
void VerifyPCHAction::ExecuteAction() {
@@ -414,8 +415,14 @@ private:
return "DeclaringSpecialMember";
case CodeSynthesisContext::DefiningSynthesizedFunction:
return "DefiningSynthesizedFunction";
+ case CodeSynthesisContext::RewritingOperatorAsSpaceship:
+ return "RewritingOperatorAsSpaceship";
case CodeSynthesisContext::Memoization:
return "Memoization";
+ case CodeSynthesisContext::ConstraintsCheck:
+ return "ConstraintsCheck";
+ case CodeSynthesisContext::ConstraintSubstitution:
+ return "ConstraintSubstitution";
}
return "";
}
@@ -465,7 +472,7 @@ private:
std::unique_ptr<ASTConsumer>
TemplightDumpAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
- return llvm::make_unique<ASTConsumer>();
+ return std::make_unique<ASTConsumer>();
}
void TemplightDumpAction::ExecuteAction() {
@@ -478,7 +485,7 @@ void TemplightDumpAction::ExecuteAction() {
EnsureSemaIsCreated(CI, *this);
CI.getSema().TemplateInstCallbacks.push_back(
- llvm::make_unique<DefaultTemplateInstCallback>());
+ std::make_unique<DefaultTemplateInstCallback>());
ASTFrontendAction::ExecuteAction();
}
@@ -695,7 +702,7 @@ void DumpModuleInfoAction::ExecuteAction() {
if (!OutputFileName.empty() && OutputFileName != "-") {
std::error_code EC;
OutFile.reset(new llvm::raw_fd_ostream(OutputFileName.str(), EC,
- llvm::sys::fs::F_Text));
+ llvm::sys::fs::OF_Text));
}
llvm::raw_ostream &Out = OutFile.get()? *OutFile.get() : llvm::outs();
@@ -832,19 +839,19 @@ void PrintPreprocessedAction::ExecuteAction() {
void PrintPreambleAction::ExecuteAction() {
switch (getCurrentFileKind().getLanguage()) {
- case InputKind::C:
- case InputKind::CXX:
- case InputKind::ObjC:
- case InputKind::ObjCXX:
- case InputKind::OpenCL:
- case InputKind::CUDA:
- case InputKind::HIP:
+ case Language::C:
+ case Language::CXX:
+ case Language::ObjC:
+ case Language::ObjCXX:
+ case Language::OpenCL:
+ case Language::CUDA:
+ case Language::HIP:
break;
- case InputKind::Unknown:
- case InputKind::Asm:
- case InputKind::LLVM_IR:
- case InputKind::RenderScript:
+ case Language::Unknown:
+ case Language::Asm:
+ case Language::LLVM_IR:
+ case Language::RenderScript:
// We can't do anything with these.
return;
}
@@ -927,7 +934,7 @@ void PrintDependencyDirectivesSourceMinimizerAction::ExecuteAction() {
// 'expected' comments.
if (CI.getDiagnosticOpts().VerifyDiagnostics) {
// Make sure we don't emit new diagnostics!
- CI.getDiagnostics().setSuppressAllDiagnostics();
+ CI.getDiagnostics().setSuppressAllDiagnostics(true);
Preprocessor &PP = getCompilerInstance().getPreprocessor();
PP.EnterMainSourceFile();
Token Tok;
diff --git a/lib/Frontend/FrontendOptions.cpp b/lib/Frontend/FrontendOptions.cpp
index 6ccb2c395604..5c1fbf889c23 100644
--- a/lib/Frontend/FrontendOptions.cpp
+++ b/lib/Frontend/FrontendOptions.cpp
@@ -7,28 +7,29 @@
//===----------------------------------------------------------------------===//
#include "clang/Frontend/FrontendOptions.h"
+#include "clang/Basic/LangStandard.h"
#include "llvm/ADT/StringSwitch.h"
using namespace clang;
InputKind FrontendOptions::getInputKindForExtension(StringRef Extension) {
return llvm::StringSwitch<InputKind>(Extension)
- .Cases("ast", "pcm", InputKind(InputKind::Unknown, InputKind::Precompiled))
- .Case("c", InputKind::C)
- .Cases("S", "s", InputKind::Asm)
- .Case("i", InputKind(InputKind::C).getPreprocessed())
- .Case("ii", InputKind(InputKind::CXX).getPreprocessed())
- .Case("cui", InputKind(InputKind::CUDA).getPreprocessed())
- .Case("m", InputKind::ObjC)
- .Case("mi", InputKind(InputKind::ObjC).getPreprocessed())
- .Cases("mm", "M", InputKind::ObjCXX)
- .Case("mii", InputKind(InputKind::ObjCXX).getPreprocessed())
- .Cases("C", "cc", "cp", InputKind::CXX)
- .Cases("cpp", "CPP", "c++", "cxx", "hpp", InputKind::CXX)
- .Case("cppm", InputKind::CXX)
- .Case("iim", InputKind(InputKind::CXX).getPreprocessed())
- .Case("cl", InputKind::OpenCL)
- .Case("cu", InputKind::CUDA)
- .Cases("ll", "bc", InputKind::LLVM_IR)
- .Default(InputKind::Unknown);
+ .Cases("ast", "pcm", InputKind(Language::Unknown, InputKind::Precompiled))
+ .Case("c", Language::C)
+ .Cases("S", "s", Language::Asm)
+ .Case("i", InputKind(Language::C).getPreprocessed())
+ .Case("ii", InputKind(Language::CXX).getPreprocessed())
+ .Case("cui", InputKind(Language::CUDA).getPreprocessed())
+ .Case("m", Language::ObjC)
+ .Case("mi", InputKind(Language::ObjC).getPreprocessed())
+ .Cases("mm", "M", Language::ObjCXX)
+ .Case("mii", InputKind(Language::ObjCXX).getPreprocessed())
+ .Cases("C", "cc", "cp", Language::CXX)
+ .Cases("cpp", "CPP", "c++", "cxx", "hpp", Language::CXX)
+ .Case("cppm", Language::CXX)
+ .Case("iim", InputKind(Language::CXX).getPreprocessed())
+ .Case("cl", Language::OpenCL)
+ .Case("cu", Language::CUDA)
+ .Cases("ll", "bc", Language::LLVM_IR)
+ .Default(Language::Unknown);
}
diff --git a/lib/Frontend/HeaderIncludeGen.cpp b/lib/Frontend/HeaderIncludeGen.cpp
index d60f5333bf5b..5f91157816b0 100644
--- a/lib/Frontend/HeaderIncludeGen.cpp
+++ b/lib/Frontend/HeaderIncludeGen.cpp
@@ -100,7 +100,8 @@ void clang::AttachHeaderIncludeGen(Preprocessor &PP,
if (!OutputPath.empty()) {
std::error_code EC;
llvm::raw_fd_ostream *OS = new llvm::raw_fd_ostream(
- OutputPath.str(), EC, llvm::sys::fs::F_Append | llvm::sys::fs::F_Text);
+ OutputPath.str(), EC,
+ llvm::sys::fs::OF_Append | llvm::sys::fs::OF_Text);
if (EC) {
PP.getDiagnostics().Report(clang::diag::warn_fe_cc_print_header_failure)
<< EC.message();
@@ -119,7 +120,7 @@ void clang::AttachHeaderIncludeGen(Preprocessor &PP,
// the GNU way to generate rules is -M / -MM / -MD / -MMD.
for (const auto &Header : DepOpts.ExtraDeps)
PrintHeaderInfo(OutputFile, Header, ShowDepth, 2, MSStyle);
- PP.addPPCallbacks(llvm::make_unique<HeaderIncludesCallback>(
+ PP.addPPCallbacks(std::make_unique<HeaderIncludesCallback>(
&PP, ShowAllHeaders, OutputFile, DepOpts, OwnsOutputFile, ShowDepth,
MSStyle));
}
diff --git a/lib/Frontend/InitHeaderSearch.cpp b/lib/Frontend/InitHeaderSearch.cpp
index d65d13489dc4..5d877ee9c0d7 100644
--- a/lib/Frontend/InitHeaderSearch.cpp
+++ b/lib/Frontend/InitHeaderSearch.cpp
@@ -137,6 +137,13 @@ bool InitHeaderSearch::AddUnmappedPath(const Twine &Path, IncludeDirGroup Group,
SmallString<256> MappedPathStorage;
StringRef MappedPathStr = Path.toStringRef(MappedPathStorage);
+ // If use system headers while cross-compiling, emit the warning.
+ if (HasSysroot && (MappedPathStr.startswith("/usr/include") ||
+ MappedPathStr.startswith("/usr/local/include"))) {
+ Headers.getDiags().Report(diag::warn_poison_system_directories)
+ << MappedPathStr;
+ }
+
// Compute the DirectoryLookup type.
SrcMgr::CharacteristicKind Type;
if (Group == Quoted || Group == Angled || Group == IndexHeaderMap) {
@@ -148,17 +155,17 @@ bool InitHeaderSearch::AddUnmappedPath(const Twine &Path, IncludeDirGroup Group,
}
// If the directory exists, add it.
- if (const DirectoryEntry *DE = FM.getDirectory(MappedPathStr)) {
+ if (auto DE = FM.getOptionalDirectoryRef(MappedPathStr)) {
IncludePath.push_back(
- std::make_pair(Group, DirectoryLookup(DE, Type, isFramework)));
+ std::make_pair(Group, DirectoryLookup(*DE, Type, isFramework)));
return true;
}
// Check to see if this is an apple-style headermap (which are not allowed to
// be frameworks).
if (!isFramework) {
- if (const FileEntry *FE = FM.getFile(MappedPathStr)) {
- if (const HeaderMap *HM = Headers.CreateHeaderMap(FE)) {
+ if (auto FE = FM.getFile(MappedPathStr)) {
+ if (const HeaderMap *HM = Headers.CreateHeaderMap(*FE)) {
// It is a headermap, add it to the search path.
IncludePath.push_back(
std::make_pair(Group,
@@ -636,8 +643,8 @@ void clang::ApplyHeaderSearchOptions(HeaderSearch &HS,
// Set up the builtin include directory in the module map.
SmallString<128> P = StringRef(HSOpts.ResourceDir);
llvm::sys::path::append(P, "include");
- if (const DirectoryEntry *Dir = HS.getFileMgr().getDirectory(P))
- HS.getModuleMap().setBuiltinIncludeDir(Dir);
+ if (auto Dir = HS.getFileMgr().getDirectory(P))
+ HS.getModuleMap().setBuiltinIncludeDir(*Dir);
}
Init.Realize(Lang);
diff --git a/lib/Frontend/InitPreprocessor.cpp b/lib/Frontend/InitPreprocessor.cpp
index 3906e2ae1b98..c27c33c530f6 100644
--- a/lib/Frontend/InitPreprocessor.cpp
+++ b/lib/Frontend/InitPreprocessor.cpp
@@ -24,6 +24,7 @@
#include "clang/Lex/PreprocessorOptions.h"
#include "clang/Serialization/ASTReader.h"
#include "llvm/ADT/APFloat.h"
+#include "llvm/IR/DataLayout.h"
using namespace clang;
static bool MacroBodyEndsInBackslash(StringRef MacroBody) {
@@ -437,17 +438,17 @@ static void InitializeStandardPredefinedMacros(const TargetInfo &TI,
default:
llvm_unreachable("Unsupported OpenCL version");
}
- Builder.defineMacro("CL_VERSION_1_0", "100");
- Builder.defineMacro("CL_VERSION_1_1", "110");
- Builder.defineMacro("CL_VERSION_1_2", "120");
- Builder.defineMacro("CL_VERSION_2_0", "200");
+ }
+ Builder.defineMacro("CL_VERSION_1_0", "100");
+ Builder.defineMacro("CL_VERSION_1_1", "110");
+ Builder.defineMacro("CL_VERSION_1_2", "120");
+ Builder.defineMacro("CL_VERSION_2_0", "200");
- if (TI.isLittleEndian())
- Builder.defineMacro("__ENDIAN_LITTLE__");
+ if (TI.isLittleEndian())
+ Builder.defineMacro("__ENDIAN_LITTLE__");
- if (LangOpts.FastRelaxedMath)
- Builder.defineMacro("__FAST_RELAXED_MATH__");
- }
+ if (LangOpts.FastRelaxedMath)
+ Builder.defineMacro("__FAST_RELAXED_MATH__");
}
// Not "standard" per se, but available even with the -undef flag.
if (LangOpts.AsmPreprocessor)
@@ -480,6 +481,7 @@ static void InitializeCPlusPlusFeatureTestMacros(const LangOptions &LangOpts,
Builder.defineMacro("__cpp_user_defined_literals", "200809L");
Builder.defineMacro("__cpp_lambdas", "200907L");
Builder.defineMacro("__cpp_constexpr",
+ LangOpts.CPlusPlus2a ? "201907L" :
LangOpts.CPlusPlus17 ? "201603L" :
LangOpts.CPlusPlus14 ? "201304L" : "200704");
Builder.defineMacro("__cpp_range_based_for",
@@ -540,8 +542,11 @@ static void InitializeCPlusPlusFeatureTestMacros(const LangOptions &LangOpts,
Builder.defineMacro("__cpp_template_template_args", "201611L");
// C++20 features.
- if (LangOpts.CPlusPlus2a)
+ if (LangOpts.CPlusPlus2a) {
Builder.defineMacro("__cpp_conditional_explicit", "201806L");
+ Builder.defineMacro("__cpp_constexpr_dynamic_alloc", "201907L");
+ Builder.defineMacro("__cpp_constinit", "201907L");
+ }
if (LangOpts.Char8)
Builder.defineMacro("__cpp_char8_t", "201811L");
Builder.defineMacro("__cpp_impl_destroying_delete", "201806L");
@@ -556,6 +561,7 @@ static void InitializeCPlusPlusFeatureTestMacros(const LangOptions &LangOpts,
static void InitializePredefinedMacros(const TargetInfo &TI,
const LangOptions &LangOpts,
const FrontendOptions &FEOpts,
+ const PreprocessorOptions &PPOpts,
MacroBuilder &Builder) {
// Compiler version introspection macros.
Builder.defineMacro("__llvm__"); // LLVM Backend
@@ -570,13 +576,22 @@ static void InitializePredefinedMacros(const TargetInfo &TI,
Builder.defineMacro("__clang_version__",
"\"" CLANG_VERSION_STRING " "
+ getClangFullRepositoryVersion() + "\"");
- if (!LangOpts.MSVCCompat) {
- // Currently claim to be compatible with GCC 4.2.1-5621, but only if we're
- // not compiling for MSVC compatibility
- Builder.defineMacro("__GNUC_MINOR__", "2");
- Builder.defineMacro("__GNUC_PATCHLEVEL__", "1");
- Builder.defineMacro("__GNUC__", "4");
+
+ if (LangOpts.GNUCVersion != 0) {
+ // Major, minor, patch, are given two decimal places each, so 4.2.1 becomes
+ // 40201.
+ unsigned GNUCMajor = LangOpts.GNUCVersion / 100 / 100;
+ unsigned GNUCMinor = LangOpts.GNUCVersion / 100 % 100;
+ unsigned GNUCPatch = LangOpts.GNUCVersion % 100;
+ Builder.defineMacro("__GNUC__", Twine(GNUCMajor));
+ Builder.defineMacro("__GNUC_MINOR__", Twine(GNUCMinor));
+ Builder.defineMacro("__GNUC_PATCHLEVEL__", Twine(GNUCPatch));
Builder.defineMacro("__GXX_ABI_VERSION", "1002");
+
+ if (LangOpts.CPlusPlus) {
+ Builder.defineMacro("__GNUG__", Twine(GNUCMajor));
+ Builder.defineMacro("__GXX_WEAK__");
+ }
}
// Define macros for the C11 / C++11 memory orderings
@@ -615,7 +630,7 @@ static void InitializePredefinedMacros(const TargetInfo &TI,
if (!LangOpts.GNUMode && !LangOpts.MSVCCompat)
Builder.defineMacro("__STRICT_ANSI__");
- if (!LangOpts.MSVCCompat && LangOpts.CPlusPlus11)
+ if (LangOpts.GNUCVersion && LangOpts.CPlusPlus11)
Builder.defineMacro("__GXX_EXPERIMENTAL_CXX0X__");
if (LangOpts.ObjC) {
@@ -695,7 +710,7 @@ static void InitializePredefinedMacros(const TargetInfo &TI,
if (!LangOpts.MSVCCompat && LangOpts.Exceptions)
Builder.defineMacro("__EXCEPTIONS");
- if (!LangOpts.MSVCCompat && LangOpts.RTTI)
+ if (LangOpts.GNUCVersion && LangOpts.RTTI)
Builder.defineMacro("__GXX_RTTI");
if (LangOpts.SjLjExceptions)
@@ -709,11 +724,8 @@ static void InitializePredefinedMacros(const TargetInfo &TI,
if (LangOpts.Deprecated)
Builder.defineMacro("__DEPRECATED");
- if (!LangOpts.MSVCCompat && LangOpts.CPlusPlus) {
- Builder.defineMacro("__GNUG__", "4");
- Builder.defineMacro("__GXX_WEAK__");
+ if (!LangOpts.MSVCCompat && LangOpts.CPlusPlus)
Builder.defineMacro("__private_extern__", "extern");
- }
if (LangOpts.MicrosoftExt) {
if (LangOpts.WChar) {
@@ -923,7 +935,7 @@ static void InitializePredefinedMacros(const TargetInfo &TI,
else
Builder.defineMacro("__FINITE_MATH_ONLY__", "0");
- if (!LangOpts.MSVCCompat) {
+ if (LangOpts.GNUCVersion) {
if (LangOpts.GNUInline || LangOpts.CPlusPlus)
Builder.defineMacro("__GNUC_GNU_INLINE__");
else
@@ -960,7 +972,7 @@ static void InitializePredefinedMacros(const TargetInfo &TI,
#undef DEFINE_LOCK_FREE_MACRO
};
addLockFreeMacros("__CLANG_ATOMIC_");
- if (!LangOpts.MSVCCompat)
+ if (LangOpts.GNUCVersion)
addLockFreeMacros("__GCC_ATOMIC_");
if (LangOpts.NoInlineDefine)
@@ -987,8 +999,7 @@ static void InitializePredefinedMacros(const TargetInfo &TI,
else if (LangOpts.getStackProtector() == LangOptions::SSPReq)
Builder.defineMacro("__SSP_ALL__", "3");
- // Define a macro that exists only when using the static analyzer.
- if (FEOpts.ProgramAction == frontend::RunAnalysis)
+ if (PPOpts.SetUpStaticAnalyzer)
Builder.defineMacro("__clang_analyzer__");
if (LangOpts.FastRelaxedMath)
@@ -1032,15 +1043,18 @@ static void InitializePredefinedMacros(const TargetInfo &TI,
switch (LangOpts.OpenMP) {
case 0:
break;
+ case 31:
+ Builder.defineMacro("_OPENMP", "201107");
+ break;
case 40:
Builder.defineMacro("_OPENMP", "201307");
break;
- case 45:
- Builder.defineMacro("_OPENMP", "201511");
+ case 50:
+ Builder.defineMacro("_OPENMP", "201811");
break;
default:
- // Default version is OpenMP 3.1
- Builder.defineMacro("_OPENMP", "201107");
+ // Default version is OpenMP 4.5
+ Builder.defineMacro("_OPENMP", "201511");
break;
}
}
@@ -1112,9 +1126,10 @@ void clang::InitializePreprocessor(
// macros. This is not the right way to handle this.
if ((LangOpts.CUDA || LangOpts.OpenMPIsDevice) && PP.getAuxTargetInfo())
InitializePredefinedMacros(*PP.getAuxTargetInfo(), LangOpts, FEOpts,
- Builder);
+ PP.getPreprocessorOpts(), Builder);
- InitializePredefinedMacros(PP.getTargetInfo(), LangOpts, FEOpts, Builder);
+ InitializePredefinedMacros(PP.getTargetInfo(), LangOpts, FEOpts,
+ PP.getPreprocessorOpts(), Builder);
// Install definitions to make Objective-C++ ARC work well with various
// C++ Standard Library implementations.
diff --git a/lib/Frontend/InterfaceStubFunctionsConsumer.cpp b/lib/Frontend/InterfaceStubFunctionsConsumer.cpp
index fbba9ae4d6a7..0b28b78de3b1 100644
--- a/lib/Frontend/InterfaceStubFunctionsConsumer.cpp
+++ b/lib/Frontend/InterfaceStubFunctionsConsumer.cpp
@@ -15,6 +15,7 @@
using namespace clang;
+namespace {
class InterfaceStubFunctionsConsumer : public ASTConsumer {
CompilerInstance &Instance;
StringRef InFile;
@@ -176,6 +177,10 @@ class InterfaceStubFunctionsConsumer : public ASTConsumer {
HandleTemplateSpecializations(*cast<FunctionTemplateDecl>(ND), Symbols,
RDO);
return true;
+ case Decl::Kind::Record:
+ case Decl::Kind::Typedef:
+ case Decl::Kind::Enum:
+ case Decl::Kind::EnumConstant:
case Decl::Kind::TemplateTypeParm:
return true;
case Decl::Kind::Var:
@@ -246,92 +251,27 @@ public:
for (const NamedDecl *ND : v.NamedDecls)
HandleNamedDecl(ND, Symbols, FromTU);
- auto writeIfoYaml = [this](const llvm::Triple &T,
- const MangledSymbols &Symbols,
- const ASTContext &context, StringRef Format,
- raw_ostream &OS) -> void {
- OS << "--- !" << Format << "\n";
- OS << "FileHeader:\n";
- OS << " Class: ELFCLASS";
- OS << (T.isArch64Bit() ? "64" : "32");
- OS << "\n";
- OS << " Data: ELFDATA2";
- OS << (T.isLittleEndian() ? "LSB" : "MSB");
- OS << "\n";
- OS << " Type: ET_REL\n";
- OS << " Machine: "
- << llvm::StringSwitch<llvm::StringRef>(T.getArchName())
- .Case("x86_64", "EM_X86_64")
- .Case("i386", "EM_386")
- .Case("i686", "EM_386")
- .Case("aarch64", "EM_AARCH64")
- .Case("amdgcn", "EM_AMDGPU")
- .Case("r600", "EM_AMDGPU")
- .Case("arm", "EM_ARM")
- .Case("thumb", "EM_ARM")
- .Case("avr", "EM_AVR")
- .Case("mips", "EM_MIPS")
- .Case("mipsel", "EM_MIPS")
- .Case("mips64", "EM_MIPS")
- .Case("mips64el", "EM_MIPS")
- .Case("msp430", "EM_MSP430")
- .Case("ppc", "EM_PPC")
- .Case("ppc64", "EM_PPC64")
- .Case("ppc64le", "EM_PPC64")
- .Case("x86", T.isOSIAMCU() ? "EM_IAMCU" : "EM_386")
- .Case("x86_64", "EM_X86_64")
- .Default("EM_NONE")
- << "\nSymbols:\n";
- for (const auto &E : Symbols) {
- const MangledSymbol &Symbol = E.second;
- for (auto Name : Symbol.Names) {
- OS << " - Name: "
- << (Symbol.ParentName.empty() || Instance.getLangOpts().CPlusPlus
- ? ""
- : (Symbol.ParentName + "."))
- << Name << "\n"
- << " Type: STT_";
- switch (Symbol.Type) {
- default:
- case llvm::ELF::STT_NOTYPE:
- OS << "NOTYPE";
- break;
- case llvm::ELF::STT_OBJECT:
- OS << "OBJECT";
- break;
- case llvm::ELF::STT_FUNC:
- OS << "FUNC";
- break;
- }
- OS << "\n Binding: STB_"
- << ((Symbol.Binding == llvm::ELF::STB_WEAK) ? "WEAK" : "GLOBAL")
- << "\n";
- }
- }
- OS << "...\n";
- OS.flush();
- };
-
- auto writeIfoElfAbiYaml =
+ auto writeIfsV1 =
[this](const llvm::Triple &T, const MangledSymbols &Symbols,
const ASTContext &context, StringRef Format,
raw_ostream &OS) -> void {
OS << "--- !" << Format << "\n";
- OS << "TbeVersion: 1.0\n";
- OS << "Arch: " << T.getArchName() << "\n";
+ OS << "IfsVersion: 1.0\n";
+ OS << "Triple: " << T.str() << "\n";
+ OS << "ObjectFileFormat: " << "ELF" << "\n"; // TODO: For now, just ELF.
OS << "Symbols:\n";
for (const auto &E : Symbols) {
const MangledSymbol &Symbol = E.second;
for (auto Name : Symbol.Names) {
- OS << " "
+ OS << " \""
<< (Symbol.ParentName.empty() || Instance.getLangOpts().CPlusPlus
? ""
: (Symbol.ParentName + "."))
- << Name << ": { Type: ";
+ << Name << "\" : { Type: ";
switch (Symbol.Type) {
default:
llvm_unreachable(
- "clang -emit-iterface-stubs: Unexpected symbol type.");
+ "clang -emit-interface-stubs: Unexpected symbol type.");
case llvm::ELF::STT_NOTYPE:
OS << "NoType";
break;
@@ -354,25 +294,15 @@ public:
OS.flush();
};
- if (Format == "experimental-yaml-elf-v1")
- writeIfoYaml(Instance.getTarget().getTriple(), Symbols, context, Format,
- *OS);
- else
- writeIfoElfAbiYaml(Instance.getTarget().getTriple(), Symbols, context,
- Format, *OS);
+ assert(Format == "experimental-ifs-v1" && "Unexpected IFS Format.");
+ writeIfsV1(Instance.getTarget().getTriple(), Symbols, context, Format, *OS);
}
};
+} // namespace
std::unique_ptr<ASTConsumer>
-GenerateInterfaceYAMLExpV1Action::CreateASTConsumer(CompilerInstance &CI,
- StringRef InFile) {
- return llvm::make_unique<InterfaceStubFunctionsConsumer>(
- CI, InFile, "experimental-yaml-elf-v1");
-}
-
-std::unique_ptr<ASTConsumer>
-GenerateInterfaceTBEExpV1Action::CreateASTConsumer(CompilerInstance &CI,
+GenerateInterfaceIfsExpV1Action::CreateASTConsumer(CompilerInstance &CI,
StringRef InFile) {
- return llvm::make_unique<InterfaceStubFunctionsConsumer>(
- CI, InFile, "experimental-tapi-elf-v1");
+ return std::make_unique<InterfaceStubFunctionsConsumer>(
+ CI, InFile, "experimental-ifs-v1");
}
diff --git a/lib/Frontend/LangStandards.cpp b/lib/Frontend/LangStandards.cpp
deleted file mode 100644
index 05087eb41f01..000000000000
--- a/lib/Frontend/LangStandards.cpp
+++ /dev/null
@@ -1,42 +0,0 @@
-//===--- LangStandards.cpp - Language Standard Definitions ----------------===//
-//
-// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
-// See https://llvm.org/LICENSE.txt for license information.
-// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
-//
-//===----------------------------------------------------------------------===//
-
-#include "clang/Frontend/LangStandard.h"
-#include "llvm/ADT/StringSwitch.h"
-#include "llvm/Support/ErrorHandling.h"
-using namespace clang;
-using namespace clang::frontend;
-
-#define LANGSTANDARD(id, name, lang, desc, features) \
-static const LangStandard Lang_##id = { name, desc, features, InputKind::lang };
-#include "clang/Frontend/LangStandards.def"
-
-const LangStandard &LangStandard::getLangStandardForKind(Kind K) {
- switch (K) {
- case lang_unspecified:
- llvm::report_fatal_error("getLangStandardForKind() on unspecified kind");
-#define LANGSTANDARD(id, name, lang, desc, features) \
- case lang_##id: return Lang_##id;
-#include "clang/Frontend/LangStandards.def"
- }
- llvm_unreachable("Invalid language kind!");
-}
-
-const LangStandard *LangStandard::getLangStandardForName(StringRef Name) {
- Kind K = llvm::StringSwitch<Kind>(Name)
-#define LANGSTANDARD(id, name, lang, desc, features) \
- .Case(name, lang_##id)
-#include "clang/Frontend/LangStandards.def"
- .Default(lang_unspecified);
- if (K == lang_unspecified)
- return nullptr;
-
- return &getLangStandardForKind(K);
-}
-
-
diff --git a/lib/Frontend/ModuleDependencyCollector.cpp b/lib/Frontend/ModuleDependencyCollector.cpp
index c1d8c0d9eb24..fd22433d31bd 100644
--- a/lib/Frontend/ModuleDependencyCollector.cpp
+++ b/lib/Frontend/ModuleDependencyCollector.cpp
@@ -99,14 +99,14 @@ struct ModuleDependencyMMCallbacks : public ModuleMapCallbacks {
}
void ModuleDependencyCollector::attachToASTReader(ASTReader &R) {
- R.addListener(llvm::make_unique<ModuleDependencyListener>(*this));
+ R.addListener(std::make_unique<ModuleDependencyListener>(*this));
}
void ModuleDependencyCollector::attachToPreprocessor(Preprocessor &PP) {
- PP.addPPCallbacks(llvm::make_unique<ModuleDependencyPPCallbacks>(
+ PP.addPPCallbacks(std::make_unique<ModuleDependencyPPCallbacks>(
*this, PP.getSourceManager()));
PP.getHeaderSearchInfo().getModuleMap().addModuleMapCallbacks(
- llvm::make_unique<ModuleDependencyMMCallbacks>(*this));
+ std::make_unique<ModuleDependencyMMCallbacks>(*this));
}
static bool isCaseSensitivePath(StringRef Path) {
@@ -148,7 +148,7 @@ void ModuleDependencyCollector::writeFileMap() {
std::error_code EC;
SmallString<256> YAMLPath = VFSDir;
llvm::sys::path::append(YAMLPath, "vfs.yaml");
- llvm::raw_fd_ostream OS(YAMLPath, EC, llvm::sys::fs::F_Text);
+ llvm::raw_fd_ostream OS(YAMLPath, EC, llvm::sys::fs::OF_Text);
if (EC) {
HasErrors = true;
return;
diff --git a/lib/Frontend/MultiplexConsumer.cpp b/lib/Frontend/MultiplexConsumer.cpp
index ed7028769d34..04e896296c95 100644
--- a/lib/Frontend/MultiplexConsumer.cpp
+++ b/lib/Frontend/MultiplexConsumer.cpp
@@ -249,11 +249,11 @@ MultiplexConsumer::MultiplexConsumer(
}
if (!mutationListeners.empty()) {
MutationListener =
- llvm::make_unique<MultiplexASTMutationListener>(mutationListeners);
+ std::make_unique<MultiplexASTMutationListener>(mutationListeners);
}
if (!serializationListeners.empty()) {
DeserializationListener =
- llvm::make_unique<MultiplexASTDeserializationListener>(
+ std::make_unique<MultiplexASTDeserializationListener>(
serializationListeners);
}
}
diff --git a/lib/Frontend/PrecompiledPreamble.cpp b/lib/Frontend/PrecompiledPreamble.cpp
index 276a9676eaa9..ced32c670288 100644
--- a/lib/Frontend/PrecompiledPreamble.cpp
+++ b/lib/Frontend/PrecompiledPreamble.cpp
@@ -12,6 +12,7 @@
#include "clang/Frontend/PrecompiledPreamble.h"
#include "clang/AST/DeclObjC.h"
+#include "clang/Basic/LangStandard.h"
#include "clang/Basic/TargetInfo.h"
#include "clang/Frontend/CompilerInstance.h"
#include "clang/Frontend/CompilerInvocation.h"
@@ -26,11 +27,10 @@
#include "llvm/Config/llvm-config.h"
#include "llvm/Support/CrashRecoveryContext.h"
#include "llvm/Support/FileSystem.h"
-#include "llvm/Support/Mutex.h"
-#include "llvm/Support/MutexGuard.h"
#include "llvm/Support/Process.h"
#include "llvm/Support/VirtualFileSystem.h"
#include <limits>
+#include <mutex>
#include <utility>
using namespace clang;
@@ -95,7 +95,7 @@ public:
void removeFile(StringRef File);
private:
- llvm::sys::SmartMutex<false> Mutex;
+ std::mutex Mutex;
llvm::StringSet<> Files;
};
@@ -105,20 +105,20 @@ TemporaryFiles &TemporaryFiles::getInstance() {
}
TemporaryFiles::~TemporaryFiles() {
- llvm::MutexGuard Guard(Mutex);
+ std::lock_guard<std::mutex> Guard(Mutex);
for (const auto &File : Files)
llvm::sys::fs::remove(File.getKey());
}
void TemporaryFiles::addFile(StringRef File) {
- llvm::MutexGuard Guard(Mutex);
+ std::lock_guard<std::mutex> Guard(Mutex);
auto IsInserted = Files.insert(File).second;
(void)IsInserted;
assert(IsInserted && "File has already been added");
}
void TemporaryFiles::removeFile(StringRef File) {
- llvm::MutexGuard Guard(Mutex);
+ std::lock_guard<std::mutex> Guard(Mutex);
auto WasPresent = Files.erase(File);
(void)WasPresent;
assert(WasPresent && "File was not tracked");
@@ -202,7 +202,7 @@ PrecompilePreambleAction::CreateASTConsumer(CompilerInstance &CI,
std::unique_ptr<llvm::raw_ostream> OS;
if (InMemStorage) {
- OS = llvm::make_unique<llvm::raw_string_ostream>(*InMemStorage);
+ OS = std::make_unique<llvm::raw_string_ostream>(*InMemStorage);
} else {
std::string OutputFile;
OS = GeneratePCHAction::CreateOutputFile(CI, InFile, OutputFile);
@@ -213,7 +213,7 @@ PrecompilePreambleAction::CreateASTConsumer(CompilerInstance &CI,
if (!CI.getFrontendOpts().RelocatablePCH)
Sysroot.clear();
- return llvm::make_unique<PrecompilePreambleConsumer>(
+ return std::make_unique<PrecompilePreambleConsumer>(
*this, CI.getPreprocessor(), CI.getModuleCache(), Sysroot, std::move(OS));
}
@@ -303,7 +303,7 @@ llvm::ErrorOr<PrecompiledPreamble> PrecompiledPreamble::Build(
Clang->getFrontendOpts().Inputs[0].getKind().getFormat() !=
InputKind::Source ||
Clang->getFrontendOpts().Inputs[0].getKind().getLanguage() ==
- InputKind::LLVM_IR) {
+ Language::LLVM_IR) {
return BuildPreambleError::BadInputs;
}
@@ -369,9 +369,11 @@ llvm::ErrorOr<PrecompiledPreamble> PrecompiledPreamble::Build(
SourceManager &SourceMgr = Clang->getSourceManager();
for (auto &Filename : PreambleDepCollector->getDependencies()) {
- const FileEntry *File = Clang->getFileManager().getFile(Filename);
- if (!File || File == SourceMgr.getFileEntryForID(SourceMgr.getMainFileID()))
+ auto FileOrErr = Clang->getFileManager().getFile(Filename);
+ if (!FileOrErr ||
+ *FileOrErr == SourceMgr.getFileEntryForID(SourceMgr.getMainFileID()))
continue;
+ auto File = *FileOrErr;
if (time_t ModTime = File->getModificationTime()) {
FilesInPreamble[File->getName()] =
PrecompiledPreamble::PreambleFileHash::createForFile(File->getSize(),
diff --git a/lib/Frontend/PrintPreprocessedOutput.cpp b/lib/Frontend/PrintPreprocessedOutput.cpp
index 732edacffbe3..24ea1ccba207 100644
--- a/lib/Frontend/PrintPreprocessedOutput.cpp
+++ b/lib/Frontend/PrintPreprocessedOutput.cpp
@@ -675,7 +675,7 @@ struct UnknownPragmaHandler : public PragmaHandler {
if (ShouldExpandTokens) {
// The first token does not have expanded macros. Expand them, if
// required.
- auto Toks = llvm::make_unique<Token[]>(1);
+ auto Toks = std::make_unique<Token[]>(1);
Toks[0] = PragmaTok;
PP.EnterTokenStream(std::move(Toks), /*NumToks=*/1,
/*DisableMacroExpansion=*/false,
diff --git a/lib/Frontend/Rewrite/FixItRewriter.cpp b/lib/Frontend/Rewrite/FixItRewriter.cpp
index 667b9f0469f7..0217b3385a51 100644
--- a/lib/Frontend/Rewrite/FixItRewriter.cpp
+++ b/lib/Frontend/Rewrite/FixItRewriter.cpp
@@ -101,7 +101,7 @@ bool FixItRewriter::WriteFixedFiles(
if (fd != -1) {
OS.reset(new llvm::raw_fd_ostream(fd, /*shouldClose=*/true));
} else {
- OS.reset(new llvm::raw_fd_ostream(Filename, EC, llvm::sys::fs::F_None));
+ OS.reset(new llvm::raw_fd_ostream(Filename, EC, llvm::sys::fs::OF_None));
}
if (EC) {
Diags.Report(clang::diag::err_fe_unable_to_open_output) << Filename
diff --git a/lib/Frontend/Rewrite/FrontendActions.cpp b/lib/Frontend/Rewrite/FrontendActions.cpp
index 0f1a0584c72b..549b86edebcd 100644
--- a/lib/Frontend/Rewrite/FrontendActions.cpp
+++ b/lib/Frontend/Rewrite/FrontendActions.cpp
@@ -9,6 +9,7 @@
#include "clang/Rewrite/Frontend/FrontendActions.h"
#include "clang/AST/ASTConsumer.h"
#include "clang/Basic/CharInfo.h"
+#include "clang/Basic/LangStandard.h"
#include "clang/Config/config.h"
#include "clang/Frontend/CompilerInstance.h"
#include "clang/Frontend/FrontendActions.h"
@@ -49,7 +50,7 @@ FixItAction::~FixItAction() {}
std::unique_ptr<ASTConsumer>
FixItAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
- return llvm::make_unique<ASTConsumer>();
+ return std::make_unique<ASTConsumer>();
}
namespace {
@@ -211,16 +212,16 @@ public:
void visitModuleFile(StringRef Filename,
serialization::ModuleKind Kind) override {
- auto *File = CI.getFileManager().getFile(Filename);
+ auto File = CI.getFileManager().getFile(Filename);
assert(File && "missing file for loaded module?");
// Only rewrite each module file once.
- if (!Rewritten.insert(File).second)
+ if (!Rewritten.insert(*File).second)
return;
serialization::ModuleFile *MF =
- CI.getModuleManager()->getModuleManager().lookup(File);
- assert(File && "missing module file for loaded module?");
+ CI.getModuleManager()->getModuleManager().lookup(*File);
+ assert(MF && "missing module file for loaded module?");
// Not interested in PCH / preambles.
if (!MF->isModule())
@@ -250,7 +251,7 @@ public:
Instance.getFrontendOpts().DisableFree = false;
Instance.getFrontendOpts().Inputs.clear();
Instance.getFrontendOpts().Inputs.emplace_back(
- Filename, InputKind(InputKind::Unknown, InputKind::Precompiled));
+ Filename, InputKind(Language::Unknown, InputKind::Precompiled));
Instance.getFrontendOpts().ModuleFiles.clear();
Instance.getFrontendOpts().ModuleMapFiles.clear();
// Don't recursively rewrite imports. We handle them all at the top level.
@@ -294,7 +295,7 @@ bool RewriteIncludesAction::BeginSourceFileAction(CompilerInstance &CI) {
if (CI.getPreprocessorOutputOpts().RewriteImports) {
CI.createModuleManager();
CI.getModuleManager()->addListener(
- llvm::make_unique<RewriteImportsListener>(CI, OutputStream));
+ std::make_unique<RewriteImportsListener>(CI, OutputStream));
}
return true;
diff --git a/lib/Frontend/Rewrite/HTMLPrint.cpp b/lib/Frontend/Rewrite/HTMLPrint.cpp
index a5b36bc7856c..982e56cebbca 100644
--- a/lib/Frontend/Rewrite/HTMLPrint.cpp
+++ b/lib/Frontend/Rewrite/HTMLPrint.cpp
@@ -48,7 +48,7 @@ namespace {
std::unique_ptr<ASTConsumer>
clang::CreateHTMLPrinter(std::unique_ptr<raw_ostream> OS, Preprocessor &PP,
bool SyntaxHighlight, bool HighlightMacros) {
- return llvm::make_unique<HTMLPrinter>(std::move(OS), PP, SyntaxHighlight,
+ return std::make_unique<HTMLPrinter>(std::move(OS), PP, SyntaxHighlight,
HighlightMacros);
}
diff --git a/lib/Frontend/Rewrite/InclusionRewriter.cpp b/lib/Frontend/Rewrite/InclusionRewriter.cpp
index cb4e773aca87..dcf645f67f2f 100644
--- a/lib/Frontend/Rewrite/InclusionRewriter.cpp
+++ b/lib/Frontend/Rewrite/InclusionRewriter.cpp
@@ -49,6 +49,8 @@ class InclusionRewriter : public PPCallbacks {
std::map<unsigned, const Module *> ModuleIncludes;
/// Tracks where inclusions that enter modules (in a module build) are found.
std::map<unsigned, const Module *> ModuleEntryIncludes;
+ /// Tracks where #if and #elif directives get evaluated and whether to true.
+ std::map<unsigned, bool> IfConditions;
/// Used transitively for building up the FileIncludes mapping over the
/// various \c PPCallbacks callbacks.
SourceLocation LastInclusionLocation;
@@ -70,7 +72,7 @@ private:
void FileChanged(SourceLocation Loc, FileChangeReason Reason,
SrcMgr::CharacteristicKind FileType,
FileID PrevFID) override;
- void FileSkipped(const FileEntry &SkippedFile, const Token &FilenameTok,
+ void FileSkipped(const FileEntryRef &SkippedFile, const Token &FilenameTok,
SrcMgr::CharacteristicKind FileType) override;
void InclusionDirective(SourceLocation HashLoc, const Token &IncludeTok,
StringRef FileName, bool IsAngled,
@@ -78,6 +80,10 @@ private:
StringRef SearchPath, StringRef RelativePath,
const Module *Imported,
SrcMgr::CharacteristicKind FileType) override;
+ void If(SourceLocation Loc, SourceRange ConditionRange,
+ ConditionValueKind ConditionValue) override;
+ void Elif(SourceLocation Loc, SourceRange ConditionRange,
+ ConditionValueKind ConditionValue, SourceLocation IfLoc) override;
void WriteLineInfo(StringRef Filename, int Line,
SrcMgr::CharacteristicKind FileType,
StringRef Extra = StringRef());
@@ -89,12 +95,10 @@ private:
void CommentOutDirective(Lexer &DirectivesLex, const Token &StartToken,
const MemoryBuffer &FromFile, StringRef EOL,
unsigned &NextToWrite, int &Lines);
- bool HandleHasInclude(FileID FileId, Lexer &RawLex,
- const DirectoryLookup *Lookup, Token &Tok,
- bool &FileExists);
const IncludedFile *FindIncludeAtLocation(SourceLocation Loc) const;
const Module *FindModuleAtLocation(SourceLocation Loc) const;
const Module *FindEnteredModule(SourceLocation Loc) const;
+ bool IsIfAtLocationTrue(SourceLocation Loc) const;
StringRef NextIdentifierName(Lexer &RawLex, Token &RawToken);
};
@@ -169,8 +173,8 @@ void InclusionRewriter::FileChanged(SourceLocation Loc,
/// Called whenever an inclusion is skipped due to canonical header protection
/// macros.
-void InclusionRewriter::FileSkipped(const FileEntry &/*SkippedFile*/,
- const Token &/*FilenameTok*/,
+void InclusionRewriter::FileSkipped(const FileEntryRef & /*SkippedFile*/,
+ const Token & /*FilenameTok*/,
SrcMgr::CharacteristicKind /*FileType*/) {
assert(LastInclusionLocation.isValid() &&
"A file, that wasn't found via an inclusion directive, was skipped");
@@ -203,6 +207,23 @@ void InclusionRewriter::InclusionDirective(SourceLocation HashLoc,
LastInclusionLocation = HashLoc;
}
+void InclusionRewriter::If(SourceLocation Loc, SourceRange ConditionRange,
+ ConditionValueKind ConditionValue) {
+ auto P = IfConditions.insert(
+ std::make_pair(Loc.getRawEncoding(), ConditionValue == CVK_True));
+ (void)P;
+ assert(P.second && "Unexpected revisitation of the same if directive");
+}
+
+void InclusionRewriter::Elif(SourceLocation Loc, SourceRange ConditionRange,
+ ConditionValueKind ConditionValue,
+ SourceLocation IfLoc) {
+ auto P = IfConditions.insert(
+ std::make_pair(Loc.getRawEncoding(), ConditionValue == CVK_True));
+ (void)P;
+ assert(P.second && "Unexpected revisitation of the same elif directive");
+}
+
/// Simple lookup for a SourceLocation (specifically one denoting the hash in
/// an inclusion directive) in the map of inclusion information, FileChanges.
const InclusionRewriter::IncludedFile *
@@ -233,6 +254,13 @@ InclusionRewriter::FindEnteredModule(SourceLocation Loc) const {
return nullptr;
}
+bool InclusionRewriter::IsIfAtLocationTrue(SourceLocation Loc) const {
+ const auto I = IfConditions.find(Loc.getRawEncoding());
+ if (I != IfConditions.end())
+ return I->second;
+ return false;
+}
+
/// Detect the likely line ending style of \p FromFile by examining the first
/// newline found within it.
static StringRef DetectEOL(const MemoryBuffer &FromFile) {
@@ -346,80 +374,6 @@ StringRef InclusionRewriter::NextIdentifierName(Lexer &RawLex,
return StringRef();
}
-// Expand __has_include and __has_include_next if possible. If there's no
-// definitive answer return false.
-bool InclusionRewriter::HandleHasInclude(
- FileID FileId, Lexer &RawLex, const DirectoryLookup *Lookup, Token &Tok,
- bool &FileExists) {
- // Lex the opening paren.
- RawLex.LexFromRawLexer(Tok);
- if (Tok.isNot(tok::l_paren))
- return false;
-
- RawLex.LexFromRawLexer(Tok);
-
- SmallString<128> FilenameBuffer;
- StringRef Filename;
- // Since the raw lexer doesn't give us angle_literals we have to parse them
- // ourselves.
- // FIXME: What to do if the file name is a macro?
- if (Tok.is(tok::less)) {
- RawLex.LexFromRawLexer(Tok);
-
- FilenameBuffer += '<';
- do {
- if (Tok.is(tok::eod)) // Sanity check.
- return false;
-
- if (Tok.is(tok::raw_identifier))
- PP.LookUpIdentifierInfo(Tok);
-
- // Get the string piece.
- SmallVector<char, 128> TmpBuffer;
- bool Invalid = false;
- StringRef TmpName = PP.getSpelling(Tok, TmpBuffer, &Invalid);
- if (Invalid)
- return false;
-
- FilenameBuffer += TmpName;
-
- RawLex.LexFromRawLexer(Tok);
- } while (Tok.isNot(tok::greater));
-
- FilenameBuffer += '>';
- Filename = FilenameBuffer;
- } else {
- if (Tok.isNot(tok::string_literal))
- return false;
-
- bool Invalid = false;
- Filename = PP.getSpelling(Tok, FilenameBuffer, &Invalid);
- if (Invalid)
- return false;
- }
-
- // Lex the closing paren.
- RawLex.LexFromRawLexer(Tok);
- if (Tok.isNot(tok::r_paren))
- return false;
-
- // Now ask HeaderInfo if it knows about the header.
- // FIXME: Subframeworks aren't handled here. Do we care?
- bool isAngled = PP.GetIncludeFilenameSpelling(Tok.getLocation(), Filename);
- const DirectoryLookup *CurDir;
- const FileEntry *FileEnt = PP.getSourceManager().getFileEntryForID(FileId);
- SmallVector<std::pair<const FileEntry *, const DirectoryEntry *>, 1>
- Includers;
- Includers.push_back(std::make_pair(FileEnt, FileEnt->getDir()));
- // FIXME: Why don't we call PP.LookupFile here?
- const FileEntry *File = PP.getHeaderSearchInfo().LookupFile(
- Filename, SourceLocation(), isAngled, Lookup, CurDir, Includers, nullptr,
- nullptr, nullptr, nullptr, nullptr, nullptr);
-
- FileExists = File != nullptr;
- return true;
-}
-
/// Use a raw lexer to analyze \p FileId, incrementally copying parts of it
/// and including content of included files recursively.
void InclusionRewriter::Process(FileID FileId,
@@ -519,53 +473,33 @@ void InclusionRewriter::Process(FileID FileId,
case tok::pp_elif: {
bool elif = (RawToken.getIdentifierInfo()->getPPKeywordID() ==
tok::pp_elif);
- // Rewrite special builtin macros to avoid pulling in host details.
+ bool isTrue = IsIfAtLocationTrue(RawToken.getLocation());
+ OutputContentUpTo(FromFile, NextToWrite,
+ SM.getFileOffset(HashToken.getLocation()),
+ LocalEOL, Line, /*EnsureNewline=*/true);
do {
- // Walk over the directive.
RawLex.LexFromRawLexer(RawToken);
- if (RawToken.is(tok::raw_identifier))
- PP.LookUpIdentifierInfo(RawToken);
-
- if (RawToken.is(tok::identifier)) {
- bool HasFile;
- SourceLocation Loc = RawToken.getLocation();
-
- // Rewrite __has_include(x)
- if (RawToken.getIdentifierInfo()->isStr("__has_include")) {
- if (!HandleHasInclude(FileId, RawLex, nullptr, RawToken,
- HasFile))
- continue;
- // Rewrite __has_include_next(x)
- } else if (RawToken.getIdentifierInfo()->isStr(
- "__has_include_next")) {
- if (DirLookup)
- ++DirLookup;
-
- if (!HandleHasInclude(FileId, RawLex, DirLookup, RawToken,
- HasFile))
- continue;
- } else {
- continue;
- }
- // Replace the macro with (0) or (1), followed by the commented
- // out macro for reference.
- OutputContentUpTo(FromFile, NextToWrite, SM.getFileOffset(Loc),
- LocalEOL, Line, false);
- OS << '(' << (int) HasFile << ")/*";
- OutputContentUpTo(FromFile, NextToWrite,
- SM.getFileOffset(RawToken.getLocation()) +
- RawToken.getLength(),
- LocalEOL, Line, false);
- OS << "*/";
- }
- } while (RawToken.isNot(tok::eod));
+ } while (!RawToken.is(tok::eod) && RawToken.isNot(tok::eof));
+ // We need to disable the old condition, but that is tricky.
+ // Trying to comment it out can easily lead to comment nesting.
+ // So instead make the condition harmless by making it enclose
+ // and empty block. Moreover, put it itself inside an #if 0 block
+ // to disable it from getting evaluated (e.g. __has_include_next
+ // warns if used from the primary source file).
+ OS << "#if 0 /* disabled by -frewrite-includes */" << MainEOL;
if (elif) {
- OutputContentUpTo(FromFile, NextToWrite,
- SM.getFileOffset(RawToken.getLocation()) +
- RawToken.getLength(),
- LocalEOL, Line, /*EnsureNewline=*/ true);
- WriteLineInfo(FileName, Line, FileType);
+ OS << "#if 0" << MainEOL;
}
+ OutputContentUpTo(FromFile, NextToWrite,
+ SM.getFileOffset(RawToken.getLocation()) +
+ RawToken.getLength(),
+ LocalEOL, Line, /*EnsureNewline=*/true);
+ // Close the empty block and the disabling block.
+ OS << "#endif" << MainEOL;
+ OS << "#endif /* disabled by -frewrite-includes */" << MainEOL;
+ OS << (elif ? "#elif " : "#if ") << (isTrue ? "1" : "0")
+ << " /* evaluated by -frewrite-includes */" << MainEOL;
+ WriteLineInfo(FileName, Line, FileType);
break;
}
case tok::pp_endif:
diff --git a/lib/Frontend/Rewrite/RewriteModernObjC.cpp b/lib/Frontend/Rewrite/RewriteModernObjC.cpp
index bd091ee03351..45495065ada6 100644
--- a/lib/Frontend/Rewrite/RewriteModernObjC.cpp
+++ b/lib/Frontend/Rewrite/RewriteModernObjC.cpp
@@ -505,7 +505,7 @@ namespace {
/// otherwise.
bool convertBlockPointerToFunctionPointer(QualType &T) {
if (isTopLevelBlockPointerType(T)) {
- const BlockPointerType *BPT = T->getAs<BlockPointerType>();
+ const auto *BPT = T->castAs<BlockPointerType>();
T = Context->getPointerType(BPT->getPointeeType());
return true;
}
@@ -597,8 +597,8 @@ namespace {
StringLiteral *getStringLiteral(StringRef Str) {
QualType StrType = Context->getConstantArrayType(
- Context->CharTy, llvm::APInt(32, Str.size() + 1), ArrayType::Normal,
- 0);
+ Context->CharTy, llvm::APInt(32, Str.size() + 1), nullptr,
+ ArrayType::Normal, 0);
return StringLiteral::Create(*Context, Str, StringLiteral::Ascii,
/*Pascal=*/false, StrType, SourceLocation());
}
@@ -663,7 +663,7 @@ std::unique_ptr<ASTConsumer> clang::CreateModernObjCRewriter(
const std::string &InFile, std::unique_ptr<raw_ostream> OS,
DiagnosticsEngine &Diags, const LangOptions &LOpts,
bool SilenceRewriteMacroWarning, bool LineInfo) {
- return llvm::make_unique<RewriteModernObjC>(InFile, std::move(OS), Diags,
+ return std::make_unique<RewriteModernObjC>(InFile, std::move(OS), Diags,
LOpts, SilenceRewriteMacroWarning,
LineInfo);
}
@@ -852,12 +852,11 @@ RewriteModernObjC::getIvarAccessString(ObjCIvarDecl *D) {
IvarT = GetGroupRecordTypeForObjCIvarBitfield(D);
if (!isa<TypedefType>(IvarT) && IvarT->isRecordType()) {
- RecordDecl *RD = IvarT->getAs<RecordType>()->getDecl();
+ RecordDecl *RD = IvarT->castAs<RecordType>()->getDecl();
RD = RD->getDefinition();
if (RD && !RD->getDeclName().getAsIdentifierInfo()) {
// decltype(((Foo_IMPL*)0)->bar) *
- ObjCContainerDecl *CDecl =
- dyn_cast<ObjCContainerDecl>(D->getDeclContext());
+ auto *CDecl = cast<ObjCContainerDecl>(D->getDeclContext());
// ivar in class extensions requires special treatment.
if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(CDecl))
CDecl = CatDecl->getClassInterface();
@@ -1332,6 +1331,7 @@ void RewriteModernObjC::RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
void RewriteModernObjC::RewriteImplementationDecl(Decl *OID) {
ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
+ assert((IMD || CID) && "Unknown implementation type");
if (IMD) {
if (IMD->getIvarRBraceLoc().isValid()) {
@@ -2103,8 +2103,7 @@ RewriteModernObjC::SynthesizeCallToFunctionDecl(FunctionDecl *FD,
ImplicitCastExpr::Create(*Context, pToFunc, CK_FunctionToPointerDecay,
DRE, nullptr, VK_RValue);
- const FunctionType *FT = msgSendType->getAs<FunctionType>();
-
+ const auto *FT = msgSendType->castAs<FunctionType>();
CallExpr *Exp = CallExpr::Create(
*Context, ICE, Args, FT->getCallResultType(*Context), VK_RValue, EndLoc);
return Exp;
@@ -2752,7 +2751,7 @@ Stmt *RewriteModernObjC::RewriteObjCArrayLiteralExpr(ObjCArrayLiteral *Exp) {
// Create a call to objc_getClass("NSArray"). It will be th 1st argument.
ObjCInterfaceDecl *Class =
- expType->getPointeeType()->getAs<ObjCObjectType>()->getInterface();
+ expType->getPointeeType()->castAs<ObjCObjectType>()->getInterface();
IdentifierInfo *clsName = Class->getIdentifier();
ClsExprs.push_back(getStringLiteral(clsName->getName()));
@@ -2806,7 +2805,7 @@ Stmt *RewriteModernObjC::RewriteObjCArrayLiteralExpr(ObjCArrayLiteral *Exp) {
// Don't forget the parens to enforce the proper binding.
ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
- const FunctionType *FT = msgSendType->getAs<FunctionType>();
+ const FunctionType *FT = msgSendType->castAs<FunctionType>();
CallExpr *CE = CallExpr::Create(*Context, PE, MsgExprs, FT->getReturnType(),
VK_RValue, EndLoc);
ReplaceStmt(Exp, CE);
@@ -2894,7 +2893,7 @@ Stmt *RewriteModernObjC::RewriteObjCDictionaryLiteralExpr(ObjCDictionaryLiteral
// Create a call to objc_getClass("NSArray"). It will be th 1st argument.
ObjCInterfaceDecl *Class =
- expType->getPointeeType()->getAs<ObjCObjectType>()->getInterface();
+ expType->getPointeeType()->castAs<ObjCObjectType>()->getInterface();
IdentifierInfo *clsName = Class->getIdentifier();
ClsExprs.push_back(getStringLiteral(clsName->getName()));
@@ -2957,7 +2956,7 @@ Stmt *RewriteModernObjC::RewriteObjCDictionaryLiteralExpr(ObjCDictionaryLiteral
// Don't forget the parens to enforce the proper binding.
ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
- const FunctionType *FT = msgSendType->getAs<FunctionType>();
+ const FunctionType *FT = msgSendType->castAs<FunctionType>();
CallExpr *CE = CallExpr::Create(*Context, PE, MsgExprs, FT->getReturnType(),
VK_RValue, EndLoc);
ReplaceStmt(Exp, CE);
@@ -3309,7 +3308,7 @@ Stmt *RewriteModernObjC::SynthMessageExpr(ObjCMessageExpr *Exp,
case ObjCMessageExpr::Class: {
SmallVector<Expr*, 8> ClsExprs;
ObjCInterfaceDecl *Class
- = Exp->getClassReceiver()->getAs<ObjCObjectType>()->getInterface();
+ = Exp->getClassReceiver()->castAs<ObjCObjectType>()->getInterface();
IdentifierInfo *clsName = Class->getIdentifier();
ClsExprs.push_back(getStringLiteral(clsName->getName()));
CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl, ClsExprs,
@@ -3530,7 +3529,7 @@ Stmt *RewriteModernObjC::SynthMessageExpr(ObjCMessageExpr *Exp,
// Don't forget the parens to enforce the proper binding.
ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
- const FunctionType *FT = msgSendType->getAs<FunctionType>();
+ const FunctionType *FT = msgSendType->castAs<FunctionType>();
CallExpr *CE = CallExpr::Create(*Context, PE, MsgExprs, FT->getReturnType(),
VK_RValue, EndLoc);
Stmt *ReplacingStmt = CE;
@@ -3637,7 +3636,7 @@ bool RewriteModernObjC::RewriteObjCFieldDeclType(QualType &Type,
return RewriteObjCFieldDeclType(ElemTy, Result);
}
else if (Type->isRecordType()) {
- RecordDecl *RD = Type->getAs<RecordType>()->getDecl();
+ RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
if (RD->isCompleteDefinition()) {
if (RD->isStruct())
Result += "\n\tstruct ";
@@ -3660,7 +3659,7 @@ bool RewriteModernObjC::RewriteObjCFieldDeclType(QualType &Type,
}
}
else if (Type->isEnumeralType()) {
- EnumDecl *ED = Type->getAs<EnumType>()->getDecl();
+ EnumDecl *ED = Type->castAs<EnumType>()->getDecl();
if (ED->isCompleteDefinition()) {
Result += "\n\tenum ";
Result += ED->getName();
@@ -3727,15 +3726,15 @@ void RewriteModernObjC::RewriteLocallyDefinedNamedAggregates(FieldDecl *fieldDec
return;
if (Type->isArrayType())
Type = Context->getBaseElementType(Type);
- ObjCContainerDecl *IDecl =
- dyn_cast<ObjCContainerDecl>(fieldDecl->getDeclContext());
+
+ auto *IDecl = dyn_cast<ObjCContainerDecl>(fieldDecl->getDeclContext());
TagDecl *TD = nullptr;
if (Type->isRecordType()) {
- TD = Type->getAs<RecordType>()->getDecl();
+ TD = Type->castAs<RecordType>()->getDecl();
}
else if (Type->isEnumeralType()) {
- TD = Type->getAs<EnumType>()->getDecl();
+ TD = Type->castAs<EnumType>()->getDecl();
}
if (TD) {
@@ -5753,7 +5752,7 @@ void RewriteModernObjC::HandleDeclInMainFile(Decl *D) {
}
}
} else if (VD->getType()->isRecordType()) {
- RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
+ RecordDecl *RD = VD->getType()->castAs<RecordType>()->getDecl();
if (RD->isCompleteDefinition())
RewriteRecordBody(RD);
}
@@ -7494,7 +7493,7 @@ Stmt *RewriteModernObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) {
IvarT = GetGroupRecordTypeForObjCIvarBitfield(D);
if (!isa<TypedefType>(IvarT) && IvarT->isRecordType()) {
- RecordDecl *RD = IvarT->getAs<RecordType>()->getDecl();
+ RecordDecl *RD = IvarT->castAs<RecordType>()->getDecl();
RD = RD->getDefinition();
if (RD && !RD->getDeclName().getAsIdentifierInfo()) {
// decltype(((Foo_IMPL*)0)->bar) *
diff --git a/lib/Frontend/Rewrite/RewriteObjC.cpp b/lib/Frontend/Rewrite/RewriteObjC.cpp
index 05078baee790..6a22da178fbc 100644
--- a/lib/Frontend/Rewrite/RewriteObjC.cpp
+++ b/lib/Frontend/Rewrite/RewriteObjC.cpp
@@ -416,7 +416,7 @@ namespace {
/// otherwise.
bool convertBlockPointerToFunctionPointer(QualType &T) {
if (isTopLevelBlockPointerType(T)) {
- const BlockPointerType *BPT = T->getAs<BlockPointerType>();
+ const auto *BPT = T->castAs<BlockPointerType>();
T = Context->getPointerType(BPT->getPointeeType());
return true;
}
@@ -497,8 +497,8 @@ namespace {
StringLiteral *getStringLiteral(StringRef Str) {
QualType StrType = Context->getConstantArrayType(
- Context->CharTy, llvm::APInt(32, Str.size() + 1), ArrayType::Normal,
- 0);
+ Context->CharTy, llvm::APInt(32, Str.size() + 1), nullptr,
+ ArrayType::Normal, 0);
return StringLiteral::Create(*Context, Str, StringLiteral::Ascii,
/*Pascal=*/false, StrType, SourceLocation());
}
@@ -593,7 +593,7 @@ clang::CreateObjCRewriter(const std::string &InFile,
std::unique_ptr<raw_ostream> OS,
DiagnosticsEngine &Diags, const LangOptions &LOpts,
bool SilenceRewriteMacroWarning) {
- return llvm::make_unique<RewriteObjCFragileABI>(
+ return std::make_unique<RewriteObjCFragileABI>(
InFile, std::move(OS), Diags, LOpts, SilenceRewriteMacroWarning);
}
@@ -1163,6 +1163,7 @@ void RewriteObjC::RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
void RewriteObjC::RewriteImplementationDecl(Decl *OID) {
ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
+ assert((IMD || CID) && "Unknown ImplementationDecl");
InsertText(IMD ? IMD->getBeginLoc() : CID->getBeginLoc(), "// ");
@@ -2017,7 +2018,7 @@ RewriteObjC::SynthesizeCallToFunctionDecl(FunctionDecl *FD,
ImplicitCastExpr::Create(*Context, pToFunc, CK_FunctionToPointerDecay,
DRE, nullptr, VK_RValue);
- const FunctionType *FT = msgSendType->getAs<FunctionType>();
+ const auto *FT = msgSendType->castAs<FunctionType>();
CallExpr *Exp = CallExpr::Create(
*Context, ICE, Args, FT->getCallResultType(*Context), VK_RValue, EndLoc);
@@ -2285,7 +2286,7 @@ void RewriteObjC::RewriteBlockPointerTypeVariable(std::string& Str,
void RewriteObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) {
SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
- const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(funcType);
+ const FunctionProtoType *proto = dyn_cast_or_null<FunctionProtoType>(funcType);
if (!proto)
return;
QualType Type = proto->getReturnType();
@@ -2604,7 +2605,7 @@ CallExpr *RewriteObjC::SynthMsgSendStretCallExpr(FunctionDecl *MsgSendStretFlavo
// Don't forget the parens to enforce the proper binding.
ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
- const FunctionType *FT = msgSendType->getAs<FunctionType>();
+ const auto *FT = msgSendType->castAs<FunctionType>();
CallExpr *STCE = CallExpr::Create(*Context, PE, MsgExprs, FT->getReturnType(),
VK_RValue, SourceLocation());
return STCE;
@@ -2735,8 +2736,8 @@ Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp,
case ObjCMessageExpr::Class: {
SmallVector<Expr*, 8> ClsExprs;
- ObjCInterfaceDecl *Class
- = Exp->getClassReceiver()->getAs<ObjCObjectType>()->getInterface();
+ auto *Class =
+ Exp->getClassReceiver()->castAs<ObjCObjectType>()->getInterface();
IdentifierInfo *clsName = Class->getIdentifier();
ClsExprs.push_back(getStringLiteral(clsName->getName()));
CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl, ClsExprs,
@@ -2957,7 +2958,7 @@ Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp,
// Don't forget the parens to enforce the proper binding.
ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
- const FunctionType *FT = msgSendType->getAs<FunctionType>();
+ const auto *FT = msgSendType->castAs<FunctionType>();
CallExpr *CE = CallExpr::Create(*Context, PE, MsgExprs, FT->getReturnType(),
VK_RValue, EndLoc);
Stmt *ReplacingStmt = CE;
@@ -4849,7 +4850,7 @@ void RewriteObjC::HandleDeclInMainFile(Decl *D) {
}
}
} else if (VD->getType()->isRecordType()) {
- RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
+ RecordDecl *RD = VD->getType()->castAs<RecordType>()->getDecl();
if (RD->isCompleteDefinition())
RewriteRecordBody(RD);
}
diff --git a/lib/Frontend/SerializedDiagnosticPrinter.cpp b/lib/Frontend/SerializedDiagnosticPrinter.cpp
index c1434a95cc70..8042b52ddc03 100644
--- a/lib/Frontend/SerializedDiagnosticPrinter.cpp
+++ b/lib/Frontend/SerializedDiagnosticPrinter.cpp
@@ -296,7 +296,7 @@ namespace clang {
namespace serialized_diags {
std::unique_ptr<DiagnosticConsumer>
create(StringRef OutputFile, DiagnosticOptions *Diags, bool MergeChildRecords) {
- return llvm::make_unique<SDiagsWriter>(OutputFile, Diags, MergeChildRecords);
+ return std::make_unique<SDiagsWriter>(OutputFile, Diags, MergeChildRecords);
}
} // end namespace serialized_diags
@@ -743,7 +743,7 @@ DiagnosticsEngine *SDiagsWriter::getMetaDiags() {
IntrusiveRefCntPtr<DiagnosticIDs> IDs(new DiagnosticIDs());
auto Client =
new TextDiagnosticPrinter(llvm::errs(), State->DiagOpts.get());
- State->MetaDiagnostics = llvm::make_unique<DiagnosticsEngine>(
+ State->MetaDiagnostics = std::make_unique<DiagnosticsEngine>(
IDs, State->DiagOpts.get(), Client);
}
return State->MetaDiagnostics.get();
@@ -780,8 +780,8 @@ void SDiagsWriter::finish() {
}
std::error_code EC;
- auto OS = llvm::make_unique<llvm::raw_fd_ostream>(State->OutputFile.c_str(),
- EC, llvm::sys::fs::F_None);
+ auto OS = std::make_unique<llvm::raw_fd_ostream>(State->OutputFile.c_str(),
+ EC, llvm::sys::fs::OF_None);
if (EC) {
getMetaDiags()->Report(diag::warn_fe_serialized_diag_failure)
<< State->OutputFile << EC.message();
diff --git a/lib/Frontend/TextDiagnostic.cpp b/lib/Frontend/TextDiagnostic.cpp
index d0c91286250e..7bb6c5b74d5f 100644
--- a/lib/Frontend/TextDiagnostic.cpp
+++ b/lib/Frontend/TextDiagnostic.cpp
@@ -683,8 +683,9 @@ void TextDiagnostic::emitDiagnosticMessage(
if (DiagOpts->ShowColors)
OS.resetColor();
- printDiagnosticLevel(OS, Level, DiagOpts->ShowColors,
- DiagOpts->CLFallbackMode);
+ if (DiagOpts->ShowLevel)
+ printDiagnosticLevel(OS, Level, DiagOpts->ShowColors,
+ DiagOpts->CLFallbackMode);
printDiagnosticMessage(OS,
/*IsSupplemental*/ Level == DiagnosticsEngine::Note,
Message, OS.tell() - StartOfLocationInfo,
@@ -762,7 +763,7 @@ void TextDiagnostic::printDiagnosticMessage(raw_ostream &OS,
void TextDiagnostic::emitFilename(StringRef Filename, const SourceManager &SM) {
SmallVector<char, 128> AbsoluteFilename;
if (DiagOpts->AbsolutePath) {
- const DirectoryEntry *Dir = SM.getFileManager().getDirectory(
+ auto Dir = SM.getFileManager().getDirectory(
llvm::sys::path::parent_path(Filename));
if (Dir) {
// We want to print a simplified absolute path, i. e. without "dots".
@@ -780,12 +781,12 @@ void TextDiagnostic::emitFilename(StringRef Filename, const SourceManager &SM) {
// on Windows we can just use llvm::sys::path::remove_dots(), because,
// on that system, both aforementioned paths point to the same place.
#ifdef _WIN32
- SmallString<4096> DirName = Dir->getName();
+ SmallString<4096> DirName = (*Dir)->getName();
llvm::sys::fs::make_absolute(DirName);
llvm::sys::path::native(DirName);
llvm::sys::path::remove_dots(DirName, /* remove_dot_dot */ true);
#else
- StringRef DirName = SM.getFileManager().getCanonicalName(Dir);
+ StringRef DirName = SM.getFileManager().getCanonicalName(*Dir);
#endif
llvm::sys::path::append(AbsoluteFilename, DirName,
llvm::sys::path::filename(Filename));
diff --git a/lib/Frontend/VerifyDiagnosticConsumer.cpp b/lib/Frontend/VerifyDiagnosticConsumer.cpp
index a68ef03d4db1..82c2af87706e 100644
--- a/lib/Frontend/VerifyDiagnosticConsumer.cpp
+++ b/lib/Frontend/VerifyDiagnosticConsumer.cpp
@@ -528,15 +528,16 @@ static bool ParseDirective(StringRef S, ExpectedData *ED, SourceManager &SM,
// Lookup file via Preprocessor, like a #include.
const DirectoryLookup *CurDir;
- const FileEntry *FE =
+ Optional<FileEntryRef> File =
PP->LookupFile(Pos, Filename, false, nullptr, nullptr, CurDir,
nullptr, nullptr, nullptr, nullptr, nullptr);
- if (!FE) {
+ if (!File) {
Diags.Report(Pos.getLocWithOffset(PH.C-PH.Begin),
diag::err_verify_missing_file) << Filename << KindStr;
continue;
}
+ const FileEntry *FE = &File->getFileEntry();
if (SM.translateFile(FE).isInvalid())
SM.createFileID(FE, Pos, SrcMgr::C_User);
@@ -671,7 +672,7 @@ void VerifyDiagnosticConsumer::BeginSourceFile(const LangOptions &LangOpts,
#ifndef NDEBUG
// Debug build tracks parsed files.
const_cast<Preprocessor *>(PP)->addPPCallbacks(
- llvm::make_unique<VerifyFileTracker>(*this, *SrcManager));
+ std::make_unique<VerifyFileTracker>(*this, *SrcManager));
#endif
}
}
@@ -1116,7 +1117,7 @@ std::unique_ptr<Directive> Directive::create(bool RegexKind,
bool MatchAnyLine, StringRef Text,
unsigned Min, unsigned Max) {
if (!RegexKind)
- return llvm::make_unique<StandardDirective>(DirectiveLoc, DiagnosticLoc,
+ return std::make_unique<StandardDirective>(DirectiveLoc, DiagnosticLoc,
MatchAnyLine, Text, Min, Max);
// Parse the directive into a regular expression.
@@ -1142,6 +1143,6 @@ std::unique_ptr<Directive> Directive::create(bool RegexKind,
}
}
- return llvm::make_unique<RegexDirective>(
+ return std::make_unique<RegexDirective>(
DirectiveLoc, DiagnosticLoc, MatchAnyLine, Text, Min, Max, RegexStr);
}