diff --git a/flang/include/flang/Frontend/.clang-tidy b/flang/include/flang/Frontend/.clang-tidy new file mode 100644 --- /dev/null +++ b/flang/include/flang/Frontend/.clang-tidy @@ -0,0 +1,9 @@ +Checks: '-readability-braces-around-statements,readability-identifier-naming,llvm-include-order,clang-diagnostic-*' +InheritParentConfig: true +CheckOptions: + - key: readability-identifier-naming.MemberCase + value: camelBack + - key: readability-identifier-naming.ParameterCase + value: camelBack + - key: readability-identifier-naming.VariableCase + value: camelBack diff --git a/flang/include/flang/Frontend/CompilerInstance.h b/flang/include/flang/Frontend/CompilerInstance.h --- a/flang/include/flang/Frontend/CompilerInstance.h +++ b/flang/include/flang/Frontend/CompilerInstance.h @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// -#ifndef LLVM_FLANG_FRONTEND_COMPILERINSTANCE_H -#define LLVM_FLANG_FRONTEND_COMPILERINSTANCE_H +#ifndef FORTRAN_FRONTEND_COMPILERINSTANCE_H +#define FORTRAN_FRONTEND_COMPILERINSTANCE_H #include "flang/Frontend/CompilerInvocation.h" #include "flang/Frontend/FrontendAction.h" @@ -37,43 +37,43 @@ class CompilerInstance { /// The options used in this compiler instance. - std::shared_ptr invocation_; + std::shared_ptr invocation; /// Flang file manager. - std::shared_ptr allSources_; + std::shared_ptr allSources; - std::shared_ptr allCookedSources_; + std::shared_ptr allCookedSources; - std::shared_ptr parsing_; + std::shared_ptr parsing; - std::unique_ptr semantics_; + std::unique_ptr semantics; - std::unique_ptr rtTyTables_; + std::unique_ptr rtTyTables; /// The stream for diagnostics from Semantics - llvm::raw_ostream *semaOutputStream_ = &llvm::errs(); + llvm::raw_ostream *semaOutputStream = &llvm::errs(); /// The stream for diagnostics from Semantics if owned, otherwise nullptr. - std::unique_ptr ownedSemaOutputStream_; + std::unique_ptr ownedSemaOutputStream; /// The diagnostics engine instance. - llvm::IntrusiveRefCntPtr diagnostics_; + llvm::IntrusiveRefCntPtr diagnostics; /// Holds information about the output file. struct OutputFile { - std::string filename_; + std::string filename; OutputFile(std::string inputFilename) - : filename_(std::move(inputFilename)) {} + : filename(std::move(inputFilename)) {} }; /// The list of active output files. - std::list outputFiles_; + std::list outputFiles; /// Holds the output stream provided by the user. Normally, users of /// CompilerInstance will call CreateOutputFile to obtain/create an output /// stream. If they want to provide their own output stream, this field will /// facilitate this. It is optional and will normally be just a nullptr. - std::unique_ptr outputStream_; + std::unique_ptr outputStream; public: explicit CompilerInstance(); @@ -83,26 +83,26 @@ /// @name Compiler Invocation /// { - CompilerInvocation &invocation() { - assert(invocation_ && "Compiler instance has no invocation!"); - return *invocation_; + CompilerInvocation &getInvocation() { + assert(invocation && "Compiler instance has no invocation!"); + return *invocation; }; /// Replace the current invocation. - void set_invocation(std::shared_ptr value); + void setInvocation(std::shared_ptr value); /// } /// @name File manager /// { /// Return the current allSources. - Fortran::parser::AllSources &allSources() const { return *allSources_; } + Fortran::parser::AllSources &getAllSources() const { return *allSources; } - bool HasAllSources() const { return allSources_ != nullptr; } + bool hasAllSources() const { return allSources != nullptr; } - parser::AllCookedSources &allCookedSources() { - assert(allCookedSources_ && "Compiler instance has no AllCookedSources!"); - return *allCookedSources_; + parser::AllCookedSources &getAllCookedSources() { + assert(allCookedSources && "Compiler instance has no AllCookedSources!"); + return *allCookedSources; }; /// } @@ -110,36 +110,38 @@ /// { /// Return parsing to be used by Actions. - Fortran::parser::Parsing &parsing() const { return *parsing_; } + Fortran::parser::Parsing &getParsing() const { return *parsing; } /// } /// @name Semantic analysis /// { /// Replace the current stream for verbose output. - void set_semaOutputStream(llvm::raw_ostream &Value); + void setSemaOutputStream(llvm::raw_ostream &value); /// Replace the current stream for verbose output. - void set_semaOutputStream(std::unique_ptr Value); + void setSemaOutputStream(std::unique_ptr value); /// Get the current stream for verbose output. - llvm::raw_ostream &semaOutputStream() { return *semaOutputStream_; } + llvm::raw_ostream &getSemaOutputStream() { return *semaOutputStream; } - Fortran::semantics::Semantics &semantics() { return *semantics_; } - const Fortran::semantics::Semantics &semantics() const { return *semantics_; } + Fortran::semantics::Semantics &getSemantics() { return *semantics; } + const Fortran::semantics::Semantics &getSemantics() const { + return *semantics; + } - void SetSemantics(std::unique_ptr semantics) { - semantics_ = std::move(semantics); + void setSemantics(std::unique_ptr sema) { + semantics = std::move(sema); } void setRtTyTables( std::unique_ptr tables) { - rtTyTables_ = std::move(tables); + rtTyTables = std::move(tables); } Fortran::semantics::RuntimeDerivedTypeTables &getRtTyTables() { - assert(rtTyTables_ && "Missing runtime derived type tables!"); - return *rtTyTables_; + assert(rtTyTables && "Missing runtime derived type tables!"); + return *rtTyTables; } /// } @@ -150,47 +152,47 @@ /// CompilerInvocation object. /// \param act - The action to execute. /// \return - True on success. - bool ExecuteAction(FrontendAction &act); + bool executeAction(FrontendAction &act); /// } /// @name Forwarding Methods /// { - clang::DiagnosticOptions &GetDiagnosticOpts() { - return invocation_->GetDiagnosticOpts(); + clang::DiagnosticOptions &getDiagnosticOpts() { + return invocation->getDiagnosticOpts(); } - const clang::DiagnosticOptions &GetDiagnosticOpts() const { - return invocation_->GetDiagnosticOpts(); + const clang::DiagnosticOptions &getDiagnosticOpts() const { + return invocation->getDiagnosticOpts(); } - FrontendOptions &frontendOpts() { return invocation_->frontendOpts(); } - const FrontendOptions &frontendOpts() const { - return invocation_->frontendOpts(); + FrontendOptions &getFrontendOpts() { return invocation->getFrontendOpts(); } + const FrontendOptions &getFrontendOpts() const { + return invocation->getFrontendOpts(); } PreprocessorOptions &preprocessorOpts() { - return invocation_->preprocessorOpts(); + return invocation->getPreprocessorOpts(); } const PreprocessorOptions &preprocessorOpts() const { - return invocation_->preprocessorOpts(); + return invocation->getPreprocessorOpts(); } /// } /// @name Diagnostics Engine /// { - bool HasDiagnostics() const { return diagnostics_ != nullptr; } + bool hasDiagnostics() const { return diagnostics != nullptr; } /// Get the current diagnostics engine. - clang::DiagnosticsEngine &diagnostics() const { - assert(diagnostics_ && "Compiler instance has no diagnostics!"); - return *diagnostics_; + clang::DiagnosticsEngine &getDiagnostics() const { + assert(diagnostics && "Compiler instance has no diagnostics!"); + return *diagnostics; } - clang::DiagnosticConsumer &GetDiagnosticClient() const { - assert(diagnostics_ && diagnostics_->getClient() && + clang::DiagnosticConsumer &getDiagnosticClient() const { + assert(diagnostics && diagnostics->getClient() && "Compiler instance has no diagnostic client!"); - return *diagnostics_->getClient(); + return *diagnostics->getClient(); } /// { @@ -198,7 +200,7 @@ /// { /// Clear the output file list. - void ClearOutputFiles(bool eraseFiles); + void clearOutputFiles(bool eraseFiles); /// Create the default output file (based on the invocation's options) and /// add it to the list of tracked output files. If the name of the output @@ -211,7 +213,7 @@ /// \param extension The extension to use for output names derived from /// \p baseInput. /// \return Null on error, ostream for the output file otherwise - std::unique_ptr CreateDefaultOutputFile( + std::unique_ptr createDefaultOutputFile( bool binary = true, llvm::StringRef baseInput = "", llvm::StringRef extension = ""); @@ -221,7 +223,7 @@ /// \param outputPath The path to the output file. /// \param binary The mode to open the file in. /// \return Null on error, ostream for the output file otherwise - llvm::Expected> CreateOutputFileImpl( + llvm::Expected> createOutputFileImpl( llvm::StringRef outputPath, bool binary); public: @@ -244,33 +246,33 @@ /// DiagnosticsEngine object. /// /// \return The new object on success, or null on failure. - static clang::IntrusiveRefCntPtr CreateDiagnostics( + static clang::IntrusiveRefCntPtr createDiagnostics( clang::DiagnosticOptions *opts, clang::DiagnosticConsumer *client = nullptr, bool shouldOwnClient = true); - void CreateDiagnostics( + void createDiagnostics( clang::DiagnosticConsumer *client = nullptr, bool shouldOwnClient = true); /// } /// @name Output Stream Methods /// { - void set_outputStream(std::unique_ptr outStream) { - outputStream_ = std::move(outStream); + void setOutputStream(std::unique_ptr outStream) { + outputStream = std::move(outStream); } - bool IsOutputStreamNull() { return (outputStream_ == nullptr); } + bool isOutputStreamNull() { return (outputStream == nullptr); } // Allow the frontend compiler to write in the output stream. - void WriteOutputStream(const std::string &message) { - *outputStream_ << message; + void writeOutputStream(const std::string &message) { + *outputStream << message; } /// Get the user specified output stream. - llvm::raw_pwrite_stream &GetOutputStream() { - assert(outputStream_ && + llvm::raw_pwrite_stream &getOutputStream() { + assert(outputStream && "Compiler instance has no user-specified output stream!"); - return *outputStream_; + return *outputStream; } }; } // end namespace Fortran::frontend -#endif // LLVM_FLANG_FRONTEND_COMPILERINSTANCE_H +#endif // FORTRAN_FRONTEND_COMPILERINSTANCE_H diff --git a/flang/include/flang/Frontend/CompilerInvocation.h b/flang/include/flang/Frontend/CompilerInvocation.h --- a/flang/include/flang/Frontend/CompilerInvocation.h +++ b/flang/include/flang/Frontend/CompilerInvocation.h @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// -#ifndef LLVM_FLANG_FRONTEND_COMPILERINVOCATION_H -#define LLVM_FLANG_FRONTEND_COMPILERINVOCATION_H +#ifndef FORTRAN_FRONTEND_COMPILERINVOCATION_H +#define FORTRAN_FRONTEND_COMPILERINVOCATION_H #include "flang/Frontend/FrontendOptions.h" #include "flang/Frontend/PreprocessorOptions.h" @@ -24,30 +24,30 @@ /// /// When errors are encountered, return false and, if Diags is non-null, /// report the error(s). -bool ParseDiagnosticArgs(clang::DiagnosticOptions &opts, +bool parseDiagnosticArgs(clang::DiagnosticOptions &opts, llvm::opt::ArgList &args, bool defaultDiagColor = true); class CompilerInvocationBase { public: /// Options controlling the diagnostic engine. - llvm::IntrusiveRefCntPtr diagnosticOpts_; + llvm::IntrusiveRefCntPtr diagnosticOpts; /// Options for the preprocessor. - std::shared_ptr preprocessorOpts_; + std::shared_ptr preprocessorOpts; CompilerInvocationBase(); CompilerInvocationBase(const CompilerInvocationBase &x); ~CompilerInvocationBase(); - clang::DiagnosticOptions &GetDiagnosticOpts() { - return *diagnosticOpts_.get(); + clang::DiagnosticOptions &getDiagnosticOpts() { + return *diagnosticOpts.get(); } - const clang::DiagnosticOptions &GetDiagnosticOpts() const { - return *diagnosticOpts_.get(); + const clang::DiagnosticOptions &getDiagnosticOpts() const { + return *diagnosticOpts.get(); } - PreprocessorOptions &preprocessorOpts() { return *preprocessorOpts_; } - const PreprocessorOptions &preprocessorOpts() const { - return *preprocessorOpts_; + PreprocessorOptions &getPreprocessorOpts() { return *preprocessorOpts; } + const PreprocessorOptions &getPreprocessorOpts() const { + return *preprocessorOpts; } }; @@ -55,43 +55,43 @@ /// Options for the frontend driver // TODO: Merge with or translate to parserOpts_. We shouldn't need two sets of // options. - FrontendOptions frontendOpts_; + FrontendOptions frontendOpts; /// Options for Flang parser - // TODO: Merge with or translate to frontendOpts_. We shouldn't need two sets + // TODO: Merge with or translate to frontendOpts. We shouldn't need two sets // of options. - Fortran::parser::Options parserOpts_; + Fortran::parser::Options parserOpts; /// Options controlling the target. - Fortran::frontend::TargetOptions targetOpts_; + Fortran::frontend::TargetOptions targetOpts; // Semantics context - std::unique_ptr semanticsContext_; + std::unique_ptr semanticsContext; /// Semantic options - // TODO: Merge with or translate to frontendOpts_. We shouldn't need two sets + // TODO: Merge with or translate to frontendOpts. We shouldn't need two sets // of options. - std::string moduleDir_ = "."; + std::string moduleDir = "."; - std::string moduleFileSuffix_ = ".mod"; + std::string moduleFileSuffix = ".mod"; - bool debugModuleDir_ = false; + bool debugModuleDir = false; - bool warnAsErr_ = false; + bool warnAsErr = false; /// This flag controls the unparsing and is used to decide whether to print out /// the semantically analyzed version of an object or expression or the plain /// version that does not include any information from semantic analysis. - bool useAnalyzedObjectsForUnparse_ = true; + bool useAnalyzedObjectsForUnparse = true; // Fortran Dialect options - Fortran::common::IntrinsicTypeDefaultKinds defaultKinds_; + Fortran::common::IntrinsicTypeDefaultKinds defaultKinds; - bool EnableConformanceChecks_ = false; + bool enableConformanceChecks = false; /// Used in e.g. unparsing to dump the analyzed rather than the original /// parse-tree objects. - Fortran::parser::AnalyzedObjectsAsFortran AsFortran_{ + Fortran::parser::AnalyzedObjectsAsFortran asFortran{ [](llvm::raw_ostream &o, const Fortran::evaluate::GenericExprWrapper &x) { if (x.v) { x.v->AsFortran(o); @@ -115,102 +115,106 @@ public: CompilerInvocation() = default; - FrontendOptions &frontendOpts() { return frontendOpts_; } - const FrontendOptions &frontendOpts() const { return frontendOpts_; } + FrontendOptions &getFrontendOpts() { return frontendOpts; } + const FrontendOptions &getFrontendOpts() const { return frontendOpts; } - Fortran::parser::Options &fortranOpts() { return parserOpts_; } - const Fortran::parser::Options &fortranOpts() const { return parserOpts_; } + Fortran::parser::Options &getFortranOpts() { return parserOpts; } + const Fortran::parser::Options &getFortranOpts() const { return parserOpts; } - TargetOptions &targetOpts() { return targetOpts_; } - const TargetOptions &targetOpts() const { return targetOpts_; } + TargetOptions &getTargetOpts() { return targetOpts; } + const TargetOptions &getTargetOpts() const { return targetOpts; } - Fortran::semantics::SemanticsContext &semanticsContext() { - return *semanticsContext_; + Fortran::semantics::SemanticsContext &getSemanticsContext() { + return *semanticsContext; } - const Fortran::semantics::SemanticsContext &semanticsContext() const { - return *semanticsContext_; + const Fortran::semantics::SemanticsContext &getSemanticsContext() const { + return *semanticsContext; } - std::string &moduleDir() { return moduleDir_; } - const std::string &moduleDir() const { return moduleDir_; } + std::string &getModuleDir() { return moduleDir; } + const std::string &getModuleDir() const { return moduleDir; } - std::string &moduleFileSuffix() { return moduleFileSuffix_; } - const std::string &moduleFileSuffix() const { return moduleFileSuffix_; } + std::string &getModuleFileSuffix() { return moduleFileSuffix; } + const std::string &getModuleFileSuffix() const { return moduleFileSuffix; } - bool &debugModuleDir() { return debugModuleDir_; } - const bool &debugModuleDir() const { return debugModuleDir_; } + bool &getDebugModuleDir() { return debugModuleDir; } + const bool &getDebugModuleDir() const { return debugModuleDir; } - bool &warnAsErr() { return warnAsErr_; } - const bool &warnAsErr() const { return warnAsErr_; } + bool &getWarnAsErr() { return warnAsErr; } + const bool &getWarnAsErr() const { return warnAsErr; } - bool &useAnalyzedObjectsForUnparse() { return useAnalyzedObjectsForUnparse_; } - const bool &useAnalyzedObjectsForUnparse() const { - return useAnalyzedObjectsForUnparse_; + bool &getUseAnalyzedObjectsForUnparse() { + return useAnalyzedObjectsForUnparse; + } + const bool &getUseAnalyzedObjectsForUnparse() const { + return useAnalyzedObjectsForUnparse; } - bool &enableConformanceChecks() { return EnableConformanceChecks_; } - const bool &enableConformanceChecks() const { - return EnableConformanceChecks_; + bool &getEnableConformanceChecks() { return enableConformanceChecks; } + const bool &getEnableConformanceChecks() const { + return enableConformanceChecks; } - Fortran::parser::AnalyzedObjectsAsFortran &asFortran() { return AsFortran_; } - const Fortran::parser::AnalyzedObjectsAsFortran &asFortran() const { - return AsFortran_; + Fortran::parser::AnalyzedObjectsAsFortran &getAsFortran() { + return asFortran; + } + const Fortran::parser::AnalyzedObjectsAsFortran &getAsFortran() const { + return asFortran; } - Fortran::common::IntrinsicTypeDefaultKinds &defaultKinds() { - return defaultKinds_; + Fortran::common::IntrinsicTypeDefaultKinds &getDefaultKinds() { + return defaultKinds; } - const Fortran::common::IntrinsicTypeDefaultKinds &defaultKinds() const { - return defaultKinds_; + const Fortran::common::IntrinsicTypeDefaultKinds &getDefaultKinds() const { + return defaultKinds; } /// Create a compiler invocation from a list of input options. /// \returns true on success. /// \returns false if an error was encountered while parsing the arguments /// \param [out] res - The resulting invocation. - static bool CreateFromArgs(CompilerInvocation &res, + static bool createFromArgs(CompilerInvocation &res, llvm::ArrayRef commandLineArgs, clang::DiagnosticsEngine &diags); // Enables the std=f2018 conformance check - void set_EnableConformanceChecks() { EnableConformanceChecks_ = true; } + void setEnableConformanceChecks() { enableConformanceChecks = true; } /// Useful setters - void SetModuleDir(std::string &moduleDir) { moduleDir_ = moduleDir; } + void setModuleDir(std::string &dir) { moduleDir = dir; } - void SetModuleFileSuffix(const char *moduleFileSuffix) { - moduleFileSuffix_ = std::string(moduleFileSuffix); + void setModuleFileSuffix(const char *suffix) { + moduleFileSuffix = std::string(suffix); } - void SetDebugModuleDir(bool flag) { debugModuleDir_ = flag; } + void setDebugModuleDir(bool flag) { debugModuleDir = flag; } - void SetWarnAsErr(bool flag) { warnAsErr_ = flag; } + void setWarnAsErr(bool flag) { warnAsErr = flag; } - void SetUseAnalyzedObjectsForUnparse(bool flag) { - useAnalyzedObjectsForUnparse_ = flag; + void setUseAnalyzedObjectsForUnparse(bool flag) { + useAnalyzedObjectsForUnparse = flag; } /// Set the Fortran options to predefined defaults. // TODO: We should map frontendOpts_ to parserOpts_ instead. For that, we // need to extend frontendOpts_ first. Next, we need to add the corresponding // compiler driver options in libclangDriver. - void SetDefaultFortranOpts(); + void setDefaultFortranOpts(); /// Set the default predefinitions. - void SetDefaultPredefinitions(); + void setDefaultPredefinitions(); /// Collect the macro definitions from preprocessorOpts_ and prepare them for /// the parser (i.e. copy into parserOpts_) - void CollectMacroDefinitions(); + void collectMacroDefinitions(); /// Set the Fortran options to user-specified values. /// These values are found in the preprocessor options. - void SetFortranOpts(); + void setFortranOpts(); /// Set the Semantic Options - void SetSemanticsOpts(Fortran::parser::AllCookedSources &); + void setSemanticsOpts(Fortran::parser::AllCookedSources &); }; } // end namespace Fortran::frontend -#endif // LLVM_FLANG_FRONTEND_COMPILERINVOCATION_H +#endif // FORTRAN_FRONTEND_COMPILERINVOCATION_H diff --git a/flang/include/flang/Frontend/FrontendAction.h b/flang/include/flang/Frontend/FrontendAction.h --- a/flang/include/flang/Frontend/FrontendAction.h +++ b/flang/include/flang/Frontend/FrontendAction.h @@ -11,8 +11,8 @@ /// //===----------------------------------------------------------------------===// -#ifndef LLVM_FLANG_FRONTEND_FRONTENDACTION_H -#define LLVM_FLANG_FRONTEND_FRONTENDACTION_H +#ifndef FORTRAN_FRONTEND_FRONTENDACTION_H +#define FORTRAN_FRONTEND_FRONTENDACTION_H #include "flang/Frontend/FrontendOptions.h" #include "llvm/Support/Error.h" @@ -22,8 +22,8 @@ /// Abstract base class for actions which can be performed by the frontend. class FrontendAction { - FrontendInputFile currentInput_; - CompilerInstance *instance_; + FrontendInputFile currentInput; + CompilerInstance *instance; protected: /// @name Implementation Action Interface @@ -31,54 +31,54 @@ /// Callback to run the program action, using the initialized /// compiler instance. - virtual void ExecuteAction() = 0; + virtual void executeAction() = 0; /// Callback at the end of processing a single input, to determine /// if the output files should be erased or not. /// /// By default it returns true if a compiler error occurred. - virtual bool ShouldEraseOutputFiles(); + virtual bool shouldEraseOutputFiles(); /// Callback at the start of processing a single input. /// /// \return True on success; on failure ExecutionAction() and /// EndSourceFileAction() will not be called. - virtual bool BeginSourceFileAction() { return true; } + virtual bool beginSourceFileAction() { return true; } /// @} public: - FrontendAction() : instance_(nullptr) {} + FrontendAction() : instance(nullptr) {} virtual ~FrontendAction() = default; /// @name Compiler Instance Access /// @{ - CompilerInstance &instance() const { - assert(instance_ && "Compiler instance not registered!"); - return *instance_; + CompilerInstance &getInstance() const { + assert(instance && "Compiler instance not registered!"); + return *instance; } - void set_instance(CompilerInstance *value) { instance_ = value; } + void setInstance(CompilerInstance *value) { instance = value; } /// @} /// @name Current File Information /// @{ - const FrontendInputFile ¤tInput() const { return currentInput_; } + const FrontendInputFile &getCurrentInput() const { return currentInput; } - llvm::StringRef GetCurrentFile() const { - assert(!currentInput_.IsEmpty() && "No current file!"); - return currentInput_.file(); + llvm::StringRef getCurrentFile() const { + assert(!currentInput.isEmpty() && "No current file!"); + return currentInput.getFile(); } - llvm::StringRef GetCurrentFileOrBufferName() const { - assert(!currentInput_.IsEmpty() && "No current file!"); - return currentInput_.IsFile() - ? currentInput_.file() - : currentInput_.buffer()->getBufferIdentifier(); + llvm::StringRef getCurrentFileOrBufferName() const { + assert(!currentInput.isEmpty() && "No current file!"); + return currentInput.isFile() + ? currentInput.getFile() + : currentInput.getBuffer()->getBufferIdentifier(); } - void set_currentInput(const FrontendInputFile ¤tInput); + void setCurrentInput(const FrontendInputFile ¤tIntput); /// @} /// @name Public Action Interface @@ -92,30 +92,30 @@ /// action may store and use this object. /// \param input - The input filename and kind. /// \return True on success; on failure the compilation of this file should - bool BeginSourceFile(CompilerInstance &ci, const FrontendInputFile &input); + bool beginSourceFile(CompilerInstance &ci, const FrontendInputFile &input); /// Run the action. - llvm::Error Execute(); + llvm::Error execute(); /// Perform any per-file post processing, deallocate per-file /// objects, and run statistics and output file cleanup code. - void EndSourceFile(); + void endSourceFile(); /// @} protected: // Prescan the current input file. Return False if fatal errors are reported, // True otherwise. - bool RunPrescan(); + bool runPrescan(); // Parse the current input file. Return False if fatal errors are reported, // True otherwise. - bool RunParse(); + bool runParse(); // Run semantic checks for the current input file. Return False if fatal // errors are reported, True otherwise. - bool RunSemanticChecks(); + bool runSemanticChecks(); // Generate run-time type information for derived types. This may lead to new // semantic errors. Return False if fatal errors are reported, True // otherwise. - bool GenerateRtTypeTables(); + bool generateRtTypeTables(); // Report fatal semantic errors. Return True if present, false otherwise. bool reportFatalSemanticErrors(); @@ -136,4 +136,4 @@ } // namespace Fortran::frontend -#endif // LLVM_FLANG_FRONTEND_FRONTENDACTION_H +#endif // FORTRAN_FRONTEND_FRONTENDACTION_H diff --git a/flang/include/flang/Frontend/FrontendActions.h b/flang/include/flang/Frontend/FrontendActions.h --- a/flang/include/flang/Frontend/FrontendActions.h +++ b/flang/include/flang/Frontend/FrontendActions.h @@ -6,8 +6,8 @@ // //===----------------------------------------------------------------------===// -#ifndef LLVM_FLANG_FRONTEND_FRONTENDACTIONS_H -#define LLVM_FLANG_FRONTEND_FRONTENDACTIONS_H +#ifndef FORTRAN_FRONTEND_FRONTENDACTIONS_H +#define FORTRAN_FRONTEND_FRONTENDACTIONS_H #include "flang/Frontend/FrontendAction.h" #include "flang/Parser/parsing.h" @@ -37,51 +37,51 @@ //===----------------------------------------------------------------------===// class InputOutputTestAction : public FrontendAction { - void ExecuteAction() override; + void executeAction() override; }; class InitOnlyAction : public FrontendAction { - void ExecuteAction() override; + void executeAction() override; }; //===----------------------------------------------------------------------===// // Prescan Actions //===----------------------------------------------------------------------===// class PrescanAction : public FrontendAction { - void ExecuteAction() override = 0; - bool BeginSourceFileAction() override; + void executeAction() override = 0; + bool beginSourceFileAction() override; }; class PrintPreprocessedAction : public PrescanAction { - void ExecuteAction() override; + void executeAction() override; }; class DebugDumpProvenanceAction : public PrescanAction { - void ExecuteAction() override; + void executeAction() override; }; class DebugDumpParsingLogAction : public PrescanAction { - void ExecuteAction() override; + void executeAction() override; }; class DebugMeasureParseTreeAction : public PrescanAction { - void ExecuteAction() override; + void executeAction() override; }; //===----------------------------------------------------------------------===// // PrescanAndParse Actions //===----------------------------------------------------------------------===// class PrescanAndParseAction : public FrontendAction { - void ExecuteAction() override = 0; - bool BeginSourceFileAction() override; + void executeAction() override = 0; + bool beginSourceFileAction() override; }; class DebugUnparseNoSemaAction : public PrescanAndParseAction { - void ExecuteAction() override; + void executeAction() override; }; class DebugDumpParseTreeNoSemaAction : public PrescanAndParseAction { - void ExecuteAction() override; + void executeAction() override; }; //===----------------------------------------------------------------------===// @@ -92,48 +92,48 @@ //===----------------------------------------------------------------------===// class PrescanAndSemaAction : public FrontendAction { - void ExecuteAction() override = 0; - bool BeginSourceFileAction() override; + void executeAction() override = 0; + bool beginSourceFileAction() override; }; class DebugUnparseWithSymbolsAction : public PrescanAndSemaAction { - void ExecuteAction() override; + void executeAction() override; }; class DebugUnparseAction : public PrescanAndSemaAction { - void ExecuteAction() override; + void executeAction() override; }; class DebugDumpSymbolsAction : public PrescanAndSemaAction { - void ExecuteAction() override; + void executeAction() override; }; class DebugDumpParseTreeAction : public PrescanAndSemaAction { - void ExecuteAction() override; + void executeAction() override; }; class DebugDumpPFTAction : public PrescanAndSemaAction { - void ExecuteAction() override; + void executeAction() override; }; class DebugPreFIRTreeAction : public PrescanAndSemaAction { - void ExecuteAction() override; + void executeAction() override; }; class GetDefinitionAction : public PrescanAndSemaAction { - void ExecuteAction() override; + void executeAction() override; }; class GetSymbolsSourcesAction : public PrescanAndSemaAction { - void ExecuteAction() override; + void executeAction() override; }; class ParseSyntaxOnlyAction : public PrescanAndSemaAction { - void ExecuteAction() override; + void executeAction() override; }; class PluginParseTreeAction : public PrescanAndSemaAction { - void ExecuteAction() override = 0; + void executeAction() override = 0; public: Fortran::parser::Parsing &getParsing(); @@ -160,12 +160,12 @@ //===----------------------------------------------------------------------===// class PrescanAndSemaDebugAction : public FrontendAction { - void ExecuteAction() override = 0; - bool BeginSourceFileAction() override; + void executeAction() override = 0; + bool beginSourceFileAction() override; }; class DebugDumpAllAction : public PrescanAndSemaDebugAction { - void ExecuteAction() override; + void executeAction() override; }; //===----------------------------------------------------------------------===// @@ -191,10 +191,10 @@ /// tree to an MLIR module. class CodeGenAction : public FrontendAction { - void ExecuteAction() override; + void executeAction() override; /// Runs prescan, parsing, sema and lowers to MLIR. - bool BeginSourceFileAction() override; - void SetUpTargetMachine(); + bool beginSourceFileAction() override; + void setUpTargetMachine(); protected: CodeGenAction(BackendActionTy act) : action{act} {}; @@ -210,11 +210,11 @@ /// Generates an LLVM IR module from CodeGenAction::mlirModule and saves it /// in CodeGenAction::llvmModule. - void GenerateLLVMIR(); + void generateLLVMIR(); BackendActionTy action; - std::unique_ptr TM; + std::unique_ptr tm; /// } public: ~CodeGenAction() override; @@ -247,4 +247,4 @@ } // namespace Fortran::frontend -#endif // LLVM_FLANG_FRONTEND_FRONTENDACTIONS_H +#endif // FORTRAN_FRONTEND_FRONTENDACTIONS_H diff --git a/flang/include/flang/Frontend/FrontendOptions.h b/flang/include/flang/Frontend/FrontendOptions.h --- a/flang/include/flang/Frontend/FrontendOptions.h +++ b/flang/include/flang/Frontend/FrontendOptions.h @@ -5,15 +5,14 @@ // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// -#ifndef LLVM_FLANG_FRONTEND_FRONTENDOPTIONS_H -#define LLVM_FLANG_FRONTEND_FRONTENDOPTIONS_H +#ifndef FORTRAN_FRONTEND_FRONTENDOPTIONS_H +#define FORTRAN_FRONTEND_FRONTENDOPTIONS_H #include "flang/Common/Fortran-features.h" #include "flang/Parser/characters.h" #include "flang/Parser/unparse.h" #include "llvm/ADT/StringRef.h" #include "llvm/Support/MemoryBuffer.h" - #include #include @@ -106,7 +105,7 @@ /// \param suffix The file extension /// \return True if the file should be preprocessed -bool mustBePreprocessed(llvm::StringRef suffix); +bool isToBePreprocessed(llvm::StringRef suffix); enum class Language : uint8_t { Unknown, @@ -134,76 +133,75 @@ /// The kind of a file that we've been handed as an input. class InputKind { private: - Language lang_; + Language lang; public: /// The input file format. enum Format { Source, ModuleMap, Precompiled }; - constexpr InputKind(Language l = Language::Unknown) : lang_(l) {} + constexpr InputKind(Language l = Language::Unknown) : lang(l) {} - Language GetLanguage() const { return static_cast(lang_); } + Language getLanguage() const { return static_cast(lang); } /// Is the input kind fully-unknown? - bool IsUnknown() const { return lang_ == Language::Unknown; } + bool isUnknown() const { return lang == Language::Unknown; } }; /// An input file for the front end. class FrontendInputFile { /// The file name, or "-" to read from standard input. - std::string file_; + std::string file; /// The input, if it comes from a buffer rather than a file. This object /// does not own the buffer, and the caller is responsible for ensuring /// that it outlives any users. - const llvm::MemoryBuffer *buffer_ = nullptr; + const llvm::MemoryBuffer *buffer = nullptr; /// The kind of input, atm it contains language - InputKind kind_; + InputKind kind; /// Is this input file in fixed-form format? This is simply derived from the /// file extension and should not be altered by consumers. For input from /// stdin this is never modified. - bool isFixedForm_ = false; + bool isFixedForm = false; /// Must this file be preprocessed? Note that in Flang the preprocessor is /// always run. This flag is used to control whether predefined and command /// line preprocessor macros are enabled or not. In practice, this is /// sufficient to implement gfortran`s logic controlled with `-cpp/-nocpp`. - unsigned mustBePreprocessed_ : 1; + unsigned mustBePreprocessed : 1; public: FrontendInputFile() = default; - FrontendInputFile(llvm::StringRef file, InputKind kind) - : file_(file.str()), kind_(kind) { + FrontendInputFile(llvm::StringRef file, InputKind inKind) + : file(file.str()), kind(inKind) { // Based on the extension, decide whether this is a fixed or free form // file. auto pathDotIndex{file.rfind(".")}; std::string pathSuffix{file.substr(pathDotIndex + 1)}; - isFixedForm_ = isFixedFormSuffix(pathSuffix); - mustBePreprocessed_ = mustBePreprocessed(pathSuffix); + isFixedForm = isFixedFormSuffix(pathSuffix); + mustBePreprocessed = isToBePreprocessed(pathSuffix); } - FrontendInputFile(const llvm::MemoryBuffer *buffer, InputKind kind) - : buffer_(buffer), kind_(kind) {} + FrontendInputFile(const llvm::MemoryBuffer *memBuf, InputKind inKind) + : buffer(memBuf), kind(inKind) {} - InputKind kind() const { return kind_; } + InputKind getKind() const { return kind; } - bool IsEmpty() const { return file_.empty() && buffer_ == nullptr; } - bool IsFile() const { return !IsBuffer(); } - bool IsBuffer() const { return buffer_ != nullptr; } - bool IsFixedForm() const { return isFixedForm_; } - bool MustBePreprocessed() const { return mustBePreprocessed_; } + bool isEmpty() const { return file.empty() && buffer == nullptr; } + bool isFile() const { return (buffer == nullptr); } + bool getIsFixedForm() const { return isFixedForm; } + bool getMustBePreprocessed() const { return mustBePreprocessed; } - llvm::StringRef file() const { - assert(IsFile()); - return file_; + llvm::StringRef getFile() const { + assert(isFile()); + return file; } - const llvm::MemoryBuffer *buffer() const { - assert(IsBuffer() && "Requested buffer_, but it is empty!"); - return buffer_; + const llvm::MemoryBuffer *getBuffer() const { + assert(buffer && "Requested buffer, but it is empty!"); + return buffer; } }; @@ -265,7 +263,7 @@ std::vector plugins; /// The name of the action to run when using a plugin action. - std::string ActionName; + std::string actionName; /// A list of arguments to forward to LLVM's option processing; this /// should only be used for debugging and experimental features. @@ -280,8 +278,8 @@ /// /// \return The input kind for the extension, or Language::Unknown if the /// extension is not recognized. - static InputKind GetInputKindForExtension(llvm::StringRef extension); + static InputKind getInputKindForExtension(llvm::StringRef extension); }; } // namespace Fortran::frontend -#endif // LLVM_FLANG_FRONTEND_FRONTENDOPTIONS_H +#endif // FORTRAN_FRONTEND_FRONTENDOPTIONS_H diff --git a/flang/include/flang/Frontend/FrontendPluginRegistry.h b/flang/include/flang/Frontend/FrontendPluginRegistry.h --- a/flang/include/flang/Frontend/FrontendPluginRegistry.h +++ b/flang/include/flang/Frontend/FrontendPluginRegistry.h @@ -10,8 +10,8 @@ // //===----------------------------------------------------------------------===// -#ifndef FLANG_FRONTEND_FRONTENDPLUGINREGISTRY_H -#define FLANG_FRONTEND_FRONTENDPLUGINREGISTRY_H +#ifndef FORTRAN_FRONTEND_FRONTENDPLUGINREGISTRY_H +#define FORTRAN_FRONTEND_FRONTENDPLUGINREGISTRY_H #include "flang/Frontend/FrontendActions.h" #include "llvm/Support/Registry.h" @@ -23,4 +23,4 @@ } // namespace Fortran::frontend -#endif // FLANG_FRONTEND_FRONTENDPLUGINREGISTRY_H +#endif // FORTRAN_FRONTEND_FRONTENDPLUGINREGISTRY_H diff --git a/flang/include/flang/Frontend/PreprocessorOptions.h b/flang/include/flang/Frontend/PreprocessorOptions.h --- a/flang/include/flang/Frontend/PreprocessorOptions.h +++ b/flang/include/flang/Frontend/PreprocessorOptions.h @@ -12,8 +12,8 @@ /// //===----------------------------------------------------------------------===// -#ifndef LLVM_FLANG_PREPROCESSOROPTIONS_H -#define LLVM_FLANG_PREPROCESSOROPTIONS_H +#ifndef FORTRAN_FRONTEND_PREPROCESSOROPTIONS_H +#define FORTRAN_FRONTEND_PREPROCESSOROPTIONS_H #include "llvm/ADT/StringRef.h" @@ -63,4 +63,4 @@ } // namespace Fortran::frontend -#endif // LLVM_FLANG_PREPROCESSOROPTIONS_H +#endif // FORTRAN_FRONTEND_PREPROCESSOROPTIONS_H diff --git a/flang/include/flang/Frontend/TargetOptions.h b/flang/include/flang/Frontend/TargetOptions.h --- a/flang/include/flang/Frontend/TargetOptions.h +++ b/flang/include/flang/Frontend/TargetOptions.h @@ -11,8 +11,8 @@ /// //===----------------------------------------------------------------------===// -#ifndef LLVM_FLANG_TARGETOPTIONS_H -#define LLVM_FLANG_TARGETOPTIONS_H +#ifndef FORTRAN_FRONTEND_TARGETOPTIONS_H +#define FORTRAN_FRONTEND_TARGETOPTIONS_H namespace Fortran::frontend { diff --git a/flang/include/flang/Frontend/TextDiagnostic.h b/flang/include/flang/Frontend/TextDiagnostic.h --- a/flang/include/flang/Frontend/TextDiagnostic.h +++ b/flang/include/flang/Frontend/TextDiagnostic.h @@ -12,8 +12,8 @@ // TODO: If expanding, consider sharing the implementation with Clang. //===----------------------------------------------------------------------===// -#ifndef LLVM_FLANG_FRONTEND_TEXTDIAGNOSTIC_H -#define LLVM_FLANG_FRONTEND_TEXTDIAGNOSTIC_H +#ifndef FORTRAN_FRONTEND_TEXTDIAGNOSTIC_H +#define FORTRAN_FRONTEND_TEXTDIAGNOSTIC_H #include "clang/Basic/Diagnostic.h" #include "llvm/ADT/IntrusiveRefCntPtr.h" @@ -46,7 +46,7 @@ /// \param os Where the message is printed /// \param level The diagnostic level (e.g. error or warning) /// \param showColors Enable colorizing of the message. - static void PrintDiagnosticLevel(llvm::raw_ostream &os, + static void printDiagnosticLevel(llvm::raw_ostream &os, clang::DiagnosticsEngine::Level level, bool showColors); /// Pretty-print a diagnostic message to a llvm::raw_ostream. @@ -61,7 +61,7 @@ /// \param isSupplemental true if this is a continuation note diagnostic /// \param message The text actually printed /// \param showColors Enable colorizing of the message. - static void PrintDiagnosticMessage(llvm::raw_ostream &os, bool isSupplemental, + static void printDiagnosticMessage(llvm::raw_ostream &os, bool isSupplemental, llvm::StringRef message, bool showColors); }; diff --git a/flang/include/flang/Frontend/TextDiagnosticBuffer.h b/flang/include/flang/Frontend/TextDiagnosticBuffer.h --- a/flang/include/flang/Frontend/TextDiagnosticBuffer.h +++ b/flang/include/flang/Frontend/TextDiagnosticBuffer.h @@ -12,8 +12,8 @@ // //===----------------------------------------------------------------------===// -#ifndef LLVM_FLANG_FRONTEND_TEXTDIAGNOSTICBUFFER_H -#define LLVM_FLANG_FRONTEND_TEXTDIAGNOSTICBUFFER_H +#ifndef FORTRAN_FRONTEND_TEXTDIAGNOSTICBUFFER_H +#define FORTRAN_FRONTEND_TEXTDIAGNOSTICBUFFER_H #include "clang/Basic/Diagnostic.h" #include "clang/Basic/SourceLocation.h" @@ -31,22 +31,22 @@ std::vector>; private: - DiagList errors_, warnings_, remarks_, notes_; + DiagList errors, warnings, remarks, notes; /// All diagnostics in the order in which they were generated. That order /// likely doesn't correspond to user input order, but at least it keeps /// notes in the right places. Each pair is a diagnostic level and an index /// into the corresponding DiagList above. - DiagnosticsLevelAndIndexPairs all_; + DiagnosticsLevelAndIndexPairs all; public: void HandleDiagnostic(clang::DiagnosticsEngine::Level diagLevel, const clang::Diagnostic &info) override; /// Flush the buffered diagnostics to a given diagnostic engine. - void FlushDiagnostics(clang::DiagnosticsEngine &diags) const; + void flushDiagnostics(clang::DiagnosticsEngine &diags) const; }; } // namespace Fortran::frontend -#endif // LLVM_CLANG_FRONTEND_TEXTDIAGNOSTICBUFFER_H +#endif // FORTRAN_FRONTEND_TEXTDIAGNOSTICBUFFER_H diff --git a/flang/include/flang/Frontend/TextDiagnosticPrinter.h b/flang/include/flang/Frontend/TextDiagnosticPrinter.h --- a/flang/include/flang/Frontend/TextDiagnosticPrinter.h +++ b/flang/include/flang/Frontend/TextDiagnosticPrinter.h @@ -13,8 +13,8 @@ // //===----------------------------------------------------------------------===// -#ifndef LLVM_FLANG_FRONTEND_TEXTDIAGNOSTICPRINTER_H -#define LLVM_FLANG_FRONTEND_TEXTDIAGNOSTICPRINTER_H +#ifndef FORTRAN_FRONTEND_TEXTDIAGNOSTICPRINTER_H +#define FORTRAN_FRONTEND_TEXTDIAGNOSTICPRINTER_H #include "clang/Basic/Diagnostic.h" #include "llvm/ADT/IntrusiveRefCntPtr.h" @@ -32,11 +32,11 @@ class TextDiagnostic; class TextDiagnosticPrinter : public clang::DiagnosticConsumer { - raw_ostream &os_; - llvm::IntrusiveRefCntPtr diagOpts_; + raw_ostream &os; + llvm::IntrusiveRefCntPtr diagOpts; /// A string to prefix to error messages. - std::string prefix_; + std::string prefix; public: TextDiagnosticPrinter(raw_ostream &os, clang::DiagnosticOptions *diags); @@ -44,7 +44,7 @@ /// Set the diagnostic printer prefix string, which will be printed at the /// start of any diagnostics. If empty, no prefix string is used. - void set_prefix(std::string value) { prefix_ = std::move(value); } + void setPrefix(std::string value) { prefix = std::move(value); } void HandleDiagnostic(clang::DiagnosticsEngine::Level level, const clang::Diagnostic &info) override; diff --git a/flang/include/flang/FrontendTool/.clang-tidy b/flang/include/flang/FrontendTool/.clang-tidy new file mode 100644 --- /dev/null +++ b/flang/include/flang/FrontendTool/.clang-tidy @@ -0,0 +1,9 @@ +Checks: '-readability-braces-around-statements,readability-identifier-naming,llvm-include-order,clang-diagnostic-*' +InheritParentConfig: true +CheckOptions: + - key: readability-identifier-naming.MemberCase + value: camelBack + - key: readability-identifier-naming.ParameterCase + value: camelBack + - key: readability-identifier-naming.VariableCase + value: camelBack diff --git a/flang/include/flang/FrontendTool/Utils.h b/flang/include/flang/FrontendTool/Utils.h --- a/flang/include/flang/FrontendTool/Utils.h +++ b/flang/include/flang/FrontendTool/Utils.h @@ -11,8 +11,8 @@ // //===----------------------------------------------------------------------===// -#ifndef LLVM_FLANG_FRONTENDTOOL_UTILS_H -#define LLVM_FLANG_FRONTENDTOOL_UTILS_H +#ifndef FORTRAN_FRONTEND_FRONTENDTOOL_UTILS_H +#define FORTRAN_FRONTEND_FRONTENDTOOL_UTILS_H namespace Fortran::frontend { @@ -22,8 +22,8 @@ /// compiler invocation object in the given compiler instance. /// /// \return - True on success. -bool ExecuteCompilerInvocation(CompilerInstance *flang); +bool executeCompilerInvocation(CompilerInstance *flang); } // end namespace Fortran::frontend -#endif // LLVM_FLANG_FRONTENDTOOL_UTILS_H +#endif // FORTRAN_FRONTEND_FRONTENDTOOL_UTILS_H diff --git a/flang/lib/Frontend/.clang-tidy b/flang/lib/Frontend/.clang-tidy new file mode 100644 --- /dev/null +++ b/flang/lib/Frontend/.clang-tidy @@ -0,0 +1,9 @@ +Checks: '-readability-braces-around-statements,readability-identifier-naming,llvm-include-order,clang-diagnostic-*' +InheritParentConfig: true +CheckOptions: + - key: readability-identifier-naming.MemberCase + value: camelBack + - key: readability-identifier-naming.ParameterCase + value: camelBack + - key: readability-identifier-naming.VariableCase + value: camelBack diff --git a/flang/lib/Frontend/CompilerInstance.cpp b/flang/lib/Frontend/CompilerInstance.cpp --- a/flang/lib/Frontend/CompilerInstance.cpp +++ b/flang/lib/Frontend/CompilerInstance.cpp @@ -22,33 +22,32 @@ using namespace Fortran::frontend; CompilerInstance::CompilerInstance() - : invocation_(new CompilerInvocation()), - allSources_(new Fortran::parser::AllSources()), - allCookedSources_(new Fortran::parser::AllCookedSources(*allSources_)), - parsing_(new Fortran::parser::Parsing(*allCookedSources_)) { + : invocation(new CompilerInvocation()), + allSources(new Fortran::parser::AllSources()), + allCookedSources(new Fortran::parser::AllCookedSources(*allSources)), + parsing(new Fortran::parser::Parsing(*allCookedSources)) { // TODO: This is a good default during development, but ultimately we should // give the user the opportunity to specify this. - allSources_->set_encoding(Fortran::parser::Encoding::UTF_8); + allSources->set_encoding(Fortran::parser::Encoding::UTF_8); } CompilerInstance::~CompilerInstance() { - assert(outputFiles_.empty() && "Still output files in flight?"); + assert(outputFiles.empty() && "Still output files in flight?"); } -void CompilerInstance::set_invocation( +void CompilerInstance::setInvocation( std::shared_ptr value) { - invocation_ = std::move(value); + invocation = std::move(value); } -void CompilerInstance::set_semaOutputStream(raw_ostream &Value) { - ownedSemaOutputStream_.release(); - semaOutputStream_ = &Value; +void CompilerInstance::setSemaOutputStream(raw_ostream &value) { + ownedSemaOutputStream.release(); + semaOutputStream = &value; } -void CompilerInstance::set_semaOutputStream( - std::unique_ptr Value) { - ownedSemaOutputStream_.swap(Value); - semaOutputStream_ = ownedSemaOutputStream_.get(); +void CompilerInstance::setSemaOutputStream(std::unique_ptr value) { + ownedSemaOutputStream.swap(value); + semaOutputStream = ownedSemaOutputStream.get(); } // Helper method to generate the path of the output file. The following logic @@ -59,8 +58,9 @@ // the input file (i.e. inputFilename + extension) // 3. If the output file is not specified and the input file is `-`, then set // the output file to `-` as well. -static std::string GetOutputFilePath(llvm::StringRef outputFilename, - llvm::StringRef inputFilename, llvm::StringRef extension) { +static std::string getOutputFilePath(llvm::StringRef outputFilename, + llvm::StringRef inputFilename, + llvm::StringRef extension) { // Output filename _is_ specified. Just use that. if (!outputFilename.empty()) @@ -78,35 +78,35 @@ } std::unique_ptr -CompilerInstance::CreateDefaultOutputFile( - bool binary, llvm::StringRef baseName, llvm::StringRef extension) { +CompilerInstance::createDefaultOutputFile(bool binary, llvm::StringRef baseName, + llvm::StringRef extension) { // Get the path of the output file std::string outputFilePath = - GetOutputFilePath(frontendOpts().outputFile, baseName, extension); + getOutputFilePath(getFrontendOpts().outputFile, baseName, extension); // Create the output file llvm::Expected> os = - CreateOutputFileImpl(outputFilePath, binary); + createOutputFileImpl(outputFilePath, binary); // If successful, add the file to the list of tracked output files and // return. if (os) { - outputFiles_.emplace_back(OutputFile(outputFilePath)); + outputFiles.emplace_back(OutputFile(outputFilePath)); return std::move(*os); } // If unsuccessful, issue an error and return Null - unsigned DiagID = diagnostics().getCustomDiagID( + unsigned diagID = getDiagnostics().getCustomDiagID( clang::DiagnosticsEngine::Error, "unable to open output file '%0': '%1'"); - diagnostics().Report(DiagID) + getDiagnostics().Report(diagID) << outputFilePath << llvm::errorToErrorCode(os.takeError()).message(); return nullptr; } llvm::Expected> -CompilerInstance::CreateOutputFileImpl( - llvm::StringRef outputFilePath, bool binary) { +CompilerInstance::createOutputFileImpl(llvm::StringRef outputFilePath, + bool binary) { // Creates the file descriptor for the output file std::unique_ptr os; @@ -128,47 +128,48 @@ return std::make_unique(std::move(os)); } -void CompilerInstance::ClearOutputFiles(bool eraseFiles) { - for (OutputFile &of : outputFiles_) - if (!of.filename_.empty() && eraseFiles) - llvm::sys::fs::remove(of.filename_); +void CompilerInstance::clearOutputFiles(bool eraseFiles) { + for (OutputFile &of : outputFiles) + if (!of.filename.empty() && eraseFiles) + llvm::sys::fs::remove(of.filename); - outputFiles_.clear(); + outputFiles.clear(); } -bool CompilerInstance::ExecuteAction(FrontendAction &act) { - auto &invoc = this->invocation(); +bool CompilerInstance::executeAction(FrontendAction &act) { + auto &invoc = this->getInvocation(); // Set some sane defaults for the frontend. - invoc.SetDefaultFortranOpts(); + invoc.setDefaultFortranOpts(); // Update the fortran options based on user-based input. - invoc.SetFortranOpts(); + invoc.setFortranOpts(); // Set the encoding to read all input files in based on user input. - allSources_->set_encoding(invoc.fortranOpts().encoding); + allSources->set_encoding(invoc.getFortranOpts().encoding); // Create the semantics context and set semantic options. - invoc.SetSemanticsOpts(*this->allCookedSources_); + invoc.setSemanticsOpts(*this->allCookedSources); // Run the frontend action `act` for every input file. - for (const FrontendInputFile &fif : frontendOpts().inputs) { - if (act.BeginSourceFile(*this, fif)) { - if (llvm::Error err = act.Execute()) { + for (const FrontendInputFile &fif : getFrontendOpts().inputs) { + if (act.beginSourceFile(*this, fif)) { + if (llvm::Error err = act.execute()) { consumeError(std::move(err)); } - act.EndSourceFile(); + act.endSourceFile(); } } - return !diagnostics().getClient()->getNumErrors(); + return !getDiagnostics().getClient()->getNumErrors(); } -void CompilerInstance::CreateDiagnostics( - clang::DiagnosticConsumer *client, bool shouldOwnClient) { - diagnostics_ = - CreateDiagnostics(&GetDiagnosticOpts(), client, shouldOwnClient); +void CompilerInstance::createDiagnostics(clang::DiagnosticConsumer *client, + bool shouldOwnClient) { + diagnostics = + createDiagnostics(&getDiagnosticOpts(), client, shouldOwnClient); } clang::IntrusiveRefCntPtr -CompilerInstance::CreateDiagnostics(clang::DiagnosticOptions *opts, - clang::DiagnosticConsumer *client, bool shouldOwnClient) { +CompilerInstance::createDiagnostics(clang::DiagnosticOptions *opts, + clang::DiagnosticConsumer *client, + bool shouldOwnClient) { clang::IntrusiveRefCntPtr diagID( new clang::DiagnosticIDs()); clang::IntrusiveRefCntPtr diags( diff --git a/flang/lib/Frontend/CompilerInvocation.cpp b/flang/lib/Frontend/CompilerInvocation.cpp --- a/flang/lib/Frontend/CompilerInvocation.cpp +++ b/flang/lib/Frontend/CompilerInvocation.cpp @@ -37,12 +37,12 @@ // Initialization. //===----------------------------------------------------------------------===// CompilerInvocationBase::CompilerInvocationBase() - : diagnosticOpts_(new clang::DiagnosticOptions()), - preprocessorOpts_(new PreprocessorOptions()) {} + : diagnosticOpts(new clang::DiagnosticOptions()), + preprocessorOpts(new PreprocessorOptions()) {} CompilerInvocationBase::CompilerInvocationBase(const CompilerInvocationBase &x) - : diagnosticOpts_(new clang::DiagnosticOptions(x.GetDiagnosticOpts())), - preprocessorOpts_(new PreprocessorOptions(x.preprocessorOpts())) {} + : diagnosticOpts(new clang::DiagnosticOptions(x.getDiagnosticOpts())), + preprocessorOpts(new PreprocessorOptions(x.getPreprocessorOpts())) {} CompilerInvocationBase::~CompilerInvocationBase() = default; @@ -59,31 +59,33 @@ Colors_On, Colors_Off, Colors_Auto - } ShowColors = defaultColor ? Colors_Auto : Colors_Off; + } showColors = defaultColor ? Colors_Auto : Colors_Off; for (auto *a : args) { - const llvm::opt::Option &O = a->getOption(); - if (O.matches(clang::driver::options::OPT_fcolor_diagnostics)) { - ShowColors = Colors_On; - } else if (O.matches(clang::driver::options::OPT_fno_color_diagnostics)) { - ShowColors = Colors_Off; - } else if (O.matches(clang::driver::options::OPT_fdiagnostics_color_EQ)) { + const llvm::opt::Option &opt = a->getOption(); + if (opt.matches(clang::driver::options::OPT_fcolor_diagnostics)) { + showColors = Colors_On; + } else if (opt.matches(clang::driver::options::OPT_fno_color_diagnostics)) { + showColors = Colors_Off; + } else if (opt.matches(clang::driver::options::OPT_fdiagnostics_color_EQ)) { llvm::StringRef value(a->getValue()); if (value == "always") - ShowColors = Colors_On; + showColors = Colors_On; else if (value == "never") - ShowColors = Colors_Off; + showColors = Colors_Off; else if (value == "auto") - ShowColors = Colors_Auto; + showColors = Colors_Auto; } } - return ShowColors == Colors_On || - (ShowColors == Colors_Auto && llvm::sys::Process::StandardErrHasColors()); + return showColors == Colors_On || + (showColors == Colors_Auto && + llvm::sys::Process::StandardErrHasColors()); } -bool Fortran::frontend::ParseDiagnosticArgs(clang::DiagnosticOptions &opts, - llvm::opt::ArgList &args, bool defaultDiagColor) { +bool Fortran::frontend::parseDiagnosticArgs(clang::DiagnosticOptions &opts, + llvm::opt::ArgList &args, + bool defaultDiagColor) { opts.ShowColors = parseShowColorsArgs(args, defaultDiagColor); return true; @@ -94,7 +96,7 @@ /// /// \param [in] opts The target options instance to update /// \param [in] args The list of input arguments (from the compiler invocation) -static void ParseTargetArgs(TargetOptions &opts, llvm::opt::ArgList &args) { +static void parseTargetArgs(TargetOptions &opts, llvm::opt::ArgList &args) { if (const llvm::opt::Arg *a = args.getLastArg(clang::driver::options::OPT_triple)) opts.triple = a->getValue(); @@ -110,8 +112,8 @@ opts.needProvenanceRangeToCharBlockMappings = true; } -static bool ParseFrontendArgs(FrontendOptions &opts, llvm::opt::ArgList &args, - clang::DiagnosticsEngine &diags) { +static bool parseFrontendArgs(FrontendOptions &opts, llvm::opt::ArgList &args, + clang::DiagnosticsEngine &diags) { unsigned numErrorsBefore = diags.getNumErrors(); // By default the frontend driver creates a ParseSyntaxOnly action. @@ -243,7 +245,7 @@ if (const llvm::opt::Arg *a = args.getLastArg(clang::driver::options::OPT_plugin)) { opts.programAction = PluginAction; - opts.ActionName = a->getValue(); + opts.actionName = a->getValue(); } opts.outputFile = args.getLastArgValue(clang::driver::options::OPT_o); @@ -254,19 +256,19 @@ InputKind dashX(Language::Unknown); if (const llvm::opt::Arg *a = args.getLastArg(clang::driver::options::OPT_x)) { - llvm::StringRef XValue = a->getValue(); + llvm::StringRef xValue = a->getValue(); // Principal languages. - dashX = llvm::StringSwitch(XValue) + dashX = llvm::StringSwitch(xValue) .Case("f90", Language::Fortran) .Default(Language::Unknown); // Some special cases cannot be combined with suffixes. - if (dashX.IsUnknown()) - dashX = llvm::StringSwitch(XValue) + if (dashX.isUnknown()) + dashX = llvm::StringSwitch(xValue) .Case("ir", Language::LLVM_IR) .Default(Language::Unknown); - if (dashX.IsUnknown()) + if (dashX.isUnknown()) diags.Report(clang::diag::err_drv_invalid_value) << a->getAsString(args) << a->getValue(); } @@ -280,10 +282,10 @@ inputs.push_back("-"); for (unsigned i = 0, e = inputs.size(); i != e; ++i) { InputKind ik = dashX; - if (ik.IsUnknown()) { - ik = FrontendOptions::GetInputKindForExtension( + if (ik.isUnknown()) { + ik = FrontendOptions::getInputKindForExtension( llvm::StringRef(inputs[i]).rsplit('.').second); - if (ik.IsUnknown()) + if (ik.isUnknown()) ik = Language::Unknown; if (i == 0) dashX = ik; @@ -449,23 +451,23 @@ diags.Report(diagID); } if (moduleDirList.size() == 1) - res.SetModuleDir(moduleDirList[0]); + res.setModuleDir(moduleDirList[0]); // -fdebug-module-writer option if (args.hasArg(clang::driver::options::OPT_fdebug_module_writer)) { - res.SetDebugModuleDir(true); + res.setDebugModuleDir(true); } // -module-suffix if (const auto *moduleSuffix = args.getLastArg(clang::driver::options::OPT_module_suffix)) { - res.SetModuleFileSuffix(moduleSuffix->getValue()); + res.setModuleFileSuffix(moduleSuffix->getValue()); } // -f{no-}analyzed-objects-for-unparse - res.SetUseAnalyzedObjectsForUnparse( - args.hasFlag(clang::driver::options::OPT_fanalyzed_objects_for_unparse, - clang::driver::options::OPT_fno_analyzed_objects_for_unparse, true)); + res.setUseAnalyzedObjectsForUnparse(args.hasFlag( + clang::driver::options::OPT_fanalyzed_objects_for_unparse, + clang::driver::options::OPT_fno_analyzed_objects_for_unparse, true)); return diags.getNumErrors() == numErrorsBefore; } @@ -482,7 +484,7 @@ if (args.hasArg(clang::driver::options::OPT_W_Joined)) { if (args.getLastArgValue(clang::driver::options::OPT_W_Joined) .equals("error")) { - res.SetWarnAsErr(true); + res.setWarnAsErr(true); } else { const unsigned diagID = diags.getCustomDiagID(clang::DiagnosticsEngine::Error, @@ -502,13 +504,13 @@ // -fdefault* family if (args.hasArg(clang::driver::options::OPT_fdefault_real_8)) { - res.defaultKinds().set_defaultRealKind(8); - res.defaultKinds().set_doublePrecisionKind(16); + res.getDefaultKinds().set_defaultRealKind(8); + res.getDefaultKinds().set_doublePrecisionKind(16); } if (args.hasArg(clang::driver::options::OPT_fdefault_integer_8)) { - res.defaultKinds().set_defaultIntegerKind(8); - res.defaultKinds().set_subscriptIntegerKind(8); - res.defaultKinds().set_sizeIntegerKind(8); + res.getDefaultKinds().set_defaultIntegerKind(8); + res.getDefaultKinds().set_subscriptIntegerKind(8); + res.getDefaultKinds().set_sizeIntegerKind(8); } if (args.hasArg(clang::driver::options::OPT_fdefault_double_8)) { if (!args.hasArg(clang::driver::options::OPT_fdefault_real_8)) { @@ -520,24 +522,24 @@ diags.Report(diagID); } // https://gcc.gnu.org/onlinedocs/gfortran/Fortran-Dialect-Options.html - res.defaultKinds().set_doublePrecisionKind(8); + res.getDefaultKinds().set_doublePrecisionKind(8); } if (args.hasArg(clang::driver::options::OPT_flarge_sizes)) - res.defaultKinds().set_sizeIntegerKind(8); + res.getDefaultKinds().set_sizeIntegerKind(8); // -fopenmp and -fopenacc if (args.hasArg(clang::driver::options::OPT_fopenacc)) { - res.frontendOpts().features.Enable( + res.getFrontendOpts().features.Enable( Fortran::common::LanguageFeature::OpenACC); } if (args.hasArg(clang::driver::options::OPT_fopenmp)) { - res.frontendOpts().features.Enable( + res.getFrontendOpts().features.Enable( Fortran::common::LanguageFeature::OpenMP); } // -pedantic if (args.hasArg(clang::driver::options::OPT_pedantic)) { - res.set_EnableConformanceChecks(); + res.setEnableConformanceChecks(); } // -std=f2018 (currently this implies -pedantic) // TODO: Set proper options when more fortran standards @@ -546,7 +548,7 @@ auto standard = args.getLastArgValue(clang::driver::options::OPT_std_EQ); // We only allow f2018 as the given standard if (standard.equals("f2018")) { - res.set_EnableConformanceChecks(); + res.setEnableConformanceChecks(); } else { const unsigned diagID = diags.getCustomDiagID(clang::DiagnosticsEngine::Error, @@ -557,8 +559,8 @@ return diags.getNumErrors() == numErrorsBefore; } -bool CompilerInvocation::CreateFromArgs(CompilerInvocation &res, - llvm::ArrayRef commandLineArgs, +bool CompilerInvocation::createFromArgs( + CompilerInvocation &res, llvm::ArrayRef commandLineArgs, clang::DiagnosticsEngine &diags) { bool success = true; @@ -569,7 +571,7 @@ // NOTE: Like in Clang, it would be nice to use option marshalling // for this so that the entire logic for setting-up the triple is in one // place. - res.targetOpts().triple = + res.getTargetOpts().triple = llvm::Triple::normalize(llvm::sys::getDefaultTargetTriple()); // Parse the arguments @@ -598,23 +600,23 @@ success = false; } - success &= ParseFrontendArgs(res.frontendOpts(), args, diags); - ParseTargetArgs(res.targetOpts(), args); - parsePreprocessorArgs(res.preprocessorOpts(), args); + success &= parseFrontendArgs(res.getFrontendOpts(), args, diags); + parseTargetArgs(res.getTargetOpts(), args); + parsePreprocessorArgs(res.getPreprocessorOpts(), args); success &= parseSemaArgs(res, args, diags); success &= parseDialectArgs(res, args, diags); success &= parseDiagArgs(res, args, diags); - res.frontendOpts_.llvmArgs = + res.frontendOpts.llvmArgs = args.getAllArgValues(clang::driver::options::OPT_mllvm); - res.frontendOpts_.mlirArgs = + res.frontendOpts.mlirArgs = args.getAllArgValues(clang::driver::options::OPT_mmlir); return success; } -void CompilerInvocation::CollectMacroDefinitions() { - auto &ppOpts = this->preprocessorOpts(); +void CompilerInvocation::collectMacroDefinitions() { + auto &ppOpts = this->getPreprocessorOpts(); for (unsigned i = 0, n = ppOpts.macros.size(); i != n; ++i) { llvm::StringRef macro = ppOpts.macros[i].first; @@ -626,8 +628,8 @@ // For an #undef'd macro, we only care about the name. if (isUndef) { - parserOpts_.predefinitions.emplace_back( - macroName.str(), std::optional{}); + parserOpts.predefinitions.emplace_back(macroName.str(), + std::optional{}); continue; } @@ -636,16 +638,16 @@ macroBody = "1"; else { // Note: GCC drops anything following an end-of-line character. - llvm::StringRef::size_type End = macroBody.find_first_of("\n\r"); - macroBody = macroBody.substr(0, End); + llvm::StringRef::size_type end = macroBody.find_first_of("\n\r"); + macroBody = macroBody.substr(0, end); } - parserOpts_.predefinitions.emplace_back( + parserOpts.predefinitions.emplace_back( macroName, std::optional(macroBody.str())); } } -void CompilerInvocation::SetDefaultFortranOpts() { - auto &fortranOptions = fortranOpts(); +void CompilerInvocation::setDefaultFortranOpts() { + auto &fortranOptions = getFortranOpts(); std::vector searchDirectories{"."s}; fortranOptions.searchDirectories = searchDirectories; @@ -660,9 +662,9 @@ // TODO: When expanding this method, consider creating a dedicated API for // this. Also at some point we will need to differentiate between different // targets and add dedicated predefines for each. -void CompilerInvocation::SetDefaultPredefinitions() { - auto &fortranOptions = fortranOpts(); - const auto &frontendOptions = frontendOpts(); +void CompilerInvocation::setDefaultPredefinitions() { + auto &fortranOptions = getFortranOpts(); + const auto &frontendOptions = getFrontendOpts(); // Populate the macro list with version numbers and other predefinitions. fortranOptions.predefinitions.emplace_back("__flang__", "1"); @@ -684,11 +686,11 @@ } } -void CompilerInvocation::SetFortranOpts() { - auto &fortranOptions = fortranOpts(); - const auto &frontendOptions = frontendOpts(); - const auto &preprocessorOptions = preprocessorOpts(); - auto &moduleDirJ = moduleDir(); +void CompilerInvocation::setFortranOpts() { + auto &fortranOptions = getFortranOpts(); + const auto &frontendOptions = getFrontendOpts(); + const auto &preprocessorOptions = getPreprocessorOpts(); + auto &moduleDirJ = getModuleDir(); if (frontendOptions.fortranForm != FortranForm::Unknown) { fortranOptions.isFixedForm = @@ -725,22 +727,22 @@ if (frontendOptions.needProvenanceRangeToCharBlockMappings) fortranOptions.needProvenanceRangeToCharBlockMappings = true; - if (enableConformanceChecks()) { + if (getEnableConformanceChecks()) { fortranOptions.features.WarnOnAllNonstandard(); } } -void CompilerInvocation::SetSemanticsOpts( +void CompilerInvocation::setSemanticsOpts( Fortran::parser::AllCookedSources &allCookedSources) { - const auto &fortranOptions = fortranOpts(); + const auto &fortranOptions = getFortranOpts(); - semanticsContext_ = std::make_unique( - defaultKinds(), fortranOptions.features, allCookedSources); + semanticsContext = std::make_unique( + getDefaultKinds(), fortranOptions.features, allCookedSources); - semanticsContext_->set_moduleDirectory(moduleDir()) + semanticsContext->set_moduleDirectory(getModuleDir()) .set_searchDirectories(fortranOptions.searchDirectories) .set_intrinsicModuleDirectories(fortranOptions.intrinsicModuleDirectories) - .set_warnOnNonstandardUsage(enableConformanceChecks()) - .set_warningsAreErrors(warnAsErr()) - .set_moduleFileSuffix(moduleFileSuffix()); + .set_warnOnNonstandardUsage(getEnableConformanceChecks()) + .set_warningsAreErrors(getWarnAsErr()) + .set_moduleFileSuffix(getModuleFileSuffix()); } diff --git a/flang/lib/Frontend/FrontendAction.cpp b/flang/lib/Frontend/FrontendAction.cpp --- a/flang/lib/Frontend/FrontendAction.cpp +++ b/flang/lib/Frontend/FrontendAction.cpp @@ -19,110 +19,111 @@ LLVM_INSTANTIATE_REGISTRY(FrontendPluginRegistry) -void FrontendAction::set_currentInput(const FrontendInputFile ¤tInput) { - this->currentInput_ = currentInput; +void FrontendAction::setCurrentInput(const FrontendInputFile &input) { + this->currentInput = input; } // Call this method if BeginSourceFile fails. // Deallocate compiler instance, input and output descriptors -static void BeginSourceFileCleanUp(FrontendAction &fa, CompilerInstance &ci) { - ci.ClearOutputFiles(/*EraseFiles=*/true); - fa.set_currentInput(FrontendInputFile()); - fa.set_instance(nullptr); +static void beginSourceFileCleanUp(FrontendAction &fa, CompilerInstance &ci) { + ci.clearOutputFiles(/*EraseFiles=*/true); + fa.setCurrentInput(FrontendInputFile()); + fa.setInstance(nullptr); } -bool FrontendAction::BeginSourceFile( - CompilerInstance &ci, const FrontendInputFile &realInput) { +bool FrontendAction::beginSourceFile(CompilerInstance &ci, + const FrontendInputFile &realInput) { FrontendInputFile input(realInput); // Return immediately if the input file does not exist or is not a file. Note // that we cannot check this for input from stdin. - if (input.file() != "-") { - if (!llvm::sys::fs::is_regular_file(input.file())) { + if (input.getFile() != "-") { + if (!llvm::sys::fs::is_regular_file(input.getFile())) { // Create an diagnostic ID to report unsigned diagID; - if (llvm::vfs::getRealFileSystem()->exists(input.file())) { - ci.diagnostics().Report(clang::diag::err_fe_error_reading) - << input.file(); - diagID = ci.diagnostics().getCustomDiagID( + if (llvm::vfs::getRealFileSystem()->exists(input.getFile())) { + ci.getDiagnostics().Report(clang::diag::err_fe_error_reading) + << input.getFile(); + diagID = ci.getDiagnostics().getCustomDiagID( clang::DiagnosticsEngine::Error, "%0 is not a regular file"); } else { - diagID = ci.diagnostics().getCustomDiagID( + diagID = ci.getDiagnostics().getCustomDiagID( clang::DiagnosticsEngine::Error, "%0 does not exist"); } // Report the diagnostic and return - ci.diagnostics().Report(diagID) << input.file(); - BeginSourceFileCleanUp(*this, ci); + ci.getDiagnostics().Report(diagID) << input.getFile(); + beginSourceFileCleanUp(*this, ci); return false; } } - assert(!instance_ && "Already processing a source file!"); - assert(!realInput.IsEmpty() && "Unexpected empty filename!"); - set_currentInput(realInput); - set_instance(&ci); + assert(!instance && "Already processing a source file!"); + assert(!realInput.isEmpty() && "Unexpected empty filename!"); + setCurrentInput(realInput); + setInstance(&ci); - if (!ci.HasAllSources()) { - BeginSourceFileCleanUp(*this, ci); + if (!ci.hasAllSources()) { + beginSourceFileCleanUp(*this, ci); return false; } - auto &invoc = ci.invocation(); + auto &invoc = ci.getInvocation(); // Include command-line and predefined preprocessor macros. Use either: // * `-cpp/-nocpp`, or // * the file extension (if the user didn't express any preference) // to decide whether to include them or not. - if ((invoc.preprocessorOpts().macrosFlag == PPMacrosFlag::Include) || - (invoc.preprocessorOpts().macrosFlag == PPMacrosFlag::Unknown && - currentInput().MustBePreprocessed())) { - invoc.SetDefaultPredefinitions(); - invoc.CollectMacroDefinitions(); + if ((invoc.getPreprocessorOpts().macrosFlag == PPMacrosFlag::Include) || + (invoc.getPreprocessorOpts().macrosFlag == PPMacrosFlag::Unknown && + getCurrentInput().getMustBePreprocessed())) { + invoc.setDefaultPredefinitions(); + invoc.collectMacroDefinitions(); } // Decide between fixed and free form (if the user didn't express any // preference, use the file extension to decide) - if (invoc.frontendOpts().fortranForm == FortranForm::Unknown) { - invoc.fortranOpts().isFixedForm = currentInput().IsFixedForm(); + if (invoc.getFrontendOpts().fortranForm == FortranForm::Unknown) { + invoc.getFortranOpts().isFixedForm = getCurrentInput().getIsFixedForm(); } - if (!BeginSourceFileAction()) { - BeginSourceFileCleanUp(*this, ci); + if (!beginSourceFileAction()) { + beginSourceFileCleanUp(*this, ci); return false; } return true; } -bool FrontendAction::ShouldEraseOutputFiles() { - return instance().diagnostics().hasErrorOccurred(); +bool FrontendAction::shouldEraseOutputFiles() { + return getInstance().getDiagnostics().hasErrorOccurred(); } -llvm::Error FrontendAction::Execute() { - ExecuteAction(); +llvm::Error FrontendAction::execute() { + executeAction(); return llvm::Error::success(); } -void FrontendAction::EndSourceFile() { - CompilerInstance &ci = instance(); +void FrontendAction::endSourceFile() { + CompilerInstance &ci = getInstance(); // Cleanup the output streams, and erase the output files if instructed by the // FrontendAction. - ci.ClearOutputFiles(/*EraseFiles=*/ShouldEraseOutputFiles()); + ci.clearOutputFiles(/*EraseFiles=*/shouldEraseOutputFiles()); - set_instance(nullptr); - set_currentInput(FrontendInputFile()); + setInstance(nullptr); + setCurrentInput(FrontendInputFile()); } -bool FrontendAction::RunPrescan() { - CompilerInstance &ci = this->instance(); - std::string currentInputPath{GetCurrentFileOrBufferName()}; - Fortran::parser::Options parserOptions = ci.invocation().fortranOpts(); +bool FrontendAction::runPrescan() { + CompilerInstance &ci = this->getInstance(); + std::string currentInputPath{getCurrentFileOrBufferName()}; + Fortran::parser::Options parserOptions = ci.getInvocation().getFortranOpts(); - if (ci.invocation().frontendOpts().fortranForm == FortranForm::Unknown) { + if (ci.getInvocation().getFrontendOpts().fortranForm == + FortranForm::Unknown) { // Switch between fixed and free form format based on the input file // extension. // @@ -130,41 +131,41 @@ // method (i.e. before processing any specific input files). However, we // can't decide between fixed and free form based on the file extension // earlier than this. - parserOptions.isFixedForm = currentInput().IsFixedForm(); + parserOptions.isFixedForm = getCurrentInput().getIsFixedForm(); } // Prescan. In case of failure, report and return. - ci.parsing().Prescan(currentInputPath, parserOptions); + ci.getParsing().Prescan(currentInputPath, parserOptions); return !reportFatalScanningErrors(); } -bool FrontendAction::RunParse() { - CompilerInstance &ci = this->instance(); +bool FrontendAction::runParse() { + CompilerInstance &ci = this->getInstance(); // Parse. In case of failure, report and return. - ci.parsing().Parse(llvm::outs()); + ci.getParsing().Parse(llvm::outs()); if (reportFatalParsingErrors()) { return false; } - // Report the diagnostics from parsing - ci.parsing().messages().Emit(llvm::errs(), ci.allCookedSources()); + // Report the diagnostics from getParsing + ci.getParsing().messages().Emit(llvm::errs(), ci.getAllCookedSources()); return true; } -bool FrontendAction::RunSemanticChecks() { - CompilerInstance &ci = this->instance(); - std::optional &parseTree{ci.parsing().parseTree()}; +bool FrontendAction::runSemanticChecks() { + CompilerInstance &ci = this->getInstance(); + std::optional &parseTree{ci.getParsing().parseTree()}; assert(parseTree && "Cannot run semantic checks without a parse tree!"); // Prepare semantics - ci.SetSemantics(std::make_unique( - ci.invocation().semanticsContext(), *parseTree, - ci.invocation().debugModuleDir())); - auto &semantics = ci.semantics(); + ci.setSemantics(std::make_unique( + ci.getInvocation().getSemanticsContext(), *parseTree, + ci.getInvocation().getDebugModuleDir())); + auto &semantics = ci.getSemantics(); // Run semantic checks semantics.Perform(); @@ -174,16 +175,16 @@ } // Report the diagnostics from the semantic checks - semantics.EmitMessages(ci.semaOutputStream()); + semantics.EmitMessages(ci.getSemaOutputStream()); return true; } -bool FrontendAction::GenerateRtTypeTables() { - instance().setRtTyTables( +bool FrontendAction::generateRtTypeTables() { + getInstance().setRtTyTables( std::make_unique( BuildRuntimeDerivedTypeTables( - instance().invocation().semanticsContext()))); + getInstance().getInvocation().getSemanticsContext()))); // The runtime derived type information table builder may find additional // semantic errors. Report them. @@ -196,28 +197,28 @@ template bool FrontendAction::reportFatalErrors(const char (&message)[N]) { - if (!instance_->parsing().messages().empty() && - (instance_->invocation().warnAsErr() || - instance_->parsing().messages().AnyFatalError())) { - const unsigned diagID = instance_->diagnostics().getCustomDiagID( + if (!instance->getParsing().messages().empty() && + (instance->getInvocation().getWarnAsErr() || + instance->getParsing().messages().AnyFatalError())) { + const unsigned diagID = instance->getDiagnostics().getCustomDiagID( clang::DiagnosticsEngine::Error, message); - instance_->diagnostics().Report(diagID) << GetCurrentFileOrBufferName(); - instance_->parsing().messages().Emit( - llvm::errs(), instance_->allCookedSources()); + instance->getDiagnostics().Report(diagID) << getCurrentFileOrBufferName(); + instance->getParsing().messages().Emit(llvm::errs(), + instance->getAllCookedSources()); return true; } return false; } bool FrontendAction::reportFatalSemanticErrors() { - auto &diags = instance_->diagnostics(); - auto &sema = instance_->semantics(); - - if (instance_->semantics().AnyFatalError()) { - unsigned DiagID = diags.getCustomDiagID( - clang::DiagnosticsEngine::Error, "Semantic errors in %0"); - diags.Report(DiagID) << GetCurrentFileOrBufferName(); - sema.EmitMessages(instance_->semaOutputStream()); + auto &diags = instance->getDiagnostics(); + auto &sema = instance->getSemantics(); + + if (instance->getSemantics().AnyFatalError()) { + unsigned diagID = diags.getCustomDiagID(clang::DiagnosticsEngine::Error, + "Semantic errors in %0"); + diags.Report(diagID) << getCurrentFileOrBufferName(); + sema.EmitMessages(instance->getSemaOutputStream()); return true; } diff --git a/flang/lib/Frontend/FrontendActions.cpp b/flang/lib/Frontend/FrontendActions.cpp --- a/flang/lib/Frontend/FrontendActions.cpp +++ b/flang/lib/Frontend/FrontendActions.cpp @@ -30,6 +30,7 @@ #include "mlir/IR/Dialect.h" #include "mlir/Pass/PassManager.h" #include "mlir/Target/LLVMIR/ModuleTranslation.h" +#include "clang/Basic/Diagnostic.h" #include "clang/Basic/DiagnosticFrontend.h" #include "llvm/ADT/StringRef.h" #include "llvm/Analysis/TargetLibraryInfo.h" @@ -42,7 +43,6 @@ #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/SourceMgr.h" #include "llvm/Target/TargetMachine.h" -#include #include using namespace Fortran::frontend; @@ -51,46 +51,46 @@ // Custom BeginSourceFileAction //===----------------------------------------------------------------------===// -bool PrescanAction::BeginSourceFileAction() { return RunPrescan(); } +bool PrescanAction::beginSourceFileAction() { return runPrescan(); } -bool PrescanAndParseAction::BeginSourceFileAction() { - return RunPrescan() && RunParse(); +bool PrescanAndParseAction::beginSourceFileAction() { + return runPrescan() && runParse(); } -bool PrescanAndSemaAction::BeginSourceFileAction() { - return RunPrescan() && RunParse() && RunSemanticChecks() && - GenerateRtTypeTables(); +bool PrescanAndSemaAction::beginSourceFileAction() { + return runPrescan() && runParse() && runSemanticChecks() && + generateRtTypeTables(); } -bool PrescanAndSemaDebugAction::BeginSourceFileAction() { +bool PrescanAndSemaDebugAction::beginSourceFileAction() { // This is a "debug" action for development purposes. To facilitate this, the // semantic checks are made to succeed unconditionally to prevent this action // from exiting early (i.e. in the presence of semantic errors). We should // never do this in actions intended for end-users or otherwise regular // compiler workflows! - return RunPrescan() && RunParse() && (RunSemanticChecks() || true) && - (GenerateRtTypeTables() || true); + return runPrescan() && runParse() && (runSemanticChecks() || true) && + (generateRtTypeTables() || true); } -bool CodeGenAction::BeginSourceFileAction() { +bool CodeGenAction::beginSourceFileAction() { llvmCtx = std::make_unique(); // If the input is an LLVM file, just parse it and return. - if (this->currentInput().kind().GetLanguage() == Language::LLVM_IR) { + if (this->getCurrentInput().getKind().getLanguage() == Language::LLVM_IR) { llvm::SMDiagnostic err; - llvmModule = llvm::parseIRFile(currentInput().file(), err, *llvmCtx); + llvmModule = llvm::parseIRFile(getCurrentInput().getFile(), err, *llvmCtx); return (nullptr != llvmModule); } // Otherwise, generate an MLIR module from the input Fortran source - assert(currentInput().kind().GetLanguage() == Language::Fortran && + assert(getCurrentInput().getKind().getLanguage() == Language::Fortran && "Invalid input type - expecting a Fortran file"); - bool res = RunPrescan() && RunParse() && RunSemanticChecks(); + bool res = runPrescan() && runParse() && runSemanticChecks(); if (!res) return res; - CompilerInstance &ci = this->instance(); + CompilerInstance &ci = this->getInstance(); // Load the MLIR dialects required by Flang mlir::DialectRegistry registry; @@ -100,28 +100,29 @@ // Create a LoweringBridge const common::IntrinsicTypeDefaultKinds &defKinds = - ci.invocation().semanticsContext().defaultKinds(); + ci.getInvocation().getSemanticsContext().defaultKinds(); fir::KindMapping kindMap(mlirCtx.get(), llvm::ArrayRef{fir::fromDefaultKinds(defKinds)}); - lower::LoweringBridge lb = Fortran::lower::LoweringBridge::create(*mlirCtx, - defKinds, ci.invocation().semanticsContext().intrinsics(), - ci.parsing().allCooked(), ci.invocation().targetOpts().triple, kindMap); + lower::LoweringBridge lb = Fortran::lower::LoweringBridge::create( + *mlirCtx, defKinds, ci.getInvocation().getSemanticsContext().intrinsics(), + ci.getParsing().allCooked(), ci.getInvocation().getTargetOpts().triple, + kindMap); // Create a parse tree and lower it to FIR - Fortran::parser::Program &parseTree{*ci.parsing().parseTree()}; - lb.lower(parseTree, ci.invocation().semanticsContext()); + Fortran::parser::Program &parseTree{*ci.getParsing().parseTree()}; + lb.lower(parseTree, ci.getInvocation().getSemanticsContext()); mlirModule = std::make_unique(lb.getModule()); - // Run the default passes. + // run the default passes. mlir::PassManager pm(mlirCtx.get(), mlir::OpPassManager::Nesting::Implicit); pm.enableVerifier(/*verifyPasses=*/true); pm.addPass(std::make_unique()); if (mlir::failed(pm.run(*mlirModule))) { - unsigned diagID = - ci.diagnostics().getCustomDiagID(clang::DiagnosticsEngine::Error, - "verification of lowering to FIR failed"); - ci.diagnostics().Report(diagID); + unsigned diagID = ci.getDiagnostics().getCustomDiagID( + clang::DiagnosticsEngine::Error, + "verification of lowering to FIR failed"); + ci.getDiagnostics().Report(diagID); return false; } @@ -131,66 +132,66 @@ //===----------------------------------------------------------------------===// // Custom ExecuteAction //===----------------------------------------------------------------------===// -void InputOutputTestAction::ExecuteAction() { - CompilerInstance &ci = instance(); +void InputOutputTestAction::executeAction() { + CompilerInstance &ci = getInstance(); // Create a stream for errors std::string buf; - llvm::raw_string_ostream error_stream{buf}; + llvm::raw_string_ostream errorStream{buf}; // Read the input file - Fortran::parser::AllSources &allSources{ci.allSources()}; - std::string path{GetCurrentFileOrBufferName()}; + Fortran::parser::AllSources &allSources{ci.getAllSources()}; + std::string path{getCurrentFileOrBufferName()}; const Fortran::parser::SourceFile *sf; if (path == "-") - sf = allSources.ReadStandardInput(error_stream); + sf = allSources.ReadStandardInput(errorStream); else - sf = allSources.Open(path, error_stream, std::optional{"."s}); + sf = allSources.Open(path, errorStream, std::optional{"."s}); llvm::ArrayRef fileContent = sf->content(); // Output file descriptor to receive the contents of the input file. std::unique_ptr os; // Copy the contents from the input file to the output file - if (!ci.IsOutputStreamNull()) { + if (!ci.isOutputStreamNull()) { // An output stream (outputStream_) was set earlier - ci.WriteOutputStream(fileContent.data()); + ci.writeOutputStream(fileContent.data()); } else { // No pre-set output stream - create an output file - os = ci.CreateDefaultOutputFile( - /*binary=*/true, GetCurrentFileOrBufferName(), "txt"); + os = ci.createDefaultOutputFile( + /*binary=*/true, getCurrentFileOrBufferName(), "txt"); if (!os) return; (*os) << fileContent.data(); } } -void PrintPreprocessedAction::ExecuteAction() { +void PrintPreprocessedAction::executeAction() { std::string buf; llvm::raw_string_ostream outForPP{buf}; // Format or dump the prescanner's output - CompilerInstance &ci = this->instance(); - if (ci.invocation().preprocessorOpts().noReformat) { - ci.parsing().DumpCookedChars(outForPP); + CompilerInstance &ci = this->getInstance(); + if (ci.getInvocation().getPreprocessorOpts().noReformat) { + ci.getParsing().DumpCookedChars(outForPP); } else { - ci.parsing().EmitPreprocessedSource( - outForPP, !ci.invocation().preprocessorOpts().noLineDirectives); + ci.getParsing().EmitPreprocessedSource( + outForPP, !ci.getInvocation().getPreprocessorOpts().noLineDirectives); } - // Print diagnostics from the prescanner - ci.parsing().messages().Emit(llvm::errs(), ci.allCookedSources()); + // Print getDiagnostics from the prescanner + ci.getParsing().messages().Emit(llvm::errs(), ci.getAllCookedSources()); // If a pre-defined output stream exists, dump the preprocessed content there - if (!ci.IsOutputStreamNull()) { + if (!ci.isOutputStreamNull()) { // Send the output to the pre-defined output buffer. - ci.WriteOutputStream(outForPP.str()); + ci.writeOutputStream(outForPP.str()); return; } // Create a file and save the preprocessed output there - std::unique_ptr os{ci.CreateDefaultOutputFile( - /*Binary=*/true, /*InFile=*/GetCurrentFileOrBufferName())}; + std::unique_ptr os{ci.createDefaultOutputFile( + /*Binary=*/true, /*InFile=*/getCurrentFileOrBufferName())}; if (!os) { return; } @@ -198,46 +199,47 @@ (*os) << outForPP.str(); } -void DebugDumpProvenanceAction::ExecuteAction() { - this->instance().parsing().DumpProvenance(llvm::outs()); +void DebugDumpProvenanceAction::executeAction() { + this->getInstance().getParsing().DumpProvenance(llvm::outs()); } -void ParseSyntaxOnlyAction::ExecuteAction() { -} +void ParseSyntaxOnlyAction::executeAction() {} -void DebugUnparseNoSemaAction::ExecuteAction() { - auto &invoc = this->instance().invocation(); - auto &parseTree{instance().parsing().parseTree()}; +void DebugUnparseNoSemaAction::executeAction() { + auto &invoc = this->getInstance().getInvocation(); + auto &parseTree{getInstance().getParsing().parseTree()}; // TODO: Options should come from CompilerInvocation Unparse(llvm::outs(), *parseTree, - /*encoding=*/Fortran::parser::Encoding::UTF_8, - /*capitalizeKeywords=*/true, /*backslashEscapes=*/false, - /*preStatement=*/nullptr, - invoc.useAnalyzedObjectsForUnparse() ? &invoc.asFortran() : nullptr); + /*encoding=*/Fortran::parser::Encoding::UTF_8, + /*capitalizeKeywords=*/true, /*backslashEscapes=*/false, + /*preStatement=*/nullptr, + invoc.getUseAnalyzedObjectsForUnparse() ? &invoc.getAsFortran() + : nullptr); } -void DebugUnparseAction::ExecuteAction() { - auto &invoc = this->instance().invocation(); - auto &parseTree{instance().parsing().parseTree()}; +void DebugUnparseAction::executeAction() { + auto &invoc = this->getInstance().getInvocation(); + auto &parseTree{getInstance().getParsing().parseTree()}; - CompilerInstance &ci = this->instance(); - auto os{ci.CreateDefaultOutputFile( - /*Binary=*/false, /*InFile=*/GetCurrentFileOrBufferName())}; + CompilerInstance &ci = this->getInstance(); + auto os{ci.createDefaultOutputFile( + /*Binary=*/false, /*InFile=*/getCurrentFileOrBufferName())}; // TODO: Options should come from CompilerInvocation Unparse(*os, *parseTree, - /*encoding=*/Fortran::parser::Encoding::UTF_8, - /*capitalizeKeywords=*/true, /*backslashEscapes=*/false, - /*preStatement=*/nullptr, - invoc.useAnalyzedObjectsForUnparse() ? &invoc.asFortran() : nullptr); + /*encoding=*/Fortran::parser::Encoding::UTF_8, + /*capitalizeKeywords=*/true, /*backslashEscapes=*/false, + /*preStatement=*/nullptr, + invoc.getUseAnalyzedObjectsForUnparse() ? &invoc.getAsFortran() + : nullptr); // Report fatal semantic errors reportFatalSemanticErrors(); } -void DebugUnparseWithSymbolsAction::ExecuteAction() { - auto &parseTree{*instance().parsing().parseTree()}; +void DebugUnparseWithSymbolsAction::executeAction() { + auto &parseTree{*getInstance().getParsing().parseTree()}; Fortran::semantics::UnparseWithSymbols( llvm::outs(), parseTree, /*encoding=*/Fortran::parser::Encoding::UTF_8); @@ -246,38 +248,38 @@ reportFatalSemanticErrors(); } -void DebugDumpSymbolsAction::ExecuteAction() { - CompilerInstance &ci = this->instance(); +void DebugDumpSymbolsAction::executeAction() { + CompilerInstance &ci = this->getInstance(); if (!ci.getRtTyTables().schemata) { - unsigned DiagID = - ci.diagnostics().getCustomDiagID(clang::DiagnosticsEngine::Error, - "could not find module file for __fortran_type_info"); - ci.diagnostics().Report(DiagID); + unsigned diagID = ci.getDiagnostics().getCustomDiagID( + clang::DiagnosticsEngine::Error, + "could not find module file for __fortran_type_info"); + ci.getDiagnostics().Report(diagID); llvm::errs() << "\n"; return; } // Dump symbols - ci.semantics().DumpSymbols(llvm::outs()); + ci.getSemantics().DumpSymbols(llvm::outs()); } -void DebugDumpAllAction::ExecuteAction() { - CompilerInstance &ci = this->instance(); +void DebugDumpAllAction::executeAction() { + CompilerInstance &ci = this->getInstance(); // Dump parse tree - auto &parseTree{instance().parsing().parseTree()}; + auto &parseTree{getInstance().getParsing().parseTree()}; llvm::outs() << "========================"; llvm::outs() << " Flang: parse tree dump "; llvm::outs() << "========================\n"; - Fortran::parser::DumpTree( - llvm::outs(), parseTree, &ci.invocation().asFortran()); + Fortran::parser::DumpTree(llvm::outs(), parseTree, + &ci.getInvocation().getAsFortran()); if (!ci.getRtTyTables().schemata) { - unsigned DiagID = - ci.diagnostics().getCustomDiagID(clang::DiagnosticsEngine::Error, - "could not find module file for __fortran_type_info"); - ci.diagnostics().Report(DiagID); + unsigned diagID = ci.getDiagnostics().getCustomDiagID( + clang::DiagnosticsEngine::Error, + "could not find module file for __fortran_type_info"); + ci.getDiagnostics().Report(diagID); llvm::errs() << "\n"; return; } @@ -286,50 +288,52 @@ llvm::outs() << "====================="; llvm::outs() << " Flang: symbols dump "; llvm::outs() << "=====================\n"; - ci.semantics().DumpSymbols(llvm::outs()); + ci.getSemantics().DumpSymbols(llvm::outs()); } -void DebugDumpParseTreeNoSemaAction::ExecuteAction() { - auto &parseTree{instance().parsing().parseTree()}; +void DebugDumpParseTreeNoSemaAction::executeAction() { + auto &parseTree{getInstance().getParsing().parseTree()}; // Dump parse tree Fortran::parser::DumpTree( - llvm::outs(), parseTree, &this->instance().invocation().asFortran()); + llvm::outs(), parseTree, + &this->getInstance().getInvocation().getAsFortran()); } -void DebugDumpParseTreeAction::ExecuteAction() { - auto &parseTree{instance().parsing().parseTree()}; +void DebugDumpParseTreeAction::executeAction() { + auto &parseTree{getInstance().getParsing().parseTree()}; // Dump parse tree Fortran::parser::DumpTree( - llvm::outs(), parseTree, &this->instance().invocation().asFortran()); + llvm::outs(), parseTree, + &this->getInstance().getInvocation().getAsFortran()); // Report fatal semantic errors reportFatalSemanticErrors(); } -void DebugMeasureParseTreeAction::ExecuteAction() { - CompilerInstance &ci = this->instance(); +void DebugMeasureParseTreeAction::executeAction() { + CompilerInstance &ci = this->getInstance(); // Parse. In case of failure, report and return. - ci.parsing().Parse(llvm::outs()); + ci.getParsing().Parse(llvm::outs()); - if (!ci.parsing().messages().empty() && - (ci.invocation().warnAsErr() || - ci.parsing().messages().AnyFatalError())) { - unsigned diagID = ci.diagnostics().getCustomDiagID( + if (!ci.getParsing().messages().empty() && + (ci.getInvocation().getWarnAsErr() || + ci.getParsing().messages().AnyFatalError())) { + unsigned diagID = ci.getDiagnostics().getCustomDiagID( clang::DiagnosticsEngine::Error, "Could not parse %0"); - ci.diagnostics().Report(diagID) << GetCurrentFileOrBufferName(); + ci.getDiagnostics().Report(diagID) << getCurrentFileOrBufferName(); - ci.parsing().messages().Emit( - llvm::errs(), this->instance().allCookedSources()); + ci.getParsing().messages().Emit(llvm::errs(), + this->getInstance().getAllCookedSources()); return; } - // Report the diagnostics from parsing - ci.parsing().messages().Emit(llvm::errs(), ci.allCookedSources()); + // Report the getDiagnostics from parsing + ci.getParsing().messages().Emit(llvm::errs(), ci.getAllCookedSources()); - auto &parseTree{*ci.parsing().parseTree()}; + auto &parseTree{*ci.getParsing().parseTree()}; // Measure the parse tree MeasurementVisitor visitor; @@ -339,61 +343,61 @@ << " total bytes.\n"; } -void DebugPreFIRTreeAction::ExecuteAction() { - CompilerInstance &ci = this->instance(); +void DebugPreFIRTreeAction::executeAction() { + CompilerInstance &ci = this->getInstance(); // Report and exit if fatal semantic errors are present if (reportFatalSemanticErrors()) { return; } - auto &parseTree{*ci.parsing().parseTree()}; + auto &parseTree{*ci.getParsing().parseTree()}; // Dump pre-FIR tree if (auto ast{Fortran::lower::createPFT( - parseTree, ci.invocation().semanticsContext())}) { + parseTree, ci.getInvocation().getSemanticsContext())}) { Fortran::lower::dumpPFT(llvm::outs(), *ast); } else { - unsigned diagID = ci.diagnostics().getCustomDiagID( + unsigned diagID = ci.getDiagnostics().getCustomDiagID( clang::DiagnosticsEngine::Error, "Pre FIR Tree is NULL."); - ci.diagnostics().Report(diagID); + ci.getDiagnostics().Report(diagID); } } -void DebugDumpParsingLogAction::ExecuteAction() { - CompilerInstance &ci = this->instance(); +void DebugDumpParsingLogAction::executeAction() { + CompilerInstance &ci = this->getInstance(); - ci.parsing().Parse(llvm::errs()); - ci.parsing().DumpParsingLog(llvm::outs()); + ci.getParsing().Parse(llvm::errs()); + ci.getParsing().DumpParsingLog(llvm::outs()); } -void GetDefinitionAction::ExecuteAction() { - CompilerInstance &ci = this->instance(); +void GetDefinitionAction::executeAction() { + CompilerInstance &ci = this->getInstance(); // Report and exit if fatal semantic errors are present if (reportFatalSemanticErrors()) { return; } - parser::AllCookedSources &cs = ci.allCookedSources(); - unsigned diagID = ci.diagnostics().getCustomDiagID( + parser::AllCookedSources &cs = ci.getAllCookedSources(); + unsigned diagID = ci.getDiagnostics().getCustomDiagID( clang::DiagnosticsEngine::Error, "Symbol not found"); - auto gdv = ci.invocation().frontendOpts().getDefVals; + auto gdv = ci.getInvocation().getFrontendOpts().getDefVals; auto charBlock{cs.GetCharBlockFromLineAndColumns( gdv.line, gdv.startColumn, gdv.endColumn)}; if (!charBlock) { - ci.diagnostics().Report(diagID); + ci.getDiagnostics().Report(diagID); return; } llvm::outs() << "String range: >" << charBlock->ToString() << "<\n"; - auto *symbol{ci.invocation() - .semanticsContext() + auto *symbol{ci.getInvocation() + .getSemanticsContext() .FindScope(*charBlock) .FindSymbol(*charBlock)}; if (!symbol) { - ci.diagnostics().Report(diagID); + ci.getDiagnostics().Report(diagID); return; } @@ -414,15 +418,15 @@ << "-" << sourceInfo->second.column << "\n"; } -void GetSymbolsSourcesAction::ExecuteAction() { - CompilerInstance &ci = this->instance(); +void GetSymbolsSourcesAction::executeAction() { + CompilerInstance &ci = this->getInstance(); // Report and exit if fatal semantic errors are present if (reportFatalSemanticErrors()) { return; } - ci.semantics().DumpSymbolsSources(llvm::outs()); + ci.getSemantics().DumpSymbolsSources(llvm::outs()); } //===----------------------------------------------------------------------===// @@ -434,10 +438,10 @@ #include "flang/Tools/CLOptions.inc" // Lower the previously generated MLIR module into an LLVM IR module -void CodeGenAction::GenerateLLVMIR() { +void CodeGenAction::generateLLVMIR() { assert(mlirModule && "The MLIR module has not been generated yet."); - CompilerInstance &ci = this->instance(); + CompilerInstance &ci = this->getInstance(); fir::support::loadDialects(*mlirCtx); fir::support::registerLLVMTranslation(*mlirCtx); @@ -452,11 +456,11 @@ fir::createMLIRToLLVMPassPipeline(pm); mlir::applyPassManagerCLOptions(pm); - // Run the pass manager + // run the pass manager if (!mlir::succeeded(pm.run(*mlirModule))) { - unsigned diagID = ci.diagnostics().getCustomDiagID( + unsigned diagID = ci.getDiagnostics().getCustomDiagID( clang::DiagnosticsEngine::Error, "Lowering to LLVM IR failed"); - ci.diagnostics().Report(diagID); + ci.getDiagnostics().Report(diagID); } // Translate to LLVM IR @@ -465,20 +469,21 @@ *mlirModule, *llvmCtx, moduleName ? *moduleName : "FIRModule"); if (!llvmModule) { - unsigned diagID = ci.diagnostics().getCustomDiagID( + unsigned diagID = ci.getDiagnostics().getCustomDiagID( clang::DiagnosticsEngine::Error, "failed to create the LLVM module"); - ci.diagnostics().Report(diagID); + ci.getDiagnostics().Report(diagID); return; } } -void CodeGenAction::SetUpTargetMachine() { - CompilerInstance &ci = this->instance(); +void CodeGenAction::setUpTargetMachine() { + CompilerInstance &ci = this->getInstance(); // Set the triple based on the CompilerInvocation set-up - const std::string &theTriple = ci.invocation().targetOpts().triple; + const std::string &theTriple = ci.getInvocation().getTargetOpts().triple; if (llvmModule->getTargetTriple() != theTriple) { - ci.diagnostics().Report(clang::diag::warn_fe_override_module) << theTriple; + ci.getDiagnostics().Report(clang::diag::warn_fe_override_module) + << theTriple; llvmModule->setTargetTriple(theTriple); } @@ -489,31 +494,31 @@ assert(theTarget && "Failed to create Target"); // Create `TargetMachine` - TM.reset(theTarget->createTargetMachine(theTriple, /*CPU=*/"", + tm.reset(theTarget->createTargetMachine(theTriple, /*CPU=*/"", /*Features=*/"", llvm::TargetOptions(), llvm::None)); - assert(TM && "Failed to create TargetMachine"); - llvmModule->setDataLayout(TM->createDataLayout()); + assert(tm && "Failed to create TargetMachine"); + llvmModule->setDataLayout(tm->createDataLayout()); } static std::unique_ptr -GetOutputStream(CompilerInstance &ci, llvm::StringRef inFile, +getOutputStream(CompilerInstance &ci, llvm::StringRef inFile, BackendActionTy action) { switch (action) { case BackendActionTy::Backend_EmitAssembly: - return ci.CreateDefaultOutputFile( + return ci.createDefaultOutputFile( /*Binary=*/false, inFile, /*extension=*/"s"); case BackendActionTy::Backend_EmitLL: - return ci.CreateDefaultOutputFile( + return ci.createDefaultOutputFile( /*Binary=*/false, inFile, /*extension=*/"ll"); case BackendActionTy::Backend_EmitMLIR: - return ci.CreateDefaultOutputFile( + return ci.createDefaultOutputFile( /*Binary=*/false, inFile, /*extension=*/"mlir"); case BackendActionTy::Backend_EmitBC: - return ci.CreateDefaultOutputFile( + return ci.createDefaultOutputFile( /*Binary=*/true, inFile, /*extension=*/"bc"); case BackendActionTy::Backend_EmitObj: - return ci.CreateDefaultOutputFile( + return ci.createDefaultOutputFile( /*Binary=*/true, inFile, /*extension=*/"o"); } @@ -524,12 +529,12 @@ /// module. /// /// \param [in] diags Diagnostics engine for reporting errors -/// \param [in] TM Target machine to aid the code-gen pipeline set-up +/// \param [in] tm Target machine to aid the code-gen pipeline set-up /// \param [in] act Backend act to run (assembly vs machine-code generation) /// \param [in] llvmModule LLVM module to lower to assembly/machine-code /// \param [out] os Output stream to emit the generated code to static void GenerateMachineCodeOrAssemblyImpl(clang::DiagnosticsEngine &diags, - llvm::TargetMachine &TM, + llvm::TargetMachine &tm, BackendActionTy act, llvm::Module &llvmModule, llvm::raw_pwrite_stream &os) { @@ -540,20 +545,20 @@ // Set-up the pass manager, i.e create an LLVM code-gen pass pipeline. // Currently only the legacy pass manager is supported. // TODO: Switch to the new PM once it's available in the backend. - llvm::legacy::PassManager CodeGenPasses; - CodeGenPasses.add( - createTargetTransformInfoWrapperPass(TM.getTargetIRAnalysis())); + llvm::legacy::PassManager codeGenPasses; + codeGenPasses.add( + createTargetTransformInfoWrapperPass(tm.getTargetIRAnalysis())); llvm::Triple triple(llvmModule.getTargetTriple()); - std::unique_ptr TLII = + std::unique_ptr tLII = std::make_unique(triple); - assert(TLII && "Failed to create TargetLibraryInfo"); - CodeGenPasses.add(new llvm::TargetLibraryInfoWrapperPass(*TLII)); + assert(tLII && "Failed to create TargetLibraryInfo"); + codeGenPasses.add(new llvm::TargetLibraryInfoWrapperPass(*tLII)); llvm::CodeGenFileType cgft = (act == BackendActionTy::Backend_EmitAssembly) ? llvm::CodeGenFileType::CGFT_AssemblyFile : llvm::CodeGenFileType::CGFT_ObjectFile; - if (TM.addPassesToEmitFile(CodeGenPasses, os, nullptr, cgft)) { + if (tm.addPassesToEmitFile(codeGenPasses, os, nullptr, cgft)) { unsigned diagID = diags.getCustomDiagID(clang::DiagnosticsEngine::Error, "emission of this file type is not supported"); @@ -562,120 +567,120 @@ } // Run the passes - CodeGenPasses.run(llvmModule); + codeGenPasses.run(llvmModule); } /// Generate LLVM byte code file from the input LLVM module. /// -/// \param [in] TM Target machine to aid the code-gen pipeline set-up +/// \param [in] tm Target machine to aid the code-gen pipeline set-up /// \param [in] llvmModule LLVM module to lower to assembly/machine-code /// \param [out] os Output stream to emit the generated code to -static void GenerateLLVMBCImpl(llvm::TargetMachine &TM, +static void GenerateLLVMBCImpl(llvm::TargetMachine &tm, llvm::Module &llvmModule, llvm::raw_pwrite_stream &os) { // Set-up the pass manager - llvm::ModulePassManager MPM; - llvm::ModuleAnalysisManager MAM; - llvm::PassBuilder PB(&TM); - PB.registerModuleAnalyses(MAM); - MPM.addPass(llvm::BitcodeWriterPass(os)); - - // Run the passes - MPM.run(llvmModule, MAM); + llvm::ModulePassManager mPM; + llvm::ModuleAnalysisManager mAM; + llvm::PassBuilder pB(&tm); + pB.registerModuleAnalyses(mAM); + mPM.addPass(llvm::BitcodeWriterPass(os)); + + // run the passes + mPM.run(llvmModule, mAM); } -void CodeGenAction::ExecuteAction() { - CompilerInstance &ci = this->instance(); +void CodeGenAction::executeAction() { + CompilerInstance &ci = this->getInstance(); // If the output stream is a file, generate it and define the corresponding // output stream. If a pre-defined output stream is available, we will use // that instead. // // NOTE: `os` is a smart pointer that will be destroyed at the end of this - // method. However, it won't be written to until `CodeGenPasses` is - // destroyed. By defining `os` before `CodeGenPasses`, we make sure that the + // method. However, it won't be written to until `codeGenPasses` is + // destroyed. By defining `os` before `codeGenPasses`, we make sure that the // output stream won't be destroyed before it is written to. This only // applies when an output file is used (i.e. there is no pre-defined output // stream). - // TODO: Revisit once the new PM is ready (i.e. when `CodeGenPasses` is + // TODO: Revisit once the new PM is ready (i.e. when `codeGenPasses` is // updated to use it). std::unique_ptr os; - if (ci.IsOutputStreamNull()) { - os = GetOutputStream(ci, GetCurrentFileOrBufferName(), action); + if (ci.isOutputStreamNull()) { + os = getOutputStream(ci, getCurrentFileOrBufferName(), action); if (!os) { - unsigned diagID = ci.diagnostics().getCustomDiagID( + unsigned diagID = ci.getDiagnostics().getCustomDiagID( clang::DiagnosticsEngine::Error, "failed to create the output file"); - ci.diagnostics().Report(diagID); + ci.getDiagnostics().Report(diagID); return; } } if (action == BackendActionTy::Backend_EmitMLIR) { - mlirModule->print(ci.IsOutputStreamNull() ? *os : ci.GetOutputStream()); + mlirModule->print(ci.isOutputStreamNull() ? *os : ci.getOutputStream()); return; } - // Generate an LLVM module if it's not already present (it will already be + // generate an LLVM module if it's not already present (it will already be // present if the input file is an LLVM IR/BC file). if (!llvmModule) - GenerateLLVMIR(); + generateLLVMIR(); if (action == BackendActionTy::Backend_EmitLL) { - llvmModule->print(ci.IsOutputStreamNull() ? *os : ci.GetOutputStream(), + llvmModule->print(ci.isOutputStreamNull() ? *os : ci.getOutputStream(), /*AssemblyAnnotationWriter=*/nullptr); return; } - SetUpTargetMachine(); + setUpTargetMachine(); if (action == BackendActionTy::Backend_EmitBC) { - GenerateLLVMBCImpl(*TM, *llvmModule, *os); + GenerateLLVMBCImpl(*tm, *llvmModule, *os); return; } if (action == BackendActionTy::Backend_EmitAssembly || action == BackendActionTy::Backend_EmitObj) { GenerateMachineCodeOrAssemblyImpl( - ci.diagnostics(), *TM, action, *llvmModule, - ci.IsOutputStreamNull() ? *os : ci.GetOutputStream()); + ci.getDiagnostics(), *tm, action, *llvmModule, + ci.isOutputStreamNull() ? *os : ci.getOutputStream()); return; } } -void InitOnlyAction::ExecuteAction() { - CompilerInstance &ci = this->instance(); - unsigned DiagID = - ci.diagnostics().getCustomDiagID(clang::DiagnosticsEngine::Warning, - "Use `-init-only` for testing purposes only"); - ci.diagnostics().Report(DiagID); +void InitOnlyAction::executeAction() { + CompilerInstance &ci = this->getInstance(); + unsigned diagID = ci.getDiagnostics().getCustomDiagID( + clang::DiagnosticsEngine::Warning, + "Use `-init-only` for testing purposes only"); + ci.getDiagnostics().Report(diagID); } -void PluginParseTreeAction::ExecuteAction() {} +void PluginParseTreeAction::executeAction() {} -void DebugDumpPFTAction::ExecuteAction() { - CompilerInstance &ci = this->instance(); +void DebugDumpPFTAction::executeAction() { + CompilerInstance &ci = this->getInstance(); - if (auto ast = Fortran::lower::createPFT( - *ci.parsing().parseTree(), ci.semantics().context())) { + if (auto ast = Fortran::lower::createPFT(*ci.getParsing().parseTree(), + ci.getSemantics().context())) { Fortran::lower::dumpPFT(llvm::outs(), *ast); return; } - unsigned DiagID = ci.diagnostics().getCustomDiagID( + unsigned diagID = ci.getDiagnostics().getCustomDiagID( clang::DiagnosticsEngine::Error, "Pre FIR Tree is NULL."); - ci.diagnostics().Report(DiagID); + ci.getDiagnostics().Report(diagID); } Fortran::parser::Parsing &PluginParseTreeAction::getParsing() { - return instance().parsing(); + return getInstance().getParsing(); } std::unique_ptr PluginParseTreeAction::createOutputFile(llvm::StringRef extension = "") { - std::unique_ptr OS{ - instance().CreateDefaultOutputFile( - /*Binary=*/false, /*InFile=*/GetCurrentFileOrBufferName(), + std::unique_ptr os{ + getInstance().createDefaultOutputFile( + /*Binary=*/false, /*InFile=*/getCurrentFileOrBufferName(), extension)}; - return OS; + return os; } diff --git a/flang/lib/Frontend/FrontendOptions.cpp b/flang/lib/Frontend/FrontendOptions.cpp --- a/flang/lib/Frontend/FrontendOptions.cpp +++ b/flang/lib/Frontend/FrontendOptions.cpp @@ -25,13 +25,13 @@ suffix == "F08" || suffix == "f18" || suffix == "F18"; } -bool Fortran::frontend::mustBePreprocessed(llvm::StringRef suffix) { +bool Fortran::frontend::isToBePreprocessed(llvm::StringRef suffix) { return suffix == "F" || suffix == "FOR" || suffix == "fpp" || suffix == "FPP" || suffix == "F90" || suffix == "F95" || suffix == "F03" || suffix == "F08" || suffix == "F18"; } -InputKind FrontendOptions::GetInputKindForExtension(llvm::StringRef extension) { +InputKind FrontendOptions::getInputKindForExtension(llvm::StringRef extension) { if (isFixedFormSuffix(extension) || isFreeFormSuffix(extension)) { return Language::Fortran; } diff --git a/flang/lib/Frontend/TextDiagnostic.cpp b/flang/lib/Frontend/TextDiagnostic.cpp --- a/flang/lib/Frontend/TextDiagnostic.cpp +++ b/flang/lib/Frontend/TextDiagnostic.cpp @@ -30,8 +30,10 @@ TextDiagnostic::~TextDiagnostic() {} -/*static*/ void TextDiagnostic::PrintDiagnosticLevel(llvm::raw_ostream &os, - clang::DiagnosticsEngine::Level level, bool showColors) { +/*static*/ void +TextDiagnostic::printDiagnosticLevel(llvm::raw_ostream &os, + clang::DiagnosticsEngine::Level level, + bool showColors) { if (showColors) { // Print diagnostic category in bold and color switch (level) { @@ -82,8 +84,10 @@ } /*static*/ -void TextDiagnostic::PrintDiagnosticMessage(llvm::raw_ostream &os, - bool isSupplemental, llvm::StringRef message, bool showColors) { +void TextDiagnostic::printDiagnosticMessage(llvm::raw_ostream &os, + bool isSupplemental, + llvm::StringRef message, + bool showColors) { if (showColors && !isSupplemental) { // Print primary diagnostic messages in bold and without color. os.changeColor(savedColor, true); diff --git a/flang/lib/Frontend/TextDiagnosticBuffer.cpp b/flang/lib/Frontend/TextDiagnosticBuffer.cpp --- a/flang/lib/Frontend/TextDiagnosticBuffer.cpp +++ b/flang/lib/Frontend/TextDiagnosticBuffer.cpp @@ -30,44 +30,44 @@ default: llvm_unreachable("Diagnostic not handled during diagnostic buffering!"); case clang::DiagnosticsEngine::Note: - all_.emplace_back(level, notes_.size()); - notes_.emplace_back(info.getLocation(), std::string(buf.str())); + all.emplace_back(level, notes.size()); + notes.emplace_back(info.getLocation(), std::string(buf.str())); break; case clang::DiagnosticsEngine::Warning: - all_.emplace_back(level, warnings_.size()); - warnings_.emplace_back(info.getLocation(), std::string(buf.str())); + all.emplace_back(level, warnings.size()); + warnings.emplace_back(info.getLocation(), std::string(buf.str())); break; case clang::DiagnosticsEngine::Remark: - all_.emplace_back(level, remarks_.size()); - remarks_.emplace_back(info.getLocation(), std::string(buf.str())); + all.emplace_back(level, remarks.size()); + remarks.emplace_back(info.getLocation(), std::string(buf.str())); break; case clang::DiagnosticsEngine::Error: case clang::DiagnosticsEngine::Fatal: - all_.emplace_back(level, errors_.size()); - errors_.emplace_back(info.getLocation(), std::string(buf.str())); + all.emplace_back(level, errors.size()); + errors.emplace_back(info.getLocation(), std::string(buf.str())); break; } } -void TextDiagnosticBuffer::FlushDiagnostics( - clang::DiagnosticsEngine &Diags) const { - for (const auto &i : all_) { - auto Diag = Diags.Report(Diags.getCustomDiagID(i.first, "%0")); +void TextDiagnosticBuffer::flushDiagnostics( + clang::DiagnosticsEngine &diags) const { + for (const auto &i : all) { + auto diag = diags.Report(diags.getCustomDiagID(i.first, "%0")); switch (i.first) { default: llvm_unreachable("Diagnostic not handled during diagnostic flushing!"); case clang::DiagnosticsEngine::Note: - Diag << notes_[i.second].second; + diag << notes[i.second].second; break; case clang::DiagnosticsEngine::Warning: - Diag << warnings_[i.second].second; + diag << warnings[i.second].second; break; case clang::DiagnosticsEngine::Remark: - Diag << remarks_[i.second].second; + diag << remarks[i.second].second; break; case clang::DiagnosticsEngine::Error: case clang::DiagnosticsEngine::Fatal: - Diag << errors_[i.second].second; + diag << errors[i.second].second; break; } } diff --git a/flang/lib/Frontend/TextDiagnosticPrinter.cpp b/flang/lib/Frontend/TextDiagnosticPrinter.cpp --- a/flang/lib/Frontend/TextDiagnosticPrinter.cpp +++ b/flang/lib/Frontend/TextDiagnosticPrinter.cpp @@ -19,9 +19,9 @@ using namespace Fortran::frontend; -TextDiagnosticPrinter::TextDiagnosticPrinter( - raw_ostream &os, clang::DiagnosticOptions *diags) - : os_(os), diagOpts_(diags) {} +TextDiagnosticPrinter::TextDiagnosticPrinter(raw_ostream &diagOs, + clang::DiagnosticOptions *diags) + : os(diagOs), diagOpts(diags) {} TextDiagnosticPrinter::~TextDiagnosticPrinter() {} @@ -35,21 +35,22 @@ llvm::SmallString<100> outStr; info.FormatDiagnostic(outStr); - llvm::raw_svector_ostream DiagMessageStream(outStr); + llvm::raw_svector_ostream diagMessageStream(outStr); - if (!prefix_.empty()) - os_ << prefix_ << ": "; + if (!prefix.empty()) + os << prefix << ": "; // We only emit diagnostics in contexts that lack valid source locations. assert(!info.getLocation().isValid() && "Diagnostics with valid source location are not supported"); - Fortran::frontend::TextDiagnostic::PrintDiagnosticLevel( - os_, level, diagOpts_->ShowColors); - Fortran::frontend::TextDiagnostic::PrintDiagnosticMessage(os_, + Fortran::frontend::TextDiagnostic::printDiagnosticLevel(os, level, + diagOpts->ShowColors); + Fortran::frontend::TextDiagnostic::printDiagnosticMessage( + os, /*IsSupplemental=*/level == clang::DiagnosticsEngine::Note, - DiagMessageStream.str(), diagOpts_->ShowColors); + diagMessageStream.str(), diagOpts->ShowColors); - os_.flush(); + os.flush(); return; } diff --git a/flang/lib/FrontendTool/.clang-tidy b/flang/lib/FrontendTool/.clang-tidy new file mode 100644 --- /dev/null +++ b/flang/lib/FrontendTool/.clang-tidy @@ -0,0 +1,9 @@ +Checks: '-readability-braces-around-statements,readability-identifier-naming,llvm-include-order,clang-diagnostic-*' +InheritParentConfig: true +CheckOptions: + - key: readability-identifier-naming.MemberCase + value: camelBack + - key: readability-identifier-naming.ParameterCase + value: camelBack + - key: readability-identifier-naming.VariableCase + value: camelBack diff --git a/flang/lib/FrontendTool/ExecuteCompilerInvocation.cpp b/flang/lib/FrontendTool/ExecuteCompilerInvocation.cpp --- a/flang/lib/FrontendTool/ExecuteCompilerInvocation.cpp +++ b/flang/lib/FrontendTool/ExecuteCompilerInvocation.cpp @@ -14,20 +14,21 @@ #include "flang/Frontend/CompilerInstance.h" #include "flang/Frontend/FrontendActions.h" #include "flang/Frontend/FrontendPluginRegistry.h" + +#include "mlir/IR/MLIRContext.h" +#include "mlir/Pass/PassManager.h" #include "clang/Driver/Options.h" #include "llvm/Option/OptTable.h" #include "llvm/Option/Option.h" #include "llvm/Support/BuryPointer.h" #include "llvm/Support/CommandLine.h" -#include "mlir/IR/MLIRContext.h" -#include "mlir/Pass/PassManager.h" namespace Fortran::frontend { -static std::unique_ptr CreateFrontendAction( +static std::unique_ptr createFrontendAction( CompilerInstance &ci) { - switch (ci.frontendOpts().programAction) { + switch (ci.getFrontendOpts().programAction) { case InputOutputTest: return std::make_unique(); case PrintPreprocessedInput: @@ -77,14 +78,14 @@ case PluginAction: { for (const FrontendPluginRegistry::entry &plugin : FrontendPluginRegistry::entries()) { - if (plugin.getName() == ci.frontendOpts().ActionName) { + if (plugin.getName() == ci.getFrontendOpts().actionName) { std::unique_ptr p(plugin.instantiate()); return std::move(p); } } - unsigned diagID = ci.diagnostics().getCustomDiagID( + unsigned diagID = ci.getDiagnostics().getCustomDiagID( clang::DiagnosticsEngine::Error, "unable to find plugin '%0'"); - ci.diagnostics().Report(diagID) << ci.frontendOpts().ActionName; + ci.getDiagnostics().Report(diagID) << ci.getFrontendOpts().actionName; return nullptr; } } @@ -92,9 +93,9 @@ llvm_unreachable("Invalid program action!"); } -bool ExecuteCompilerInvocation(CompilerInstance *flang) { +bool executeCompilerInvocation(CompilerInstance *flang) { // Honor -help. - if (flang->frontendOpts().showHelp) { + if (flang->getFrontendOpts().showHelp) { clang::driver::getDriverOptTable().printHelp(llvm::outs(), "flang-new -fc1 [options] file...", "LLVM 'Flang' Compiler", /*Include=*/clang::driver::options::FC1Option, @@ -104,61 +105,61 @@ } // Honor -version. - if (flang->frontendOpts().showVersion) { + if (flang->getFrontendOpts().showVersion) { llvm::cl::PrintVersionMessage(); return true; } // Load any requested plugins. - for (const std::string &Path : flang->frontendOpts().plugins) { - std::string Error; + for (const std::string &path : flang->getFrontendOpts().plugins) { + std::string error; if (llvm::sys::DynamicLibrary::LoadLibraryPermanently( - Path.c_str(), &Error)) { - unsigned diagID = flang->diagnostics().getCustomDiagID( + path.c_str(), &error)) { + unsigned diagID = flang->getDiagnostics().getCustomDiagID( clang::DiagnosticsEngine::Error, "unable to load plugin '%0': '%1'"); - flang->diagnostics().Report(diagID) << Path << Error; + flang->getDiagnostics().Report(diagID) << path << error; } } // Honor -mllvm. This should happen AFTER plugins have been loaded! - if (!flang->frontendOpts().llvmArgs.empty()) { - unsigned numArgs = flang->frontendOpts().llvmArgs.size(); + if (!flang->getFrontendOpts().llvmArgs.empty()) { + unsigned numArgs = flang->getFrontendOpts().llvmArgs.size(); auto args = std::make_unique(numArgs + 2); args[0] = "flang (LLVM option parsing)"; for (unsigned i = 0; i != numArgs; ++i) - args[i + 1] = flang->frontendOpts().llvmArgs[i].c_str(); + args[i + 1] = flang->getFrontendOpts().llvmArgs[i].c_str(); args[numArgs + 1] = nullptr; llvm::cl::ParseCommandLineOptions(numArgs + 1, args.get()); } // Honor -mmlir. This should happen AFTER plugins have been loaded! - if (!flang->frontendOpts().mlirArgs.empty()) { + if (!flang->getFrontendOpts().mlirArgs.empty()) { mlir::registerMLIRContextCLOptions(); mlir::registerPassManagerCLOptions(); - unsigned numArgs = flang->frontendOpts().mlirArgs.size(); + unsigned numArgs = flang->getFrontendOpts().mlirArgs.size(); auto args = std::make_unique(numArgs + 2); args[0] = "flang (MLIR option parsing)"; for (unsigned i = 0; i != numArgs; ++i) - args[i + 1] = flang->frontendOpts().mlirArgs[i].c_str(); + args[i + 1] = flang->getFrontendOpts().mlirArgs[i].c_str(); args[numArgs + 1] = nullptr; llvm::cl::ParseCommandLineOptions(numArgs + 1, args.get()); } // If there were errors in processing arguments, don't do anything else. - if (flang->diagnostics().hasErrorOccurred()) { + if (flang->getDiagnostics().hasErrorOccurred()) { return false; } // Create and execute the frontend action. - std::unique_ptr act(CreateFrontendAction(*flang)); + std::unique_ptr act(createFrontendAction(*flang)); if (!act) return false; - bool success = flang->ExecuteAction(*act); + bool success = flang->executeAction(*act); return success; } diff --git a/flang/tools/flang-driver/.clang-tidy b/flang/tools/flang-driver/.clang-tidy new file mode 100644 --- /dev/null +++ b/flang/tools/flang-driver/.clang-tidy @@ -0,0 +1,9 @@ +Checks: '-readability-braces-around-statements,readability-identifier-naming,llvm-include-order,clang-diagnostic-*' +InheritParentConfig: true +CheckOptions: + - key: readability-identifier-naming.MemberCase + value: camelBack + - key: readability-identifier-naming.ParameterCase + value: camelBack + - key: readability-identifier-naming.VariableCase + value: camelBack diff --git a/flang/tools/flang-driver/driver.cpp b/flang/tools/flang-driver/driver.cpp --- a/flang/tools/flang-driver/driver.cpp +++ b/flang/tools/flang-driver/driver.cpp @@ -29,15 +29,15 @@ // main frontend method. Lives inside fc1_main.cpp extern int fc1_main(llvm::ArrayRef argv, const char *argv0); -std::string GetExecutablePath(const char *argv0) { +std::string getExecutablePath(const char *argv0) { // This just needs to be some symbol in the binary - void *p = (void *)(intptr_t)GetExecutablePath; + void *p = (void *)(intptr_t)getExecutablePath; return llvm::sys::fs::getMainExecutable(argv0, p); } // This lets us create the DiagnosticsEngine with a properly-filled-out // DiagnosticOptions instance -static clang::DiagnosticOptions *CreateAndPopulateDiagOpts( +static clang::DiagnosticOptions *createAndPopulateDiagOpts( llvm::ArrayRef argv) { auto *diagOpts = new clang::DiagnosticOptions; @@ -49,12 +49,12 @@ argv.slice(1), missingArgIndex, missingArgCount, /*FlagsToInclude=*/clang::driver::options::FlangOption); - (void)Fortran::frontend::ParseDiagnosticArgs(*diagOpts, args); + (void)Fortran::frontend::parseDiagnosticArgs(*diagOpts, args); return diagOpts; } -static int ExecuteFC1Tool(llvm::SmallVectorImpl &argV) { +static int executeFC1Tool(llvm::SmallVectorImpl &argV) { llvm::StringRef tool = argV[1]; if (tool == "-fc1") return fc1_main(makeArrayRef(argV).slice(2), argV[0]); @@ -73,7 +73,7 @@ llvm::SmallVector args(argv, argv + argc); clang::driver::ParsedClangName targetandMode("flang", "--driver-mode=flang"); - std::string driverPath = GetExecutablePath(args[0]); + std::string driverPath = getExecutablePath(args[0]); // Check if flang-new is in the frontend mode auto firstArg = std::find_if( @@ -86,7 +86,7 @@ } // Call flang-new frontend if (llvm::StringRef(args[1]).startswith("-fc1")) { - return ExecuteFC1Tool(args); + return executeFC1Tool(args); } } @@ -94,14 +94,14 @@ // Create DiagnosticsEngine for the compiler driver llvm::IntrusiveRefCntPtr diagOpts = - CreateAndPopulateDiagOpts(args); + createAndPopulateDiagOpts(args); llvm::IntrusiveRefCntPtr diagID( new clang::DiagnosticIDs()); Fortran::frontend::TextDiagnosticPrinter *diagClient = new Fortran::frontend::TextDiagnosticPrinter(llvm::errs(), &*diagOpts); - diagClient->set_prefix( - std::string(llvm::sys::path::stem(GetExecutablePath(args[0])))); + diagClient->setPrefix( + std::string(llvm::sys::path::stem(getExecutablePath(args[0])))); clang::DiagnosticsEngine diags(diagID, &*diagOpts, diagClient); @@ -120,18 +120,18 @@ res = theDriver.ExecuteCompilation(*c, failingCommands); for (const auto &p : failingCommands) { - int CommandRes = p.first; + int commandRes = p.first; const clang::driver::Command *failingCommand = p.second; if (!res) - res = CommandRes; + res = commandRes; // If result status is < 0 (e.g. when sys::ExecuteAndWait returns -1), // then the driver command signalled an error. On Windows, abort will // return an exit code of 3. In these cases, generate additional diagnostic // information if possible. - isCrash = CommandRes < 0; + isCrash = commandRes < 0; #ifdef _WIN32 - isCrash |= CommandRes == 3; + isCrash |= commandRes == 3; #endif if (isCrash) { theDriver.generateCompilationDiagnostics(*c, *failingCommand); diff --git a/flang/tools/flang-driver/fc1_main.cpp b/flang/tools/flang-driver/fc1_main.cpp --- a/flang/tools/flang-driver/fc1_main.cpp +++ b/flang/tools/flang-driver/fc1_main.cpp @@ -31,8 +31,8 @@ std::unique_ptr flang(new CompilerInstance()); // Create DiagnosticsEngine for the frontend driver - flang->CreateDiagnostics(); - if (!flang->HasDiagnostics()) + flang->createDiagnostics(); + if (!flang->hasDiagnostics()) return 1; // We will buffer diagnostics from argument parsing so that we can output @@ -47,23 +47,23 @@ new clang::DiagnosticOptions(); clang::DiagnosticsEngine diags(diagID, &*diagOpts, diagsBuffer); bool success = - CompilerInvocation::CreateFromArgs(flang->invocation(), argv, diags); + CompilerInvocation::createFromArgs(flang->getInvocation(), argv, diags); // Initialize targets first, so that --version shows registered targets. llvm::InitializeAllTargets(); llvm::InitializeAllTargetMCs(); llvm::InitializeAllAsmPrinters(); - diagsBuffer->FlushDiagnostics(flang->diagnostics()); + diagsBuffer->flushDiagnostics(flang->getDiagnostics()); if (!success) return 1; // Execute the frontend actions. - success = ExecuteCompilerInvocation(flang.get()); + success = executeCompilerInvocation(flang.get()); // Delete output files to free Compiler Instance - flang->ClearOutputFiles(/*EraseFiles=*/false); + flang->clearOutputFiles(/*EraseFiles=*/false); return !success; } diff --git a/flang/unittests/Frontend/.clang-tidy b/flang/unittests/Frontend/.clang-tidy new file mode 100644 --- /dev/null +++ b/flang/unittests/Frontend/.clang-tidy @@ -0,0 +1,9 @@ +Checks: '-readability-braces-around-statements,readability-identifier-naming,llvm-include-order,clang-diagnostic-*' +InheritParentConfig: true +CheckOptions: + - key: readability-identifier-naming.MemberCase + value: camelBack + - key: readability-identifier-naming.ParameterCase + value: camelBack + - key: readability-identifier-naming.VariableCase + value: camelBack diff --git a/flang/unittests/Frontend/CompilerInstanceTest.cpp b/flang/unittests/Frontend/CompilerInstanceTest.cpp --- a/flang/unittests/Frontend/CompilerInstanceTest.cpp +++ b/flang/unittests/Frontend/CompilerInstanceTest.cpp @@ -44,10 +44,10 @@ // 2. Set up CompilerInstance (i.e. specify the input file) std::string buf; - llvm::raw_string_ostream error_stream{buf}; + llvm::raw_string_ostream errorStream{buf}; CompilerInstance compInst; const Fortran::parser::SourceFile *sf = - compInst.allSources().Open(testFilePath, error_stream); + compInst.getAllSources().Open(testFilePath, errorStream); // 3. Verify the content of the input file // This is just a sanity check to make sure that CompilerInstance is capable @@ -82,7 +82,7 @@ // 4. Create a DiagnosticEngine with an unowned consumer IntrusiveRefCntPtr diags = - compInst.CreateDiagnostics(diagOpts, diagPrinter.get(), + compInst.createDiagnostics(diagOpts, diagPrinter.get(), /*ShouldOwnClient=*/false); // 5. Report a diagnostic diff --git a/flang/unittests/Frontend/FrontendActionTest.cpp b/flang/unittests/Frontend/FrontendActionTest.cpp --- a/flang/unittests/Frontend/FrontendActionTest.cpp +++ b/flang/unittests/Frontend/FrontendActionTest.cpp @@ -27,51 +27,51 @@ // AllSources (which is used to manage files inside every compiler // instance), works with paths. So we need a filename and a path for the // input file. - // TODO: We could use `-` for inputFilePath_, but then we'd need a way to + // TODO: We could use `-` for inputFilePath, but then we'd need a way to // write to stdin that's then read by AllSources. Ideally, AllSources should // be capable of reading from any stream. - std::string inputFileName_; - std::string inputFilePath_; + std::string inputFileName; + std::string inputFilePath; // The output stream for the input file. Use this to populate the input. - std::unique_ptr inputFileOs_; + std::unique_ptr inputFileOs; - std::error_code ec_; + std::error_code ec; - CompilerInstance compInst_; - std::shared_ptr invocation_; + CompilerInstance compInst; + std::shared_ptr invoc; void SetUp() override { // Generate a unique test file name. - const testing::TestInfo *const test_info = + const testing::TestInfo *const testInfo = testing::UnitTest::GetInstance()->current_test_info(); - inputFileName_ = std::string(test_info->name()) + "_test-file.f90"; + inputFileName = std::string(testInfo->name()) + "_test-file.f90"; // Create the input file stream. Note that this stream is populated // separately in every test (i.e. the input is test specific). - inputFileOs_ = std::make_unique( - inputFileName_, ec_, llvm::sys::fs::OF_None); - if (ec_) + inputFileOs = std::make_unique( + inputFileName, ec, llvm::sys::fs::OF_None); + if (ec) FAIL() << "Failed to create the input file"; // Get the path of the input file. llvm::SmallString<256> cwd; - if (std::error_code ec_ = llvm::sys::fs::current_path(cwd)) + if (std::error_code ec = llvm::sys::fs::current_path(cwd)) FAIL() << "Failed to obtain the current working directory"; - inputFilePath_ = cwd.c_str(); - inputFilePath_ += "/" + inputFileName_; + inputFilePath = cwd.c_str(); + inputFilePath += "/" + inputFileName; // Prepare the compiler (CompilerInvocation + CompilerInstance) - compInst_.CreateDiagnostics(); - invocation_ = std::make_shared(); + compInst.createDiagnostics(); + invoc = std::make_shared(); - compInst_.set_invocation(std::move(invocation_)); - compInst_.frontendOpts().inputs.push_back( - FrontendInputFile(inputFilePath_, Language::Fortran)); + compInst.setInvocation(std::move(invoc)); + compInst.getFrontendOpts().inputs.push_back( + FrontendInputFile(inputFilePath, Language::Fortran)); } void TearDown() override { // Clear the input file. - llvm::sys::fs::remove(inputFileName_); + llvm::sys::fs::remove(inputFileName); // Clear the output files. // Note that these tests use an output buffer (as opposed to an output @@ -79,27 +79,27 @@ // `EraseFiles` is set to `false`. Also, some actions (e.g. // `ParseSyntaxOnly`) don't generated output. In such cases there's no // output to clear and `ClearOutputFile` returns immediately. - compInst_.ClearOutputFiles(/*EraseFiles=*/false); + compInst.clearOutputFiles(/*EraseFiles=*/false); } }; TEST_F(FrontendActionTest, TestInputOutput) { // Populate the input file with the pre-defined input and flush it. - *(inputFileOs_) << "End Program arithmetic"; - inputFileOs_.reset(); + *(inputFileOs) << "End Program arithmetic"; + inputFileOs.reset(); // Set-up the action kind. - compInst_.invocation().frontendOpts().programAction = InputOutputTest; + compInst.getInvocation().getFrontendOpts().programAction = InputOutputTest; // Set-up the output stream. Using output buffer wrapped as an output // stream, as opposed to an actual file (or a file descriptor). llvm::SmallVector outputFileBuffer; std::unique_ptr outputFileStream( new llvm::raw_svector_ostream(outputFileBuffer)); - compInst_.set_outputStream(std::move(outputFileStream)); + compInst.setOutputStream(std::move(outputFileStream)); // Execute the action. - bool success = ExecuteCompilerInvocation(&compInst_); + bool success = executeCompilerInvocation(&compInst); // Validate the expected output. EXPECT_TRUE(success); @@ -110,26 +110,27 @@ TEST_F(FrontendActionTest, PrintPreprocessedInput) { // Populate the input file with the pre-defined input and flush it. - *(inputFileOs_) << "#ifdef NEW\n" - << " Program A \n" - << "#else\n" - << " Program B\n" - << "#endif"; - inputFileOs_.reset(); + *(inputFileOs) << "#ifdef NEW\n" + << " Program A \n" + << "#else\n" + << " Program B\n" + << "#endif"; + inputFileOs.reset(); // Set-up the action kind. - compInst_.invocation().frontendOpts().programAction = PrintPreprocessedInput; - compInst_.invocation().preprocessorOpts().noReformat = true; + compInst.getInvocation().getFrontendOpts().programAction = + PrintPreprocessedInput; + compInst.getInvocation().getPreprocessorOpts().noReformat = true; // Set-up the output stream. We are using output buffer wrapped as an output // stream, as opposed to an actual file (or a file descriptor). llvm::SmallVector outputFileBuffer; std::unique_ptr outputFileStream( new llvm::raw_svector_ostream(outputFileBuffer)); - compInst_.set_outputStream(std::move(outputFileStream)); + compInst.setOutputStream(std::move(outputFileStream)); // Execute the action. - bool success = ExecuteCompilerInvocation(&compInst_); + bool success = executeCompilerInvocation(&compInst); // Validate the expected output. EXPECT_TRUE(success); @@ -140,21 +141,21 @@ TEST_F(FrontendActionTest, ParseSyntaxOnly) { // Populate the input file with the pre-defined input and flush it. - *(inputFileOs_) << "IF (A > 0.0) IF (B < 0.0) A = LOG (A)\n" - << "END"; - inputFileOs_.reset(); + *(inputFileOs) << "IF (A > 0.0) IF (B < 0.0) A = LOG (A)\n" + << "END"; + inputFileOs.reset(); // Set-up the action kind. - compInst_.invocation().frontendOpts().programAction = ParseSyntaxOnly; + compInst.getInvocation().getFrontendOpts().programAction = ParseSyntaxOnly; // Set-up the output stream for the semantic diagnostics. llvm::SmallVector outputDiagBuffer; std::unique_ptr outputStream( new llvm::raw_svector_ostream(outputDiagBuffer)); - compInst_.set_semaOutputStream(std::move(outputStream)); + compInst.setSemaOutputStream(std::move(outputStream)); // Execute the action. - bool success = ExecuteCompilerInvocation(&compInst_); + bool success = executeCompilerInvocation(&compInst); // Validate the expected output. EXPECT_FALSE(success); @@ -167,14 +168,14 @@ TEST_F(FrontendActionTest, EmitLLVM) { // Populate the input file with the pre-defined input and flush it. - *(inputFileOs_) << "end program"; - inputFileOs_.reset(); + *(inputFileOs) << "end program"; + inputFileOs.reset(); // Set-up the action kind. - compInst_.invocation().frontendOpts().programAction = EmitLLVM; + compInst.getInvocation().getFrontendOpts().programAction = EmitLLVM; // Set-up default target triple. - compInst_.invocation().targetOpts().triple = + compInst.getInvocation().getTargetOpts().triple = llvm::Triple::normalize(llvm::sys::getDefaultTargetTriple()); // Set-up the output stream. We are using output buffer wrapped as an output @@ -182,10 +183,10 @@ llvm::SmallVector outputFileBuffer; std::unique_ptr outputFileStream( new llvm::raw_svector_ostream(outputFileBuffer)); - compInst_.set_outputStream(std::move(outputFileStream)); + compInst.setOutputStream(std::move(outputFileStream)); // Execute the action. - bool success = ExecuteCompilerInvocation(&compInst_); + bool success = executeCompilerInvocation(&compInst); // Validate the expected output. EXPECT_TRUE(success); @@ -197,14 +198,14 @@ TEST_F(FrontendActionTest, EmitAsm) { // Populate the input file with the pre-defined input and flush it. - *(inputFileOs_) << "end program"; - inputFileOs_.reset(); + *(inputFileOs) << "end program"; + inputFileOs.reset(); // Set-up the action kind. - compInst_.invocation().frontendOpts().programAction = EmitAssembly; + compInst.getInvocation().getFrontendOpts().programAction = EmitAssembly; // Set-up default target triple. - compInst_.invocation().targetOpts().triple = + compInst.getInvocation().getTargetOpts().triple = llvm::Triple::normalize(llvm::sys::getDefaultTargetTriple()); // Initialise LLVM backend @@ -217,10 +218,10 @@ llvm::SmallVector outputFileBuffer; std::unique_ptr outputFileStream( new llvm::raw_svector_ostream(outputFileBuffer)); - compInst_.set_outputStream(std::move(outputFileStream)); + compInst.setOutputStream(std::move(outputFileStream)); // Execute the action. - bool success = ExecuteCompilerInvocation(&compInst_); + bool success = executeCompilerInvocation(&compInst); // Validate the expected output. EXPECT_TRUE(success);