Convert llvmc to use the lib/System interface instead of directly

using Unix operating system calls.


git-svn-id: https://llvm.org/svn/llvm-project/llvm/trunk@16089 91177308-0d34-0410-b5e6-96231b3b80d8
This commit is contained in:
Reid Spencer 2004-08-29 19:26:56 +00:00
parent bd4dd5c33a
commit 52c2dc1a42
9 changed files with 711 additions and 712 deletions

File diff suppressed because it is too large Load Diff

View File

@ -16,7 +16,7 @@
#include <string>
#include <vector>
#include "Support/SetVector.h"
#include "llvm/System/Program.h"
namespace llvm {
/// This class provides the high level interface to the LLVM Compiler Driver.
@ -30,9 +30,12 @@ namespace llvm {
/// @name Types
/// @{
public:
/// @brief A vector of strings, commonly used
/// @brief A vector of strings, used for argument lists
typedef std::vector<std::string> StringVector;
/// @brief A vector of sys::Path, used for path lists
typedef std::vector<sys::Path> PathVector;
/// @brief A table of strings, indexed typically by Phases
typedef std::vector<StringVector> StringTable;
@ -65,11 +68,26 @@ namespace llvm {
FLAGS_MASK = 0x000F, ///< Union of all flags
};
/// @brief Driver specific flags
enum DriverFlags {
DRY_RUN_FLAG = 0x0001, ///< Do everything but execute actions
FORCE_FLAG = 0x0002, ///< Force overwrite of output files
VERBOSE_FLAG = 0x0004, ///< Print each action
DEBUG_FLAG = 0x0008, ///< Print debug information
TIME_PASSES_FLAG = 0x0010, ///< Time the passes as they execute
TIME_ACTIONS_FLAG = 0x0020, ///< Time the actions as they execute
SHOW_STATS_FLAG = 0x0040, ///< Show pass statistics
EMIT_NATIVE_FLAG = 0x0080, ///< Emit native code instead of bc
EMIT_RAW_FLAG = 0x0100, ///< Emit raw, unoptimized bytecode
KEEP_TEMPS_FLAG = 0x0200, ///< Don't delete temporary files
DRIVER_FLAGS_MASK = 0x02FF, ///< Union of the above flags
};
/// This type is the input list to the CompilerDriver. It provides
/// a vector of filename/filetype pairs. The filetype is used to look up
/// a vector of pathname/filetype pairs. The filetype is used to look up
/// the configuration of the actions to be taken by the driver.
/// @brief The Input Data to the execute method
typedef std::vector<std::pair<std::string,std::string> > InputList;
typedef std::vector<std::pair<sys::Path,std::string> > InputList;
/// This type is read from configuration files or otherwise provided to
/// the CompilerDriver through a "ConfigDataProvider". It serves as both
@ -78,7 +96,7 @@ namespace llvm {
/// language.
struct Action {
Action() : flags(0) {}
std::string program; ///< The program to execve
sys::Program program; ///< The program to execve
StringVector args; ///< Arguments to the program
unsigned flags; ///< Action specific flags
void set(unsigned fl ) { flags |= fl; }
@ -107,127 +125,49 @@ namespace llvm {
class ConfigDataProvider {
public:
virtual ConfigData* ProvideConfigData(const std::string& filetype) = 0;
virtual void setConfigDir(const std::string& dirName) = 0;
virtual void setConfigDir(const sys::Path& dirName) = 0;
};
/// @}
/// @name Constructors
/// @{
public:
CompilerDriver(ConfigDataProvider& cdp );
/// @brief Static Constructor
static CompilerDriver* Get(ConfigDataProvider& CDP);
/// @brief Virtual destructor
virtual ~CompilerDriver();
/// @}
/// @name Methods
/// @{
public:
/// @brief Handle an error
virtual void error(const std::string& errmsg);
/// @brief Execute the actions requested for the given input list.
virtual int execute(const InputList& list, const std::string& output);
virtual int execute(const InputList& list, const sys::Path& output) = 0;
/// @}
/// @name Mutators
/// @{
public:
/// @brief Set the final phase at which compilation terminates
void setFinalPhase( Phases phase ) { finalPhase = phase; }
virtual void setFinalPhase(Phases phase) = 0;
/// @brief Set the optimization level for the compilation
void setOptimization( OptimizationLevels level ) { optLevel = level; }
virtual void setOptimization(OptimizationLevels level) = 0;
/// @brief Prevent the CompilerDriver from taking any actions
void setDryRun( bool TF ) { isDryRun = TF; }
/// @brief Cause the CompilerDriver to print to stderr all the
/// actions it is taking.
void setVerbose( bool TF ) { isVerbose = TF; }
/// @brief Cause the CompilerDriver to print to stderr very verbose
/// information that might be useful in debugging the driver's actions
void setDebug( bool TF ) { isDebug = TF; }
/// @brief Cause the CompilerDriver to print to stderr the
/// execution time of each action taken.
void setTimeActions( bool TF ) { timeActions = TF; }
/// @brief Cause the CompilerDriver to print timings for each pass.
void setTimePasses( bool TF ) { timePasses = TF; }
/// @brief Cause the CompilerDriver to show statistics gathered
void setShowStats( bool TF ) { showStats = TF; }
/// @brief Indicate that native code is to be generated instead
/// of LLVM bytecode.
void setEmitNativeCode( bool TF ) { emitNativeCode = TF; }
/// @brief Indicate that raw, unoptimized code is to be generated.
void setEmitRawCode(bool TF ) { emitRawCode = TF; }
void setKeepTemporaries(bool TF) { keepTemps = TF; }
/// @brief Set the driver flags.
virtual void setDriverFlags(unsigned flags) = 0;
/// @brief Set the output machine name.
void setOutputMachine( const std::string& machineName ) {
machine = machineName;
}
virtual void setOutputMachine(const std::string& machineName) = 0;
/// @brief Set Preprocessor specific options
void setPhaseArgs(Phases phase, const std::vector<std::string>& opts) {
assert(phase <= LINKING && phase >= PREPROCESSING);
AdditionalArgs[phase] = opts;
}
virtual void setPhaseArgs(Phases phase, const StringVector& opts) = 0;
/// @brief Set Library Paths
void setLibraryPaths(const std::vector<std::string>& paths) {
LibraryPaths = paths;
}
virtual void setLibraryPaths(const StringVector& paths) = 0;
/// @brief Set the list of library paths to be searched for
/// libraries.
void addLibraryPath( const std::string& libPath ) {
LibraryPaths.push_back(libPath);
}
virtual void addLibraryPath( const sys::Path& libPath ) = 0;
/// @}
/// @name Functions
/// @{
private:
Action* GetAction(ConfigData* cd, const std::string& input,
const std::string& output, Phases phase );
bool DoAction(Action* a);
std::string GetPathForLinkageItem(const std::string& link_item,
const std::string& dir);
bool ProcessLinkageItem(const std::string& link_item,
SetVector<std::string>& set,
std::string& err);
/// @}
/// @name Data
/// @{
private:
ConfigDataProvider* cdp; ///< Where we get configuration data from
Phases finalPhase; ///< The final phase of compilation
OptimizationLevels optLevel; ///< The optimization level to apply
bool isDryRun; ///< Prevent actions ?
bool isVerbose; ///< Print actions?
bool isDebug; ///< Print lotsa debug info?
bool timeActions; ///< Time the actions executed ?
bool timePasses; ///< Time each pass and print timing ?
bool showStats; ///< Show gathered statistics ?
bool emitRawCode; ///< Emit Raw (unoptimized) code?
bool emitNativeCode; ///< Emit native code instead of bytecode?
bool keepTemps; ///< Keep temporary files?
std::string machine; ///< Target machine name
StringVector LibraryPaths; ///< -L options
StringTable AdditionalArgs; ///< The -Txyz options
std::string TempDir; ///< Name of the temporary directory.
/// @}
};
}

View File

@ -57,6 +57,7 @@ enum ConfigLexerTokens {
COMMAND, ///< The name "command" (and variants)
EQUALS, ///< The equals sign, =
FALSETOK, ///< A boolean false value (false/no/off)
FORCE_SUBST, ///< The substitution item %force%
IN_SUBST, ///< The substitution item %in%
INTEGER, ///< An integer
LANG, ///< The name "lang" (and variants)
@ -85,6 +86,7 @@ enum ConfigLexerTokens {
TRANSLATES, ///< The name "translates" (and variants)
TRANSLATOR, ///< The name "translator" (and variants)
TRUETOK, ///< A boolean true value (true/yes/on)
VERBOSE_SUBST,///< The substitution item %verbose%
VERSION, ///< The name "version" (and variants)
};

View File

@ -160,12 +160,14 @@ White [ \t]*
{LINKER} { return handleNameContext(LINKER); }
%args% { return handleSubstitution(ARGS_SUBST); }
%force% { return handleSubstitution(FORCE_SUBST); }
%in% { return handleSubstitution(IN_SUBST); }
%out% { return handleSubstitution(OUT_SUBST); }
%time% { return handleSubstitution(TIME_SUBST); }
%stats% { return handleSubstitution(STATS_SUBST); }
%opt% { return handleSubstitution(OPT_SUBST); }
%out% { return handleSubstitution(OUT_SUBST); }
%stats% { return handleSubstitution(STATS_SUBST); }
%target% { return handleSubstitution(TARGET_SUBST); }
%time% { return handleSubstitution(TIME_SUBST); }
%verbose% { return handleSubstitution(VERBOSE_SUBST); }
{BadSubst} { YY_FATAL_ERROR("Invalid substitution token"); }
{Assembly} { return handleValueContext(ASSEMBLY); }

View File

@ -90,19 +90,19 @@ namespace {
InputProvider* provider;
CompilerDriver::ConfigData* confDat;
int next() {
inline int next() {
token = Configlex();
if (DumpTokens)
std::cerr << token << "\n";
return token;
}
bool next_is_real() {
inline bool next_is_real() {
next();
return (token != EOLTOK) && (token != ERRORTOK) && (token != 0);
}
void eatLineRemnant() {
inline void eatLineRemnant() {
while (next_is_real()) ;
}
@ -162,6 +162,8 @@ namespace {
case STATS_SUBST: optList.push_back("%stats%"); break;
case OPT_SUBST: optList.push_back("%opt%"); break;
case TARGET_SUBST: optList.push_back("%target%"); break;
case FORCE_SUBST: optList.push_back("%force%"); break;
case VERBOSE_SUBST: optList.push_back("%verbose%"); break;
default:
return false;
}
@ -229,7 +231,7 @@ namespace {
action.args.clear();
} else {
if (token == STRING || token == OPTION) {
action.program = ConfigLexerState.StringVal;
action.program.set_file(ConfigLexerState.StringVal);
} else {
error("Expecting a program name");
}
@ -415,42 +417,46 @@ namespace {
CompilerDriver::ConfigData*
LLVMC_ConfigDataProvider::ReadConfigData(const std::string& ftype) {
CompilerDriver::ConfigData* result = 0;
std::string dir_name;
if (configDir.empty()) {
sys::Path confFile;
if (configDir.is_empty()) {
// Try the environment variable
const char* conf = getenv("LLVM_CONFIG_DIR");
if (conf) {
dir_name = conf;
dir_name += "/";
if (!::sys::FileIsReadable(dir_name + ftype))
confFile.set_directory(conf);
confFile.append_file(ftype);
if (!confFile.readable())
throw "Configuration file for '" + ftype + "' is not available.";
} else {
// Try the user's home directory
const char* home = getenv("HOME");
if (home) {
dir_name = home;
dir_name += "/.llvm/etc/";
if (!::sys::FileIsReadable(dir_name + ftype)) {
// Okay, try the LLVM installation directory
dir_name = LLVM_ETCDIR;
dir_name += "/";
if (!::sys::FileIsReadable(dir_name + ftype)) {
// Okay, try the "standard" place
dir_name = "/etc/llvm/";
if (!::sys::FileIsReadable(dir_name + ftype)) {
throw "Configuration file for '" + ftype + "' is not available.";
}
confFile = sys::Path::GetUserHomeDirectory();
if (!confFile.is_empty()) {
confFile.append_directory(".llvm");
confFile.append_directory("etc");
confFile.append_file(ftype);
if (!confFile.readable())
confFile.clear();
}
if (!confFile.is_empty()) {
// Okay, try the LLVM installation directory
confFile = sys::Path::GetLLVMConfigDir();
confFile.append_file(ftype);
if (!confFile.readable()) {
// Okay, try the "standard" place
confFile = sys::Path::GetLLVMDefaultConfigDir();
confFile.append_file(ftype);
if (!confFile.readable()) {
throw "Configuration file for '" + ftype + "' is not available.";
}
}
}
}
} else {
dir_name = configDir + "/";
if (!::sys::FileIsReadable(dir_name + ftype)) {
confFile = configDir;
confFile.append_file(ftype);
if (!confFile.readable())
throw "Configuration file for '" + ftype + "' is not available.";
}
}
FileInputProvider fip( dir_name + ftype );
FileInputProvider fip( confFile.get() );
if (!fip.okay()) {
throw "Configuration file for '" + ftype + "' is not available.";
}
@ -459,13 +465,6 @@ LLVMC_ConfigDataProvider::ReadConfigData(const std::string& ftype) {
return result;
}
LLVMC_ConfigDataProvider::LLVMC_ConfigDataProvider()
: Configurations()
, configDir()
{
Configurations.clear();
}
LLVMC_ConfigDataProvider::~LLVMC_ConfigDataProvider()
{
ConfigDataMap::iterator cIt = Configurations.begin();
@ -491,7 +490,7 @@ LLVMC_ConfigDataProvider::ProvideConfigData(const std::string& filetype) {
// The configuration data doesn't exist, we have to go read it.
result = ReadConfigData(filetype);
// If we got one, cache it
if ( result != 0 )
if (result != 0)
Configurations.insert(std::make_pair(filetype,result));
}
return result; // Might return 0

View File

@ -29,7 +29,6 @@ namespace llvm {
/// @name Constructor
/// @{
public:
LLVMC_ConfigDataProvider();
virtual ~LLVMC_ConfigDataProvider();
/// @name Methods
@ -40,7 +39,9 @@ namespace llvm {
ProvideConfigData(const std::string& filetype);
/// @brief Allow the configuration directory to be set
virtual void setConfigDir(const std::string& dirName) { configDir = dirName; }
virtual void setConfigDir(const sys::Path& dirName) {
configDir = dirName;
}
private:
CompilerDriver::ConfigData* ReadConfigData(const std::string& ftype);
@ -53,7 +54,7 @@ namespace llvm {
typedef hash_map<std::string,CompilerDriver::ConfigData*,
hash<std::string>,std::equal_to<std::string> > ConfigDataMap;
ConfigDataMap Configurations; ///< The cache of configurations
std::string configDir;
sys::Path configDir;
/// @}
};
}

View File

@ -8,7 +8,7 @@
##===----------------------------------------------------------------------===##
LEVEL = ../..
TOOLNAME = llvmc
USEDLIBS = bcreader vmcore support.a
USEDLIBS = bcreader vmcore support.a LLVMsystem.a
CONFIG_FILES = st ll
include $(LEVEL)/Makefile.common

View File

@ -108,6 +108,9 @@ cl::list<std::string> Libraries("l", cl::Prefix,
cl::opt<std::string> OutputFilename("o",
cl::desc("Override output filename"), cl::value_desc("filename"));
cl::opt<bool> ForceOutput("f", cl::Optional, cl::init(false),
cl::desc("Force output files to be overridden"));
cl::opt<std::string> OutputMachine("m", cl::Prefix,
cl::desc("Specify a target machine"), cl::value_desc("machine"));
@ -156,7 +159,7 @@ static cl::opt<bool> EmitRawCode("emit-raw-code", cl::Hidden, cl::Optional,
static cl::opt<bool> PipeCommands("pipe", cl::Optional,
cl::desc("Invoke sub-commands by linking input/output with pipes"));
static cl::opt<bool> KeepTemporaries("keep-temps", cl::Optional,
static cl::opt<bool> KeepTemps("keep-temps", cl::Optional,
cl::desc("Don't delete the temporary files created during compilation"));
//===------------------------------------------------------------------------===
@ -199,15 +202,16 @@ const std::string GetFileType(const std::string& fname, unsigned pos ) {
/// @brief The main program for llvmc
int main(int argc, char **argv) {
// Make sure we print stack trace if we get bad signals
sys::PrintStackTraceOnErrorSignal();
try {
// Make sure we print stack trace if we get bad signals
PrintStackTraceOnErrorSignal();
// Parse the command line options
cl::ParseCommandLineOptions(argc, argv,
" LLVM Compilation Driver (llvmc)\n\n"
" LLVM Compiler Driver (llvmc)\n\n"
" This program provides easy invocation of the LLVM tool set\n"
" and source language compiler tools.\n"
" and other compiler tools.\n"
);
// Deal with unimplemented options.
@ -220,13 +224,12 @@ int main(int argc, char **argv) {
else
throw "An output file must be specified. Please use the -o option";
// Construct the ConfigDataProvider object
LLVMC_ConfigDataProvider Provider;
Provider.setConfigDir(ConfigDir);
Provider.setConfigDir(sys::Path(ConfigDir));
// Construct the CompilerDriver object
CompilerDriver CD(Provider);
CompilerDriver* CD = CompilerDriver::Get(Provider);
// If the LLVM_LIB_SEARCH_PATH environment variable is
// set, append it to the list of places to search for libraries
@ -234,30 +237,37 @@ int main(int argc, char **argv) {
if (!srchPath.empty())
LibPaths.push_back(srchPath);
// Configure the driver based on options
CD.setVerbose(Verbose);
CD.setDebug(Debug);
CD.setDryRun(DryRun);
CD.setFinalPhase(FinalPhase);
CD.setOptimization(OptLevel);
CD.setOutputMachine(OutputMachine);
CD.setEmitNativeCode(Native);
CD.setEmitRawCode(EmitRawCode);
CD.setTimeActions(TimeActions);
CD.setTimePasses(TimePassesIsEnabled);
CD.setShowStats(ShowStats);
CD.setKeepTemporaries(KeepTemporaries);
CD.setLibraryPaths(LibPaths);
// Set the driver flags based on command line options
unsigned flags = 0;
if (Verbose) flags |= CompilerDriver::VERBOSE_FLAG;
if (Debug) flags |= CompilerDriver::DEBUG_FLAG;
if (DryRun) flags |= CompilerDriver::DRY_RUN_FLAG;
if (ForceOutput) flags |= CompilerDriver::FORCE_FLAG;
if (Native) flags |= CompilerDriver::EMIT_NATIVE_FLAG;
if (EmitRawCode) flags |= CompilerDriver::EMIT_RAW_FLAG;
if (KeepTemps) flags |= CompilerDriver::KEEP_TEMPS_FLAG;
if (ShowStats) flags |= CompilerDriver::SHOW_STATS_FLAG;
if (TimeActions) flags |= CompilerDriver::TIME_ACTIONS_FLAG;
if (TimePassesIsEnabled) flags |= CompilerDriver::TIME_PASSES_FLAG;
CD->setDriverFlags(flags);
// Specify requred parameters
CD->setFinalPhase(FinalPhase);
CD->setOptimization(OptLevel);
CD->setOutputMachine(OutputMachine);
CD->setLibraryPaths(LibPaths);
// Provide additional tool arguments
if (!PreprocessorToolOpts.empty())
CD.setPhaseArgs(CompilerDriver::PREPROCESSING, PreprocessorToolOpts);
CD->setPhaseArgs(CompilerDriver::PREPROCESSING, PreprocessorToolOpts);
if (!TranslatorToolOpts.empty())
CD.setPhaseArgs(CompilerDriver::TRANSLATION, TranslatorToolOpts);
CD->setPhaseArgs(CompilerDriver::TRANSLATION, TranslatorToolOpts);
if (!OptimizerToolOpts.empty())
CD.setPhaseArgs(CompilerDriver::OPTIMIZATION, OptimizerToolOpts);
CD->setPhaseArgs(CompilerDriver::OPTIMIZATION, OptimizerToolOpts);
if (!AssemblerToolOpts.empty())
CD.setPhaseArgs(CompilerDriver::ASSEMBLY,AssemblerToolOpts);
CD->setPhaseArgs(CompilerDriver::ASSEMBLY,AssemblerToolOpts);
if (!LinkerToolOpts.empty())
CD.setPhaseArgs(CompilerDriver::LINKING, LinkerToolOpts);
CD->setPhaseArgs(CompilerDriver::LINKING, LinkerToolOpts);
// Prepare the list of files to be compiled by the CompilerDriver.
CompilerDriver::InputList InpList;
@ -288,7 +298,7 @@ int main(int argc, char **argv) {
}
// Tell the driver to do its thing
int result = CD.execute(InpList,OutputFilename);
int result = CD->execute(InpList,sys::Path(OutputFilename));
if (result != 0) {
throw "Error executing actions. Terminated.\n";
return result;

View File

@ -34,7 +34,7 @@
# To compile stacker source, we just run the stacker
# compiler with a default stack size of 2048 entries.
translator.command=stkrc -s 2048 %in% -o %out% %time% \
%stats% %args%
%stats% %force% %args%
# stkrc doesn't preprocess but we set this to true so
# that we don't run the cp command by default.
@ -52,7 +52,7 @@
# For optimization, we use the LLVM "opt" program
optimizer.command=opt %in% -o %out% %opt% %time% %stats% \
%args%
%force% %args%
optimizer.required = true