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