llvm-mc.cpp revision fb4a6b397665df011348ade24a8e38d2219f095a
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/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" 32using namespace llvm; 33 34static cl::opt<std::string> 35InputFilename(cl::Positional, cl::desc("<input file>"), cl::init("-")); 36 37static cl::opt<std::string> 38OutputFilename("o", cl::desc("Output filename"), 39 cl::value_desc("filename")); 40 41enum OutputFileType { 42 OFT_AssemblyFile, 43 OFT_ObjectFile 44}; 45static cl::opt<OutputFileType> 46FileType("filetype", cl::init(OFT_AssemblyFile), 47 cl::desc("Choose an output file type:"), 48 cl::values( 49 clEnumValN(OFT_AssemblyFile, "asm", 50 "Emit an assembly ('.s') file"), 51 clEnumValN(OFT_ObjectFile, "obj", 52 "Emit a native object ('.o') file"), 53 clEnumValEnd)); 54 55static cl::opt<bool> 56Force("f", cl::desc("Overwrite output files")); 57 58static cl::list<std::string> 59IncludeDirs("I", cl::desc("Directory of include files"), 60 cl::value_desc("directory"), cl::Prefix); 61 62static cl::opt<std::string> 63TripleName("triple", cl::desc("Target triple to assemble for," 64 "see -version for available targets"), 65 cl::init(LLVM_HOSTTRIPLE)); 66 67enum ActionType { 68 AC_AsLex, 69 AC_Assemble 70}; 71 72static cl::opt<ActionType> 73Action(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)"), 79 clEnumValEnd)); 80 81static int AsLexInput(const char *ProgName) { 82 std::string ErrorMessage; 83 MemoryBuffer *Buffer = MemoryBuffer::getFileOrSTDIN(InputFilename, 84 &ErrorMessage); 85 if (Buffer == 0) { 86 errs() << ProgName << ": "; 87 if (ErrorMessage.size()) 88 errs() << ErrorMessage << "\n"; 89 else 90 errs() << "input file didn't read correctly.\n"; 91 return 1; 92 } 93 94 SourceMgr SrcMgr; 95 96 // Tell SrcMgr about this buffer, which is what TGParser will pick up. 97 SrcMgr.AddNewSourceBuffer(Buffer, SMLoc()); 98 99 // Record the location of the include directories so that the lexer can find 100 // it later. 101 SrcMgr.setIncludeDirs(IncludeDirs); 102 103 AsmLexer Lexer(SrcMgr); 104 105 bool Error = false; 106 107 while (Lexer.Lex().isNot(AsmToken::Eof)) { 108 switch (Lexer.getKind()) { 109 default: 110 Lexer.PrintMessage(Lexer.getLoc(), "unknown token", "warning"); 111 Error = true; 112 break; 113 case AsmToken::Error: 114 Error = true; // error already printed. 115 break; 116 case AsmToken::Identifier: 117 outs() << "identifier: " << Lexer.getTok().getString() << '\n'; 118 break; 119 case AsmToken::Register: 120 outs() << "register: " << Lexer.getTok().getString() << '\n'; 121 break; 122 case AsmToken::String: 123 outs() << "string: " << Lexer.getTok().getString() << '\n'; 124 break; 125 case AsmToken::Integer: 126 outs() << "int: " << Lexer.getTok().getString() << '\n'; 127 break; 128 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; 158 } 159 } 160 161 return Error; 162} 163 164static const Target *GetTarget(const char *ProgName) { 165 // Get the target specific parser. 166 std::string Error; 167 const Target *TheTarget = TargetRegistry::lookupTarget(TripleName, Error); 168 if (TheTarget) 169 return TheTarget; 170 171 errs() << ProgName << ": error: unable to get target for '" << TripleName 172 << "', see --version and --triple.\n"; 173 return 0; 174} 175 176static formatted_raw_ostream *GetOutputStream() { 177 if (OutputFilename == "" || OutputFilename == "-") 178 return &fouts(); 179 180 // Make sure that the Out file gets unlinked from the disk if we get a 181 // SIGINT 182 sys::RemoveFileOnSignal(sys::Path(OutputFilename)); 183 184 std::string Err; 185 raw_fd_ostream *Out = new raw_fd_ostream(OutputFilename.c_str(), 186 /*Binary=*/false, Force, Err); 187 if (!Err.empty()) { 188 errs() << Err << '\n'; 189 if (!Force) 190 errs() << "Use -f command line argument to force output\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<MCStreamer> Str; 240 241 if (FileType == OFT_AssemblyFile) { 242 const TargetAsmInfo *TAI = TheTarget->createAsmInfo(TripleName); 243 assert(TAI && "Unable to create target asm info!"); 244 245 AP.reset(TheTarget->createAsmPrinter(*Out, *TM, TAI, true)); 246 Str.reset(createAsmStreamer(Ctx, *Out, *TAI, AP.get())); 247 } else { 248 assert(FileType == OFT_ObjectFile && "Invalid file type!"); 249 Str.reset(createMachOStreamer(Ctx, *Out)); 250 } 251 252 // FIXME: Target hook & command line option for initial section. 253 Str.get()->SwitchSection(MCSectionMachO::Create("__TEXT","__text", 254 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS, 255 0, SectionKind::getText(), 256 Ctx)); 257 258 AsmParser Parser(SrcMgr, Ctx, *Str.get()); 259 OwningPtr<TargetAsmParser> TAP(TheTarget->createAsmParser(Parser)); 260 if (!TAP) { 261 errs() << ProgName 262 << ": error: this target does not support assembly parsing.\n"; 263 return 1; 264 } 265 266 Parser.setTargetParser(*TAP.get()); 267 268 int Res = Parser.Run(); 269 if (Out != &fouts()) 270 delete Out; 271 272 return Res; 273} 274 275 276int main(int argc, char **argv) { 277 // Print a stack trace if we signal out. 278 sys::PrintStackTraceOnErrorSignal(); 279 PrettyStackTraceProgram X(argc, argv); 280 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit. 281 282 // Initialize targets and assembly printers/parsers. 283 llvm::InitializeAllTargetInfos(); 284 // FIXME: We shouldn't need to initialize the Target(Machine)s. 285 llvm::InitializeAllTargets(); 286 llvm::InitializeAllAsmPrinters(); 287 llvm::InitializeAllAsmParsers(); 288 289 cl::ParseCommandLineOptions(argc, argv, "llvm machine code playground\n"); 290 291 switch (Action) { 292 default: 293 case AC_AsLex: 294 return AsLexInput(argv[0]); 295 case AC_Assemble: 296 return AssembleInput(argv[0]); 297 } 298 299 return 0; 300} 301 302