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/DiagnosticOptions.h"
23 #include "clang/Frontend/FrontendDiagnostic.h"
24 #include "clang/Frontend/TextDiagnosticPrinter.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/MCStreamer.h"
34 #include "llvm/MC/MCSubtargetInfo.h"
35 #include "llvm/Support/CommandLine.h"
36 #include "llvm/Support/FormattedStream.h"
37 #include "llvm/Support/ErrorHandling.h"
38 #include "llvm/Support/ManagedStatic.h"
39 #include "llvm/Support/MemoryBuffer.h"
40 #include "llvm/Support/PrettyStackTrace.h"
41 #include "llvm/Support/SourceMgr.h"
42 #include "llvm/Support/Timer.h"
43 #include "llvm/Support/raw_ostream.h"
44 #include "llvm/Support/Host.h"
45 #include "llvm/Support/Path.h"
46 #include "llvm/Support/Signals.h"
47 #include "llvm/Support/system_error.h"
48 #include "llvm/Target/TargetAsmBackend.h"
49 #include "llvm/Target/TargetAsmInfo.h"
50 #include "llvm/Target/TargetAsmParser.h"
51 #include "llvm/Target/TargetData.h"
52 #include "llvm/Target/TargetInstrInfo.h"
53 #include "llvm/Target/TargetLowering.h"
54 #include "llvm/Target/TargetLoweringObjectFile.h"
55 #include "llvm/Target/TargetMachine.h"
56 #include "llvm/Target/TargetRegistry.h"
57 #include "llvm/Target/TargetSelect.h"
58 #include "llvm/Target/TargetSubtargetInfo.h"
59 using namespace clang;
60 using namespace clang::driver;
65 /// \brief Helper class for representing a single invocation of the assembler.
66 struct AssemblerInvocation {
67 /// @name Target Options
73 /// @name Language Options
76 std::vector<std::string> IncludePaths;
77 unsigned NoInitialTextSection : 1;
78 unsigned SaveTemporaryLabels : 1;
81 /// @name Frontend Options
84 std::string InputFile;
85 std::vector<std::string> LLVMArgs;
86 std::string OutputPath;
88 FT_Asm, ///< Assembly (.s) output, transliterate mode.
89 FT_Null, ///< No output, for timing purposes.
90 FT_Obj ///< Object file output.
93 unsigned ShowHelp : 1;
94 unsigned ShowVersion : 1;
97 /// @name Transliterate Options
100 unsigned OutputAsmVariant;
101 unsigned ShowEncoding : 1;
102 unsigned ShowInst : 1;
105 /// @name Assembler Options
108 unsigned RelaxAll : 1;
109 unsigned NoExecStack : 1;
114 AssemblerInvocation() {
116 NoInitialTextSection = 0;
120 OutputAsmVariant = 0;
127 static void CreateFromArgs(AssemblerInvocation &Res, const char **ArgBegin,
128 const char **ArgEnd, Diagnostic &Diags);
133 void AssemblerInvocation::CreateFromArgs(AssemblerInvocation &Opts,
134 const char **ArgBegin,
137 using namespace clang::driver::cc1asoptions;
138 // Parse the arguments.
139 OwningPtr<OptTable> OptTbl(createCC1AsOptTable());
140 unsigned MissingArgIndex, MissingArgCount;
141 OwningPtr<InputArgList> Args(
142 OptTbl->ParseArgs(ArgBegin, ArgEnd,MissingArgIndex, MissingArgCount));
144 // Check for missing argument error.
146 Diags.Report(diag::err_drv_missing_argument)
147 << Args->getArgString(MissingArgIndex) << MissingArgCount;
149 // Issue errors on unknown arguments.
150 for (arg_iterator it = Args->filtered_begin(cc1asoptions::OPT_UNKNOWN),
151 ie = Args->filtered_end(); it != ie; ++it)
152 Diags.Report(diag::err_drv_unknown_argument) << (*it) ->getAsString(*Args);
154 // Construct the invocation.
157 Opts.Triple = Triple::normalize(Args->getLastArgValue(OPT_triple));
158 if (Opts.Triple.empty()) // Use the host triple if unspecified.
159 Opts.Triple = sys::getHostTriple();
162 Opts.IncludePaths = Args->getAllArgValues(OPT_I);
163 Opts.NoInitialTextSection = Args->hasArg(OPT_n);
164 Opts.SaveTemporaryLabels = Args->hasArg(OPT_L);
167 if (Args->hasArg(OPT_INPUT)) {
169 for (arg_iterator it = Args->filtered_begin(OPT_INPUT),
170 ie = Args->filtered_end(); it != ie; ++it, First=false) {
173 Opts.InputFile = A->getValue(*Args);
175 Diags.Report(diag::err_drv_unknown_argument) << A->getAsString(*Args);
178 Opts.LLVMArgs = Args->getAllArgValues(OPT_mllvm);
179 if (Args->hasArg(OPT_fatal_warnings))
180 Opts.LLVMArgs.push_back("-fatal-assembler-warnings");
181 Opts.OutputPath = Args->getLastArgValue(OPT_o);
182 if (Arg *A = Args->getLastArg(OPT_filetype)) {
183 StringRef Name = A->getValue(*Args);
184 unsigned OutputType = StringSwitch<unsigned>(Name)
186 .Case("null", FT_Null)
189 if (OutputType == ~0U)
190 Diags.Report(diag::err_drv_invalid_value)
191 << A->getAsString(*Args) << Name;
193 Opts.OutputType = FileType(OutputType);
195 Opts.ShowHelp = Args->hasArg(OPT_help);
196 Opts.ShowVersion = Args->hasArg(OPT_version);
198 // Transliterate Options
199 Opts.OutputAsmVariant = Args->getLastArgIntValue(OPT_output_asm_variant,
201 Opts.ShowEncoding = Args->hasArg(OPT_show_encoding);
202 Opts.ShowInst = Args->hasArg(OPT_show_inst);
205 Opts.RelaxAll = Args->hasArg(OPT_relax_all);
206 Opts.NoExecStack = Args->hasArg(OPT_no_exec_stack);
209 static formatted_raw_ostream *GetOutputStream(AssemblerInvocation &Opts,
212 if (Opts.OutputPath.empty())
213 Opts.OutputPath = "-";
215 // Make sure that the Out file gets unlinked from the disk if we get a
217 if (Opts.OutputPath != "-")
218 sys::RemoveFileOnSignal(sys::Path(Opts.OutputPath));
221 raw_fd_ostream *Out =
222 new raw_fd_ostream(Opts.OutputPath.c_str(), Error,
223 (Binary ? raw_fd_ostream::F_Binary : 0));
224 if (!Error.empty()) {
225 Diags.Report(diag::err_fe_unable_to_open_output)
226 << Opts.OutputPath << Error;
230 return new formatted_raw_ostream(*Out, formatted_raw_ostream::DELETE_STREAM);
233 static bool ExecuteAssembler(AssemblerInvocation &Opts, Diagnostic &Diags) {
234 // Get the target specific parser.
236 const Target *TheTarget(TargetRegistry::lookupTarget(Opts.Triple, Error));
238 Diags.Report(diag::err_target_unknown_triple) << Opts.Triple;
242 OwningPtr<MemoryBuffer> BufferPtr;
243 if (error_code ec = MemoryBuffer::getFileOrSTDIN(Opts.InputFile, BufferPtr)) {
244 Error = ec.message();
245 Diags.Report(diag::err_fe_error_reading) << Opts.InputFile;
248 MemoryBuffer *Buffer = BufferPtr.take();
252 // Tell SrcMgr about this buffer, which is what the parser will pick up.
253 SrcMgr.AddNewSourceBuffer(Buffer, SMLoc());
255 // Record the location of the include directories so that the lexer can find
257 SrcMgr.setIncludeDirs(Opts.IncludePaths);
259 OwningPtr<MCAsmInfo> MAI(TheTarget->createMCAsmInfo(Opts.Triple));
260 assert(MAI && "Unable to create target asm info!");
262 bool IsBinary = Opts.OutputType == AssemblerInvocation::FT_Obj;
263 formatted_raw_ostream *Out = GetOutputStream(Opts, Diags, IsBinary);
267 // FIXME: We shouldn't need to do this (and link in codegen).
268 OwningPtr<TargetMachine> TM(TheTarget->createTargetMachine(Opts.Triple,
271 Diags.Report(diag::err_target_unknown_triple) << Opts.Triple;
275 const TargetAsmInfo *tai = new TargetAsmInfo(*TM);
276 MCContext Ctx(*MAI, tai);
277 if (Opts.SaveTemporaryLabels)
278 Ctx.setAllowTemporaryLabels(false);
280 OwningPtr<MCStreamer> Str;
282 const TargetLoweringObjectFile &TLOF =
283 TM->getTargetLowering()->getObjFileLowering();
284 const_cast<TargetLoweringObjectFile&>(TLOF).Initialize(Ctx, *TM);
286 const MCSubtargetInfo &STI = TM->getSubtarget<MCSubtargetInfo>();
288 // FIXME: There is a bit of code duplication with addPassesToEmitFile.
289 if (Opts.OutputType == AssemblerInvocation::FT_Asm) {
291 TheTarget->createMCInstPrinter(Opts.OutputAsmVariant, *MAI);
292 MCCodeEmitter *CE = 0;
293 TargetAsmBackend *TAB = 0;
294 if (Opts.ShowEncoding) {
295 CE = TheTarget->createCodeEmitter(*TM->getInstrInfo(), STI, Ctx);
296 TAB = TheTarget->createAsmBackend(Opts.Triple);
298 Str.reset(TheTarget->createAsmStreamer(Ctx, *Out, /*asmverbose*/true,
300 /*useCFI*/ true, IP, CE, TAB,
302 } else if (Opts.OutputType == AssemblerInvocation::FT_Null) {
303 Str.reset(createNullStreamer(Ctx));
305 assert(Opts.OutputType == AssemblerInvocation::FT_Obj &&
306 "Invalid file type!");
307 MCCodeEmitter *CE = TheTarget->createCodeEmitter(*TM->getInstrInfo(),
309 TargetAsmBackend *TAB = TheTarget->createAsmBackend(Opts.Triple);
310 Str.reset(TheTarget->createObjectStreamer(Opts.Triple, Ctx, *TAB, *Out,
313 Str.get()->InitSections();
316 OwningPtr<MCAsmParser> Parser(createMCAsmParser(*TheTarget, SrcMgr, Ctx,
318 OwningPtr<TargetAsmParser>
319 TAP(TheTarget->createAsmParser(const_cast<MCSubtargetInfo&>(STI), *Parser));
321 Diags.Report(diag::err_target_unknown_triple) << Opts.Triple;
325 Parser->setTargetParser(*TAP.get());
327 bool Success = !Parser->Run(Opts.NoInitialTextSection);
332 // Delete output on errors.
333 if (!Success && Opts.OutputPath != "-")
334 sys::Path(Opts.OutputPath).eraseFromDisk();
339 static void LLVMErrorHandler(void *UserData, const std::string &Message) {
340 Diagnostic &Diags = *static_cast<Diagnostic*>(UserData);
342 Diags.Report(diag::err_fe_error_backend) << Message;
344 // We cannot recover from llvm errors.
348 int cc1as_main(const char **ArgBegin, const char **ArgEnd,
349 const char *Argv0, void *MainAddr) {
350 // Print a stack trace if we signal out.
351 sys::PrintStackTraceOnErrorSignal();
352 PrettyStackTraceProgram X(ArgEnd - ArgBegin, ArgBegin);
353 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
355 // Initialize targets and assembly printers/parsers.
356 InitializeAllTargetInfos();
357 // FIXME: We shouldn't need to initialize the Target(Machine)s.
358 InitializeAllTargets();
359 InitializeAllMCAsmInfos();
360 InitializeAllMCInstrInfos();
361 InitializeAllMCSubtargetInfos();
362 InitializeAllAsmPrinters();
363 InitializeAllAsmParsers();
365 // Construct our diagnostic client.
366 TextDiagnosticPrinter *DiagClient
367 = new TextDiagnosticPrinter(errs(), DiagnosticOptions());
368 DiagClient->setPrefix("clang -cc1as");
369 llvm::IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
370 Diagnostic Diags(DiagID, DiagClient);
372 // Set an error handler, so that any LLVM backend diagnostics go through our
374 ScopedFatalErrorHandler FatalErrorHandler
375 (LLVMErrorHandler, static_cast<void*>(&Diags));
377 // Parse the arguments.
378 AssemblerInvocation Asm;
379 AssemblerInvocation::CreateFromArgs(Asm, ArgBegin, ArgEnd, Diags);
383 llvm::OwningPtr<driver::OptTable> Opts(driver::createCC1AsOptTable());
384 Opts->PrintHelp(llvm::outs(), "clang -cc1as", "Clang Integrated Assembler");
390 // FIXME: Use a better -version message?
391 if (Asm.ShowVersion) {
392 llvm::cl::PrintVersionMessage();
398 // FIXME: Remove this, one day.
399 if (!Asm.LLVMArgs.empty()) {
400 unsigned NumArgs = Asm.LLVMArgs.size();
401 const char **Args = new const char*[NumArgs + 2];
402 Args[0] = "clang (LLVM option parsing)";
403 for (unsigned i = 0; i != NumArgs; ++i)
404 Args[i + 1] = Asm.LLVMArgs[i].c_str();
405 Args[NumArgs + 1] = 0;
406 llvm::cl::ParseCommandLineOptions(NumArgs + 1, const_cast<char **>(Args));
409 // Execute the invocation, unless there were parsing errors.
410 bool Success = false;
411 if (!Diags.hasErrorOccurred())
412 Success = ExecuteAssembler(Asm, Diags);
414 // If any timers were active but haven't been destroyed yet, print their
416 TimerGroup::printAll(errs());