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/CC1AsOptions.h"
18 #include "clang/Driver/DriverDiagnostic.h"
19 #include "clang/Driver/Options.h"
20 #include "clang/Frontend/FrontendDiagnostic.h"
21 #include "clang/Frontend/TextDiagnosticPrinter.h"
22 #include "clang/Frontend/Utils.h"
23 #include "llvm/ADT/OwningPtr.h"
24 #include "llvm/ADT/StringSwitch.h"
25 #include "llvm/ADT/Triple.h"
26 #include "llvm/IR/DataLayout.h"
27 #include "llvm/MC/MCAsmBackend.h"
28 #include "llvm/MC/MCAsmInfo.h"
29 #include "llvm/MC/MCCodeEmitter.h"
30 #include "llvm/MC/MCContext.h"
31 #include "llvm/MC/MCInstrInfo.h"
32 #include "llvm/MC/MCObjectFileInfo.h"
33 #include "llvm/MC/MCParser/MCAsmParser.h"
34 #include "llvm/MC/MCRegisterInfo.h"
35 #include "llvm/MC/MCStreamer.h"
36 #include "llvm/MC/MCSubtargetInfo.h"
37 #include "llvm/MC/MCTargetAsmParser.h"
38 #include "llvm/Option/Arg.h"
39 #include "llvm/Option/ArgList.h"
40 #include "llvm/Option/OptTable.h"
41 #include "llvm/Support/CommandLine.h"
42 #include "llvm/Support/ErrorHandling.h"
43 #include "llvm/Support/FileSystem.h"
44 #include "llvm/Support/FormattedStream.h"
45 #include "llvm/Support/Host.h"
46 #include "llvm/Support/ManagedStatic.h"
47 #include "llvm/Support/MemoryBuffer.h"
48 #include "llvm/Support/Path.h"
49 #include "llvm/Support/PrettyStackTrace.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"
56 #include "llvm/Support/system_error.h"
57 using namespace clang;
58 using namespace clang::driver;
60 using namespace llvm::opt;
64 /// \brief Helper class for representing a single invocation of the assembler.
65 struct AssemblerInvocation {
66 /// @name Target Options
69 /// The name of the target triple to assemble for.
72 /// If given, the name of the target CPU to determine which instructions
76 /// The list of target specific features to enable or disable -- this should
77 /// be a list of strings starting with '+' or '-'.
78 std::vector<std::string> Features;
81 /// @name Language Options
84 std::vector<std::string> IncludePaths;
85 unsigned NoInitialTextSection : 1;
86 unsigned SaveTemporaryLabels : 1;
87 unsigned GenDwarfForAssembly : 1;
88 std::string DwarfDebugFlags;
89 std::string DwarfDebugProducer;
90 std::string DebugCompilationDir;
91 std::string MainFileName;
94 /// @name Frontend Options
97 std::string InputFile;
98 std::vector<std::string> LLVMArgs;
99 std::string OutputPath;
101 FT_Asm, ///< Assembly (.s) output, transliterate mode.
102 FT_Null, ///< No output, for timing purposes.
103 FT_Obj ///< Object file output.
106 unsigned ShowHelp : 1;
107 unsigned ShowVersion : 1;
110 /// @name Transliterate Options
113 unsigned OutputAsmVariant;
114 unsigned ShowEncoding : 1;
115 unsigned ShowInst : 1;
118 /// @name Assembler Options
121 unsigned RelaxAll : 1;
122 unsigned NoExecStack : 1;
127 AssemblerInvocation() {
129 NoInitialTextSection = 0;
133 OutputAsmVariant = 0;
140 static bool CreateFromArgs(AssemblerInvocation &Res, const char **ArgBegin,
141 const char **ArgEnd, DiagnosticsEngine &Diags);
146 bool AssemblerInvocation::CreateFromArgs(AssemblerInvocation &Opts,
147 const char **ArgBegin,
149 DiagnosticsEngine &Diags) {
150 using namespace clang::driver::cc1asoptions;
153 // Parse the arguments.
154 OwningPtr<OptTable> OptTbl(createCC1AsOptTable());
155 unsigned MissingArgIndex, MissingArgCount;
156 OwningPtr<InputArgList> Args(
157 OptTbl->ParseArgs(ArgBegin, ArgEnd,MissingArgIndex, MissingArgCount));
159 // Check for missing argument error.
160 if (MissingArgCount) {
161 Diags.Report(diag::err_drv_missing_argument)
162 << Args->getArgString(MissingArgIndex) << MissingArgCount;
166 // Issue errors on unknown arguments.
167 for (arg_iterator it = Args->filtered_begin(cc1asoptions::OPT_UNKNOWN),
168 ie = Args->filtered_end(); it != ie; ++it) {
169 Diags.Report(diag::err_drv_unknown_argument) << (*it) ->getAsString(*Args);
173 // Construct the invocation.
176 Opts.Triple = llvm::Triple::normalize(Args->getLastArgValue(OPT_triple));
177 Opts.CPU = Args->getLastArgValue(OPT_target_cpu);
178 Opts.Features = Args->getAllArgValues(OPT_target_feature);
180 // Use the default target triple if unspecified.
181 if (Opts.Triple.empty())
182 Opts.Triple = llvm::sys::getDefaultTargetTriple();
185 Opts.IncludePaths = Args->getAllArgValues(OPT_I);
186 Opts.NoInitialTextSection = Args->hasArg(OPT_n);
187 Opts.SaveTemporaryLabels = Args->hasArg(OPT_msave_temp_labels);
188 Opts.GenDwarfForAssembly = Args->hasArg(OPT_g);
189 Opts.DwarfDebugFlags = Args->getLastArgValue(OPT_dwarf_debug_flags);
190 Opts.DwarfDebugProducer = Args->getLastArgValue(OPT_dwarf_debug_producer);
191 Opts.DebugCompilationDir = Args->getLastArgValue(OPT_fdebug_compilation_dir);
192 Opts.MainFileName = Args->getLastArgValue(OPT_main_file_name);
195 if (Args->hasArg(OPT_INPUT)) {
197 for (arg_iterator it = Args->filtered_begin(OPT_INPUT),
198 ie = Args->filtered_end(); it != ie; ++it, First=false) {
201 Opts.InputFile = A->getValue();
203 Diags.Report(diag::err_drv_unknown_argument) << A->getAsString(*Args);
208 Opts.LLVMArgs = Args->getAllArgValues(OPT_mllvm);
209 Opts.OutputPath = Args->getLastArgValue(OPT_o);
210 if (Arg *A = Args->getLastArg(OPT_filetype)) {
211 StringRef Name = A->getValue();
212 unsigned OutputType = StringSwitch<unsigned>(Name)
214 .Case("null", FT_Null)
217 if (OutputType == ~0U) {
218 Diags.Report(diag::err_drv_invalid_value)
219 << A->getAsString(*Args) << Name;
222 Opts.OutputType = FileType(OutputType);
224 Opts.ShowHelp = Args->hasArg(OPT_help);
225 Opts.ShowVersion = Args->hasArg(OPT_version);
227 // Transliterate Options
228 Opts.OutputAsmVariant =
229 getLastArgIntValue(*Args.get(), OPT_output_asm_variant, 0, Diags);
230 Opts.ShowEncoding = Args->hasArg(OPT_show_encoding);
231 Opts.ShowInst = Args->hasArg(OPT_show_inst);
234 Opts.RelaxAll = Args->hasArg(OPT_mrelax_all);
235 Opts.NoExecStack = Args->hasArg(OPT_mno_exec_stack);
240 static formatted_raw_ostream *GetOutputStream(AssemblerInvocation &Opts,
241 DiagnosticsEngine &Diags,
243 if (Opts.OutputPath.empty())
244 Opts.OutputPath = "-";
246 // Make sure that the Out file gets unlinked from the disk if we get a
248 if (Opts.OutputPath != "-")
249 sys::RemoveFileOnSignal(Opts.OutputPath);
252 raw_fd_ostream *Out =
253 new raw_fd_ostream(Opts.OutputPath.c_str(), Error,
254 (Binary ? sys::fs::F_Binary : sys::fs::F_None));
255 if (!Error.empty()) {
256 Diags.Report(diag::err_fe_unable_to_open_output)
257 << Opts.OutputPath << Error;
261 return new formatted_raw_ostream(*Out, formatted_raw_ostream::DELETE_STREAM);
264 static bool ExecuteAssembler(AssemblerInvocation &Opts,
265 DiagnosticsEngine &Diags) {
266 // Get the target specific parser.
268 const Target *TheTarget(TargetRegistry::lookupTarget(Opts.Triple, Error));
270 Diags.Report(diag::err_target_unknown_triple) << Opts.Triple;
274 OwningPtr<MemoryBuffer> BufferPtr;
275 if (error_code ec = MemoryBuffer::getFileOrSTDIN(Opts.InputFile, BufferPtr)) {
276 Error = ec.message();
277 Diags.Report(diag::err_fe_error_reading) << Opts.InputFile;
280 MemoryBuffer *Buffer = BufferPtr.take();
284 // Tell SrcMgr about this buffer, which is what the parser will pick up.
285 SrcMgr.AddNewSourceBuffer(Buffer, SMLoc());
287 // Record the location of the include directories so that the lexer can find
289 SrcMgr.setIncludeDirs(Opts.IncludePaths);
291 OwningPtr<MCRegisterInfo> MRI(TheTarget->createMCRegInfo(Opts.Triple));
292 assert(MRI && "Unable to create target register info!");
294 OwningPtr<MCAsmInfo> MAI(TheTarget->createMCAsmInfo(*MRI, Opts.Triple));
295 assert(MAI && "Unable to create target asm info!");
297 bool IsBinary = Opts.OutputType == AssemblerInvocation::FT_Obj;
298 formatted_raw_ostream *Out = GetOutputStream(Opts, Diags, IsBinary);
302 // FIXME: This is not pretty. MCContext has a ptr to MCObjectFileInfo and
303 // MCObjectFileInfo needs a MCContext reference in order to initialize itself.
304 OwningPtr<MCObjectFileInfo> MOFI(new MCObjectFileInfo());
305 MCContext Ctx(MAI.get(), MRI.get(), MOFI.get(), &SrcMgr);
306 // FIXME: Assembler behavior can change with -static.
307 MOFI->InitMCObjectFileInfo(Opts.Triple,
308 Reloc::Default, CodeModel::Default, Ctx);
309 if (Opts.SaveTemporaryLabels)
310 Ctx.setAllowTemporaryLabels(false);
311 if (Opts.GenDwarfForAssembly)
312 Ctx.setGenDwarfForAssembly(true);
313 if (!Opts.DwarfDebugFlags.empty())
314 Ctx.setDwarfDebugFlags(StringRef(Opts.DwarfDebugFlags));
315 if (!Opts.DwarfDebugProducer.empty())
316 Ctx.setDwarfDebugProducer(StringRef(Opts.DwarfDebugProducer));
317 if (!Opts.DebugCompilationDir.empty())
318 Ctx.setCompilationDir(Opts.DebugCompilationDir);
319 if (!Opts.MainFileName.empty())
320 Ctx.setMainFileName(StringRef(Opts.MainFileName));
322 // Build up the feature string from the target feature list.
324 if (!Opts.Features.empty()) {
325 FS = Opts.Features[0];
326 for (unsigned i = 1, e = Opts.Features.size(); i != e; ++i)
327 FS += "," + Opts.Features[i];
330 OwningPtr<MCStreamer> Str;
332 OwningPtr<MCInstrInfo> MCII(TheTarget->createMCInstrInfo());
333 OwningPtr<MCSubtargetInfo>
334 STI(TheTarget->createMCSubtargetInfo(Opts.Triple, Opts.CPU, FS));
336 // FIXME: There is a bit of code duplication with addPassesToEmitFile.
337 if (Opts.OutputType == AssemblerInvocation::FT_Asm) {
339 TheTarget->createMCInstPrinter(Opts.OutputAsmVariant, *MAI, *MCII, *MRI,
341 MCCodeEmitter *CE = 0;
342 MCAsmBackend *MAB = 0;
343 if (Opts.ShowEncoding) {
344 CE = TheTarget->createMCCodeEmitter(*MCII, *MRI, *STI, Ctx);
345 MAB = TheTarget->createMCAsmBackend(*MRI, Opts.Triple, Opts.CPU);
347 Str.reset(TheTarget->createAsmStreamer(Ctx, *Out, /*asmverbose*/true,
350 /*useDwarfDirectory*/ true,
353 } else if (Opts.OutputType == AssemblerInvocation::FT_Null) {
354 Str.reset(createNullStreamer(Ctx));
356 assert(Opts.OutputType == AssemblerInvocation::FT_Obj &&
357 "Invalid file type!");
358 MCCodeEmitter *CE = TheTarget->createMCCodeEmitter(*MCII, *MRI, *STI, Ctx);
359 MCAsmBackend *MAB = TheTarget->createMCAsmBackend(*MRI, Opts.Triple,
361 Str.reset(TheTarget->createMCObjectStreamer(Opts.Triple, Ctx, *MAB, *Out,
364 Str.get()->InitSections();
367 OwningPtr<MCAsmParser> Parser(createMCAsmParser(SrcMgr, Ctx,
369 OwningPtr<MCTargetAsmParser> TAP(TheTarget->createMCAsmParser(*STI, *Parser, *MCII));
371 Diags.Report(diag::err_target_unknown_triple) << Opts.Triple;
375 Parser->setTargetParser(*TAP.get());
377 bool Success = !Parser->Run(Opts.NoInitialTextSection);
382 // Delete output on errors.
383 if (!Success && Opts.OutputPath != "-")
384 sys::fs::remove(Opts.OutputPath);
389 static void LLVMErrorHandler(void *UserData, const std::string &Message,
391 DiagnosticsEngine &Diags = *static_cast<DiagnosticsEngine*>(UserData);
393 Diags.Report(diag::err_fe_error_backend) << Message;
395 // We cannot recover from llvm errors.
399 int cc1as_main(const char **ArgBegin, const char **ArgEnd,
400 const char *Argv0, void *MainAddr) {
401 // Print a stack trace if we signal out.
402 sys::PrintStackTraceOnErrorSignal();
403 PrettyStackTraceProgram X(ArgEnd - ArgBegin, ArgBegin);
404 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
406 // Initialize targets and assembly printers/parsers.
407 InitializeAllTargetInfos();
408 InitializeAllTargetMCs();
409 InitializeAllAsmParsers();
411 // Construct our diagnostic client.
412 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
413 TextDiagnosticPrinter *DiagClient
414 = new TextDiagnosticPrinter(errs(), &*DiagOpts);
415 DiagClient->setPrefix("clang -cc1as");
416 IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
417 DiagnosticsEngine Diags(DiagID, &*DiagOpts, DiagClient);
419 // Set an error handler, so that any LLVM backend diagnostics go through our
421 ScopedFatalErrorHandler FatalErrorHandler
422 (LLVMErrorHandler, static_cast<void*>(&Diags));
424 // Parse the arguments.
425 AssemblerInvocation Asm;
426 if (!AssemblerInvocation::CreateFromArgs(Asm, ArgBegin, ArgEnd, Diags))
431 OwningPtr<OptTable> Opts(driver::createCC1AsOptTable());
432 Opts->PrintHelp(llvm::outs(), "clang -cc1as", "Clang Integrated Assembler");
438 // FIXME: Use a better -version message?
439 if (Asm.ShowVersion) {
440 llvm::cl::PrintVersionMessage();
446 // FIXME: Remove this, one day.
447 if (!Asm.LLVMArgs.empty()) {
448 unsigned NumArgs = Asm.LLVMArgs.size();
449 const char **Args = new const char*[NumArgs + 2];
450 Args[0] = "clang (LLVM option parsing)";
451 for (unsigned i = 0; i != NumArgs; ++i)
452 Args[i + 1] = Asm.LLVMArgs[i].c_str();
453 Args[NumArgs + 1] = 0;
454 llvm::cl::ParseCommandLineOptions(NumArgs + 1, Args);
457 // Execute the invocation, unless there were parsing errors.
458 bool Success = false;
459 if (!Diags.hasErrorOccurred())
460 Success = ExecuteAssembler(Asm, Diags);
462 // If any timers were active but haven't been destroyed yet, print their
464 TimerGroup::printAll(errs());