Change raw_fd_ostream to take flags as an optional bitmask
[oota-llvm.git] / tools / llvm-mc / llvm-mc.cpp
1 //===-- llvm-mc.cpp - Machine Code Hacking Driver -------------------------===//
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 utility is a simple driver that allows command line hacking on machine
11 // code.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "llvm/MC/MCContext.h"
16 #include "llvm/MC/MCSectionMachO.h"
17 #include "llvm/MC/MCStreamer.h"
18 #include "llvm/ADT/OwningPtr.h"
19 #include "llvm/CodeGen/AsmPrinter.h"
20 #include "llvm/Support/CommandLine.h"
21 #include "llvm/Support/FormattedStream.h"
22 #include "llvm/Support/ManagedStatic.h"
23 #include "llvm/Support/MemoryBuffer.h"
24 #include "llvm/Support/PrettyStackTrace.h"
25 #include "llvm/Support/SourceMgr.h"
26 #include "llvm/Support/raw_ostream.h"
27 #include "llvm/System/Signals.h"
28 #include "llvm/Target/TargetAsmParser.h"
29 #include "llvm/Target/TargetRegistry.h"
30 #include "llvm/Target/TargetSelect.h"
31 #include "AsmParser.h"
32 using namespace llvm;
33
34 static cl::opt<std::string>
35 InputFilename(cl::Positional, cl::desc("<input file>"), cl::init("-"));
36
37 static cl::opt<std::string>
38 OutputFilename("o", cl::desc("Output filename"),
39                cl::value_desc("filename"));
40
41 enum OutputFileType {
42   OFT_AssemblyFile,
43   OFT_ObjectFile
44 };
45 static cl::opt<OutputFileType>
46 FileType("filetype", cl::init(OFT_AssemblyFile),
47   cl::desc("Choose an output file type:"),
48   cl::values(
49        clEnumValN(OFT_AssemblyFile, "asm",
50                   "Emit an assembly ('.s') file"),
51        clEnumValN(OFT_ObjectFile, "obj",
52                   "Emit a native object ('.o') file"),
53        clEnumValEnd));
54
55 static cl::opt<bool>
56 Force("f", cl::desc("Overwrite output files"));
57
58 static cl::list<std::string>
59 IncludeDirs("I", cl::desc("Directory of include files"),
60             cl::value_desc("directory"), cl::Prefix);
61
62 static cl::opt<std::string>
63 TripleName("triple", cl::desc("Target triple to assemble for,"
64                           "see -version for available targets"),
65        cl::init(LLVM_HOSTTRIPLE));
66
67 enum ActionType {
68   AC_AsLex,
69   AC_Assemble
70 };
71
72 static cl::opt<ActionType>
73 Action(cl::desc("Action to perform:"),
74        cl::init(AC_Assemble),
75        cl::values(clEnumValN(AC_AsLex, "as-lex",
76                              "Lex tokens from a .s file"),
77                   clEnumValN(AC_Assemble, "assemble",
78                              "Assemble a .s file (default)"),
79                   clEnumValEnd));
80
81 static int AsLexInput(const char *ProgName) {
82   std::string ErrorMessage;
83   MemoryBuffer *Buffer = MemoryBuffer::getFileOrSTDIN(InputFilename,
84                                                       &ErrorMessage);
85   if (Buffer == 0) {
86     errs() << ProgName << ": ";
87     if (ErrorMessage.size())
88       errs() << ErrorMessage << "\n";
89     else
90       errs() << "input file didn't read correctly.\n";
91     return 1;
92   }
93
94   SourceMgr SrcMgr;
95   
96   // Tell SrcMgr about this buffer, which is what TGParser will pick up.
97   SrcMgr.AddNewSourceBuffer(Buffer, SMLoc());
98   
99   // Record the location of the include directories so that the lexer can find
100   // it later.
101   SrcMgr.setIncludeDirs(IncludeDirs);
102
103   AsmLexer Lexer(SrcMgr);
104   
105   bool Error = false;
106   
107   while (Lexer.Lex().isNot(AsmToken::Eof)) {
108     switch (Lexer.getKind()) {
109     default:
110       Lexer.PrintMessage(Lexer.getLoc(), "unknown token", "warning");
111       Error = true;
112       break;
113     case AsmToken::Error:
114       Error = true; // error already printed.
115       break;
116     case AsmToken::Identifier:
117       outs() << "identifier: " << Lexer.getTok().getString() << '\n';
118       break;
119     case AsmToken::Register:
120       outs() << "register: " << Lexer.getTok().getString() << '\n';
121       break;
122     case AsmToken::String:
123       outs() << "string: " << Lexer.getTok().getString() << '\n';
124       break;
125     case AsmToken::Integer:
126       outs() << "int: " << Lexer.getTok().getString() << '\n';
127       break;
128
129     case AsmToken::Amp:            outs() << "Amp\n"; break;
130     case AsmToken::AmpAmp:         outs() << "AmpAmp\n"; break;
131     case AsmToken::Caret:          outs() << "Caret\n"; break;
132     case AsmToken::Colon:          outs() << "Colon\n"; break;
133     case AsmToken::Comma:          outs() << "Comma\n"; break;
134     case AsmToken::Dollar:         outs() << "Dollar\n"; break;
135     case AsmToken::EndOfStatement: outs() << "EndOfStatement\n"; break;
136     case AsmToken::Eof:            outs() << "Eof\n"; break;
137     case AsmToken::Equal:          outs() << "Equal\n"; break;
138     case AsmToken::EqualEqual:     outs() << "EqualEqual\n"; break;
139     case AsmToken::Exclaim:        outs() << "Exclaim\n"; break;
140     case AsmToken::ExclaimEqual:   outs() << "ExclaimEqual\n"; break;
141     case AsmToken::Greater:        outs() << "Greater\n"; break;
142     case AsmToken::GreaterEqual:   outs() << "GreaterEqual\n"; break;
143     case AsmToken::GreaterGreater: outs() << "GreaterGreater\n"; break;
144     case AsmToken::LParen:         outs() << "LParen\n"; break;
145     case AsmToken::Less:           outs() << "Less\n"; break;
146     case AsmToken::LessEqual:      outs() << "LessEqual\n"; break;
147     case AsmToken::LessGreater:    outs() << "LessGreater\n"; break;
148     case AsmToken::LessLess:       outs() << "LessLess\n"; break;
149     case AsmToken::Minus:          outs() << "Minus\n"; break;
150     case AsmToken::Percent:        outs() << "Percent\n"; break;
151     case AsmToken::Pipe:           outs() << "Pipe\n"; break;
152     case AsmToken::PipePipe:       outs() << "PipePipe\n"; break;
153     case AsmToken::Plus:           outs() << "Plus\n"; break;
154     case AsmToken::RParen:         outs() << "RParen\n"; break;
155     case AsmToken::Slash:          outs() << "Slash\n"; break;
156     case AsmToken::Star:           outs() << "Star\n"; break;
157     case AsmToken::Tilde:          outs() << "Tilde\n"; break;
158     }
159   }
160   
161   return Error;
162 }
163
164 static const Target *GetTarget(const char *ProgName) {
165   // Get the target specific parser.
166   std::string Error;
167   const Target *TheTarget = TargetRegistry::lookupTarget(TripleName, Error);
168   if (TheTarget)
169     return TheTarget;
170
171   errs() << ProgName << ": error: unable to get target for '" << TripleName
172          << "', see --version and --triple.\n";
173   return 0;
174 }
175
176 static formatted_raw_ostream *GetOutputStream() {
177   if (OutputFilename == "")
178     OutputFilename = "-";
179
180   // Make sure that the Out file gets unlinked from the disk if we get a
181   // SIGINT.
182   if (OutputFilename != "-")
183     sys::RemoveFileOnSignal(sys::Path(OutputFilename));
184
185   std::string Err;
186   raw_fd_ostream *Out = new raw_fd_ostream(OutputFilename.c_str(), Err,
187                                            raw_fd_ostream::F_Binary |
188                                          (Force ? raw_fd_ostream::F_Force : 0));
189   if (!Err.empty()) {
190     errs() << Err << '\n';
191     if (!Force)
192       errs() << "Use -f command line argument to force output\n";
193     delete Out;
194     return 0;
195   }
196   
197   return new formatted_raw_ostream(*Out, formatted_raw_ostream::DELETE_STREAM);
198 }
199
200 static int AssembleInput(const char *ProgName) {
201   const Target *TheTarget = GetTarget(ProgName);
202   if (!TheTarget)
203     return 1;
204
205   std::string Error;
206   MemoryBuffer *Buffer = MemoryBuffer::getFileOrSTDIN(InputFilename, &Error);
207   if (Buffer == 0) {
208     errs() << ProgName << ": ";
209     if (Error.size())
210       errs() << Error << "\n";
211     else
212       errs() << "input file didn't read correctly.\n";
213     return 1;
214   }
215   
216   SourceMgr SrcMgr;
217   
218   // Tell SrcMgr about this buffer, which is what the parser will pick up.
219   SrcMgr.AddNewSourceBuffer(Buffer, SMLoc());
220   
221   // Record the location of the include directories so that the lexer can find
222   // it later.
223   SrcMgr.setIncludeDirs(IncludeDirs);
224   
225   MCContext Ctx;
226   formatted_raw_ostream *Out = GetOutputStream();
227   if (!Out)
228     return 1;
229
230
231   // FIXME: We shouldn't need to do this (and link in codegen).
232   OwningPtr<TargetMachine> TM(TheTarget->createTargetMachine(TripleName, ""));
233
234   if (!TM) {
235     errs() << ProgName << ": error: could not create target for triple '"
236            << TripleName << "'.\n";
237     return 1;
238   }
239
240   OwningPtr<AsmPrinter> AP;
241   OwningPtr<MCStreamer> Str;
242
243   if (FileType == OFT_AssemblyFile) {
244     const MCAsmInfo *TAI = TheTarget->createAsmInfo(TripleName);
245     assert(TAI && "Unable to create target asm info!");
246
247     AP.reset(TheTarget->createAsmPrinter(*Out, *TM, TAI, true));
248     Str.reset(createAsmStreamer(Ctx, *Out, *TAI, AP.get()));
249   } else {
250     assert(FileType == OFT_ObjectFile && "Invalid file type!");
251     Str.reset(createMachOStreamer(Ctx, *Out));
252   }
253
254   // FIXME: Target hook & command line option for initial section.
255   Str.get()->SwitchSection(MCSectionMachO::Create("__TEXT","__text",
256                                        MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
257                                                   0, SectionKind::getText(),
258                                                   Ctx));
259
260   AsmParser Parser(SrcMgr, Ctx, *Str.get());
261   OwningPtr<TargetAsmParser> TAP(TheTarget->createAsmParser(Parser));
262   if (!TAP) {
263     errs() << ProgName 
264            << ": error: this target does not support assembly parsing.\n";
265     return 1;
266   }
267
268   Parser.setTargetParser(*TAP.get());
269
270   int Res = Parser.Run();
271   if (Out != &fouts())
272     delete Out;
273
274   return Res;
275 }  
276
277
278 int main(int argc, char **argv) {
279   // Print a stack trace if we signal out.
280   sys::PrintStackTraceOnErrorSignal();
281   PrettyStackTraceProgram X(argc, argv);
282   llvm_shutdown_obj Y;  // Call llvm_shutdown() on exit.
283
284   // Initialize targets and assembly printers/parsers.
285   llvm::InitializeAllTargetInfos();
286   // FIXME: We shouldn't need to initialize the Target(Machine)s.
287   llvm::InitializeAllTargets();
288   llvm::InitializeAllAsmPrinters();
289   llvm::InitializeAllAsmParsers();
290   
291   cl::ParseCommandLineOptions(argc, argv, "llvm machine code playground\n");
292
293   switch (Action) {
294   default:
295   case AC_AsLex:
296     return AsLexInput(argv[0]);
297   case AC_Assemble:
298     return AssembleInput(argv[0]);
299   }
300   
301   return 0;
302 }
303