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