1 //===-- llvm-mc.cpp - Machine Code Hacking Driver -------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This utility is a simple driver that allows command line hacking on machine
13 //===----------------------------------------------------------------------===//
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/ADT/OwningPtr.h"
20 #include "llvm/CodeGen/AsmPrinter.h"
21 #include "llvm/Support/CommandLine.h"
22 #include "llvm/Support/FormattedStream.h"
23 #include "llvm/Support/ManagedStatic.h"
24 #include "llvm/Support/MemoryBuffer.h"
25 #include "llvm/Support/PrettyStackTrace.h"
26 #include "llvm/Support/SourceMgr.h"
27 #include "llvm/Support/raw_ostream.h"
28 #include "llvm/System/Signals.h"
29 #include "llvm/Target/TargetAsmParser.h"
30 #include "llvm/Target/TargetRegistry.h"
31 #include "llvm/Target/TargetSelect.h"
32 #include "AsmParser.h"
35 static cl::opt<std::string>
36 InputFilename(cl::Positional, cl::desc("<input file>"), cl::init("-"));
38 static cl::opt<std::string>
39 OutputFilename("o", cl::desc("Output filename"),
40 cl::value_desc("filename"));
46 static cl::opt<OutputFileType>
47 FileType("filetype", cl::init(OFT_AssemblyFile),
48 cl::desc("Choose an output file type:"),
50 clEnumValN(OFT_AssemblyFile, "asm",
51 "Emit an assembly ('.s') file"),
52 clEnumValN(OFT_ObjectFile, "obj",
53 "Emit a native object ('.o') file"),
57 Force("f", cl::desc("Enable binary output on terminals"));
59 static cl::list<std::string>
60 IncludeDirs("I", cl::desc("Directory of include files"),
61 cl::value_desc("directory"), cl::Prefix);
63 static cl::opt<std::string>
64 TripleName("triple", cl::desc("Target triple to assemble for,"
65 "see -version for available targets"),
66 cl::init(LLVM_HOSTTRIPLE));
73 static cl::opt<ActionType>
74 Action(cl::desc("Action to perform:"),
75 cl::init(AC_Assemble),
76 cl::values(clEnumValN(AC_AsLex, "as-lex",
77 "Lex tokens from a .s file"),
78 clEnumValN(AC_Assemble, "assemble",
79 "Assemble a .s file (default)"),
82 static int AsLexInput(const char *ProgName) {
83 std::string ErrorMessage;
84 MemoryBuffer *Buffer = MemoryBuffer::getFileOrSTDIN(InputFilename,
87 errs() << ProgName << ": ";
88 if (ErrorMessage.size())
89 errs() << ErrorMessage << "\n";
91 errs() << "input file didn't read correctly.\n";
97 // Tell SrcMgr about this buffer, which is what TGParser will pick up.
98 SrcMgr.AddNewSourceBuffer(Buffer, SMLoc());
100 // Record the location of the include directories so that the lexer can find
102 SrcMgr.setIncludeDirs(IncludeDirs);
104 AsmLexer Lexer(SrcMgr);
108 while (Lexer.Lex().isNot(AsmToken::Eof)) {
109 switch (Lexer.getKind()) {
111 Lexer.PrintMessage(Lexer.getLoc(), "unknown token", "warning");
114 case AsmToken::Error:
115 Error = true; // error already printed.
117 case AsmToken::Identifier:
118 outs() << "identifier: " << Lexer.getTok().getString() << '\n';
120 case AsmToken::Register:
121 outs() << "register: " << Lexer.getTok().getString() << '\n';
123 case AsmToken::String:
124 outs() << "string: " << Lexer.getTok().getString() << '\n';
126 case AsmToken::Integer:
127 outs() << "int: " << Lexer.getTok().getString() << '\n';
130 case AsmToken::Amp: outs() << "Amp\n"; break;
131 case AsmToken::AmpAmp: outs() << "AmpAmp\n"; break;
132 case AsmToken::Caret: outs() << "Caret\n"; break;
133 case AsmToken::Colon: outs() << "Colon\n"; break;
134 case AsmToken::Comma: outs() << "Comma\n"; break;
135 case AsmToken::Dollar: outs() << "Dollar\n"; break;
136 case AsmToken::EndOfStatement: outs() << "EndOfStatement\n"; break;
137 case AsmToken::Eof: outs() << "Eof\n"; break;
138 case AsmToken::Equal: outs() << "Equal\n"; break;
139 case AsmToken::EqualEqual: outs() << "EqualEqual\n"; break;
140 case AsmToken::Exclaim: outs() << "Exclaim\n"; break;
141 case AsmToken::ExclaimEqual: outs() << "ExclaimEqual\n"; break;
142 case AsmToken::Greater: outs() << "Greater\n"; break;
143 case AsmToken::GreaterEqual: outs() << "GreaterEqual\n"; break;
144 case AsmToken::GreaterGreater: outs() << "GreaterGreater\n"; break;
145 case AsmToken::LParen: outs() << "LParen\n"; break;
146 case AsmToken::Less: outs() << "Less\n"; break;
147 case AsmToken::LessEqual: outs() << "LessEqual\n"; break;
148 case AsmToken::LessGreater: outs() << "LessGreater\n"; break;
149 case AsmToken::LessLess: outs() << "LessLess\n"; break;
150 case AsmToken::Minus: outs() << "Minus\n"; break;
151 case AsmToken::Percent: outs() << "Percent\n"; break;
152 case AsmToken::Pipe: outs() << "Pipe\n"; break;
153 case AsmToken::PipePipe: outs() << "PipePipe\n"; break;
154 case AsmToken::Plus: outs() << "Plus\n"; break;
155 case AsmToken::RParen: outs() << "RParen\n"; break;
156 case AsmToken::Slash: outs() << "Slash\n"; break;
157 case AsmToken::Star: outs() << "Star\n"; break;
158 case AsmToken::Tilde: outs() << "Tilde\n"; break;
165 static const Target *GetTarget(const char *ProgName) {
166 // Get the target specific parser.
168 const Target *TheTarget = TargetRegistry::lookupTarget(TripleName, Error);
172 errs() << ProgName << ": error: unable to get target for '" << TripleName
173 << "', see --version and --triple.\n";
177 static formatted_raw_ostream *GetOutputStream() {
178 if (OutputFilename == "")
179 OutputFilename = "-";
181 // Make sure that the Out file gets unlinked from the disk if we get a
183 if (OutputFilename != "-")
184 sys::RemoveFileOnSignal(sys::Path(OutputFilename));
187 raw_fd_ostream *Out = new raw_fd_ostream(OutputFilename.c_str(), Err,
188 raw_fd_ostream::F_Binary);
190 errs() << Err << '\n';
195 return new formatted_raw_ostream(*Out, formatted_raw_ostream::DELETE_STREAM);
198 static int AssembleInput(const char *ProgName) {
199 const Target *TheTarget = GetTarget(ProgName);
204 MemoryBuffer *Buffer = MemoryBuffer::getFileOrSTDIN(InputFilename, &Error);
206 errs() << ProgName << ": ";
208 errs() << Error << "\n";
210 errs() << "input file didn't read correctly.\n";
216 // Tell SrcMgr about this buffer, which is what the parser will pick up.
217 SrcMgr.AddNewSourceBuffer(Buffer, SMLoc());
219 // Record the location of the include directories so that the lexer can find
221 SrcMgr.setIncludeDirs(IncludeDirs);
224 formatted_raw_ostream *Out = GetOutputStream();
229 // FIXME: We shouldn't need to do this (and link in codegen).
230 OwningPtr<TargetMachine> TM(TheTarget->createTargetMachine(TripleName, ""));
233 errs() << ProgName << ": error: could not create target for triple '"
234 << TripleName << "'.\n";
238 OwningPtr<AsmPrinter> AP;
239 OwningPtr<MCCodeEmitter> CE;
240 OwningPtr<MCStreamer> Str;
242 if (FileType == OFT_AssemblyFile) {
243 const MCAsmInfo *TAI = TheTarget->createAsmInfo(TripleName);
244 assert(TAI && "Unable to create target asm info!");
246 AP.reset(TheTarget->createAsmPrinter(*Out, *TM, TAI, true));
247 CE.reset(TheTarget->createCodeEmitter(*TM));
248 Str.reset(createAsmStreamer(Ctx, *Out, *TAI, AP.get(), CE.get()));
250 assert(FileType == OFT_ObjectFile && "Invalid file type!");
251 Str.reset(createMachOStreamer(Ctx, *Out));
254 AsmParser Parser(SrcMgr, Ctx, *Str.get());
255 OwningPtr<TargetAsmParser> TAP(TheTarget->createAsmParser(Parser));
258 << ": error: this target does not support assembly parsing.\n";
262 Parser.setTargetParser(*TAP.get());
264 int Res = Parser.Run();
272 int main(int argc, char **argv) {
273 // Print a stack trace if we signal out.
274 sys::PrintStackTraceOnErrorSignal();
275 PrettyStackTraceProgram X(argc, argv);
276 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
278 // Initialize targets and assembly printers/parsers.
279 llvm::InitializeAllTargetInfos();
280 // FIXME: We shouldn't need to initialize the Target(Machine)s.
281 llvm::InitializeAllTargets();
282 llvm::InitializeAllAsmPrinters();
283 llvm::InitializeAllAsmParsers();
285 cl::ParseCommandLineOptions(argc, argv, "llvm machine code playground\n");
290 return AsLexInput(argv[0]);
292 return AssembleInput(argv[0]);