Driver/MC: Add 'clang -cc1as' integrated assembler tool, currently accepts approximately the same interface as 'llvm-mc'.

llvm-svn: 104239
This commit is contained in:
Daniel Dunbar 2010-05-20 17:49:16 +00:00
parent d7d6638e3e
commit 2fcaa549a8
11 changed files with 498 additions and 10 deletions

View File

@ -0,0 +1,32 @@
//===--- CC1AsOptions.h - Clang Assembler Options Table ---------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#ifndef CLANG_DRIVER_CC1ASOPTIONS_H
#define CLANG_DRIVER_CC1ASOPTIONS_H
namespace clang {
namespace driver {
class OptTable;
namespace cc1asoptions {
enum ID {
OPT_INVALID = 0, // This is not an option ID.
#define OPTION(NAME, ID, KIND, GROUP, ALIAS, FLAGS, PARAM, \
HELPTEXT, METAVAR) OPT_##ID,
#include "clang/Driver/CC1AsOptions.inc"
LastOption
#undef OPTION
};
}
OptTable *createCC1AsOptTable();
}
}
#endif

View File

@ -0,0 +1,58 @@
//===--- CC1AsOptions.td - Options for clang -cc1as -----------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines the options accepted by clang -cc1as.
//
//===----------------------------------------------------------------------===//
// Include the common option parsing interfaces.
include "OptParser.td"
//===----------------------------------------------------------------------===//
// Target Options
//===----------------------------------------------------------------------===//
def triple : Separate<"-triple">,
HelpText<"Specify target triple (e.g. x86_64-pc-linux-gnu)">;
//===----------------------------------------------------------------------===//
// Language Options
//===----------------------------------------------------------------------===//
def I : JoinedOrSeparate<"-I">, MetaVarName<"<directory>">,
HelpText<"Add directory to include search path">;
def n : Flag<"-n">,
HelpText<"Don't automatically start assembly file with a text section">;
//===----------------------------------------------------------------------===//
// Frontend Options
//===----------------------------------------------------------------------===//
def o : Separate<"-o">, MetaVarName<"<path>">, HelpText<"Specify output file">;
def filetype : Separate<"-filetype">,
HelpText<"Specify the output file type ('asm', 'null', or 'obj')">;
//===----------------------------------------------------------------------===//
// Transliterate Options
//===----------------------------------------------------------------------===//
def output_asm_variant : Separate<"-output-asm-variant">,
HelpText<"Select the asm variant index to use for output">;
def show_encoding : Flag<"-show-encoding">,
HelpText<"Show instruction encoding information in transliterate mode">;
def show_inst : Flag<"-show-inst">,
HelpText<"Show internal instruction representation in transliterate mode">;
//===----------------------------------------------------------------------===//
// Assemble Options
//===----------------------------------------------------------------------===//
def relax_all : Flag<"-relax-all">,
HelpText<"Relax all fixups (for performance testing)">;

View File

@ -9,3 +9,9 @@ tablegen(CC1Options.inc
-gen-opt-parser-defs)
add_custom_target(ClangCC1Options
DEPENDS CC1Options.inc)
set(LLVM_TARGET_DEFINITIONS CC1AsOptions.td)
tablegen(CC1AsOptions.inc
-gen-opt-parser-defs)
add_custom_target(ClangCC1AsOptions
DEPENDS CC1AsOptions.inc)

View File

@ -1,5 +1,5 @@
LEVEL = ../../../../..
BUILT_SOURCES = Options.inc CC1Options.inc
BUILT_SOURCES = Options.inc CC1Options.inc CC1AsOptions.inc
TABLEGEN_INC_FILES_COMMON = 1
@ -13,4 +13,6 @@ $(ObjDir)/CC1Options.inc.tmp : CC1Options.td OptParser.td $(TBLGEN) $(ObjDir)/.d
$(Echo) "Building Clang CC1 Option tables with tblgen"
$(Verb) $(TableGen) -gen-opt-parser-defs -o $(call SYSPATH, $@) $<
$(ObjDir)/CC1AsOptions.inc.tmp : CC1AsOptions.td OptParser.td $(TBLGEN) $(ObjDir)/.dir
$(Echo) "Building Clang CC1 Assembler Option tables with tblgen"
$(Verb) $(TableGen) -gen-opt-parser-defs -o $(call SYSPATH, $@) $<

