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