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/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/MCParser/MCAsmParser.h"
32 #include "llvm/MC/MCRegisterInfo.h"
33 #include "llvm/MC/MCStreamer.h"
34 #include "llvm/MC/MCSubtargetInfo.h"
35 #include "llvm/MC/MCTargetAsmParser.h"
36 #include "llvm/MC/MCTargetOptions.h"
37 #include "llvm/Option/Arg.h"
38 #include "llvm/Option/ArgList.h"
39 #include "llvm/Option/OptTable.h"
40 #include "llvm/Support/CommandLine.h"
41 #include "llvm/Support/ErrorHandling.h"
42 #include "llvm/Support/FileSystem.h"
43 #include "llvm/Support/FormattedStream.h"
44 #include "llvm/Support/Host.h"
45 #include "llvm/Support/ManagedStatic.h"
46 #include "llvm/Support/MemoryBuffer.h"
47 #include "llvm/Support/Path.h"
48 #include "llvm/Support/PrettyStackTrace.h"
49 #include "llvm/Support/Signals.h"
50 #include "llvm/Support/SourceMgr.h"
51 #include "llvm/Support/TargetRegistry.h"
52 #include "llvm/Support/TargetSelect.h"
53 #include "llvm/Support/Timer.h"
54 #include "llvm/Support/raw_ostream.h"
56 #include <system_error>
57 using namespace clang;
58 using namespace clang::driver;
59 using namespace clang::driver::options;
61 using namespace llvm::opt;
65 /// \brief Helper class for representing a single invocation of the assembler.
66 struct AssemblerInvocation {
67 /// @name Target Options
70 /// The name of the target triple to assemble for.
73 /// If given, the name of the target CPU to determine which instructions
77 /// The list of target specific features to enable or disable -- this should
78 /// be a list of strings starting with '+' or '-'.
79 std::vector<std::string> Features;
82 /// @name Language Options
85 std::vector<std::string> IncludePaths;
86 unsigned NoInitialTextSection : 1;
87 unsigned SaveTemporaryLabels : 1;
88 unsigned GenDwarfForAssembly : 1;
89 unsigned CompressDebugSections : 1;
90 unsigned DwarfVersion;
91 std::string DwarfDebugFlags;
92 std::string DwarfDebugProducer;
93 std::string DebugCompilationDir;
94 std::string MainFileName;
97 /// @name Frontend Options
100 std::string InputFile;
101 std::vector<std::string> LLVMArgs;
102 std::string OutputPath;
104 FT_Asm, ///< Assembly (.s) output, transliterate mode.
105 FT_Null, ///< No output, for timing purposes.
106 FT_Obj ///< Object file output.
109 unsigned ShowHelp : 1;
110 unsigned ShowVersion : 1;
113 /// @name Transliterate Options
116 unsigned OutputAsmVariant;
117 unsigned ShowEncoding : 1;
118 unsigned ShowInst : 1;
121 /// @name Assembler Options
124 unsigned RelaxAll : 1;
125 unsigned NoExecStack : 1;
130 AssemblerInvocation() {
132 NoInitialTextSection = 0;
136 OutputAsmVariant = 0;
144 static bool CreateFromArgs(AssemblerInvocation &Res, const char **ArgBegin,
145 const char **ArgEnd, DiagnosticsEngine &Diags);
150 bool AssemblerInvocation::CreateFromArgs(AssemblerInvocation &Opts,
151 const char **ArgBegin,
153 DiagnosticsEngine &Diags) {
156 // Parse the arguments.
157 std::unique_ptr<OptTable> OptTbl(createDriverOptTable());
159 const unsigned IncludedFlagsBitmask = options::CC1AsOption;
160 unsigned MissingArgIndex, MissingArgCount;
161 std::unique_ptr<InputArgList> Args(
162 OptTbl->ParseArgs(ArgBegin, ArgEnd, MissingArgIndex, MissingArgCount,
163 IncludedFlagsBitmask));
165 // Check for missing argument error.
166 if (MissingArgCount) {
167 Diags.Report(diag::err_drv_missing_argument)
168 << Args->getArgString(MissingArgIndex) << MissingArgCount;
172 // Issue errors on unknown arguments.
173 for (arg_iterator it = Args->filtered_begin(OPT_UNKNOWN),
174 ie = Args->filtered_end();
176 Diags.Report(diag::err_drv_unknown_argument) << (*it)->getAsString(*Args);
180 // Construct the invocation.
183 Opts.Triple = llvm::Triple::normalize(Args->getLastArgValue(OPT_triple));
184 Opts.CPU = Args->getLastArgValue(OPT_target_cpu);
185 Opts.Features = Args->getAllArgValues(OPT_target_feature);
187 // Use the default target triple if unspecified.
188 if (Opts.Triple.empty())
189 Opts.Triple = llvm::sys::getDefaultTargetTriple();
192 Opts.IncludePaths = Args->getAllArgValues(OPT_I);
193 Opts.NoInitialTextSection = Args->hasArg(OPT_n);
194 Opts.SaveTemporaryLabels = Args->hasArg(OPT_msave_temp_labels);
195 Opts.GenDwarfForAssembly = Args->hasArg(OPT_g_Flag);
196 Opts.CompressDebugSections = Args->hasArg(OPT_compress_debug_sections);
197 if (Args->hasArg(OPT_gdwarf_2))
198 Opts.DwarfVersion = 2;
199 if (Args->hasArg(OPT_gdwarf_3))
200 Opts.DwarfVersion = 3;
201 if (Args->hasArg(OPT_gdwarf_4))
202 Opts.DwarfVersion = 4;
203 Opts.DwarfDebugFlags = Args->getLastArgValue(OPT_dwarf_debug_flags);
204 Opts.DwarfDebugProducer = Args->getLastArgValue(OPT_dwarf_debug_producer);
205 Opts.DebugCompilationDir = Args->getLastArgValue(OPT_fdebug_compilation_dir);
206 Opts.MainFileName = Args->getLastArgValue(OPT_main_file_name);
209 if (Args->hasArg(OPT_INPUT)) {
211 for (arg_iterator it = Args->filtered_begin(OPT_INPUT),
212 ie = Args->filtered_end(); it != ie; ++it, First=false) {
215 Opts.InputFile = A->getValue();
217 Diags.Report(diag::err_drv_unknown_argument) << A->getAsString(*Args);
222 Opts.LLVMArgs = Args->getAllArgValues(OPT_mllvm);
223 Opts.OutputPath = Args->getLastArgValue(OPT_o);
224 if (Arg *A = Args->getLastArg(OPT_filetype)) {
225 StringRef Name = A->getValue();
226 unsigned OutputType = StringSwitch<unsigned>(Name)
228 .Case("null", FT_Null)
231 if (OutputType == ~0U) {
232 Diags.Report(diag::err_drv_invalid_value)
233 << A->getAsString(*Args) << Name;
236 Opts.OutputType = FileType(OutputType);
238 Opts.ShowHelp = Args->hasArg(OPT_help);
239 Opts.ShowVersion = Args->hasArg(OPT_version);
241 // Transliterate Options
242 Opts.OutputAsmVariant =
243 getLastArgIntValue(*Args.get(), OPT_output_asm_variant, 0, Diags);
244 Opts.ShowEncoding = Args->hasArg(OPT_show_encoding);
245 Opts.ShowInst = Args->hasArg(OPT_show_inst);
248 Opts.RelaxAll = Args->hasArg(OPT_mrelax_all);
249 Opts.NoExecStack = Args->hasArg(OPT_mno_exec_stack);
254 static formatted_raw_ostream *GetOutputStream(AssemblerInvocation &Opts,
255 DiagnosticsEngine &Diags,
257 if (Opts.OutputPath.empty())
258 Opts.OutputPath = "-";
260 // Make sure that the Out file gets unlinked from the disk if we get a
262 if (Opts.OutputPath != "-")
263 sys::RemoveFileOnSignal(Opts.OutputPath);
266 raw_fd_ostream *Out =
267 new raw_fd_ostream(Opts.OutputPath.c_str(), Error,
268 (Binary ? sys::fs::F_None : sys::fs::F_Text));
269 if (!Error.empty()) {
270 Diags.Report(diag::err_fe_unable_to_open_output)
271 << Opts.OutputPath << Error;
276 return new formatted_raw_ostream(*Out, formatted_raw_ostream::DELETE_STREAM);
279 static bool ExecuteAssembler(AssemblerInvocation &Opts,
280 DiagnosticsEngine &Diags) {
281 // Get the target specific parser.
283 const Target *TheTarget = TargetRegistry::lookupTarget(Opts.Triple, Error);
285 return Diags.Report(diag::err_target_unknown_triple) << Opts.Triple;
287 ErrorOr<std::unique_ptr<MemoryBuffer>> Buffer =
288 MemoryBuffer::getFileOrSTDIN(Opts.InputFile);
290 if (std::error_code EC = Buffer.getError()) {
291 Error = EC.message();
292 return Diags.Report(diag::err_fe_error_reading) << Opts.InputFile;
297 // Tell SrcMgr about this buffer, which is what the parser will pick up.
298 SrcMgr.AddNewSourceBuffer(Buffer->release(), SMLoc());
300 // Record the location of the include directories so that the lexer can find
302 SrcMgr.setIncludeDirs(Opts.IncludePaths);
304 std::unique_ptr<MCRegisterInfo> MRI(TheTarget->createMCRegInfo(Opts.Triple));
305 assert(MRI && "Unable to create target register info!");
307 std::unique_ptr<MCAsmInfo> MAI(TheTarget->createMCAsmInfo(*MRI, Opts.Triple));
308 assert(MAI && "Unable to create target asm info!");
310 // Ensure MCAsmInfo initialization occurs before any use, otherwise sections
311 // may be created with a combination of default and explicit settings.
312 if (Opts.CompressDebugSections)
313 MAI->setCompressDebugSections(true);
315 bool IsBinary = Opts.OutputType == AssemblerInvocation::FT_Obj;
316 std::unique_ptr<formatted_raw_ostream> Out(
317 GetOutputStream(Opts, Diags, IsBinary));
321 // FIXME: This is not pretty. MCContext has a ptr to MCObjectFileInfo and
322 // MCObjectFileInfo needs a MCContext reference in order to initialize itself.
323 std::unique_ptr<MCObjectFileInfo> MOFI(new MCObjectFileInfo());
325 MCContext Ctx(MAI.get(), MRI.get(), MOFI.get(), &SrcMgr);
326 // FIXME: Assembler behavior can change with -static.
327 MOFI->InitMCObjectFileInfo(Opts.Triple,
328 Reloc::Default, CodeModel::Default, Ctx);
329 if (Opts.SaveTemporaryLabels)
330 Ctx.setAllowTemporaryLabels(false);
331 if (Opts.GenDwarfForAssembly)
332 Ctx.setGenDwarfForAssembly(true);
333 if (!Opts.DwarfDebugFlags.empty())
334 Ctx.setDwarfDebugFlags(StringRef(Opts.DwarfDebugFlags));
335 if (!Opts.DwarfDebugProducer.empty())
336 Ctx.setDwarfDebugProducer(StringRef(Opts.DwarfDebugProducer));
337 if (!Opts.DebugCompilationDir.empty())
338 Ctx.setCompilationDir(Opts.DebugCompilationDir);
339 if (!Opts.MainFileName.empty())
340 Ctx.setMainFileName(StringRef(Opts.MainFileName));
341 Ctx.setDwarfVersion(Opts.DwarfVersion);
343 // Build up the feature string from the target feature list.
345 if (!Opts.Features.empty()) {
346 FS = Opts.Features[0];
347 for (unsigned i = 1, e = Opts.Features.size(); i != e; ++i)
348 FS += "," + Opts.Features[i];
351 std::unique_ptr<MCStreamer> Str;
353 std::unique_ptr<MCInstrInfo> MCII(TheTarget->createMCInstrInfo());
354 std::unique_ptr<MCSubtargetInfo> STI(
355 TheTarget->createMCSubtargetInfo(Opts.Triple, Opts.CPU, FS));
357 // FIXME: There is a bit of code duplication with addPassesToEmitFile.
358 if (Opts.OutputType == AssemblerInvocation::FT_Asm) {
360 TheTarget->createMCInstPrinter(Opts.OutputAsmVariant, *MAI, *MCII, *MRI,
362 MCCodeEmitter *CE = nullptr;
363 MCAsmBackend *MAB = nullptr;
364 if (Opts.ShowEncoding) {
365 CE = TheTarget->createMCCodeEmitter(*MCII, *MRI, *STI, Ctx);
366 MAB = TheTarget->createMCAsmBackend(*MRI, Opts.Triple, Opts.CPU);
368 Str.reset(TheTarget->createAsmStreamer(Ctx, *Out, /*asmverbose*/true,
369 /*useDwarfDirectory*/ true,
372 } else if (Opts.OutputType == AssemblerInvocation::FT_Null) {
373 Str.reset(createNullStreamer(Ctx));
375 assert(Opts.OutputType == AssemblerInvocation::FT_Obj &&
376 "Invalid file type!");
377 MCCodeEmitter *CE = TheTarget->createMCCodeEmitter(*MCII, *MRI, *STI, Ctx);
378 MCAsmBackend *MAB = TheTarget->createMCAsmBackend(*MRI, Opts.Triple,
380 Str.reset(TheTarget->createMCObjectStreamer(Opts.Triple, Ctx, *MAB, *Out,
381 CE, *STI, Opts.RelaxAll,
383 Str.get()->InitSections();
388 std::unique_ptr<MCAsmParser> Parser(
389 createMCAsmParser(SrcMgr, Ctx, *Str.get(), *MAI));
391 // FIXME: init MCTargetOptions from sanitizer flags here.
392 MCTargetOptions Options;
393 std::unique_ptr<MCTargetAsmParser> TAP(
394 TheTarget->createMCAsmParser(*STI, *Parser, *MCII, Options));
396 Failed = Diags.Report(diag::err_target_unknown_triple) << Opts.Triple;
399 Parser->setTargetParser(*TAP.get());
400 Failed = Parser->Run(Opts.NoInitialTextSection);
403 // Close the output stream early.
406 // Delete output file if there were errors.
407 if (Failed && Opts.OutputPath != "-")
408 sys::fs::remove(Opts.OutputPath);
413 static void LLVMErrorHandler(void *UserData, const std::string &Message,
415 DiagnosticsEngine &Diags = *static_cast<DiagnosticsEngine*>(UserData);
417 Diags.Report(diag::err_fe_error_backend) << Message;
419 // We cannot recover from llvm errors.
423 int cc1as_main(const char **ArgBegin, const char **ArgEnd,
424 const char *Argv0, void *MainAddr) {
425 // Print a stack trace if we signal out.
426 sys::PrintStackTraceOnErrorSignal();
427 PrettyStackTraceProgram X(ArgEnd - ArgBegin, ArgBegin);
428 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
430 // Initialize targets and assembly printers/parsers.
431 InitializeAllTargetInfos();
432 InitializeAllTargetMCs();
433 InitializeAllAsmParsers();
435 // Construct our diagnostic client.
436 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
437 TextDiagnosticPrinter *DiagClient
438 = new TextDiagnosticPrinter(errs(), &*DiagOpts);
439 DiagClient->setPrefix("clang -cc1as");
440 IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
441 DiagnosticsEngine Diags(DiagID, &*DiagOpts, DiagClient);
443 // Set an error handler, so that any LLVM backend diagnostics go through our
445 ScopedFatalErrorHandler FatalErrorHandler
446 (LLVMErrorHandler, static_cast<void*>(&Diags));
448 // Parse the arguments.
449 AssemblerInvocation Asm;
450 if (!AssemblerInvocation::CreateFromArgs(Asm, ArgBegin, ArgEnd, Diags))
454 std::unique_ptr<OptTable> Opts(driver::createDriverOptTable());
455 Opts->PrintHelp(llvm::outs(), "clang -cc1as", "Clang Integrated Assembler",
456 /*Include=*/driver::options::CC1AsOption, /*Exclude=*/0);
462 // FIXME: Use a better -version message?
463 if (Asm.ShowVersion) {
464 llvm::cl::PrintVersionMessage();
470 // FIXME: Remove this, one day.
471 if (!Asm.LLVMArgs.empty()) {
472 unsigned NumArgs = Asm.LLVMArgs.size();
473 const char **Args = new const char*[NumArgs + 2];
474 Args[0] = "clang (LLVM option parsing)";
475 for (unsigned i = 0; i != NumArgs; ++i)
476 Args[i + 1] = Asm.LLVMArgs[i].c_str();
477 Args[NumArgs + 1] = nullptr;
478 llvm::cl::ParseCommandLineOptions(NumArgs + 1, Args);
481 // Execute the invocation, unless there were parsing errors.
482 bool Failed = Diags.hasErrorOccurred() || ExecuteAssembler(Asm, Diags);
484 // If any timers were active but haven't been destroyed yet, print their
486 TimerGroup::printAll(errs());