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