blob: 497fb1987764e4a36f8ef2025b9769a55030923b [file] [log] [blame]
Eugene Zelenkoffec81c2015-11-04 22:32:32 +00001//===-- llvm-mc.cpp - Machine Code Hacking Driver ---------------*- C++ -*-===//
Chris Lattner8dd8a522009-06-18 23:04:45 +00002//
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//
Chris Lattnerc7ab9532009-06-18 23:05:21 +000010// This utility is a simple driver that allows command line hacking on machine
11// code.
Chris Lattner8dd8a522009-06-18 23:04:45 +000012//
13//===----------------------------------------------------------------------===//
14
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000015#include "Disassembler.h"
Evan Cheng5928e692011-07-25 23:24:55 +000016#include "llvm/MC/MCAsmBackend.h"
Craig Toppera6e377f2012-04-15 22:00:22 +000017#include "llvm/MC/MCAsmInfo.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000018#include "llvm/MC/MCContext.h"
Chris Lattner11b2fc92009-09-14 03:02:37 +000019#include "llvm/MC/MCInstPrinter.h"
Evan Chengc5e6d2f2011-07-11 03:57:24 +000020#include "llvm/MC/MCInstrInfo.h"
Evan Cheng76792992011-07-20 05:58:47 +000021#include "llvm/MC/MCObjectFileInfo.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000022#include "llvm/MC/MCParser/AsmLexer.h"
Benjamin Kramerb3e8a6d2016-01-27 10:01:28 +000023#include "llvm/MC/MCParser/MCTargetAsmParser.h"
Evan Cheng76792992011-07-20 05:58:47 +000024#include "llvm/MC/MCRegisterInfo.h"
Chris Lattner6c203912009-08-10 18:15:01 +000025#include "llvm/MC/MCSectionMachO.h"
Chris Lattner92ffdd12009-06-24 00:52:40 +000026#include "llvm/MC/MCStreamer.h"
Evan Cheng91111d22011-07-09 05:47:46 +000027#include "llvm/MC/MCSubtargetInfo.h"
Evgeniy Stepanov0a951b72014-04-23 11:16:03 +000028#include "llvm/MC/MCTargetOptionsCommandFlags.h"
Chris Lattner8dd8a522009-06-18 23:04:45 +000029#include "llvm/Support/CommandLine.h"
David Blaikie9c3857c2014-03-28 21:00:25 +000030#include "llvm/Support/Compression.h"
Dan Gohman268b0f42010-08-20 01:07:01 +000031#include "llvm/Support/FileUtilities.h"
Daniel Dunbar80d484e2009-08-14 03:48:55 +000032#include "llvm/Support/FormattedStream.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000033#include "llvm/Support/Host.h"
Chris Lattner8dd8a522009-06-18 23:04:45 +000034#include "llvm/Support/ManagedStatic.h"
35#include "llvm/Support/MemoryBuffer.h"
36#include "llvm/Support/PrettyStackTrace.h"
Michael J. Spencer447762d2010-11-29 18:16:10 +000037#include "llvm/Support/Signals.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000038#include "llvm/Support/SourceMgr.h"
Evan Cheng2bb40352011-08-24 18:08:43 +000039#include "llvm/Support/TargetRegistry.h"
40#include "llvm/Support/TargetSelect.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000041#include "llvm/Support/ToolOutputFile.h"
Eugene Zelenkoffec81c2015-11-04 22:32:32 +000042
Chris Lattner8dd8a522009-06-18 23:04:45 +000043using namespace llvm;
44
45static cl::opt<std::string>
46InputFilename(cl::Positional, cl::desc("<input file>"), cl::init("-"));
47
48static cl::opt<std::string>
49OutputFilename("o", cl::desc("Output filename"),
50 cl::value_desc("filename"));
51
Daniel Dunbard18dd1d2009-08-27 07:56:39 +000052static cl::opt<bool>
53ShowEncoding("show-encoding", cl::desc("Show instruction encodings"));
54
Rafael Espindolae021e852016-06-17 17:04:56 +000055static cl::opt<bool> RelaxELFRel(
56 "relax-relocations", cl::init(true),
57 cl::desc("Emit R_X86_64_GOTPCRELX instead of R_X86_64_GOTPCREL"));
Rafael Espindola9768d732016-05-29 01:11:00 +000058
George Rimarc91e38c2016-05-27 12:27:32 +000059static cl::opt<DebugCompressionType>
60CompressDebugSections("compress-debug-sections", cl::ValueOptional,
61 cl::init(DebugCompressionType::DCT_None),
62 cl::desc("Choose DWARF debug sections compression:"),
63 cl::values(
64 clEnumValN(DebugCompressionType::DCT_None, "none",
65 "No compression"),
66 clEnumValN(DebugCompressionType::DCT_Zlib, "zlib",
67 "Use zlib compression"),
68 clEnumValN(DebugCompressionType::DCT_ZlibGnu, "zlib-gnu",
Mehdi Amini732afdd2016-10-08 19:41:06 +000069 "Use zlib-gnu compression (deprecated)")));
David Blaikie7400a972014-03-27 20:45:58 +000070
71static cl::opt<bool>
Daniel Dunbare3ee3322010-02-03 18:18:30 +000072ShowInst("show-inst", cl::desc("Show internal instruction representation"));
73
Daniel Dunbar2eca0252010-08-11 06:37:09 +000074static cl::opt<bool>
75ShowInstOperands("show-inst-operands",
76 cl::desc("Show instructions operands as parsed"));
77
Chris Lattner44790342009-09-20 07:17:49 +000078static cl::opt<unsigned>
79OutputAsmVariant("output-asm-variant",
80 cl::desc("Syntax variant to use for output printing"));
81
Jim Grosbach3fdf7cf2014-06-11 20:26:40 +000082static cl::opt<bool>
83PrintImmHex("print-imm-hex", cl::init(false),
84 cl::desc("Prefer hex format for immediate values"));
85
Colin LeMahieu229a1e62015-06-07 01:46:24 +000086static cl::list<std::string>
87DefineSymbol("defsym", cl::desc("Defines a symbol to be an integer constant"));
88
Nirav Dave53a72f42016-07-11 12:42:14 +000089static cl::opt<bool>
90 PreserveComments("preserve-comments",
91 cl::desc("Preserve Comments in outputted assembly"));
92
Daniel Dunbar3016db32009-08-21 09:11:24 +000093enum OutputFileType {
Daniel Dunbarb09b8902010-03-23 23:47:12 +000094 OFT_Null,
Daniel Dunbar3016db32009-08-21 09:11:24 +000095 OFT_AssemblyFile,
96 OFT_ObjectFile
97};
98static cl::opt<OutputFileType>
99FileType("filetype", cl::init(OFT_AssemblyFile),
100 cl::desc("Choose an output file type:"),
101 cl::values(
102 clEnumValN(OFT_AssemblyFile, "asm",
103 "Emit an assembly ('.s') file"),
Daniel Dunbarb09b8902010-03-23 23:47:12 +0000104 clEnumValN(OFT_Null, "null",
105 "Don't emit anything (for timing purposes)"),
Daniel Dunbar3016db32009-08-21 09:11:24 +0000106 clEnumValN(OFT_ObjectFile, "obj",
Mehdi Amini732afdd2016-10-08 19:41:06 +0000107 "Emit a native object ('.o') file")));
Daniel Dunbar3016db32009-08-21 09:11:24 +0000108
Chris Lattnerd70e15b42009-06-21 05:22:37 +0000109static cl::list<std::string>
110IncludeDirs("I", cl::desc("Directory of include files"),
111 cl::value_desc("directory"), cl::Prefix);
Chris Lattner8dd8a522009-06-18 23:04:45 +0000112
Daniel Dunbar8c6bad22009-07-17 22:38:58 +0000113static cl::opt<std::string>
Daniel Dunbar46892112010-03-13 02:20:38 +0000114ArchName("arch", cl::desc("Target arch to assemble for, "
Bill Wendlinge3031142011-06-17 20:35:21 +0000115 "see -version for available targets"));
Daniel Dunbar46892112010-03-13 02:20:38 +0000116
117static cl::opt<std::string>
Nick Lewyckyb2449092009-11-01 22:07:54 +0000118TripleName("triple", cl::desc("Target triple to assemble for, "
Daniel Dunbar46892112010-03-13 02:20:38 +0000119 "see -version for available targets"));
Daniel Dunbar8c6bad22009-07-17 22:38:58 +0000120
Jim Grosbach685b7732010-10-30 15:57:50 +0000121static cl::opt<std::string>
122MCPU("mcpu",
123 cl::desc("Target a specific cpu type (-mcpu=help for details)"),
124 cl::value_desc("cpu-name"),
125 cl::init(""));
126
James Molloy4c493e82011-09-07 17:24:38 +0000127static cl::list<std::string>
128MAttrs("mattr",
129 cl::CommaSeparated,
130 cl::desc("Target specific attributes (-mattr=help for details)"),
131 cl::value_desc("a1,+a2,-a3,..."));
132
Rafael Espindola699281c2016-05-18 11:58:50 +0000133static cl::opt<bool> PIC("position-independent",
134 cl::desc("Position independent"), cl::init(false));
Evan Cheng2129f592011-07-19 06:37:02 +0000135
Evan Chengefd9b422011-07-20 07:51:56 +0000136static cl::opt<llvm::CodeModel::Model>
137CMModel("code-model",
138 cl::desc("Choose code model"),
139 cl::init(CodeModel::Default),
140 cl::values(clEnumValN(CodeModel::Default, "default",
141 "Target default code model"),
142 clEnumValN(CodeModel::Small, "small",
143 "Small code model"),
144 clEnumValN(CodeModel::Kernel, "kernel",
145 "Kernel code model"),
146 clEnumValN(CodeModel::Medium, "medium",
147 "Medium code model"),
148 clEnumValN(CodeModel::Large, "large",
Mehdi Amini732afdd2016-10-08 19:41:06 +0000149 "Large code model")));
Evan Chengefd9b422011-07-20 07:51:56 +0000150
Daniel Dunbar322fec62010-03-13 02:20:57 +0000151static cl::opt<bool>
Bill Wendlinge3031142011-06-17 20:35:21 +0000152NoInitialTextSection("n", cl::desc("Don't assume assembly file starts "
153 "in the text section"));
Daniel Dunbar322fec62010-03-13 02:20:57 +0000154
Daniel Dunbar4ee0d032011-03-28 22:49:15 +0000155static cl::opt<bool>
Kevin Enderby6469fc22011-11-01 22:27:22 +0000156GenDwarfForAssembly("g", cl::desc("Generate dwarf debugging info for assembly "
157 "source files"));
158
Chandler Carruth10700aad2012-12-17 21:32:42 +0000159static cl::opt<std::string>
160DebugCompilationDir("fdebug-compilation-dir",
161 cl::desc("Specifies the debug info's compilation dir"));
162
Eric Christopher906da232012-12-18 00:31:01 +0000163static cl::opt<std::string>
164MainFileName("main-file-name",
165 cl::desc("Specifies the name we should consider the input file"));
166
Eric Christopherdc3e9c72014-05-21 00:20:01 +0000167static cl::opt<bool> SaveTempLabels("save-temp-labels",
168 cl::desc("Don't discard temporary labels"));
169
Eric Christopher472cee32014-05-21 21:05:09 +0000170static cl::opt<bool> NoExecStack("no-exec-stack",
171 cl::desc("File doesn't need an exec stack"));
172
Chris Lattnerd70e15b42009-06-21 05:22:37 +0000173enum ActionType {
Chris Lattnerb0133452009-06-21 20:16:42 +0000174 AC_AsLex,
Sean Callanan7e645502009-12-17 01:49:59 +0000175 AC_Assemble,
Sean Callanan2d03d3a2010-04-12 19:43:00 +0000176 AC_Disassemble,
Kevin Enderby168ffb32012-12-05 18:13:19 +0000177 AC_MDisassemble,
Chris Lattnerd70e15b42009-06-21 05:22:37 +0000178};
Chris Lattner8dd8a522009-06-18 23:04:45 +0000179
Chris Lattnerd70e15b42009-06-21 05:22:37 +0000180static cl::opt<ActionType>
181Action(cl::desc("Action to perform:"),
Chris Lattnerb0133452009-06-21 20:16:42 +0000182 cl::init(AC_Assemble),
183 cl::values(clEnumValN(AC_AsLex, "as-lex",
184 "Lex tokens from a .s file"),
185 clEnumValN(AC_Assemble, "assemble",
Chris Lattnerd70e15b42009-06-21 05:22:37 +0000186 "Assemble a .s file (default)"),
Sean Callanan7e645502009-12-17 01:49:59 +0000187 clEnumValN(AC_Disassemble, "disassemble",
188 "Disassemble strings of hex bytes"),
Kevin Enderby62183c42012-10-22 22:31:46 +0000189 clEnumValN(AC_MDisassemble, "mdis",
Mehdi Amini732afdd2016-10-08 19:41:06 +0000190 "Marked up disassembly of strings of hex bytes")));
Chris Lattnerd70e15b42009-06-21 05:22:37 +0000191
Kevin Enderbyf92f9902009-09-04 21:45:34 +0000192static const Target *GetTarget(const char *ProgName) {
Daniel Dunbar46892112010-03-13 02:20:38 +0000193 // Figure out the target triple.
194 if (TripleName.empty())
Sebastian Pop94441fb2011-11-01 21:32:20 +0000195 TripleName = sys::getDefaultTargetTriple();
Evan Chenge64f0e52011-07-26 19:02:16 +0000196 Triple TheTriple(Triple::normalize(TripleName));
197
Kevin Enderbyfe3d0052012-05-08 23:38:45 +0000198 // 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;
Craig Toppere6cb63e2014-04-25 04:24:47 +0000204 return nullptr;
Daniel Dunbar46892112010-03-13 02:20:38 +0000205 }
206
Kevin Enderbyfe3d0052012-05-08 23:38:45 +0000207 // Update the triple name and return the found target.
Evan Chenge64f0e52011-07-26 19:02:16 +0000208 TripleName = TheTriple.getTriple();
209 return TheTarget;
Kevin Enderbyf92f9902009-09-04 21:45:34 +0000210}
211
Craig Topper8c8ee4d2014-12-12 07:52:16 +0000212static std::unique_ptr<tool_output_file> GetOutputStream() {
Dan Gohman268b0f42010-08-20 01:07:01 +0000213 if (OutputFilename == "")
214 OutputFilename = "-";
215
Rafael Espindola3fd1e992014-08-25 18:16:47 +0000216 std::error_code EC;
Craig Topper8c8ee4d2014-12-12 07:52:16 +0000217 auto Out = llvm::make_unique<tool_output_file>(OutputFilename, EC,
218 sys::fs::F_None);
Rafael Espindola3fd1e992014-08-25 18:16:47 +0000219 if (EC) {
220 errs() << EC.message() << '\n';
Craig Toppere6cb63e2014-04-25 04:24:47 +0000221 return nullptr;
Dan Gohman268b0f42010-08-20 01:07:01 +0000222 }
Dan Gohmana2233f22010-09-01 14:20:41 +0000223
224 return Out;
Dan Gohman268b0f42010-08-20 01:07:01 +0000225}
226
Kevin Enderbye7739d42011-12-09 18:09:40 +0000227static std::string DwarfDebugFlags;
228static void setDwarfDebugFlags(int argc, char **argv) {
229 if (!getenv("RC_DEBUG_OPTIONS"))
230 return;
231 for (int i = 0; i < argc; i++) {
232 DwarfDebugFlags += argv[i];
233 if (i + 1 < argc)
234 DwarfDebugFlags += " ";
235 }
236}
237
Kevin Enderbye82ada62013-01-16 17:46:23 +0000238static std::string DwarfDebugProducer;
Eugene Zelenkoffec81c2015-11-04 22:32:32 +0000239static void setDwarfDebugProducer() {
Kevin Enderbye82ada62013-01-16 17:46:23 +0000240 if(!getenv("DEBUG_PRODUCER"))
241 return;
242 DwarfDebugProducer += getenv("DEBUG_PRODUCER");
243}
244
Eric Christopher23c6d1f2014-06-19 06:22:01 +0000245static int AsLexInput(SourceMgr &SrcMgr, MCAsmInfo &MAI,
Craig Topper4e05fc32014-12-12 07:52:19 +0000246 raw_ostream &OS) {
Chris Lattnerd70e15b42009-06-21 05:22:37 +0000247
Richard Bartondef81b92012-04-16 11:32:10 +0000248 AsmLexer Lexer(MAI);
Rafael Espindola8026bd02014-07-06 14:17:29 +0000249 Lexer.setBuffer(SrcMgr.getMemoryBuffer(SrcMgr.getMainFileID())->getBuffer());
Daniel Dunbar7a85f9c2010-07-18 18:31:28 +0000250
Chris Lattnerb0133452009-06-21 20:16:42 +0000251 bool Error = false;
Daniel Dunbarbc798162009-07-28 16:56:42 +0000252 while (Lexer.Lex().isNot(AsmToken::Eof)) {
Benjamin Kramer4ca41fd2016-06-12 17:30:47 +0000253 const AsmToken &Tok = Lexer.getTok();
Daniel Dunbar1601f552010-10-25 20:18:46 +0000254
255 switch (Tok.getKind()) {
Chris Lattnerb0133452009-06-21 20:16:42 +0000256 default:
Chris Lattner03b80a42011-10-16 05:43:57 +0000257 SrcMgr.PrintMessage(Lexer.getLoc(), SourceMgr::DK_Warning,
258 "unknown token");
Chris Lattnerb0133452009-06-21 20:16:42 +0000259 Error = true;
260 break;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +0000261 case AsmToken::Error:
Chris Lattnerb0133452009-06-21 20:16:42 +0000262 Error = true; // error already printed.
Chris Lattnerd0765612009-06-21 19:21:25 +0000263 break;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +0000264 case AsmToken::Identifier:
Craig Topper4e05fc32014-12-12 07:52:19 +0000265 OS << "identifier: " << Lexer.getTok().getString();
Chris Lattnerc8dfbcb2009-06-21 07:19:10 +0000266 break;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +0000267 case AsmToken::Integer:
Craig Topper4e05fc32014-12-12 07:52:19 +0000268 OS << "int: " << Lexer.getTok().getString();
Chris Lattnerc8dfbcb2009-06-21 07:19:10 +0000269 break;
Daniel Dunbar3068a932010-09-24 01:59:31 +0000270 case AsmToken::Real:
Craig Topper4e05fc32014-12-12 07:52:19 +0000271 OS << "real: " << Lexer.getTok().getString();
Daniel Dunbar3068a932010-09-24 01:59:31 +0000272 break;
Daniel Dunbar25c2c622010-09-16 00:42:35 +0000273 case AsmToken::String:
Craig Topper4e05fc32014-12-12 07:52:19 +0000274 OS << "string: " << Lexer.getTok().getString();
Daniel Dunbar25c2c622010-09-16 00:42:35 +0000275 break;
Daniel Dunbar9c4809a2009-07-01 06:56:54 +0000276
Craig Topper4e05fc32014-12-12 07:52:19 +0000277 case AsmToken::Amp: OS << "Amp"; break;
278 case AsmToken::AmpAmp: OS << "AmpAmp"; break;
279 case AsmToken::At: OS << "At"; break;
280 case AsmToken::Caret: OS << "Caret"; break;
281 case AsmToken::Colon: OS << "Colon"; break;
282 case AsmToken::Comma: OS << "Comma"; break;
283 case AsmToken::Dollar: OS << "Dollar"; break;
284 case AsmToken::Dot: OS << "Dot"; break;
285 case AsmToken::EndOfStatement: OS << "EndOfStatement"; break;
286 case AsmToken::Eof: OS << "Eof"; break;
287 case AsmToken::Equal: OS << "Equal"; break;
288 case AsmToken::EqualEqual: OS << "EqualEqual"; break;
289 case AsmToken::Exclaim: OS << "Exclaim"; break;
290 case AsmToken::ExclaimEqual: OS << "ExclaimEqual"; break;
291 case AsmToken::Greater: OS << "Greater"; break;
292 case AsmToken::GreaterEqual: OS << "GreaterEqual"; break;
293 case AsmToken::GreaterGreater: OS << "GreaterGreater"; break;
294 case AsmToken::Hash: OS << "Hash"; break;
295 case AsmToken::LBrac: OS << "LBrac"; break;
296 case AsmToken::LCurly: OS << "LCurly"; break;
297 case AsmToken::LParen: OS << "LParen"; break;
298 case AsmToken::Less: OS << "Less"; break;
299 case AsmToken::LessEqual: OS << "LessEqual"; break;
300 case AsmToken::LessGreater: OS << "LessGreater"; break;
301 case AsmToken::LessLess: OS << "LessLess"; break;
302 case AsmToken::Minus: OS << "Minus"; break;
303 case AsmToken::Percent: OS << "Percent"; break;
304 case AsmToken::Pipe: OS << "Pipe"; break;
305 case AsmToken::PipePipe: OS << "PipePipe"; break;
306 case AsmToken::Plus: OS << "Plus"; break;
307 case AsmToken::RBrac: OS << "RBrac"; break;
308 case AsmToken::RCurly: OS << "RCurly"; break;
309 case AsmToken::RParen: OS << "RParen"; break;
310 case AsmToken::Slash: OS << "Slash"; break;
311 case AsmToken::Star: OS << "Star"; break;
312 case AsmToken::Tilde: OS << "Tilde"; break;
Daniel Sanders3feeb9c2016-08-08 11:50:25 +0000313 case AsmToken::PercentCall16:
314 OS << "PercentCall16";
315 break;
316 case AsmToken::PercentCall_Hi:
317 OS << "PercentCall_Hi";
318 break;
319 case AsmToken::PercentCall_Lo:
320 OS << "PercentCall_Lo";
321 break;
322 case AsmToken::PercentDtprel_Hi:
323 OS << "PercentDtprel_Hi";
324 break;
325 case AsmToken::PercentDtprel_Lo:
326 OS << "PercentDtprel_Lo";
327 break;
328 case AsmToken::PercentGot:
329 OS << "PercentGot";
330 break;
331 case AsmToken::PercentGot_Disp:
332 OS << "PercentGot_Disp";
333 break;
334 case AsmToken::PercentGot_Hi:
335 OS << "PercentGot_Hi";
336 break;
337 case AsmToken::PercentGot_Lo:
338 OS << "PercentGot_Lo";
339 break;
340 case AsmToken::PercentGot_Ofst:
341 OS << "PercentGot_Ofst";
342 break;
343 case AsmToken::PercentGot_Page:
344 OS << "PercentGot_Page";
345 break;
346 case AsmToken::PercentGottprel:
347 OS << "PercentGottprel";
348 break;
349 case AsmToken::PercentGp_Rel:
350 OS << "PercentGp_Rel";
351 break;
352 case AsmToken::PercentHi:
353 OS << "PercentHi";
354 break;
355 case AsmToken::PercentHigher:
356 OS << "PercentHigher";
357 break;
358 case AsmToken::PercentHighest:
359 OS << "PercentHighest";
360 break;
361 case AsmToken::PercentLo:
362 OS << "PercentLo";
363 break;
364 case AsmToken::PercentNeg:
365 OS << "PercentNeg";
366 break;
367 case AsmToken::PercentPcrel_Hi:
368 OS << "PercentPcrel_Hi";
369 break;
370 case AsmToken::PercentPcrel_Lo:
371 OS << "PercentPcrel_Lo";
372 break;
373 case AsmToken::PercentTlsgd:
374 OS << "PercentTlsgd";
375 break;
376 case AsmToken::PercentTlsldm:
377 OS << "PercentTlsldm";
378 break;
379 case AsmToken::PercentTprel_Hi:
380 OS << "PercentTprel_Hi";
381 break;
382 case AsmToken::PercentTprel_Lo:
383 OS << "PercentTprel_Lo";
384 break;
Chris Lattnerc8dfbcb2009-06-21 07:19:10 +0000385 }
Daniel Dunbar1601f552010-10-25 20:18:46 +0000386
387 // Print the token string.
Craig Topper4e05fc32014-12-12 07:52:19 +0000388 OS << " (\"";
389 OS.write_escaped(Tok.getString());
390 OS << "\")\n";
Chris Lattnerc8dfbcb2009-06-21 07:19:10 +0000391 }
Dan Gohman268b0f42010-08-20 01:07:01 +0000392
Chris Lattnerb0133452009-06-21 20:16:42 +0000393 return Error;
Chris Lattnerd70e15b42009-06-21 05:22:37 +0000394}
395
Mandeep Singh Grang32360072016-12-01 18:42:04 +0000396static int fillCommandLineSymbols(MCAsmParser &Parser) {
Mandeep Singh Grang9a561aa2016-12-06 02:49:17 +0000397 for (auto &I: DefineSymbol) {
398 auto Pair = StringRef(I).split('=');
399 auto Sym = Pair.first;
400 auto Val = Pair.second;
401
402 if (Sym.empty() || Val.empty()) {
403 errs() << "error: defsym must be of the form: sym=value: " << I << "\n";
Colin LeMahieu229a1e62015-06-07 01:46:24 +0000404 return 1;
Mandeep Singh Grang9a561aa2016-12-06 02:49:17 +0000405 }
406 int64_t Value;
407 if (Val.getAsInteger(0, Value)) {
408 errs() << "error: Value is not an integer: " << Val << "\n";
409 return 1;
410 }
411 Parser.getContext().setSymbolValue(Parser.getStreamer(), Sym, Value);
412 }
Colin LeMahieu229a1e62015-06-07 01:46:24 +0000413 return 0;
414}
415
NAKAMURA Takumi89b8c172014-01-22 03:12:43 +0000416static int AssembleInput(const char *ProgName, const Target *TheTarget,
Richard Bartondef81b92012-04-16 11:32:10 +0000417 SourceMgr &SrcMgr, MCContext &Ctx, MCStreamer &Str,
Eric Christopher23c6d1f2014-06-19 06:22:01 +0000418 MCAsmInfo &MAI, MCSubtargetInfo &STI,
Eric Christopher4c5bff32014-06-19 06:22:08 +0000419 MCInstrInfo &MCII, MCTargetOptions &MCOptions) {
Evgeniy Stepanov0a951b72014-04-23 11:16:03 +0000420 std::unique_ptr<MCAsmParser> Parser(
421 createMCAsmParser(SrcMgr, Ctx, Str, MAI));
Ahmed Charles56440fd2014-03-06 05:51:42 +0000422 std::unique_ptr<MCTargetAsmParser> TAP(
Eric Christopher4c5bff32014-06-19 06:22:08 +0000423 TheTarget->createMCAsmParser(STI, *Parser, MCII, MCOptions));
424
Richard Bartondef81b92012-04-16 11:32:10 +0000425 if (!TAP) {
426 errs() << ProgName
427 << ": error: this target does not support assembly parsing.\n";
428 return 1;
429 }
430
Colin LeMahieu229a1e62015-06-07 01:46:24 +0000431 int SymbolResult = fillCommandLineSymbols(*Parser);
432 if(SymbolResult)
433 return SymbolResult;
Richard Bartondef81b92012-04-16 11:32:10 +0000434 Parser->setShowParsedOperands(ShowInstOperands);
Craig Topper4e05fc32014-12-12 07:52:19 +0000435 Parser->setTargetParser(*TAP);
Richard Bartondef81b92012-04-16 11:32:10 +0000436
437 int Res = Parser->Run(NoInitialTextSection);
438
439 return Res;
440}
441
442int main(int argc, char **argv) {
443 // Print a stack trace if we signal out.
Richard Smith2ad6d482016-06-09 00:53:21 +0000444 sys::PrintStackTraceOnErrorSignal(argv[0]);
Richard Bartondef81b92012-04-16 11:32:10 +0000445 PrettyStackTraceProgram X(argc, argv);
446 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
447
448 // Initialize targets and assembly printers/parsers.
449 llvm::InitializeAllTargetInfos();
450 llvm::InitializeAllTargetMCs();
451 llvm::InitializeAllAsmParsers();
452 llvm::InitializeAllDisassemblers();
453
454 // Register the target printer for --version.
455 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
456
457 cl::ParseCommandLineOptions(argc, argv, "llvm machine code playground\n");
Eric Christopher4c5bff32014-06-19 06:22:08 +0000458 MCTargetOptions MCOptions = InitMCTargetOptionsFromFlags();
Richard Bartondef81b92012-04-16 11:32:10 +0000459 TripleName = Triple::normalize(TripleName);
460 setDwarfDebugFlags(argc, argv);
461
Kevin Enderbye82ada62013-01-16 17:46:23 +0000462 setDwarfDebugProducer();
463
Richard Bartondef81b92012-04-16 11:32:10 +0000464 const char *ProgName = argv[0];
Daniel Dunbar80d484e2009-08-14 03:48:55 +0000465 const Target *TheTarget = GetTarget(ProgName);
466 if (!TheTarget)
467 return 1;
Daniel Sandersc535d932015-06-16 09:57:38 +0000468 // Now that GetTarget() has (potentially) replaced TripleName, it's safe to
469 // construct the Triple object.
470 Triple TheTriple(TripleName);
Daniel Dunbar80d484e2009-08-14 03:48:55 +0000471
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000472 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferPtr =
473 MemoryBuffer::getFileOrSTDIN(InputFilename);
474 if (std::error_code EC = BufferPtr.getError()) {
Davide Italiano2c007d02015-09-14 17:10:01 +0000475 errs() << InputFilename << ": " << EC.message() << '\n';
Chris Lattnerb0133452009-06-21 20:16:42 +0000476 return 1;
477 }
David Blaikie1961f142014-08-21 20:44:56 +0000478 MemoryBuffer *Buffer = BufferPtr->get();
Jim Grosbach112a2de2011-05-09 20:05:25 +0000479
Chris Lattnerb0133452009-06-21 20:16:42 +0000480 SourceMgr SrcMgr;
Jim Grosbach112a2de2011-05-09 20:05:25 +0000481
Daniel Dunbar5c947db2009-08-19 16:25:53 +0000482 // Tell SrcMgr about this buffer, which is what the parser will pick up.
David Blaikie1961f142014-08-21 20:44:56 +0000483 SrcMgr.AddNewSourceBuffer(std::move(*BufferPtr), SMLoc());
Jim Grosbach112a2de2011-05-09 20:05:25 +0000484
Chris Lattnerb0133452009-06-21 20:16:42 +0000485 // Record the location of the include directories so that the lexer can find
486 // it later.
487 SrcMgr.setIncludeDirs(IncludeDirs);
Jim Grosbach112a2de2011-05-09 20:05:25 +0000488
Ahmed Charles56440fd2014-03-06 05:51:42 +0000489 std::unique_ptr<MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TripleName));
Evan Chengd60fa58b2011-07-18 20:57:22 +0000490 assert(MRI && "Unable to create target register info!");
491
Ahmed Charles56440fd2014-03-06 05:51:42 +0000492 std::unique_ptr<MCAsmInfo> MAI(TheTarget->createMCAsmInfo(*MRI, TripleName));
Rafael Espindola227144c2013-05-13 01:16:13 +0000493 assert(MAI && "Unable to create target asm info!");
494
Rafael Espindola9768d732016-05-29 01:11:00 +0000495 MAI->setRelaxELFRelocations(RelaxELFRel);
496
George Rimarc91e38c2016-05-27 12:27:32 +0000497 if (CompressDebugSections != DebugCompressionType::DCT_None) {
David Blaikie9b620b42014-03-28 20:45:24 +0000498 if (!zlib::isAvailable()) {
Eric Christopher23c6d1f2014-06-19 06:22:01 +0000499 errs() << ProgName
500 << ": build tools with zlib to enable -compress-debug-sections";
David Blaikie9b620b42014-03-28 20:45:24 +0000501 return 1;
502 }
George Rimarc91e38c2016-05-27 12:27:32 +0000503 MAI->setCompressDebugSections(CompressDebugSections);
David Blaikie9b620b42014-03-28 20:45:24 +0000504 }
Nirav Dave53a72f42016-07-11 12:42:14 +0000505 MAI->setPreserveAsmComments(PreserveComments);
David Blaikie7400a972014-03-27 20:45:58 +0000506
Evan Cheng76792992011-07-20 05:58:47 +0000507 // FIXME: This is not pretty. MCContext has a ptr to MCObjectFileInfo and
508 // MCObjectFileInfo needs a MCContext reference in order to initialize itself.
Rafael Espindola75556bc2014-06-28 17:46:19 +0000509 MCObjectFileInfo MOFI;
510 MCContext Ctx(MAI.get(), MRI.get(), &MOFI, &SrcMgr);
Rafael Espindola699281c2016-05-18 11:58:50 +0000511 MOFI.InitMCObjectFileInfo(TheTriple, PIC, CMModel, Ctx);
Evan Cheng76792992011-07-20 05:58:47 +0000512
Daniel Dunbar4ee0d032011-03-28 22:49:15 +0000513 if (SaveTempLabels)
514 Ctx.setAllowTemporaryLabels(false);
Rafael Espindola0a017a62010-12-10 07:39:47 +0000515
Kevin Enderby6469fc22011-11-01 22:27:22 +0000516 Ctx.setGenDwarfForAssembly(GenDwarfForAssembly);
Eric Christopher4c5bff32014-06-19 06:22:08 +0000517 // Default to 4 for dwarf version.
518 unsigned DwarfVersion = MCOptions.DwarfVersion ? MCOptions.DwarfVersion : 4;
Oliver Stannard7eacbd52014-05-01 08:46:02 +0000519 if (DwarfVersion < 2 || DwarfVersion > 4) {
520 errs() << ProgName << ": Dwarf version " << DwarfVersion
521 << " is not supported." << '\n';
522 return 1;
523 }
524 Ctx.setDwarfVersion(DwarfVersion);
Chandler Carruth10700aad2012-12-17 21:32:42 +0000525 if (!DwarfDebugFlags.empty())
Kevin Enderbye7739d42011-12-09 18:09:40 +0000526 Ctx.setDwarfDebugFlags(StringRef(DwarfDebugFlags));
Kevin Enderbye82ada62013-01-16 17:46:23 +0000527 if (!DwarfDebugProducer.empty())
528 Ctx.setDwarfDebugProducer(StringRef(DwarfDebugProducer));
Chandler Carruth10700aad2012-12-17 21:32:42 +0000529 if (!DebugCompilationDir.empty())
530 Ctx.setCompilationDir(DebugCompilationDir);
Justin Bogner8809c402016-03-22 22:24:29 +0000531 else {
532 // If no compilation dir is set, try to use the current directory.
533 SmallString<128> CWD;
534 if (!sys::fs::current_path(CWD))
535 Ctx.setCompilationDir(CWD);
536 }
Eric Christopher906da232012-12-18 00:31:01 +0000537 if (!MainFileName.empty())
538 Ctx.setMainFileName(MainFileName);
Kevin Enderby6469fc22011-11-01 22:27:22 +0000539
James Molloy4c493e82011-09-07 17:24:38 +0000540 // Package up features to be passed to target/subtarget
541 std::string FeaturesStr;
542 if (MAttrs.size()) {
543 SubtargetFeatures Features;
544 for (unsigned i = 0; i != MAttrs.size(); ++i)
545 Features.AddFeature(MAttrs[i]);
546 FeaturesStr = Features.getString();
547 }
548
Craig Topper8c8ee4d2014-12-12 07:52:16 +0000549 std::unique_ptr<tool_output_file> Out = GetOutputStream();
Dan Gohman268b0f42010-08-20 01:07:01 +0000550 if (!Out)
551 return 1;
552
Rafael Espindola5560a4c2015-04-14 22:14:34 +0000553 std::unique_ptr<buffer_ostream> BOS;
554 raw_pwrite_stream *OS = &Out->os();
Ahmed Charles56440fd2014-03-06 05:51:42 +0000555 std::unique_ptr<MCStreamer> Str;
Chris Lattnera61e93d2009-08-17 04:23:44 +0000556
Ahmed Charles56440fd2014-03-06 05:51:42 +0000557 std::unique_ptr<MCInstrInfo> MCII(TheTarget->createMCInstrInfo());
558 std::unique_ptr<MCSubtargetInfo> STI(
559 TheTarget->createMCSubtargetInfo(TripleName, MCPU, FeaturesStr));
Evan Cheng91111d22011-07-09 05:47:46 +0000560
Craig Toppere6cb63e2014-04-25 04:24:47 +0000561 MCInstPrinter *IP = nullptr;
Kevin Enderbyf92f9902009-09-04 21:45:34 +0000562 if (FileType == OFT_AssemblyFile) {
Daniel Sanders50f17232015-09-15 16:17:27 +0000563 IP = TheTarget->createMCInstPrinter(Triple(TripleName), OutputAsmVariant,
564 *MAI, *MCII, *MRI);
Jim Grosbach3fdf7cf2014-06-11 20:26:40 +0000565
Nirav Davea9395af2016-10-31 18:36:31 +0000566 if (!IP) {
567 errs()
568 << "error: unable to create instruction printer for target triple '"
569 << TheTriple.normalize() << "' with assembly variant "
570 << OutputAsmVariant << ".\n";
571 return 1;
572 }
573
Jim Grosbach3fdf7cf2014-06-11 20:26:40 +0000574 // Set the display preference for hex vs. decimal immediates.
575 IP->setPrintImmHex(PrintImmHex);
576
577 // Set up the AsmStreamer.
Craig Toppere6cb63e2014-04-25 04:24:47 +0000578 MCCodeEmitter *CE = nullptr;
579 MCAsmBackend *MAB = nullptr;
Daniel Dunbarecd0c8a2010-12-16 03:05:59 +0000580 if (ShowEncoding) {
Eric Christopher0169e422015-03-10 22:03:14 +0000581 CE = TheTarget->createMCCodeEmitter(*MCII, *MRI, Ctx);
Joel Jones373d7d32016-07-25 17:18:28 +0000582 MAB = TheTarget->createMCAsmBackend(*MRI, TripleName, MCPU, MCOptions);
Daniel Dunbarecd0c8a2010-12-16 03:05:59 +0000583 }
Rafael Espindola5560a4c2015-04-14 22:14:34 +0000584 auto FOut = llvm::make_unique<formatted_raw_ostream>(*OS);
Rafael Espindola5682ce22015-04-09 21:06:08 +0000585 Str.reset(TheTarget->createAsmStreamer(
586 Ctx, std::move(FOut), /*asmverbose*/ true,
587 /*useDwarfDirectory*/ true, IP, CE, MAB, ShowInst));
Jim Grosbach78309c42011-12-05 23:20:14 +0000588
Daniel Dunbarb09b8902010-03-23 23:47:12 +0000589 } else if (FileType == OFT_Null) {
Peter Collingbournef4498a42015-02-19 00:45:04 +0000590 Str.reset(TheTarget->createNullStreamer(Ctx));
Daniel Dunbar3016db32009-08-21 09:11:24 +0000591 } else {
592 assert(FileType == OFT_ObjectFile && "Invalid file type!");
Rafael Espindola5560a4c2015-04-14 22:14:34 +0000593
Rafael Espindolaf27fa2b2015-06-17 16:26:47 +0000594 // Don't waste memory on names of temp labels.
595 Ctx.setUseNamesOnTempLabels(false);
596
Rafael Espindola5560a4c2015-04-14 22:14:34 +0000597 if (!Out->os().supportsSeeking()) {
598 BOS = make_unique<buffer_ostream>(Out->os());
599 OS = BOS.get();
600 }
601
Eric Christopher0169e422015-03-10 22:03:14 +0000602 MCCodeEmitter *CE = TheTarget->createMCCodeEmitter(*MCII, *MRI, Ctx);
Joel Jones373d7d32016-07-25 17:18:28 +0000603 MCAsmBackend *MAB = TheTarget->createMCAsmBackend(*MRI, TripleName, MCPU,
604 MCOptions);
David Majnemer03e2cc32015-12-21 22:09:27 +0000605 Str.reset(TheTarget->createMCObjectStreamer(
606 TheTriple, Ctx, *MAB, *OS, CE, *STI, MCOptions.MCRelaxAll,
607 MCOptions.MCIncrementalLinkerCompatible,
608 /*DWARFMustBeAtTheEnd*/ false));
Rafael Espindola7b61ddf2014-10-15 16:12:52 +0000609 if (NoExecStack)
610 Str->InitSections(true);
Daniel Dunbar3016db32009-08-21 09:11:24 +0000611 }
Daniel Dunbara10e5192009-06-24 23:30:00 +0000612
Richard Bartondef81b92012-04-16 11:32:10 +0000613 int Res = 1;
Kevin Enderby168ffb32012-12-05 18:13:19 +0000614 bool disassemble = false;
Chris Lattnerd70e15b42009-06-21 05:22:37 +0000615 switch (Action) {
Chris Lattnerb0133452009-06-21 20:16:42 +0000616 case AC_AsLex:
Craig Topper4e05fc32014-12-12 07:52:19 +0000617 Res = AsLexInput(SrcMgr, *MAI, Out->os());
Richard Bartondef81b92012-04-16 11:32:10 +0000618 break;
Chris Lattnerd70e15b42009-06-21 05:22:37 +0000619 case AC_Assemble:
Eric Christopher23c6d1f2014-06-19 06:22:01 +0000620 Res = AssembleInput(ProgName, TheTarget, SrcMgr, Ctx, *Str, *MAI, *STI,
Eric Christopher4c5bff32014-06-19 06:22:08 +0000621 *MCII, MCOptions);
Richard Bartondef81b92012-04-16 11:32:10 +0000622 break;
Kevin Enderby62183c42012-10-22 22:31:46 +0000623 case AC_MDisassemble:
Eli Bendersky6f5d70e2013-02-26 23:04:17 +0000624 assert(IP && "Expected assembly output");
Kevin Enderby62183c42012-10-22 22:31:46 +0000625 IP->setUseMarkup(1);
Kevin Enderby168ffb32012-12-05 18:13:19 +0000626 disassemble = true;
627 break;
Sean Callanan7e645502009-12-17 01:49:59 +0000628 case AC_Disassemble:
Kevin Enderby168ffb32012-12-05 18:13:19 +0000629 disassemble = true;
Richard Bartondef81b92012-04-16 11:32:10 +0000630 break;
Chris Lattnerd70e15b42009-06-21 05:22:37 +0000631 }
Kevin Enderby168ffb32012-12-05 18:13:19 +0000632 if (disassemble)
633 Res = Disassembler::disassemble(*TheTarget, TripleName, *STI, *Str,
634 *Buffer, SrcMgr, Out->os());
Richard Bartondef81b92012-04-16 11:32:10 +0000635
636 // Keep output if no errors.
637 if (Res == 0) Out->keep();
638 return Res;
Chris Lattner8dd8a522009-06-18 23:04:45 +0000639}