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