Home | History | Annotate | Download | only in driver
      1 //===-- cc1as_main.cpp - Clang Assembler  ---------------------------------===//
      2 //
      3 //                     The LLVM Compiler Infrastructure
      4 //
      5 // This file is distributed under the University of Illinois Open Source
      6 // License. See LICENSE.TXT for details.
      7 //
      8 //===----------------------------------------------------------------------===//
      9 //
     10 // This is the entry point to the clang -cc1as functionality, which implements
     11 // the direct interface to the LLVM MC based assembler.
     12 //
     13 //===----------------------------------------------------------------------===//
     14 
     15 #include "clang/Basic/Diagnostic.h"
     16 #include "clang/Basic/DiagnosticOptions.h"
     17 #include "clang/Driver/DriverDiagnostic.h"
     18 #include "clang/Driver/Options.h"
     19 #include "clang/Frontend/FrontendDiagnostic.h"
     20 #include "clang/Frontend/TextDiagnosticPrinter.h"
     21 #include "clang/Frontend/Utils.h"
     22 #include "llvm/ADT/StringSwitch.h"
     23 #include "llvm/ADT/Triple.h"
     24 #include "llvm/IR/DataLayout.h"
     25 #include "llvm/MC/MCAsmBackend.h"
     26 #include "llvm/MC/MCAsmInfo.h"
     27 #include "llvm/MC/MCCodeEmitter.h"
     28 #include "llvm/MC/MCContext.h"
     29 #include "llvm/MC/MCInstrInfo.h"
     30 #include "llvm/MC/MCObjectFileInfo.h"
     31 #include "llvm/MC/MCParser/MCAsmParser.h"
     32 #include "llvm/MC/MCRegisterInfo.h"
     33 #include "llvm/MC/MCStreamer.h"
     34 #include "llvm/MC/MCSubtargetInfo.h"
     35 #include "llvm/MC/MCTargetAsmParser.h"
     36 #include "llvm/MC/MCTargetOptions.h"
     37 #include "llvm/Option/Arg.h"
     38 #include "llvm/Option/ArgList.h"
     39 #include "llvm/Option/OptTable.h"
     40 #include "llvm/Support/CommandLine.h"
     41 #include "llvm/Support/ErrorHandling.h"
     42 #include "llvm/Support/FileSystem.h"
     43 #include "llvm/Support/FormattedStream.h"
     44 #include "llvm/Support/Host.h"
     45 #include "llvm/Support/ManagedStatic.h"
     46 #include "llvm/Support/MemoryBuffer.h"
     47 #include "llvm/Support/Path.h"
     48 #include "llvm/Support/PrettyStackTrace.h"
     49 #include "llvm/Support/Signals.h"
     50 #include "llvm/Support/SourceMgr.h"
     51 #include "llvm/Support/TargetRegistry.h"
     52 #include "llvm/Support/TargetSelect.h"
     53 #include "llvm/Support/Timer.h"
     54 #include "llvm/Support/raw_ostream.h"
     55 #include <memory>
     56 #include <system_error>
     57 using namespace clang;
     58 using namespace clang::driver;
     59 using namespace clang::driver::options;
     60 using namespace llvm;
     61 using namespace llvm::opt;
     62 
     63 namespace {
     64 
     65 /// \brief Helper class for representing a single invocation of the assembler.
     66 struct AssemblerInvocation {
     67   /// @name Target Options
     68   /// @{
     69 
     70   /// The name of the target triple to assemble for.
     71   std::string Triple;
     72 
     73   /// If given, the name of the target CPU to determine which instructions
     74   /// are legal.
     75   std::string CPU;
     76 
     77   /// The list of target specific features to enable or disable -- this should
     78   /// be a list of strings starting with '+' or '-'.
     79   std::vector<std::string> Features;
     80 
     81   /// @}
     82   /// @name Language Options
     83   /// @{
     84 
     85   std::vector<std::string> IncludePaths;
     86   unsigned NoInitialTextSection : 1;
     87   unsigned SaveTemporaryLabels : 1;
     88   unsigned GenDwarfForAssembly : 1;
     89   unsigned CompressDebugSections : 1;
     90   unsigned DwarfVersion;
     91   std::string DwarfDebugFlags;
     92   std::string DwarfDebugProducer;
     93   std::string DebugCompilationDir;
     94   std::string MainFileName;
     95 
     96   /// @}
     97   /// @name Frontend Options
     98   /// @{
     99 
    100   std::string InputFile;
    101   std::vector<std::string> LLVMArgs;
    102   std::string OutputPath;
    103   enum FileType {
    104     FT_Asm,  ///< Assembly (.s) output, transliterate mode.
    105     FT_Null, ///< No output, for timing purposes.
    106     FT_Obj   ///< Object file output.
    107   };
    108   FileType OutputType;
    109   unsigned ShowHelp : 1;
    110   unsigned ShowVersion : 1;
    111 
    112   /// @}
    113   /// @name Transliterate Options
    114   /// @{
    115 
    116   unsigned OutputAsmVariant;
    117   unsigned ShowEncoding : 1;
    118   unsigned ShowInst : 1;
    119 
    120   /// @}
    121   /// @name Assembler Options
    122   /// @{
    123 
    124   unsigned RelaxAll : 1;
    125   unsigned NoExecStack : 1;
    126 
    127   /// @}
    128 
    129 public:
    130   AssemblerInvocation() {
    131     Triple = "";
    132     NoInitialTextSection = 0;
    133     InputFile = "-";
    134     OutputPath = "-";
    135     OutputType = FT_Asm;
    136     OutputAsmVariant = 0;
    137     ShowInst = 0;
    138     ShowEncoding = 0;
    139     RelaxAll = 0;
    140     NoExecStack = 0;
    141     DwarfVersion = 3;
    142   }
    143 
    144   static bool CreateFromArgs(AssemblerInvocation &Res, const char **ArgBegin,
    145                              const char **ArgEnd, DiagnosticsEngine &Diags);
    146 };
    147 
    148 }
    149 
    150 bool AssemblerInvocation::CreateFromArgs(AssemblerInvocation &Opts,
    151                                          const char **ArgBegin,
    152                                          const char **ArgEnd,
    153                                          DiagnosticsEngine &Diags) {
    154   bool Success = true;
    155 
    156   // Parse the arguments.
    157   std::unique_ptr<OptTable> OptTbl(createDriverOptTable());
    158 
    159   const unsigned IncludedFlagsBitmask = options::CC1AsOption;
    160   unsigned MissingArgIndex, MissingArgCount;
    161   std::unique_ptr<InputArgList> Args(
    162       OptTbl->ParseArgs(ArgBegin, ArgEnd, MissingArgIndex, MissingArgCount,
    163                         IncludedFlagsBitmask));
    164 
    165   // Check for missing argument error.
    166   if (MissingArgCount) {
    167     Diags.Report(diag::err_drv_missing_argument)
    168         << Args->getArgString(MissingArgIndex) << MissingArgCount;
    169     Success = false;
    170   }
    171 
    172   // Issue errors on unknown arguments.
    173   for (arg_iterator it = Args->filtered_begin(OPT_UNKNOWN),
    174                     ie = Args->filtered_end();
    175        it != ie; ++it) {
    176     Diags.Report(diag::err_drv_unknown_argument) << (*it)->getAsString(*Args);
    177     Success = false;
    178   }
    179 
    180   // Construct the invocation.
    181 
    182   // Target Options
    183   Opts.Triple = llvm::Triple::normalize(Args->getLastArgValue(OPT_triple));
    184   Opts.CPU = Args->getLastArgValue(OPT_target_cpu);
    185   Opts.Features = Args->getAllArgValues(OPT_target_feature);
    186 
    187   // Use the default target triple if unspecified.
    188   if (Opts.Triple.empty())
    189     Opts.Triple = llvm::sys::getDefaultTargetTriple();
    190 
    191   // Language Options
    192   Opts.IncludePaths = Args->getAllArgValues(OPT_I);
    193   Opts.NoInitialTextSection = Args->hasArg(OPT_n);
    194   Opts.SaveTemporaryLabels = Args->hasArg(OPT_msave_temp_labels);
    195   Opts.GenDwarfForAssembly = Args->hasArg(OPT_g_Flag);
    196   Opts.CompressDebugSections = Args->hasArg(OPT_compress_debug_sections);
    197   if (Args->hasArg(OPT_gdwarf_2))
    198     Opts.DwarfVersion = 2;
    199   if (Args->hasArg(OPT_gdwarf_3))
    200     Opts.DwarfVersion = 3;
    201   if (Args->hasArg(OPT_gdwarf_4))
    202     Opts.DwarfVersion = 4;
    203   Opts.DwarfDebugFlags = Args->getLastArgValue(OPT_dwarf_debug_flags);
    204   Opts.DwarfDebugProducer = Args->getLastArgValue(OPT_dwarf_debug_producer);
    205   Opts.DebugCompilationDir = Args->getLastArgValue(OPT_fdebug_compilation_dir);
    206   Opts.MainFileName = Args->getLastArgValue(OPT_main_file_name);
    207 
    208   // Frontend Options
    209   if (Args->hasArg(OPT_INPUT)) {
    210     bool First = true;
    211     for (arg_iterator it = Args->filtered_begin(OPT_INPUT),
    212            ie = Args->filtered_end(); it != ie; ++it, First=false) {
    213       const Arg *A = it;
    214       if (First)
    215         Opts.InputFile = A->getValue();
    216       else {
    217         Diags.Report(diag::err_drv_unknown_argument) << A->getAsString(*Args);
    218         Success = false;
    219       }
    220     }
    221   }
    222   Opts.LLVMArgs = Args->getAllArgValues(OPT_mllvm);
    223   Opts.OutputPath = Args->getLastArgValue(OPT_o);
    224   if (Arg *A = Args->getLastArg(OPT_filetype)) {
    225     StringRef Name = A->getValue();
    226     unsigned OutputType = StringSwitch<unsigned>(Name)
    227       .Case("asm", FT_Asm)
    228       .Case("null", FT_Null)
    229       .Case("obj", FT_Obj)
    230       .Default(~0U);
    231     if (OutputType == ~0U) {
    232       Diags.Report(diag::err_drv_invalid_value)
    233         << A->getAsString(*Args) << Name;
    234       Success = false;
    235     } else
    236       Opts.OutputType = FileType(OutputType);
    237   }
    238   Opts.ShowHelp = Args->hasArg(OPT_help);
    239   Opts.ShowVersion = Args->hasArg(OPT_version);
    240 
    241   // Transliterate Options
    242   Opts.OutputAsmVariant =
    243       getLastArgIntValue(*Args.get(), OPT_output_asm_variant, 0, Diags);
    244   Opts.ShowEncoding = Args->hasArg(OPT_show_encoding);
    245   Opts.ShowInst = Args->hasArg(OPT_show_inst);
    246 
    247   // Assemble Options
    248   Opts.RelaxAll = Args->hasArg(OPT_mrelax_all);
    249   Opts.NoExecStack =  Args->hasArg(OPT_mno_exec_stack);
    250 
    251   return Success;
    252 }
    253 
    254 static formatted_raw_ostream *GetOutputStream(AssemblerInvocation &Opts,
    255                                               DiagnosticsEngine &Diags,
    256                                               bool Binary) {
    257   if (Opts.OutputPath.empty())
    258     Opts.OutputPath = "-";
    259 
    260   // Make sure that the Out file gets unlinked from the disk if we get a
    261   // SIGINT.
    262   if (Opts.OutputPath != "-")
    263     sys::RemoveFileOnSignal(Opts.OutputPath);
    264 
    265   std::string Error;
    266   raw_fd_ostream *Out =
    267       new raw_fd_ostream(Opts.OutputPath.c_str(), Error,
    268                          (Binary ? sys::fs::F_None : sys::fs::F_Text));
    269   if (!Error.empty()) {
    270     Diags.Report(diag::err_fe_unable_to_open_output)
    271       << Opts.OutputPath << Error;
    272     delete Out;
    273     return nullptr;
    274   }
    275 
    276   return new formatted_raw_ostream(*Out, formatted_raw_ostream::DELETE_STREAM);
    277 }
    278 
    279 static bool ExecuteAssembler(AssemblerInvocation &Opts,
    280                              DiagnosticsEngine &Diags) {
    281   // Get the target specific parser.
    282   std::string Error;
    283   const Target *TheTarget = TargetRegistry::lookupTarget(Opts.Triple, Error);
    284   if (!TheTarget)
    285     return Diags.Report(diag::err_target_unknown_triple) << Opts.Triple;
    286 
    287   ErrorOr<std::unique_ptr<MemoryBuffer>> Buffer =
    288       MemoryBuffer::getFileOrSTDIN(Opts.InputFile);
    289 
    290   if (std::error_code EC = Buffer.getError()) {
    291     Error = EC.message();
    292     return Diags.Report(diag::err_fe_error_reading) << Opts.InputFile;
    293   }
    294 
    295   SourceMgr SrcMgr;
    296 
    297   // Tell SrcMgr about this buffer, which is what the parser will pick up.
    298   SrcMgr.AddNewSourceBuffer(Buffer->release(), SMLoc());
    299 
    300   // Record the location of the include directories so that the lexer can find
    301   // it later.
    302   SrcMgr.setIncludeDirs(Opts.IncludePaths);
    303 
    304   std::unique_ptr<MCRegisterInfo> MRI(TheTarget->createMCRegInfo(Opts.Triple));
    305   assert(MRI && "Unable to create target register info!");
    306 
    307   std::unique_ptr<MCAsmInfo> MAI(TheTarget->createMCAsmInfo(*MRI, Opts.Triple));
    308   assert(MAI && "Unable to create target asm info!");
    309 
    310   // Ensure MCAsmInfo initialization occurs before any use, otherwise sections
    311   // may be created with a combination of default and explicit settings.
    312   if (Opts.CompressDebugSections)
    313     MAI->setCompressDebugSections(true);
    314 
    315   bool IsBinary = Opts.OutputType == AssemblerInvocation::FT_Obj;
    316   std::unique_ptr<formatted_raw_ostream> Out(
    317       GetOutputStream(Opts, Diags, IsBinary));
    318   if (!Out)
    319     return true;
    320 
    321   // FIXME: This is not pretty. MCContext has a ptr to MCObjectFileInfo and
    322   // MCObjectFileInfo needs a MCContext reference in order to initialize itself.
    323   std::unique_ptr<MCObjectFileInfo> MOFI(new MCObjectFileInfo());
    324 
    325   MCContext Ctx(MAI.get(), MRI.get(), MOFI.get(), &SrcMgr);
    326   // FIXME: Assembler behavior can change with -static.
    327   MOFI->InitMCObjectFileInfo(Opts.Triple,
    328                              Reloc::Default, CodeModel::Default, Ctx);
    329   if (Opts.SaveTemporaryLabels)
    330     Ctx.setAllowTemporaryLabels(false);
    331   if (Opts.GenDwarfForAssembly)
    332     Ctx.setGenDwarfForAssembly(true);
    333   if (!Opts.DwarfDebugFlags.empty())
    334     Ctx.setDwarfDebugFlags(StringRef(Opts.DwarfDebugFlags));
    335   if (!Opts.DwarfDebugProducer.empty())
    336     Ctx.setDwarfDebugProducer(StringRef(Opts.DwarfDebugProducer));
    337   if (!Opts.DebugCompilationDir.empty())
    338     Ctx.setCompilationDir(Opts.DebugCompilationDir);
    339   if (!Opts.MainFileName.empty())
    340     Ctx.setMainFileName(StringRef(Opts.MainFileName));
    341   Ctx.setDwarfVersion(Opts.DwarfVersion);
    342 
    343   // Build up the feature string from the target feature list.
    344   std::string FS;
    345   if (!Opts.Features.empty()) {
    346     FS = Opts.Features[0];
    347     for (unsigned i = 1, e = Opts.Features.size(); i != e; ++i)
    348       FS += "," + Opts.Features[i];
    349   }
    350 
    351   std::unique_ptr<MCStreamer> Str;
    352 
    353   std::unique_ptr<MCInstrInfo> MCII(TheTarget->createMCInstrInfo());
    354   std::unique_ptr<MCSubtargetInfo> STI(
    355       TheTarget->createMCSubtargetInfo(Opts.Triple, Opts.CPU, FS));
    356 
    357   // FIXME: There is a bit of code duplication with addPassesToEmitFile.
    358   if (Opts.OutputType == AssemblerInvocation::FT_Asm) {
    359     MCInstPrinter *IP =
    360       TheTarget->createMCInstPrinter(Opts.OutputAsmVariant, *MAI, *MCII, *MRI,
    361                                      *STI);
    362     MCCodeEmitter *CE = nullptr;
    363     MCAsmBackend *MAB = nullptr;
    364     if (Opts.ShowEncoding) {
    365       CE = TheTarget->createMCCodeEmitter(*MCII, *MRI, *STI, Ctx);
    366       MAB = TheTarget->createMCAsmBackend(*MRI, Opts.Triple, Opts.CPU);
    367     }
    368     Str.reset(TheTarget->createAsmStreamer(Ctx, *Out, /*asmverbose*/true,
    369                                            /*useDwarfDirectory*/ true,
    370                                            IP, CE, MAB,
    371                                            Opts.ShowInst));
    372   } else if (Opts.OutputType == AssemblerInvocation::FT_Null) {
    373     Str.reset(createNullStreamer(Ctx));
    374   } else {
    375     assert(Opts.OutputType == AssemblerInvocation::FT_Obj &&
    376            "Invalid file type!");
    377     MCCodeEmitter *CE = TheTarget->createMCCodeEmitter(*MCII, *MRI, *STI, Ctx);
    378     MCAsmBackend *MAB = TheTarget->createMCAsmBackend(*MRI, Opts.Triple,
    379                                                       Opts.CPU);
    380     Str.reset(TheTarget->createMCObjectStreamer(Opts.Triple, Ctx, *MAB, *Out,
    381                                                 CE, *STI, Opts.RelaxAll,
    382                                                 Opts.NoExecStack));
    383     Str.get()->InitSections();
    384   }
    385 
    386   bool Failed = false;
    387 
    388   std::unique_ptr<MCAsmParser> Parser(
    389       createMCAsmParser(SrcMgr, Ctx, *Str.get(), *MAI));
    390 
    391   // FIXME: init MCTargetOptions from sanitizer flags here.
    392   MCTargetOptions Options;
    393   std::unique_ptr<MCTargetAsmParser> TAP(
    394       TheTarget->createMCAsmParser(*STI, *Parser, *MCII, Options));
    395   if (!TAP)
    396     Failed = Diags.Report(diag::err_target_unknown_triple) << Opts.Triple;
    397 
    398   if (!Failed) {
    399     Parser->setTargetParser(*TAP.get());
    400     Failed = Parser->Run(Opts.NoInitialTextSection);
    401   }
    402 
    403   // Close the output stream early.
    404   Out.reset();
    405 
    406   // Delete output file if there were errors.
    407   if (Failed && Opts.OutputPath != "-")
    408     sys::fs::remove(Opts.OutputPath);
    409 
    410   return Failed;
    411 }
    412 
    413 static void LLVMErrorHandler(void *UserData, const std::string &Message,
    414                              bool GenCrashDiag) {
    415   DiagnosticsEngine &Diags = *static_cast<DiagnosticsEngine*>(UserData);
    416 
    417   Diags.Report(diag::err_fe_error_backend) << Message;
    418 
    419   // We cannot recover from llvm errors.
    420   exit(1);
    421 }
    422 
    423 int cc1as_main(const char **ArgBegin, const char **ArgEnd,
    424                const char *Argv0, void *MainAddr) {
    425   // Print a stack trace if we signal out.
    426   sys::PrintStackTraceOnErrorSignal();
    427   PrettyStackTraceProgram X(ArgEnd - ArgBegin, ArgBegin);
    428   llvm_shutdown_obj Y;  // Call llvm_shutdown() on exit.
    429 
    430   // Initialize targets and assembly printers/parsers.
    431   InitializeAllTargetInfos();
    432   InitializeAllTargetMCs();
    433   InitializeAllAsmParsers();
    434 
    435   // Construct our diagnostic client.
    436   IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
    437   TextDiagnosticPrinter *DiagClient
    438     = new TextDiagnosticPrinter(errs(), &*DiagOpts);
    439   DiagClient->setPrefix("clang -cc1as");
    440   IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
    441   DiagnosticsEngine Diags(DiagID, &*DiagOpts, DiagClient);
    442 
    443   // Set an error handler, so that any LLVM backend diagnostics go through our
    444   // error handler.
    445   ScopedFatalErrorHandler FatalErrorHandler
    446     (LLVMErrorHandler, static_cast<void*>(&Diags));
    447 
    448   // Parse the arguments.
    449   AssemblerInvocation Asm;
    450   if (!AssemblerInvocation::CreateFromArgs(Asm, ArgBegin, ArgEnd, Diags))
    451     return 1;
    452 
    453   if (Asm.ShowHelp) {
    454     std::unique_ptr<OptTable> Opts(driver::createDriverOptTable());
    455     Opts->PrintHelp(llvm::outs(), "clang -cc1as", "Clang Integrated Assembler",
    456                     /*Include=*/driver::options::CC1AsOption, /*Exclude=*/0);
    457     return 0;
    458   }
    459 
    460   // Honor -version.
    461   //
    462   // FIXME: Use a better -version message?
    463   if (Asm.ShowVersion) {
    464     llvm::cl::PrintVersionMessage();
    465     return 0;
    466   }
    467 
    468   // Honor -mllvm.
    469   //
    470   // FIXME: Remove this, one day.
    471   if (!Asm.LLVMArgs.empty()) {
    472     unsigned NumArgs = Asm.LLVMArgs.size();
    473     const char **Args = new const char*[NumArgs + 2];
    474     Args[0] = "clang (LLVM option parsing)";
    475     for (unsigned i = 0; i != NumArgs; ++i)
    476       Args[i + 1] = Asm.LLVMArgs[i].c_str();
    477     Args[NumArgs + 1] = nullptr;
    478     llvm::cl::ParseCommandLineOptions(NumArgs + 1, Args);
    479   }
    480 
    481   // Execute the invocation, unless there were parsing errors.
    482   bool Failed = Diags.hasErrorOccurred() || ExecuteAssembler(Asm, Diags);
    483 
    484   // If any timers were active but haven't been destroyed yet, print their
    485   // results now.
    486   TimerGroup::printAll(errs());
    487 
    488   return !!Failed;
    489 }
    490 
    491