1 //===-- cc1as_main.cpp - Clang Assembler ---------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This is the entry point to the clang -cc1as functionality, which implements
11 // the direct interface to the LLVM MC based assembler.
13 //===----------------------------------------------------------------------===//
15 #include "clang/Basic/Diagnostic.h"
16 #include "clang/Basic/DiagnosticOptions.h"
17 #include "clang/Driver/DriverDiagnostic.h"
18 #include "clang/Driver/Options.h"
19 #include "clang/Frontend/FrontendDiagnostic.h"
20 #include "clang/Frontend/TextDiagnosticPrinter.h"
21 #include "clang/Frontend/Utils.h"
22 #include "llvm/ADT/STLExtras.h"
23 #include "llvm/ADT/StringSwitch.h"
24 #include "llvm/ADT/Triple.h"
25 #include "llvm/IR/DataLayout.h"
26 #include "llvm/MC/MCAsmBackend.h"
27 #include "llvm/MC/MCAsmInfo.h"
28 #include "llvm/MC/MCCodeEmitter.h"
29 #include "llvm/MC/MCContext.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/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/Signals.h"
51 #include "llvm/Support/SourceMgr.h"
52 #include "llvm/Support/TargetRegistry.h"
53 #include "llvm/Support/TargetSelect.h"
54 #include "llvm/Support/Timer.h"
55 #include "llvm/Support/raw_ostream.h"
57 #include <system_error>
58 using namespace clang;
59 using namespace clang::driver;
60 using namespace clang::driver::options;
62 using namespace llvm::opt;
66 /// Helper class for representing a single invocation of the assembler.
67 struct AssemblerInvocation {
68 /// @name Target Options
71 /// The name of the target triple to assemble for.
74 /// If given, the name of the target CPU to determine which instructions
78 /// The list of target specific features to enable or disable -- this should
79 /// be a list of strings starting with '+' or '-'.
80 std::vector<std::string> Features;
82 /// The list of symbol definitions.
83 std::vector<std::string> SymbolDefs;
86 /// @name Language Options
89 std::vector<std::string> IncludePaths;
90 unsigned NoInitialTextSection : 1;
91 unsigned SaveTemporaryLabels : 1;
92 unsigned GenDwarfForAssembly : 1;
93 unsigned RelaxELFRelocations : 1;
94 unsigned DwarfVersion;
95 std::string DwarfDebugFlags;
96 std::string DwarfDebugProducer;
97 std::string DebugCompilationDir;
98 std::map<const std::string, const std::string> DebugPrefixMap;
99 llvm::DebugCompressionType CompressDebugSections =
100 llvm::DebugCompressionType::None;
101 std::string MainFileName;
102 std::string SplitDwarfFile;
105 /// @name Frontend Options
108 std::string InputFile;
109 std::vector<std::string> LLVMArgs;
110 std::string OutputPath;
112 FT_Asm, ///< Assembly (.s) output, transliterate mode.
113 FT_Null, ///< No output, for timing purposes.
114 FT_Obj ///< Object file output.
117 unsigned ShowHelp : 1;
118 unsigned ShowVersion : 1;
121 /// @name Transliterate Options
124 unsigned OutputAsmVariant;
125 unsigned ShowEncoding : 1;
126 unsigned ShowInst : 1;
129 /// @name Assembler Options
132 unsigned RelaxAll : 1;
133 unsigned NoExecStack : 1;
134 unsigned FatalWarnings : 1;
135 unsigned IncrementalLinkerCompatible : 1;
136 unsigned EmbedBitcode : 1;
138 /// The name of the relocation model to use.
139 std::string RelocationModel;
144 AssemblerInvocation() {
146 NoInitialTextSection = 0;
150 OutputAsmVariant = 0;
156 IncrementalLinkerCompatible = 0;
161 static bool CreateFromArgs(AssemblerInvocation &Res,
162 ArrayRef<const char *> Argv,
163 DiagnosticsEngine &Diags);
168 bool AssemblerInvocation::CreateFromArgs(AssemblerInvocation &Opts,
169 ArrayRef<const char *> Argv,
170 DiagnosticsEngine &Diags) {
173 // Parse the arguments.
174 std::unique_ptr<OptTable> OptTbl(createDriverOptTable());
176 const unsigned IncludedFlagsBitmask = options::CC1AsOption;
177 unsigned MissingArgIndex, MissingArgCount;
178 InputArgList Args = OptTbl->ParseArgs(Argv, MissingArgIndex, MissingArgCount,
179 IncludedFlagsBitmask);
181 // Check for missing argument error.
182 if (MissingArgCount) {
183 Diags.Report(diag::err_drv_missing_argument)
184 << Args.getArgString(MissingArgIndex) << MissingArgCount;
188 // Issue errors on unknown arguments.
189 for (const Arg *A : Args.filtered(OPT_UNKNOWN)) {
190 auto ArgString = A->getAsString(Args);
192 if (OptTbl->findNearest(ArgString, Nearest, IncludedFlagsBitmask) > 1)
193 Diags.Report(diag::err_drv_unknown_argument) << ArgString;
195 Diags.Report(diag::err_drv_unknown_argument_with_suggestion)
196 << ArgString << Nearest;
200 // Construct the invocation.
203 Opts.Triple = llvm::Triple::normalize(Args.getLastArgValue(OPT_triple));
204 Opts.CPU = Args.getLastArgValue(OPT_target_cpu);
205 Opts.Features = Args.getAllArgValues(OPT_target_feature);
207 // Use the default target triple if unspecified.
208 if (Opts.Triple.empty())
209 Opts.Triple = llvm::sys::getDefaultTargetTriple();
212 Opts.IncludePaths = Args.getAllArgValues(OPT_I);
213 Opts.NoInitialTextSection = Args.hasArg(OPT_n);
214 Opts.SaveTemporaryLabels = Args.hasArg(OPT_msave_temp_labels);
215 // Any DebugInfoKind implies GenDwarfForAssembly.
216 Opts.GenDwarfForAssembly = Args.hasArg(OPT_debug_info_kind_EQ);
218 if (const Arg *A = Args.getLastArg(OPT_compress_debug_sections,
219 OPT_compress_debug_sections_EQ)) {
220 if (A->getOption().getID() == OPT_compress_debug_sections) {
221 // TODO: be more clever about the compression type auto-detection
222 Opts.CompressDebugSections = llvm::DebugCompressionType::GNU;
224 Opts.CompressDebugSections =
225 llvm::StringSwitch<llvm::DebugCompressionType>(A->getValue())
226 .Case("none", llvm::DebugCompressionType::None)
227 .Case("zlib", llvm::DebugCompressionType::Z)
228 .Case("zlib-gnu", llvm::DebugCompressionType::GNU)
229 .Default(llvm::DebugCompressionType::None);
233 Opts.RelaxELFRelocations = Args.hasArg(OPT_mrelax_relocations);
234 Opts.DwarfVersion = getLastArgIntValue(Args, OPT_dwarf_version_EQ, 2, Diags);
235 Opts.DwarfDebugFlags = Args.getLastArgValue(OPT_dwarf_debug_flags);
236 Opts.DwarfDebugProducer = Args.getLastArgValue(OPT_dwarf_debug_producer);
237 Opts.DebugCompilationDir = Args.getLastArgValue(OPT_fdebug_compilation_dir);
238 Opts.MainFileName = Args.getLastArgValue(OPT_main_file_name);
240 for (const auto &Arg : Args.getAllArgValues(OPT_fdebug_prefix_map_EQ))
241 Opts.DebugPrefixMap.insert(StringRef(Arg).split('='));
244 if (Args.hasArg(OPT_INPUT)) {
246 for (const Arg *A : Args.filtered(OPT_INPUT)) {
248 Opts.InputFile = A->getValue();
251 Diags.Report(diag::err_drv_unknown_argument) << A->getAsString(Args);
256 Opts.LLVMArgs = Args.getAllArgValues(OPT_mllvm);
257 Opts.OutputPath = Args.getLastArgValue(OPT_o);
258 Opts.SplitDwarfFile = Args.getLastArgValue(OPT_split_dwarf_file);
259 if (Arg *A = Args.getLastArg(OPT_filetype)) {
260 StringRef Name = A->getValue();
261 unsigned OutputType = StringSwitch<unsigned>(Name)
263 .Case("null", FT_Null)
266 if (OutputType == ~0U) {
267 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Name;
270 Opts.OutputType = FileType(OutputType);
272 Opts.ShowHelp = Args.hasArg(OPT_help);
273 Opts.ShowVersion = Args.hasArg(OPT_version);
275 // Transliterate Options
276 Opts.OutputAsmVariant =
277 getLastArgIntValue(Args, OPT_output_asm_variant, 0, Diags);
278 Opts.ShowEncoding = Args.hasArg(OPT_show_encoding);
279 Opts.ShowInst = Args.hasArg(OPT_show_inst);
282 Opts.RelaxAll = Args.hasArg(OPT_mrelax_all);
283 Opts.NoExecStack = Args.hasArg(OPT_mno_exec_stack);
284 Opts.FatalWarnings = Args.hasArg(OPT_massembler_fatal_warnings);
285 Opts.RelocationModel = Args.getLastArgValue(OPT_mrelocation_model, "pic");
286 Opts.IncrementalLinkerCompatible =
287 Args.hasArg(OPT_mincremental_linker_compatible);
288 Opts.SymbolDefs = Args.getAllArgValues(OPT_defsym);
290 // EmbedBitcode Option. If -fembed-bitcode is enabled, set the flag.
291 // EmbedBitcode behaves the same for all embed options for assembly files.
292 if (auto *A = Args.getLastArg(OPT_fembed_bitcode_EQ)) {
293 Opts.EmbedBitcode = llvm::StringSwitch<unsigned>(A->getValue())
303 static std::unique_ptr<raw_fd_ostream>
304 getOutputStream(StringRef Path, DiagnosticsEngine &Diags, bool Binary) {
305 // Make sure that the Out file gets unlinked from the disk if we get a
308 sys::RemoveFileOnSignal(Path);
311 auto Out = llvm::make_unique<raw_fd_ostream>(
312 Path, EC, (Binary ? sys::fs::F_None : sys::fs::F_Text));
314 Diags.Report(diag::err_fe_unable_to_open_output) << Path << EC.message();
321 static bool ExecuteAssembler(AssemblerInvocation &Opts,
322 DiagnosticsEngine &Diags) {
323 // Get the target specific parser.
325 const Target *TheTarget = TargetRegistry::lookupTarget(Opts.Triple, Error);
327 return Diags.Report(diag::err_target_unknown_triple) << Opts.Triple;
329 ErrorOr<std::unique_ptr<MemoryBuffer>> Buffer =
330 MemoryBuffer::getFileOrSTDIN(Opts.InputFile);
332 if (std::error_code EC = Buffer.getError()) {
333 Error = EC.message();
334 return Diags.Report(diag::err_fe_error_reading) << Opts.InputFile;
339 // Tell SrcMgr about this buffer, which is what the parser will pick up.
340 SrcMgr.AddNewSourceBuffer(std::move(*Buffer), SMLoc());
342 // Record the location of the include directories so that the lexer can find
344 SrcMgr.setIncludeDirs(Opts.IncludePaths);
346 std::unique_ptr<MCRegisterInfo> MRI(TheTarget->createMCRegInfo(Opts.Triple));
347 assert(MRI && "Unable to create target register info!");
349 std::unique_ptr<MCAsmInfo> MAI(TheTarget->createMCAsmInfo(*MRI, Opts.Triple));
350 assert(MAI && "Unable to create target asm info!");
352 // Ensure MCAsmInfo initialization occurs before any use, otherwise sections
353 // may be created with a combination of default and explicit settings.
354 MAI->setCompressDebugSections(Opts.CompressDebugSections);
356 MAI->setRelaxELFRelocations(Opts.RelaxELFRelocations);
358 bool IsBinary = Opts.OutputType == AssemblerInvocation::FT_Obj;
359 if (Opts.OutputPath.empty())
360 Opts.OutputPath = "-";
361 std::unique_ptr<raw_fd_ostream> FDOS =
362 getOutputStream(Opts.OutputPath, Diags, IsBinary);
365 std::unique_ptr<raw_fd_ostream> DwoOS;
366 if (!Opts.SplitDwarfFile.empty())
367 DwoOS = getOutputStream(Opts.SplitDwarfFile, Diags, IsBinary);
369 // FIXME: This is not pretty. MCContext has a ptr to MCObjectFileInfo and
370 // MCObjectFileInfo needs a MCContext reference in order to initialize itself.
371 std::unique_ptr<MCObjectFileInfo> MOFI(new MCObjectFileInfo());
373 MCContext Ctx(MAI.get(), MRI.get(), MOFI.get(), &SrcMgr);
376 if (Opts.RelocationModel == "static") {
378 } else if (Opts.RelocationModel == "pic") {
381 assert(Opts.RelocationModel == "dynamic-no-pic" &&
382 "Invalid PIC model!");
386 MOFI->InitMCObjectFileInfo(Triple(Opts.Triple), PIC, Ctx);
387 if (Opts.SaveTemporaryLabels)
388 Ctx.setAllowTemporaryLabels(false);
389 if (Opts.GenDwarfForAssembly)
390 Ctx.setGenDwarfForAssembly(true);
391 if (!Opts.DwarfDebugFlags.empty())
392 Ctx.setDwarfDebugFlags(StringRef(Opts.DwarfDebugFlags));
393 if (!Opts.DwarfDebugProducer.empty())
394 Ctx.setDwarfDebugProducer(StringRef(Opts.DwarfDebugProducer));
395 if (!Opts.DebugCompilationDir.empty())
396 Ctx.setCompilationDir(Opts.DebugCompilationDir);
397 if (!Opts.DebugPrefixMap.empty())
398 for (const auto &KV : Opts.DebugPrefixMap)
399 Ctx.addDebugPrefixMapEntry(KV.first, KV.second);
400 if (!Opts.MainFileName.empty())
401 Ctx.setMainFileName(StringRef(Opts.MainFileName));
402 Ctx.setDwarfVersion(Opts.DwarfVersion);
404 // Build up the feature string from the target feature list.
406 if (!Opts.Features.empty()) {
407 FS = Opts.Features[0];
408 for (unsigned i = 1, e = Opts.Features.size(); i != e; ++i)
409 FS += "," + Opts.Features[i];
412 std::unique_ptr<MCStreamer> Str;
414 std::unique_ptr<MCInstrInfo> MCII(TheTarget->createMCInstrInfo());
415 std::unique_ptr<MCSubtargetInfo> STI(
416 TheTarget->createMCSubtargetInfo(Opts.Triple, Opts.CPU, FS));
418 raw_pwrite_stream *Out = FDOS.get();
419 std::unique_ptr<buffer_ostream> BOS;
421 // FIXME: There is a bit of code duplication with addPassesToEmitFile.
422 if (Opts.OutputType == AssemblerInvocation::FT_Asm) {
423 MCInstPrinter *IP = TheTarget->createMCInstPrinter(
424 llvm::Triple(Opts.Triple), Opts.OutputAsmVariant, *MAI, *MCII, *MRI);
426 std::unique_ptr<MCCodeEmitter> CE;
427 if (Opts.ShowEncoding)
428 CE.reset(TheTarget->createMCCodeEmitter(*MCII, *MRI, Ctx));
429 MCTargetOptions MCOptions;
430 std::unique_ptr<MCAsmBackend> MAB(
431 TheTarget->createMCAsmBackend(*STI, *MRI, MCOptions));
433 auto FOut = llvm::make_unique<formatted_raw_ostream>(*Out);
434 Str.reset(TheTarget->createAsmStreamer(
435 Ctx, std::move(FOut), /*asmverbose*/ true,
436 /*useDwarfDirectory*/ true, IP, std::move(CE), std::move(MAB),
438 } else if (Opts.OutputType == AssemblerInvocation::FT_Null) {
439 Str.reset(createNullStreamer(Ctx));
441 assert(Opts.OutputType == AssemblerInvocation::FT_Obj &&
442 "Invalid file type!");
443 if (!FDOS->supportsSeeking()) {
444 BOS = make_unique<buffer_ostream>(*FDOS);
448 std::unique_ptr<MCCodeEmitter> CE(
449 TheTarget->createMCCodeEmitter(*MCII, *MRI, Ctx));
450 MCTargetOptions MCOptions;
451 std::unique_ptr<MCAsmBackend> MAB(
452 TheTarget->createMCAsmBackend(*STI, *MRI, MCOptions));
453 std::unique_ptr<MCObjectWriter> OW =
454 DwoOS ? MAB->createDwoObjectWriter(*Out, *DwoOS)
455 : MAB->createObjectWriter(*Out);
457 Triple T(Opts.Triple);
458 Str.reset(TheTarget->createMCObjectStreamer(
459 T, Ctx, std::move(MAB), std::move(OW), std::move(CE), *STI,
460 Opts.RelaxAll, Opts.IncrementalLinkerCompatible,
461 /*DWARFMustBeAtTheEnd*/ true));
462 Str.get()->InitSections(Opts.NoExecStack);
465 // When -fembed-bitcode is passed to clang_as, a 1-byte marker
466 // is emitted in __LLVM,__asm section if the object file is MachO format.
467 if (Opts.EmbedBitcode && Ctx.getObjectFileInfo()->getObjectFileType() ==
468 MCObjectFileInfo::IsMachO) {
469 MCSection *AsmLabel = Ctx.getMachOSection(
470 "__LLVM", "__asm", MachO::S_REGULAR, 4, SectionKind::getReadOnly());
471 Str.get()->SwitchSection(AsmLabel);
472 Str.get()->EmitZeros(1);
475 // Assembly to object compilation should leverage assembly info.
476 Str->setUseAssemblerInfoForParsing(true);
480 std::unique_ptr<MCAsmParser> Parser(
481 createMCAsmParser(SrcMgr, Ctx, *Str.get(), *MAI));
483 // FIXME: init MCTargetOptions from sanitizer flags here.
484 MCTargetOptions Options;
485 std::unique_ptr<MCTargetAsmParser> TAP(
486 TheTarget->createMCAsmParser(*STI, *Parser, *MCII, Options));
488 Failed = Diags.Report(diag::err_target_unknown_triple) << Opts.Triple;
490 // Set values for symbols, if any.
491 for (auto &S : Opts.SymbolDefs) {
492 auto Pair = StringRef(S).split('=');
493 auto Sym = Pair.first;
494 auto Val = Pair.second;
496 // We have already error checked this in the driver.
497 Val.getAsInteger(0, Value);
498 Ctx.setSymbolValue(Parser->getStreamer(), Sym, Value);
502 Parser->setTargetParser(*TAP.get());
503 Failed = Parser->Run(Opts.NoInitialTextSection);
506 // Close Streamer first.
507 // It might have a reference to the output stream.
509 // Close the output stream early.
513 // Delete output file if there were errors.
515 if (Opts.OutputPath != "-")
516 sys::fs::remove(Opts.OutputPath);
517 if (!Opts.SplitDwarfFile.empty() && Opts.SplitDwarfFile != "-")
518 sys::fs::remove(Opts.SplitDwarfFile);
524 static void LLVMErrorHandler(void *UserData, const std::string &Message,
526 DiagnosticsEngine &Diags = *static_cast<DiagnosticsEngine*>(UserData);
528 Diags.Report(diag::err_fe_error_backend) << Message;
530 // We cannot recover from llvm errors.
534 int cc1as_main(ArrayRef<const char *> Argv, const char *Argv0, void *MainAddr) {
535 // Initialize targets and assembly printers/parsers.
536 InitializeAllTargetInfos();
537 InitializeAllTargetMCs();
538 InitializeAllAsmParsers();
540 // Construct our diagnostic client.
541 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
542 TextDiagnosticPrinter *DiagClient
543 = new TextDiagnosticPrinter(errs(), &*DiagOpts);
544 DiagClient->setPrefix("clang -cc1as");
545 IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
546 DiagnosticsEngine Diags(DiagID, &*DiagOpts, DiagClient);
548 // Set an error handler, so that any LLVM backend diagnostics go through our
550 ScopedFatalErrorHandler FatalErrorHandler
551 (LLVMErrorHandler, static_cast<void*>(&Diags));
553 // Parse the arguments.
554 AssemblerInvocation Asm;
555 if (!AssemblerInvocation::CreateFromArgs(Asm, Argv, Diags))
559 std::unique_ptr<OptTable> Opts(driver::createDriverOptTable());
560 Opts->PrintHelp(llvm::outs(), "clang -cc1as [options] file...",
561 "Clang Integrated Assembler",
562 /*Include=*/driver::options::CC1AsOption, /*Exclude=*/0,
563 /*ShowAllAliases=*/false);
569 // FIXME: Use a better -version message?
570 if (Asm.ShowVersion) {
571 llvm::cl::PrintVersionMessage();
577 // FIXME: Remove this, one day.
578 if (!Asm.LLVMArgs.empty()) {
579 unsigned NumArgs = Asm.LLVMArgs.size();
580 auto Args = llvm::make_unique<const char*[]>(NumArgs + 2);
581 Args[0] = "clang (LLVM option parsing)";
582 for (unsigned i = 0; i != NumArgs; ++i)
583 Args[i + 1] = Asm.LLVMArgs[i].c_str();
584 Args[NumArgs + 1] = nullptr;
585 llvm::cl::ParseCommandLineOptions(NumArgs + 1, Args.get());
588 // Execute the invocation, unless there were parsing errors.
589 bool Failed = Diags.hasErrorOccurred() || ExecuteAssembler(Asm, Diags);
591 // If any timers were active but haven't been destroyed yet, print their
593 TimerGroup::printAll(errs());