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