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

View File

@@ -14,26 +14,19 @@
#include "CompilerDriver.h" #include "CompilerDriver.h"
#include "ConfigLexer.h" #include "ConfigLexer.h"
#include "llvm/Bytecode/Reader.h"
#include "llvm/Module.h" #include "llvm/Module.h"
#include "llvm/Bytecode/Reader.h"
#include "Support/FileUtilities.h" #include "Support/FileUtilities.h"
#include "Support/SystemUtils.h" #include "Support/SetVector.h"
#include "Support/StringExtras.h" #include "Support/StringExtras.h"
#include <iostream> #include <iostream>
using namespace llvm; using namespace llvm;
namespace { namespace {
inline std::string RemoveSuffix(const std::string& fullName) {
size_t dotpos = fullName.rfind('.',fullName.size());
if ( dotpos == std::string::npos ) return fullName;
return fullName.substr(0, dotpos);
}
const char OutputSuffix[] = ".o";
void WriteAction(CompilerDriver::Action* action ) { void WriteAction(CompilerDriver::Action* action ) {
std::cerr << action->program; std::cerr << action->program.c_str();
std::vector<std::string>::iterator I = action->args.begin(); std::vector<std::string>::iterator I = action->args.begin();
while (I != action->args.end()) { while (I != action->args.end()) {
std::cerr << " " + *I; std::cerr << " " + *I;
@@ -43,7 +36,7 @@ namespace {
} }
void DumpAction(CompilerDriver::Action* action) { void DumpAction(CompilerDriver::Action* action) {
std::cerr << "command = " << action->program; std::cerr << "command = " << action->program.c_str();
std::vector<std::string>::iterator I = action->args.begin(); std::vector<std::string>::iterator I = action->args.begin();
while (I != action->args.end()) { while (I != action->args.end()) {
std::cerr << " " + *I; std::cerr << " " + *I;
@@ -74,118 +67,107 @@ namespace {
static const char* DefaultFastCompileOptimizations[] = { static const char* DefaultFastCompileOptimizations[] = {
"-simplifycfg", "-mem2reg", "-instcombine" "-simplifycfg", "-mem2reg", "-instcombine"
}; };
}
// Stuff in this namespace properly belongs in lib/System and needs class CompilerDriverImpl : public CompilerDriver {
// to be portable but we're avoiding that for now. /// @name Constructors
namespace sys { /// @{
public:
bool FileIsReadable(const std::string& fname) { CompilerDriverImpl(ConfigDataProvider& confDatProv )
return 0 == access(fname.c_str(), F_OK | R_OK);
}
void CleanupTempFile(const std::string& fname) {
if (FileIsReadable(fname))
unlink(fname.c_str());
}
std::string MakeTemporaryDirectory() {
char temp_name[64];
strcpy(temp_name,"/tmp/llvm_XXXXXX");
if (0 == mkdtemp(temp_name))
throw std::string("Can't create temporary directory");
return temp_name;
}
std::string FindExecutableInPath(const std::string& program) {
// First, just see if the program is already executable
if (isExecutableFile(program)) return program;
// Get the path. If its empty, we can't do anything
const char *PathStr = getenv("PATH");
if (PathStr == 0) return "";
// Now we have a colon separated list of directories to search; try them.
unsigned PathLen = strlen(PathStr);
while (PathLen) {
// Find the first colon...
const char *Colon = std::find(PathStr, PathStr+PathLen, ':');
// Check to see if this first directory contains the executable...
std::string FilePath = std::string(PathStr, Colon) + '/' + program;
if (isExecutableFile(FilePath))
return FilePath; // Found the executable!
// Nope it wasn't in this directory, check the next range!
PathLen -= Colon-PathStr;
PathStr = Colon;
// Advance past duplicate coons
while (*PathStr == ':') {
PathStr++;
PathLen--;
}
}
// If we fell out, we ran out of directories in PATH to search, return failure
return "";
}
}
CompilerDriver::CompilerDriver(ConfigDataProvider& confDatProv )
: cdp(&confDatProv) : cdp(&confDatProv)
, finalPhase(LINKING) , finalPhase(LINKING)
, optLevel(OPT_FAST_COMPILE) , optLevel(OPT_FAST_COMPILE)
, isDryRun(false) , Flags(0)
, isVerbose(false)
, isDebug(false)
, timeActions(false)
, emitRawCode(false)
, emitNativeCode(false)
, keepTemps(false)
, machine() , machine()
, LibraryPaths() , LibraryPaths()
, AdditionalArgs()
, TempDir() , TempDir()
{ , AdditionalArgs()
// FIXME: These libraries are platform specific {
LibraryPaths.push_back("/lib"); TempDir = sys::Path::GetTemporaryDirectory();
LibraryPaths.push_back("/usr/lib"); sys::RemoveDirectoryOnSignal(TempDir);
AdditionalArgs.reserve(NUM_PHASES); AdditionalArgs.reserve(NUM_PHASES);
StringVector emptyVec; StringVector emptyVec;
for (unsigned i = 0; i < NUM_PHASES; ++i) for (unsigned i = 0; i < NUM_PHASES; ++i)
AdditionalArgs.push_back(emptyVec); AdditionalArgs.push_back(emptyVec);
} }
CompilerDriver::~CompilerDriver() { virtual ~CompilerDriverImpl() {
cleanup();
cdp = 0; cdp = 0;
LibraryPaths.clear(); LibraryPaths.clear();
AdditionalArgs.clear(); AdditionalArgs.clear();
} }
CompilerDriver::ConfigData::ConfigData() /// @}
: langName() /// @name Methods
, PreProcessor() /// @{
, Translator() public:
, Optimizer() virtual void setFinalPhase( Phases phase ) {
, Assembler() finalPhase = phase;
, Linker() }
{
StringVector emptyVec;
for (unsigned i = 0; i < NUM_PHASES; ++i)
opts.push_back(emptyVec);
}
void CompilerDriver::error( const std::string& errmsg ) { virtual void setOptimization( OptimizationLevels level ) {
std::cerr << "llvmc: Error: " << errmsg << ".\n"; optLevel = level;
exit(1); }
}
CompilerDriver::Action* CompilerDriver::GetAction(ConfigData* cd, virtual void setDriverFlags( unsigned flags ) {
const std::string& input, Flags = flags & DRIVER_FLAGS_MASK;
const std::string& output, }
virtual void setOutputMachine( const std::string& machineName ) {
machine = machineName;
}
virtual void setPhaseArgs(Phases phase, const StringVector& opts) {
assert(phase <= LINKING && phase >= PREPROCESSING);
AdditionalArgs[phase] = opts;
}
virtual void setLibraryPaths(const StringVector& paths) {
StringVector::const_iterator I = paths.begin();
StringVector::const_iterator E = paths.end();
while (I != E) {
sys::Path tmp;
tmp.set_directory(*I);
LibraryPaths.push_back(tmp);
++I;
}
}
virtual void addLibraryPath( const sys::Path& libPath ) {
LibraryPaths.push_back(libPath);
}
/// @}
/// @name Functions
/// @{
private:
bool isSet(DriverFlags flag) {
return 0 != ((flag & DRIVER_FLAGS_MASK) & Flags);
}
void cleanup() {
if (!isSet(KEEP_TEMPS_FLAG)) {
if (TempDir.is_directory() && TempDir.writable())
TempDir.destroy_directory(/*remove_contents=*/true);
} else {
std::cout << "Temporary files are in " << TempDir.get() << "\n";
}
}
sys::Path MakeTempFile(const std::string& basename, const std::string& suffix ) {
sys::Path result(TempDir);
if (!result.append_file(basename))
throw basename + ": can't use this file name";
if (!result.append_suffix(suffix))
throw suffix + ": can't use this file suffix";
return result;
}
Action* GetAction(ConfigData* cd,
const sys::Path& input,
const sys::Path& output,
Phases phase) Phases phase)
{ {
Action* pat = 0; ///< The pattern/template for the action Action* pat = 0; ///< The pattern/template for the action
Action* action = new Action; ///< The actual action to execute Action* action = new Action; ///< The actual action to execute
@@ -212,26 +194,32 @@ CompilerDriver::Action* CompilerDriver::GetAction(ConfigData* cd,
while (PI != PE) { while (PI != PE) {
if ((*PI)[0] == '%') { if ((*PI)[0] == '%') {
if (*PI == "%in%") { if (*PI == "%in%") {
action->args.push_back(input); action->args.push_back(input.get());
} else if (*PI == "%out%") { } else if (*PI == "%out%") {
action->args.push_back(output); action->args.push_back(output.get());
} else if (*PI == "%time%") { } else if (*PI == "%time%") {
if (timePasses) if (isSet(TIME_PASSES_FLAG))
action->args.push_back("-time-passes"); action->args.push_back("-time-passes");
} else if (*PI == "%stats%") { } else if (*PI == "%stats%") {
if (showStats) if (isSet(SHOW_STATS_FLAG))
action->args.push_back("-stats"); action->args.push_back("-stats");
} else if (*PI == "%force%") {
if (isSet(FORCE_FLAG))
action->args.push_back("-f");
} else if (*PI == "%verbose%") {
if (isSet(VERBOSE_FLAG))
action->args.push_back("-v");
} else if (*PI == "%target%") { } else if (*PI == "%target%") {
// FIXME: Ignore for now // FIXME: Ignore for now
} else if (*PI == "%opt%") { } else if (*PI == "%opt%") {
if (!emitRawCode) { if (!isSet(EMIT_RAW_FLAG)) {
if (cd->opts.size() > static_cast<unsigned>(optLevel) && if (cd->opts.size() > static_cast<unsigned>(optLevel) &&
!cd->opts[optLevel].empty()) !cd->opts[optLevel].empty())
action->args.insert(action->args.end(), cd->opts[optLevel].begin(), action->args.insert(action->args.end(), cd->opts[optLevel].begin(),
cd->opts[optLevel].end()); cd->opts[optLevel].end());
else else
error("Optimization options for level " + utostr(unsigned(optLevel)) + throw std::string("Optimization options for level ") +
" were not specified"); utostr(unsigned(optLevel)) + " were not specified";
} }
} else if (*PI == "%args%") { } else if (*PI == "%args%") {
if (AdditionalArgs.size() > unsigned(phase)) if (AdditionalArgs.size() > unsigned(phase))
@@ -242,7 +230,7 @@ CompilerDriver::Action* CompilerDriver::GetAction(ConfigData* cd,
action->args.insert(action->args.end(), addargs.begin(), addargs.end()); action->args.insert(action->args.end(), addargs.begin(), addargs.end());
} }
} else { } else {
error("Invalid substitution name" + *PI); throw "Invalid substitution name" + *PI;
} }
} else { } else {
// Its not a substitution, just put it in the action // Its not a substitution, just put it in the action
@@ -254,75 +242,76 @@ CompilerDriver::Action* CompilerDriver::GetAction(ConfigData* cd,
// Finally, we're done // Finally, we're done
return action; return action;
} }
bool CompilerDriver::DoAction(Action*action) { bool DoAction(Action*action) {
assert(action != 0 && "Invalid Action!"); assert(action != 0 && "Invalid Action!");
if (isVerbose) if (isSet(VERBOSE_FLAG))
WriteAction(action); WriteAction(action);
if (!isDryRun) { if (!isSet(DRY_RUN_FLAG)) {
std::string prog(sys::FindExecutableInPath(action->program)); action->program = sys::Program::FindProgramByName(action->program.get());
if (prog.empty()) if (action->program.is_empty())
error("Can't find program '" + action->program + "'"); throw "Can't find program '" + action->program.get() + "'";
// Get the program's arguments
const char* argv[action->args.size() + 1];
argv[0] = prog.c_str();
unsigned i = 1;
for (; i <= action->args.size(); ++i)
argv[i] = action->args[i-1].c_str();
argv[i] = 0;
// Invoke the program // Invoke the program
return !ExecWait(argv, environ); return 0 == action->program.ExecuteAndWait(action->args);
} }
return true; return true;
} }
/// This method tries various variants of a linkage item's file /// This method tries various variants of a linkage item's file
/// name to see if it can find an appropriate file to link with /// name to see if it can find an appropriate file to link with
/// in the directory specified. /// in the directory specified.
std::string CompilerDriver::GetPathForLinkageItem(const std::string& link_item, llvm::sys::Path GetPathForLinkageItem(const std::string& link_item,
const std::string& dir) { const sys::Path& dir) {
std::string fullpath(dir + "/" + link_item + ".o"); sys::Path fullpath(dir);
if (::sys::FileIsReadable(fullpath)) fullpath.append_file(link_item);
fullpath.append_suffix("bc");
if (fullpath.readable())
return fullpath; return fullpath;
fullpath = dir + "/" + link_item + ".bc"; fullpath.elide_suffix();
if (::sys::FileIsReadable(fullpath)) fullpath.append_suffix("o");
if (fullpath.readable())
return fullpath; return fullpath;
fullpath = dir + "/lib" + link_item + ".a"; fullpath = dir;
if (::sys::FileIsReadable(fullpath)) fullpath.append_file(std::string("lib") + link_item);
fullpath.append_suffix("a");
if (fullpath.readable())
return fullpath; return fullpath;
fullpath = dir + "/lib" + link_item + ".so"; fullpath.elide_suffix();
if (::sys::FileIsReadable(fullpath)) fullpath.append_suffix("so");
if (fullpath.readable())
return fullpath; return fullpath;
return "";
}
/// This method processes a linkage item. The item could be a // Didn't find one.
/// Bytecode file needing translation to native code and that is fullpath.clear();
/// dependent on other bytecode libraries, or a native code return fullpath;
/// library that should just be linked into the program. }
bool CompilerDriver::ProcessLinkageItem(const std::string& link_item,
SetVector<std::string>& set, /// This method processes a linkage item. The item could be a
/// Bytecode file needing translation to native code and that is
/// dependent on other bytecode libraries, or a native code
/// library that should just be linked into the program.
bool ProcessLinkageItem(const llvm::sys::Path& link_item,
SetVector<sys::Path>& set,
std::string& err) { std::string& err) {
// First, see if the unadorned file name is not readable. If so, // First, see if the unadorned file name is not readable. If so,
// we must track down the file in the lib search path. // we must track down the file in the lib search path.
std::string fullpath; sys::Path fullpath;
if (!sys::FileIsReadable(link_item)) { if (!link_item.readable()) {
// First, look for the library using the -L arguments specified // First, look for the library using the -L arguments specified
// on the command line. // on the command line.
StringVector::iterator PI = LibraryPaths.begin(); PathVector::iterator PI = LibraryPaths.begin();
StringVector::iterator PE = LibraryPaths.end(); PathVector::iterator PE = LibraryPaths.end();
while (PI != PE && fullpath.empty()) { while (PI != PE && fullpath.is_empty()) {
fullpath = GetPathForLinkageItem(link_item,*PI); fullpath = GetPathForLinkageItem(link_item.get(),*PI);
++PI; ++PI;
} }
// If we didn't find the file in any of the library search paths // If we didn't find the file in any of the library search paths
// so we have to bail. No where else to look. // so we have to bail. No where else to look.
if (fullpath.empty()) { if (fullpath.is_empty()) {
err = std::string("Can't find linkage item '") + link_item + "'"; err = std::string("Can't find linkage item '") + link_item.get() + "'";
return false; return false;
} }
} else { } else {
@@ -333,21 +322,21 @@ bool CompilerDriver::ProcessLinkageItem(const std::string& link_item,
set.insert(fullpath); set.insert(fullpath);
// If its an LLVM bytecode file ... // If its an LLVM bytecode file ...
if (CheckMagic(fullpath, "llvm")) { if (CheckMagic(fullpath.get(), "llvm")) {
// Process the dependent libraries recursively // Process the dependent libraries recursively
Module::LibraryListType modlibs; Module::LibraryListType modlibs;
if (GetBytecodeDependentLibraries(fullpath,modlibs)) { if (GetBytecodeDependentLibraries(fullpath.get(),modlibs)) {
// Traverse the dependent libraries list // Traverse the dependent libraries list
Module::lib_iterator LI = modlibs.begin(); Module::lib_iterator LI = modlibs.begin();
Module::lib_iterator LE = modlibs.end(); Module::lib_iterator LE = modlibs.end();
while ( LI != LE ) { while ( LI != LE ) {
if (!ProcessLinkageItem(*LI,set,err)) { if (!ProcessLinkageItem(sys::Path(*LI),set,err)) {
if (err.empty()) { if (err.empty()) {
err = std::string("Library '") + *LI + err = std::string("Library '") + *LI +
"' is not valid for linking but is required by file '" + "' is not valid for linking but is required by file '" +
fullpath + "'"; fullpath.get() + "'";
} else { } else {
err += " which is required by file '" + fullpath + "'"; err += " which is required by file '" + fullpath.get() + "'";
} }
return false; return false;
} }
@@ -355,58 +344,58 @@ bool CompilerDriver::ProcessLinkageItem(const std::string& link_item,
} }
} else if (err.empty()) { } else if (err.empty()) {
err = std::string("The dependent libraries could not be extracted from '") err = std::string("The dependent libraries could not be extracted from '")
+ fullpath; + fullpath.get();
return false; return false;
} }
} }
return true; return true;
} }
/// @}
int CompilerDriver::execute(const InputList& InpList, /// @name Methods
const std::string& Output ) { /// @{
public:
virtual int execute(const InputList& InpList, const sys::Path& Output ) {
try {
// Echo the configuration of options if we're running verbose // Echo the configuration of options if we're running verbose
if (isDebug) if (isSet(DEBUG_FLAG)) {
{
std::cerr << "Compiler Driver Options:\n"; std::cerr << "Compiler Driver Options:\n";
std::cerr << "DryRun = " << isDryRun << "\n"; std::cerr << "DryRun = " << isSet(DRY_RUN_FLAG) << "\n";
std::cerr << "Verbose = " << isVerbose << " \n"; std::cerr << "Verbose = " << isSet(VERBOSE_FLAG) << " \n";
std::cerr << "TimeActions = " << timeActions << "\n"; std::cerr << "TimeActions = " << isSet(TIME_ACTIONS_FLAG) << "\n";
std::cerr << "EmitRawCode = " << emitRawCode << "\n"; std::cerr << "TimePasses = " << isSet(TIME_PASSES_FLAG) << "\n";
std::cerr << "ShowStats = " << isSet(SHOW_STATS_FLAG) << "\n";
std::cerr << "EmitRawCode = " << isSet(EMIT_RAW_FLAG) << "\n";
std::cerr << "EmitNativeCode = " << isSet(EMIT_NATIVE_FLAG) << "\n";
std::cerr << "ForceOutput = " << isSet(FORCE_FLAG) << "\n";
std::cerr << "KeepTemps = " << isSet(KEEP_TEMPS_FLAG) << "\n";
std::cerr << "OutputMachine = " << machine << "\n"; std::cerr << "OutputMachine = " << machine << "\n";
std::cerr << "EmitNativeCode = " << emitNativeCode << "\n";
InputList::const_iterator I = InpList.begin(); InputList::const_iterator I = InpList.begin();
while ( I != InpList.end() ) { while ( I != InpList.end() ) {
std::cerr << "Input: " << I->first << "(" << I->second << ")\n"; std::cerr << "Input: " << I->first.get() << "(" << I->second << ")\n";
++I; ++I;
} }
std::cerr << "Output: " << Output << "\n"; std::cerr << "Output: " << Output.get() << "\n";
} }
// If there's no input, we're done. // If there's no input, we're done.
if (InpList.empty()) if (InpList.empty())
error("Nothing to compile."); throw std::string("Nothing to compile.");
// If they are asking for linking and didn't provide an output // If they are asking for linking and didn't provide an output
// file then its an error (no way for us to "make up" a meaningful // file then its an error (no way for us to "make up" a meaningful
// file name based on the various linker input files). // file name based on the various linker input files).
if (finalPhase == LINKING && Output.empty()) if (finalPhase == LINKING && Output.is_empty())
error("An output file name must be specified for linker output"); throw std::string(
"An output file name must be specified for linker output");
// This vector holds all the resulting actions of the following loop. // This vector holds all the resulting actions of the following loop.
std::vector<Action*> actions; std::vector<Action*> actions;
// Create a temporary directory for our temporary files
std::string TempDir(sys::MakeTemporaryDirectory());
std::string TempPreprocessorOut(TempDir + "/preproc.o");
std::string TempTranslatorOut(TempDir + "/trans.o");
std::string TempOptimizerOut(TempDir + "/opt.o");
std::string TempAssemblerOut(TempDir + "/asm.o");
/// PRE-PROCESSING / TRANSLATION / OPTIMIZATION / ASSEMBLY phases /// PRE-PROCESSING / TRANSLATION / OPTIMIZATION / ASSEMBLY phases
// for each input item // for each input item
std::vector<std::string> LinkageItems; SetVector<sys::Path> LinkageItems;
std::string OutFile(Output); sys::Path OutFile(Output);
InputList::const_iterator I = InpList.begin(); InputList::const_iterator I = InpList.begin();
while ( I != InpList.end() ) { while ( I != InpList.end() ) {
// Get the suffix of the file name // Get the suffix of the file name
@@ -419,9 +408,10 @@ int CompilerDriver::execute(const InputList& InpList,
// We shouldn't get any of these types of files unless we're // We shouldn't get any of these types of files unless we're
// later going to link. Enforce this limit now. // later going to link. Enforce this limit now.
if (finalPhase != LINKING) { if (finalPhase != LINKING) {
error("Pre-compiled objects found but linking not requested"); throw std::string(
"Pre-compiled objects found but linking not requested");
} }
LinkageItems.push_back(I->first); LinkageItems.insert(I->first);
++I; continue; // short circuit remainder of loop ++I; continue; // short circuit remainder of loop
} }
@@ -430,33 +420,33 @@ int CompilerDriver::execute(const InputList& InpList,
// for this kind of file. // for this kind of file.
ConfigData* cd = cdp->ProvideConfigData(I->second); ConfigData* cd = cdp->ProvideConfigData(I->second);
if (cd == 0) if (cd == 0)
error(std::string("Files of type '") + I->second + throw std::string("Files of type '") + I->second +
"' are not recognized." ); "' are not recognized.";
if (isDebug) if (isSet(DEBUG_FLAG))
DumpConfigData(cd,I->second); DumpConfigData(cd,I->second);
// Initialize the input file // Initialize the input file
std::string InFile(I->first); sys::Path InFile(I->first);
// PRE-PROCESSING PHASE // PRE-PROCESSING PHASE
Action& action = cd->PreProcessor; Action& action = cd->PreProcessor;
// Get the preprocessing action, if needed, or error if appropriate // Get the preprocessing action, if needed, or error if appropriate
if (!action.program.empty()) { if (!action.program.is_empty()) {
if (action.isSet(REQUIRED_FLAG) || finalPhase == PREPROCESSING) { if (action.isSet(REQUIRED_FLAG) || finalPhase == PREPROCESSING) {
if (finalPhase == PREPROCESSING) if (finalPhase == PREPROCESSING)
actions.push_back(GetAction(cd,InFile,OutFile,PREPROCESSING)); actions.push_back(GetAction(cd,InFile,OutFile,PREPROCESSING));
else { else {
actions.push_back(GetAction(cd,InFile,TempPreprocessorOut, sys::Path TempFile(MakeTempFile(I->first.get(),"E"));
PREPROCESSING)); actions.push_back(GetAction(cd,InFile,TempFile,PREPROCESSING));
InFile = TempPreprocessorOut; InFile = TempFile;
} }
} }
} else if (finalPhase == PREPROCESSING) { } else if (finalPhase == PREPROCESSING) {
error(cd->langName + " does not support pre-processing"); throw cd->langName + " does not support pre-processing";
} else if (action.isSet(REQUIRED_FLAG)) { } else if (action.isSet(REQUIRED_FLAG)) {
error(std::string("Don't know how to pre-process ") + throw std::string("Don't know how to pre-process ") +
cd->langName + " files"); cd->langName + " files";
} }
// Short-circuit remaining actions if all they want is pre-processing // Short-circuit remaining actions if all they want is pre-processing
@@ -466,13 +456,14 @@ int CompilerDriver::execute(const InputList& InpList,
action = cd->Translator; action = cd->Translator;
// Get the translation action, if needed, or error if appropriate // Get the translation action, if needed, or error if appropriate
if (!action.program.empty()) { if (!action.program.is_empty()) {
if (action.isSet(REQUIRED_FLAG) || finalPhase == TRANSLATION) { if (action.isSet(REQUIRED_FLAG) || finalPhase == TRANSLATION) {
if (finalPhase == TRANSLATION) if (finalPhase == TRANSLATION)
actions.push_back(GetAction(cd,InFile,OutFile,TRANSLATION)); actions.push_back(GetAction(cd,InFile,OutFile,TRANSLATION));
else { else {
actions.push_back(GetAction(cd,InFile,TempTranslatorOut,TRANSLATION)); sys::Path TempFile(MakeTempFile(I->first.get(),"trans"));
InFile = TempTranslatorOut; actions.push_back(GetAction(cd,InFile,TempFile,TRANSLATION));
InFile = TempFile;
} }
// ll -> bc Helper // ll -> bc Helper
@@ -480,19 +471,19 @@ int CompilerDriver::execute(const InputList& InpList,
/// The output of the translator is an LLVM Assembly program /// The output of the translator is an LLVM Assembly program
/// We need to translate it to bytecode /// We need to translate it to bytecode
Action* action = new Action(); Action* action = new Action();
action->program = "llvm-as"; action->program.set_file("llvm-as");
action->args.push_back(InFile); action->args.push_back(InFile.get());
action->args.push_back("-o"); action->args.push_back("-o");
InFile += ".bc"; InFile.append_suffix("bc");
action->args.push_back(InFile); action->args.push_back(InFile.get());
actions.push_back(action); actions.push_back(action);
} }
} }
} else if (finalPhase == TRANSLATION) { } else if (finalPhase == TRANSLATION) {
error(cd->langName + " does not support translation"); throw cd->langName + " does not support translation";
} else if (action.isSet(REQUIRED_FLAG)) { } else if (action.isSet(REQUIRED_FLAG)) {
error(std::string("Don't know how to translate ") + throw std::string("Don't know how to translate ") +
cd->langName + " files"); cd->langName + " files";
} }
// Short-circuit remaining actions if all they want is translation // Short-circuit remaining actions if all they want is translation
@@ -502,34 +493,35 @@ int CompilerDriver::execute(const InputList& InpList,
action = cd->Optimizer; action = cd->Optimizer;
// Get the optimization action, if needed, or error if appropriate // Get the optimization action, if needed, or error if appropriate
if (!emitRawCode) { if (!isSet(EMIT_RAW_FLAG)) {
if (!action.program.empty()) { if (!action.program.is_empty()) {
if (action.isSet(REQUIRED_FLAG) || finalPhase == OPTIMIZATION) { if (action.isSet(REQUIRED_FLAG) || finalPhase == OPTIMIZATION) {
if (finalPhase == OPTIMIZATION) if (finalPhase == OPTIMIZATION)
actions.push_back(GetAction(cd,InFile,OutFile,OPTIMIZATION)); actions.push_back(GetAction(cd,InFile,OutFile,OPTIMIZATION));
else { else {
actions.push_back(GetAction(cd,InFile,TempOptimizerOut,OPTIMIZATION)); sys::Path TempFile(MakeTempFile(I->first.get(),"opt"));
InFile = TempOptimizerOut; actions.push_back(GetAction(cd,InFile,TempFile,OPTIMIZATION));
InFile = TempFile;
} }
// ll -> bc Helper // ll -> bc Helper
if (action.isSet(OUTPUT_IS_ASM_FLAG)) { if (action.isSet(OUTPUT_IS_ASM_FLAG)) {
/// The output of the translator is an LLVM Assembly program /// The output of the translator is an LLVM Assembly program
/// We need to translate it to bytecode /// We need to translate it to bytecode
Action* action = new Action(); Action* action = new Action();
action->program = "llvm-as"; action->program.set_file("llvm-as");
action->args.push_back(InFile); action->args.push_back(InFile.get());
action->args.push_back("-f"); action->args.push_back("-f");
action->args.push_back("-o"); action->args.push_back("-o");
InFile += ".bc"; InFile.append_suffix("bc");
action->args.push_back(InFile); action->args.push_back(InFile.get());
actions.push_back(action); actions.push_back(action);
} }
} }
} else if (finalPhase == OPTIMIZATION) { } else if (finalPhase == OPTIMIZATION) {
error(cd->langName + " does not support optimization"); throw cd->langName + " does not support optimization";
} else if (action.isSet(REQUIRED_FLAG)) { } else if (action.isSet(REQUIRED_FLAG)) {
error(std::string("Don't know how to optimize ") + throw std::string("Don't know how to optimize ") +
cd->langName + " files"); cd->langName + " files";
} }
} }
@@ -539,25 +531,26 @@ int CompilerDriver::execute(const InputList& InpList,
/// ASSEMBLY PHASE /// ASSEMBLY PHASE
action = cd->Assembler; action = cd->Assembler;
if (finalPhase == ASSEMBLY || emitNativeCode) { if (finalPhase == ASSEMBLY || isSet(EMIT_NATIVE_FLAG)) {
if (emitNativeCode) { if (isSet(EMIT_NATIVE_FLAG)) {
if (action.program.empty()) { if (action.program.is_empty()) {
error(std::string("Native Assembler not specified for ") + throw std::string("Native Assembler not specified for ") +
cd->langName + " files"); cd->langName + " files";
} else if (finalPhase == ASSEMBLY) { } else if (finalPhase == ASSEMBLY) {
actions.push_back(GetAction(cd,InFile,OutFile,ASSEMBLY)); actions.push_back(GetAction(cd,InFile,OutFile,ASSEMBLY));
} else { } else {
actions.push_back(GetAction(cd,InFile,TempAssemblerOut,ASSEMBLY)); sys::Path TempFile(MakeTempFile(I->first.get(),"S"));
InFile = TempAssemblerOut; actions.push_back(GetAction(cd,InFile,TempFile,ASSEMBLY));
InFile = TempFile;
} }
} else { } else {
// Just convert back to llvm assembly with llvm-dis // Just convert back to llvm assembly with llvm-dis
Action* action = new Action(); Action* action = new Action();
action->program = "llvm-dis"; action->program.set_file("llvm-dis");
action->args.push_back(InFile); action->args.push_back(InFile.get());
action->args.push_back("-f"); action->args.push_back("-f");
action->args.push_back("-o"); action->args.push_back("-o");
action->args.push_back(OutFile); action->args.push_back(OutFile.get());
actions.push_back(action); actions.push_back(action);
} }
} }
@@ -566,66 +559,118 @@ int CompilerDriver::execute(const InputList& InpList,
if (finalPhase == ASSEMBLY) { ++I; continue; } if (finalPhase == ASSEMBLY) { ++I; continue; }
// Register the OutFile as a link candidate // Register the OutFile as a link candidate
LinkageItems.push_back(InFile); LinkageItems.insert(InFile);
// Go to next file to be processed // Go to next file to be processed
++I; ++I;
} }
/// RUN THE COMPILATION ACTIONS /// RUN THE COMPILATION ACTIONS
std::vector<Action*>::iterator aIter = actions.begin(); std::vector<Action*>::iterator AI = actions.begin();
while (aIter != actions.end()) { std::vector<Action*>::iterator AE = actions.end();
if (!DoAction(*aIter)) while (AI != AE) {
error("Action failed"); if (!DoAction(*AI))
aIter++; throw "Action failed";
AI++;
} }
/// LINKING PHASE /// LINKING PHASE
actions.clear();
if (finalPhase == LINKING) { if (finalPhase == LINKING) {
if (emitNativeCode) { if (isSet(EMIT_NATIVE_FLAG)) {
error("llvmc doesn't know how to link native code yet"); throw "llvmc doesn't know how to link native code yet";
} else { } else {
// First, we need to examine the files to ensure that they all contain // First, we need to examine the files to ensure that they all contain
// bytecode files. Since the final output is bytecode, we can only // bytecode files. Since the final output is bytecode, we can only
// link bytecode. // link bytecode.
StringVector::const_iterator I = LinkageItems.begin(); SetVector<sys::Path>::const_iterator I = LinkageItems.begin();
StringVector::const_iterator E = LinkageItems.end(); SetVector<sys::Path>::const_iterator E = LinkageItems.end();
SetVector<std::string> link_items;
std::string errmsg; std::string errmsg;
while (I != E && ProcessLinkageItem(*I,link_items,errmsg))
while (I != E && ProcessLinkageItem(*I,LinkageItems,errmsg))
++I; ++I;
if (!errmsg.empty()) if (!errmsg.empty())
error(errmsg); throw errmsg;
// Insert the system libraries.
LibraryPaths.push_back(sys::Path::GetSystemLibraryPath1());
LibraryPaths.push_back(sys::Path::GetSystemLibraryPath2());
// We're emitting bytecode so let's build an llvm-link Action // We're emitting bytecode so let's build an llvm-link Action
Action* link = new Action(); Action* link = new Action();
link->program = "llvm-link"; link->program.set_file("llvm-link");
link->args = LinkageItems; for (PathVector::const_iterator I=LinkageItems.begin(),
link->args.insert(link->args.end(), link_items.begin(), link_items.end()); E=LinkageItems.end(); I != E; ++I )
link->args.push_back(I->get());
if (isSet(VERBOSE_FLAG))
link->args.push_back("-v");
link->args.push_back("-f"); link->args.push_back("-f");
link->args.push_back("-o"); link->args.push_back("-o");
link->args.push_back(OutFile); link->args.push_back(OutFile.get());
if (timePasses) if (isSet(TIME_PASSES_FLAG))
link->args.push_back("-time-passes"); link->args.push_back("-time-passes");
if (showStats) if (isSet(SHOW_STATS_FLAG))
link->args.push_back("-stats"); link->args.push_back("-stats");
actions.push_back(link); actions.push_back(link);
} }
} }
if (!keepTemps) { /// RUN THE LINKING ACTIONS
// Cleanup files AI = actions.begin();
::sys::CleanupTempFile(TempPreprocessorOut); AE = actions.end();
::sys::CleanupTempFile(TempTranslatorOut); while (AI != AE) {
::sys::CleanupTempFile(TempOptimizerOut); if (!DoAction(*AI))
throw std::string("Action failed");
// Cleanup temporary directory we created AI++;
if (::sys::FileIsReadable(TempDir)) }
rmdir(TempDir.c_str()); } catch (std::string& msg) {
cleanup();
throw;
} catch (...) {
cleanup();
throw std::string("Unspecified error");
}
cleanup();
return 0;
} }
return 0; /// @}
/// @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
unsigned Flags; ///< The driver flags
std::string machine; ///< Target machine name
PathVector LibraryPaths; ///< -L options
sys::Path TempDir; ///< Name of the temporary directory.
StringTable AdditionalArgs; ///< The -Txyz options
/// @}
};
}
CompilerDriver::~CompilerDriver() {
}
CompilerDriver*
CompilerDriver::Get(ConfigDataProvider& CDP) {
return new CompilerDriverImpl(CDP);
}
CompilerDriver::ConfigData::ConfigData()
: langName()
, PreProcessor()
, Translator()
, Optimizer()
, Assembler()
, Linker()
{
StringVector emptyVec;
for (unsigned i = 0; i < NUM_PHASES; ++i)
opts.push_back(emptyVec);
} }
// vim: sw=2 smartindent smarttab tw=80 autoindent expandtab // vim: sw=2 smartindent smarttab tw=80 autoindent expandtab

View File

@@ -16,7 +16,7 @@
#include <string> #include <string>
#include <vector> #include <vector>
#include "Support/SetVector.h" #include "llvm/System/Program.h"
namespace llvm { namespace llvm {
/// This class provides the high level interface to the LLVM Compiler Driver. /// This class provides the high level interface to the LLVM Compiler Driver.
@@ -30,9 +30,12 @@ namespace llvm {
/// @name Types /// @name Types
/// @{ /// @{
public: public:
/// @brief A vector of strings, commonly used /// @brief A vector of strings, used for argument lists
typedef std::vector<std::string> StringVector; 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 /// @brief A table of strings, indexed typically by Phases
typedef std::vector<StringVector> StringTable; typedef std::vector<StringVector> StringTable;
@@ -65,11 +68,26 @@ namespace llvm {
FLAGS_MASK = 0x000F, ///< Union of all flags 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 /// 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. /// the configuration of the actions to be taken by the driver.
/// @brief The Input Data to the execute method /// @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 /// This type is read from configuration files or otherwise provided to
/// the CompilerDriver through a "ConfigDataProvider". It serves as both /// the CompilerDriver through a "ConfigDataProvider". It serves as both
@@ -78,7 +96,7 @@ namespace llvm {
/// language. /// language.
struct Action { struct Action {
Action() : flags(0) {} Action() : flags(0) {}
std::string program; ///< The program to execve sys::Program program; ///< The program to execve
StringVector args; ///< Arguments to the program StringVector args; ///< Arguments to the program
unsigned flags; ///< Action specific flags unsigned flags; ///< Action specific flags
void set(unsigned fl ) { flags |= fl; } void set(unsigned fl ) { flags |= fl; }
@@ -107,127 +125,49 @@ namespace llvm {
class ConfigDataProvider { class ConfigDataProvider {
public: public:
virtual ConfigData* ProvideConfigData(const std::string& filetype) = 0; 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 /// @name Constructors
/// @{ /// @{
public: public:
CompilerDriver(ConfigDataProvider& cdp ); /// @brief Static Constructor
static CompilerDriver* Get(ConfigDataProvider& CDP);
/// @brief Virtual destructor
virtual ~CompilerDriver(); virtual ~CompilerDriver();
/// @} /// @}
/// @name Methods /// @name Methods
/// @{ /// @{
public: public:
/// @brief Handle an error
virtual void error(const std::string& errmsg);
/// @brief Execute the actions requested for the given input list. /// @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 /// @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 /// @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 /// @brief Set the driver flags.
void setDryRun( bool TF ) { isDryRun = TF; } virtual void setDriverFlags(unsigned flags) = 0;
/// @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 output machine name. /// @brief Set the output machine name.
void setOutputMachine( const std::string& machineName ) { virtual void setOutputMachine(const std::string& machineName) = 0;
machine = machineName;
}
/// @brief Set Preprocessor specific options /// @brief Set Preprocessor specific options
void setPhaseArgs(Phases phase, const std::vector<std::string>& opts) { virtual void setPhaseArgs(Phases phase, const StringVector& opts) = 0;
assert(phase <= LINKING && phase >= PREPROCESSING);
AdditionalArgs[phase] = opts;
}
/// @brief Set Library Paths /// @brief Set Library Paths
void setLibraryPaths(const std::vector<std::string>& paths) { virtual void setLibraryPaths(const StringVector& paths) = 0;
LibraryPaths = paths;
}
/// @brief Set the list of library paths to be searched for /// @brief Set the list of library paths to be searched for
/// libraries. /// libraries.
void addLibraryPath( const std::string& libPath ) { virtual void addLibraryPath( const sys::Path& libPath ) = 0;
LibraryPaths.push_back(libPath);
}
/// @} /// @}
/// @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) COMMAND, ///< The name "command" (and variants)
EQUALS, ///< The equals sign, = EQUALS, ///< The equals sign, =
FALSETOK, ///< A boolean false value (false/no/off) FALSETOK, ///< A boolean false value (false/no/off)
FORCE_SUBST, ///< The substitution item %force%
IN_SUBST, ///< The substitution item %in% IN_SUBST, ///< The substitution item %in%
INTEGER, ///< An integer INTEGER, ///< An integer
LANG, ///< The name "lang" (and variants) LANG, ///< The name "lang" (and variants)
@@ -85,6 +86,7 @@ enum ConfigLexerTokens {
TRANSLATES, ///< The name "translates" (and variants) TRANSLATES, ///< The name "translates" (and variants)
TRANSLATOR, ///< The name "translator" (and variants) TRANSLATOR, ///< The name "translator" (and variants)
TRUETOK, ///< A boolean true value (true/yes/on) TRUETOK, ///< A boolean true value (true/yes/on)
VERBOSE_SUBST,///< The substitution item %verbose%
VERSION, ///< The name "version" (and variants) VERSION, ///< The name "version" (and variants)
}; };

View File

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

View File

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

View File

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

View File

@@ -8,7 +8,7 @@
##===----------------------------------------------------------------------===## ##===----------------------------------------------------------------------===##
LEVEL = ../.. LEVEL = ../..
TOOLNAME = llvmc TOOLNAME = llvmc
USEDLIBS = bcreader vmcore support.a USEDLIBS = bcreader vmcore support.a LLVMsystem.a
CONFIG_FILES = st ll CONFIG_FILES = st ll
include $(LEVEL)/Makefile.common 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::opt<std::string> OutputFilename("o",
cl::desc("Override output filename"), cl::value_desc("filename")); 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::opt<std::string> OutputMachine("m", cl::Prefix,
cl::desc("Specify a target machine"), cl::value_desc("machine")); 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, static cl::opt<bool> PipeCommands("pipe", cl::Optional,
cl::desc("Invoke sub-commands by linking input/output with pipes")); 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")); 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 /// @brief The main program for llvmc
int main(int argc, char **argv) { int main(int argc, char **argv) {
try {
// Make sure we print stack trace if we get bad signals // Make sure we print stack trace if we get bad signals
PrintStackTraceOnErrorSignal(); sys::PrintStackTraceOnErrorSignal();
try {
// Parse the command line options // Parse the command line options
cl::ParseCommandLineOptions(argc, argv, 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" " 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. // Deal with unimplemented options.
@@ -220,13 +224,12 @@ int main(int argc, char **argv) {
else else
throw "An output file must be specified. Please use the -o option"; throw "An output file must be specified. Please use the -o option";
// Construct the ConfigDataProvider object // Construct the ConfigDataProvider object
LLVMC_ConfigDataProvider Provider; LLVMC_ConfigDataProvider Provider;
Provider.setConfigDir(ConfigDir); Provider.setConfigDir(sys::Path(ConfigDir));
// Construct the CompilerDriver object // Construct the CompilerDriver object
CompilerDriver CD(Provider); CompilerDriver* CD = CompilerDriver::Get(Provider);
// If the LLVM_LIB_SEARCH_PATH environment variable is // If the LLVM_LIB_SEARCH_PATH environment variable is
// set, append it to the list of places to search for libraries // 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()) if (!srchPath.empty())
LibPaths.push_back(srchPath); LibPaths.push_back(srchPath);
// Configure the driver based on options // Set the driver flags based on command line options
CD.setVerbose(Verbose); unsigned flags = 0;
CD.setDebug(Debug); if (Verbose) flags |= CompilerDriver::VERBOSE_FLAG;
CD.setDryRun(DryRun); if (Debug) flags |= CompilerDriver::DEBUG_FLAG;
CD.setFinalPhase(FinalPhase); if (DryRun) flags |= CompilerDriver::DRY_RUN_FLAG;
CD.setOptimization(OptLevel); if (ForceOutput) flags |= CompilerDriver::FORCE_FLAG;
CD.setOutputMachine(OutputMachine); if (Native) flags |= CompilerDriver::EMIT_NATIVE_FLAG;
CD.setEmitNativeCode(Native); if (EmitRawCode) flags |= CompilerDriver::EMIT_RAW_FLAG;
CD.setEmitRawCode(EmitRawCode); if (KeepTemps) flags |= CompilerDriver::KEEP_TEMPS_FLAG;
CD.setTimeActions(TimeActions); if (ShowStats) flags |= CompilerDriver::SHOW_STATS_FLAG;
CD.setTimePasses(TimePassesIsEnabled); if (TimeActions) flags |= CompilerDriver::TIME_ACTIONS_FLAG;
CD.setShowStats(ShowStats); if (TimePassesIsEnabled) flags |= CompilerDriver::TIME_PASSES_FLAG;
CD.setKeepTemporaries(KeepTemporaries); CD->setDriverFlags(flags);
CD.setLibraryPaths(LibPaths);
// Specify requred parameters
CD->setFinalPhase(FinalPhase);
CD->setOptimization(OptLevel);
CD->setOutputMachine(OutputMachine);
CD->setLibraryPaths(LibPaths);
// Provide additional tool arguments
if (!PreprocessorToolOpts.empty()) if (!PreprocessorToolOpts.empty())
CD.setPhaseArgs(CompilerDriver::PREPROCESSING, PreprocessorToolOpts); CD->setPhaseArgs(CompilerDriver::PREPROCESSING, PreprocessorToolOpts);
if (!TranslatorToolOpts.empty()) if (!TranslatorToolOpts.empty())
CD.setPhaseArgs(CompilerDriver::TRANSLATION, TranslatorToolOpts); CD->setPhaseArgs(CompilerDriver::TRANSLATION, TranslatorToolOpts);
if (!OptimizerToolOpts.empty()) if (!OptimizerToolOpts.empty())
CD.setPhaseArgs(CompilerDriver::OPTIMIZATION, OptimizerToolOpts); CD->setPhaseArgs(CompilerDriver::OPTIMIZATION, OptimizerToolOpts);
if (!AssemblerToolOpts.empty()) if (!AssemblerToolOpts.empty())
CD.setPhaseArgs(CompilerDriver::ASSEMBLY,AssemblerToolOpts); CD->setPhaseArgs(CompilerDriver::ASSEMBLY,AssemblerToolOpts);
if (!LinkerToolOpts.empty()) if (!LinkerToolOpts.empty())
CD.setPhaseArgs(CompilerDriver::LINKING, LinkerToolOpts); CD->setPhaseArgs(CompilerDriver::LINKING, LinkerToolOpts);
// Prepare the list of files to be compiled by the CompilerDriver. // Prepare the list of files to be compiled by the CompilerDriver.
CompilerDriver::InputList InpList; CompilerDriver::InputList InpList;
@@ -288,7 +298,7 @@ int main(int argc, char **argv) {
} }
// Tell the driver to do its thing // Tell the driver to do its thing
int result = CD.execute(InpList,OutputFilename); int result = CD->execute(InpList,sys::Path(OutputFilename));
if (result != 0) { if (result != 0) {
throw "Error executing actions. Terminated.\n"; throw "Error executing actions. Terminated.\n";
return result; return result;

View File

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