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/Driver/Arg.h"
17 #include "clang/Driver/ArgList.h"
18 #include "clang/Driver/DriverDiagnostic.h"
19 #include "clang/Driver/CC1AsOptions.h"
20 #include "clang/Driver/OptTable.h"
21 #include "clang/Driver/Options.h"
22 #include "clang/Frontend/FrontendDiagnostic.h"
23 #include "clang/Frontend/TextDiagnosticPrinter.h"
24 #include "clang/Basic/DiagnosticOptions.h"
25 #include "llvm/ADT/OwningPtr.h"
26 #include "llvm/ADT/StringSwitch.h"
27 #include "llvm/ADT/Triple.h"
28 #include "llvm/MC/MCParser/MCAsmParser.h"
29 #include "llvm/MC/MCAsmInfo.h"
30 #include "llvm/MC/MCCodeEmitter.h"
31 #include "llvm/MC/MCContext.h"
32 #include "llvm/MC/MCInstrInfo.h"
33 #include "llvm/MC/MCObjectFileInfo.h"
34 #include "llvm/MC/MCRegisterInfo.h"
35 #include "llvm/MC/MCStreamer.h"
36 #include "llvm/MC/MCSubtargetInfo.h"
37 #include "llvm/MC/MCAsmBackend.h"
38 #include "llvm/MC/MCTargetAsmParser.h"
39 #include "llvm/Support/CommandLine.h"
40 #include "llvm/Support/FormattedStream.h"
41 #include "llvm/Support/ErrorHandling.h"
42 #include "llvm/Support/ManagedStatic.h"
43 #include "llvm/Support/MemoryBuffer.h"
44 #include "llvm/Support/PrettyStackTrace.h"
45 #include "llvm/Support/SourceMgr.h"
46 #include "llvm/Support/Host.h"
47 #include "llvm/Support/Path.h"
48 #include "llvm/Support/Signals.h"
49 #include "llvm/Support/TargetRegistry.h"
50 #include "llvm/Support/TargetSelect.h"
51 #include "llvm/Support/Timer.h"
52 #include "llvm/Support/raw_ostream.h"
53 #include "llvm/Support/system_error.h"
54 #include "llvm/DataLayout.h"
55 using namespace clang;
56 using namespace clang::driver;
61 /// \brief Helper class for representing a single invocation of the assembler.
62 struct AssemblerInvocation {
63 /// @name Target Options
66 /// The name of the target triple to assemble for.
69 /// If given, the name of the target CPU to determine which instructions
73 /// The list of target specific features to enable or disable -- this should
74 /// be a list of strings starting with '+' or '-'.
75 std::vector<std::string> Features;
78 /// @name Language Options
81 std::vector<std::string> IncludePaths;
82 unsigned NoInitialTextSection : 1;
83 unsigned SaveTemporaryLabels : 1;
84 unsigned GenDwarfForAssembly : 1;
85 std::string DwarfDebugFlags;
88 /// @name Frontend Options
91 std::string InputFile;
92 std::vector<std::string> LLVMArgs;
93 std::string OutputPath;
95 FT_Asm, ///< Assembly (.s) output, transliterate mode.
96 FT_Null, ///< No output, for timing purposes.
97 FT_Obj ///< Object file output.
100 unsigned ShowHelp : 1;
101 unsigned ShowVersion : 1;
104 /// @name Transliterate Options
107 unsigned OutputAsmVariant;
108 unsigned ShowEncoding : 1;
109 unsigned ShowInst : 1;
112 /// @name Assembler Options
115 unsigned RelaxAll : 1;
116 unsigned NoExecStack : 1;
121 AssemblerInvocation() {
123 NoInitialTextSection = 0;
127 OutputAsmVariant = 0;
134 static bool CreateFromArgs(AssemblerInvocation &Res, const char **ArgBegin,
135 const char **ArgEnd, DiagnosticsEngine &Diags);
140 bool AssemblerInvocation::CreateFromArgs(AssemblerInvocation &Opts,
141 const char **ArgBegin,
143 DiagnosticsEngine &Diags) {
144 using namespace clang::driver::cc1asoptions;
147 // Parse the arguments.
148 OwningPtr<OptTable> OptTbl(createCC1AsOptTable());
149 unsigned MissingArgIndex, MissingArgCount;
150 OwningPtr<InputArgList> Args(
151 OptTbl->ParseArgs(ArgBegin, ArgEnd,MissingArgIndex, MissingArgCount));
153 // Check for missing argument error.
154 if (MissingArgCount) {
155 Diags.Report(diag::err_drv_missing_argument)
156 << Args->getArgString(MissingArgIndex) << MissingArgCount;
160 // Issue errors on unknown arguments.
161 for (arg_iterator it = Args->filtered_begin(cc1asoptions::OPT_UNKNOWN),
162 ie = Args->filtered_end(); it != ie; ++it) {
163 Diags.Report(diag::err_drv_unknown_argument) << (*it) ->getAsString(*Args);
167 // Construct the invocation.
170 Opts.Triple = llvm::Triple::normalize(Args->getLastArgValue(OPT_triple));
171 Opts.CPU = Args->getLastArgValue(OPT_target_cpu);
172 Opts.Features = Args->getAllArgValues(OPT_target_feature);
174 // Use the default target triple if unspecified.
175 if (Opts.Triple.empty())
176 Opts.Triple = llvm::sys::getDefaultTargetTriple();
179 Opts.IncludePaths = Args->getAllArgValues(OPT_I);
180 Opts.NoInitialTextSection = Args->hasArg(OPT_n);
181 Opts.SaveTemporaryLabels = Args->hasArg(OPT_L);
182 Opts.GenDwarfForAssembly = Args->hasArg(OPT_g);
183 Opts.DwarfDebugFlags = Args->getLastArgValue(OPT_dwarf_debug_flags);
186 if (Args->hasArg(OPT_INPUT)) {
188 for (arg_iterator it = Args->filtered_begin(OPT_INPUT),
189 ie = Args->filtered_end(); it != ie; ++it, First=false) {
192 Opts.InputFile = A->getValue();
194 Diags.Report(diag::err_drv_unknown_argument) << A->getAsString(*Args);
199 Opts.LLVMArgs = Args->getAllArgValues(OPT_mllvm);
200 if (Args->hasArg(OPT_fatal_warnings))
201 Opts.LLVMArgs.push_back("-fatal-assembler-warnings");
202 Opts.OutputPath = Args->getLastArgValue(OPT_o);
203 if (Arg *A = Args->getLastArg(OPT_filetype)) {
204 StringRef Name = A->getValue();
205 unsigned OutputType = StringSwitch<unsigned>(Name)
207 .Case("null", FT_Null)
210 if (OutputType == ~0U) {
211 Diags.Report(diag::err_drv_invalid_value)
212 << A->getAsString(*Args) << Name;
215 Opts.OutputType = FileType(OutputType);
217 Opts.ShowHelp = Args->hasArg(OPT_help);
218 Opts.ShowVersion = Args->hasArg(OPT_version);
220 // Transliterate Options
221 Opts.OutputAsmVariant = Args->getLastArgIntValue(OPT_output_asm_variant,
223 Opts.ShowEncoding = Args->hasArg(OPT_show_encoding);
224 Opts.ShowInst = Args->hasArg(OPT_show_inst);
227 Opts.RelaxAll = Args->hasArg(OPT_relax_all);
228 Opts.NoExecStack = Args->hasArg(OPT_no_exec_stack);
233 static formatted_raw_ostream *GetOutputStream(AssemblerInvocation &Opts,
234 DiagnosticsEngine &Diags,
236 if (Opts.OutputPath.empty())
237 Opts.OutputPath = "-";
239 // Make sure that the Out file gets unlinked from the disk if we get a
241 if (Opts.OutputPath != "-")
242 sys::RemoveFileOnSignal(sys::Path(Opts.OutputPath));
245 raw_fd_ostream *Out =
246 new raw_fd_ostream(Opts.OutputPath.c_str(), Error,
247 (Binary ? raw_fd_ostream::F_Binary : 0));
248 if (!Error.empty()) {
249 Diags.Report(diag::err_fe_unable_to_open_output)
250 << Opts.OutputPath << Error;
254 return new formatted_raw_ostream(*Out, formatted_raw_ostream::DELETE_STREAM);
257 static bool ExecuteAssembler(AssemblerInvocation &Opts,
258 DiagnosticsEngine &Diags) {
259 // Get the target specific parser.
261 const Target *TheTarget(TargetRegistry::lookupTarget(Opts.Triple, Error));
263 Diags.Report(diag::err_target_unknown_triple) << Opts.Triple;
267 OwningPtr<MemoryBuffer> BufferPtr;
268 if (error_code ec = MemoryBuffer::getFileOrSTDIN(Opts.InputFile, BufferPtr)) {
269 Error = ec.message();
270 Diags.Report(diag::err_fe_error_reading) << Opts.InputFile;
273 MemoryBuffer *Buffer = BufferPtr.take();
277 // Tell SrcMgr about this buffer, which is what the parser will pick up.
278 SrcMgr.AddNewSourceBuffer(Buffer, SMLoc());
280 // Record the location of the include directories so that the lexer can find
282 SrcMgr.setIncludeDirs(Opts.IncludePaths);
284 OwningPtr<MCAsmInfo> MAI(TheTarget->createMCAsmInfo(Opts.Triple));
285 assert(MAI && "Unable to create target asm info!");
287 OwningPtr<MCRegisterInfo> MRI(TheTarget->createMCRegInfo(Opts.Triple));
288 assert(MRI && "Unable to create target register info!");
290 bool IsBinary = Opts.OutputType == AssemblerInvocation::FT_Obj;
291 formatted_raw_ostream *Out = GetOutputStream(Opts, Diags, IsBinary);
295 // FIXME: This is not pretty. MCContext has a ptr to MCObjectFileInfo and
296 // MCObjectFileInfo needs a MCContext reference in order to initialize itself.
297 OwningPtr<MCObjectFileInfo> MOFI(new MCObjectFileInfo());
298 MCContext Ctx(*MAI, *MRI, MOFI.get(), &SrcMgr);
299 // FIXME: Assembler behavior can change with -static.
300 MOFI->InitMCObjectFileInfo(Opts.Triple,
301 Reloc::Default, CodeModel::Default, Ctx);
302 if (Opts.SaveTemporaryLabels)
303 Ctx.setAllowTemporaryLabels(false);
304 if (Opts.GenDwarfForAssembly)
305 Ctx.setGenDwarfForAssembly(true);
306 if (!Opts.DwarfDebugFlags.empty())
307 Ctx.setDwarfDebugFlags(StringRef(Opts.DwarfDebugFlags));
309 // Build up the feature string from the target feature list.
311 if (!Opts.Features.empty()) {
312 FS = Opts.Features[0];
313 for (unsigned i = 1, e = Opts.Features.size(); i != e; ++i)
314 FS += "," + Opts.Features[i];
317 OwningPtr<MCStreamer> Str;
319 OwningPtr<MCInstrInfo> MCII(TheTarget->createMCInstrInfo());
320 OwningPtr<MCSubtargetInfo>
321 STI(TheTarget->createMCSubtargetInfo(Opts.Triple, Opts.CPU, FS));
323 // FIXME: There is a bit of code duplication with addPassesToEmitFile.
324 if (Opts.OutputType == AssemblerInvocation::FT_Asm) {
326 TheTarget->createMCInstPrinter(Opts.OutputAsmVariant, *MAI, *MCII, *MRI,
328 MCCodeEmitter *CE = 0;
329 MCAsmBackend *MAB = 0;
330 if (Opts.ShowEncoding) {
331 CE = TheTarget->createMCCodeEmitter(*MCII, *MRI, *STI, Ctx);
332 MAB = TheTarget->createMCAsmBackend(Opts.Triple, Opts.CPU);
334 Str.reset(TheTarget->createAsmStreamer(Ctx, *Out, /*asmverbose*/true,
337 /*useDwarfDirectory*/ true,
340 } else if (Opts.OutputType == AssemblerInvocation::FT_Null) {
341 Str.reset(createNullStreamer(Ctx));
343 assert(Opts.OutputType == AssemblerInvocation::FT_Obj &&
344 "Invalid file type!");
345 MCCodeEmitter *CE = TheTarget->createMCCodeEmitter(*MCII, *MRI, *STI, Ctx);
346 MCAsmBackend *MAB = TheTarget->createMCAsmBackend(Opts.Triple, Opts.CPU);
347 Str.reset(TheTarget->createMCObjectStreamer(Opts.Triple, Ctx, *MAB, *Out,
350 Str.get()->InitSections();
353 OwningPtr<MCAsmParser> Parser(createMCAsmParser(SrcMgr, Ctx,
355 OwningPtr<MCTargetAsmParser> TAP(TheTarget->createMCAsmParser(*STI, *Parser));
357 Diags.Report(diag::err_target_unknown_triple) << Opts.Triple;
361 Parser->setTargetParser(*TAP.get());
363 bool Success = !Parser->Run(Opts.NoInitialTextSection);
368 // Delete output on errors.
369 if (!Success && Opts.OutputPath != "-")
370 sys::Path(Opts.OutputPath).eraseFromDisk();
375 static void LLVMErrorHandler(void *UserData, const std::string &Message) {
376 DiagnosticsEngine &Diags = *static_cast<DiagnosticsEngine*>(UserData);
378 Diags.Report(diag::err_fe_error_backend) << Message;
380 // We cannot recover from llvm errors.
384 int cc1as_main(const char **ArgBegin, const char **ArgEnd,
385 const char *Argv0, void *MainAddr) {
386 // Print a stack trace if we signal out.
387 sys::PrintStackTraceOnErrorSignal();
388 PrettyStackTraceProgram X(ArgEnd - ArgBegin, ArgBegin);
389 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
391 // Initialize targets and assembly printers/parsers.
392 InitializeAllTargetInfos();
393 InitializeAllTargetMCs();
394 InitializeAllAsmParsers();
396 // Construct our diagnostic client.
397 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
398 TextDiagnosticPrinter *DiagClient
399 = new TextDiagnosticPrinter(errs(), &*DiagOpts);
400 DiagClient->setPrefix("clang -cc1as");
401 IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
402 DiagnosticsEngine Diags(DiagID, &*DiagOpts, DiagClient);
404 // Set an error handler, so that any LLVM backend diagnostics go through our
406 ScopedFatalErrorHandler FatalErrorHandler
407 (LLVMErrorHandler, static_cast<void*>(&Diags));
409 // Parse the arguments.
410 AssemblerInvocation Asm;
411 if (!AssemblerInvocation::CreateFromArgs(Asm, ArgBegin, ArgEnd, Diags))
416 OwningPtr<driver::OptTable> Opts(driver::createCC1AsOptTable());
417 Opts->PrintHelp(llvm::outs(), "clang -cc1as", "Clang Integrated Assembler");
423 // FIXME: Use a better -version message?
424 if (Asm.ShowVersion) {
425 llvm::cl::PrintVersionMessage();
431 // FIXME: Remove this, one day.
432 if (!Asm.LLVMArgs.empty()) {
433 unsigned NumArgs = Asm.LLVMArgs.size();
434 const char **Args = new const char*[NumArgs + 2];
435 Args[0] = "clang (LLVM option parsing)";
436 for (unsigned i = 0; i != NumArgs; ++i)
437 Args[i + 1] = Asm.LLVMArgs[i].c_str();
438 Args[NumArgs + 1] = 0;
439 llvm::cl::ParseCommandLineOptions(NumArgs + 1, Args);
442 // Execute the invocation, unless there were parsing errors.
443 bool Success = false;
444 if (!Diags.hasErrorOccurred())
445 Success = ExecuteAssembler(Asm, Diags);
447 // If any timers were active but haven't been destroyed yet, print their
449 TimerGroup::printAll(errs());