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