[Frontend] Fix some Clang-tidy modernize and Include What You Use warnings; other minor fixes (NFC).

llvm-svn: 328584
This commit is contained in:
Eugene Zelenko 2018-03-26 21:45:04 +00:00
parent f6440b6fb1
commit 44357eef97
7 changed files with 444 additions and 272 deletions

View File

@ -1,4 +1,4 @@
//===-- CompilerInvocation.h - Compiler Invocation Helper Data --*- C++ -*-===//
//===- CompilerInvocation.h - Compiler Invocation Helper Data ---*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
@ -7,11 +7,12 @@
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_FRONTEND_COMPILERINVOCATION_H_
#define LLVM_CLANG_FRONTEND_COMPILERINVOCATION_H_
#ifndef LLVM_CLANG_FRONTEND_COMPILERINVOCATION_H
#define LLVM_CLANG_FRONTEND_COMPILERINVOCATION_H
#include "clang/Basic/DiagnosticOptions.h"
#include "clang/Basic/FileSystemOptions.h"
#include "clang/Basic/LLVM.h"
#include "clang/Basic/LangOptions.h"
#include "clang/Frontend/CodeGenOptions.h"
#include "clang/Frontend/DependencyOutputOptions.h"
@ -21,23 +22,27 @@
#include "clang/Frontend/PreprocessorOutputOptions.h"
#include "clang/StaticAnalyzer/Core/AnalyzerOptions.h"
#include "llvm/ADT/IntrusiveRefCntPtr.h"
#include <memory>
#include <string>
namespace llvm {
class Triple;
namespace opt {
class ArgList;
}
}
} // namespace opt
} // namespace llvm
namespace clang {
class PreprocessorOptions;
class HeaderSearchOptions;
class TargetOptions;
class LangOptions;
class CompilerInvocation;
class DiagnosticsEngine;
class HeaderSearchOptions;
class PreprocessorOptions;
class TargetOptions;
/// \brief Fill out Opts based on the options given in Args.
///
@ -52,8 +57,6 @@ bool ParseDiagnosticArgs(DiagnosticOptions &Opts, llvm::opt::ArgList &Args,
bool DefaultShowOpt = true);
class CompilerInvocationBase {
void operator=(const CompilerInvocationBase &) = delete;
public:
/// Options controlling the language variant.
std::shared_ptr<LangOptions> LangOpts;
@ -71,24 +74,24 @@ public:
std::shared_ptr<PreprocessorOptions> PreprocessorOpts;
CompilerInvocationBase();
~CompilerInvocationBase();
CompilerInvocationBase(const CompilerInvocationBase &X);
CompilerInvocationBase &operator=(const CompilerInvocationBase &) = delete;
~CompilerInvocationBase();
LangOptions *getLangOpts() { return LangOpts.get(); }
const LangOptions *getLangOpts() const { return LangOpts.get(); }
TargetOptions &getTargetOpts() { return *TargetOpts.get(); }
const TargetOptions &getTargetOpts() const {
return *TargetOpts.get();
}
const TargetOptions &getTargetOpts() const { return *TargetOpts.get(); }
DiagnosticOptions &getDiagnosticOpts() const { return *DiagnosticOpts; }
HeaderSearchOptions &getHeaderSearchOpts() { return *HeaderSearchOpts; }
const HeaderSearchOptions &getHeaderSearchOpts() const {
return *HeaderSearchOpts;
}
std::shared_ptr<HeaderSearchOptions> getHeaderSearchOptsPtr() const {
return HeaderSearchOpts;
}
@ -96,7 +99,9 @@ public:
std::shared_ptr<PreprocessorOptions> getPreprocessorOptsPtr() {
return PreprocessorOpts;
}
PreprocessorOptions &getPreprocessorOpts() { return *PreprocessorOpts; }
const PreprocessorOptions &getPreprocessorOpts() const {
return *PreprocessorOpts;
}
@ -176,40 +181,35 @@ public:
/// @name Option Subgroups
/// @{
AnalyzerOptionsRef getAnalyzerOpts() const {
return AnalyzerOpts;
}
AnalyzerOptionsRef getAnalyzerOpts() const { return AnalyzerOpts; }
MigratorOptions &getMigratorOpts() { return MigratorOpts; }
const MigratorOptions &getMigratorOpts() const {
return MigratorOpts;
}
const MigratorOptions &getMigratorOpts() const { return MigratorOpts; }
CodeGenOptions &getCodeGenOpts() { return CodeGenOpts; }
const CodeGenOptions &getCodeGenOpts() const {
return CodeGenOpts;
}
const CodeGenOptions &getCodeGenOpts() const { return CodeGenOpts; }
DependencyOutputOptions &getDependencyOutputOpts() {
return DependencyOutputOpts;
}
const DependencyOutputOptions &getDependencyOutputOpts() const {
return DependencyOutputOpts;
}
FileSystemOptions &getFileSystemOpts() { return FileSystemOpts; }
const FileSystemOptions &getFileSystemOpts() const {
return FileSystemOpts;
}
FrontendOptions &getFrontendOpts() { return FrontendOpts; }
const FrontendOptions &getFrontendOpts() const {
return FrontendOpts;
}
const FrontendOptions &getFrontendOpts() const { return FrontendOpts; }
PreprocessorOutputOptions &getPreprocessorOutputOpts() {
return PreprocessorOutputOpts;
}
const PreprocessorOutputOptions &getPreprocessorOutputOpts() const {
return PreprocessorOutputOpts;
}
@ -218,8 +218,10 @@ public:
};
namespace vfs {
class FileSystem;
}
class FileSystem;
} // namespace vfs
IntrusiveRefCntPtr<vfs::FileSystem>
createVFSFromCompilerInvocation(const CompilerInvocation &CI,
@ -230,6 +232,6 @@ createVFSFromCompilerInvocation(const CompilerInvocation &CI,
DiagnosticsEngine &Diags,
IntrusiveRefCntPtr<vfs::FileSystem> BaseFS);
} // end namespace clang
} // namespace clang
#endif
#endif // LLVM_CLANG_FRONTEND_COMPILERINVOCATION_H

View File

