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