blob: 40ee20eed0fa1a194ddac224a46ee104a1a93ce2 [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"
Michael J. Spencer03013fa2010-11-29 18:12:39 +000042#include "llvm/Support/Host.h"
43#include "llvm/Support/Path.h"
44#include "llvm/Support/Signals.h"
Michael J. Spencer3a321e22010-12-09 17:36:38 +000045#include "llvm/Support/system_error.h"
Daniel Dunbar41b5b172010-05-20 17:49:16 +000046#include "llvm/Target/TargetAsmBackend.h"
47#include "llvm/Target/TargetAsmParser.h"
48#include "llvm/Target/TargetData.h"
49#include "llvm/Target/TargetMachine.h"
50#include "llvm/Target/TargetRegistry.h"
51#include "llvm/Target/TargetSelect.h"
52using namespace clang;
53using namespace clang::driver;
54using namespace llvm;
55
56namespace {
57
58/// \brief Helper class for representing a single invocation of the assembler.
59struct AssemblerInvocation {
60 /// @name Target Options
61 /// @{
62
63 std::string Triple;
64
65 /// @}
66 /// @name Language Options
67 /// @{
68
69 std::vector<std::string> IncludePaths;
70 unsigned NoInitialTextSection : 1;
71
72 /// @}
73 /// @name Frontend Options
74 /// @{
75
76 std::string InputFile;
Daniel Dunbarc673af72010-05-20 18:15:20 +000077 std::vector<std::string> LLVMArgs;
Daniel Dunbar41b5b172010-05-20 17:49:16 +000078 std::string OutputPath;
79 enum FileType {
80 FT_Asm, ///< Assembly (.s) output, transliterate mode.
81 FT_Null, ///< No output, for timing purposes.
82 FT_Obj ///< Object file output.
83 };
84 FileType OutputType;
Daniel Dunbarc673af72010-05-20 18:15:20 +000085 unsigned ShowHelp : 1;
86 unsigned ShowVersion : 1;
Daniel Dunbar41b5b172010-05-20 17:49:16 +000087
88 /// @}
89 /// @name Transliterate Options
90 /// @{
91
92 unsigned OutputAsmVariant;
93 unsigned ShowEncoding : 1;
94 unsigned ShowInst : 1;
95
96 /// @}
97 /// @name Assembler Options
98 /// @{
99
100 unsigned RelaxAll : 1;
101
102 /// @}
103
104public:
105 AssemblerInvocation() {
106 Triple = "";
107 NoInitialTextSection = 0;
108 InputFile = "-";
Daniel Dunbarc673af72010-05-20 18:15:20 +0000109 OutputPath = "-";
Daniel Dunbar41b5b172010-05-20 17:49:16 +0000110 OutputType = FT_Asm;
111 OutputAsmVariant = 0;
112 ShowInst = 0;
113 ShowEncoding = 0;
114 RelaxAll = 0;
115 }
116
117 static void CreateFromArgs(AssemblerInvocation &Res, const char **ArgBegin,
118 const char **ArgEnd, Diagnostic &Diags);
119};
120
121}
122
123void AssemblerInvocation::CreateFromArgs(AssemblerInvocation &Opts,
124 const char **ArgBegin,
125 const char **ArgEnd,
126 Diagnostic &Diags) {
127 using namespace clang::driver::cc1asoptions;
128 // Parse the arguments.
129 OwningPtr<OptTable> OptTbl(createCC1AsOptTable());
130 unsigned MissingArgIndex, MissingArgCount;
131 OwningPtr<InputArgList> Args(
132 OptTbl->ParseArgs(ArgBegin, ArgEnd,MissingArgIndex, MissingArgCount));
133
134 // Check for missing argument error.
135 if (MissingArgCount)
136 Diags.Report(diag::err_drv_missing_argument)
137 << Args->getArgString(MissingArgIndex) << MissingArgCount;
138
139 // Issue errors on unknown arguments.
140 for (arg_iterator it = Args->filtered_begin(cc1asoptions::OPT_UNKNOWN),
141 ie = Args->filtered_end(); it != ie; ++it)
Daniel Dunbar7e4953e2010-06-11 22:00:13 +0000142 Diags.Report(diag::err_drv_unknown_argument) << (*it) ->getAsString(*Args);
Daniel Dunbar41b5b172010-05-20 17:49:16 +0000143
144 // Construct the invocation.
145
146 // Target Options
Duncan Sands2dc14532010-08-30 09:42:39 +0000147 Opts.Triple = Triple::normalize(Args->getLastArgValue(OPT_triple));
Daniel Dunbar41b5b172010-05-20 17:49:16 +0000148 if (Opts.Triple.empty()) // Use the host triple if unspecified.
149 Opts.Triple = sys::getHostTriple();
150
151 // Language Options
152 Opts.IncludePaths = Args->getAllArgValues(OPT_I);
153 Opts.NoInitialTextSection = Args->hasArg(OPT_n);
154
155 // Frontend Options
156 if (Args->hasArg(OPT_INPUT)) {
157 bool First = true;
158 for (arg_iterator it = Args->filtered_begin(OPT_INPUT),
159 ie = Args->filtered_end(); it != ie; ++it, First=false) {
Daniel Dunbar7e4953e2010-06-11 22:00:13 +0000160 const Arg *A = it;
Daniel Dunbar41b5b172010-05-20 17:49:16 +0000161 if (First)
Daniel Dunbar7e4953e2010-06-11 22:00:13 +0000162 Opts.InputFile = A->getValue(*Args);
Daniel Dunbar41b5b172010-05-20 17:49:16 +0000163 else
Daniel Dunbar7e4953e2010-06-11 22:00:13 +0000164 Diags.Report(diag::err_drv_unknown_argument) << A->getAsString(*Args);
Daniel Dunbar41b5b172010-05-20 17:49:16 +0000165 }
166 }
Daniel Dunbarc673af72010-05-20 18:15:20 +0000167 Opts.LLVMArgs = Args->getAllArgValues(OPT_mllvm);
Daniel Dunbar41b5b172010-05-20 17:49:16 +0000168 Opts.OutputPath = Args->getLastArgValue(OPT_o);
169 if (Arg *A = Args->getLastArg(OPT_filetype)) {
170 StringRef Name = A->getValue(*Args);
171 unsigned OutputType = StringSwitch<unsigned>(Name)
172 .Case("asm", FT_Asm)
173 .Case("null", FT_Null)
174 .Case("obj", FT_Obj)
175 .Default(~0U);
176 if (OutputType == ~0U)
177 Diags.Report(diag::err_drv_invalid_value)
178 << A->getAsString(*Args) << Name;
179 else
180 Opts.OutputType = FileType(OutputType);
181 }
Daniel Dunbarc673af72010-05-20 18:15:20 +0000182 Opts.ShowHelp = Args->hasArg(OPT_help);
183 Opts.ShowVersion = Args->hasArg(OPT_version);
Daniel Dunbar41b5b172010-05-20 17:49:16 +0000184
185 // Transliterate Options
186 Opts.OutputAsmVariant = Args->getLastArgIntValue(OPT_output_asm_variant,
187 0, Diags);
188 Opts.ShowEncoding = Args->hasArg(OPT_show_encoding);
189 Opts.ShowInst = Args->hasArg(OPT_show_inst);
190
191 // Assemble Options
192 Opts.RelaxAll = Args->hasArg(OPT_relax_all);
193}
194
195static formatted_raw_ostream *GetOutputStream(AssemblerInvocation &Opts,
196 Diagnostic &Diags,
197 bool Binary) {
Daniel Dunbarc673af72010-05-20 18:15:20 +0000198 if (Opts.OutputPath.empty())
199 Opts.OutputPath = "-";
200
Daniel Dunbar41b5b172010-05-20 17:49:16 +0000201 // Make sure that the Out file gets unlinked from the disk if we get a
202 // SIGINT.
203 if (Opts.OutputPath != "-")
204 sys::RemoveFileOnSignal(sys::Path(Opts.OutputPath));
205
206 std::string Error;
207 raw_fd_ostream *Out =
208 new raw_fd_ostream(Opts.OutputPath.c_str(), Error,
209 (Binary ? raw_fd_ostream::F_Binary : 0));
210 if (!Error.empty()) {
211 Diags.Report(diag::err_fe_unable_to_open_output)
212 << Opts.OutputPath << Error;
213 return 0;
214 }
215
216 return new formatted_raw_ostream(*Out, formatted_raw_ostream::DELETE_STREAM);
217}
218
219static bool ExecuteAssembler(AssemblerInvocation &Opts, Diagnostic &Diags) {
220 // Get the target specific parser.
221 std::string Error;
222 const Target *TheTarget(TargetRegistry::lookupTarget(Opts.Triple, Error));
223 if (!TheTarget) {
224 Diags.Report(diag::err_target_unknown_triple) << Opts.Triple;
225 return false;
226 }
227
Michael J. Spencer3a321e22010-12-09 17:36:38 +0000228 error_code ec;
229 MemoryBuffer *Buffer = MemoryBuffer::getFileOrSTDIN(Opts.InputFile, ec);
Daniel Dunbar41b5b172010-05-20 17:49:16 +0000230 if (Buffer == 0) {
Michael J. Spencer3a321e22010-12-09 17:36:38 +0000231 Error = ec.message();
Daniel Dunbar41b5b172010-05-20 17:49:16 +0000232 Diags.Report(diag::err_fe_error_reading) << Opts.InputFile;
233 return false;
234 }
235
236 SourceMgr SrcMgr;
237
238 // Tell SrcMgr about this buffer, which is what the parser will pick up.
239 SrcMgr.AddNewSourceBuffer(Buffer, SMLoc());
240
241 // Record the location of the include directories so that the lexer can find
242 // it later.
243 SrcMgr.setIncludeDirs(Opts.IncludePaths);
244
245 OwningPtr<MCAsmInfo> MAI(TheTarget->createAsmInfo(Opts.Triple));
246 assert(MAI && "Unable to create target asm info!");
247
248 MCContext Ctx(*MAI);
249 bool IsBinary = Opts.OutputType == AssemblerInvocation::FT_Obj;
250 formatted_raw_ostream *Out = GetOutputStream(Opts, Diags, IsBinary);
251 if (!Out)
252 return false;
253
254 // FIXME: We shouldn't need to do this (and link in codegen).
255 OwningPtr<TargetMachine> TM(TheTarget->createTargetMachine(Opts.Triple, ""));
256 if (!TM) {
257 Diags.Report(diag::err_target_unknown_triple) << Opts.Triple;
258 return false;
259 }
260
Daniel Dunbar41b5b172010-05-20 17:49:16 +0000261 OwningPtr<MCStreamer> Str;
Daniel Dunbar41b5b172010-05-20 17:49:16 +0000262
263 if (Opts.OutputType == AssemblerInvocation::FT_Asm) {
264 MCInstPrinter *IP =
265 TheTarget->createMCInstPrinter(Opts.OutputAsmVariant, *MAI);
Benjamin Kramer7ac3d5a2010-07-29 17:48:03 +0000266 MCCodeEmitter *CE = 0;
Daniel Dunbar41b5b172010-05-20 17:49:16 +0000267 if (Opts.ShowEncoding)
Benjamin Kramer7ac3d5a2010-07-29 17:48:03 +0000268 CE = TheTarget->createCodeEmitter(*TM, Ctx);
Daniel Dunbar41b5b172010-05-20 17:49:16 +0000269 Str.reset(createAsmStreamer(Ctx, *Out,TM->getTargetData()->isLittleEndian(),
Benjamin Kramer7ac3d5a2010-07-29 17:48:03 +0000270 /*asmverbose*/true, IP, CE, Opts.ShowInst));
Daniel Dunbar41b5b172010-05-20 17:49:16 +0000271 } else if (Opts.OutputType == AssemblerInvocation::FT_Null) {
272 Str.reset(createNullStreamer(Ctx));
273 } else {
274 assert(Opts.OutputType == AssemblerInvocation::FT_Obj &&
275 "Invalid file type!");
Benjamin Kramer7ac3d5a2010-07-29 17:48:03 +0000276 MCCodeEmitter *CE = TheTarget->createCodeEmitter(*TM, Ctx);
277 TargetAsmBackend *TAB = TheTarget->createAsmBackend(Opts.Triple);
278 Str.reset(TheTarget->createObjectStreamer(Opts.Triple, Ctx, *TAB, *Out,
279 CE, Opts.RelaxAll));
Rafael Espindola4f036fa2010-10-13 14:53:57 +0000280 Str.get()->InitSections();
Daniel Dunbar41b5b172010-05-20 17:49:16 +0000281 }
282
Daniel Dunbar7374f1b2010-07-17 02:26:21 +0000283 OwningPtr<MCAsmParser> Parser(createMCAsmParser(*TheTarget, SrcMgr, Ctx,
284 *Str.get(), *MAI));
Daniel Dunbare9122a32010-07-19 00:33:53 +0000285 OwningPtr<TargetAsmParser> TAP(TheTarget->createAsmParser(*Parser, *TM));
Daniel Dunbar41b5b172010-05-20 17:49:16 +0000286 if (!TAP) {
287 Diags.Report(diag::err_target_unknown_triple) << Opts.Triple;
288 return false;
289 }
290
Daniel Dunbar7374f1b2010-07-17 02:26:21 +0000291 Parser->setTargetParser(*TAP.get());
Daniel Dunbar41b5b172010-05-20 17:49:16 +0000292
Daniel Dunbar7374f1b2010-07-17 02:26:21 +0000293 bool Success = !Parser->Run(Opts.NoInitialTextSection);
Daniel Dunbar41b5b172010-05-20 17:49:16 +0000294
295 // Close the output.
296 delete Out;
297
298 // Delete output on errors.
299 if (!Success && Opts.OutputPath != "-")
300 sys::Path(Opts.OutputPath).eraseFromDisk();
301
302 return Success;
303}
304
305static void LLVMErrorHandler(void *UserData, const std::string &Message) {
306 Diagnostic &Diags = *static_cast<Diagnostic*>(UserData);
307
308 Diags.Report(diag::err_fe_error_backend) << Message;
309
310 // We cannot recover from llvm errors.
311 exit(1);
312}
313
314int cc1as_main(const char **ArgBegin, const char **ArgEnd,
315 const char *Argv0, void *MainAddr) {
316 // Print a stack trace if we signal out.
317 sys::PrintStackTraceOnErrorSignal();
318 PrettyStackTraceProgram X(ArgEnd - ArgBegin, ArgBegin);
319 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
320
321 // Initialize targets and assembly printers/parsers.
322 InitializeAllTargetInfos();
323 // FIXME: We shouldn't need to initialize the Target(Machine)s.
324 InitializeAllTargets();
325 InitializeAllAsmPrinters();
326 InitializeAllAsmParsers();
327
328 // Construct our diagnostic client.
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000329 TextDiagnosticPrinter *DiagClient
330 = new TextDiagnosticPrinter(errs(), DiagnosticOptions());
331 DiagClient->setPrefix("clang -cc1as");
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000332 llvm::IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
333 Diagnostic Diags(DiagID, DiagClient);
Daniel Dunbar41b5b172010-05-20 17:49:16 +0000334
335 // Set an error handler, so that any LLVM backend diagnostics go through our
336 // error handler.
Dan Gohman726578c2010-08-18 21:23:17 +0000337 ScopedFatalErrorHandler FatalErrorHandler
338 (LLVMErrorHandler, static_cast<void*>(&Diags));
Daniel Dunbar41b5b172010-05-20 17:49:16 +0000339
340 // Parse the arguments.
341 AssemblerInvocation Asm;
342 AssemblerInvocation::CreateFromArgs(Asm, ArgBegin, ArgEnd, Diags);
343
Daniel Dunbarc673af72010-05-20 18:15:20 +0000344 // Honor -help.
345 if (Asm.ShowHelp) {
346 llvm::OwningPtr<driver::OptTable> Opts(driver::createCC1AsOptTable());
347 Opts->PrintHelp(llvm::outs(), "clang -cc1as", "Clang Integrated Assembler");
348 return 0;
349 }
350
351 // Honor -version.
352 //
353 // FIXME: Use a better -version message?
354 if (Asm.ShowVersion) {
355 llvm::cl::PrintVersionMessage();
356 return 0;
357 }
358
359 // Honor -mllvm.
360 //
361 // FIXME: Remove this, one day.
362 if (!Asm.LLVMArgs.empty()) {
363 unsigned NumArgs = Asm.LLVMArgs.size();
364 const char **Args = new const char*[NumArgs + 2];
365 Args[0] = "clang (LLVM option parsing)";
366 for (unsigned i = 0; i != NumArgs; ++i)
367 Args[i + 1] = Asm.LLVMArgs[i].c_str();
368 Args[NumArgs + 1] = 0;
369 llvm::cl::ParseCommandLineOptions(NumArgs + 1, const_cast<char **>(Args));
370 }
371
Daniel Dunbar41b5b172010-05-20 17:49:16 +0000372 // Execute the invocation, unless there were parsing errors.
373 bool Success = false;
Argyrios Kyrtzidise8f0ba72010-11-19 00:19:18 +0000374 if (!Diags.hasErrorOccurred())
Daniel Dunbar41b5b172010-05-20 17:49:16 +0000375 Success = ExecuteAssembler(Asm, Diags);
376
377 // If any timers were active but haven't been destroyed yet, print their
378 // results now.
379 TimerGroup::printAll(errs());
380
381 return !Success;
382}