@ -1,4 +1,4 @@
//===--- FrontendOptions.h --------------------------------------*- C++ -*-===//
//===- FrontendOptions.h ----------------------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
@ -14,55 +14,124 @@
#include "clang/Serialization/ModuleFileExtension.h"
#include "clang/Sema/CodeCompleteOptions.h"
#include "llvm/ADT/StringRef.h"
#include <cassert>
#include <memory>
#include <string>
#include <vector>
#include <unordered_map>
namespace llvm {
class MemoryBuffer;
}
} // namespace llvm
namespace clang {
class FileEntry;
namespace frontend {
enum ActionKind {
ASTDeclList, ///< Parse ASTs and list Decl nodes.
ASTDump, ///< Parse ASTs and dump them.
ASTPrint, ///< Parse ASTs and print them.
ASTView, ///< Parse ASTs and view them in Graphviz.
DumpRawTokens, ///< Dump out raw tokens.
DumpTokens, ///< Dump out preprocessed tokens.
EmitAssembly, ///< Emit a .s file.
EmitBC, ///< Emit a .bc file.
EmitHTML, ///< Translate input source into HTML.
EmitLLVM, ///< Emit a .ll file.
EmitLLVMOnly, ///< Generate LLVM IR, but do not emit anything.
EmitCodeGenOnly, ///< Generate machine code, but don't emit anything.
EmitObj, ///< Emit a .o file.
FixIt, ///< Parse and apply any fixits to the source.
GenerateModule, ///< Generate pre-compiled module from a module map.
GenerateModuleInterface,///< Generate pre-compiled module from a C++ module
///< interface file.
GeneratePCH, ///< Generate pre-compiled header.
GeneratePTH, ///< Generate pre-tokenized header.
InitOnly, ///< Only execute frontend initialization.
ModuleFileInfo, ///< Dump information about a module file.
VerifyPCH, ///< Load and verify that a PCH file is usable.
ParseSyntaxOnly, ///< Parse and perform semantic analysis.
PluginAction, ///< Run a plugin action, \see ActionName.
PrintDeclContext, ///< Print DeclContext and their Decls.
PrintPreamble, ///< Print the "preamble" of the input file
PrintPreprocessedInput, ///< -E mode.
RewriteMacros, ///< Expand macros but not \#includes.
RewriteObjC, ///< ObjC->C Rewriter.
RewriteTest, ///< Rewriter playground
RunAnalysis, ///< Run one or more source code analyses.
TemplightDump, ///< Dump template instantiations
MigrateSource, ///< Run migrator.
RunPreprocessorOnly ///< Just lex, no output.
};
}
enum ActionKind {
/// Parse ASTs and list Decl nodes.
ASTDeclList,
/// Parse ASTs and dump them.
ASTDump,
/// Parse ASTs and print them.
ASTPrint,
/// Parse ASTs and view them in Graphviz.
ASTView,
/// Dump out raw tokens.
DumpRawTokens,
/// Dump out preprocessed tokens.
DumpTokens,
/// Emit a .s file.
EmitAssembly,
/// Emit a .bc file.
EmitBC,
/// Translate input source into HTML.
EmitHTML,
/// Emit a .ll file.
EmitLLVM,
/// Generate LLVM IR, but do not emit anything.
EmitLLVMOnly,
/// Generate machine code, but don't emit anything.
EmitCodeGenOnly,
/// Emit a .o file.
EmitObj,
/// Parse and apply any fixits to the source.
FixIt,
/// Generate pre-compiled module from a module map.
GenerateModule,
/// Generate pre-compiled module from a C++ module interface file.
GenerateModuleInterface,
/// Generate pre-compiled header.
GeneratePCH,
/// Generate pre-tokenized header.
GeneratePTH,
/// Only execute frontend initialization.
InitOnly,
/// Dump information about a module file.
ModuleFileInfo,
/// Load and verify that a PCH file is usable.
VerifyPCH,
/// Parse and perform semantic analysis.
ParseSyntaxOnly,
/// Run a plugin action, \see ActionName.
PluginAction,
/// Print DeclContext and their Decls.
PrintDeclContext,
/// Print the "preamble" of the input file
PrintPreamble,
/// -E mode.
PrintPreprocessedInput,
/// Expand macros but not \#includes.
RewriteMacros,
/// ObjC->C Rewriter.
RewriteObjC,
/// Rewriter playground
RewriteTest,
/// Run one or more source code analyses.
RunAnalysis,
/// Dump template instantiations
TemplightDump,
/// Run migrator.
MigrateSource,
/// Just lex, no output.
RunPreprocessorOnly
};
} // namespace frontend
/// The kind of a file that we've been handed as an input.
class InputKind {
@ -119,6 +188,7 @@ public:
InputKind getPreprocessed() const {
return InputKind(getLanguage(), getFormat(), true);
}
InputKind withFormat(Format F) const {
return InputKind(getLanguage(), F, isPreprocessed());
}
@ -141,12 +211,12 @@ class FrontendInputFile {
bool IsSystem = false;
public:
FrontendInputFile() { }
FrontendInputFile() = default;
FrontendInputFile(StringRef File, InputKind Kind, bool IsSystem = false)
: File(File.str()), Kind(Kind), IsSystem(IsSystem) { }
: File(File.str()), Kind(Kind), IsSystem(IsSystem) {}
FrontendInputFile(llvm::MemoryBuffer *Buffer, InputKind Kind,
bool IsSystem = false)
: Buffer(Buffer), Kind(Kind), IsSystem(IsSystem) { }
: Buffer(Buffer), Kind(Kind), IsSystem(IsSystem) {}
InputKind getKind() const { return Kind; }
bool isSystem() const { return IsSystem; }
@ -160,6 +230,7 @@ public:
assert(isFile());
return File;
}
llvm::MemoryBuffer *getBuffer() const {
assert(isBuffer());
return Buffer;
@ -169,43 +240,67 @@ public:
/// FrontendOptions - Options for controlling the behavior of the frontend.
class FrontendOptions {
public:
unsigned DisableFree : 1; ///< Disable memory freeing on exit.
unsigned RelocatablePCH : 1; ///< When generating PCH files,
/// instruct the AST writer to create
/// relocatable PCH files.
unsigned ShowHelp : 1; ///< Show the -help text.
unsigned ShowStats : 1; ///< Show frontend performance
/// metrics and statistics.
unsigned ShowTimers : 1; ///< Show timers for individual
/// actions.
unsigned ShowVersion : 1; ///< Show the -version text.
unsigned FixWhatYouCan : 1; ///< Apply fixes even if there are
/// unfixable errors.
unsigned FixOnlyWarnings : 1; ///< Apply fixes only for warnings.
unsigned FixAndRecompile : 1; ///< Apply fixes and recompile.
unsigned FixToTemporaries : 1; ///< Apply fixes to temporary files.
unsigned ARCMTMigrateEmitARCErrors : 1; /// Emit ARC errors even if the
/// migrator can fix them
unsigned SkipFunctionBodies : 1; ///< Skip over function bodies to
/// speed up parsing in cases you do
/// not need them (e.g. with code
/// completion).
unsigned UseGlobalModuleIndex : 1; ///< Whether we can use the
///< global module index if available.
unsigned GenerateGlobalModuleIndex : 1; ///< Whether we can generate the
///< global module index if needed.
unsigned ASTDumpDecls : 1; ///< Whether we include declaration
///< dumps in AST dumps.
unsigned ASTDumpAll : 1; ///< Whether we deserialize all decls
///< when forming AST dumps.
unsigned ASTDumpLookups : 1; ///< Whether we include lookup table
///< dumps in AST dumps.
unsigned BuildingImplicitModule : 1; ///< Whether we are performing an
///< implicit module build.
unsigned ModulesEmbedAllFiles : 1; ///< Whether we should embed all used
///< files into the PCM file.
unsigned IncludeTimestamps : 1; ///< Whether timestamps should be
///< written to the produced PCH file.
/// Disable memory freeing on exit.
unsigned DisableFree : 1;
/// When generating PCH files, instruct the AST writer to create relocatable
/// PCH files.
unsigned RelocatablePCH : 1;
/// Show the -help text.
unsigned ShowHelp : 1;
/// Show frontend performance metrics and statistics.
unsigned ShowStats : 1;
/// Show timers for individual actions.
unsigned ShowTimers : 1;
/// Show the -version text.
unsigned ShowVersion : 1;
/// Apply fixes even if there are unfixable errors.
unsigned FixWhatYouCan : 1;
/// Apply fixes only for warnings.
unsigned FixOnlyWarnings : 1;
/// Apply fixes and recompile.
unsigned FixAndRecompile : 1;
/// Apply fixes to temporary files.
unsigned FixToTemporaries : 1;
/// Emit ARC errors even if the migrator can fix them.
unsigned ARCMTMigrateEmitARCErrors : 1;
/// Skip over function bodies to speed up parsing in cases you do not need
/// them (e.g. with code completion).
unsigned SkipFunctionBodies : 1;
/// Whether we can use the global module index if available.
unsigned UseGlobalModuleIndex : 1;
/// Whether we can generate the global module index if needed.
unsigned GenerateGlobalModuleIndex : 1;
/// Whether we include declaration dumps in AST dumps.
unsigned ASTDumpDecls : 1;
/// Whether we deserialize all decls when forming AST dumps.
unsigned ASTDumpAll : 1;
/// Whether we include lookup table dumps in AST dumps.
unsigned ASTDumpLookups : 1;
/// Whether we are performing an implicit module build.
unsigned BuildingImplicitModule : 1;
/// Whether we should embed all used files into the PCM file.
unsigned ModulesEmbedAllFiles : 1;
/// Whether timestamps should be written to the produced PCH file.
unsigned IncludeTimestamps : 1;
CodeCompleteOptions CodeCompleteOpts;
@ -214,38 +309,53 @@ public:
ARCMT_Check,
ARCMT_Modify,
ARCMT_Migrate
} ARCMTAction;
} ARCMTAction = ARCMT_None;
enum {
ObjCMT_None = 0,
/// \brief Enable migration to modern ObjC literals.
ObjCMT_Literals = 0x1,
/// \brief Enable migration to modern ObjC subscripting.
ObjCMT_Subscripting = 0x2,
/// \brief Enable migration to modern ObjC readonly property.
ObjCMT_ReadonlyProperty = 0x4,
/// \brief Enable migration to modern ObjC readwrite property.
ObjCMT_ReadwriteProperty = 0x8,
/// \brief Enable migration to modern ObjC property.
ObjCMT_Property = (ObjCMT_ReadonlyProperty | ObjCMT_ReadwriteProperty),
/// \brief Enable annotation of ObjCMethods of all kinds.
ObjCMT_Annotation = 0x10,
/// \brief Enable migration of ObjC methods to 'instancetype'.
ObjCMT_Instancetype = 0x20,
/// \brief Enable migration to NS_ENUM/NS_OPTIONS macros.
ObjCMT_NsMacros = 0x40,
/// \brief Enable migration to add conforming protocols.
ObjCMT_ProtocolConformance = 0x80,
/// \brief prefer 'atomic' property over 'nonatomic'.
ObjCMT_AtomicProperty = 0x100,
/// \brief annotate property with NS_RETURNS_INNER_POINTER
ObjCMT_ReturnsInnerPointerProperty = 0x200,
/// \brief use NS_NONATOMIC_IOSONLY for property 'atomic' attribute
ObjCMT_NsAtomicIOSOnlyProperty = 0x400,
/// \brief Enable inferring NS_DESIGNATED_INITIALIZER for ObjC methods.
ObjCMT_DesignatedInitializer = 0x800,
/// \brief Enable converting setter/getter expressions to property-dot syntx.
ObjCMT_PropertyDotSyntax = 0x1000,
ObjCMT_MigrateDecls = (ObjCMT_ReadonlyProperty | ObjCMT_ReadwriteProperty |
ObjCMT_Annotation | ObjCMT_Instancetype |
ObjCMT_NsMacros | ObjCMT_ProtocolConformance |
@ -254,7 +364,7 @@ public:
ObjCMT_MigrateAll = (ObjCMT_Literals | ObjCMT_Subscripting |
ObjCMT_MigrateDecls | ObjCMT_PropertyDotSyntax)
};
unsigned ObjCMTAction;
unsigned ObjCMTAction = ObjCMT_None;
std::string ObjCMTWhiteListPath;
std::string MTMigrateDir;
@ -280,7 +390,7 @@ public:
ParsedSourceLocation CodeCompletionAt;
/// The frontend action to perform.
frontend::ActionKind ProgramAction;
frontend::ActionKind ProgramAction = frontend::ParseSyntaxOnly;
/// The name of the action to run when using a plugin action.
std::string ActionName;
@ -329,17 +439,15 @@ public:
std::string StatsFile;
public:
FrontendOptions() :
DisableFree(false), RelocatablePCH(false), ShowHelp(false),
ShowStats(false), ShowTimers(false), ShowVersion(false),
FixWhatYouCan(false), FixOnlyWarnings(false), FixAndRecompile(false),
FixToTemporaries(false), ARCMTMigrateEmitARCErrors(false),
SkipFunctionBodies(false), UseGlobalModuleIndex(true),
GenerateGlobalModuleIndex(true), ASTDumpDecls(false), ASTDumpLookups(false),
BuildingImplicitModule(false), ModulesEmbedAllFiles(false),
IncludeTimestamps(true), ARCMTAction(ARCMT_None),
ObjCMTAction(ObjCMT_None), ProgramAction(frontend::ParseSyntaxOnly)
{}
FrontendOptions()
: DisableFree(false), RelocatablePCH(false), ShowHelp(false),
ShowStats(false), ShowTimers(false), ShowVersion(false),
FixWhatYouCan(false), FixOnlyWarnings(false), FixAndRecompile(false),
FixToTemporaries(false), ARCMTMigrateEmitARCErrors(false),
SkipFunctionBodies(false), UseGlobalModuleIndex(true),
GenerateGlobalModuleIndex(true), ASTDumpDecls(false),
ASTDumpLookups(false), BuildingImplicitModule(false),
ModulesEmbedAllFiles(false), IncludeTimestamps(true) {}
/// getInputKindForExtension - Return the appropriate input kind for a file
/// extension. For example, "c" would return InputKind::C.
@ -349,6 +457,6 @@ public:
static InputKind getInputKindForExtension(StringRef Extension);
};
} // end namespace clang
} // namespace clang
#endif
#endif // LLVM_CLANG_FRONTEND_FRONTENDOPTIONS_H

