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