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 (arg_iterator it = Args.filtered_begin(OPT_INPUT),
216                       ie = Args.filtered_end();
217          it != ie; ++it, First = false) {
218       const Arg *A = it;
219       if (First)
220         Opts.InputFile = A->getValue();
221       else {
222         Diags.Report(diag::err_drv_unknown_argument) << A->getAsString(Args);
223         Success = false;
224       }
225     }
226   }
227   Opts.LLVMArgs = Args.getAllArgValues(OPT_mllvm);
228   Opts.OutputPath = Args.getLastArgValue(OPT_o);
229   if (Arg *A = Args.getLastArg(OPT_filetype)) {
230     StringRef Name = A->getValue();
231     unsigned OutputType = StringSwitch<unsigned>(Name)
232       .Case("asm", FT_Asm)
233       .Case("null", FT_Null)
234       .Case("obj", FT_Obj)
235       .Default(~0U);
236     if (OutputType == ~0U) {
237       Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Name;
238       Success = false;
239     } else
240       Opts.OutputType = FileType(OutputType);
241   }
242   Opts.ShowHelp = Args.hasArg(OPT_help);
243   Opts.ShowVersion = Args.hasArg(OPT_version);
244 
245   // Transliterate Options
246   Opts.OutputAsmVariant =
247       getLastArgIntValue(Args, OPT_output_asm_variant, 0, Diags);
248   Opts.ShowEncoding = Args.hasArg(OPT_show_encoding);
249   Opts.ShowInst = Args.hasArg(OPT_show_inst);
250 
251   // Assemble Options
252   Opts.RelaxAll = Args.hasArg(OPT_mrelax_all);
253   Opts.NoExecStack = Args.hasArg(OPT_mno_exec_stack);
254   Opts.FatalWarnings = Args.hasArg(OPT_massembler_fatal_warnings);
255   Opts.RelocationModel = Args.getLastArgValue(OPT_mrelocation_model, "pic");
256   Opts.IncrementalLinkerCompatible =
257       Args.hasArg(OPT_mincremental_linker_compatible);
258   Opts.SymbolDefs = Args.getAllArgValues(OPT_defsym);
259 
260   return Success;
261 }
262 
263 static std::unique_ptr<raw_fd_ostream>
264 getOutputStream(AssemblerInvocation &Opts, DiagnosticsEngine &Diags,
265                 bool Binary) {
266   if (Opts.OutputPath.empty())
267     Opts.OutputPath = "-";
268 
269   // Make sure that the Out file gets unlinked from the disk if we get a
270   // SIGINT.
271   if (Opts.OutputPath != "-")
272     sys::RemoveFileOnSignal(Opts.OutputPath);
273 
274   std::error_code EC;
275   auto Out = llvm::make_unique<raw_fd_ostream>(
276       Opts.OutputPath, EC, (Binary ? sys::fs::F_None : sys::fs::F_Text));
277   if (EC) {
278     Diags.Report(diag::err_fe_unable_to_open_output) << Opts.OutputPath
279                                                      << EC.message();
280     return nullptr;
281   }
282 
283   return Out;
284 }
285 
286 static bool ExecuteAssembler(AssemblerInvocation &Opts,
287                              DiagnosticsEngine &Diags) {
288   // Get the target specific parser.
289   std::string Error;
290   const Target *TheTarget = TargetRegistry::lookupTarget(Opts.Triple, Error);
291   if (!TheTarget)
292     return Diags.Report(diag::err_target_unknown_triple) << Opts.Triple;
293 
294   ErrorOr<std::unique_ptr<MemoryBuffer>> Buffer =
295       MemoryBuffer::getFileOrSTDIN(Opts.InputFile);
296 
297   if (std::error_code EC = Buffer.getError()) {
298     Error = EC.message();
299     return Diags.Report(diag::err_fe_error_reading) << Opts.InputFile;
300   }
301 
302   SourceMgr SrcMgr;
303 
304   // Tell SrcMgr about this buffer, which is what the parser will pick up.
305   SrcMgr.AddNewSourceBuffer(std::move(*Buffer), SMLoc());
306 
307   // Record the location of the include directories so that the lexer can find
308   // it later.
309   SrcMgr.setIncludeDirs(Opts.IncludePaths);
310 
311   std::unique_ptr<MCRegisterInfo> MRI(TheTarget->createMCRegInfo(Opts.Triple));
312   assert(MRI && "Unable to create target register info!");
313 
314   std::unique_ptr<MCAsmInfo> MAI(TheTarget->createMCAsmInfo(*MRI, Opts.Triple));
315   assert(MAI && "Unable to create target asm info!");
316 
317   // Ensure MCAsmInfo initialization occurs before any use, otherwise sections
318   // may be created with a combination of default and explicit settings.
319   if (Opts.CompressDebugSections)
320     MAI->setCompressDebugSections(DebugCompressionType::DCT_ZlibGnu);
321 
322   MAI->setRelaxELFRelocations(Opts.RelaxELFRelocations);
323 
324   bool IsBinary = Opts.OutputType == AssemblerInvocation::FT_Obj;
325   std::unique_ptr<raw_fd_ostream> FDOS = getOutputStream(Opts, Diags, IsBinary);
326   if (!FDOS)
327     return true;
328 
329   // FIXME: This is not pretty. MCContext has a ptr to MCObjectFileInfo and
330   // MCObjectFileInfo needs a MCContext reference in order to initialize itself.
331   std::unique_ptr<MCObjectFileInfo> MOFI(new MCObjectFileInfo());
332 
333   MCContext Ctx(MAI.get(), MRI.get(), MOFI.get(), &SrcMgr);
334 
335   bool PIC = false;
336   if (Opts.RelocationModel == "static") {
337     PIC = false;
338   } else if (Opts.RelocationModel == "pic") {
339     PIC = true;
340   } else {
341     assert(Opts.RelocationModel == "dynamic-no-pic" &&
342            "Invalid PIC model!");
343     PIC = false;
344   }
345 
346   MOFI->InitMCObjectFileInfo(Triple(Opts.Triple), PIC, CodeModel::Default, Ctx);
347   if (Opts.SaveTemporaryLabels)
348     Ctx.setAllowTemporaryLabels(false);
349   if (Opts.GenDwarfForAssembly)
350     Ctx.setGenDwarfForAssembly(true);
351   if (!Opts.DwarfDebugFlags.empty())
352     Ctx.setDwarfDebugFlags(StringRef(Opts.DwarfDebugFlags));
353   if (!Opts.DwarfDebugProducer.empty())
354     Ctx.setDwarfDebugProducer(StringRef(Opts.DwarfDebugProducer));
355   if (!Opts.DebugCompilationDir.empty())
356     Ctx.setCompilationDir(Opts.DebugCompilationDir);
357   if (!Opts.MainFileName.empty())
358     Ctx.setMainFileName(StringRef(Opts.MainFileName));
359   Ctx.setDwarfVersion(Opts.DwarfVersion);
360 
361   // Build up the feature string from the target feature list.
362   std::string FS;
363   if (!Opts.Features.empty()) {
364     FS = Opts.Features[0];
365     for (unsigned i = 1, e = Opts.Features.size(); i != e; ++i)
366       FS += "," + Opts.Features[i];
367   }
368 
369   std::unique_ptr<MCStreamer> Str;
370 
371   std::unique_ptr<MCInstrInfo> MCII(TheTarget->createMCInstrInfo());
372   std::unique_ptr<MCSubtargetInfo> STI(
373       TheTarget->createMCSubtargetInfo(Opts.Triple, Opts.CPU, FS));
374 
375   raw_pwrite_stream *Out = FDOS.get();
376   std::unique_ptr<buffer_ostream> BOS;
377 
378   // FIXME: There is a bit of code duplication with addPassesToEmitFile.
379   if (Opts.OutputType == AssemblerInvocation::FT_Asm) {
380     MCInstPrinter *IP = TheTarget->createMCInstPrinter(
381         llvm::Triple(Opts.Triple), Opts.OutputAsmVariant, *MAI, *MCII, *MRI);
382     MCCodeEmitter *CE = nullptr;
383     MCAsmBackend *MAB = nullptr;
384     if (Opts.ShowEncoding) {
385       CE = TheTarget->createMCCodeEmitter(*MCII, *MRI, Ctx);
386       MCTargetOptions Options;
387       MAB = TheTarget->createMCAsmBackend(*MRI, Opts.Triple, Opts.CPU, Options);
388     }
389     auto FOut = llvm::make_unique<formatted_raw_ostream>(*Out);
390     Str.reset(TheTarget->createAsmStreamer(
391         Ctx, std::move(FOut), /*asmverbose*/ true,
392         /*useDwarfDirectory*/ true, IP, CE, MAB, Opts.ShowInst));
393   } else if (Opts.OutputType == AssemblerInvocation::FT_Null) {
394     Str.reset(createNullStreamer(Ctx));
395   } else {
396     assert(Opts.OutputType == AssemblerInvocation::FT_Obj &&
397            "Invalid file type!");
398     if (!FDOS->supportsSeeking()) {
399       BOS = make_unique<buffer_ostream>(*FDOS);
400       Out = BOS.get();
401     }
402 
403     MCCodeEmitter *CE = TheTarget->createMCCodeEmitter(*MCII, *MRI, Ctx);
404     MCTargetOptions Options;
405     MCAsmBackend *MAB = TheTarget->createMCAsmBackend(*MRI, Opts.Triple,
406                                                       Opts.CPU, Options);
407     Triple T(Opts.Triple);
408     Str.reset(TheTarget->createMCObjectStreamer(
409         T, Ctx, *MAB, *Out, CE, *STI, Opts.RelaxAll,
410         Opts.IncrementalLinkerCompatible,
411         /*DWARFMustBeAtTheEnd*/ true));
412     Str.get()->InitSections(Opts.NoExecStack);
413   }
414 
415   bool Failed = false;
416 
417   std::unique_ptr<MCAsmParser> Parser(
418       createMCAsmParser(SrcMgr, Ctx, *Str.get(), *MAI));
419 
420   // FIXME: init MCTargetOptions from sanitizer flags here.
421   MCTargetOptions Options;
422   std::unique_ptr<MCTargetAsmParser> TAP(
423       TheTarget->createMCAsmParser(*STI, *Parser, *MCII, Options));
424   if (!TAP)
425     Failed = Diags.Report(diag::err_target_unknown_triple) << Opts.Triple;
426 
427   // Set values for symbols, if any.
428   for (auto &S : Opts.SymbolDefs) {
429     auto Pair = StringRef(S).split('=');
430     auto Sym = Pair.first;
431     auto Val = Pair.second;
432     int64_t Value;
433     // We have already error checked this in the driver.
434     Val.getAsInteger(0, Value);
435     Ctx.setSymbolValue(Parser->getStreamer(), Sym, Value);
436   }
437 
438   if (!Failed) {
439     Parser->setTargetParser(*TAP.get());
440     Failed = Parser->Run(Opts.NoInitialTextSection);
441   }
442 
443   // Close Streamer first.
444   // It might have a reference to the output stream.
445   Str.reset();
446   // Close the output stream early.
447   BOS.reset();
448   FDOS.reset();
449 
450   // Delete output file if there were errors.
451   if (Failed && Opts.OutputPath != "-")
452     sys::fs::remove(Opts.OutputPath);
453 
454   return Failed;
455 }
456 
457 static void LLVMErrorHandler(void *UserData, const std::string &Message,
458                              bool GenCrashDiag) {
459   DiagnosticsEngine &Diags = *static_cast<DiagnosticsEngine*>(UserData);
460 
461   Diags.Report(diag::err_fe_error_backend) << Message;
462 
463   // We cannot recover from llvm errors.
464   exit(1);
465 }
466 
467 int cc1as_main(ArrayRef<const char *> Argv, const char *Argv0, void *MainAddr) {
468   // Initialize targets and assembly printers/parsers.
469   InitializeAllTargetInfos();
470   InitializeAllTargetMCs();
471   InitializeAllAsmParsers();
472 
473   // Construct our diagnostic client.
474   IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
475   TextDiagnosticPrinter *DiagClient
476     = new TextDiagnosticPrinter(errs(), &*DiagOpts);
477   DiagClient->setPrefix("clang -cc1as");
478   IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
479   DiagnosticsEngine Diags(DiagID, &*DiagOpts, DiagClient);
480 
481   // Set an error handler, so that any LLVM backend diagnostics go through our
482   // error handler.
483   ScopedFatalErrorHandler FatalErrorHandler
484     (LLVMErrorHandler, static_cast<void*>(&Diags));
485 
486   // Parse the arguments.
487   AssemblerInvocation Asm;
488   if (!AssemblerInvocation::CreateFromArgs(Asm, Argv, Diags))
489     return 1;
490 
491   if (Asm.ShowHelp) {
492     std::unique_ptr<OptTable> Opts(driver::createDriverOptTable());
493     Opts->PrintHelp(llvm::outs(), "clang -cc1as", "Clang Integrated Assembler",
494                     /*Include=*/driver::options::CC1AsOption, /*Exclude=*/0);
495     return 0;
496   }
497 
498   // Honor -version.
499   //
500   // FIXME: Use a better -version message?
501   if (Asm.ShowVersion) {
502     llvm::cl::PrintVersionMessage();
503     return 0;
504   }
505 
506   // Honor -mllvm.
507   //
508   // FIXME: Remove this, one day.
509   if (!Asm.LLVMArgs.empty()) {
510     unsigned NumArgs = Asm.LLVMArgs.size();
511     const char **Args = new const char*[NumArgs + 2];
512     Args[0] = "clang (LLVM option parsing)";
513     for (unsigned i = 0; i != NumArgs; ++i)
514       Args[i + 1] = Asm.LLVMArgs[i].c_str();
515     Args[NumArgs + 1] = nullptr;
516     llvm::cl::ParseCommandLineOptions(NumArgs + 1, Args);
517   }
518 
519   // Execute the invocation, unless there were parsing errors.
520   bool Failed = Diags.hasErrorOccurred() || ExecuteAssembler(Asm, Diags);
521 
522   // If any timers were active but haven't been destroyed yet, print their
523   // results now.
524   TimerGroup::printAll(errs());
525 
526   return !!Failed;
527 }
528