Fix LLVM target initialization to deal with sociopathic outside projects
[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/MCParser/AsmLexer.h"
16 #include "llvm/MC/MCParser/MCAsmLexer.h"
17 #include "llvm/MC/MCContext.h"
18 #include "llvm/MC/MCCodeEmitter.h"
19 #include "llvm/MC/MCInstPrinter.h"
20 #include "llvm/MC/MCSectionMachO.h"
21 #include "llvm/MC/MCStreamer.h"
22 #include "llvm/Target/TargetAsmBackend.h"
23 #include "llvm/Target/TargetAsmParser.h"
24 #include "llvm/Target/TargetData.h"
25 #include "llvm/Target/TargetRegistry.h"
26 #include "llvm/Target/TargetMachine.h"  // FIXME.
27 #include "llvm/Target/TargetSelect.h"
28 #include "llvm/ADT/OwningPtr.h"
29 #include "llvm/Support/CommandLine.h"
30 #include "llvm/Support/FileUtilities.h"
31 #include "llvm/Support/FormattedStream.h"
32 #include "llvm/Support/ManagedStatic.h"
33 #include "llvm/Support/MemoryBuffer.h"
34 #include "llvm/Support/PrettyStackTrace.h"
35 #include "llvm/Support/SourceMgr.h"
36 #include "llvm/Support/raw_ostream.h"
37 #include "llvm/System/Host.h"
38 #include "llvm/System/Signals.h"
39 #include "Disassembler.h"
40 using namespace llvm;
41
42 static cl::opt<std::string>
43 InputFilename(cl::Positional, cl::desc("<input file>"), cl::init("-"));
44
45 static cl::opt<std::string>
46 OutputFilename("o", cl::desc("Output filename"),
47                cl::value_desc("filename"));
48
49 static cl::opt<bool>
50 ShowEncoding("show-encoding", cl::desc("Show instruction encodings"));
51
52 static cl::opt<bool>
53 ShowInst("show-inst", cl::desc("Show internal instruction representation"));
54
55 static cl::opt<bool>
56 ShowInstOperands("show-inst-operands",
57                  cl::desc("Show instructions operands as parsed"));
58
59 static cl::opt<unsigned>
60 OutputAsmVariant("output-asm-variant",
61                  cl::desc("Syntax variant to use for output printing"));
62
63 static cl::opt<bool>
64 RelaxAll("mc-relax-all", cl::desc("Relax all fixups"));
65
66 static cl::opt<bool>
67 EnableLogging("enable-api-logging", cl::desc("Enable MC API logging"));
68
69 enum OutputFileType {
70   OFT_Null,
71   OFT_AssemblyFile,
72   OFT_ObjectFile
73 };
74 static cl::opt<OutputFileType>
75 FileType("filetype", cl::init(OFT_AssemblyFile),
76   cl::desc("Choose an output file type:"),
77   cl::values(
78        clEnumValN(OFT_AssemblyFile, "asm",
79                   "Emit an assembly ('.s') file"),
80        clEnumValN(OFT_Null, "null",
81                   "Don't emit anything (for timing purposes)"),
82        clEnumValN(OFT_ObjectFile, "obj",
83                   "Emit a native object ('.o') file"),
84        clEnumValEnd));
85
86 static cl::list<std::string>
87 IncludeDirs("I", cl::desc("Directory of include files"),
88             cl::value_desc("directory"), cl::Prefix);
89
90 static cl::opt<std::string>
91 ArchName("arch", cl::desc("Target arch to assemble for, "
92                             "see -version for available targets"));
93
94 static cl::opt<std::string>
95 TripleName("triple", cl::desc("Target triple to assemble for, "
96                               "see -version for available targets"));
97
98 static cl::opt<bool>
99 NoInitialTextSection("n", cl::desc(
100                    "Don't assume assembly file starts in the text section"));
101
102 enum ActionType {
103   AC_AsLex,
104   AC_Assemble,
105   AC_Disassemble,
106   AC_EDisassemble
107 };
108
109 static cl::opt<ActionType>
110 Action(cl::desc("Action to perform:"),
111        cl::init(AC_Assemble),
112        cl::values(clEnumValN(AC_AsLex, "as-lex",
113                              "Lex tokens from a .s file"),
114                   clEnumValN(AC_Assemble, "assemble",
115                              "Assemble a .s file (default)"),
116                   clEnumValN(AC_Disassemble, "disassemble",
117                              "Disassemble strings of hex bytes"),
118                   clEnumValN(AC_EDisassemble, "edis",
119                              "Enhanced disassembly of strings of hex bytes"),
120                   clEnumValEnd));
121
122 static const Target *GetTarget(const char *ProgName) {
123   // Figure out the target triple.
124   if (TripleName.empty())
125     TripleName = sys::getHostTriple();
126   if (!ArchName.empty()) {
127     llvm::Triple TT(TripleName);
128     TT.setArchName(ArchName);
129     TripleName = TT.str();
130   }
131
132   // Get the target specific parser.
133   std::string Error;
134   const Target *TheTarget = TargetRegistry::lookupTarget(TripleName, Error);
135   if (TheTarget)
136     return TheTarget;
137
138   errs() << ProgName << ": error: unable to get target for '" << TripleName
139          << "', see --version and --triple.\n";
140   return 0;
141 }
142
143 static formatted_tool_output_file *GetOutputStream() {
144   if (OutputFilename == "")
145     OutputFilename = "-";
146
147   std::string Err;
148   tool_output_file *Out = new tool_output_file(OutputFilename.c_str(), Err,
149                                                raw_fd_ostream::F_Binary);
150   if (!Err.empty()) {
151     errs() << Err << '\n';
152     delete Out;
153     return 0;
154   }
155   
156   return new formatted_tool_output_file(*Out,
157                                         formatted_raw_ostream::DELETE_STREAM);
158 }
159
160 static int AsLexInput(const char *ProgName) {
161   std::string ErrorMessage;
162   MemoryBuffer *Buffer = MemoryBuffer::getFileOrSTDIN(InputFilename,
163                                                       &ErrorMessage);
164   if (Buffer == 0) {
165     errs() << ProgName << ": ";
166     if (ErrorMessage.size())
167       errs() << ErrorMessage << "\n";
168     else
169       errs() << "input file didn't read correctly.\n";
170     return 1;
171   }
172
173   SourceMgr SrcMgr;
174   
175   // Tell SrcMgr about this buffer, which is what TGParser will pick up.
176   SrcMgr.AddNewSourceBuffer(Buffer, SMLoc());
177   
178   // Record the location of the include directories so that the lexer can find
179   // it later.
180   SrcMgr.setIncludeDirs(IncludeDirs);
181
182   const Target *TheTarget = GetTarget(ProgName);
183   if (!TheTarget)
184     return 1;
185
186   llvm::OwningPtr<MCAsmInfo> MAI(TheTarget->createAsmInfo(TripleName));
187   assert(MAI && "Unable to create target asm info!");
188
189   AsmLexer Lexer(*MAI);
190   Lexer.setBuffer(SrcMgr.getMemoryBuffer(0));
191
192   OwningPtr<formatted_tool_output_file> Out(GetOutputStream());
193   if (!Out)
194     return 1;
195
196   bool Error = false;
197   while (Lexer.Lex().isNot(AsmToken::Eof)) {
198     switch (Lexer.getKind()) {
199     default:
200       SrcMgr.PrintMessage(Lexer.getLoc(), "unknown token", "warning");
201       Error = true;
202       break;
203     case AsmToken::Error:
204       Error = true; // error already printed.
205       break;
206     case AsmToken::Identifier:
207       *Out << "identifier: " << Lexer.getTok().getString() << '\n';
208       break;
209     case AsmToken::String:
210       *Out << "string: " << Lexer.getTok().getString() << '\n';
211       break;
212     case AsmToken::Integer:
213       *Out << "int: " << Lexer.getTok().getString() << '\n';
214       break;
215
216     case AsmToken::Amp:            *Out << "Amp\n"; break;
217     case AsmToken::AmpAmp:         *Out << "AmpAmp\n"; break;
218     case AsmToken::Caret:          *Out << "Caret\n"; break;
219     case AsmToken::Colon:          *Out << "Colon\n"; break;
220     case AsmToken::Comma:          *Out << "Comma\n"; break;
221     case AsmToken::Dollar:         *Out << "Dollar\n"; break;
222     case AsmToken::EndOfStatement: *Out << "EndOfStatement\n"; break;
223     case AsmToken::Eof:            *Out << "Eof\n"; break;
224     case AsmToken::Equal:          *Out << "Equal\n"; break;
225     case AsmToken::EqualEqual:     *Out << "EqualEqual\n"; break;
226     case AsmToken::Exclaim:        *Out << "Exclaim\n"; break;
227     case AsmToken::ExclaimEqual:   *Out << "ExclaimEqual\n"; break;
228     case AsmToken::Greater:        *Out << "Greater\n"; break;
229     case AsmToken::GreaterEqual:   *Out << "GreaterEqual\n"; break;
230     case AsmToken::GreaterGreater: *Out << "GreaterGreater\n"; break;
231     case AsmToken::LParen:         *Out << "LParen\n"; break;
232     case AsmToken::Less:           *Out << "Less\n"; break;
233     case AsmToken::LessEqual:      *Out << "LessEqual\n"; break;
234     case AsmToken::LessGreater:    *Out << "LessGreater\n"; break;
235     case AsmToken::LessLess:       *Out << "LessLess\n"; break;
236     case AsmToken::Minus:          *Out << "Minus\n"; break;
237     case AsmToken::Percent:        *Out << "Percent\n"; break;
238     case AsmToken::Pipe:           *Out << "Pipe\n"; break;
239     case AsmToken::PipePipe:       *Out << "PipePipe\n"; break;
240     case AsmToken::Plus:           *Out << "Plus\n"; break;
241     case AsmToken::RParen:         *Out << "RParen\n"; break;
242     case AsmToken::Slash:          *Out << "Slash\n"; break;
243     case AsmToken::Star:           *Out << "Star\n"; break;
244     case AsmToken::Tilde:          *Out << "Tilde\n"; break;
245     }
246   }
247
248   // Keep output if no errors.
249   if (Error == 0) Out->keep();
250  
251   return Error;
252 }
253
254 static int AssembleInput(const char *ProgName) {
255   const Target *TheTarget = GetTarget(ProgName);
256   if (!TheTarget)
257     return 1;
258
259   std::string Error;
260   MemoryBuffer *Buffer = MemoryBuffer::getFileOrSTDIN(InputFilename, &Error);
261   if (Buffer == 0) {
262     errs() << ProgName << ": ";
263     if (Error.size())
264       errs() << Error << "\n";
265     else
266       errs() << "input file didn't read correctly.\n";
267     return 1;
268   }
269   
270   SourceMgr SrcMgr;
271   
272   // Tell SrcMgr about this buffer, which is what the parser will pick up.
273   SrcMgr.AddNewSourceBuffer(Buffer, SMLoc());
274   
275   // Record the location of the include directories so that the lexer can find
276   // it later.
277   SrcMgr.setIncludeDirs(IncludeDirs);
278   
279   
280   llvm::OwningPtr<MCAsmInfo> MAI(TheTarget->createAsmInfo(TripleName));
281   assert(MAI && "Unable to create target asm info!");
282   
283   MCContext Ctx(*MAI);
284
285   // FIXME: We shouldn't need to do this (and link in codegen).
286   OwningPtr<TargetMachine> TM(TheTarget->createTargetMachine(TripleName, ""));
287
288   if (!TM) {
289     errs() << ProgName << ": error: could not create target for triple '"
290            << TripleName << "'.\n";
291     return 1;
292   }
293
294   OwningPtr<formatted_tool_output_file> Out(GetOutputStream());
295   if (!Out)
296     return 1;
297
298   OwningPtr<MCStreamer> Str;
299
300   if (FileType == OFT_AssemblyFile) {
301     MCInstPrinter *IP =
302       TheTarget->createMCInstPrinter(OutputAsmVariant, *MAI);
303     MCCodeEmitter *CE = 0;
304     if (ShowEncoding)
305       CE = TheTarget->createCodeEmitter(*TM, Ctx);
306     Str.reset(createAsmStreamer(Ctx, *Out,
307                                 TM->getTargetData()->isLittleEndian(),
308                                 /*asmverbose*/true, IP, CE, ShowInst));
309   } else if (FileType == OFT_Null) {
310     Str.reset(createNullStreamer(Ctx));
311   } else {
312     assert(FileType == OFT_ObjectFile && "Invalid file type!");
313     MCCodeEmitter *CE = TheTarget->createCodeEmitter(*TM, Ctx);
314     TargetAsmBackend *TAB = TheTarget->createAsmBackend(TripleName);
315     Str.reset(TheTarget->createObjectStreamer(TripleName, Ctx, *TAB,
316                                               *Out, CE, RelaxAll));
317   }
318
319   if (EnableLogging) {
320     Str.reset(createLoggingStreamer(Str.take(), errs()));
321   }
322
323   OwningPtr<MCAsmParser> Parser(createMCAsmParser(*TheTarget, SrcMgr, Ctx,
324                                                    *Str.get(), *MAI));
325   OwningPtr<TargetAsmParser> TAP(TheTarget->createAsmParser(*Parser, *TM));
326   if (!TAP) {
327     errs() << ProgName 
328            << ": error: this target does not support assembly parsing.\n";
329     return 1;
330   }
331
332   Parser->setShowParsedOperands(ShowInstOperands);
333   Parser->setTargetParser(*TAP.get());
334
335   int Res = Parser->Run(NoInitialTextSection);
336
337   // Keep output if no errors.
338   if (Res == 0) Out->keep();
339
340   return Res;
341 }
342
343 static int DisassembleInput(const char *ProgName, bool Enhanced) {
344   const Target *TheTarget = GetTarget(ProgName);
345   if (!TheTarget)
346     return 0;
347   
348   std::string ErrorMessage;
349   
350   MemoryBuffer *Buffer = MemoryBuffer::getFileOrSTDIN(InputFilename,
351                                                       &ErrorMessage);
352
353   if (Buffer == 0) {
354     errs() << ProgName << ": ";
355     if (ErrorMessage.size())
356       errs() << ErrorMessage << "\n";
357     else
358       errs() << "input file didn't read correctly.\n";
359     return 1;
360   }
361   
362   OwningPtr<formatted_tool_output_file> Out(GetOutputStream());
363   if (!Out)
364     return 1;
365
366   int Res;
367   if (Enhanced)
368     Res = Disassembler::disassembleEnhanced(TripleName, *Buffer, *Out);
369   else
370     Res = Disassembler::disassemble(*TheTarget, TripleName, *Buffer, *Out);
371
372   // Keep output if no errors.
373   if (Res == 0) Out->keep();
374
375   return Res;
376 }
377
378
379 int main(int argc, char **argv) {
380   // Print a stack trace if we signal out.
381   sys::PrintStackTraceOnErrorSignal();
382   PrettyStackTraceProgram X(argc, argv);
383   llvm_shutdown_obj Y;  // Call llvm_shutdown() on exit.
384
385   // Initialize targets and assembly printers/parsers.
386   llvm::InitializeAllTargetInfos();
387   // FIXME: We shouldn't need to initialize the Target(Machine)s.
388   llvm::InitializeAllTargets();
389   llvm::InitializeAllAsmPrinters();
390   llvm::InitializeAllAsmParsers();
391   llvm::InitializeAllDisassemblers();
392   
393   cl::ParseCommandLineOptions(argc, argv, "llvm machine code playground\n");
394   TripleName = Triple::normalize(TripleName);
395
396   switch (Action) {
397   default:
398   case AC_AsLex:
399     return AsLexInput(argv[0]);
400   case AC_Assemble:
401     return AssembleInput(argv[0]);
402   case AC_Disassemble:
403     return DisassembleInput(argv[0], false);
404   case AC_EDisassemble:
405     return DisassembleInput(argv[0], true);
406   }
407   
408   return 0;
409 }
410