View File

@ -1,4 +1,4 @@
//===--- SerializedDiagnosticReader.h - Reads diagnostics -------*- C++ -*-===//
//===- SerializedDiagnosticReader.h - Reads diagnostics ---------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
@ -7,12 +7,14 @@
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_FRONTEND_SERIALIZED_DIAGNOSTIC_READER_H_
#define LLVM_CLANG_FRONTEND_SERIALIZED_DIAGNOSTIC_READER_H_
#ifndef LLVM_CLANG_FRONTEND_SERIALIZEDDIAGNOSTICREADER_H
#define LLVM_CLANG_FRONTEND_SERIALIZEDDIAGNOSTICREADER_H
#include "clang/Basic/LLVM.h"
#include "llvm/Bitcode/BitstreamReader.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/Support/ErrorOr.h"
#include <system_error>
namespace clang {
namespace serialized_diags {
@ -47,6 +49,7 @@ struct Location {
unsigned Line;
unsigned Col;
unsigned Offset;
Location(unsigned FileID, unsigned Line, unsigned Col, unsigned Offset)
: FileID(FileID), Line(Line), Col(Col), Offset(Offset) {}
};
@ -57,8 +60,8 @@ struct Location {
/// the various constructs that are found in serialized diagnostics.
class SerializedDiagnosticReader {
public:
SerializedDiagnosticReader() {}
virtual ~SerializedDiagnosticReader() {}
SerializedDiagnosticReader() = default;
virtual ~SerializedDiagnosticReader() = default;
/// \brief Read the diagnostics in \c File
std::error_code readDiagnostics(StringRef File);
@ -78,53 +81,59 @@ private:
protected:
/// \brief Visit the start of a diagnostic block.
virtual std::error_code visitStartOfDiagnostic() {
return std::error_code();
}
virtual std::error_code visitStartOfDiagnostic() { return {}; }
/// \brief Visit the end of a diagnostic block.
virtual std::error_code visitEndOfDiagnostic() { return std::error_code(); }
virtual std::error_code visitEndOfDiagnostic() { return {}; }
/// \brief Visit a category. This associates the category \c ID to a \c Name.
virtual std::error_code visitCategoryRecord(unsigned ID, StringRef Name) {
return std::error_code();
return {};
}
/// \brief Visit a flag. This associates the flag's \c ID to a \c Name.
virtual std::error_code visitDiagFlagRecord(unsigned ID, StringRef Name) {
return std::error_code();
return {};
}
/// \brief Visit a diagnostic.
virtual std::error_code
visitDiagnosticRecord(unsigned Severity, const Location &Location,
unsigned Category, unsigned Flag, StringRef Message) {
return std::error_code();
return {};
}
/// \brief Visit a filename. This associates the file's \c ID to a \c Name.
virtual std::error_code visitFilenameRecord(unsigned ID, unsigned Size,
unsigned Timestamp,
StringRef Name) {
return std::error_code();
return {};
}
/// \brief Visit a fixit hint.
virtual std::error_code
visitFixitRecord(const Location &Start, const Location &End, StringRef Text) {
return std::error_code();
return {};
}
/// \brief Visit a source range.
virtual std::error_code visitSourceRangeRecord(const Location &Start,
const Location &End) {
return std::error_code();
return {};
}
/// \brief Visit the version of the set of diagnostics.
virtual std::error_code visitVersionRecord(unsigned Version) {
return std::error_code();
}
virtual std::error_code visitVersionRecord(unsigned Version) { return {}; }
};
} // end serialized_diags namespace
} // end clang namespace
} // namespace serialized_diags
} // namespace clang
namespace std {
template <>
struct is_error_code_enum<clang::serialized_diags::SDError> : std::true_type {};
}
#endif
} // namespace std
#endif // LLVM_CLANG_FRONTEND_SERIALIZEDDIAGNOSTICREADER_H

