OSDN Git Service

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