blob: d352a6c41f0837a2eac89e6a43677879d2ec0a15 [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"
Rafael Espindola7872d482010-12-10 07:40:14 +000047#include "llvm/Target/TargetAsmInfo.h"
Daniel Dunbar41b5b172010-05-20 17:49:16 +000048#include "llvm/Target/TargetAsmParser.h"
49#include "llvm/Target/TargetData.h"
Rafael Espindola7872d482010-12-10 07:40:14 +000050#include "llvm/Target/TargetLowering.h"
51#include "llvm/Target/TargetLoweringObjectFile.h"
Daniel Dunbar41b5b172010-05-20 17:49:16 +000052#include "llvm/Target/TargetMachine.h"
53#include "llvm/Target/TargetRegistry.h"
54#include "llvm/Target/TargetSelect.h"
55using namespace clang;
56using namespace clang::driver;
57using namespace llvm;
58
59namespace {
60
61/// \brief Helper class for representing a single invocation of the assembler.
62struct AssemblerInvocation {
63 /// @name Target Options
64 /// @{
65
66 std::string Triple;
67
68 /// @}
69 /// @name Language Options
70 /// @{
71
72 std::vector<std::string> IncludePaths;
73 unsigned NoInitialTextSection : 1;
74
75 /// @}
76 /// @name Frontend Options
77 /// @{
78
79 std::string InputFile;
Daniel Dunbarc673af72010-05-20 18:15:20 +000080 std::vector<std::string> LLVMArgs;
Daniel Dunbar41b5b172010-05-20 17:49:16 +000081 std::string OutputPath;
82 enum FileType {
83 FT_Asm, ///< Assembly (.s) output, transliterate mode.
84 FT_Null, ///< No output, for timing purposes.
85 FT_Obj ///< Object file output.
86 };
87 FileType OutputType;
Daniel Dunbarc673af72010-05-20 18:15:20 +000088 unsigned ShowHelp : 1;
89 unsigned ShowVersion : 1;
Daniel Dunbar41b5b172010-05-20 17:49:16 +000090
91 /// @}
92 /// @name Transliterate Options
93 /// @{
94
95 unsigned OutputAsmVariant;
96 unsigned ShowEncoding : 1;
97 unsigned ShowInst : 1;
98
99 /// @}
100 /// @name Assembler Options
101 /// @{
102
103 unsigned RelaxAll : 1;
104
105 /// @}
106
107public:
108 AssemblerInvocation() {
109 Triple = "";
110 NoInitialTextSection = 0;
111 InputFile = "-";
Daniel Dunbarc673af72010-05-20 18:15:20 +0000112 OutputPath = "-";
Daniel Dunbar41b5b172010-05-20 17:49:16 +0000113 OutputType = FT_Asm;
114 OutputAsmVariant = 0;
115 ShowInst = 0;
116 ShowEncoding = 0;
117 RelaxAll = 0;
118 }
119
120 static void CreateFromArgs(AssemblerInvocation &Res, const char **ArgBegin,
121 const char **ArgEnd, Diagnostic &Diags);
122};
123
124}
125
126void AssemblerInvocation::CreateFromArgs(AssemblerInvocation &Opts,
127 const char **ArgBegin,
128 const char **ArgEnd,
129 Diagnostic &Diags) {
130 using namespace clang::driver::cc1asoptions;
131 // Parse the arguments.
132 OwningPtr<OptTable> OptTbl(createCC1AsOptTable());
133 unsigned MissingArgIndex, MissingArgCount;
134 OwningPtr<InputArgList> Args(
135 OptTbl->ParseArgs(ArgBegin, ArgEnd,MissingArgIndex, MissingArgCount));
136
137 // Check for missing argument error.
138 if (MissingArgCount)
139 Diags.Report(diag::err_drv_missing_argument)
140 << Args->getArgString(MissingArgIndex) << MissingArgCount;
141
142 // Issue errors on unknown arguments.
143 for (arg_iterator it = Args->filtered_begin(cc1asoptions::OPT_UNKNOWN),
144 ie = Args->filtered_end(); it != ie; ++it)
Daniel Dunbar7e4953e2010-06-11 22:00:13 +0000145 Diags.Report(diag::err_drv_unknown_argument) << (*it) ->getAsString(*Args);
Daniel Dunbar41b5b172010-05-20 17:49:16 +0000146
147 // Construct the invocation.
148
149 // Target Options
Duncan Sands2dc14532010-08-30 09:42:39 +0000150 Opts.Triple = Triple::normalize(Args->getLastArgValue(OPT_triple));
Daniel Dunbar41b5b172010-05-20 17:49:16 +0000151 if (Opts.Triple.empty()) // Use the host triple if unspecified.
152 Opts.Triple = sys::getHostTriple();
153
154 // Language Options
155 Opts.IncludePaths = Args->getAllArgValues(OPT_I);
156 Opts.NoInitialTextSection = Args->hasArg(OPT_n);
157
158 // Frontend Options
159 if (Args->hasArg(OPT_INPUT)) {
160 bool First = true;
161 for (arg_iterator it = Args->filtered_begin(OPT_INPUT),
162 ie = Args->filtered_end(); it != ie; ++it, First=false) {
Daniel Dunbar7e4953e2010-06-11 22:00:13 +0000163 const Arg *A = it;
Daniel Dunbar41b5b172010-05-20 17:49:16 +0000164 if (First)
Daniel Dunbar7e4953e2010-06-11 22:00:13 +0000165 Opts.InputFile = A->getValue(*Args);
Daniel Dunbar41b5b172010-05-20 17:49:16 +0000166 else
Daniel Dunbar7e4953e2010-06-11 22:00:13 +0000167 Diags.Report(diag::err_drv_unknown_argument) << A->getAsString(*Args);
Daniel Dunbar41b5b172010-05-20 17:49:16 +0000168 }
169 }
Daniel Dunbarc673af72010-05-20 18:15:20 +0000170 Opts.LLVMArgs = Args->getAllArgValues(OPT_mllvm);
Daniel Dunbar41b5b172010-05-20 17:49:16 +0000171 Opts.OutputPath = Args->getLastArgValue(OPT_o);
172 if (Arg *A = Args->getLastArg(OPT_filetype)) {
173 StringRef Name = A->getValue(*Args);
174 unsigned OutputType = StringSwitch<unsigned>(Name)
175 .Case("asm", FT_Asm)
176 .Case("null", FT_Null)
177 .Case("obj", FT_Obj)
178 .Default(~0U);
179 if (OutputType == ~0U)
180 Diags.Report(diag::err_drv_invalid_value)
181 << A->getAsString(*Args) << Name;
182 else
183 Opts.OutputType = FileType(OutputType);
184 }
Daniel Dunbarc673af72010-05-20 18:15:20 +0000185 Opts.ShowHelp = Args->hasArg(OPT_help);
186 Opts.ShowVersion = Args->hasArg(OPT_version);
Daniel Dunbar41b5b172010-05-20 17:49:16 +0000187
188 // Transliterate Options
189 Opts.OutputAsmVariant = Args->getLastArgIntValue(OPT_output_asm_variant,
190 0, Diags);
191 Opts.ShowEncoding = Args->hasArg(OPT_show_encoding);
192 Opts.ShowInst = Args->hasArg(OPT_show_inst);
193
194 // Assemble Options
195 Opts.RelaxAll = Args->hasArg(OPT_relax_all);
196}
197
198static formatted_raw_ostream *GetOutputStream(AssemblerInvocation &Opts,
199 Diagnostic &Diags,
200 bool Binary) {
Daniel Dunbarc673af72010-05-20 18:15:20 +0000201 if (Opts.OutputPath.empty())
202 Opts.OutputPath = "-";
203
Daniel Dunbar41b5b172010-05-20 17:49:16 +0000204 // Make sure that the Out file gets unlinked from the disk if we get a
205 // SIGINT.
206 if (Opts.OutputPath != "-")
207 sys::RemoveFileOnSignal(sys::Path(Opts.OutputPath));
208
209 std::string Error;
210 raw_fd_ostream *Out =
211 new raw_fd_ostream(Opts.OutputPath.c_str(), Error,
212 (Binary ? raw_fd_ostream::F_Binary : 0));
213 if (!Error.empty()) {
214 Diags.Report(diag::err_fe_unable_to_open_output)
215 << Opts.OutputPath << Error;
216 return 0;
217 }
218
219 return new formatted_raw_ostream(*Out, formatted_raw_ostream::DELETE_STREAM);
220}
221
222static bool ExecuteAssembler(AssemblerInvocation &Opts, Diagnostic &Diags) {
223 // Get the target specific parser.
224 std::string Error;
225 const Target *TheTarget(TargetRegistry::lookupTarget(Opts.Triple, Error));
226 if (!TheTarget) {
227 Diags.Report(diag::err_target_unknown_triple) << Opts.Triple;
228 return false;
229 }
230
Michael J. Spencer3a321e22010-12-09 17:36:38 +0000231 error_code ec;
232 MemoryBuffer *Buffer = MemoryBuffer::getFileOrSTDIN(Opts.InputFile, ec);
Daniel Dunbar41b5b172010-05-20 17:49:16 +0000233 if (Buffer == 0) {
Michael J. Spencer3a321e22010-12-09 17:36:38 +0000234 Error = ec.message();
Daniel Dunbar41b5b172010-05-20 17:49:16 +0000235 Diags.Report(diag::err_fe_error_reading) << Opts.InputFile;
236 return false;
237 }
238
239 SourceMgr SrcMgr;
240
241 // Tell SrcMgr about this buffer, which is what the parser will pick up.
242 SrcMgr.AddNewSourceBuffer(Buffer, SMLoc());
243
244 // Record the location of the include directories so that the lexer can find
245 // it later.
246 SrcMgr.setIncludeDirs(Opts.IncludePaths);
247
248 OwningPtr<MCAsmInfo> MAI(TheTarget->createAsmInfo(Opts.Triple));
249 assert(MAI && "Unable to create target asm info!");
250
Daniel Dunbar41b5b172010-05-20 17:49:16 +0000251 bool IsBinary = Opts.OutputType == AssemblerInvocation::FT_Obj;
252 formatted_raw_ostream *Out = GetOutputStream(Opts, Diags, IsBinary);
253 if (!Out)
254 return false;
255
256 // FIXME: We shouldn't need to do this (and link in codegen).
257 OwningPtr<TargetMachine> TM(TheTarget->createTargetMachine(Opts.Triple, ""));
258 if (!TM) {
259 Diags.Report(diag::err_target_unknown_triple) << Opts.Triple;
260 return false;
261 }
262
Rafael Espindola7872d482010-12-10 07:40:14 +0000263 const TargetAsmInfo *tai = new TargetAsmInfo(*TM);
264 MCContext Ctx(*MAI, tai);
265
Daniel Dunbar41b5b172010-05-20 17:49:16 +0000266 OwningPtr<MCStreamer> Str;
Daniel Dunbar41b5b172010-05-20 17:49:16 +0000267
Rafael Espindola7872d482010-12-10 07:40:14 +0000268 const TargetLoweringObjectFile &TLOF =
269 TM->getTargetLowering()->getObjFileLowering();
270 const_cast<TargetLoweringObjectFile&>(TLOF).Initialize(Ctx, *TM);
271
272
Daniel Dunbar41b5b172010-05-20 17:49:16 +0000273 if (Opts.OutputType == AssemblerInvocation::FT_Asm) {
274 MCInstPrinter *IP =
275 TheTarget->createMCInstPrinter(Opts.OutputAsmVariant, *MAI);
Benjamin Kramer7ac3d5a2010-07-29 17:48:03 +0000276 MCCodeEmitter *CE = 0;
Daniel Dunbar41b5b172010-05-20 17:49:16 +0000277 if (Opts.ShowEncoding)
Benjamin Kramer7ac3d5a2010-07-29 17:48:03 +0000278 CE = TheTarget->createCodeEmitter(*TM, Ctx);
Rafael Espindola7872d482010-12-10 07:40:14 +0000279 Str.reset(TheTarget->createAsmStreamer(Ctx, *Out, /*asmverbose*/true,
280 /*useLoc*/ true, IP, CE,
281 Opts.ShowInst));
Daniel Dunbar41b5b172010-05-20 17:49:16 +0000282 } else if (Opts.OutputType == AssemblerInvocation::FT_Null) {
283 Str.reset(createNullStreamer(Ctx));
284 } else {
285 assert(Opts.OutputType == AssemblerInvocation::FT_Obj &&
286 "Invalid file type!");
Benjamin Kramer7ac3d5a2010-07-29 17:48:03 +0000287 MCCodeEmitter *CE = TheTarget->createCodeEmitter(*TM, Ctx);
288 TargetAsmBackend *TAB = TheTarget->createAsmBackend(Opts.Triple);
289 Str.reset(TheTarget->createObjectStreamer(Opts.Triple, Ctx, *TAB, *Out,
290 CE, Opts.RelaxAll));
Rafael Espindola4f036fa2010-10-13 14:53:57 +0000291 Str.get()->InitSections();
Daniel Dunbar41b5b172010-05-20 17:49:16 +0000292 }
293
Daniel Dunbar7374f1b2010-07-17 02:26:21 +0000294 OwningPtr<MCAsmParser> Parser(createMCAsmParser(*TheTarget, SrcMgr, Ctx,
295 *Str.get(), *MAI));
Daniel Dunbare9122a32010-07-19 00:33:53 +0000296 OwningPtr<TargetAsmParser> TAP(TheTarget->createAsmParser(*Parser, *TM));
Daniel Dunbar41b5b172010-05-20 17:49:16 +0000297 if (!TAP) {
298 Diags.Report(diag::err_target_unknown_triple) << Opts.Triple;
299 return false;
300 }
301
Daniel Dunbar7374f1b2010-07-17 02:26:21 +0000302 Parser->setTargetParser(*TAP.get());
Daniel Dunbar41b5b172010-05-20 17:49:16 +0000303
Daniel Dunbar7374f1b2010-07-17 02:26:21 +0000304 bool Success = !Parser->Run(Opts.NoInitialTextSection);
Daniel Dunbar41b5b172010-05-20 17:49:16 +0000305
306 // Close the output.
307 delete Out;
308
309 // Delete output on errors.
310 if (!Success && Opts.OutputPath != "-")
311 sys::Path(Opts.OutputPath).eraseFromDisk();
312
313 return Success;
314}
315
316static void LLVMErrorHandler(void *UserData, const std::string &Message) {
317 Diagnostic &Diags = *static_cast<Diagnostic*>(UserData);
318
319 Diags.Report(diag::err_fe_error_backend) << Message;
320
321 // We cannot recover from llvm errors.
322 exit(1);
323}
324
325int cc1as_main(const char **ArgBegin, const char **ArgEnd,
326 const char *Argv0, void *MainAddr) {
327 // Print a stack trace if we signal out.
328 sys::PrintStackTraceOnErrorSignal();
329 PrettyStackTraceProgram X(ArgEnd - ArgBegin, ArgBegin);
330 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
331
332 // Initialize targets and assembly printers/parsers.
333 InitializeAllTargetInfos();
334 // FIXME: We shouldn't need to initialize the Target(Machine)s.
335 InitializeAllTargets();
336 InitializeAllAsmPrinters();
337 InitializeAllAsmParsers();
338
339 // Construct our diagnostic client.
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000340 TextDiagnosticPrinter *DiagClient
341 = new TextDiagnosticPrinter(errs(), DiagnosticOptions());
342 DiagClient->setPrefix("clang -cc1as");
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000343 llvm::IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
344 Diagnostic Diags(DiagID, DiagClient);
Daniel Dunbar41b5b172010-05-20 17:49:16 +0000345
346 // Set an error handler, so that any LLVM backend diagnostics go through our
347 // error handler.
Dan Gohman726578c2010-08-18 21:23:17 +0000348 ScopedFatalErrorHandler FatalErrorHandler
349 (LLVMErrorHandler, static_cast<void*>(&Diags));
Daniel Dunbar41b5b172010-05-20 17:49:16 +0000350
351 // Parse the arguments.
352 AssemblerInvocation Asm;
353 AssemblerInvocation::CreateFromArgs(Asm, ArgBegin, ArgEnd, Diags);
354
Daniel Dunbarc673af72010-05-20 18:15:20 +0000355 // Honor -help.
356 if (Asm.ShowHelp) {
357 llvm::OwningPtr<driver::OptTable> Opts(driver::createCC1AsOptTable());
358 Opts->PrintHelp(llvm::outs(), "clang -cc1as", "Clang Integrated Assembler");
359 return 0;
360 }
361
362 // Honor -version.
363 //
364 // FIXME: Use a better -version message?
365 if (Asm.ShowVersion) {
366 llvm::cl::PrintVersionMessage();
367 return 0;
368 }
369
370 // Honor -mllvm.
371 //
372 // FIXME: Remove this, one day.
373 if (!Asm.LLVMArgs.empty()) {
374 unsigned NumArgs = Asm.LLVMArgs.size();
375 const char **Args = new const char*[NumArgs + 2];
376 Args[0] = "clang (LLVM option parsing)";
377 for (unsigned i = 0; i != NumArgs; ++i)
378 Args[i + 1] = Asm.LLVMArgs[i].c_str();
379 Args[NumArgs + 1] = 0;
380 llvm::cl::ParseCommandLineOptions(NumArgs + 1, const_cast<char **>(Args));
381 }
382
Daniel Dunbar41b5b172010-05-20 17:49:16 +0000383 // Execute the invocation, unless there were parsing errors.
384 bool Success = false;
Argyrios Kyrtzidise8f0ba72010-11-19 00:19:18 +0000385 if (!Diags.hasErrorOccurred())
Daniel Dunbar41b5b172010-05-20 17:49:16 +0000386 Success = ExecuteAssembler(Asm, Diags);
387
388 // If any timers were active but haven't been destroyed yet, print their
389 // results now.
390 TimerGroup::printAll(errs());
391
392 return !Success;
393}