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