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