]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/llvm-mc/llvm-mc.cpp
Merge llvm, clang, compiler-rt, libc++, libunwind, lld, lldb and openmp
[FreeBSD/FreeBSD.git] / contrib / llvm / tools / llvm-mc / llvm-mc.cpp
1 //===-- llvm-mc.cpp - Machine Code Hacking Driver ---------------*- C++ -*-===//
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/MCCodeEmitter.h"
19 #include "llvm/MC/MCContext.h"
20 #include "llvm/MC/MCInstPrinter.h"
21 #include "llvm/MC/MCInstrInfo.h"
22 #include "llvm/MC/MCObjectFileInfo.h"
23 #include "llvm/MC/MCObjectWriter.h"
24 #include "llvm/MC/MCParser/AsmLexer.h"
25 #include "llvm/MC/MCParser/MCTargetAsmParser.h"
26 #include "llvm/MC/MCRegisterInfo.h"
27 #include "llvm/MC/MCStreamer.h"
28 #include "llvm/MC/MCSubtargetInfo.h"
29 #include "llvm/MC/MCTargetOptionsCommandFlags.inc"
30 #include "llvm/Support/CommandLine.h"
31 #include "llvm/Support/Compression.h"
32 #include "llvm/Support/FileUtilities.h"
33 #include "llvm/Support/FormattedStream.h"
34 #include "llvm/Support/Host.h"
35 #include "llvm/Support/InitLLVM.h"
36 #include "llvm/Support/MemoryBuffer.h"
37 #include "llvm/Support/SourceMgr.h"
38 #include "llvm/Support/TargetRegistry.h"
39 #include "llvm/Support/TargetSelect.h"
40 #include "llvm/Support/ToolOutputFile.h"
41 #include "llvm/Support/WithColor.h"
42
43 using namespace llvm;
44
45 static cl::opt<std::string>
46 InputFilename(cl::Positional, cl::desc("<input file>"), cl::init("-"));
47
48 static cl::opt<std::string> OutputFilename("o", cl::desc("Output filename"),
49                                            cl::value_desc("filename"),
50                                            cl::init("-"));
51
52 static cl::opt<std::string> SplitDwarfFile("split-dwarf-file",
53                                            cl::desc("DWO output filename"),
54                                            cl::value_desc("filename"));
55
56 static cl::opt<bool>
57 ShowEncoding("show-encoding", cl::desc("Show instruction encodings"));
58
59 static cl::opt<bool> RelaxELFRel(
60     "relax-relocations", cl::init(true),
61     cl::desc("Emit R_X86_64_GOTPCRELX instead of R_X86_64_GOTPCREL"));
62
63 static cl::opt<DebugCompressionType> CompressDebugSections(
64     "compress-debug-sections", cl::ValueOptional,
65     cl::init(DebugCompressionType::None),
66     cl::desc("Choose DWARF debug sections compression:"),
67     cl::values(clEnumValN(DebugCompressionType::None, "none", "No compression"),
68                clEnumValN(DebugCompressionType::Z, "zlib",
69                           "Use zlib compression"),
70                clEnumValN(DebugCompressionType::GNU, "zlib-gnu",
71                           "Use zlib-gnu compression (deprecated)")));
72
73 static cl::opt<bool>
74 ShowInst("show-inst", cl::desc("Show internal instruction representation"));
75
76 static cl::opt<bool>
77 ShowInstOperands("show-inst-operands",
78                  cl::desc("Show instructions operands as parsed"));
79
80 static cl::opt<unsigned>
81 OutputAsmVariant("output-asm-variant",
82                  cl::desc("Syntax variant to use for output printing"));
83
84 static cl::opt<bool>
85 PrintImmHex("print-imm-hex", cl::init(false),
86             cl::desc("Prefer hex format for immediate values"));
87
88 static cl::list<std::string>
89 DefineSymbol("defsym", cl::desc("Defines a symbol to be an integer constant"));
90
91 static cl::opt<bool>
92     PreserveComments("preserve-comments",
93                      cl::desc("Preserve Comments in outputted assembly"));
94
95 enum OutputFileType {
96   OFT_Null,
97   OFT_AssemblyFile,
98   OFT_ObjectFile
99 };
100 static cl::opt<OutputFileType>
101 FileType("filetype", cl::init(OFT_AssemblyFile),
102   cl::desc("Choose an output file type:"),
103   cl::values(
104        clEnumValN(OFT_AssemblyFile, "asm",
105                   "Emit an assembly ('.s') file"),
106        clEnumValN(OFT_Null, "null",
107                   "Don't emit anything (for timing purposes)"),
108        clEnumValN(OFT_ObjectFile, "obj",
109                   "Emit a native object ('.o') file")));
110
111 static cl::list<std::string>
112 IncludeDirs("I", cl::desc("Directory of include files"),
113             cl::value_desc("directory"), cl::Prefix);
114
115 static cl::opt<std::string>
116 ArchName("arch", cl::desc("Target arch to assemble for, "
117                           "see -version for available targets"));
118
119 static cl::opt<std::string>
120 TripleName("triple", cl::desc("Target triple to assemble for, "
121                               "see -version for available targets"));
122
123 static cl::opt<std::string>
124 MCPU("mcpu",
125      cl::desc("Target a specific cpu type (-mcpu=help for details)"),
126      cl::value_desc("cpu-name"),
127      cl::init(""));
128
129 static cl::list<std::string>
130 MAttrs("mattr",
131   cl::CommaSeparated,
132   cl::desc("Target specific attributes (-mattr=help for details)"),
133   cl::value_desc("a1,+a2,-a3,..."));
134
135 static cl::opt<bool> PIC("position-independent",
136                          cl::desc("Position independent"), cl::init(false));
137
138 static cl::opt<bool>
139     LargeCodeModel("large-code-model",
140                    cl::desc("Create cfi directives that assume the code might "
141                             "be more than 2gb away"));
142
143 static cl::opt<bool>
144 NoInitialTextSection("n", cl::desc("Don't assume assembly file starts "
145                                    "in the text section"));
146
147 static cl::opt<bool>
148 GenDwarfForAssembly("g", cl::desc("Generate dwarf debugging info for assembly "
149                                   "source files"));
150
151 static cl::opt<std::string>
152 DebugCompilationDir("fdebug-compilation-dir",
153                     cl::desc("Specifies the debug info's compilation dir"));
154
155 static cl::list<std::string>
156 DebugPrefixMap("fdebug-prefix-map",
157                cl::desc("Map file source paths in debug info"),
158                cl::value_desc("= separated key-value pairs"));
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> LexMasmIntegers(
168     "masm-integers",
169     cl::desc("Enable binary and hex masm integers (0b110 and 0ABCh)"));
170
171 static cl::opt<bool> NoExecStack("no-exec-stack",
172                                  cl::desc("File doesn't need an exec stack"));
173
174 enum ActionType {
175   AC_AsLex,
176   AC_Assemble,
177   AC_Disassemble,
178   AC_MDisassemble,
179 };
180
181 static cl::opt<ActionType>
182 Action(cl::desc("Action to perform:"),
183        cl::init(AC_Assemble),
184        cl::values(clEnumValN(AC_AsLex, "as-lex",
185                              "Lex tokens from a .s file"),
186                   clEnumValN(AC_Assemble, "assemble",
187                              "Assemble a .s file (default)"),
188                   clEnumValN(AC_Disassemble, "disassemble",
189                              "Disassemble strings of hex bytes"),
190                   clEnumValN(AC_MDisassemble, "mdis",
191                              "Marked up disassembly of strings of hex bytes")));
192
193 static const Target *GetTarget(const char *ProgName) {
194   // Figure out the target triple.
195   if (TripleName.empty())
196     TripleName = sys::getDefaultTargetTriple();
197   Triple TheTriple(Triple::normalize(TripleName));
198
199   // Get the target specific parser.
200   std::string Error;
201   const Target *TheTarget = TargetRegistry::lookupTarget(ArchName, TheTriple,
202                                                          Error);
203   if (!TheTarget) {
204     WithColor::error(errs(), ProgName) << Error;
205     return nullptr;
206   }
207
208   // Update the triple name and return the found target.
209   TripleName = TheTriple.getTriple();
210   return TheTarget;
211 }
212
213 static std::unique_ptr<ToolOutputFile> GetOutputStream(StringRef Path) {
214   std::error_code EC;
215   auto Out = llvm::make_unique<ToolOutputFile>(Path, EC, sys::fs::F_None);
216   if (EC) {
217     WithColor::error() << EC.message() << '\n';
218     return nullptr;
219   }
220
221   return Out;
222 }
223
224 static std::string DwarfDebugFlags;
225 static void setDwarfDebugFlags(int argc, char **argv) {
226   if (!getenv("RC_DEBUG_OPTIONS"))
227     return;
228   for (int i = 0; i < argc; i++) {
229     DwarfDebugFlags += argv[i];
230     if (i + 1 < argc)
231       DwarfDebugFlags += " ";
232   }
233 }
234
235 static std::string DwarfDebugProducer;
236 static void setDwarfDebugProducer() {
237   if(!getenv("DEBUG_PRODUCER"))
238     return;
239   DwarfDebugProducer += getenv("DEBUG_PRODUCER");
240 }
241
242 static int AsLexInput(SourceMgr &SrcMgr, MCAsmInfo &MAI,
243                       raw_ostream &OS) {
244
245   AsmLexer Lexer(MAI);
246   Lexer.setBuffer(SrcMgr.getMemoryBuffer(SrcMgr.getMainFileID())->getBuffer());
247
248   bool Error = false;
249   while (Lexer.Lex().isNot(AsmToken::Eof)) {
250     Lexer.getTok().dump(OS);
251     OS << "\n";
252     if (Lexer.getTok().getKind() == AsmToken::Error)
253       Error = true;
254   }
255
256   return Error;
257 }
258
259 static int fillCommandLineSymbols(MCAsmParser &Parser) {
260   for (auto &I: DefineSymbol) {
261     auto Pair = StringRef(I).split('=');
262     auto Sym = Pair.first;
263     auto Val = Pair.second;
264
265     if (Sym.empty() || Val.empty()) {
266       WithColor::error() << "defsym must be of the form: sym=value: " << I
267                          << "\n";
268       return 1;
269     }
270     int64_t Value;
271     if (Val.getAsInteger(0, Value)) {
272       WithColor::error() << "value is not an integer: " << Val << "\n";
273       return 1;
274     }
275     Parser.getContext().setSymbolValue(Parser.getStreamer(), Sym, Value);
276   }
277   return 0;
278 }
279
280 static int AssembleInput(const char *ProgName, const Target *TheTarget,
281                          SourceMgr &SrcMgr, MCContext &Ctx, MCStreamer &Str,
282                          MCAsmInfo &MAI, MCSubtargetInfo &STI,
283                          MCInstrInfo &MCII, MCTargetOptions &MCOptions) {
284   std::unique_ptr<MCAsmParser> Parser(
285       createMCAsmParser(SrcMgr, Ctx, Str, MAI));
286   std::unique_ptr<MCTargetAsmParser> TAP(
287       TheTarget->createMCAsmParser(STI, *Parser, MCII, MCOptions));
288
289   if (!TAP) {
290     WithColor::error(errs(), ProgName)
291         << "this target does not support assembly parsing.\n";
292     return 1;
293   }
294
295   int SymbolResult = fillCommandLineSymbols(*Parser);
296   if(SymbolResult)
297     return SymbolResult;
298   Parser->setShowParsedOperands(ShowInstOperands);
299   Parser->setTargetParser(*TAP);
300   Parser->getLexer().setLexMasmIntegers(LexMasmIntegers);
301
302   int Res = Parser->Run(NoInitialTextSection);
303
304   return Res;
305 }
306
307 int main(int argc, char **argv) {
308   InitLLVM X(argc, argv);
309
310   // Initialize targets and assembly printers/parsers.
311   llvm::InitializeAllTargetInfos();
312   llvm::InitializeAllTargetMCs();
313   llvm::InitializeAllAsmParsers();
314   llvm::InitializeAllDisassemblers();
315
316   // Register the target printer for --version.
317   cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
318
319   cl::ParseCommandLineOptions(argc, argv, "llvm machine code playground\n");
320   MCTargetOptions MCOptions = InitMCTargetOptionsFromFlags();
321   setDwarfDebugFlags(argc, argv);
322
323   setDwarfDebugProducer();
324
325   const char *ProgName = argv[0];
326   const Target *TheTarget = GetTarget(ProgName);
327   if (!TheTarget)
328     return 1;
329   // Now that GetTarget() has (potentially) replaced TripleName, it's safe to
330   // construct the Triple object.
331   Triple TheTriple(TripleName);
332
333   ErrorOr<std::unique_ptr<MemoryBuffer>> BufferPtr =
334       MemoryBuffer::getFileOrSTDIN(InputFilename);
335   if (std::error_code EC = BufferPtr.getError()) {
336     WithColor::error(errs(), ProgName)
337         << InputFilename << ": " << EC.message() << '\n';
338     return 1;
339   }
340   MemoryBuffer *Buffer = BufferPtr->get();
341
342   SourceMgr SrcMgr;
343
344   // Tell SrcMgr about this buffer, which is what the parser will pick up.
345   SrcMgr.AddNewSourceBuffer(std::move(*BufferPtr), SMLoc());
346
347   // Record the location of the include directories so that the lexer can find
348   // it later.
349   SrcMgr.setIncludeDirs(IncludeDirs);
350
351   std::unique_ptr<MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TripleName));
352   assert(MRI && "Unable to create target register info!");
353
354   std::unique_ptr<MCAsmInfo> MAI(TheTarget->createMCAsmInfo(*MRI, TripleName));
355   assert(MAI && "Unable to create target asm info!");
356
357   MAI->setRelaxELFRelocations(RelaxELFRel);
358
359   if (CompressDebugSections != DebugCompressionType::None) {
360     if (!zlib::isAvailable()) {
361       WithColor::error(errs(), ProgName)
362           << "build tools with zlib to enable -compress-debug-sections";
363       return 1;
364     }
365     MAI->setCompressDebugSections(CompressDebugSections);
366   }
367   MAI->setPreserveAsmComments(PreserveComments);
368
369   // FIXME: This is not pretty. MCContext has a ptr to MCObjectFileInfo and
370   // MCObjectFileInfo needs a MCContext reference in order to initialize itself.
371   MCObjectFileInfo MOFI;
372   MCContext Ctx(MAI.get(), MRI.get(), &MOFI, &SrcMgr);
373   MOFI.InitMCObjectFileInfo(TheTriple, PIC, Ctx, LargeCodeModel);
374
375   if (SaveTempLabels)
376     Ctx.setAllowTemporaryLabels(false);
377
378   Ctx.setGenDwarfForAssembly(GenDwarfForAssembly);
379   // Default to 4 for dwarf version.
380   unsigned DwarfVersion = MCOptions.DwarfVersion ? MCOptions.DwarfVersion : 4;
381   if (DwarfVersion < 2 || DwarfVersion > 5) {
382     errs() << ProgName << ": Dwarf version " << DwarfVersion
383            << " is not supported." << '\n';
384     return 1;
385   }
386   Ctx.setDwarfVersion(DwarfVersion);
387   if (!DwarfDebugFlags.empty())
388     Ctx.setDwarfDebugFlags(StringRef(DwarfDebugFlags));
389   if (!DwarfDebugProducer.empty())
390     Ctx.setDwarfDebugProducer(StringRef(DwarfDebugProducer));
391   if (!DebugCompilationDir.empty())
392     Ctx.setCompilationDir(DebugCompilationDir);
393   else {
394     // If no compilation dir is set, try to use the current directory.
395     SmallString<128> CWD;
396     if (!sys::fs::current_path(CWD))
397       Ctx.setCompilationDir(CWD);
398   }
399   for (const auto &Arg : DebugPrefixMap) {
400     const auto &KV = StringRef(Arg).split('=');
401     Ctx.addDebugPrefixMapEntry(KV.first, KV.second);
402   }
403   if (!MainFileName.empty())
404     Ctx.setMainFileName(MainFileName);
405   if (GenDwarfForAssembly && DwarfVersion >= 5) {
406     // DWARF v5 needs the root file as well as the compilation directory.
407     // If we find a '.file 0' directive that will supersede these values.
408     MD5 Hash;
409     MD5::MD5Result *Cksum =
410         (MD5::MD5Result *)Ctx.allocate(sizeof(MD5::MD5Result), 1);
411     Hash.update(Buffer->getBuffer());
412     Hash.final(*Cksum);
413     Ctx.setMCLineTableRootFile(
414         /*CUID=*/0, Ctx.getCompilationDir(),
415         !MainFileName.empty() ? MainFileName : InputFilename, Cksum, None);
416   }
417
418   // Package up features to be passed to target/subtarget
419   std::string FeaturesStr;
420   if (MAttrs.size()) {
421     SubtargetFeatures Features;
422     for (unsigned i = 0; i != MAttrs.size(); ++i)
423       Features.AddFeature(MAttrs[i]);
424     FeaturesStr = Features.getString();
425   }
426
427   std::unique_ptr<ToolOutputFile> Out = GetOutputStream(OutputFilename);
428   if (!Out)
429     return 1;
430
431   std::unique_ptr<ToolOutputFile> DwoOut;
432   if (!SplitDwarfFile.empty()) {
433     if (FileType != OFT_ObjectFile) {
434       WithColor::error() << "dwo output only supported with object files\n";
435       return 1;
436     }
437     DwoOut = GetOutputStream(SplitDwarfFile);
438     if (!DwoOut)
439       return 1;
440   }
441
442   std::unique_ptr<buffer_ostream> BOS;
443   raw_pwrite_stream *OS = &Out->os();
444   std::unique_ptr<MCStreamer> Str;
445
446   std::unique_ptr<MCInstrInfo> MCII(TheTarget->createMCInstrInfo());
447   std::unique_ptr<MCSubtargetInfo> STI(
448       TheTarget->createMCSubtargetInfo(TripleName, MCPU, FeaturesStr));
449
450   MCInstPrinter *IP = nullptr;
451   if (FileType == OFT_AssemblyFile) {
452     IP = TheTarget->createMCInstPrinter(Triple(TripleName), OutputAsmVariant,
453                                         *MAI, *MCII, *MRI);
454
455     if (!IP) {
456       WithColor::error()
457           << "unable to create instruction printer for target triple '"
458           << TheTriple.normalize() << "' with assembly variant "
459           << OutputAsmVariant << ".\n";
460       return 1;
461     }
462
463     // Set the display preference for hex vs. decimal immediates.
464     IP->setPrintImmHex(PrintImmHex);
465
466     // Set up the AsmStreamer.
467     std::unique_ptr<MCCodeEmitter> CE;
468     if (ShowEncoding)
469       CE.reset(TheTarget->createMCCodeEmitter(*MCII, *MRI, Ctx));
470
471     std::unique_ptr<MCAsmBackend> MAB(
472         TheTarget->createMCAsmBackend(*STI, *MRI, MCOptions));
473     auto FOut = llvm::make_unique<formatted_raw_ostream>(*OS);
474     Str.reset(
475         TheTarget->createAsmStreamer(Ctx, std::move(FOut), /*asmverbose*/ true,
476                                      /*useDwarfDirectory*/ true, IP,
477                                      std::move(CE), std::move(MAB), ShowInst));
478
479   } else if (FileType == OFT_Null) {
480     Str.reset(TheTarget->createNullStreamer(Ctx));
481   } else {
482     assert(FileType == OFT_ObjectFile && "Invalid file type!");
483
484     // Don't waste memory on names of temp labels.
485     Ctx.setUseNamesOnTempLabels(false);
486
487     if (!Out->os().supportsSeeking()) {
488       BOS = make_unique<buffer_ostream>(Out->os());
489       OS = BOS.get();
490     }
491
492     MCCodeEmitter *CE = TheTarget->createMCCodeEmitter(*MCII, *MRI, Ctx);
493     MCAsmBackend *MAB = TheTarget->createMCAsmBackend(*STI, *MRI, MCOptions);
494     Str.reset(TheTarget->createMCObjectStreamer(
495         TheTriple, Ctx, std::unique_ptr<MCAsmBackend>(MAB),
496         DwoOut ? MAB->createDwoObjectWriter(*OS, DwoOut->os())
497                : MAB->createObjectWriter(*OS),
498         std::unique_ptr<MCCodeEmitter>(CE), *STI, MCOptions.MCRelaxAll,
499         MCOptions.MCIncrementalLinkerCompatible,
500         /*DWARFMustBeAtTheEnd*/ false));
501     if (NoExecStack)
502       Str->InitSections(true);
503   }
504
505   // Use Assembler information for parsing.
506   Str->setUseAssemblerInfoForParsing(true);
507
508   int Res = 1;
509   bool disassemble = false;
510   switch (Action) {
511   case AC_AsLex:
512     Res = AsLexInput(SrcMgr, *MAI, Out->os());
513     break;
514   case AC_Assemble:
515     Res = AssembleInput(ProgName, TheTarget, SrcMgr, Ctx, *Str, *MAI, *STI,
516                         *MCII, MCOptions);
517     break;
518   case AC_MDisassemble:
519     assert(IP && "Expected assembly output");
520     IP->setUseMarkup(1);
521     disassemble = true;
522     break;
523   case AC_Disassemble:
524     disassemble = true;
525     break;
526   }
527   if (disassemble)
528     Res = Disassembler::disassemble(*TheTarget, TripleName, *STI, *Str,
529                                     *Buffer, SrcMgr, Out->os());
530
531   // Keep output if no errors.
532   if (Res == 0) {
533     Out->keep();
534     if (DwoOut)
535       DwoOut->keep();
536   }
537   return Res;
538 }