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

source code of clang/tools/driver/cc1as_main.cpp