View File

@ -0,0 +1,39 @@
//===--- CC1AsOptions.cpp - Clang Assembler Options Table -----------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "clang/Driver/CC1AsOptions.h"
#include "clang/Driver/Option.h"
#include "clang/Driver/OptTable.h"
using namespace clang;
using namespace clang::driver;
using namespace clang::driver::options;
using namespace clang::driver::cc1asoptions;
static const OptTable::Info CC1AsInfoTable[] = {
#define OPTION(NAME, ID, KIND, GROUP, ALIAS, FLAGS, PARAM, \
HELPTEXT, METAVAR) \
{ NAME, HELPTEXT, METAVAR, Option::KIND##Class, FLAGS, PARAM, \
OPT_##GROUP, OPT_##ALIAS },
#include "clang/Driver/CC1AsOptions.inc"
};
namespace {
class CC1AsOptTable : public OptTable {
public:
CC1AsOptTable()
: OptTable(CC1AsInfoTable,
sizeof(CC1AsInfoTable) / sizeof(CC1AsInfoTable[0])) {}
};
}
OptTable *clang::driver::createCC1AsOptTable() {
return new CC1AsOptTable();
}

View File

@ -1,4 +1,4 @@
//===--- CC1Options.cpp - Clang CC1 Options Table -----------------------*-===//
//===--- CC1Options.cpp - Clang CC1 Options Table -------------------------===//
//
// The LLVM Compiler Infrastructure
//

View File

