blob: 288e110cf49cbd129c90f83eff341c459ec6a74c [file] [log] [blame]
Daniel Dunbar41b5b172010-05-20 17:49:16 +00001//===-- cc1as_main.cpp - Clang Assembler ---------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This is the entry point to the clang -cc1as functionality, which implements
11// the direct interface to the LLVM MC based assembler.
12//
13//===----------------------------------------------------------------------===//
14
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"
Duncan Sands2dc14532010-08-30 09:42:39 +000027#include "llvm/ADT/Triple.h"
Daniel Dunbar7374f1b2010-07-17 02:26:21 +000028#include "llvm/MC/MCParser/MCAsmParser.h"
29#include "llvm/MC/MCAsmInfo.h"
Daniel Dunbar41b5b172010-05-20 17:49:16 +000030#include "llvm/MC/MCCodeEmitter.h"
31#include "llvm/MC/MCContext.h"
32#include "llvm/MC/MCStreamer.h"
Daniel Dunbarc673af72010-05-20 18:15:20 +000033#include "llvm/Support/CommandLine.h"
Daniel Dunbar41b5b172010-05-20 17:49:16 +000034#include "llvm/Support/FormattedStream.h"
35#include "llvm/Support/ErrorHandling.h"
36#include "llvm/Support/ManagedStatic.h"
37#include "llvm/Support/MemoryBuffer.h"
38#include "llvm/Support/PrettyStackTrace.h"
39#include "llvm/Support/SourceMgr.h"
40#include "llvm/Support/Timer.h"
41#include "llvm/Support/raw_ostream.h"
42#include "llvm/System/Host.h"
43#include "llvm/System/Path.h"
44#include "llvm/System/Signals.h"
45#include "llvm/Target/TargetAsmBackend.h"
46#include "llvm/Target/TargetAsmParser.h"
47#include "llvm/Target/TargetData.h"
48#include "llvm/Target/TargetMachine.h"
49#include "llvm/Target/TargetRegistry.h"
50#include "llvm/Target/TargetSelect.h"
51using namespace clang;
52using namespace clang::driver;
53using namespace llvm;
54
55namespace {
56
57/// \brief Helper class for representing a single invocation of the assembler.
58struct AssemblerInvocation {
59 /// @name Target Options
60 /// @{
61
62 std::string Triple;
63
64 /// @}
65 /// @name Language Options
66 /// @{
67
68 std::vector<std::string> IncludePaths;
69 unsigned NoInitialTextSection : 1;
70
71 /// @}
72 /// @name Frontend Options
73 /// @{
74
75 std::string InputFile;
Daniel Dunbarc673af72010-05-20 18:15:20 +000076 std::vector<std::string> LLVMArgs;
Daniel Dunbar41b5b172010-05-20 17:49:16 +000077 std::string OutputPath;
78 enum FileType {
79 FT_Asm, ///< Assembly (.s) output, transliterate mode.
80 FT_Null, ///< No output, for timing purposes.
81 FT_Obj ///< Object file output.
82 };
83 FileType OutputType;
Daniel Dunbarc673af72010-05-20 18:15:20 +000084 unsigned ShowHelp : 1;
85 unsigned ShowVersion : 1;
Daniel Dunbar41b5b172010-05-20 17:49:16 +000086
87 /// @}
88 /// @name Transliterate Options
89 /// @{
90
91 unsigned OutputAsmVariant;
92 unsigned ShowEncoding : 1;
93 unsigned ShowInst : 1;
94
95 /// @}
96 /// @name Assembler Options
97 /// @{
98
99 unsigned RelaxAll : 1;
100
101 /// @}
102
103public:
104 AssemblerInvocation() {
105 Triple = "";
106 NoInitialTextSection = 0;
107 InputFile = "-";
Daniel Dunbarc673af72010-05-20 18:15:20 +0000108 OutputPath = "-";
Daniel Dunbar41b5b172010-05-20 17:49:16 +0000109 OutputType = FT_Asm;
110 OutputAsmVariant = 0;
111 ShowInst = 0;
112 ShowEncoding = 0;
113 RelaxAll = 0;
114 }
115
116 static void CreateFromArgs(AssemblerInvocation &Res, const char **ArgBegin,
117 const char **ArgEnd, Diagnostic &Diags);
118};
119
120}
121
122void AssemblerInvocation::CreateFromArgs(AssemblerInvocation &Opts,
123 const char **ArgBegin,
124 const char **ArgEnd,
125 Diagnostic &Diags) {
126 using namespace clang::driver::cc1asoptions;
127 // Parse the arguments.
128 OwningPtr<OptTable> OptTbl(createCC1AsOptTable());
129 unsigned MissingArgIndex, MissingArgCount;
130 OwningPtr<InputArgList> Args(
131 OptTbl->ParseArgs(ArgBegin, ArgEnd,MissingArgIndex, MissingArgCount));
132
133 // Check for missing argument error.
134 if (MissingArgCount)
135 Diags.Report(diag::err_drv_missing_argument)
136 << Args->getArgString(MissingArgIndex) << MissingArgCount;
137
138 // Issue errors on unknown arguments.
139 for (arg_iterator it = Args->filtered_begin(cc1asoptions::OPT_UNKNOWN),
140 ie = Args->filtered_end(); it != ie; ++it)
Daniel Dunbar7e4953e2010-06-11 22:00:13 +0000141 Diags.Report(diag::err_drv_unknown_argument) << (*it) ->getAsString(*Args);
Daniel Dunbar41b5b172010-05-20 17:49:16 +0000142
143 // Construct the invocation.
144
145 // Target Options
Duncan Sands2dc14532010-08-30 09:42:39 +0000146 Opts.Triple = Triple::normalize(Args->getLastArgValue(OPT_triple));
Daniel Dunbar41b5b172010-05-20 17:49:16 +0000147 if (Opts.Triple.empty()) // Use the host triple if unspecified.
148 Opts.Triple = sys::getHostTriple();
149
150 // Language Options
151 Opts.IncludePaths = Args->getAllArgValues(OPT_I);
152 Opts.NoInitialTextSection = Args->hasArg(OPT_n);
153
154 // Frontend Options
155 if (Args->hasArg(OPT_INPUT)) {
156 bool First = true;
157 for (arg_iterator it = Args->filtered_begin(OPT_INPUT),
158 ie = Args->filtered_end(); it != ie; ++it, First=false) {
Daniel Dunbar7e4953e2010-06-11 22:00:13 +0000159 const Arg *A = it;
Daniel Dunbar41b5b172010-05-20 17:49:16 +0000160 if (First)
Daniel Dunbar7e4953e2010-06-11 22:00:13 +0000161 Opts.InputFile = A->getValue(*Args);
Daniel Dunbar41b5b172010-05-20 17:49:16 +0000162 else
Daniel Dunbar7e4953e2010-06-11 22:00:13 +0000163 Diags.Report(diag::err_drv_unknown_argument) << A->getAsString(*Args);
Daniel Dunbar41b5b172010-05-20 17:49:16 +0000164 }
165 }
Daniel Dunbarc673af72010-05-20 18:15:20 +0000166 Opts.LLVMArgs = Args->getAllArgValues(OPT_mllvm);
Daniel Dunbar41b5b172010-05-20 17:49:16 +0000167 Opts.OutputPath = Args->getLastArgValue(OPT_o);
168 if (Arg *A = Args->getLastArg(OPT_filetype)) {
169 StringRef Name = A->getValue(*Args);
170 unsigned OutputType = StringSwitch<unsigned>(Name)
171 .Case("asm", FT_Asm)
172 .Case("null", FT_Null)
173 .Case("obj", FT_Obj)
174 .Default(~0U);
175 if (OutputType == ~0U)
176 Diags.Report(diag::err_drv_invalid_value)
177 << A->getAsString(*Args) << Name;
178 else
179 Opts.OutputType = FileType(OutputType);
180 }
Daniel Dunbarc673af72010-05-20 18:15:20 +0000181 Opts.ShowHelp = Args->hasArg(OPT_help);
182 Opts.ShowVersion = Args->hasArg(OPT_version);
Daniel Dunbar41b5b172010-05-20 17:49:16 +0000183
184 // Transliterate Options
185 Opts.OutputAsmVariant = Args->getLastArgIntValue(OPT_output_asm_variant,
186 0, Diags);
187 Opts.ShowEncoding = Args->hasArg(OPT_show_encoding);
188 Opts.ShowInst = Args->hasArg(OPT_show_inst);
189
190 // Assemble Options
191 Opts.RelaxAll = Args->hasArg(OPT_relax_all);
192}
193
194static formatted_raw_ostream *GetOutputStream(AssemblerInvocation &Opts,
195 Diagnostic &Diags,
196 bool Binary) {
Daniel Dunbarc673af72010-05-20 18:15:20 +0000197 if (Opts.OutputPath.empty())
198 Opts.OutputPath = "-";
199
Daniel Dunbar41b5b172010-05-20 17:49:16 +0000200 // Make sure that the Out file gets unlinked from the disk if we get a
201 // SIGINT.
202 if (Opts.OutputPath != "-")
203 sys::RemoveFileOnSignal(sys::Path(Opts.OutputPath));
204
205 std::string Error;
206 raw_fd_ostream *Out =
207 new raw_fd_ostream(Opts.OutputPath.c_str(), Error,
208 (Binary ? raw_fd_ostream::F_Binary : 0));
209 if (!Error.empty()) {
210 Diags.Report(diag::err_fe_unable_to_open_output)
211 << Opts.OutputPath << Error;
212 return 0;
213 }
214
215 return new formatted_raw_ostream(*Out, formatted_raw_ostream::DELETE_STREAM);
216}
217
218static bool ExecuteAssembler(AssemblerInvocation &Opts, Diagnostic &Diags) {
219 // Get the target specific parser.
220 std::string Error;
221 const Target *TheTarget(TargetRegistry::lookupTarget(Opts.Triple, Error));
222 if (!TheTarget) {
223 Diags.Report(diag::err_target_unknown_triple) << Opts.Triple;
224 return false;
225 }
226
227 MemoryBuffer *Buffer = MemoryBuffer::getFileOrSTDIN(Opts.InputFile, &Error);
228 if (Buffer == 0) {
229 Diags.Report(diag::err_fe_error_reading) << Opts.InputFile;
230 return false;
231 }
232
233 SourceMgr SrcMgr;
234
235 // Tell SrcMgr about this buffer, which is what the parser will pick up.
236 SrcMgr.AddNewSourceBuffer(Buffer, SMLoc());
237
238 // Record the location of the include directories so that the lexer can find
239 // it later.
240 SrcMgr.setIncludeDirs(Opts.IncludePaths);
241
242 OwningPtr<MCAsmInfo> MAI(TheTarget->createAsmInfo(Opts.Triple));
243 assert(MAI && "Unable to create target asm info!");
244
245 MCContext Ctx(*MAI);
246 bool IsBinary = Opts.OutputType == AssemblerInvocation::FT_Obj;
247 formatted_raw_ostream *Out = GetOutputStream(Opts, Diags, IsBinary);
248 if (!Out)
249 return false;
250
251 // FIXME: We shouldn't need to do this (and link in codegen).
252 OwningPtr<TargetMachine> TM(TheTarget->createTargetMachine(Opts.Triple, ""));
253 if (!TM) {
254 Diags.Report(diag::err_target_unknown_triple) << Opts.Triple;
255 return false;
256 }
257
Daniel Dunbar41b5b172010-05-20 17:49:16 +0000258 OwningPtr<MCStreamer> Str;
Daniel Dunbar41b5b172010-05-20 17:49:16 +0000259
260 if (Opts.OutputType == AssemblerInvocation::FT_Asm) {
261 MCInstPrinter *IP =
262 TheTarget->createMCInstPrinter(Opts.OutputAsmVariant, *MAI);
Benjamin Kramer7ac3d5a2010-07-29 17:48:03 +0000263 MCCodeEmitter *CE = 0;
Daniel Dunbar41b5b172010-05-20 17:49:16 +0000264 if (Opts.ShowEncoding)
Benjamin Kramer7ac3d5a2010-07-29 17:48:03 +0000265 CE = TheTarget->createCodeEmitter(*TM, Ctx);
Daniel Dunbar41b5b172010-05-20 17:49:16 +0000266 Str.reset(createAsmStreamer(Ctx, *Out,TM->getTargetData()->isLittleEndian(),
Benjamin Kramer7ac3d5a2010-07-29 17:48:03 +0000267 /*asmverbose*/true, IP, CE, Opts.ShowInst));
Daniel Dunbar41b5b172010-05-20 17:49:16 +0000268 } else if (Opts.OutputType == AssemblerInvocation::FT_Null) {
269 Str.reset(createNullStreamer(Ctx));
270 } else {
271 assert(Opts.OutputType == AssemblerInvocation::FT_Obj &&
272 "Invalid file type!");
Benjamin Kramer7ac3d5a2010-07-29 17:48:03 +0000273 MCCodeEmitter *CE = TheTarget->createCodeEmitter(*TM, Ctx);
274 TargetAsmBackend *TAB = TheTarget->createAsmBackend(Opts.Triple);
275 Str.reset(TheTarget->createObjectStreamer(Opts.Triple, Ctx, *TAB, *Out,
276 CE, Opts.RelaxAll));
Rafael Espindola4f036fa2010-10-13 14:53:57 +0000277 Str.get()->InitSections();
Daniel Dunbar41b5b172010-05-20 17:49:16 +0000278 }
279
Daniel Dunbar7374f1b2010-07-17 02:26:21 +0000280 OwningPtr<MCAsmParser> Parser(createMCAsmParser(*TheTarget, SrcMgr, Ctx,
281 *Str.get(), *MAI));
Daniel Dunbare9122a32010-07-19 00:33:53 +0000282 OwningPtr<TargetAsmParser> TAP(TheTarget->createAsmParser(*Parser, *TM));
Daniel Dunbar41b5b172010-05-20 17:49:16 +0000283 if (!TAP) {
284 Diags.Report(diag::err_target_unknown_triple) << Opts.Triple;
285 return false;
286 }
287
Daniel Dunbar7374f1b2010-07-17 02:26:21 +0000288 Parser->setTargetParser(*TAP.get());
Daniel Dunbar41b5b172010-05-20 17:49:16 +0000289
Daniel Dunbar7374f1b2010-07-17 02:26:21 +0000290 bool Success = !Parser->Run(Opts.NoInitialTextSection);
Daniel Dunbar41b5b172010-05-20 17:49:16 +0000291
292 // Close the output.
293 delete Out;
294
295 // Delete output on errors.
296 if (!Success && Opts.OutputPath != "-")
297 sys::Path(Opts.OutputPath).eraseFromDisk();
298
299 return Success;
300}
301
302static void LLVMErrorHandler(void *UserData, const std::string &Message) {
303 Diagnostic &Diags = *static_cast<Diagnostic*>(UserData);
304
305 Diags.Report(diag::err_fe_error_backend) << Message;
306
307 // We cannot recover from llvm errors.
308 exit(1);
309}
310
311int cc1as_main(const char **ArgBegin, const char **ArgEnd,
312 const char *Argv0, void *MainAddr) {
313 // Print a stack trace if we signal out.
314 sys::PrintStackTraceOnErrorSignal();
315 PrettyStackTraceProgram X(ArgEnd - ArgBegin, ArgBegin);
316 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
317
318 // Initialize targets and assembly printers/parsers.
319 InitializeAllTargetInfos();
320 // FIXME: We shouldn't need to initialize the Target(Machine)s.
321 InitializeAllTargets();
322 InitializeAllAsmPrinters();
323 InitializeAllAsmParsers();
324
325 // Construct our diagnostic client.
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000326 TextDiagnosticPrinter *DiagClient
327 = new TextDiagnosticPrinter(errs(), DiagnosticOptions());
328 DiagClient->setPrefix("clang -cc1as");
329 Diagnostic Diags(DiagClient);
Daniel Dunbar41b5b172010-05-20 17:49:16 +0000330
331 // Set an error handler, so that any LLVM backend diagnostics go through our
332 // error handler.
Dan Gohman726578c2010-08-18 21:23:17 +0000333 ScopedFatalErrorHandler FatalErrorHandler
334 (LLVMErrorHandler, static_cast<void*>(&Diags));
Daniel Dunbar41b5b172010-05-20 17:49:16 +0000335
336 // Parse the arguments.
337 AssemblerInvocation Asm;
338 AssemblerInvocation::CreateFromArgs(Asm, ArgBegin, ArgEnd, Diags);
339
Daniel Dunbarc673af72010-05-20 18:15:20 +0000340 // Honor -help.
341 if (Asm.ShowHelp) {
342 llvm::OwningPtr<driver::OptTable> Opts(driver::createCC1AsOptTable());
343 Opts->PrintHelp(llvm::outs(), "clang -cc1as", "Clang Integrated Assembler");
344 return 0;
345 }
346
347 // Honor -version.
348 //
349 // FIXME: Use a better -version message?
350 if (Asm.ShowVersion) {
351 llvm::cl::PrintVersionMessage();
352 return 0;
353 }
354
355 // Honor -mllvm.
356 //
357 // FIXME: Remove this, one day.
358 if (!Asm.LLVMArgs.empty()) {
359 unsigned NumArgs = Asm.LLVMArgs.size();
360 const char **Args = new const char*[NumArgs + 2];
361 Args[0] = "clang (LLVM option parsing)";
362 for (unsigned i = 0; i != NumArgs; ++i)
363 Args[i + 1] = Asm.LLVMArgs[i].c_str();
364 Args[NumArgs + 1] = 0;
365 llvm::cl::ParseCommandLineOptions(NumArgs + 1, const_cast<char **>(Args));
366 }
367
Daniel Dunbar41b5b172010-05-20 17:49:16 +0000368 // Execute the invocation, unless there were parsing errors.
369 bool Success = false;
370 if (!Diags.getNumErrors())
371 Success = ExecuteAssembler(Asm, Diags);
372
373 // If any timers were active but haven't been destroyed yet, print their
374 // results now.
375 TimerGroup::printAll(errs());
376
377 return !Success;
378}