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