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