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