View File

@ -1,4 +1,4 @@
//===--- Utils.h - Misc utilities for the front-end -------------*- C++ -*-===//
//===- Utils.h - Misc utilities for the front-end ---------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
@ -15,45 +15,49 @@
#define LLVM_CLANG_FRONTEND_UTILS_H
#include "clang/Basic/Diagnostic.h"
#include "clang/Basic/LLVM.h"
#include "clang/Basic/VirtualFileSystem.h"
#include "llvm/ADT/IntrusiveRefCntPtr.h"
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/StringMap.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/ADT/StringSet.h"
#include "llvm/Option/OptSpecifier.h"
#include <cstdint>
#include <memory>
#include <string>
#include <system_error>
#include <utility>
#include <vector>
namespace llvm {
class raw_fd_ostream;
class Triple;
namespace opt {
class ArgList;
}
}
} // namespace opt
} // namespace llvm
namespace clang {
class ASTConsumer;
class ASTReader;
class CompilerInstance;
class CompilerInvocation;
class Decl;
class DependencyOutputOptions;
class DiagnosticsEngine;
class DiagnosticOptions;
class ExternalSemaSource;
class FileManager;
class FrontendOptions;
class HeaderSearch;
class HeaderSearchOptions;
class IdentifierTable;
class LangOptions;
class PCHContainerReader;
class Preprocessor;
class PreprocessorOptions;
class PreprocessorOutputOptions;
class SourceManager;
class Stmt;
class TargetInfo;
class FrontendOptions;
/// Apply the header search options to get given HeaderSearch object.
void ApplyHeaderSearchOptions(HeaderSearch &HS,
@ -68,7 +72,7 @@ void InitializePreprocessor(Preprocessor &PP, const PreprocessorOptions &PPOpts,
const FrontendOptions &FEOpts);
/// DoPrintPreprocessedInput - Implement -E mode.
void DoPrintPreprocessedInput(Preprocessor &PP, raw_ostream* OS,
void DoPrintPreprocessedInput(Preprocessor &PP, raw_ostream *OS,
const PreprocessorOutputOptions &Opts);
/// An interface for collecting the dependencies of a compilation. Users should
@ -78,9 +82,11 @@ void DoPrintPreprocessedInput(Preprocessor &PP, raw_ostream* OS,
/// interface.
class DependencyCollector {
public:
virtual ~DependencyCollector();
virtual void attachToPreprocessor(Preprocessor &PP);
virtual void attachToASTReader(ASTReader &R);
llvm::ArrayRef<std::string> getDependencies() const { return Dependencies; }
ArrayRef<std::string> getDependencies() const { return Dependencies; }
/// Called when a new file is seen. Return true if \p Filename should be added
/// to the list of dependencies.
@ -88,17 +94,19 @@ public:
/// The default implementation ignores <built-in> and system files.
virtual bool sawDependency(StringRef Filename, bool FromModule,
bool IsSystem, bool IsModuleFile, bool IsMissing);
/// Called when the end of the main file is reached.
virtual void finishedMainFile() { }
virtual void finishedMainFile() {}
/// Return true if system files should be passed to sawDependency().
virtual bool needSystemDependencies() { return false; }
virtual ~DependencyCollector();
public: // implementation detail
// implementation detail
/// Add a dependency \p Filename if it has not been seen before and
/// sawDependency() returns true.
void maybeAddDependency(StringRef Filename, bool FromModule, bool IsSystem,
bool IsModuleFile, bool IsMissing);
private:
llvm::StringSet<> Seen;
std::vector<std::string> Dependencies;
@ -110,10 +118,13 @@ private:
/// loaded.
class DependencyFileGenerator {
void *Impl; // Opaque implementation
DependencyFileGenerator(void *Impl);
public:
static DependencyFileGenerator *CreateAndAttachToPreprocessor(
Preprocessor &PP, const DependencyOutputOptions &Opts);
void AttachToASTReader(ASTReader &R);
};
@ -124,15 +135,20 @@ class ModuleDependencyCollector : public DependencyCollector {
bool HasErrors = false;
llvm::StringSet<> Seen;
vfs::YAMLVFSWriter VFSWriter;
llvm::StringMap<std::string> SymLinkMap;
bool getRealPath(StringRef SrcPath, SmallVectorImpl<char> &Result);
std::error_code copyToRoot(StringRef Src, StringRef Dst = "");
std::error_code copyToRoot(StringRef Src, StringRef Dst = {});
public:
ModuleDependencyCollector(std::string DestDir)
: DestDir(std::move(DestDir)) {}
~ModuleDependencyCollector() override { writeFileMap(); }
StringRef getDest() { return DestDir; }
bool insertSeen(StringRef Filename) { return Seen.insert(Filename).second; }
void addFile(StringRef Filename, StringRef FileDst = "");
void addFile(StringRef Filename, StringRef FileDst = {});
void addFileMapping(StringRef VPath, StringRef RPath) {
VFSWriter.addFileMapping(VPath, RPath);
}
@ -142,9 +158,6 @@ public:
void writeFileMap();
bool hasErrors() { return HasErrors; }
ModuleDependencyCollector(std::string DestDir)
: DestDir(std::move(DestDir)) {}
~ModuleDependencyCollector() { writeFileMap(); }
};
/// AttachDependencyGraphGen - Create a dependency graph generator, and attach
@ -167,7 +180,7 @@ void AttachDependencyGraphGen(Preprocessor &PP, StringRef OutputFile,
void AttachHeaderIncludeGen(Preprocessor &PP,
const DependencyOutputOptions &DepOpts,
bool ShowAllHeaders = false,
StringRef OutputPath = "",
StringRef OutputPath = {},
bool ShowDepth = true, bool MSStyle = false);
/// Cache tokens for use with PCH. Note that this requires a seekable stream.
@ -221,6 +234,6 @@ template <typename T> void BuryPointer(std::unique_ptr<T> Ptr) {
BuryPointer(Ptr.release());
}
} // end namespace clang
} // namespace clang
#endif
#endif // LLVM_CLANG_FRONTEND_UTILS_H

View File

@ -1,4 +1,4 @@
//===--- CompilerInvocation.cpp -------------------------------------------===//
//===- CompilerInvocation.cpp ---------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
@ -10,54 +10,99 @@
#include "clang/Frontend/CompilerInvocation.h"
#include "TestModuleFileExtension.h"
#include "clang/Basic/Builtins.h"
#include "clang/Basic/FileManager.h"
#include "clang/Basic/CharInfo.h"
#include "clang/Basic/CommentOptions.h"
#include "clang/Basic/DebugInfoOptions.h"
#include "clang/Basic/Diagnostic.h"
#include "clang/Basic/DiagnosticOptions.h"
#include "clang/Basic/FileSystemOptions.h"
#include "clang/Basic/LLVM.h"
#include "clang/Basic/LangOptions.h"
#include "clang/Basic/ObjCRuntime.h"
#include "clang/Basic/Sanitizers.h"
#include "clang/Basic/SourceLocation.h"
#include "clang/Basic/TargetOptions.h"
#include "clang/Basic/Version.h"
#include "clang/Basic/VersionTuple.h"
#include "clang/Basic/VirtualFileSystem.h"
#include "clang/Basic/Visibility.h"
#include "clang/Config/config.h"
#include "clang/Driver/DriverDiagnostic.h"
#include "clang/Driver/Options.h"
#include "clang/Driver/Util.h"
#include "clang/Frontend/CodeGenOptions.h"
#include "clang/Frontend/CommandLineSourceLoc.h"
#include "clang/Frontend/DependencyOutputOptions.h"
#include "clang/Frontend/FrontendDiagnostic.h"
#include "clang/Frontend/FrontendOptions.h"
#include "clang/Frontend/LangStandard.h"
#include "clang/Frontend/MigratorOptions.h"
#include "clang/Frontend/PreprocessorOutputOptions.h"
#include "clang/Frontend/Utils.h"
#include "clang/Lex/HeaderSearchOptions.h"
#include "clang/Lex/PreprocessorOptions.h"
#include "clang/Serialization/ASTReader.h"
#include "clang/Sema/CodeCompleteOptions.h"
#include "clang/Serialization/ModuleFileExtension.h"
#include "clang/StaticAnalyzer/Core/AnalyzerOptions.h"
#include "llvm/ADT/APInt.h"
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/CachedHashString.h"
#include "llvm/ADT/Hashing.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/None.h"
#include "llvm/ADT/Optional.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/ADT/StringSwitch.h"
#include "llvm/ADT/Triple.h"
#include "llvm/ADT/Twine.h"
#include "llvm/Linker/Linker.h"
#include "llvm/MC/MCTargetOptions.h"
#include "llvm/Option/Arg.h"
#include "llvm/Option/ArgList.h"
#include "llvm/Option/OptSpecifier.h"
#include "llvm/Option/OptTable.h"
#include "llvm/Option/Option.h"
#include "llvm/ProfileData/InstrProfReader.h"
#include "llvm/Support/CodeGen.h"
#include "llvm/Support/Compiler.h"
#include "llvm/Support/Error.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/ErrorOr.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/Host.h"
#include "llvm/Support/MathExtras.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/Process.h"
#include "llvm/Support/Regex.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Target/TargetOptions.h"
#include "llvm/Support/ScopedPrinter.h"
#include <algorithm>
#include <atomic>
#include <cassert>
#include <cstddef>
#include <cstring>
#include <memory>
#include <sys/stat.h>
#include <system_error>
#include <string>
#include <tuple>
#include <utility>
#include <vector>
using namespace clang;
using namespace driver;
using namespace options;
using namespace llvm::opt;
//===----------------------------------------------------------------------===//
// Initialization.
//===----------------------------------------------------------------------===//
CompilerInvocationBase::CompilerInvocationBase()
: LangOpts(new LangOptions()), TargetOpts(new TargetOptions()),
DiagnosticOpts(new DiagnosticOptions()),
HeaderSearchOpts(new HeaderSearchOptions()),
PreprocessorOpts(new PreprocessorOptions()) {}
: LangOpts(new LangOptions()), TargetOpts(new TargetOptions()),
DiagnosticOpts(new DiagnosticOptions()),
HeaderSearchOpts(new HeaderSearchOptions()),
PreprocessorOpts(new PreprocessorOptions()) {}
CompilerInvocationBase::CompilerInvocationBase(const CompilerInvocationBase &X)
: LangOpts(new LangOptions(*X.getLangOpts())),
@ -66,18 +111,12 @@ CompilerInvocationBase::CompilerInvocationBase(const CompilerInvocationBase &X)
HeaderSearchOpts(new HeaderSearchOptions(X.getHeaderSearchOpts())),
PreprocessorOpts(new PreprocessorOptions(X.getPreprocessorOpts())) {}
CompilerInvocationBase::~CompilerInvocationBase() {}
CompilerInvocationBase::~CompilerInvocationBase() = default;
//===----------------------------------------------------------------------===//
// Deserialization (from args)
//===----------------------------------------------------------------------===//
using namespace clang::driver;
using namespace clang::driver::options;
using namespace llvm::opt;
//
static unsigned getOptimizationLevel(ArgList &Args, InputKind IK,
DiagnosticsEngine &Diags) {
unsigned DefaultOpt = 0;
@ -91,7 +130,7 @@ static unsigned getOptimizationLevel(ArgList &Args, InputKind IK,
if (A->getOption().matches(options::OPT_Ofast))
return 3;
assert (A->getOption().matches(options::OPT_O));
assert(A->getOption().matches(options::OPT_O));
StringRef S(A->getValue());
if (S == "s" || S == "z" || S.empty())
@ -125,7 +164,7 @@ static unsigned getOptimizationLevelSize(ArgList &Args) {
static void addDiagnosticArgs(ArgList &Args, OptSpecifier Group,
OptSpecifier GroupWithValue,
std::vector<std::string> &Diagnostics) {
for (Arg *A : Args.filtered(Group)) {
for (auto *A : Args.filtered(Group)) {
if (A->getOption().getKind() == Option::FlagClass) {
// The argument is a pure flag (such as OPT_Wall or OPT_Wdeprecated). Add
// its name (minus the "W" or "R" at the beginning) to the warning list.
@ -135,7 +174,7 @@ static void addDiagnosticArgs(ArgList &Args, OptSpecifier Group,
Diagnostics.push_back(A->getOption().getName().drop_front(1).rtrim("=-"));
} else {
// Otherwise, add its value (for OPT_W_Joined and similar).
for (const char *Arg : A->getValues())
for (const auto *Arg : A->getValues())
Diagnostics.emplace_back(Arg);
}
}
@ -157,7 +196,6 @@ static void getAllNoBuiltinFuncValues(ArgList &Args,
static bool ParseAnalyzerArgs(AnalyzerOptions &Opts, ArgList &Args,
DiagnosticsEngine &Diags) {
using namespace options;
bool Success = true;
if (Arg *A = Args.getLastArg(OPT_analyzer_store)) {
StringRef Name = A->getValue();
@ -273,31 +311,31 @@ static bool ParseAnalyzerArgs(AnalyzerOptions &Opts, ArgList &Args,
StringRef checkerList = A->getValue();
SmallVector<StringRef, 4> checkers;
checkerList.split(checkers, ",");
for (StringRef checker : checkers)
for (auto checker : checkers)
Opts.CheckersControlList.emplace_back(checker, enable);
}
// Go through the analyzer configuration options.
for (const Arg *A : Args.filtered(OPT_analyzer_config)) {
for (const auto *A : Args.filtered(OPT_analyzer_config)) {
A->claim();
// We can have a list of comma separated config names, e.g:
// '-analyzer-config key1=val1,key2=val2'
StringRef configList = A->getValue();
SmallVector<StringRef, 4> configVals;
configList.split(configVals, ",");
for (unsigned i = 0, e = configVals.size(); i != e; ++i) {
for (const auto &configVal : configVals) {
StringRef key, val;
std::tie(key, val) = configVals[i].split("=");
std::tie(key, val) = configVal.split("=");
if (val.empty()) {
Diags.Report(SourceLocation(),
diag::err_analyzer_config_no_value) << configVals[i];
diag::err_analyzer_config_no_value) << configVal;
Success = false;
break;
}
if (val.find('=') != StringRef::npos) {
Diags.Report(SourceLocation(),
diag::err_analyzer_config_multiple_values)
<< configVals[i];
<< configVal;
Success = false;
break;
}
@ -306,7 +344,7 @@ static bool ParseAnalyzerArgs(AnalyzerOptions &Opts, ArgList &Args,
}
llvm::raw_string_ostream os(Opts.FullCompilerInvocation);
for (unsigned i=0; i<Args.getNumInputArgStrings(); i++) {
for (unsigned i = 0; i < Args.getNumInputArgStrings(); ++i) {
if (i != 0)
os << " ";
os << Args.getArgString(i);
@ -425,8 +463,7 @@ static void setPGOInstrumentor(CodeGenOptions &Opts, ArgList &Args,
<< S;
return;
}
CodeGenOptions::ProfileInstrKind Instrumentor =
static_cast<CodeGenOptions::ProfileInstrKind>(I);
auto Instrumentor = static_cast<CodeGenOptions::ProfileInstrKind>(I);
Opts.setProfileInstr(Instrumentor);
}
@ -451,7 +488,6 @@ static void setPGOUseInstrumentor(CodeGenOptions &Opts,
static bool ParseCodeGenArgs(CodeGenOptions &Opts, ArgList &Args, InputKind IK,
DiagnosticsEngine &Diags,
const TargetOptions &TargetOpts) {
using namespace options;
bool Success = true;
llvm::Triple Triple = llvm::Triple(TargetOpts.Triple);
@ -853,7 +889,8 @@ static bool ParseCodeGenArgs(CodeGenOptions &Opts, ArgList &Args, InputKind IK,
Opts.RelaxELFRelocations = Args.hasArg(OPT_mrelax_relocations);
Opts.DebugCompilationDir = Args.getLastArgValue(OPT_fdebug_compilation_dir);
for (auto A : Args.filtered(OPT_mlink_bitcode_file, OPT_mlink_cuda_bitcode)) {
for (auto *A :
Args.filtered(OPT_mlink_bitcode_file, OPT_mlink_cuda_bitcode)) {
CodeGenOptions::BitcodeFileToLink F;
F.Filename = A->getValue();
if (A->getOption().matches(OPT_mlink_cuda_bitcode)) {
@ -1065,7 +1102,6 @@ static bool ParseCodeGenArgs(CodeGenOptions &Opts, ArgList &Args, InputKind IK,
static void ParseDependencyOutputArgs(DependencyOutputOptions &Opts,
ArgList &Args) {
using namespace options;
Opts.OutputFile = Args.getLastArgValue(OPT_dependency_file);
Opts.Targets = Args.getAllArgValues(OPT_MT);
Opts.IncludeSystemHeaders = Args.hasArg(OPT_sys_header_deps);
@ -1085,7 +1121,7 @@ static void ParseDependencyOutputArgs(DependencyOutputOptions &Opts,
// we let make / ninja to know about this implicit dependency.
Opts.ExtraDeps = Args.getAllArgValues(OPT_fdepfile_entry);
// Only the -fmodule-file=<file> form.
for (const Arg *A : Args.filtered(OPT_fmodule_file)) {
for (const auto *A : Args.filtered(OPT_fmodule_file)) {
StringRef Val = A->getValue();
if (Val.find('=') == StringRef::npos)
Opts.ExtraDeps.push_back(Val);
@ -1102,7 +1138,7 @@ static bool parseShowColorsArgs(const ArgList &Args, bool DefaultColor) {
Colors_Off,
Colors_Auto
} ShowColors = DefaultColor ? Colors_Auto : Colors_Off;
for (Arg *A : Args) {
for (auto *A : Args) {
const Option &O = A->getOption();
if (O.matches(options::OPT_fcolor_diagnostics) ||
O.matches(options::OPT_fdiagnostics_color)) {
@ -1148,7 +1184,6 @@ static bool checkVerifyPrefixes(const std::vector<std::string> &VerifyPrefixes,
bool clang::ParseDiagnosticArgs(DiagnosticOptions &Opts, ArgList &Args,
DiagnosticsEngine *Diags,
bool DefaultDiagColor, bool DefaultShowOpt) {
using namespace options;
bool Success = true;
Opts.DiagnosticLogFile = Args.getLastArgValue(OPT_diagnostic_log_file);
@ -1315,7 +1350,6 @@ static bool parseTestModuleFileExtensionArg(StringRef Arg,
static InputKind ParseFrontendArgs(FrontendOptions &Opts, ArgList &Args,
DiagnosticsEngine &Diags,
bool &IsHeaderFile) {
using namespace options;
Opts.ProgramAction = frontend::ParseSyntaxOnly;
if (const Arg *A = Args.getLastArg(OPT_Action_Group)) {
switch (A->getOption().getID()) {
@ -1399,7 +1433,7 @@ static InputKind ParseFrontendArgs(FrontendOptions &Opts, ArgList &Args,
Opts.ActionName = A->getValue();
}
Opts.AddPluginActions = Args.getAllArgValues(OPT_add_plugin);
for (const Arg *AA : Args.filtered(OPT_plugin_arg))
for (const auto *AA : Args.filtered(OPT_plugin_arg))
Opts.PluginArgs[AA->getValue(0)].emplace_back(AA->getValue(1));
for (const std::string &Arg :
@ -1452,7 +1486,7 @@ static InputKind ParseFrontendArgs(FrontendOptions &Opts, ArgList &Args,
Opts.GenerateGlobalModuleIndex = Opts.UseGlobalModuleIndex;
Opts.ModuleMapFiles = Args.getAllArgValues(OPT_fmodule_map_file);
// Only the -fmodule-file=<file> form.
for (const Arg *A : Args.filtered(OPT_fmodule_file)) {
for (const auto *A : Args.filtered(OPT_fmodule_file)) {
StringRef Val = A->getValue();
if (Val.find('=') == StringRef::npos)
Opts.ModuleFiles.push_back(Val);
@ -1640,7 +1674,6 @@ std::string CompilerInvocation::GetResourcesPath(const char *Argv0,
static void ParseHeaderSearchArgs(HeaderSearchOptions &Opts, ArgList &Args,
const std::string &WorkingDir) {
using namespace options;
Opts.Sysroot = Args.getLastArgValue(OPT_isysroot, "/");
Opts.Verbose = Args.hasArg(OPT_v);
Opts.UseBuiltinIncludes = !Args.hasArg(OPT_nobuiltininc);
@ -1663,12 +1696,12 @@ static void ParseHeaderSearchArgs(HeaderSearchOptions &Opts, ArgList &Args,
Opts.ModuleUserBuildPath = Args.getLastArgValue(OPT_fmodules_user_build_path);
// Only the -fmodule-file=<name>=<file> form.
for (const Arg *A : Args.filtered(OPT_fmodule_file)) {
for (const auto *A : Args.filtered(OPT_fmodule_file)) {
StringRef Val = A->getValue();
if (Val.find('=') != StringRef::npos)
Opts.PrebuiltModuleFiles.insert(Val.split('='));
}
for (const Arg *A : Args.filtered(OPT_fprebuilt_module_path))
for (const auto *A : Args.filtered(OPT_fprebuilt_module_path))
Opts.AddPrebuiltModulePath(A->getValue());
Opts.DisableModuleHash = Args.hasArg(OPT_fdisable_module_hash);
Opts.ModulesHashContent = Args.hasArg(OPT_fmodules_hash_content);
@ -1689,7 +1722,7 @@ static void ParseHeaderSearchArgs(HeaderSearchOptions &Opts, ArgList &Args,
if (const Arg *A = Args.getLastArg(OPT_fmodule_format_EQ))
Opts.ModuleFormat = A->getValue();
for (const Arg *A : Args.filtered(OPT_fmodules_ignore_macro)) {
for (const auto *A : Args.filtered(OPT_fmodules_ignore_macro)) {
StringRef MacroDef = A->getValue();
Opts.ModulesIgnoreMacros.insert(
llvm::CachedHashString(MacroDef.split('=').first));
@ -1699,7 +1732,7 @@ static void ParseHeaderSearchArgs(HeaderSearchOptions &Opts, ArgList &Args,
bool IsIndexHeaderMap = false;
bool IsSysrootSpecified =
Args.hasArg(OPT__sysroot_EQ) || Args.hasArg(OPT_isysroot);
for (const Arg *A : Args.filtered(OPT_I, OPT_F, OPT_index_header_map)) {
for (const auto *A : Args.filtered(OPT_I, OPT_F, OPT_index_header_map)) {
if (A->getOption().matches(OPT_index_header_map)) {
// -index-header-map applies to the next -I or -F.
IsIndexHeaderMap = true;
@ -1726,7 +1759,7 @@ static void ParseHeaderSearchArgs(HeaderSearchOptions &Opts, ArgList &Args,
// Add -iprefix/-iwithprefix/-iwithprefixbefore options.
StringRef Prefix = ""; // FIXME: This isn't the correct default prefix.
for (const Arg *A :
for (const auto *A :
Args.filtered(OPT_iprefix, OPT_iwithprefix, OPT_iwithprefixbefore)) {
if (A->getOption().matches(OPT_iprefix))
Prefix = A->getValue();
@ -1736,31 +1769,31 @@ static void ParseHeaderSearchArgs(HeaderSearchOptions &Opts, ArgList &Args,
Opts.AddPath(Prefix.str() + A->getValue(), frontend::Angled, false, true);
}
for (const Arg *A : Args.filtered(OPT_idirafter))
for (const auto *A : Args.filtered(OPT_idirafter))
Opts.AddPath(A->getValue(), frontend::After, false, true);
for (const Arg *A : Args.filtered(OPT_iquote))
for (const auto *A : Args.filtered(OPT_iquote))
Opts.AddPath(A->getValue(), frontend::Quoted, false, true);
for (const Arg *A : Args.filtered(OPT_isystem, OPT_iwithsysroot))
for (const auto *A : Args.filtered(OPT_isystem, OPT_iwithsysroot))
Opts.AddPath(A->getValue(), frontend::System, false,
!A->getOption().matches(OPT_iwithsysroot));
for (const Arg *A : Args.filtered(OPT_iframework))
for (const auto *A : Args.filtered(OPT_iframework))
Opts.AddPath(A->getValue(), frontend::System, true, true);
for (const Arg *A : Args.filtered(OPT_iframeworkwithsysroot))
for (const auto *A : Args.filtered(OPT_iframeworkwithsysroot))
Opts.AddPath(A->getValue(), frontend::System, /*IsFramework=*/true,
/*IgnoreSysRoot=*/false);
// Add the paths for the various language specific isystem flags.
for (const Arg *A : Args.filtered(OPT_c_isystem))
for (const auto *A : Args.filtered(OPT_c_isystem))
Opts.AddPath(A->getValue(), frontend::CSystem, false, true);
for (const Arg *A : Args.filtered(OPT_cxx_isystem))
for (const auto *A : Args.filtered(OPT_cxx_isystem))
Opts.AddPath(A->getValue(), frontend::CXXSystem, false, true);
for (const Arg *A : Args.filtered(OPT_objc_isystem))
for (const auto *A : Args.filtered(OPT_objc_isystem))
Opts.AddPath(A->getValue(), frontend::ObjCSystem, false,true);
for (const Arg *A : Args.filtered(OPT_objcxx_isystem))
for (const auto *A : Args.filtered(OPT_objcxx_isystem))
Opts.AddPath(A->getValue(), frontend::ObjCXXSystem, false, true);
// Add the internal paths from a driver that detects standard include paths.
for (const Arg *A :
for (const auto *A :
Args.filtered(OPT_internal_isystem, OPT_internal_externc_isystem)) {
frontend::IncludeDirGroup Group = frontend::System;
if (A->getOption().matches(OPT_internal_externc_isystem))
@ -1769,12 +1802,12 @@ static void ParseHeaderSearchArgs(HeaderSearchOptions &Opts, ArgList &Args,
}
// Add the path prefixes which are implicitly treated as being system headers.
for (const Arg *A :
for (const auto *A :
Args.filtered(OPT_system_header_prefix, OPT_no_system_header_prefix))
Opts.AddSystemHeaderPrefix(
A->getValue(), A->getOption().matches(OPT_system_header_prefix));
for (const Arg *A : Args.filtered(OPT_ivfsoverlay))
for (const auto *A : Args.filtered(OPT_ivfsoverlay))
Opts.AddVFSOverlayFile(A->getValue());
}
@ -2508,7 +2541,7 @@ static void ParseLangArgs(LangOptions &Opts, ArgList &Args, InputKind IK,
// Add unsupported host targets here:
case llvm::Triple::nvptx:
case llvm::Triple::nvptx64:
Diags.Report(clang::diag::err_drv_omp_host_target_not_supported)
Diags.Report(diag::err_drv_omp_host_target_not_supported)
<< TargetOpts.Triple;
break;
}
@ -2536,7 +2569,7 @@ static void ParseLangArgs(LangOptions &Opts, ArgList &Args, InputKind IK,
TT.getArch() == llvm::Triple::nvptx64 ||
TT.getArch() == llvm::Triple::x86 ||
TT.getArch() == llvm::Triple::x86_64))
Diags.Report(clang::diag::err_drv_invalid_omp_target) << A->getValue(i);
Diags.Report(diag::err_drv_invalid_omp_target) << A->getValue(i);
else
Opts.OMPTargetTriples.push_back(TT);
}
@ -2547,7 +2580,7 @@ static void ParseLangArgs(LangOptions &Opts, ArgList &Args, InputKind IK,
if (Arg *A = Args.getLastArg(options::OPT_fopenmp_host_ir_file_path)) {
Opts.OMPHostIRFile = A->getValue();
if (!llvm::sys::fs::exists(Opts.OMPHostIRFile))
Diags.Report(clang::diag::err_drv_omp_host_ir_file_not_found)
Diags.Report(diag::err_drv_omp_host_ir_file_not_found)
<< Opts.OMPHostIRFile;
}
@ -2684,7 +2717,6 @@ static bool isStrictlyPreprocessorAction(frontend::ActionKind Action) {
static void ParsePreprocessorArgs(PreprocessorOptions &Opts, ArgList &Args,
DiagnosticsEngine &Diags,
frontend::ActionKind Action) {
using namespace options;
Opts.ImplicitPCHInclude = Args.getLastArgValue(OPT_include_pch);
Opts.ImplicitPTHInclude = Args.getLastArgValue(OPT_include_pth);
if (const Arg *A = Args.getLastArg(OPT_token_cache))
@ -2697,7 +2729,7 @@ static void ParsePreprocessorArgs(PreprocessorOptions &Opts, ArgList &Args,
Opts.AllowPCHWithCompilerErrors = Args.hasArg(OPT_fallow_pch_with_errors);
Opts.DumpDeserializedPCHDecls = Args.hasArg(OPT_dump_deserialized_pch_decls);
for (const Arg *A : Args.filtered(OPT_error_on_deserialized_pch_decl))
for (const auto *A : Args.filtered(OPT_error_on_deserialized_pch_decl))
Opts.DeserializedPCHDeclsToErrorOn.insert(A->getValue());
if (const Arg *A = Args.getLastArg(OPT_preamble_bytes_EQ)) {
@ -2717,7 +2749,7 @@ static void ParsePreprocessorArgs(PreprocessorOptions &Opts, ArgList &Args,
}
// Add macros from the command line.
for (const Arg *A : Args.filtered(OPT_D, OPT_U)) {
for (const auto *A : Args.filtered(OPT_D, OPT_U)) {
if (A->getOption().matches(OPT_D))
Opts.addMacroDef(A->getValue());
else
@ -2727,13 +2759,13 @@ static void ParsePreprocessorArgs(PreprocessorOptions &Opts, ArgList &Args,
Opts.MacroIncludes = Args.getAllArgValues(OPT_imacros);
// Add the ordered list of -includes.
for (const Arg *A : Args.filtered(OPT_include))
for (const auto *A : Args.filtered(OPT_include))
Opts.Includes.emplace_back(A->getValue());
for (const Arg *A : Args.filtered(OPT_chain_include))
for (const auto *A : Args.filtered(OPT_chain_include))
Opts.ChainedIncludes.emplace_back(A->getValue());
for (const Arg *A : Args.filtered(OPT_remap_file)) {
for (const auto *A : Args.filtered(OPT_remap_file)) {
std::pair<StringRef, StringRef> Split = StringRef(A->getValue()).split(';');
if (Split.second.empty()) {
@ -2767,8 +2799,6 @@ static void ParsePreprocessorArgs(PreprocessorOptions &Opts, ArgList &Args,
static void ParsePreprocessorOutputArgs(PreprocessorOutputOptions &Opts,
ArgList &Args,
frontend::ActionKind Action) {
using namespace options;
if (isStrictlyPreprocessorAction(Action))
Opts.ShowCPP = !Args.hasArg(OPT_dM);
else
@ -2786,7 +2816,6 @@ static void ParsePreprocessorOutputArgs(PreprocessorOutputOptions &Opts,
static void ParseTargetArgs(TargetOptions &Opts, ArgList &Args,
DiagnosticsEngine &Diags) {
using namespace options;
Opts.ABI = Args.getLastArgValue(OPT_target_abi);
if (Arg *A = Args.getLastArg(OPT_meabi)) {
StringRef Value = A->getValue();
@ -2837,7 +2866,7 @@ bool CompilerInvocation::CreateFromArgs(CompilerInvocation &Res,
}
// Issue errors on unknown arguments.
for (const Arg *A : Args.filtered(OPT_UNKNOWN)) {
for (const auto *A : Args.filtered(OPT_UNKNOWN)) {
auto ArgString = A->getAsString(Args);
std::string Nearest;
if (Opts->findNearest(ArgString, Nearest, IncludedFlagsBitmask) > 1)
@ -2952,29 +2981,26 @@ std::string CompilerInvocation::getModuleHash() const {
// Extend the signature with the target options.
code = hash_combine(code, TargetOpts->Triple, TargetOpts->CPU,
TargetOpts->ABI);
for (unsigned i = 0, n = TargetOpts->FeaturesAsWritten.size(); i != n; ++i)
code = hash_combine(code, TargetOpts->FeaturesAsWritten[i]);
for (const auto &FeatureAsWritten : TargetOpts->FeaturesAsWritten)
code = hash_combine(code, FeatureAsWritten);
// Extend the signature with preprocessor options.
const PreprocessorOptions &ppOpts = getPreprocessorOpts();
const HeaderSearchOptions &hsOpts = getHeaderSearchOpts();
code = hash_combine(code, ppOpts.UsePredefines, ppOpts.DetailedRecord);
for (std::vector<std::pair<std::string, bool/*isUndef*/>>::const_iterator
I = getPreprocessorOpts().Macros.begin(),
IEnd = getPreprocessorOpts().Macros.end();
I != IEnd; ++I) {
for (const auto &I : getPreprocessorOpts().Macros) {
// If we're supposed to ignore this macro for the purposes of modules,
// don't put it into the hash.
if (!hsOpts.ModulesIgnoreMacros.empty()) {
// Check whether we're ignoring this macro.
StringRef MacroDef = I->first;
StringRef MacroDef = I.first;
if (hsOpts.ModulesIgnoreMacros.count(
llvm::CachedHashString(MacroDef.split('=').first)))
continue;
}
code = hash_combine(code, I->first, I->second);
code = hash_combine(code, I.first, I.second);
}
// Extend the signature with the sysroot and other header search options.
@ -3007,8 +3033,6 @@ std::string CompilerInvocation::getModuleHash() const {
return llvm::APInt(64, code).toString(36, /*Signed=*/false);
}
namespace clang {
template<typename IntTy>
static IntTy getLastArgIntValueImpl(const ArgList &Args, OptSpecifier Id,
IntTy Default,
@ -3024,6 +3048,7 @@ static IntTy getLastArgIntValueImpl(const ArgList &Args, OptSpecifier Id,
return Res;
}
namespace clang {
// Declared in clang/Frontend/Utils.h.
int getLastArgIntValue(const ArgList &Args, OptSpecifier Id, int Default,
@ -3068,7 +3093,7 @@ createVFSFromCompilerInvocation(const CompilerInvocation &CI,
IntrusiveRefCntPtr<vfs::OverlayFileSystem> Overlay(
new vfs::OverlayFileSystem(BaseFS));
// earlier vfs files are on the bottom
for (const std::string &File : CI.getHeaderSearchOpts().VFSOverlayFiles) {
for (const auto &File : CI.getHeaderSearchOpts().VFSOverlayFiles) {
llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> Buffer =
BaseFS->getBufferForFile(File);
if (!Buffer) {
@ -3085,4 +3110,5 @@ createVFSFromCompilerInvocation(const CompilerInvocation &CI,
}
return Overlay;
}
} // end namespace clang
} // namespace clang

View File

@ -1,4 +1,4 @@
//===--- FrontendOptions.cpp ----------------------------------------------===//
//===- FrontendOptions.cpp ------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
@ -9,6 +9,7 @@
#include "clang/Frontend/FrontendOptions.h"
#include "llvm/ADT/StringSwitch.h"
using namespace clang;
InputKind FrontendOptions::getInputKindForExtension(StringRef Extension) {

View File

@ -1,4 +1,4 @@
//===--- SerializedDiagnosticReader.cpp - Reads diagnostics ---------------===//
//===- SerializedDiagnosticReader.cpp - Reads diagnostics -----------------===//
//
// The LLVM Compiler Infrastructure
//
@ -9,11 +9,22 @@
#include "clang/Frontend/SerializedDiagnosticReader.h"
#include "clang/Basic/FileManager.h"
#include "clang/Basic/FileSystemOptions.h"
#include "clang/Frontend/SerializedDiagnostics.h"
#include "llvm/ADT/Optional.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/Bitcode/BitCodes.h"
#include "llvm/Bitcode/BitstreamReader.h"
#include "llvm/Support/Compiler.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/ErrorOr.h"
#include "llvm/Support/ManagedStatic.h"
#include <cstdint>
#include <system_error>
using namespace clang;
using namespace clang::serialized_diags;
using namespace serialized_diags;
std::error_code SerializedDiagnosticReader::readDiagnostics(StringRef File) {
// Open the diagnostics file.
@ -44,13 +55,12 @@ std::error_code SerializedDiagnosticReader::readDiagnostics(StringRef File) {
std::error_code EC;
switch (Stream.ReadSubBlockID()) {
case llvm::bitc::BLOCKINFO_BLOCK_ID: {
case llvm::bitc::BLOCKINFO_BLOCK_ID:
BlockInfo = Stream.ReadBlockInfoBlock();
if (!BlockInfo)
return SDError::MalformedBlockInfoBlock;
Stream.setBlockInfo(&*BlockInfo);
continue;
}
case BLOCK_META:
if ((EC = readMetaBlock(Stream)))
return EC;
@ -65,7 +75,7 @@ std::error_code SerializedDiagnosticReader::readDiagnostics(StringRef File) {
continue;
}
}
return std::error_code();
return {};
}
enum class SerializedDiagnosticReader::Cursor {
@ -132,7 +142,7 @@ SerializedDiagnosticReader::readMetaBlock(llvm::BitstreamCursor &Stream) {
case Cursor::BlockEnd:
if (!VersionChecked)
return SDError::MissingVersion;
return std::error_code();
return {};
}
SmallVector<uint64_t, 1> Record;
@ -176,7 +186,7 @@ SerializedDiagnosticReader::readDiagnosticBlock(llvm::BitstreamCursor &Stream) {
case Cursor::BlockEnd:
if ((EC = visitEndOfDiagnostic()))
return EC;
return std::error_code();
return {};
case Cursor::Record:
break;
}
@ -253,12 +263,14 @@ SerializedDiagnosticReader::readDiagnosticBlock(llvm::BitstreamCursor &Stream) {
}
namespace {
class SDErrorCategoryType final : public std::error_category {
const char *name() const noexcept override {
return "clang.serialized_diags";
}
std::string message(int IE) const override {
SDError E = static_cast<SDError>(IE);
auto E = static_cast<SDError>(IE);
switch (E) {
case SDError::CouldNotLoad:
return "Failed to open diagnostics file";
@ -290,7 +302,8 @@ class SDErrorCategoryType final : public std::error_category {
llvm_unreachable("Unknown error type!");
}
};
}
} // namespace
static llvm::ManagedStatic<SDErrorCategoryType> ErrorCategory;
const std::error_category &clang::serialized_diags::SDErrorCategory() {