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