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/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"
34 static cl::opt<std::string>
35 InputFilename(cl::Positional, cl::desc("<input file>"), cl::init("-"));
37 static cl::opt<std::string>
38 OutputFilename("o", cl::desc("Output filename"),
39 cl::value_desc("filename"));
45 static cl::opt<OutputFileType>
46 FileType("filetype", cl::init(OFT_AssemblyFile),
47 cl::desc("Choose an output file type:"),
49 clEnumValN(OFT_AssemblyFile, "asm",
50 "Emit an assembly ('.s') file"),
51 clEnumValN(OFT_ObjectFile, "obj",
52 "Emit a native object ('.o') file"),
56 Force("f", cl::desc("Enable binary output on terminals"));
58 static cl::list<std::string>
59 IncludeDirs("I", cl::desc("Directory of include files"),
60 cl::value_desc("directory"), cl::Prefix);
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));
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)"),
81 static int AsLexInput(const char *ProgName) {
82 std::string ErrorMessage;
83 MemoryBuffer *Buffer = MemoryBuffer::getFileOrSTDIN(InputFilename,
86 errs() << ProgName << ": ";
87 if (ErrorMessage.size())
88 errs() << ErrorMessage << "\n";
90 errs() << "input file didn't read correctly.\n";
96 // Tell SrcMgr about this buffer, which is what TGParser will pick up.
97 SrcMgr.AddNewSourceBuffer(Buffer, SMLoc());
99 // Record the location of the include directories so that the lexer can find
101 SrcMgr.setIncludeDirs(IncludeDirs);
103 AsmLexer Lexer(SrcMgr);
107 while (Lexer.Lex().isNot(AsmToken::Eof)) {
108 switch (Lexer.getKind()) {
110 Lexer.PrintMessage(Lexer.getLoc(), "unknown token", "warning");
113 case AsmToken::Error:
114 Error = true; // error already printed.
116 case AsmToken::Identifier:
117 outs() << "identifier: " << Lexer.getTok().getString() << '\n';
119 case AsmToken::Register:
120 outs() << "register: " << Lexer.getTok().getString() << '\n';
122 case AsmToken::String:
123 outs() << "string: " << Lexer.getTok().getString() << '\n';
125 case AsmToken::Integer:
126 outs() << "int: " << Lexer.getTok().getString() << '\n';
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;
164 static const Target *GetTarget(const char *ProgName) {
165 // Get the target specific parser.
167 const Target *TheTarget = TargetRegistry::lookupTarget(TripleName, Error);
171 errs() << ProgName << ": error: unable to get target for '" << TripleName
172 << "', see --version and --triple.\n";
176 static formatted_raw_ostream *GetOutputStream() {
177 if (OutputFilename == "")
178 OutputFilename = "-";
180 // Make sure that the Out file gets unlinked from the disk if we get a
182 if (OutputFilename != "-")
183 sys::RemoveFileOnSignal(sys::Path(OutputFilename));
186 raw_fd_ostream *Out = new raw_fd_ostream(OutputFilename.c_str(), Err,
187 raw_fd_ostream::F_Binary);
189 errs() << Err << '\n';
194 return new formatted_raw_ostream(*Out, formatted_raw_ostream::DELETE_STREAM);
197 static int AssembleInput(const char *ProgName) {
198 const Target *TheTarget = GetTarget(ProgName);
203 MemoryBuffer *Buffer = MemoryBuffer::getFileOrSTDIN(InputFilename, &Error);
205 errs() << ProgName << ": ";
207 errs() << Error << "\n";
209 errs() << "input file didn't read correctly.\n";
215 // Tell SrcMgr about this buffer, which is what the parser will pick up.
216 SrcMgr.AddNewSourceBuffer(Buffer, SMLoc());
218 // Record the location of the include directories so that the lexer can find
220 SrcMgr.setIncludeDirs(IncludeDirs);
223 formatted_raw_ostream *Out = GetOutputStream();
228 // FIXME: We shouldn't need to do this (and link in codegen).
229 OwningPtr<TargetMachine> TM(TheTarget->createTargetMachine(TripleName, ""));
232 errs() << ProgName << ": error: could not create target for triple '"
233 << TripleName << "'.\n";
237 OwningPtr<AsmPrinter> AP;
238 OwningPtr<MCStreamer> Str;
240 if (FileType == OFT_AssemblyFile) {
241 const MCAsmInfo *TAI = TheTarget->createAsmInfo(TripleName);
242 assert(TAI && "Unable to create target asm info!");
244 AP.reset(TheTarget->createAsmPrinter(*Out, *TM, TAI, true));
245 Str.reset(createAsmStreamer(Ctx, *Out, *TAI, AP.get()));
247 assert(FileType == OFT_ObjectFile && "Invalid file type!");
248 Str.reset(createMachOStreamer(Ctx, *Out));
251 // FIXME: Target hook & command line option for initial section.
252 Str.get()->SwitchSection(MCSectionMachO::Create("__TEXT","__text",
253 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
254 0, SectionKind::getText(),
257 AsmParser Parser(SrcMgr, Ctx, *Str.get());
258 OwningPtr<TargetAsmParser> TAP(TheTarget->createAsmParser(Parser));
261 << ": error: this target does not support assembly parsing.\n";
265 Parser.setTargetParser(*TAP.get());
267 int Res = Parser.Run();
275 int main(int argc, char **argv) {
276 // Print a stack trace if we signal out.
277 sys::PrintStackTraceOnErrorSignal();
278 PrettyStackTraceProgram X(argc, argv);
279 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
281 // Initialize targets and assembly printers/parsers.
282 llvm::InitializeAllTargetInfos();
283 // FIXME: We shouldn't need to initialize the Target(Machine)s.
284 llvm::InitializeAllTargets();
285 llvm::InitializeAllAsmPrinters();
286 llvm::InitializeAllAsmParsers();
288 cl::ParseCommandLineOptions(argc, argv, "llvm machine code playground\n");
293 return AsLexInput(argv[0]);
295 return AssembleInput(argv[0]);