LCOV - code coverage report
Current view: top level - src - zig_clang_cc1as_main.cpp (source / functions) Hit Total Coverage
Test: coverage.info.cleaned Lines: 179 270 66.3 %
Date: 1970-01-01 00:00:01 Functions: 6 7 85.7 %
Branches: 51 120 42.5 %

           Branch data     Line data    Source code
       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/STLExtras.h"
      23                 :            : #include "llvm/ADT/StringSwitch.h"
      24                 :            : #include "llvm/ADT/Triple.h"
      25                 :            : #include "llvm/IR/DataLayout.h"
      26                 :            : #include "llvm/MC/MCAsmBackend.h"
      27                 :            : #include "llvm/MC/MCAsmInfo.h"
      28                 :            : #include "llvm/MC/MCCodeEmitter.h"
      29                 :            : #include "llvm/MC/MCContext.h"
      30                 :            : #include "llvm/MC/MCInstrInfo.h"
      31                 :            : #include "llvm/MC/MCObjectFileInfo.h"
      32                 :            : #include "llvm/MC/MCObjectWriter.h"
      33                 :            : #include "llvm/MC/MCParser/MCAsmParser.h"
      34                 :            : #include "llvm/MC/MCParser/MCTargetAsmParser.h"
      35                 :            : #include "llvm/MC/MCRegisterInfo.h"
      36                 :            : #include "llvm/MC/MCSectionMachO.h"
      37                 :            : #include "llvm/MC/MCStreamer.h"
      38                 :            : #include "llvm/MC/MCSubtargetInfo.h"
      39                 :            : #include "llvm/MC/MCTargetOptions.h"
      40                 :            : #include "llvm/Option/Arg.h"
      41                 :            : #include "llvm/Option/ArgList.h"
      42                 :            : #include "llvm/Option/OptTable.h"
      43                 :            : #include "llvm/Support/CommandLine.h"
      44                 :            : #include "llvm/Support/ErrorHandling.h"
      45                 :            : #include "llvm/Support/FileSystem.h"
      46                 :            : #include "llvm/Support/FormattedStream.h"
      47                 :            : #include "llvm/Support/Host.h"
      48                 :            : #include "llvm/Support/MemoryBuffer.h"
      49                 :            : #include "llvm/Support/Path.h"
      50                 :            : #include "llvm/Support/Signals.h"
      51                 :            : #include "llvm/Support/SourceMgr.h"
      52                 :            : #include "llvm/Support/TargetRegistry.h"
      53                 :            : #include "llvm/Support/TargetSelect.h"
      54                 :            : #include "llvm/Support/Timer.h"
      55                 :            : #include "llvm/Support/raw_ostream.h"
      56                 :            : #include <memory>
      57                 :            : #include <system_error>
      58                 :            : using namespace clang;
      59                 :            : using namespace clang::driver;
      60                 :            : using namespace clang::driver::options;
      61                 :            : using namespace llvm;
      62                 :            : using namespace llvm::opt;
      63                 :            : 
      64                 :            : namespace {
      65                 :            : 
      66                 :            : /// Helper class for representing a single invocation of the assembler.
      67                 :         16 : struct AssemblerInvocation {
      68                 :            :   /// @name Target Options
      69                 :            :   /// @{
      70                 :            : 
      71                 :            :   /// The name of the target triple to assemble for.
      72                 :            :   std::string Triple;
      73                 :            : 
      74                 :            :   /// If given, the name of the target CPU to determine which instructions
      75                 :            :   /// are legal.
      76                 :            :   std::string CPU;
      77                 :            : 
      78                 :            :   /// The list of target specific features to enable or disable -- this should
      79                 :            :   /// be a list of strings starting with '+' or '-'.
      80                 :            :   std::vector<std::string> Features;
      81                 :            : 
      82                 :            :   /// The list of symbol definitions.
      83                 :            :   std::vector<std::string> SymbolDefs;
      84                 :            : 
      85                 :            :   /// @}
      86                 :            :   /// @name Language Options
      87                 :            :   /// @{
      88                 :            : 
      89                 :            :   std::vector<std::string> IncludePaths;
      90                 :            :   unsigned NoInitialTextSection : 1;
      91                 :            :   unsigned SaveTemporaryLabels : 1;
      92                 :            :   unsigned GenDwarfForAssembly : 1;
      93                 :            :   unsigned RelaxELFRelocations : 1;
      94                 :            :   unsigned DwarfVersion;
      95                 :            :   std::string DwarfDebugFlags;
      96                 :            :   std::string DwarfDebugProducer;
      97                 :            :   std::string DebugCompilationDir;
      98                 :            :   std::map<const std::string, const std::string> DebugPrefixMap;
      99                 :            :   llvm::DebugCompressionType CompressDebugSections =
     100                 :            :       llvm::DebugCompressionType::None;
     101                 :            :   std::string MainFileName;
     102                 :            :   std::string SplitDwarfFile;
     103                 :            : 
     104                 :            :   /// @}
     105                 :            :   /// @name Frontend Options
     106                 :            :   /// @{
     107                 :            : 
     108                 :            :   std::string InputFile;
     109                 :            :   std::vector<std::string> LLVMArgs;
     110                 :            :   std::string OutputPath;
     111                 :            :   enum FileType {
     112                 :            :     FT_Asm,  ///< Assembly (.s) output, transliterate mode.
     113                 :            :     FT_Null, ///< No output, for timing purposes.
     114                 :            :     FT_Obj   ///< Object file output.
     115                 :            :   };
     116                 :            :   FileType OutputType;
     117                 :            :   unsigned ShowHelp : 1;
     118                 :            :   unsigned ShowVersion : 1;
     119                 :            : 
     120                 :            :   /// @}
     121                 :            :   /// @name Transliterate Options
     122                 :            :   /// @{
     123                 :            : 
     124                 :            :   unsigned OutputAsmVariant;
     125                 :            :   unsigned ShowEncoding : 1;
     126                 :            :   unsigned ShowInst : 1;
     127                 :            : 
     128                 :            :   /// @}
     129                 :            :   /// @name Assembler Options
     130                 :            :   /// @{
     131                 :            : 
     132                 :            :   unsigned RelaxAll : 1;
     133                 :            :   unsigned NoExecStack : 1;
     134                 :            :   unsigned FatalWarnings : 1;
     135                 :            :   unsigned IncrementalLinkerCompatible : 1;
     136                 :            :   unsigned EmbedBitcode : 1;
     137                 :            : 
     138                 :            :   /// The name of the relocation model to use.
     139                 :            :   std::string RelocationModel;
     140                 :            : 
     141                 :            :   /// @}
     142                 :            : 
     143                 :            : public:
     144                 :         16 :   AssemblerInvocation() {
     145                 :          8 :     Triple = "";
     146                 :          8 :     NoInitialTextSection = 0;
     147                 :          8 :     InputFile = "-";
     148                 :          8 :     OutputPath = "-";
     149                 :          8 :     OutputType = FT_Asm;
     150                 :          8 :     OutputAsmVariant = 0;
     151                 :          8 :     ShowInst = 0;
     152                 :          8 :     ShowEncoding = 0;
     153                 :          8 :     RelaxAll = 0;
     154                 :          8 :     NoExecStack = 0;
     155                 :          8 :     FatalWarnings = 0;
     156                 :          8 :     IncrementalLinkerCompatible = 0;
     157                 :          8 :     DwarfVersion = 0;
     158                 :          8 :     EmbedBitcode = 0;
     159                 :          8 :   }
     160                 :            : 
     161                 :            :   static bool CreateFromArgs(AssemblerInvocation &Res,
     162                 :            :                              ArrayRef<const char *> Argv,
     163                 :            :                              DiagnosticsEngine &Diags);
     164                 :            : };
     165                 :            : 
     166                 :            : }
     167                 :            : 
     168                 :          8 : bool AssemblerInvocation::CreateFromArgs(AssemblerInvocation &Opts,
     169                 :            :                                          ArrayRef<const char *> Argv,
     170                 :            :                                          DiagnosticsEngine &Diags) {
     171                 :          8 :   bool Success = true;
     172                 :            : 
     173                 :            :   // Parse the arguments.
     174                 :         16 :   std::unique_ptr<OptTable> OptTbl(createDriverOptTable());
     175                 :            : 
     176                 :          8 :   const unsigned IncludedFlagsBitmask = options::CC1AsOption;
     177                 :            :   unsigned MissingArgIndex, MissingArgCount;
     178                 :            :   InputArgList Args = OptTbl->ParseArgs(Argv, MissingArgIndex, MissingArgCount,
     179                 :         16 :                                         IncludedFlagsBitmask);
     180                 :            : 
     181                 :            :   // Check for missing argument error.
     182         [ -  + ]:          8 :   if (MissingArgCount) {
     183                 :          0 :     Diags.Report(diag::err_drv_missing_argument)
     184                 :          0 :         << Args.getArgString(MissingArgIndex) << MissingArgCount;
     185                 :          0 :     Success = false;
     186                 :            :   }
     187                 :            : 
     188                 :            :   // Issue errors on unknown arguments.
     189         [ -  + ]:          8 :   for (const Arg *A : Args.filtered(OPT_UNKNOWN)) {
     190                 :          0 :     auto ArgString = A->getAsString(Args);
     191                 :          0 :     std::string Nearest;
     192         [ #  # ]:          0 :     if (OptTbl->findNearest(ArgString, Nearest, IncludedFlagsBitmask) > 1)
     193                 :          0 :       Diags.Report(diag::err_drv_unknown_argument) << ArgString;
     194                 :            :     else
     195                 :          0 :       Diags.Report(diag::err_drv_unknown_argument_with_suggestion)
     196                 :          0 :           << ArgString << Nearest;
     197                 :          0 :     Success = false;
     198                 :            :   }
     199                 :            : 
     200                 :            :   // Construct the invocation.
     201                 :            : 
     202                 :            :   // Target Options
     203                 :          8 :   Opts.Triple = llvm::Triple::normalize(Args.getLastArgValue(OPT_triple));
     204                 :          8 :   Opts.CPU = Args.getLastArgValue(OPT_target_cpu);
     205                 :          8 :   Opts.Features = Args.getAllArgValues(OPT_target_feature);
     206                 :            : 
     207                 :            :   // Use the default target triple if unspecified.
     208         [ -  + ]:          8 :   if (Opts.Triple.empty())
     209                 :          0 :     Opts.Triple = llvm::sys::getDefaultTargetTriple();
     210                 :            : 
     211                 :            :   // Language Options
     212                 :          8 :   Opts.IncludePaths = Args.getAllArgValues(OPT_I);
     213                 :          8 :   Opts.NoInitialTextSection = Args.hasArg(OPT_n);
     214                 :          8 :   Opts.SaveTemporaryLabels = Args.hasArg(OPT_msave_temp_labels);
     215                 :            :   // Any DebugInfoKind implies GenDwarfForAssembly.
     216                 :          8 :   Opts.GenDwarfForAssembly = Args.hasArg(OPT_debug_info_kind_EQ);
     217                 :            : 
     218         [ -  + ]:          8 :   if (const Arg *A = Args.getLastArg(OPT_compress_debug_sections,
     219                 :          8 :                                      OPT_compress_debug_sections_EQ)) {
     220         [ #  # ]:          0 :     if (A->getOption().getID() == OPT_compress_debug_sections) {
     221                 :            :       // TODO: be more clever about the compression type auto-detection
     222                 :          0 :       Opts.CompressDebugSections = llvm::DebugCompressionType::GNU;
     223                 :            :     } else {
     224                 :          0 :       Opts.CompressDebugSections =
     225                 :          0 :           llvm::StringSwitch<llvm::DebugCompressionType>(A->getValue())
     226                 :          0 :               .Case("none", llvm::DebugCompressionType::None)
     227                 :          0 :               .Case("zlib", llvm::DebugCompressionType::Z)
     228                 :          0 :               .Case("zlib-gnu", llvm::DebugCompressionType::GNU)
     229                 :          0 :               .Default(llvm::DebugCompressionType::None);
     230                 :            :     }
     231                 :            :   }
     232                 :            : 
     233                 :          8 :   Opts.RelaxELFRelocations = Args.hasArg(OPT_mrelax_relocations);
     234                 :          8 :   Opts.DwarfVersion = getLastArgIntValue(Args, OPT_dwarf_version_EQ, 2, Diags);
     235                 :          8 :   Opts.DwarfDebugFlags = Args.getLastArgValue(OPT_dwarf_debug_flags);
     236                 :          8 :   Opts.DwarfDebugProducer = Args.getLastArgValue(OPT_dwarf_debug_producer);
     237                 :          8 :   Opts.DebugCompilationDir = Args.getLastArgValue(OPT_fdebug_compilation_dir);
     238                 :          8 :   Opts.MainFileName = Args.getLastArgValue(OPT_main_file_name);
     239                 :            : 
     240         [ -  + ]:          8 :   for (const auto &Arg : Args.getAllArgValues(OPT_fdebug_prefix_map_EQ))
     241                 :          0 :     Opts.DebugPrefixMap.insert(StringRef(Arg).split('='));
     242                 :            : 
     243                 :            :   // Frontend Options
     244         [ +  - ]:          8 :   if (Args.hasArg(OPT_INPUT)) {
     245                 :          8 :     bool First = true;
     246         [ +  + ]:         16 :     for (const Arg *A : Args.filtered(OPT_INPUT)) {
     247         [ +  - ]:          8 :       if (First) {
     248                 :          8 :         Opts.InputFile = A->getValue();
     249                 :          8 :         First = false;
     250                 :            :       } else {
     251                 :          0 :         Diags.Report(diag::err_drv_unknown_argument) << A->getAsString(Args);
     252                 :          0 :         Success = false;
     253                 :            :       }
     254                 :            :     }
     255                 :            :   }
     256                 :          8 :   Opts.LLVMArgs = Args.getAllArgValues(OPT_mllvm);
     257                 :          8 :   Opts.OutputPath = Args.getLastArgValue(OPT_o);
     258                 :          8 :   Opts.SplitDwarfFile = Args.getLastArgValue(OPT_split_dwarf_file);
     259         [ +  - ]:          8 :   if (Arg *A = Args.getLastArg(OPT_filetype)) {
     260                 :          8 :     StringRef Name = A->getValue();
     261                 :          8 :     unsigned OutputType = StringSwitch<unsigned>(Name)
     262                 :          8 :       .Case("asm", FT_Asm)
     263                 :          8 :       .Case("null", FT_Null)
     264                 :          8 :       .Case("obj", FT_Obj)
     265                 :          8 :       .Default(~0U);
     266         [ -  + ]:          8 :     if (OutputType == ~0U) {
     267                 :          0 :       Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Name;
     268                 :          0 :       Success = false;
     269                 :            :     } else
     270                 :          8 :       Opts.OutputType = FileType(OutputType);
     271                 :            :   }
     272                 :          8 :   Opts.ShowHelp = Args.hasArg(OPT_help);
     273                 :          8 :   Opts.ShowVersion = Args.hasArg(OPT_version);
     274                 :            : 
     275                 :            :   // Transliterate Options
     276                 :          8 :   Opts.OutputAsmVariant =
     277                 :          8 :       getLastArgIntValue(Args, OPT_output_asm_variant, 0, Diags);
     278                 :          8 :   Opts.ShowEncoding = Args.hasArg(OPT_show_encoding);
     279                 :          8 :   Opts.ShowInst = Args.hasArg(OPT_show_inst);
     280                 :            : 
     281                 :            :   // Assemble Options
     282                 :          8 :   Opts.RelaxAll = Args.hasArg(OPT_mrelax_all);
     283                 :          8 :   Opts.NoExecStack = Args.hasArg(OPT_mno_exec_stack);
     284                 :          8 :   Opts.FatalWarnings = Args.hasArg(OPT_massembler_fatal_warnings);
     285                 :          8 :   Opts.RelocationModel = Args.getLastArgValue(OPT_mrelocation_model, "pic");
     286                 :          8 :   Opts.IncrementalLinkerCompatible =
     287                 :          8 :       Args.hasArg(OPT_mincremental_linker_compatible);
     288                 :          8 :   Opts.SymbolDefs = Args.getAllArgValues(OPT_defsym);
     289                 :            : 
     290                 :            :   // EmbedBitcode Option. If -fembed-bitcode is enabled, set the flag.
     291                 :            :   // EmbedBitcode behaves the same for all embed options for assembly files.
     292         [ -  + ]:          8 :   if (auto *A = Args.getLastArg(OPT_fembed_bitcode_EQ)) {
     293                 :          0 :     Opts.EmbedBitcode = llvm::StringSwitch<unsigned>(A->getValue())
     294                 :          0 :                             .Case("all", 1)
     295                 :          0 :                             .Case("bitcode", 1)
     296                 :          0 :                             .Case("marker", 1)
     297                 :          0 :                             .Default(0);
     298                 :            :   }
     299                 :            : 
     300                 :         16 :   return Success;
     301                 :            : }
     302                 :            : 
     303                 :            : static std::unique_ptr<raw_fd_ostream>
     304                 :          8 : getOutputStream(StringRef Path, DiagnosticsEngine &Diags, bool Binary) {
     305                 :            :   // Make sure that the Out file gets unlinked from the disk if we get a
     306                 :            :   // SIGINT.
     307         [ +  - ]:          8 :   if (Path != "-")
     308                 :          8 :     sys::RemoveFileOnSignal(Path);
     309                 :            : 
     310                 :          8 :   std::error_code EC;
     311                 :            :   auto Out = llvm::make_unique<raw_fd_ostream>(
     312         [ +  - ]:         16 :       Path, EC, (Binary ? sys::fs::F_None : sys::fs::F_Text));
     313         [ -  + ]:          8 :   if (EC) {
     314                 :          0 :     Diags.Report(diag::err_fe_unable_to_open_output) << Path << EC.message();
     315                 :          0 :     return nullptr;
     316                 :            :   }
     317                 :            : 
     318                 :          8 :   return Out;
     319                 :            : }
     320                 :            : 
     321                 :          8 : static bool ExecuteAssembler(AssemblerInvocation &Opts,
     322                 :            :                              DiagnosticsEngine &Diags) {
     323                 :            :   // Get the target specific parser.
     324                 :         16 :   std::string Error;
     325                 :          8 :   const Target *TheTarget = TargetRegistry::lookupTarget(Opts.Triple, Error);
     326         [ -  + ]:          8 :   if (!TheTarget)
     327                 :          0 :     return Diags.Report(diag::err_target_unknown_triple) << Opts.Triple;
     328                 :            : 
     329                 :            :   ErrorOr<std::unique_ptr<MemoryBuffer>> Buffer =
     330                 :         16 :       MemoryBuffer::getFileOrSTDIN(Opts.InputFile);
     331                 :            : 
     332         [ -  + ]:          8 :   if (std::error_code EC = Buffer.getError()) {
     333                 :          0 :     Error = EC.message();
     334                 :          0 :     return Diags.Report(diag::err_fe_error_reading) << Opts.InputFile;
     335                 :            :   }
     336                 :            : 
     337                 :         16 :   SourceMgr SrcMgr;
     338                 :            : 
     339                 :            :   // Tell SrcMgr about this buffer, which is what the parser will pick up.
     340                 :          8 :   SrcMgr.AddNewSourceBuffer(std::move(*Buffer), SMLoc());
     341                 :            : 
     342                 :            :   // Record the location of the include directories so that the lexer can find
     343                 :            :   // it later.
     344                 :          8 :   SrcMgr.setIncludeDirs(Opts.IncludePaths);
     345                 :            : 
     346                 :         16 :   std::unique_ptr<MCRegisterInfo> MRI(TheTarget->createMCRegInfo(Opts.Triple));
     347         [ +  - ]:          8 :   assert(MRI && "Unable to create target register info!");
     348                 :            : 
     349                 :         16 :   std::unique_ptr<MCAsmInfo> MAI(TheTarget->createMCAsmInfo(*MRI, Opts.Triple));
     350         [ +  - ]:          8 :   assert(MAI && "Unable to create target asm info!");
     351                 :            : 
     352                 :            :   // Ensure MCAsmInfo initialization occurs before any use, otherwise sections
     353                 :            :   // may be created with a combination of default and explicit settings.
     354                 :          8 :   MAI->setCompressDebugSections(Opts.CompressDebugSections);
     355                 :            : 
     356                 :          8 :   MAI->setRelaxELFRelocations(Opts.RelaxELFRelocations);
     357                 :            : 
     358                 :          8 :   bool IsBinary = Opts.OutputType == AssemblerInvocation::FT_Obj;
     359         [ -  + ]:          8 :   if (Opts.OutputPath.empty())
     360                 :          0 :     Opts.OutputPath = "-";
     361                 :            :   std::unique_ptr<raw_fd_ostream> FDOS =
     362                 :         16 :       getOutputStream(Opts.OutputPath, Diags, IsBinary);
     363         [ -  + ]:          8 :   if (!FDOS)
     364                 :          0 :     return true;
     365                 :          8 :   std::unique_ptr<raw_fd_ostream> DwoOS;
     366         [ -  + ]:          8 :   if (!Opts.SplitDwarfFile.empty())
     367                 :          0 :     DwoOS = getOutputStream(Opts.SplitDwarfFile, Diags, IsBinary);
     368                 :            : 
     369                 :            :   // FIXME: This is not pretty. MCContext has a ptr to MCObjectFileInfo and
     370                 :            :   // MCObjectFileInfo needs a MCContext reference in order to initialize itself.
     371                 :         16 :   std::unique_ptr<MCObjectFileInfo> MOFI(new MCObjectFileInfo());
     372                 :            : 
     373                 :         16 :   MCContext Ctx(MAI.get(), MRI.get(), MOFI.get(), &SrcMgr);
     374                 :            : 
     375                 :          8 :   bool PIC = false;
     376         [ -  + ]:          8 :   if (Opts.RelocationModel == "static") {
     377                 :          0 :     PIC = false;
     378         [ +  - ]:          8 :   } else if (Opts.RelocationModel == "pic") {
     379                 :          8 :     PIC = true;
     380                 :            :   } else {
     381         [ #  # ]:          0 :     assert(Opts.RelocationModel == "dynamic-no-pic" &&
     382                 :            :            "Invalid PIC model!");
     383                 :          0 :     PIC = false;
     384                 :            :   }
     385                 :            : 
     386                 :          8 :   MOFI->InitMCObjectFileInfo(Triple(Opts.Triple), PIC, Ctx);
     387         [ -  + ]:          8 :   if (Opts.SaveTemporaryLabels)
     388                 :          0 :     Ctx.setAllowTemporaryLabels(false);
     389         [ +  - ]:          8 :   if (Opts.GenDwarfForAssembly)
     390                 :          8 :     Ctx.setGenDwarfForAssembly(true);
     391         [ -  + ]:          8 :   if (!Opts.DwarfDebugFlags.empty())
     392                 :          0 :     Ctx.setDwarfDebugFlags(StringRef(Opts.DwarfDebugFlags));
     393         [ +  - ]:          8 :   if (!Opts.DwarfDebugProducer.empty())
     394                 :          8 :     Ctx.setDwarfDebugProducer(StringRef(Opts.DwarfDebugProducer));
     395         [ +  - ]:          8 :   if (!Opts.DebugCompilationDir.empty())
     396                 :          8 :     Ctx.setCompilationDir(Opts.DebugCompilationDir);
     397         [ -  + ]:          8 :   if (!Opts.DebugPrefixMap.empty())
     398         [ #  # ]:          0 :     for (const auto &KV : Opts.DebugPrefixMap)
     399                 :          0 :       Ctx.addDebugPrefixMapEntry(KV.first, KV.second);
     400         [ +  - ]:          8 :   if (!Opts.MainFileName.empty())
     401                 :          8 :     Ctx.setMainFileName(StringRef(Opts.MainFileName));
     402                 :          8 :   Ctx.setDwarfVersion(Opts.DwarfVersion);
     403                 :            : 
     404                 :            :   // Build up the feature string from the target feature list.
     405                 :         16 :   std::string FS;
     406         [ +  - ]:          8 :   if (!Opts.Features.empty()) {
     407                 :          8 :     FS = Opts.Features[0];
     408         [ +  + ]:        568 :     for (unsigned i = 1, e = Opts.Features.size(); i != e; ++i)
     409                 :        560 :       FS += "," + Opts.Features[i];
     410                 :            :   }
     411                 :            : 
     412                 :          8 :   std::unique_ptr<MCStreamer> Str;
     413                 :            : 
     414                 :         16 :   std::unique_ptr<MCInstrInfo> MCII(TheTarget->createMCInstrInfo());
     415                 :            :   std::unique_ptr<MCSubtargetInfo> STI(
     416                 :         16 :       TheTarget->createMCSubtargetInfo(Opts.Triple, Opts.CPU, FS));
     417                 :            : 
     418                 :          8 :   raw_pwrite_stream *Out = FDOS.get();
     419                 :          8 :   std::unique_ptr<buffer_ostream> BOS;
     420                 :            : 
     421                 :            :   // FIXME: There is a bit of code duplication with addPassesToEmitFile.
     422         [ -  + ]:          8 :   if (Opts.OutputType == AssemblerInvocation::FT_Asm) {
     423                 :          0 :     MCInstPrinter *IP = TheTarget->createMCInstPrinter(
     424                 :          0 :         llvm::Triple(Opts.Triple), Opts.OutputAsmVariant, *MAI, *MCII, *MRI);
     425                 :            : 
     426                 :          0 :     std::unique_ptr<MCCodeEmitter> CE;
     427         [ #  # ]:          0 :     if (Opts.ShowEncoding)
     428                 :          0 :       CE.reset(TheTarget->createMCCodeEmitter(*MCII, *MRI, Ctx));
     429                 :          0 :     MCTargetOptions MCOptions;
     430                 :            :     std::unique_ptr<MCAsmBackend> MAB(
     431                 :          0 :         TheTarget->createMCAsmBackend(*STI, *MRI, MCOptions));
     432                 :            : 
     433                 :          0 :     auto FOut = llvm::make_unique<formatted_raw_ostream>(*Out);
     434                 :          0 :     Str.reset(TheTarget->createAsmStreamer(
     435                 :          0 :         Ctx, std::move(FOut), /*asmverbose*/ true,
     436                 :          0 :         /*useDwarfDirectory*/ true, IP, std::move(CE), std::move(MAB),
     437                 :          0 :         Opts.ShowInst));
     438         [ -  + ]:          8 :   } else if (Opts.OutputType == AssemblerInvocation::FT_Null) {
     439                 :          0 :     Str.reset(createNullStreamer(Ctx));
     440                 :            :   } else {
     441         [ -  + ]:          8 :     assert(Opts.OutputType == AssemblerInvocation::FT_Obj &&
     442                 :            :            "Invalid file type!");
     443         [ -  + ]:          8 :     if (!FDOS->supportsSeeking()) {
     444                 :          0 :       BOS = make_unique<buffer_ostream>(*FDOS);
     445                 :          0 :       Out = BOS.get();
     446                 :            :     }
     447                 :            : 
     448                 :            :     std::unique_ptr<MCCodeEmitter> CE(
     449                 :         16 :         TheTarget->createMCCodeEmitter(*MCII, *MRI, Ctx));
     450                 :         16 :     MCTargetOptions MCOptions;
     451                 :            :     std::unique_ptr<MCAsmBackend> MAB(
     452                 :         16 :         TheTarget->createMCAsmBackend(*STI, *MRI, MCOptions));
     453                 :            :     std::unique_ptr<MCObjectWriter> OW =
     454                 :          0 :         DwoOS ? MAB->createDwoObjectWriter(*Out, *DwoOS)
     455         [ -  + ]:         16 :               : MAB->createObjectWriter(*Out);
     456                 :            : 
     457                 :         16 :     Triple T(Opts.Triple);
     458                 :          8 :     Str.reset(TheTarget->createMCObjectStreamer(
     459                 :          8 :         T, Ctx, std::move(MAB), std::move(OW), std::move(CE), *STI,
     460                 :            :         Opts.RelaxAll, Opts.IncrementalLinkerCompatible,
     461                 :         16 :         /*DWARFMustBeAtTheEnd*/ true));
     462                 :          8 :     Str.get()->InitSections(Opts.NoExecStack);
     463                 :            :   }
     464                 :            : 
     465                 :            :   // When -fembed-bitcode is passed to clang_as, a 1-byte marker
     466                 :            :   // is emitted in __LLVM,__asm section if the object file is MachO format.
     467 [ -  + ][ #  # ]:          8 :   if (Opts.EmbedBitcode && Ctx.getObjectFileInfo()->getObjectFileType() ==
                 [ -  + ]
     468                 :          8 :                                MCObjectFileInfo::IsMachO) {
     469                 :          0 :     MCSection *AsmLabel = Ctx.getMachOSection(
     470                 :          0 :         "__LLVM", "__asm", MachO::S_REGULAR, 4, SectionKind::getReadOnly());
     471                 :          0 :     Str.get()->SwitchSection(AsmLabel);
     472                 :          0 :     Str.get()->EmitZeros(1);
     473                 :            :   }
     474                 :            : 
     475                 :            :   // Assembly to object compilation should leverage assembly info.
     476                 :          8 :   Str->setUseAssemblerInfoForParsing(true);
     477                 :            : 
     478                 :          8 :   bool Failed = false;
     479                 :            : 
     480                 :            :   std::unique_ptr<MCAsmParser> Parser(
     481                 :         16 :       createMCAsmParser(SrcMgr, Ctx, *Str.get(), *MAI));
     482                 :            : 
     483                 :            :   // FIXME: init MCTargetOptions from sanitizer flags here.
     484                 :         16 :   MCTargetOptions Options;
     485                 :            :   std::unique_ptr<MCTargetAsmParser> TAP(
     486                 :         16 :       TheTarget->createMCAsmParser(*STI, *Parser, *MCII, Options));
     487         [ -  + ]:          8 :   if (!TAP)
     488                 :          0 :     Failed = Diags.Report(diag::err_target_unknown_triple) << Opts.Triple;
     489                 :            : 
     490                 :            :   // Set values for symbols, if any.
     491         [ -  + ]:          8 :   for (auto &S : Opts.SymbolDefs) {
     492                 :          0 :     auto Pair = StringRef(S).split('=');
     493                 :          0 :     auto Sym = Pair.first;
     494                 :          0 :     auto Val = Pair.second;
     495                 :            :     int64_t Value;
     496                 :            :     // We have already error checked this in the driver.
     497                 :          0 :     Val.getAsInteger(0, Value);
     498                 :          0 :     Ctx.setSymbolValue(Parser->getStreamer(), Sym, Value);
     499                 :            :   }
     500                 :            : 
     501         [ +  - ]:          8 :   if (!Failed) {
     502                 :          8 :     Parser->setTargetParser(*TAP.get());
     503                 :          8 :     Failed = Parser->Run(Opts.NoInitialTextSection);
     504                 :            :   }
     505                 :            : 
     506                 :            :   // Close Streamer first.
     507                 :            :   // It might have a reference to the output stream.
     508                 :          8 :   Str.reset();
     509                 :            :   // Close the output stream early.
     510                 :          8 :   BOS.reset();
     511                 :          8 :   FDOS.reset();
     512                 :            : 
     513                 :            :   // Delete output file if there were errors.
     514         [ -  + ]:          8 :   if (Failed) {
     515         [ #  # ]:          0 :     if (Opts.OutputPath != "-")
     516                 :          0 :       sys::fs::remove(Opts.OutputPath);
     517 [ #  # ][ #  # ]:          0 :     if (!Opts.SplitDwarfFile.empty() && Opts.SplitDwarfFile != "-")
                 [ #  # ]
     518                 :          0 :       sys::fs::remove(Opts.SplitDwarfFile);
     519                 :            :   }
     520                 :            : 
     521                 :          8 :   return Failed;
     522                 :            : }
     523                 :            : 
     524                 :          0 : static void LLVMErrorHandler(void *UserData, const std::string &Message,
     525                 :            :                              bool GenCrashDiag) {
     526                 :          0 :   DiagnosticsEngine &Diags = *static_cast<DiagnosticsEngine*>(UserData);
     527                 :            : 
     528                 :          0 :   Diags.Report(diag::err_fe_error_backend) << Message;
     529                 :            : 
     530                 :            :   // We cannot recover from llvm errors.
     531                 :          0 :   exit(1);
     532                 :            : }
     533                 :            : 
     534                 :          8 : int cc1as_main(ArrayRef<const char *> Argv, const char *Argv0, void *MainAddr) {
     535                 :            :   // Initialize targets and assembly printers/parsers.
     536                 :          8 :   InitializeAllTargetInfos();
     537                 :          8 :   InitializeAllTargetMCs();
     538                 :          8 :   InitializeAllAsmParsers();
     539                 :            : 
     540                 :            :   // Construct our diagnostic client.
     541                 :         16 :   IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
     542                 :            :   TextDiagnosticPrinter *DiagClient
     543                 :          8 :     = new TextDiagnosticPrinter(errs(), &*DiagOpts);
     544                 :          8 :   DiagClient->setPrefix("clang -cc1as");
     545                 :         16 :   IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
     546                 :         16 :   DiagnosticsEngine Diags(DiagID, &*DiagOpts, DiagClient);
     547                 :            : 
     548                 :            :   // Set an error handler, so that any LLVM backend diagnostics go through our
     549                 :            :   // error handler.
     550                 :            :   ScopedFatalErrorHandler FatalErrorHandler
     551                 :         16 :     (LLVMErrorHandler, static_cast<void*>(&Diags));
     552                 :            : 
     553                 :            :   // Parse the arguments.
     554                 :         16 :   AssemblerInvocation Asm;
     555         [ -  + ]:          8 :   if (!AssemblerInvocation::CreateFromArgs(Asm, Argv, Diags))
     556                 :          0 :     return 1;
     557                 :            : 
     558         [ -  + ]:          8 :   if (Asm.ShowHelp) {
     559                 :          0 :     std::unique_ptr<OptTable> Opts(driver::createDriverOptTable());
     560                 :          0 :     Opts->PrintHelp(llvm::outs(), "clang -cc1as [options] file...",
     561                 :            :                     "Clang Integrated Assembler",
     562                 :            :                     /*Include=*/driver::options::CC1AsOption, /*Exclude=*/0,
     563                 :            :                     /*ShowAllAliases=*/false);
     564                 :          0 :     return 0;
     565                 :            :   }
     566                 :            : 
     567                 :            :   // Honor -version.
     568                 :            :   //
     569                 :            :   // FIXME: Use a better -version message?
     570         [ -  + ]:          8 :   if (Asm.ShowVersion) {
     571                 :          0 :     llvm::cl::PrintVersionMessage();
     572                 :          0 :     return 0;
     573                 :            :   }
     574                 :            : 
     575                 :            :   // Honor -mllvm.
     576                 :            :   //
     577                 :            :   // FIXME: Remove this, one day.
     578         [ -  + ]:          8 :   if (!Asm.LLVMArgs.empty()) {
     579                 :          0 :     unsigned NumArgs = Asm.LLVMArgs.size();
     580                 :          0 :     auto Args = llvm::make_unique<const char*[]>(NumArgs + 2);
     581                 :          0 :     Args[0] = "clang (LLVM option parsing)";
     582         [ #  # ]:          0 :     for (unsigned i = 0; i != NumArgs; ++i)
     583                 :          0 :       Args[i + 1] = Asm.LLVMArgs[i].c_str();
     584                 :          0 :     Args[NumArgs + 1] = nullptr;
     585                 :          0 :     llvm::cl::ParseCommandLineOptions(NumArgs + 1, Args.get());
     586                 :            :   }
     587                 :            : 
     588                 :            :   // Execute the invocation, unless there were parsing errors.
     589 [ +  - ][ -  + ]:          8 :   bool Failed = Diags.hasErrorOccurred() || ExecuteAssembler(Asm, Diags);
     590                 :            : 
     591                 :            :   // If any timers were active but haven't been destroyed yet, print their
     592                 :            :   // results now.
     593                 :          8 :   TimerGroup::printAll(errs());
     594                 :            : 
     595                 :          8 :   return !!Failed;
     596                 :            : }
     597                 :            : 

Generated by: LCOV version 1.14