#include "clang/Basic/Diagnostic.h"
#include "clang/Basic/DiagnosticOptions.h"
#include "clang/Driver/CC1AsOptions.h"
#include "clang/Driver/DriverDiagnostic.h"
#include "clang/Driver/Options.h"
#include "clang/Frontend/FrontendDiagnostic.h"
#include "clang/Frontend/TextDiagnosticPrinter.h"
#include "clang/Frontend/Utils.h"
#include "llvm/ADT/OwningPtr.h"
#include "llvm/ADT/StringSwitch.h"
#include "llvm/ADT/Triple.h"
#include "llvm/IR/DataLayout.h"
#include "llvm/MC/MCAsmBackend.h"
#include "llvm/MC/MCAsmInfo.h"
#include "llvm/MC/MCCodeEmitter.h"
#include "llvm/MC/MCContext.h"
#include "llvm/MC/MCInstrInfo.h"
#include "llvm/MC/MCObjectFileInfo.h"
#include "llvm/MC/MCParser/MCAsmParser.h"
#include "llvm/MC/MCRegisterInfo.h"
#include "llvm/MC/MCStreamer.h"
#include "llvm/MC/MCSubtargetInfo.h"
#include "llvm/MC/MCTargetAsmParser.h"
#include "llvm/Option/Arg.h"
#include "llvm/Option/ArgList.h"
#include "llvm/Option/OptTable.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/FormattedStream.h"
#include "llvm/Support/Host.h"
#include "llvm/Support/ManagedStatic.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/PrettyStackTrace.h"
#include "llvm/Support/Signals.h"
#include "llvm/Support/SourceMgr.h"
#include "llvm/Support/TargetRegistry.h"
#include "llvm/Support/TargetSelect.h"
#include "llvm/Support/Timer.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Support/system_error.h"
using namespace clang;
using namespace clang::driver;
using namespace llvm;
using namespace llvm::opt;
namespace {
struct AssemblerInvocation {
std::string Triple;
std::string CPU;
std::vector<std::string> Features;
std::vector<std::string> IncludePaths;
unsigned NoInitialTextSection : 1;
unsigned SaveTemporaryLabels : 1;
unsigned GenDwarfForAssembly : 1;
std::string DwarfDebugFlags;
std::string DwarfDebugProducer;
std::string DebugCompilationDir;
std::string MainFileName;
std::string InputFile;
std::vector<std::string> LLVMArgs;
std::string OutputPath;
enum FileType {
FT_Asm, FT_Null, FT_Obj };
FileType OutputType;
unsigned ShowHelp : 1;
unsigned ShowVersion : 1;
unsigned OutputAsmVariant;
unsigned ShowEncoding : 1;
unsigned ShowInst : 1;
unsigned RelaxAll : 1;
unsigned NoExecStack : 1;
public:
AssemblerInvocation() {
Triple = "";
NoInitialTextSection = 0;
InputFile = "-";
OutputPath = "-";
OutputType = FT_Asm;
OutputAsmVariant = 0;
ShowInst = 0;
ShowEncoding = 0;
RelaxAll = 0;
NoExecStack = 0;
}
static bool CreateFromArgs(AssemblerInvocation &Res, const char **ArgBegin,
const char **ArgEnd, DiagnosticsEngine &Diags);
};
}
bool AssemblerInvocation::CreateFromArgs(AssemblerInvocation &Opts,
const char **ArgBegin,
const char **ArgEnd,
DiagnosticsEngine &Diags) {
using namespace clang::driver::cc1asoptions;
bool Success = true;
OwningPtr<OptTable> OptTbl(createCC1AsOptTable());
unsigned MissingArgIndex, MissingArgCount;
OwningPtr<InputArgList> Args(
OptTbl->ParseArgs(ArgBegin, ArgEnd,MissingArgIndex, MissingArgCount));
if (MissingArgCount) {
Diags.Report(diag::err_drv_missing_argument)
<< Args->getArgString(MissingArgIndex) << MissingArgCount;
Success = false;
}
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);
Success = false;
}
Opts.Triple = llvm::Triple::normalize(Args->getLastArgValue(OPT_triple));
Opts.CPU = Args->getLastArgValue(OPT_target_cpu);
Opts.Features = Args->getAllArgValues(OPT_target_feature);
if (Opts.Triple.empty())
Opts.Triple = llvm::sys::getDefaultTargetTriple();
Opts.IncludePaths = Args->getAllArgValues(OPT_I);
Opts.NoInitialTextSection = Args->hasArg(OPT_n);
Opts.SaveTemporaryLabels = Args->hasArg(OPT_msave_temp_labels);
Opts.GenDwarfForAssembly = Args->hasArg(OPT_g);
Opts.DwarfDebugFlags = Args->getLastArgValue(OPT_dwarf_debug_flags);
Opts.DwarfDebugProducer = Args->getLastArgValue(OPT_dwarf_debug_producer);
Opts.DebugCompilationDir = Args->getLastArgValue(OPT_fdebug_compilation_dir);
Opts.MainFileName = Args->getLastArgValue(OPT_main_file_name);
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) {
const Arg *A = it;
if (First)
Opts.InputFile = A->getValue();
else {
Diags.Report(diag::err_drv_unknown_argument) << A->getAsString(*Args);
Success = false;
}
}
}
Opts.LLVMArgs = Args->getAllArgValues(OPT_mllvm);
Opts.OutputPath = Args->getLastArgValue(OPT_o);
if (Arg *A = Args->getLastArg(OPT_filetype)) {
StringRef Name = A->getValue();
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;
Success = false;
} else
Opts.OutputType = FileType(OutputType);
}
Opts.ShowHelp = Args->hasArg(OPT_help);
Opts.ShowVersion = Args->hasArg(OPT_version);
Opts.OutputAsmVariant =
getLastArgIntValue(*Args.get(), OPT_output_asm_variant, 0, Diags);
Opts.ShowEncoding = Args->hasArg(OPT_show_encoding);
Opts.ShowInst = Args->hasArg(OPT_show_inst);
Opts.RelaxAll = Args->hasArg(OPT_mrelax_all);
Opts.NoExecStack = Args->hasArg(OPT_mno_exec_stack);
return Success;
}
static formatted_raw_ostream *GetOutputStream(AssemblerInvocation &Opts,
DiagnosticsEngine &Diags,
bool Binary) {
if (Opts.OutputPath.empty())
Opts.OutputPath = "-";
if (Opts.OutputPath != "-")
sys::RemoveFileOnSignal(Opts.OutputPath);
std::string Error;
raw_fd_ostream *Out =
new raw_fd_ostream(Opts.OutputPath.c_str(), Error,
(Binary ? sys::fs::F_Binary : sys::fs::F_None));
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,
DiagnosticsEngine &Diags) {
std::string Error;
const Target *TheTarget(TargetRegistry::lookupTarget(Opts.Triple, Error));
if (!TheTarget) {
Diags.Report(diag::err_target_unknown_triple) << Opts.Triple;
return false;
}
OwningPtr<MemoryBuffer> BufferPtr;
if (error_code ec = MemoryBuffer::getFileOrSTDIN(Opts.InputFile, BufferPtr)) {
Error = ec.message();
Diags.Report(diag::err_fe_error_reading) << Opts.InputFile;
return false;
}
MemoryBuffer *Buffer = BufferPtr.take();
SourceMgr SrcMgr;
SrcMgr.AddNewSourceBuffer(Buffer, SMLoc());
SrcMgr.setIncludeDirs(Opts.IncludePaths);
OwningPtr<MCRegisterInfo> MRI(TheTarget->createMCRegInfo(Opts.Triple));
assert(MRI && "Unable to create target register info!");
OwningPtr<MCAsmInfo> MAI(TheTarget->createMCAsmInfo(*MRI, Opts.Triple));
assert(MAI && "Unable to create target asm info!");
bool IsBinary = Opts.OutputType == AssemblerInvocation::FT_Obj;
formatted_raw_ostream *Out = GetOutputStream(Opts, Diags, IsBinary);
if (!Out)
return false;
OwningPtr<MCObjectFileInfo> MOFI(new MCObjectFileInfo());
MCContext Ctx(MAI.get(), MRI.get(), MOFI.get(), &SrcMgr);
MOFI->InitMCObjectFileInfo(Opts.Triple,
Reloc::Default, CodeModel::Default, Ctx);
if (Opts.SaveTemporaryLabels)
Ctx.setAllowTemporaryLabels(false);
if (Opts.GenDwarfForAssembly)
Ctx.setGenDwarfForAssembly(true);
if (!Opts.DwarfDebugFlags.empty())
Ctx.setDwarfDebugFlags(StringRef(Opts.DwarfDebugFlags));
if (!Opts.DwarfDebugProducer.empty())
Ctx.setDwarfDebugProducer(StringRef(Opts.DwarfDebugProducer));
if (!Opts.DebugCompilationDir.empty())
Ctx.setCompilationDir(Opts.DebugCompilationDir);
if (!Opts.MainFileName.empty())
Ctx.setMainFileName(StringRef(Opts.MainFileName));
std::string FS;
if (!Opts.Features.empty()) {
FS = Opts.Features[0];
for (unsigned i = 1, e = Opts.Features.size(); i != e; ++i)
FS += "," + Opts.Features[i];
}
OwningPtr<MCStreamer> Str;
OwningPtr<MCInstrInfo> MCII(TheTarget->createMCInstrInfo());
OwningPtr<MCSubtargetInfo>
STI(TheTarget->createMCSubtargetInfo(Opts.Triple, Opts.CPU, FS));
if (Opts.OutputType == AssemblerInvocation::FT_Asm) {
MCInstPrinter *IP =
TheTarget->createMCInstPrinter(Opts.OutputAsmVariant, *MAI, *MCII, *MRI,
*STI);
MCCodeEmitter *CE = 0;
MCAsmBackend *MAB = 0;
if (Opts.ShowEncoding) {
CE = TheTarget->createMCCodeEmitter(*MCII, *MRI, *STI, Ctx);
MAB = TheTarget->createMCAsmBackend(*MRI, Opts.Triple, Opts.CPU);
}
Str.reset(TheTarget->createAsmStreamer(Ctx, *Out, true,
true,
true,
IP, CE, MAB,
Opts.ShowInst));
} else if (Opts.OutputType == AssemblerInvocation::FT_Null) {
Str.reset(createNullStreamer(Ctx));
} else {
assert(Opts.OutputType == AssemblerInvocation::FT_Obj &&
"Invalid file type!");
MCCodeEmitter *CE = TheTarget->createMCCodeEmitter(*MCII, *MRI, *STI, Ctx);
MCAsmBackend *MAB = TheTarget->createMCAsmBackend(*MRI, Opts.Triple,
Opts.CPU);
Str.reset(TheTarget->createMCObjectStreamer(Opts.Triple, Ctx, *MAB, *Out,
CE, *STI, Opts.RelaxAll,
Opts.NoExecStack));
Str.get()->InitSections();
}
OwningPtr<MCAsmParser> Parser(createMCAsmParser(SrcMgr, Ctx,
*Str.get(), *MAI));
OwningPtr<MCTargetAsmParser> TAP(TheTarget->createMCAsmParser(*STI, *Parser, *MCII));
if (!TAP) {
Diags.Report(diag::err_target_unknown_triple) << Opts.Triple;
return false;
}
Parser->setTargetParser(*TAP.get());
bool Success = !Parser->Run(Opts.NoInitialTextSection);
delete Out;
if (!Success && Opts.OutputPath != "-")
sys::fs::remove(Opts.OutputPath);
return Success;
}
static void LLVMErrorHandler(void *UserData, const std::string &Message,
bool GenCrashDiag) {
DiagnosticsEngine &Diags = *static_cast<DiagnosticsEngine*>(UserData);
Diags.Report(diag::err_fe_error_backend) << Message;
exit(1);
}
int cc1as_main(const char **ArgBegin, const char **ArgEnd,
const char *Argv0, void *MainAddr) {
sys::PrintStackTraceOnErrorSignal();
PrettyStackTraceProgram X(ArgEnd - ArgBegin, ArgBegin);
llvm_shutdown_obj Y;
InitializeAllTargetInfos();
InitializeAllTargetMCs();
InitializeAllAsmParsers();
IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
TextDiagnosticPrinter *DiagClient
= new TextDiagnosticPrinter(errs(), &*DiagOpts);
DiagClient->setPrefix("clang -cc1as");
IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
DiagnosticsEngine Diags(DiagID, &*DiagOpts, DiagClient);
ScopedFatalErrorHandler FatalErrorHandler
(LLVMErrorHandler, static_cast<void*>(&Diags));
AssemblerInvocation Asm;
if (!AssemblerInvocation::CreateFromArgs(Asm, ArgBegin, ArgEnd, Diags))
return 1;
if (Asm.ShowHelp) {
OwningPtr<OptTable> Opts(driver::createCC1AsOptTable());
Opts->PrintHelp(llvm::outs(), "clang -cc1as", "Clang Integrated Assembler");
return 0;
}
if (Asm.ShowVersion) {
llvm::cl::PrintVersionMessage();
return 0;
}
if (!Asm.LLVMArgs.empty()) {
unsigned NumArgs = Asm.LLVMArgs.size();
const char **Args = new const char*[NumArgs + 2];
Args[0] = "clang (LLVM option parsing)";
for (unsigned i = 0; i != NumArgs; ++i)
Args[i + 1] = Asm.LLVMArgs[i].c_str();
Args[NumArgs + 1] = 0;
llvm::cl::ParseCommandLineOptions(NumArgs + 1, Args);
}
bool Success = false;
if (!Diags.hasErrorOccurred())
Success = ExecuteAssembler(Asm, Diags);
TimerGroup::printAll(errs());
return !Success;
}