tan  0.0.1
cc1as_main.cpp
1 //===-- cc1as_main.cpp - Clang Assembler ---------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This is the entry point to the clang -cc1as functionality, which implements
10 // the direct interface to the LLVM MC based assembler.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "clang/Basic/Diagnostic.h"
15 #include "clang/Basic/DiagnosticOptions.h"
16 #include "clang/Driver/DriverDiagnostic.h"
17 #include "clang/Driver/Options.h"
18 #include "clang/Frontend/FrontendDiagnostic.h"
19 #include "clang/Frontend/TextDiagnosticPrinter.h"
20 #include "clang/Frontend/Utils.h"
21 #include "llvm/ADT/STLExtras.h"
22 #include "llvm/ADT/StringSwitch.h"
23 #include "llvm/ADT/Triple.h"
24 #include "llvm/IR/DataLayout.h"
25 #include "llvm/MC/MCAsmBackend.h"
26 #include "llvm/MC/MCAsmInfo.h"
27 #include "llvm/MC/MCCodeEmitter.h"
28 #include "llvm/MC/MCContext.h"
29 #include "llvm/MC/MCInstrInfo.h"
30 #include "llvm/MC/MCObjectFileInfo.h"
31 #include "llvm/MC/MCObjectWriter.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/MCSectionMachO.h"
36 #include "llvm/MC/MCStreamer.h"
37 #include "llvm/MC/MCSubtargetInfo.h"
38 #include "llvm/MC/MCTargetOptions.h"
39 #include "llvm/MC/TargetRegistry.h"
40 #include "llvm/Option/Arg.h"
41 #include "llvm/Option/ArgList.h"
42 #include "llvm/Option/OptTable.h"
43 #include "llvm/Support/CommandLine.h"
44 #include "llvm/Support/ErrorHandling.h"
45 #include "llvm/Support/FileSystem.h"
46 #include "llvm/Support/FormattedStream.h"
47 #include "llvm/Support/Host.h"
48 #include "llvm/Support/MemoryBuffer.h"
49 #include "llvm/Support/Path.h"
50 #include "llvm/Support/Process.h"
51 #include "llvm/Support/Signals.h"
52 #include "llvm/Support/SourceMgr.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 <optional>
58 #include <system_error>
59 using namespace clang;
60 using namespace clang::driver;
61 using namespace clang::driver::options;
62 using namespace llvm;
63 using namespace llvm::opt;
64 
65 namespace {
66 
67 /// Helper class for representing a single invocation of the assembler.
68 struct AssemblerInvocation {
69  /// @name Target Options
70  /// @{
71 
72  /// The name of the target triple to assemble for.
73  std::string Triple;
74 
75  /// If given, the name of the target CPU to determine which instructions
76  /// are legal.
77  std::string CPU;
78 
79  /// The list of target specific features to enable or disable -- this should
80  /// be a list of strings starting with '+' or '-'.
81  std::vector<std::string> Features;
82 
83  /// The list of symbol definitions.
84  std::vector<std::string> SymbolDefs;
85 
86  /// @}
87  /// @name Language Options
88  /// @{
89 
90  std::vector<std::string> IncludePaths;
91  unsigned NoInitialTextSection : 1;
92  unsigned SaveTemporaryLabels : 1;
93  unsigned GenDwarfForAssembly : 1;
94  unsigned RelaxELFRelocations : 1;
95  unsigned Dwarf64 : 1;
96  unsigned DwarfVersion;
97  std::string DwarfDebugFlags;
98  std::string DwarfDebugProducer;
99  std::string DebugCompilationDir;
100  std::map<const std::string, const std::string> DebugPrefixMap;
101  llvm::DebugCompressionType CompressDebugSections = llvm::DebugCompressionType::None;
102  std::string MainFileName;
103  std::string SplitDwarfOutput;
104 
105  /// @}
106  /// @name Frontend Options
107  /// @{
108 
109  std::string InputFile;
110  std::vector<std::string> LLVMArgs;
111  std::string OutputPath;
112  enum FileType {
113  FT_Asm, ///< Assembly (.s) output, transliterate mode.
114  FT_Null, ///< No output, for timing purposes.
115  FT_Obj ///< Object file output.
116  };
117  FileType OutputType;
118  unsigned ShowHelp : 1;
119  unsigned ShowVersion : 1;
120 
121  /// @}
122  /// @name Transliterate Options
123  /// @{
124 
125  unsigned OutputAsmVariant;
126  unsigned ShowEncoding : 1;
127  unsigned ShowInst : 1;
128 
129  /// @}
130  /// @name Assembler Options
131  /// @{
132 
133  unsigned RelaxAll : 1;
134  unsigned NoExecStack : 1;
135  unsigned FatalWarnings : 1;
136  unsigned NoWarn : 1;
137  unsigned NoTypeCheck : 1;
138  unsigned IncrementalLinkerCompatible : 1;
139  unsigned EmbedBitcode : 1;
140 
141  /// Whether to emit DWARF unwind info.
142  EmitDwarfUnwindType EmitDwarfUnwind;
143 
144  /// The name of the relocation model to use.
145  std::string RelocationModel;
146 
147  /// The ABI targeted by the backend. Specified using -target-abi. Empty
148  /// otherwise.
149  std::string TargetABI;
150 
151  /// Darwin target variant triple, the variant of the deployment target
152  /// for which the code is being compiled.
153  std::optional<llvm::Triple> DarwinTargetVariantTriple;
154 
155  /// The version of the darwin target variant SDK which was used during the
156  /// compilation
157  llvm::VersionTuple DarwinTargetVariantSDKVersion;
158 
159  /// The name of a file to use with \c .secure_log_unique directives.
160  std::string AsSecureLogFile;
161  /// @}
162 
163 public:
164  AssemblerInvocation() {
165  Triple = "";
166  NoInitialTextSection = 0;
167  InputFile = "-";
168  OutputPath = "-";
169  OutputType = FT_Asm;
170  OutputAsmVariant = 0;
171  ShowInst = 0;
172  ShowEncoding = 0;
173  RelaxAll = 0;
174  NoExecStack = 0;
175  FatalWarnings = 0;
176  NoWarn = 0;
177  NoTypeCheck = 0;
178  IncrementalLinkerCompatible = 0;
179  Dwarf64 = 0;
180  DwarfVersion = 0;
181  EmbedBitcode = 0;
182  EmitDwarfUnwind = EmitDwarfUnwindType::Default;
183  }
184 
185  static bool CreateFromArgs(AssemblerInvocation &Res, ArrayRef<const char *> Argv, DiagnosticsEngine &Diags);
186 };
187 
188 } // namespace
189 
190 bool AssemblerInvocation::CreateFromArgs(AssemblerInvocation &Opts,
191  ArrayRef<const char *> Argv,
192  DiagnosticsEngine &Diags) {
193  bool Success = true;
194 
195  // Parse the arguments.
196  const OptTable &OptTbl = getDriverOptTable();
197 
198  const unsigned IncludedFlagsBitmask = options::CC1AsOption;
199  unsigned MissingArgIndex, MissingArgCount;
200  InputArgList Args = OptTbl.ParseArgs(Argv, MissingArgIndex, MissingArgCount, IncludedFlagsBitmask);
201 
202  // Check for missing argument error.
203  if (MissingArgCount) {
204  Diags.Report(diag::err_drv_missing_argument) << Args.getArgString(MissingArgIndex) << MissingArgCount;
205  Success = false;
206  }
207 
208  // Issue errors on unknown arguments.
209  for (const Arg *A : Args.filtered(OPT_UNKNOWN)) {
210  auto ArgString = A->getAsString(Args);
211  std::string Nearest;
212  if (OptTbl.findNearest(ArgString, Nearest, IncludedFlagsBitmask) > 1)
213  Diags.Report(diag::err_drv_unknown_argument) << ArgString;
214  else
215  Diags.Report(diag::err_drv_unknown_argument_with_suggestion) << ArgString << Nearest;
216  Success = false;
217  }
218 
219  // Construct the invocation.
220 
221  // Target Options
222  Opts.Triple = llvm::Triple::normalize(Args.getLastArgValue(OPT_triple));
223  if (Arg *A = Args.getLastArg(options::OPT_darwin_target_variant_triple))
224  Opts.DarwinTargetVariantTriple = llvm::Triple(A->getValue());
225  if (Arg *A = Args.getLastArg(OPT_darwin_target_variant_sdk_version_EQ)) {
226  VersionTuple Version;
227  if (Version.tryParse(A->getValue()))
228  Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << A->getValue();
229  else
230  Opts.DarwinTargetVariantSDKVersion = Version;
231  }
232 
233  Opts.CPU = std::string(Args.getLastArgValue(OPT_target_cpu));
234  Opts.Features = Args.getAllArgValues(OPT_target_feature);
235 
236  // Use the default target triple if unspecified.
237  if (Opts.Triple.empty())
238  Opts.Triple = llvm::sys::getDefaultTargetTriple();
239 
240  // Language Options
241  Opts.IncludePaths = Args.getAllArgValues(OPT_I);
242  Opts.NoInitialTextSection = Args.hasArg(OPT_n);
243  Opts.SaveTemporaryLabels = Args.hasArg(OPT_msave_temp_labels);
244  // Any DebugInfoKind implies GenDwarfForAssembly.
245  Opts.GenDwarfForAssembly = Args.hasArg(OPT_debug_info_kind_EQ);
246 
247  if (const Arg *A = Args.getLastArg(OPT_compress_debug_sections_EQ)) {
248  Opts.CompressDebugSections = llvm::StringSwitch<llvm::DebugCompressionType>(A->getValue())
249  .Case("none", llvm::DebugCompressionType::None)
250  .Case("zlib", llvm::DebugCompressionType::Zlib)
251  .Case("zstd", llvm::DebugCompressionType::Zstd)
252  .Default(llvm::DebugCompressionType::None);
253  }
254 
255  Opts.RelaxELFRelocations = !Args.hasArg(OPT_mrelax_relocations_no);
256  if (auto *DwarfFormatArg = Args.getLastArg(OPT_gdwarf64, OPT_gdwarf32))
257  Opts.Dwarf64 = DwarfFormatArg->getOption().matches(OPT_gdwarf64);
258  Opts.DwarfVersion = getLastArgIntValue(Args, OPT_dwarf_version_EQ, 2, Diags);
259  Opts.DwarfDebugFlags = std::string(Args.getLastArgValue(OPT_dwarf_debug_flags));
260  Opts.DwarfDebugProducer = std::string(Args.getLastArgValue(OPT_dwarf_debug_producer));
261  if (const Arg *A = Args.getLastArg(options::OPT_ffile_compilation_dir_EQ, options::OPT_fdebug_compilation_dir_EQ))
262  Opts.DebugCompilationDir = A->getValue();
263  Opts.MainFileName = std::string(Args.getLastArgValue(OPT_main_file_name));
264 
265  for (const auto &Arg : Args.getAllArgValues(OPT_fdebug_prefix_map_EQ)) {
266  auto Split = StringRef(Arg).split('=');
267  Opts.DebugPrefixMap.insert({std::string(Split.first), std::string(Split.second)});
268  }
269 
270  // Frontend Options
271  if (Args.hasArg(OPT_INPUT)) {
272  bool First = true;
273  for (const Arg *A : Args.filtered(OPT_INPUT)) {
274  if (First) {
275  Opts.InputFile = A->getValue();
276  First = false;
277  } else {
278  Diags.Report(diag::err_drv_unknown_argument) << A->getAsString(Args);
279  Success = false;
280  }
281  }
282  }
283  Opts.LLVMArgs = Args.getAllArgValues(OPT_mllvm);
284  Opts.OutputPath = std::string(Args.getLastArgValue(OPT_o));
285  Opts.SplitDwarfOutput = std::string(Args.getLastArgValue(OPT_split_dwarf_output));
286  if (Arg *A = Args.getLastArg(OPT_filetype)) {
287  StringRef Name = A->getValue();
288  unsigned OutputType =
289  StringSwitch<unsigned>(Name).Case("asm", FT_Asm).Case("null", FT_Null).Case("obj", FT_Obj).Default(~0U);
290  if (OutputType == ~0U) {
291  Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Name;
292  Success = false;
293  } else
294  Opts.OutputType = FileType(OutputType);
295  }
296  Opts.ShowHelp = Args.hasArg(OPT_help);
297  Opts.ShowVersion = Args.hasArg(OPT_version);
298 
299  // Transliterate Options
300  Opts.OutputAsmVariant = getLastArgIntValue(Args, OPT_output_asm_variant, 0, Diags);
301  Opts.ShowEncoding = Args.hasArg(OPT_show_encoding);
302  Opts.ShowInst = Args.hasArg(OPT_show_inst);
303 
304  // Assemble Options
305  Opts.RelaxAll = Args.hasArg(OPT_mrelax_all);
306  Opts.NoExecStack = Args.hasArg(OPT_mno_exec_stack);
307  Opts.FatalWarnings = Args.hasArg(OPT_massembler_fatal_warnings);
308  Opts.NoWarn = Args.hasArg(OPT_massembler_no_warn);
309  Opts.NoTypeCheck = Args.hasArg(OPT_mno_type_check);
310  Opts.RelocationModel = std::string(Args.getLastArgValue(OPT_mrelocation_model, "pic"));
311  Opts.TargetABI = std::string(Args.getLastArgValue(OPT_target_abi));
312  Opts.IncrementalLinkerCompatible = Args.hasArg(OPT_mincremental_linker_compatible);
313  Opts.SymbolDefs = Args.getAllArgValues(OPT_defsym);
314 
315  // EmbedBitcode Option. If -fembed-bitcode is enabled, set the flag.
316  // EmbedBitcode behaves the same for all embed options for assembly files.
317  if (auto *A = Args.getLastArg(OPT_fembed_bitcode_EQ)) {
318  Opts.EmbedBitcode =
319  llvm::StringSwitch<unsigned>(A->getValue()).Case("all", 1).Case("bitcode", 1).Case("marker", 1).Default(0);
320  }
321 
322  if (auto *A = Args.getLastArg(OPT_femit_dwarf_unwind_EQ)) {
323  Opts.EmitDwarfUnwind = llvm::StringSwitch<EmitDwarfUnwindType>(A->getValue())
324  .Case("always", EmitDwarfUnwindType::Always)
325  .Case("no-compact-unwind", EmitDwarfUnwindType::NoCompactUnwind)
326  .Case("default", EmitDwarfUnwindType::Default);
327  }
328 
329  Opts.AsSecureLogFile = Args.getLastArgValue(OPT_as_secure_log_file);
330 
331  return Success;
332 }
333 
334 static std::unique_ptr<raw_fd_ostream> getOutputStream(StringRef Path, DiagnosticsEngine &Diags, bool Binary) {
335  // Make sure that the Out file gets unlinked from the disk if we get a
336  // SIGINT.
337  if (Path != "-")
338  sys::RemoveFileOnSignal(Path);
339 
340  std::error_code EC;
341  auto Out = std::make_unique<raw_fd_ostream>(Path, EC, (Binary ? sys::fs::OF_None : sys::fs::OF_TextWithCRLF));
342  if (EC) {
343  Diags.Report(diag::err_fe_unable_to_open_output) << Path << EC.message();
344  return nullptr;
345  }
346 
347  return Out;
348 }
349 
350 static bool ExecuteAssemblerImpl(AssemblerInvocation &Opts, DiagnosticsEngine &Diags) {
351  // Get the target specific parser.
352  std::string Error;
353  const Target *TheTarget = TargetRegistry::lookupTarget(Opts.Triple, Error);
354  if (!TheTarget)
355  return Diags.Report(diag::err_target_unknown_triple) << Opts.Triple;
356 
357  ErrorOr<std::unique_ptr<MemoryBuffer>> Buffer = MemoryBuffer::getFileOrSTDIN(Opts.InputFile, /*IsText=*/true);
358 
359  if (std::error_code EC = Buffer.getError()) {
360  Error = EC.message();
361  return Diags.Report(diag::err_fe_error_reading) << Opts.InputFile;
362  }
363 
364  SourceMgr SrcMgr;
365 
366  // Tell SrcMgr about this buffer, which is what the parser will pick up.
367  unsigned BufferIndex = SrcMgr.AddNewSourceBuffer(std::move(*Buffer), SMLoc());
368 
369  // Record the location of the include directories so that the lexer can find
370  // it later.
371  SrcMgr.setIncludeDirs(Opts.IncludePaths);
372 
373  std::unique_ptr<MCRegisterInfo> MRI(TheTarget->createMCRegInfo(Opts.Triple));
374  assert(MRI && "Unable to create target register info!");
375 
376  MCTargetOptions MCOptions;
377  MCOptions.EmitDwarfUnwind = Opts.EmitDwarfUnwind;
378  MCOptions.AsSecureLogFile = Opts.AsSecureLogFile;
379 
380  std::unique_ptr<MCAsmInfo> MAI(TheTarget->createMCAsmInfo(*MRI, Opts.Triple, MCOptions));
381  assert(MAI && "Unable to create target asm info!");
382 
383  // Ensure MCAsmInfo initialization occurs before any use, otherwise sections
384  // may be created with a combination of default and explicit settings.
385  MAI->setCompressDebugSections(Opts.CompressDebugSections);
386 
387  MAI->setRelaxELFRelocations(Opts.RelaxELFRelocations);
388 
389  bool IsBinary = Opts.OutputType == AssemblerInvocation::FT_Obj;
390  if (Opts.OutputPath.empty())
391  Opts.OutputPath = "-";
392  std::unique_ptr<raw_fd_ostream> FDOS = getOutputStream(Opts.OutputPath, Diags, IsBinary);
393  if (!FDOS)
394  return true;
395  std::unique_ptr<raw_fd_ostream> DwoOS;
396  if (!Opts.SplitDwarfOutput.empty())
397  DwoOS = getOutputStream(Opts.SplitDwarfOutput, Diags, IsBinary);
398 
399  // Build up the feature string from the target feature list.
400  std::string FS = llvm::join(Opts.Features, ",");
401 
402  std::unique_ptr<MCSubtargetInfo> STI(TheTarget->createMCSubtargetInfo(Opts.Triple, Opts.CPU, FS));
403  assert(STI && "Unable to create subtarget info!");
404 
405  MCContext Ctx(Triple(Opts.Triple), MAI.get(), MRI.get(), STI.get(), &SrcMgr, &MCOptions);
406 
407  bool PIC = false;
408  if (Opts.RelocationModel == "static") {
409  PIC = false;
410  } else if (Opts.RelocationModel == "pic") {
411  PIC = true;
412  } else {
413  assert(Opts.RelocationModel == "dynamic-no-pic" && "Invalid PIC model!");
414  PIC = false;
415  }
416 
417  // FIXME: This is not pretty. MCContext has a ptr to MCObjectFileInfo and
418  // MCObjectFileInfo needs a MCContext reference in order to initialize itself.
419  std::unique_ptr<MCObjectFileInfo> MOFI(TheTarget->createMCObjectFileInfo(Ctx, PIC));
420  if (Opts.DarwinTargetVariantTriple)
421  MOFI->setDarwinTargetVariantTriple(*Opts.DarwinTargetVariantTriple);
422  if (!Opts.DarwinTargetVariantSDKVersion.empty())
423  MOFI->setDarwinTargetVariantSDKVersion(Opts.DarwinTargetVariantSDKVersion);
424  Ctx.setObjectFileInfo(MOFI.get());
425 
426  if (Opts.SaveTemporaryLabels)
427  Ctx.setAllowTemporaryLabels(false);
428  if (Opts.GenDwarfForAssembly)
429  Ctx.setGenDwarfForAssembly(true);
430  if (!Opts.DwarfDebugFlags.empty())
431  Ctx.setDwarfDebugFlags(StringRef(Opts.DwarfDebugFlags));
432  if (!Opts.DwarfDebugProducer.empty())
433  Ctx.setDwarfDebugProducer(StringRef(Opts.DwarfDebugProducer));
434  if (!Opts.DebugCompilationDir.empty())
435  Ctx.setCompilationDir(Opts.DebugCompilationDir);
436  else {
437  // If no compilation dir is set, try to use the current directory.
438  SmallString<128> CWD;
439  if (!sys::fs::current_path(CWD))
440  Ctx.setCompilationDir(CWD);
441  }
442  if (!Opts.DebugPrefixMap.empty())
443  for (const auto &KV : Opts.DebugPrefixMap)
444  Ctx.addDebugPrefixMapEntry(KV.first, KV.second);
445  if (!Opts.MainFileName.empty())
446  Ctx.setMainFileName(StringRef(Opts.MainFileName));
447  Ctx.setDwarfFormat(Opts.Dwarf64 ? dwarf::DWARF64 : dwarf::DWARF32);
448  Ctx.setDwarfVersion(Opts.DwarfVersion);
449  if (Opts.GenDwarfForAssembly)
450  Ctx.setGenDwarfRootFile(Opts.InputFile, SrcMgr.getMemoryBuffer(BufferIndex)->getBuffer());
451 
452  std::unique_ptr<MCStreamer> Str;
453 
454  std::unique_ptr<MCInstrInfo> MCII(TheTarget->createMCInstrInfo());
455  assert(MCII && "Unable to create instruction info!");
456 
457  raw_pwrite_stream *Out = FDOS.get();
458  std::unique_ptr<buffer_ostream> BOS;
459 
460  MCOptions.MCNoWarn = Opts.NoWarn;
461  MCOptions.MCFatalWarnings = Opts.FatalWarnings;
462  MCOptions.MCNoTypeCheck = Opts.NoTypeCheck;
463  MCOptions.ABIName = Opts.TargetABI;
464 
465  // FIXME: There is a bit of code duplication with addPassesToEmitFile.
466  if (Opts.OutputType == AssemblerInvocation::FT_Asm) {
467  MCInstPrinter *IP =
468  TheTarget->createMCInstPrinter(llvm::Triple(Opts.Triple), Opts.OutputAsmVariant, *MAI, *MCII, *MRI);
469 
470  std::unique_ptr<MCCodeEmitter> CE;
471  if (Opts.ShowEncoding)
472  CE.reset(TheTarget->createMCCodeEmitter(*MCII, Ctx));
473  std::unique_ptr<MCAsmBackend> MAB(TheTarget->createMCAsmBackend(*STI, *MRI, MCOptions));
474 
475  auto FOut = std::make_unique<formatted_raw_ostream>(*Out);
476  Str.reset(TheTarget->createAsmStreamer(Ctx,
477  std::move(FOut),
478  /*asmverbose*/ true,
479  /*useDwarfDirectory*/ true,
480  IP,
481  std::move(CE),
482  std::move(MAB),
483  Opts.ShowInst));
484  } else if (Opts.OutputType == AssemblerInvocation::FT_Null) {
485  Str.reset(createNullStreamer(Ctx));
486  } else {
487  assert(Opts.OutputType == AssemblerInvocation::FT_Obj && "Invalid file type!");
488  if (!FDOS->supportsSeeking()) {
489  BOS = std::make_unique<buffer_ostream>(*FDOS);
490  Out = BOS.get();
491  }
492 
493  std::unique_ptr<MCCodeEmitter> CE(TheTarget->createMCCodeEmitter(*MCII, Ctx));
494  std::unique_ptr<MCAsmBackend> MAB(TheTarget->createMCAsmBackend(*STI, *MRI, MCOptions));
495  assert(MAB && "Unable to create asm backend!");
496 
497  std::unique_ptr<MCObjectWriter> OW =
498  DwoOS ? MAB->createDwoObjectWriter(*Out, *DwoOS) : MAB->createObjectWriter(*Out);
499 
500  Triple T(Opts.Triple);
501  Str.reset(TheTarget->createMCObjectStreamer(T,
502  Ctx,
503  std::move(MAB),
504  std::move(OW),
505  std::move(CE),
506  *STI,
507  Opts.RelaxAll,
508  Opts.IncrementalLinkerCompatible,
509  /*DWARFMustBeAtTheEnd*/ true));
510  Str.get()->initSections(Opts.NoExecStack, *STI);
511  }
512 
513  // When -fembed-bitcode is passed to clang_as, a 1-byte marker
514  // is emitted in __LLVM,__asm section if the object file is MachO format.
515  if (Opts.EmbedBitcode && Ctx.getObjectFileType() == MCContext::IsMachO) {
516  MCSection *AsmLabel = Ctx.getMachOSection("__LLVM", "__asm", MachO::S_REGULAR, 4, SectionKind::getReadOnly());
517  Str.get()->switchSection(AsmLabel);
518  Str.get()->emitZeros(1);
519  }
520 
521  // Assembly to object compilation should leverage assembly info.
522  Str->setUseAssemblerInfoForParsing(true);
523 
524  bool Failed = false;
525 
526  std::unique_ptr<MCAsmParser> Parser(createMCAsmParser(SrcMgr, Ctx, *Str.get(), *MAI));
527 
528  // FIXME: init MCTargetOptions from sanitizer flags here.
529  std::unique_ptr<MCTargetAsmParser> TAP(TheTarget->createMCAsmParser(*STI, *Parser, *MCII, MCOptions));
530  if (!TAP)
531  Failed = Diags.Report(diag::err_target_unknown_triple) << Opts.Triple;
532 
533  // Set values for symbols, if any.
534  for (auto &S : Opts.SymbolDefs) {
535  auto Pair = StringRef(S).split('=');
536  auto Sym = Pair.first;
537  auto Val = Pair.second;
538  int64_t Value;
539  // We have already error checked this in the driver.
540  Val.getAsInteger(0, Value);
541  Ctx.setSymbolValue(Parser->getStreamer(), Sym, Value);
542  }
543 
544  if (!Failed) {
545  Parser->setTargetParser(*TAP.get());
546  Failed = Parser->Run(Opts.NoInitialTextSection);
547  }
548 
549  return Failed;
550 }
551 
552 static bool ExecuteAssembler(AssemblerInvocation &Opts, DiagnosticsEngine &Diags) {
553  bool Failed = ExecuteAssemblerImpl(Opts, Diags);
554 
555  // Delete output file if there were errors.
556  if (Failed) {
557  if (Opts.OutputPath != "-")
558  sys::fs::remove(Opts.OutputPath);
559  if (!Opts.SplitDwarfOutput.empty() && Opts.SplitDwarfOutput != "-")
560  sys::fs::remove(Opts.SplitDwarfOutput);
561  }
562 
563  return Failed;
564 }
565 
566 static void LLVMErrorHandler(void *UserData, const char *Message, bool GenCrashDiag) {
567  DiagnosticsEngine &Diags = *static_cast<DiagnosticsEngine *>(UserData);
568 
569  Diags.Report(diag::err_fe_error_backend) << Message;
570 
571  // We cannot recover from llvm errors.
572  sys::Process::Exit(1);
573 }
574 
575 int cc1as_main(ArrayRef<const char *> Argv, const char *Argv0, void *MainAddr) {
576  // Initialize targets and assembly printers/parsers.
577  InitializeAllTargetInfos();
578  InitializeAllTargetMCs();
579  InitializeAllAsmParsers();
580 
581  // Construct our diagnostic client.
582  IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
583  TextDiagnosticPrinter *DiagClient = new TextDiagnosticPrinter(errs(), &*DiagOpts);
584  DiagClient->setPrefix("clang -cc1as");
585  IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
586  DiagnosticsEngine Diags(DiagID, &*DiagOpts, DiagClient);
587 
588  // Set an error handler, so that any LLVM backend diagnostics go through our
589  // error handler.
590  ScopedFatalErrorHandler FatalErrorHandler(LLVMErrorHandler, static_cast<void *>(&Diags));
591 
592  // Parse the arguments.
593  AssemblerInvocation Asm;
594  if (!AssemblerInvocation::CreateFromArgs(Asm, Argv, Diags))
595  return 1;
596 
597  if (Asm.ShowHelp) {
598  getDriverOptTable().printHelp(llvm::outs(),
599  "clang -cc1as [options] file...",
600  "Clang Integrated Assembler",
601  /*Include=*/driver::options::CC1AsOption,
602  /*Exclude=*/0,
603  /*ShowAllAliases=*/false);
604  return 0;
605  }
606 
607  // Honor -version.
608  //
609  // FIXME: Use a better -version message?
610  if (Asm.ShowVersion) {
611  llvm::cl::PrintVersionMessage();
612  return 0;
613  }
614 
615  // Honor -mllvm.
616  //
617  // FIXME: Remove this, one day.
618  if (!Asm.LLVMArgs.empty()) {
619  unsigned NumArgs = Asm.LLVMArgs.size();
620  auto Args = std::make_unique<const char *[]>(NumArgs + 2);
621  Args[0] = "clang (LLVM option parsing)";
622  for (unsigned i = 0; i != NumArgs; ++i)
623  Args[i + 1] = Asm.LLVMArgs[i].c_str();
624  Args[NumArgs + 1] = nullptr;
625  llvm::cl::ParseCommandLineOptions(NumArgs + 1, Args.get());
626  }
627 
628  // Execute the invocation, unless there were parsing errors.
629  bool Failed = Diags.hasErrorOccurred() || ExecuteAssembler(Asm, Diags);
630 
631  // If any timers were active but haven't been destroyed yet, print their
632  // results now.
633  TimerGroup::printAll(errs());
634  TimerGroup::clearAll();
635 
636  return !!Failed;
637 }