@ -5,6 +5,7 @@ add_clang_library(clangDriver
Arg.cpp
ArgList.cpp
CC1Options.cpp
CC1AsOptions.cpp
Compilation.cpp
Driver.cpp
DriverOptions.cpp
@ -20,4 +21,5 @@ add_clang_library(clangDriver
Types.cpp
)
add_dependencies(clangDriver ClangDiagnosticDriver ClangDriverOptions ClangCC1Options)
add_dependencies(clangDriver ClangDiagnosticDriver ClangDriverOptions
ClangCC1Options ClangCC1AsOptions)

View File

@ -26,6 +26,7 @@ set( LLVM_LINK_COMPONENTS
add_clang_executable(clang
driver.cpp
cc1_main.cpp
cc1as_main.cpp
)
if(UNIX)

View File

@ -1,4 +1,4 @@
//===-- cc1_main.cpp - Clang CC1 Driver -----------------------------------===//
//===-- cc1_main.cpp - Clang CC1 Compiler Frontend ------------------------===//
//
// The LLVM Compiler Infrastructure
//
@ -43,7 +43,7 @@ using namespace clang;
// Main driver
//===----------------------------------------------------------------------===//
void LLVMErrorHandler(void *UserData, const std::string &Message) {
static void LLVMErrorHandler(void *UserData, const std::string &Message) {
Diagnostic &Diags = *static_cast<Diagnostic*>(UserData);
Diags.Report(diag::err_fe_error_backend) << Message;

View File

@ -0,0 +1,335 @@
//===-- cc1as_main.cpp - Clang Assembler ---------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This is the entry point to the clang -cc1as functionality, which implements
// the direct interface to the LLVM MC based assembler.
//
//===----------------------------------------------------------------------===//
#include "clang/Basic/Diagnostic.h"
#include "clang/Driver/Arg.h"
#include "clang/Driver/ArgList.h"
#include "clang/Driver/DriverDiagnostic.h"
#include "clang/Driver/CC1AsOptions.h"
#include "clang/Driver/OptTable.h"
#include "clang/Driver/Options.h"
#include "clang/Frontend/DiagnosticOptions.h"
#include "clang/Frontend/FrontendDiagnostic.h"
#include "clang/Frontend/TextDiagnosticPrinter.h"
#include "llvm/ADT/OwningPtr.h"
#include "llvm/ADT/StringSwitch.h"
#include "llvm/MC/MCParser/AsmParser.h"
#include "llvm/MC/MCCodeEmitter.h"
#include "llvm/MC/MCContext.h"
#include "llvm/MC/MCStreamer.h"
#include "llvm/Support/FormattedStream.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/ManagedStatic.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/PrettyStackTrace.h"
#include "llvm/Support/SourceMgr.h"
#include "llvm/Support/Timer.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/System/Host.h"
#include "llvm/System/Path.h"
#include "llvm/System/Signals.h"
#include "llvm/Target/TargetAsmBackend.h"
#include "llvm/Target/TargetAsmParser.h"
#include "llvm/Target/TargetData.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Target/TargetRegistry.h"
#include "llvm/Target/TargetSelect.h"
using namespace clang;
using namespace clang::driver;
using namespace llvm;
namespace {
/// \brief Helper class for representing a single invocation of the assembler.
struct AssemblerInvocation {
/// @name Target Options
/// @{
std::string Triple;
/// @}
/// @name Language Options
/// @{
std::vector<std::string> IncludePaths;
unsigned NoInitialTextSection : 1;
/// @}
/// @name Frontend Options
/// @{
std::string InputFile;
std::string OutputPath;
enum FileType {
FT_Asm, ///< Assembly (.s) output, transliterate mode.
FT_Null, ///< No output, for timing purposes.
FT_Obj ///< Object file output.
};
FileType OutputType;
/// @}
/// @name Transliterate Options
/// @{
unsigned OutputAsmVariant;
unsigned ShowEncoding : 1;
unsigned ShowInst : 1;
/// @}
/// @name Assembler Options
/// @{
unsigned RelaxAll : 1;
/// @}
public:
AssemblerInvocation() {
Triple = "";
NoInitialTextSection = 0;
InputFile = "-";
OutputPath = "a.out";
OutputType = FT_Asm;
OutputAsmVariant = 0;
ShowInst = 0;
ShowEncoding = 0;
RelaxAll = 0;
}
static void CreateFromArgs(AssemblerInvocation &Res, const char **ArgBegin,
const char **ArgEnd, Diagnostic &Diags);
};
}
void AssemblerInvocation::CreateFromArgs(AssemblerInvocation &Opts,
const char **ArgBegin,
const char **ArgEnd,
Diagnostic &Diags) {
using namespace clang::driver::cc1asoptions;
// Parse the arguments.
OwningPtr<OptTable> OptTbl(createCC1AsOptTable());
unsigned MissingArgIndex, MissingArgCount;
OwningPtr<InputArgList> Args(
OptTbl->ParseArgs(ArgBegin, ArgEnd,MissingArgIndex, MissingArgCount));
// Check for missing argument error.
if (MissingArgCount)
Diags.Report(diag::err_drv_missing_argument)
<< Args->getArgString(MissingArgIndex) << MissingArgCount;
// Issue errors on unknown arguments.
for (arg_iterator it = Args->filtered_begin(cc1asoptions::OPT_UNKNOWN),
ie = Args->filtered_end(); it != ie; ++it)
Diags.Report(diag::err_drv_unknown_argument) << it->getAsString(*Args);
// Construct the invocation.
// Target Options
Opts.Triple = Args->getLastArgValue(OPT_triple);
if (Opts.Triple.empty()) // Use the host triple if unspecified.
Opts.Triple = sys::getHostTriple();
// Language Options
Opts.IncludePaths = Args->getAllArgValues(OPT_I);
Opts.NoInitialTextSection = Args->hasArg(OPT_n);
// Frontend Options
if (Args->hasArg(OPT_INPUT)) {
bool First = true;
for (arg_iterator it = Args->filtered_begin(OPT_INPUT),
ie = Args->filtered_end(); it != ie; ++it, First=false) {
if (First)
Opts.InputFile = it->getValue(*Args);
else
Diags.Report(diag::err_drv_unknown_argument) << it->getAsString(*Args);
}
}
Opts.OutputPath = Args->getLastArgValue(OPT_o);
if (Arg *A = Args->getLastArg(OPT_filetype)) {
StringRef Name = A->getValue(*Args);
unsigned OutputType = StringSwitch<unsigned>(Name)
.Case("asm", FT_Asm)
.Case("null", FT_Null)
.Case("obj", FT_Obj)
.Default(~0U);
if (OutputType == ~0U)
Diags.Report(diag::err_drv_invalid_value)
<< A->getAsString(*Args) << Name;
else
Opts.OutputType = FileType(OutputType);
}
// Transliterate Options
Opts.OutputAsmVariant = Args->getLastArgIntValue(OPT_output_asm_variant,
0, Diags);
Opts.ShowEncoding = Args->hasArg(OPT_show_encoding);
Opts.ShowInst = Args->hasArg(OPT_show_inst);
// Assemble Options
Opts.RelaxAll = Args->hasArg(OPT_relax_all);
}
static formatted_raw_ostream *GetOutputStream(AssemblerInvocation &Opts,
Diagnostic &Diags,
bool Binary) {
// Make sure that the Out file gets unlinked from the disk if we get a
// SIGINT.
if (Opts.OutputPath != "-")
sys::RemoveFileOnSignal(sys::Path(Opts.OutputPath));
std::string Error;
raw_fd_ostream *Out =
new raw_fd_ostream(Opts.OutputPath.c_str(), Error,
(Binary ? raw_fd_ostream::F_Binary : 0));
if (!Error.empty()) {
Diags.Report(diag::err_fe_unable_to_open_output)
<< Opts.OutputPath << Error;
return 0;
}
return new formatted_raw_ostream(*Out, formatted_raw_ostream::DELETE_STREAM);
}
static bool ExecuteAssembler(AssemblerInvocation &Opts, Diagnostic &Diags) {
// Get the target specific parser.
std::string Error;
const Target *TheTarget(TargetRegistry::lookupTarget(Opts.Triple, Error));
if (!TheTarget) {
Diags.Report(diag::err_target_unknown_triple) << Opts.Triple;
return false;
}
MemoryBuffer *Buffer = MemoryBuffer::getFileOrSTDIN(Opts.InputFile, &Error);
if (Buffer == 0) {
Diags.Report(diag::err_fe_error_reading) << Opts.InputFile;
return false;
}
SourceMgr SrcMgr;
// Tell SrcMgr about this buffer, which is what the parser will pick up.
SrcMgr.AddNewSourceBuffer(Buffer, SMLoc());
// Record the location of the include directories so that the lexer can find
// it later.
SrcMgr.setIncludeDirs(Opts.IncludePaths);
OwningPtr<MCAsmInfo> MAI(TheTarget->createAsmInfo(Opts.Triple));
assert(MAI && "Unable to create target asm info!");
MCContext Ctx(*MAI);
bool IsBinary = Opts.OutputType == AssemblerInvocation::FT_Obj;
formatted_raw_ostream *Out = GetOutputStream(Opts, Diags, IsBinary);
if (!Out)
return false;
// FIXME: We shouldn't need to do this (and link in codegen).
OwningPtr<TargetMachine> TM(TheTarget->createTargetMachine(Opts.Triple, ""));
if (!TM) {
Diags.Report(diag::err_target_unknown_triple) << Opts.Triple;
return false;
}
OwningPtr<MCCodeEmitter> CE;
OwningPtr<MCStreamer> Str;
OwningPtr<TargetAsmBackend> TAB;
if (Opts.OutputType == AssemblerInvocation::FT_Asm) {
MCInstPrinter *IP =
TheTarget->createMCInstPrinter(Opts.OutputAsmVariant, *MAI);
if (Opts.ShowEncoding)
CE.reset(TheTarget->createCodeEmitter(*TM, Ctx));
Str.reset(createAsmStreamer(Ctx, *Out,TM->getTargetData()->isLittleEndian(),
/*asmverbose*/true, IP, CE.get(),
Opts.ShowInst));
} else if (Opts.OutputType == AssemblerInvocation::FT_Null) {
Str.reset(createNullStreamer(Ctx));
} else {
assert(Opts.OutputType == AssemblerInvocation::FT_Obj &&
"Invalid file type!");
CE.reset(TheTarget->createCodeEmitter(*TM, Ctx));
TAB.reset(TheTarget->createAsmBackend(Opts.Triple));
Str.reset(createMachOStreamer(Ctx, *TAB, *Out, CE.get(), Opts.RelaxAll));
}
AsmParser Parser(SrcMgr, Ctx, *Str.get(), *MAI);
OwningPtr<TargetAsmParser> TAP(TheTarget->createAsmParser(Parser));
if (!TAP) {
Diags.Report(diag::err_target_unknown_triple) << Opts.Triple;
return false;
}
Parser.setTargetParser(*TAP.get());
bool Success = !Parser.Run(Opts.NoInitialTextSection);
// Close the output.
delete Out;
// Delete output on errors.
if (!Success && Opts.OutputPath != "-")
sys::Path(Opts.OutputPath).eraseFromDisk();
return Success;
}
static void LLVMErrorHandler(void *UserData, const std::string &Message) {
Diagnostic &Diags = *static_cast<Diagnostic*>(UserData);
Diags.Report(diag::err_fe_error_backend) << Message;
// We cannot recover from llvm errors.
exit(1);
}
int cc1as_main(const char **ArgBegin, const char **ArgEnd,
const char *Argv0, void *MainAddr) {
// Print a stack trace if we signal out.
sys::PrintStackTraceOnErrorSignal();
PrettyStackTraceProgram X(ArgEnd - ArgBegin, ArgBegin);
llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
// Initialize targets and assembly printers/parsers.
InitializeAllTargetInfos();
// FIXME: We shouldn't need to initialize the Target(Machine)s.
InitializeAllTargets();
InitializeAllAsmPrinters();
InitializeAllAsmParsers();
// Construct our diagnostic client.
TextDiagnosticPrinter DiagClient(errs(), DiagnosticOptions());
DiagClient.setPrefix("clang -cc1as");
Diagnostic Diags(&DiagClient);
// Set an error handler, so that any LLVM backend diagnostics go through our
// error handler.
install_fatal_error_handler(LLVMErrorHandler,
static_cast<void*>(&Diags));
// Parse the arguments.
AssemblerInvocation Asm;
AssemblerInvocation::CreateFromArgs(Asm, ArgBegin, ArgEnd, Diags);
// Execute the invocation, unless there were parsing errors.
bool Success = false;
if (!Diags.getNumErrors())
Success = ExecuteAssembler(Asm, Diags);
// If any timers were active but haven't been destroyed yet, print their
// results now.
TimerGroup::printAll(errs());
return !Success;
}

View File

@ -170,15 +170,28 @@ static void ApplyQAOverride(std::vector<const char*> &Args,
extern int cc1_main(const char **ArgBegin, const char **ArgEnd,
const char *Argv0, void *MainAddr);
extern int cc1as_main(const char **ArgBegin, const char **ArgEnd,
const char *Argv0, void *MainAddr);
int main(int argc, const char **argv) {
llvm::sys::PrintStackTraceOnErrorSignal();
llvm::PrettyStackTraceProgram X(argc, argv);
// Dispatch to cc1_main if appropriate.
if (argc > 1 && llvm::StringRef(argv[1]) == "-cc1")
return cc1_main(argv+2, argv+argc, argv[0],
(void*) (intptr_t) GetExecutablePath);
// Handle -cc1 integrated tools.
if (argc > 1 && llvm::StringRef(argv[1]).startswith("-cc1")) {
llvm::StringRef Tool = argv[1] + 4;
if (Tool == "")
return cc1_main(argv+2, argv+argc, argv[0],
(void*) (intptr_t) GetExecutablePath);
if (Tool == "as")
return cc1as_main(argv+2, argv+argc, argv[0],
(void*) (intptr_t) GetExecutablePath);
// Reject unknown tools.
llvm::errs() << "error: unknown integrated tool '" << Tool << "'\n";
return 1;
}
bool CanonicalPrefixes = true;
for (int i = 1; i < argc; ++i) {