[llvm-mc] More meaningful error if input file doesn't exist.
[oota-llvm.git] / tools / llvm-mc / llvm-mc.cpp
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 "Disassembler.h"
16 #include "llvm/MC/MCAsmBackend.h"
17 #include "llvm/MC/MCAsmInfo.h"
18 #include "llvm/MC/MCContext.h"
19 #include "llvm/MC/MCInstPrinter.h"
20 #include "llvm/MC/MCInstrInfo.h"
21 #include "llvm/MC/MCObjectFileInfo.h"
22 #include "llvm/MC/MCParser/AsmLexer.h"
23 #include "llvm/MC/MCRegisterInfo.h"
24 #include "llvm/MC/MCSectionMachO.h"
25 #include "llvm/MC/MCStreamer.h"
26 #include "llvm/MC/MCSubtargetInfo.h"
27 #include "llvm/MC/MCTargetAsmParser.h"
28 #include "llvm/MC/MCTargetOptionsCommandFlags.h"
29 #include "llvm/Support/CommandLine.h"
30 #include "llvm/Support/Compression.h"
31 #include "llvm/Support/FileUtilities.h"
32 #include "llvm/Support/FormattedStream.h"
33 #include "llvm/Support/Host.h"
34 #include "llvm/Support/ManagedStatic.h"
35 #include "llvm/Support/MemoryBuffer.h"
36 #include "llvm/Support/PrettyStackTrace.h"
37 #include "llvm/Support/Signals.h"
38 #include "llvm/Support/SourceMgr.h"
39 #include "llvm/Support/TargetRegistry.h"
40 #include "llvm/Support/TargetSelect.h"
41 #include "llvm/Support/ToolOutputFile.h"
42 using namespace llvm;
43
44 static cl::opt<std::string>
45 InputFilename(cl::Positional, cl::desc("<input file>"), cl::init("-"));
46
47 static cl::opt<std::string>
48 OutputFilename("o", cl::desc("Output filename"),
49                cl::value_desc("filename"));
50
51 static cl::opt<bool>
52 ShowEncoding("show-encoding", cl::desc("Show instruction encodings"));
53
54 static cl::opt<bool>
55 CompressDebugSections("compress-debug-sections",
56                       cl::desc("Compress DWARF debug sections"));
57
58 static cl::opt<bool>
59 ShowInst("show-inst", cl::desc("Show internal instruction representation"));
60
61 static cl::opt<bool>
62 ShowInstOperands("show-inst-operands",
63                  cl::desc("Show instructions operands as parsed"));
64
65 static cl::opt<unsigned>
66 OutputAsmVariant("output-asm-variant",
67                  cl::desc("Syntax variant to use for output printing"));
68
69 static cl::opt<bool>
70 PrintImmHex("print-imm-hex", cl::init(false),
71             cl::desc("Prefer hex format for immediate values"));
72
73 static cl::list<std::string>
74 DefineSymbol("defsym", cl::desc("Defines a symbol to be an integer constant"));
75
76 enum OutputFileType {
77   OFT_Null,
78   OFT_AssemblyFile,
79   OFT_ObjectFile
80 };
81 static cl::opt<OutputFileType>
82 FileType("filetype", cl::init(OFT_AssemblyFile),
83   cl::desc("Choose an output file type:"),
84   cl::values(
85        clEnumValN(OFT_AssemblyFile, "asm",
86                   "Emit an assembly ('.s') file"),
87        clEnumValN(OFT_Null, "null",
88                   "Don't emit anything (for timing purposes)"),
89        clEnumValN(OFT_ObjectFile, "obj",
90                   "Emit a native object ('.o') file"),
91        clEnumValEnd));
92
93 static cl::list<std::string>
94 IncludeDirs("I", cl::desc("Directory of include files"),
95             cl::value_desc("directory"), cl::Prefix);
96
97 static cl::opt<std::string>
98 ArchName("arch", cl::desc("Target arch to assemble for, "
99                           "see -version for available targets"));
100
101 static cl::opt<std::string>
102 TripleName("triple", cl::desc("Target triple to assemble for, "
103                               "see -version for available targets"));
104
105 static cl::opt<std::string>
106 MCPU("mcpu",
107      cl::desc("Target a specific cpu type (-mcpu=help for details)"),
108      cl::value_desc("cpu-name"),
109      cl::init(""));
110
111 static cl::list<std::string>
112 MAttrs("mattr",
113   cl::CommaSeparated,
114   cl::desc("Target specific attributes (-mattr=help for details)"),
115   cl::value_desc("a1,+a2,-a3,..."));
116
117 static cl::opt<Reloc::Model>
118 RelocModel("relocation-model",
119              cl::desc("Choose relocation model"),
120              cl::init(Reloc::Default),
121              cl::values(
122             clEnumValN(Reloc::Default, "default",
123                        "Target default relocation model"),
124             clEnumValN(Reloc::Static, "static",
125                        "Non-relocatable code"),
126             clEnumValN(Reloc::PIC_, "pic",
127                        "Fully relocatable, position independent code"),
128             clEnumValN(Reloc::DynamicNoPIC, "dynamic-no-pic",
129                        "Relocatable external references, non-relocatable code"),
130             clEnumValEnd));
131
132 static cl::opt<llvm::CodeModel::Model>
133 CMModel("code-model",
134         cl::desc("Choose code model"),
135         cl::init(CodeModel::Default),
136         cl::values(clEnumValN(CodeModel::Default, "default",
137                               "Target default code model"),
138                    clEnumValN(CodeModel::Small, "small",
139                               "Small code model"),
140                    clEnumValN(CodeModel::Kernel, "kernel",
141                               "Kernel code model"),
142                    clEnumValN(CodeModel::Medium, "medium",
143                               "Medium code model"),
144                    clEnumValN(CodeModel::Large, "large",
145                               "Large code model"),
146                    clEnumValEnd));
147
148 static cl::opt<bool>
149 NoInitialTextSection("n", cl::desc("Don't assume assembly file starts "
150                                    "in the text section"));
151
152 static cl::opt<bool>
153 GenDwarfForAssembly("g", cl::desc("Generate dwarf debugging info for assembly "
154                                   "source files"));
155
156 static cl::opt<std::string>
157 DebugCompilationDir("fdebug-compilation-dir",
158                     cl::desc("Specifies the debug info's compilation dir"));
159
160 static cl::opt<std::string>
161 MainFileName("main-file-name",
162              cl::desc("Specifies the name we should consider the input file"));
163
164 static cl::opt<bool> SaveTempLabels("save-temp-labels",
165                                     cl::desc("Don't discard temporary labels"));
166
167 static cl::opt<bool> NoExecStack("no-exec-stack",
168                                  cl::desc("File doesn't need an exec stack"));
169
170 enum ActionType {
171   AC_AsLex,
172   AC_Assemble,
173   AC_Disassemble,
174   AC_MDisassemble,
175 };
176
177 static cl::opt<ActionType>
178 Action(cl::desc("Action to perform:"),
179        cl::init(AC_Assemble),
180        cl::values(clEnumValN(AC_AsLex, "as-lex",
181                              "Lex tokens from a .s file"),
182                   clEnumValN(AC_Assemble, "assemble",
183                              "Assemble a .s file (default)"),
184                   clEnumValN(AC_Disassemble, "disassemble",
185                              "Disassemble strings of hex bytes"),
186                   clEnumValN(AC_MDisassemble, "mdis",
187                              "Marked up disassembly of strings of hex bytes"),
188                   clEnumValEnd));
189
190 static const Target *GetTarget(const char *ProgName) {
191   // Figure out the target triple.
192   if (TripleName.empty())
193     TripleName = sys::getDefaultTargetTriple();
194   Triple TheTriple(Triple::normalize(TripleName));
195
196   // Get the target specific parser.
197   std::string Error;
198   const Target *TheTarget = TargetRegistry::lookupTarget(ArchName, TheTriple,
199                                                          Error);
200   if (!TheTarget) {
201     errs() << ProgName << ": " << Error;
202     return nullptr;
203   }
204
205   // Update the triple name and return the found target.
206   TripleName = TheTriple.getTriple();
207   return TheTarget;
208 }
209
210 static std::unique_ptr<tool_output_file> GetOutputStream() {
211   if (OutputFilename == "")
212     OutputFilename = "-";
213
214   std::error_code EC;
215   auto Out = llvm::make_unique<tool_output_file>(OutputFilename, EC,
216                                                  sys::fs::F_None);
217   if (EC) {
218     errs() << EC.message() << '\n';
219     return nullptr;
220   }
221
222   return Out;
223 }
224
225 static std::string DwarfDebugFlags;
226 static void setDwarfDebugFlags(int argc, char **argv) {
227   if (!getenv("RC_DEBUG_OPTIONS"))
228     return;
229   for (int i = 0; i < argc; i++) {
230     DwarfDebugFlags += argv[i];
231     if (i + 1 < argc)
232       DwarfDebugFlags += " ";
233   }
234 }
235
236 static std::string DwarfDebugProducer;
237 static void setDwarfDebugProducer(void) {
238   if(!getenv("DEBUG_PRODUCER"))
239     return;
240   DwarfDebugProducer += getenv("DEBUG_PRODUCER");
241 }
242
243 static int AsLexInput(SourceMgr &SrcMgr, MCAsmInfo &MAI,
244                       raw_ostream &OS) {
245
246   AsmLexer Lexer(MAI);
247   Lexer.setBuffer(SrcMgr.getMemoryBuffer(SrcMgr.getMainFileID())->getBuffer());
248
249   bool Error = false;
250   while (Lexer.Lex().isNot(AsmToken::Eof)) {
251     AsmToken Tok = Lexer.getTok();
252
253     switch (Tok.getKind()) {
254     default:
255       SrcMgr.PrintMessage(Lexer.getLoc(), SourceMgr::DK_Warning,
256                           "unknown token");
257       Error = true;
258       break;
259     case AsmToken::Error:
260       Error = true; // error already printed.
261       break;
262     case AsmToken::Identifier:
263       OS << "identifier: " << Lexer.getTok().getString();
264       break;
265     case AsmToken::Integer:
266       OS << "int: " << Lexer.getTok().getString();
267       break;
268     case AsmToken::Real:
269       OS << "real: " << Lexer.getTok().getString();
270       break;
271     case AsmToken::String:
272       OS << "string: " << Lexer.getTok().getString();
273       break;
274
275     case AsmToken::Amp:            OS << "Amp"; break;
276     case AsmToken::AmpAmp:         OS << "AmpAmp"; break;
277     case AsmToken::At:             OS << "At"; break;
278     case AsmToken::Caret:          OS << "Caret"; break;
279     case AsmToken::Colon:          OS << "Colon"; break;
280     case AsmToken::Comma:          OS << "Comma"; break;
281     case AsmToken::Dollar:         OS << "Dollar"; break;
282     case AsmToken::Dot:            OS << "Dot"; break;
283     case AsmToken::EndOfStatement: OS << "EndOfStatement"; break;
284     case AsmToken::Eof:            OS << "Eof"; break;
285     case AsmToken::Equal:          OS << "Equal"; break;
286     case AsmToken::EqualEqual:     OS << "EqualEqual"; break;
287     case AsmToken::Exclaim:        OS << "Exclaim"; break;
288     case AsmToken::ExclaimEqual:   OS << "ExclaimEqual"; break;
289     case AsmToken::Greater:        OS << "Greater"; break;
290     case AsmToken::GreaterEqual:   OS << "GreaterEqual"; break;
291     case AsmToken::GreaterGreater: OS << "GreaterGreater"; break;
292     case AsmToken::Hash:           OS << "Hash"; break;
293     case AsmToken::LBrac:          OS << "LBrac"; break;
294     case AsmToken::LCurly:         OS << "LCurly"; break;
295     case AsmToken::LParen:         OS << "LParen"; break;
296     case AsmToken::Less:           OS << "Less"; break;
297     case AsmToken::LessEqual:      OS << "LessEqual"; break;
298     case AsmToken::LessGreater:    OS << "LessGreater"; break;
299     case AsmToken::LessLess:       OS << "LessLess"; break;
300     case AsmToken::Minus:          OS << "Minus"; break;
301     case AsmToken::Percent:        OS << "Percent"; break;
302     case AsmToken::Pipe:           OS << "Pipe"; break;
303     case AsmToken::PipePipe:       OS << "PipePipe"; break;
304     case AsmToken::Plus:           OS << "Plus"; break;
305     case AsmToken::RBrac:          OS << "RBrac"; break;
306     case AsmToken::RCurly:         OS << "RCurly"; break;
307     case AsmToken::RParen:         OS << "RParen"; break;
308     case AsmToken::Slash:          OS << "Slash"; break;
309     case AsmToken::Star:           OS << "Star"; break;
310     case AsmToken::Tilde:          OS << "Tilde"; break;
311     }
312
313     // Print the token string.
314     OS << " (\"";
315     OS.write_escaped(Tok.getString());
316     OS << "\")\n";
317   }
318
319   return Error;
320 }
321
322 static int fillCommandLineSymbols(MCAsmParser &Parser){
323   for(auto &I: DefineSymbol){
324     auto Pair = StringRef(I).split('=');
325     if(Pair.second.empty()){
326       errs() << "error: defsym must be of the form: sym=value: " << I;
327       return 1;
328     }
329     int64_t Value;
330     if(Pair.second.getAsInteger(0, Value)){
331       errs() << "error: Value is not an integer: " << Pair.second;
332       return 1;
333     }
334     auto &Context = Parser.getContext();
335     auto Symbol = Context.getOrCreateSymbol(Pair.first);
336     Parser.getStreamer().EmitAssignment(Symbol,
337                                         MCConstantExpr::create(Value, Context));
338   }
339   return 0;
340 }
341
342 static int AssembleInput(const char *ProgName, const Target *TheTarget,
343                          SourceMgr &SrcMgr, MCContext &Ctx, MCStreamer &Str,
344                          MCAsmInfo &MAI, MCSubtargetInfo &STI,
345                          MCInstrInfo &MCII, MCTargetOptions &MCOptions) {
346   std::unique_ptr<MCAsmParser> Parser(
347       createMCAsmParser(SrcMgr, Ctx, Str, MAI));
348   std::unique_ptr<MCTargetAsmParser> TAP(
349       TheTarget->createMCAsmParser(STI, *Parser, MCII, MCOptions));
350
351   if (!TAP) {
352     errs() << ProgName
353            << ": error: this target does not support assembly parsing.\n";
354     return 1;
355   }
356
357   int SymbolResult = fillCommandLineSymbols(*Parser);
358   if(SymbolResult)
359     return SymbolResult;
360   Parser->setShowParsedOperands(ShowInstOperands);
361   Parser->setTargetParser(*TAP);
362
363   int Res = Parser->Run(NoInitialTextSection);
364
365   return Res;
366 }
367
368 int main(int argc, char **argv) {
369   // Print a stack trace if we signal out.
370   sys::PrintStackTraceOnErrorSignal();
371   PrettyStackTraceProgram X(argc, argv);
372   llvm_shutdown_obj Y;  // Call llvm_shutdown() on exit.
373
374   // Initialize targets and assembly printers/parsers.
375   llvm::InitializeAllTargetInfos();
376   llvm::InitializeAllTargetMCs();
377   llvm::InitializeAllAsmParsers();
378   llvm::InitializeAllDisassemblers();
379
380   // Register the target printer for --version.
381   cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
382
383   cl::ParseCommandLineOptions(argc, argv, "llvm machine code playground\n");
384   MCTargetOptions MCOptions = InitMCTargetOptionsFromFlags();
385   TripleName = Triple::normalize(TripleName);
386   setDwarfDebugFlags(argc, argv);
387
388   setDwarfDebugProducer();
389
390   const char *ProgName = argv[0];
391   const Target *TheTarget = GetTarget(ProgName);
392   if (!TheTarget)
393     return 1;
394   // Now that GetTarget() has (potentially) replaced TripleName, it's safe to
395   // construct the Triple object.
396   Triple TheTriple(TripleName);
397
398   if (InputFilename != "-" && !sys::fs::exists(InputFilename)) {
399     errs() << ProgName << ": '" << InputFilename << "': "
400            << "No such file\n";
401     return 1;
402   }
403   ErrorOr<std::unique_ptr<MemoryBuffer>> BufferPtr =
404       MemoryBuffer::getFileOrSTDIN(InputFilename);
405   if (std::error_code EC = BufferPtr.getError()) {
406     errs() << ProgName << ": " << EC.message() << '\n';
407     return 1;
408   }
409   MemoryBuffer *Buffer = BufferPtr->get();
410
411   SourceMgr SrcMgr;
412
413   // Tell SrcMgr about this buffer, which is what the parser will pick up.
414   SrcMgr.AddNewSourceBuffer(std::move(*BufferPtr), SMLoc());
415
416   // Record the location of the include directories so that the lexer can find
417   // it later.
418   SrcMgr.setIncludeDirs(IncludeDirs);
419
420   std::unique_ptr<MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TripleName));
421   assert(MRI && "Unable to create target register info!");
422
423   std::unique_ptr<MCAsmInfo> MAI(TheTarget->createMCAsmInfo(*MRI, TripleName));
424   assert(MAI && "Unable to create target asm info!");
425
426   if (CompressDebugSections) {
427     if (!zlib::isAvailable()) {
428       errs() << ProgName
429              << ": build tools with zlib to enable -compress-debug-sections";
430       return 1;
431     }
432     MAI->setCompressDebugSections(true);
433   }
434
435   // FIXME: This is not pretty. MCContext has a ptr to MCObjectFileInfo and
436   // MCObjectFileInfo needs a MCContext reference in order to initialize itself.
437   MCObjectFileInfo MOFI;
438   MCContext Ctx(MAI.get(), MRI.get(), &MOFI, &SrcMgr);
439   MOFI.InitMCObjectFileInfo(TheTriple, RelocModel, CMModel, Ctx);
440
441   if (SaveTempLabels)
442     Ctx.setAllowTemporaryLabels(false);
443
444   Ctx.setGenDwarfForAssembly(GenDwarfForAssembly);
445   // Default to 4 for dwarf version.
446   unsigned DwarfVersion = MCOptions.DwarfVersion ? MCOptions.DwarfVersion : 4;
447   if (DwarfVersion < 2 || DwarfVersion > 4) {
448     errs() << ProgName << ": Dwarf version " << DwarfVersion
449            << " is not supported." << '\n';
450     return 1;
451   }
452   Ctx.setDwarfVersion(DwarfVersion);
453   if (!DwarfDebugFlags.empty())
454     Ctx.setDwarfDebugFlags(StringRef(DwarfDebugFlags));
455   if (!DwarfDebugProducer.empty())
456     Ctx.setDwarfDebugProducer(StringRef(DwarfDebugProducer));
457   if (!DebugCompilationDir.empty())
458     Ctx.setCompilationDir(DebugCompilationDir);
459   if (!MainFileName.empty())
460     Ctx.setMainFileName(MainFileName);
461
462   // Package up features to be passed to target/subtarget
463   std::string FeaturesStr;
464   if (MAttrs.size()) {
465     SubtargetFeatures Features;
466     for (unsigned i = 0; i != MAttrs.size(); ++i)
467       Features.AddFeature(MAttrs[i]);
468     FeaturesStr = Features.getString();
469   }
470
471   std::unique_ptr<tool_output_file> Out = GetOutputStream();
472   if (!Out)
473     return 1;
474
475   std::unique_ptr<buffer_ostream> BOS;
476   raw_pwrite_stream *OS = &Out->os();
477   std::unique_ptr<MCStreamer> Str;
478
479   std::unique_ptr<MCInstrInfo> MCII(TheTarget->createMCInstrInfo());
480   std::unique_ptr<MCSubtargetInfo> STI(
481       TheTarget->createMCSubtargetInfo(TripleName, MCPU, FeaturesStr));
482
483   MCInstPrinter *IP = nullptr;
484   if (FileType == OFT_AssemblyFile) {
485     IP = TheTarget->createMCInstPrinter(Triple(TripleName), OutputAsmVariant,
486                                         *MAI, *MCII, *MRI);
487
488     // Set the display preference for hex vs. decimal immediates.
489     IP->setPrintImmHex(PrintImmHex);
490
491     // Set up the AsmStreamer.
492     MCCodeEmitter *CE = nullptr;
493     MCAsmBackend *MAB = nullptr;
494     if (ShowEncoding) {
495       CE = TheTarget->createMCCodeEmitter(*MCII, *MRI, Ctx);
496       MAB = TheTarget->createMCAsmBackend(*MRI, TripleName, MCPU);
497     }
498     auto FOut = llvm::make_unique<formatted_raw_ostream>(*OS);
499     Str.reset(TheTarget->createAsmStreamer(
500         Ctx, std::move(FOut), /*asmverbose*/ true,
501         /*useDwarfDirectory*/ true, IP, CE, MAB, ShowInst));
502
503   } else if (FileType == OFT_Null) {
504     Str.reset(TheTarget->createNullStreamer(Ctx));
505   } else {
506     assert(FileType == OFT_ObjectFile && "Invalid file type!");
507
508     // Don't waste memory on names of temp labels.
509     Ctx.setUseNamesOnTempLabels(false);
510
511     if (!Out->os().supportsSeeking()) {
512       BOS = make_unique<buffer_ostream>(Out->os());
513       OS = BOS.get();
514     }
515
516     MCCodeEmitter *CE = TheTarget->createMCCodeEmitter(*MCII, *MRI, Ctx);
517     MCAsmBackend *MAB = TheTarget->createMCAsmBackend(*MRI, TripleName, MCPU);
518     Str.reset(TheTarget->createMCObjectStreamer(TheTriple, Ctx, *MAB, *OS, CE,
519                                                 *STI, RelaxAll,
520                                                 /*DWARFMustBeAtTheEnd*/ false));
521     if (NoExecStack)
522       Str->InitSections(true);
523   }
524
525   int Res = 1;
526   bool disassemble = false;
527   switch (Action) {
528   case AC_AsLex:
529     Res = AsLexInput(SrcMgr, *MAI, Out->os());
530     break;
531   case AC_Assemble:
532     Res = AssembleInput(ProgName, TheTarget, SrcMgr, Ctx, *Str, *MAI, *STI,
533                         *MCII, MCOptions);
534     break;
535   case AC_MDisassemble:
536     assert(IP && "Expected assembly output");
537     IP->setUseMarkup(1);
538     disassemble = true;
539     break;
540   case AC_Disassemble:
541     disassemble = true;
542     break;
543   }
544   if (disassemble)
545     Res = Disassembler::disassemble(*TheTarget, TripleName, *STI, *Str,
546                                     *Buffer, SrcMgr, Out->os());
547
548   // Keep output if no errors.
549   if (Res == 0) Out->keep();
550   return Res;
551 }