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