blob: 5f1ee092ba4f5534f721fc7595b7291574f29730 [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"
27#include "llvm/MC/MCParser/AsmParser.h"
28#include "llvm/MC/MCCodeEmitter.h"
29#include "llvm/MC/MCContext.h"
30#include "llvm/MC/MCStreamer.h"
Daniel Dunbarc673af72010-05-20 18:15:20 +000031#include "llvm/Support/CommandLine.h"
Daniel Dunbar41b5b172010-05-20 17:49:16 +000032#include "llvm/Support/FormattedStream.h"
33#include "llvm/Support/ErrorHandling.h"
34#include "llvm/Support/ManagedStatic.h"
35#include "llvm/Support/MemoryBuffer.h"
36#include "llvm/Support/PrettyStackTrace.h"
37#include "llvm/Support/SourceMgr.h"
38#include "llvm/Support/Timer.h"
39#include "llvm/Support/raw_ostream.h"
40#include "llvm/System/Host.h"
41#include "llvm/System/Path.h"
42#include "llvm/System/Signals.h"
43#include "llvm/Target/TargetAsmBackend.h"
44#include "llvm/Target/TargetAsmParser.h"
45#include "llvm/Target/TargetData.h"
46#include "llvm/Target/TargetMachine.h"
47#include "llvm/Target/TargetRegistry.h"
48#include "llvm/Target/TargetSelect.h"
49using namespace clang;
50using namespace clang::driver;
51using namespace llvm;
52
53namespace {
54
55/// \brief Helper class for representing a single invocation of the assembler.
56struct AssemblerInvocation {
57 /// @name Target Options
58 /// @{
59
60 std::string Triple;
61
62 /// @}
63 /// @name Language Options
64 /// @{
65
66 std::vector<std::string> IncludePaths;
67 unsigned NoInitialTextSection : 1;
68
69 /// @}
70 /// @name Frontend Options
71 /// @{
72
73 std::string InputFile;
Daniel Dunbarc673af72010-05-20 18:15:20 +000074 std::vector<std::string> LLVMArgs;
Daniel Dunbar41b5b172010-05-20 17:49:16 +000075 std::string OutputPath;
76 enum FileType {
77 FT_Asm, ///< Assembly (.s) output, transliterate mode.
78 FT_Null, ///< No output, for timing purposes.
79 FT_Obj ///< Object file output.
80 };
81 FileType OutputType;
Daniel Dunbarc673af72010-05-20 18:15:20 +000082 unsigned ShowHelp : 1;
83 unsigned ShowVersion : 1;
Daniel Dunbar41b5b172010-05-20 17:49:16 +000084
85 /// @}
86 /// @name Transliterate Options
87 /// @{
88
89 unsigned OutputAsmVariant;
90 unsigned ShowEncoding : 1;
91 unsigned ShowInst : 1;
92
93 /// @}
94 /// @name Assembler Options
95 /// @{
96
97 unsigned RelaxAll : 1;
98
99 /// @}
100
101public:
102 AssemblerInvocation() {
103 Triple = "";
104 NoInitialTextSection = 0;
105 InputFile = "-";
Daniel Dunbarc673af72010-05-20 18:15:20 +0000106 OutputPath = "-";
Daniel Dunbar41b5b172010-05-20 17:49:16 +0000107 OutputType = FT_Asm;
108 OutputAsmVariant = 0;
109 ShowInst = 0;
110 ShowEncoding = 0;
111 RelaxAll = 0;
112 }
113
114 static void CreateFromArgs(AssemblerInvocation &Res, const char **ArgBegin,
115 const char **ArgEnd, Diagnostic &Diags);
116};
117
118}
119
120void AssemblerInvocation::CreateFromArgs(AssemblerInvocation &Opts,
121 const char **ArgBegin,
122 const char **ArgEnd,
123 Diagnostic &Diags) {
124 using namespace clang::driver::cc1asoptions;
125 // Parse the arguments.
126 OwningPtr<OptTable> OptTbl(createCC1AsOptTable());
127 unsigned MissingArgIndex, MissingArgCount;
128 OwningPtr<InputArgList> Args(
129 OptTbl->ParseArgs(ArgBegin, ArgEnd,MissingArgIndex, MissingArgCount));
130
131 // Check for missing argument error.
132 if (MissingArgCount)
133 Diags.Report(diag::err_drv_missing_argument)
134 << Args->getArgString(MissingArgIndex) << MissingArgCount;
135
136 // Issue errors on unknown arguments.
137 for (arg_iterator it = Args->filtered_begin(cc1asoptions::OPT_UNKNOWN),
138 ie = Args->filtered_end(); it != ie; ++it)
139 Diags.Report(diag::err_drv_unknown_argument) << it->getAsString(*Args);
140
141 // Construct the invocation.
142
143 // Target Options
144 Opts.Triple = Args->getLastArgValue(OPT_triple);
145 if (Opts.Triple.empty()) // Use the host triple if unspecified.
146 Opts.Triple = sys::getHostTriple();
147
148 // Language Options
149 Opts.IncludePaths = Args->getAllArgValues(OPT_I);
150 Opts.NoInitialTextSection = Args->hasArg(OPT_n);
151
152 // Frontend Options
153 if (Args->hasArg(OPT_INPUT)) {
154 bool First = true;
155 for (arg_iterator it = Args->filtered_begin(OPT_INPUT),
156 ie = Args->filtered_end(); it != ie; ++it, First=false) {
157 if (First)
158 Opts.InputFile = it->getValue(*Args);
159 else
160 Diags.Report(diag::err_drv_unknown_argument) << it->getAsString(*Args);
161 }
162 }
Daniel Dunbarc673af72010-05-20 18:15:20 +0000163 Opts.LLVMArgs = Args->getAllArgValues(OPT_mllvm);
Daniel Dunbar41b5b172010-05-20 17:49:16 +0000164 Opts.OutputPath = Args->getLastArgValue(OPT_o);
165 if (Arg *A = Args->getLastArg(OPT_filetype)) {
166 StringRef Name = A->getValue(*Args);
167 unsigned OutputType = StringSwitch<unsigned>(Name)
168 .Case("asm", FT_Asm)
169 .Case("null", FT_Null)
170 .Case("obj", FT_Obj)
171 .Default(~0U);
172 if (OutputType == ~0U)
173 Diags.Report(diag::err_drv_invalid_value)
174 << A->getAsString(*Args) << Name;
175 else
176 Opts.OutputType = FileType(OutputType);
177 }
Daniel Dunbarc673af72010-05-20 18:15:20 +0000178 Opts.ShowHelp = Args->hasArg(OPT_help);
179 Opts.ShowVersion = Args->hasArg(OPT_version);
Daniel Dunbar41b5b172010-05-20 17:49:16 +0000180
181 // Transliterate Options
182 Opts.OutputAsmVariant = Args->getLastArgIntValue(OPT_output_asm_variant,
183 0, Diags);
184 Opts.ShowEncoding = Args->hasArg(OPT_show_encoding);
185 Opts.ShowInst = Args->hasArg(OPT_show_inst);
186
187 // Assemble Options
188 Opts.RelaxAll = Args->hasArg(OPT_relax_all);
189}
190
191static formatted_raw_ostream *GetOutputStream(AssemblerInvocation &Opts,
192 Diagnostic &Diags,
193 bool Binary) {
Daniel Dunbarc673af72010-05-20 18:15:20 +0000194 if (Opts.OutputPath.empty())
195 Opts.OutputPath = "-";
196
Daniel Dunbar41b5b172010-05-20 17:49:16 +0000197 // Make sure that the Out file gets unlinked from the disk if we get a
198 // SIGINT.
199 if (Opts.OutputPath != "-")
200 sys::RemoveFileOnSignal(sys::Path(Opts.OutputPath));
201
202 std::string Error;
203 raw_fd_ostream *Out =
204 new raw_fd_ostream(Opts.OutputPath.c_str(), Error,
205 (Binary ? raw_fd_ostream::F_Binary : 0));
206 if (!Error.empty()) {
207 Diags.Report(diag::err_fe_unable_to_open_output)
208 << Opts.OutputPath << Error;
209 return 0;
210 }
211
212 return new formatted_raw_ostream(*Out, formatted_raw_ostream::DELETE_STREAM);
213}
214
215static bool ExecuteAssembler(AssemblerInvocation &Opts, Diagnostic &Diags) {
216 // Get the target specific parser.
217 std::string Error;
218 const Target *TheTarget(TargetRegistry::lookupTarget(Opts.Triple, Error));
219 if (!TheTarget) {
220 Diags.Report(diag::err_target_unknown_triple) << Opts.Triple;
221 return false;
222 }
223
224 MemoryBuffer *Buffer = MemoryBuffer::getFileOrSTDIN(Opts.InputFile, &Error);
225 if (Buffer == 0) {
226 Diags.Report(diag::err_fe_error_reading) << Opts.InputFile;
227 return false;
228 }
229
230 SourceMgr SrcMgr;
231
232 // Tell SrcMgr about this buffer, which is what the parser will pick up.
233 SrcMgr.AddNewSourceBuffer(Buffer, SMLoc());
234
235 // Record the location of the include directories so that the lexer can find
236 // it later.
237 SrcMgr.setIncludeDirs(Opts.IncludePaths);
238
239 OwningPtr<MCAsmInfo> MAI(TheTarget->createAsmInfo(Opts.Triple));
240 assert(MAI && "Unable to create target asm info!");
241
242 MCContext Ctx(*MAI);
243 bool IsBinary = Opts.OutputType == AssemblerInvocation::FT_Obj;
244 formatted_raw_ostream *Out = GetOutputStream(Opts, Diags, IsBinary);
245 if (!Out)
246 return false;
247
248 // FIXME: We shouldn't need to do this (and link in codegen).
249 OwningPtr<TargetMachine> TM(TheTarget->createTargetMachine(Opts.Triple, ""));
250 if (!TM) {
251 Diags.Report(diag::err_target_unknown_triple) << Opts.Triple;
252 return false;
253 }
254
255 OwningPtr<MCCodeEmitter> CE;
256 OwningPtr<MCStreamer> Str;
257 OwningPtr<TargetAsmBackend> TAB;
258
259 if (Opts.OutputType == AssemblerInvocation::FT_Asm) {
260 MCInstPrinter *IP =
261 TheTarget->createMCInstPrinter(Opts.OutputAsmVariant, *MAI);
262 if (Opts.ShowEncoding)
263 CE.reset(TheTarget->createCodeEmitter(*TM, Ctx));
264 Str.reset(createAsmStreamer(Ctx, *Out,TM->getTargetData()->isLittleEndian(),
265 /*asmverbose*/true, IP, CE.get(),
266 Opts.ShowInst));
267 } else if (Opts.OutputType == AssemblerInvocation::FT_Null) {
268 Str.reset(createNullStreamer(Ctx));
269 } else {
270 assert(Opts.OutputType == AssemblerInvocation::FT_Obj &&
271 "Invalid file type!");
272 CE.reset(TheTarget->createCodeEmitter(*TM, Ctx));
273 TAB.reset(TheTarget->createAsmBackend(Opts.Triple));
274 Str.reset(createMachOStreamer(Ctx, *TAB, *Out, CE.get(), Opts.RelaxAll));
275 }
276
277 AsmParser Parser(SrcMgr, Ctx, *Str.get(), *MAI);
278 OwningPtr<TargetAsmParser> TAP(TheTarget->createAsmParser(Parser));
279 if (!TAP) {
280 Diags.Report(diag::err_target_unknown_triple) << Opts.Triple;
281 return false;
282 }
283
284 Parser.setTargetParser(*TAP.get());
285
286 bool Success = !Parser.Run(Opts.NoInitialTextSection);
287
288 // Close the output.
289 delete Out;
290
291 // Delete output on errors.
292 if (!Success && Opts.OutputPath != "-")
293 sys::Path(Opts.OutputPath).eraseFromDisk();
294
295 return Success;
296}
297
298static void LLVMErrorHandler(void *UserData, const std::string &Message) {
299 Diagnostic &Diags = *static_cast<Diagnostic*>(UserData);
300
301 Diags.Report(diag::err_fe_error_backend) << Message;
302
303 // We cannot recover from llvm errors.
304 exit(1);
305}
306
307int cc1as_main(const char **ArgBegin, const char **ArgEnd,
308 const char *Argv0, void *MainAddr) {
309 // Print a stack trace if we signal out.
310 sys::PrintStackTraceOnErrorSignal();
311 PrettyStackTraceProgram X(ArgEnd - ArgBegin, ArgBegin);
312 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
313
314 // Initialize targets and assembly printers/parsers.
315 InitializeAllTargetInfos();
316 // FIXME: We shouldn't need to initialize the Target(Machine)s.
317 InitializeAllTargets();
318 InitializeAllAsmPrinters();
319 InitializeAllAsmParsers();
320
321 // Construct our diagnostic client.
322 TextDiagnosticPrinter DiagClient(errs(), DiagnosticOptions());
323 DiagClient.setPrefix("clang -cc1as");
324 Diagnostic Diags(&DiagClient);
325
326 // Set an error handler, so that any LLVM backend diagnostics go through our
327 // error handler.
328 install_fatal_error_handler(LLVMErrorHandler,
329 static_cast<void*>(&Diags));
330
331 // Parse the arguments.
332 AssemblerInvocation Asm;
333 AssemblerInvocation::CreateFromArgs(Asm, ArgBegin, ArgEnd, Diags);
334
Daniel Dunbarc673af72010-05-20 18:15:20 +0000335 // Honor -help.
336 if (Asm.ShowHelp) {
337 llvm::OwningPtr<driver::OptTable> Opts(driver::createCC1AsOptTable());
338 Opts->PrintHelp(llvm::outs(), "clang -cc1as", "Clang Integrated Assembler");
339 return 0;
340 }
341
342 // Honor -version.
343 //
344 // FIXME: Use a better -version message?
345 if (Asm.ShowVersion) {
346 llvm::cl::PrintVersionMessage();
347 return 0;
348 }
349
350 // Honor -mllvm.
351 //
352 // FIXME: Remove this, one day.
353 if (!Asm.LLVMArgs.empty()) {
354 unsigned NumArgs = Asm.LLVMArgs.size();
355 const char **Args = new const char*[NumArgs + 2];
356 Args[0] = "clang (LLVM option parsing)";
357 for (unsigned i = 0; i != NumArgs; ++i)
358 Args[i + 1] = Asm.LLVMArgs[i].c_str();
359 Args[NumArgs + 1] = 0;
360 llvm::cl::ParseCommandLineOptions(NumArgs + 1, const_cast<char **>(Args));
361 }
362
Daniel Dunbar41b5b172010-05-20 17:49:16 +0000363 // Execute the invocation, unless there were parsing errors.
364 bool Success = false;
365 if (!Diags.getNumErrors())
366 Success = ExecuteAssembler(Asm, Diags);
367
368 // If any timers were active but haven't been destroyed yet, print their
369 // results now.
370 TimerGroup::printAll(errs());
371
372 return !Success;
373}