blob: 91f3159ee2abe392bc92543c35faba91d73308be [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"
Lang Hames2241ffa2017-10-11 23:34:47 +000018#include "llvm/MC/MCCodeEmitter.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000019#include "llvm/MC/MCContext.h"
Chris Lattner11b2fc92009-09-14 03:02:37 +000020#include "llvm/MC/MCInstPrinter.h"
Evan Chengc5e6d2f2011-07-11 03:57:24 +000021#include "llvm/MC/MCInstrInfo.h"
Evan Cheng76792992011-07-20 05:58:47 +000022#include "llvm/MC/MCObjectFileInfo.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000023#include "llvm/MC/MCParser/AsmLexer.h"
Benjamin Kramerb3e8a6d2016-01-27 10:01:28 +000024#include "llvm/MC/MCParser/MCTargetAsmParser.h"
Evan Cheng76792992011-07-20 05:58:47 +000025#include "llvm/MC/MCRegisterInfo.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"
David Blaikie4333f972018-04-11 18:49:37 +000028#include "llvm/MC/MCTargetOptionsCommandFlags.inc"
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
Saleem Abdulrasool1f62f572017-06-09 00:40:19 +000059static cl::opt<DebugCompressionType> CompressDebugSections(
60 "compress-debug-sections", cl::ValueOptional,
61 cl::init(DebugCompressionType::None),
62 cl::desc("Choose DWARF debug sections compression:"),
63 cl::values(clEnumValN(DebugCompressionType::None, "none", "No compression"),
64 clEnumValN(DebugCompressionType::Z, "zlib",
65 "Use zlib compression"),
66 clEnumValN(DebugCompressionType::GNU, "zlib-gnu",
67 "Use zlib-gnu compression (deprecated)")));
David Blaikie7400a972014-03-27 20:45:58 +000068
69static cl::opt<bool>
Daniel Dunbare3ee3322010-02-03 18:18:30 +000070ShowInst("show-inst", cl::desc("Show internal instruction representation"));
71
Daniel Dunbar2eca0252010-08-11 06:37:09 +000072static cl::opt<bool>
73ShowInstOperands("show-inst-operands",
74 cl::desc("Show instructions operands as parsed"));
75
Chris Lattner44790342009-09-20 07:17:49 +000076static cl::opt<unsigned>
77OutputAsmVariant("output-asm-variant",
78 cl::desc("Syntax variant to use for output printing"));
79
Jim Grosbach3fdf7cf2014-06-11 20:26:40 +000080static cl::opt<bool>
81PrintImmHex("print-imm-hex", cl::init(false),
82 cl::desc("Prefer hex format for immediate values"));
83
Colin LeMahieu229a1e62015-06-07 01:46:24 +000084static cl::list<std::string>
85DefineSymbol("defsym", cl::desc("Defines a symbol to be an integer constant"));
86
Nirav Dave53a72f42016-07-11 12:42:14 +000087static cl::opt<bool>
88 PreserveComments("preserve-comments",
89 cl::desc("Preserve Comments in outputted assembly"));
90
Daniel Dunbar3016db32009-08-21 09:11:24 +000091enum OutputFileType {
Daniel Dunbarb09b8902010-03-23 23:47:12 +000092 OFT_Null,
Daniel Dunbar3016db32009-08-21 09:11:24 +000093 OFT_AssemblyFile,
94 OFT_ObjectFile
95};
96static cl::opt<OutputFileType>
97FileType("filetype", cl::init(OFT_AssemblyFile),
98 cl::desc("Choose an output file type:"),
99 cl::values(
100 clEnumValN(OFT_AssemblyFile, "asm",
101 "Emit an assembly ('.s') file"),
Daniel Dunbarb09b8902010-03-23 23:47:12 +0000102 clEnumValN(OFT_Null, "null",
103 "Don't emit anything (for timing purposes)"),
Daniel Dunbar3016db32009-08-21 09:11:24 +0000104 clEnumValN(OFT_ObjectFile, "obj",
Mehdi Amini732afdd2016-10-08 19:41:06 +0000105 "Emit a native object ('.o') file")));
Daniel Dunbar3016db32009-08-21 09:11:24 +0000106
Chris Lattnerd70e15b42009-06-21 05:22:37 +0000107static cl::list<std::string>
108IncludeDirs("I", cl::desc("Directory of include files"),
109 cl::value_desc("directory"), cl::Prefix);
Chris Lattner8dd8a522009-06-18 23:04:45 +0000110
Daniel Dunbar8c6bad22009-07-17 22:38:58 +0000111static cl::opt<std::string>
Daniel Dunbar46892112010-03-13 02:20:38 +0000112ArchName("arch", cl::desc("Target arch to assemble for, "
Bill Wendlinge3031142011-06-17 20:35:21 +0000113 "see -version for available targets"));
Daniel Dunbar46892112010-03-13 02:20:38 +0000114
115static cl::opt<std::string>
Nick Lewyckyb2449092009-11-01 22:07:54 +0000116TripleName("triple", cl::desc("Target triple to assemble for, "
Daniel Dunbar46892112010-03-13 02:20:38 +0000117 "see -version for available targets"));
Daniel Dunbar8c6bad22009-07-17 22:38:58 +0000118
Jim Grosbach685b7732010-10-30 15:57:50 +0000119static cl::opt<std::string>
120MCPU("mcpu",
121 cl::desc("Target a specific cpu type (-mcpu=help for details)"),
122 cl::value_desc("cpu-name"),
123 cl::init(""));
124
James Molloy4c493e82011-09-07 17:24:38 +0000125static cl::list<std::string>
126MAttrs("mattr",
127 cl::CommaSeparated,
128 cl::desc("Target specific attributes (-mattr=help for details)"),
129 cl::value_desc("a1,+a2,-a3,..."));
130
Rafael Espindola699281c2016-05-18 11:58:50 +0000131static cl::opt<bool> PIC("position-independent",
132 cl::desc("Position independent"), cl::init(false));
Evan Cheng2129f592011-07-19 06:37:02 +0000133
Rafael Espindola9f929952017-08-02 20:32:26 +0000134static cl::opt<bool>
135 LargeCodeModel("large-code-model",
136 cl::desc("Create cfi directives that assume the code might "
137 "be more than 2gb away"));
Evan Chengefd9b422011-07-20 07:51:56 +0000138
Daniel Dunbar322fec62010-03-13 02:20:57 +0000139static cl::opt<bool>
Bill Wendlinge3031142011-06-17 20:35:21 +0000140NoInitialTextSection("n", cl::desc("Don't assume assembly file starts "
141 "in the text section"));
Daniel Dunbar322fec62010-03-13 02:20:57 +0000142
Daniel Dunbar4ee0d032011-03-28 22:49:15 +0000143static cl::opt<bool>
Kevin Enderby6469fc22011-11-01 22:27:22 +0000144GenDwarfForAssembly("g", cl::desc("Generate dwarf debugging info for assembly "
145 "source files"));
146
Chandler Carruth10700aad2012-12-17 21:32:42 +0000147static cl::opt<std::string>
148DebugCompilationDir("fdebug-compilation-dir",
149 cl::desc("Specifies the debug info's compilation dir"));
150
Eric Christopher906da232012-12-18 00:31:01 +0000151static cl::opt<std::string>
152MainFileName("main-file-name",
153 cl::desc("Specifies the name we should consider the input file"));
154
Eric Christopherdc3e9c72014-05-21 00:20:01 +0000155static cl::opt<bool> SaveTempLabels("save-temp-labels",
156 cl::desc("Don't discard temporary labels"));
157
Eric Christopher472cee32014-05-21 21:05:09 +0000158static cl::opt<bool> NoExecStack("no-exec-stack",
159 cl::desc("File doesn't need an exec stack"));
160
Chris Lattnerd70e15b42009-06-21 05:22:37 +0000161enum ActionType {
Chris Lattnerb0133452009-06-21 20:16:42 +0000162 AC_AsLex,
Sean Callanan7e645502009-12-17 01:49:59 +0000163 AC_Assemble,
Sean Callanan2d03d3a2010-04-12 19:43:00 +0000164 AC_Disassemble,
Kevin Enderby168ffb32012-12-05 18:13:19 +0000165 AC_MDisassemble,
Chris Lattnerd70e15b42009-06-21 05:22:37 +0000166};
Chris Lattner8dd8a522009-06-18 23:04:45 +0000167
Chris Lattnerd70e15b42009-06-21 05:22:37 +0000168static cl::opt<ActionType>
169Action(cl::desc("Action to perform:"),
Chris Lattnerb0133452009-06-21 20:16:42 +0000170 cl::init(AC_Assemble),
171 cl::values(clEnumValN(AC_AsLex, "as-lex",
172 "Lex tokens from a .s file"),
173 clEnumValN(AC_Assemble, "assemble",
Chris Lattnerd70e15b42009-06-21 05:22:37 +0000174 "Assemble a .s file (default)"),
Sean Callanan7e645502009-12-17 01:49:59 +0000175 clEnumValN(AC_Disassemble, "disassemble",
176 "Disassemble strings of hex bytes"),
Kevin Enderby62183c42012-10-22 22:31:46 +0000177 clEnumValN(AC_MDisassemble, "mdis",
Mehdi Amini732afdd2016-10-08 19:41:06 +0000178 "Marked up disassembly of strings of hex bytes")));
Chris Lattnerd70e15b42009-06-21 05:22:37 +0000179
Kevin Enderbyf92f9902009-09-04 21:45:34 +0000180static const Target *GetTarget(const char *ProgName) {
Daniel Dunbar46892112010-03-13 02:20:38 +0000181 // Figure out the target triple.
182 if (TripleName.empty())
Sebastian Pop94441fb2011-11-01 21:32:20 +0000183 TripleName = sys::getDefaultTargetTriple();
Evan Chenge64f0e52011-07-26 19:02:16 +0000184 Triple TheTriple(Triple::normalize(TripleName));
185
Kevin Enderbyfe3d0052012-05-08 23:38:45 +0000186 // Get the target specific parser.
187 std::string Error;
188 const Target *TheTarget = TargetRegistry::lookupTarget(ArchName, TheTriple,
189 Error);
190 if (!TheTarget) {
191 errs() << ProgName << ": " << Error;
Craig Toppere6cb63e2014-04-25 04:24:47 +0000192 return nullptr;
Daniel Dunbar46892112010-03-13 02:20:38 +0000193 }
194
Kevin Enderbyfe3d0052012-05-08 23:38:45 +0000195 // Update the triple name and return the found target.
Evan Chenge64f0e52011-07-26 19:02:16 +0000196 TripleName = TheTriple.getTriple();
197 return TheTarget;
Kevin Enderbyf92f9902009-09-04 21:45:34 +0000198}
199
Reid Kleckner3fc649c2017-09-23 01:03:17 +0000200static std::unique_ptr<ToolOutputFile> GetOutputStream() {
Dan Gohman268b0f42010-08-20 01:07:01 +0000201 if (OutputFilename == "")
202 OutputFilename = "-";
203
Rafael Espindola3fd1e992014-08-25 18:16:47 +0000204 std::error_code EC;
Reid Kleckner3fc649c2017-09-23 01:03:17 +0000205 auto Out =
206 llvm::make_unique<ToolOutputFile>(OutputFilename, EC, sys::fs::F_None);
Rafael Espindola3fd1e992014-08-25 18:16:47 +0000207 if (EC) {
208 errs() << EC.message() << '\n';
Craig Toppere6cb63e2014-04-25 04:24:47 +0000209 return nullptr;
Dan Gohman268b0f42010-08-20 01:07:01 +0000210 }
Dan Gohmana2233f22010-09-01 14:20:41 +0000211
212 return Out;
Dan Gohman268b0f42010-08-20 01:07:01 +0000213}
214
Kevin Enderbye7739d42011-12-09 18:09:40 +0000215static std::string DwarfDebugFlags;
216static void setDwarfDebugFlags(int argc, char **argv) {
217 if (!getenv("RC_DEBUG_OPTIONS"))
218 return;
219 for (int i = 0; i < argc; i++) {
220 DwarfDebugFlags += argv[i];
221 if (i + 1 < argc)
222 DwarfDebugFlags += " ";
223 }
224}
225
Kevin Enderbye82ada62013-01-16 17:46:23 +0000226static std::string DwarfDebugProducer;
Eugene Zelenkoffec81c2015-11-04 22:32:32 +0000227static void setDwarfDebugProducer() {
Kevin Enderbye82ada62013-01-16 17:46:23 +0000228 if(!getenv("DEBUG_PRODUCER"))
229 return;
230 DwarfDebugProducer += getenv("DEBUG_PRODUCER");
231}
232
Eric Christopher23c6d1f2014-06-19 06:22:01 +0000233static int AsLexInput(SourceMgr &SrcMgr, MCAsmInfo &MAI,
Craig Topper4e05fc32014-12-12 07:52:19 +0000234 raw_ostream &OS) {
Chris Lattnerd70e15b42009-06-21 05:22:37 +0000235
Richard Bartondef81b92012-04-16 11:32:10 +0000236 AsmLexer Lexer(MAI);
Rafael Espindola8026bd02014-07-06 14:17:29 +0000237 Lexer.setBuffer(SrcMgr.getMemoryBuffer(SrcMgr.getMainFileID())->getBuffer());
Daniel Dunbar7a85f9c2010-07-18 18:31:28 +0000238
Chris Lattnerb0133452009-06-21 20:16:42 +0000239 bool Error = false;
Daniel Dunbarbc798162009-07-28 16:56:42 +0000240 while (Lexer.Lex().isNot(AsmToken::Eof)) {
Oliver Stannard5c032ce2018-03-06 14:02:14 +0000241 Lexer.getTok().dump(OS);
242 OS << "\n";
243 if (Lexer.getTok().getKind() == AsmToken::Error)
Chris Lattnerb0133452009-06-21 20:16:42 +0000244 Error = true;
Chris Lattnerc8dfbcb2009-06-21 07:19:10 +0000245 }
Dan Gohman268b0f42010-08-20 01:07:01 +0000246
Chris Lattnerb0133452009-06-21 20:16:42 +0000247 return Error;
Chris Lattnerd70e15b42009-06-21 05:22:37 +0000248}
249
Mandeep Singh Grang32360072016-12-01 18:42:04 +0000250static int fillCommandLineSymbols(MCAsmParser &Parser) {
Mandeep Singh Grang9a561aa2016-12-06 02:49:17 +0000251 for (auto &I: DefineSymbol) {
252 auto Pair = StringRef(I).split('=');
253 auto Sym = Pair.first;
254 auto Val = Pair.second;
255
256 if (Sym.empty() || Val.empty()) {
257 errs() << "error: defsym must be of the form: sym=value: " << I << "\n";
Colin LeMahieu229a1e62015-06-07 01:46:24 +0000258 return 1;
Mandeep Singh Grang9a561aa2016-12-06 02:49:17 +0000259 }
260 int64_t Value;
261 if (Val.getAsInteger(0, Value)) {
262 errs() << "error: Value is not an integer: " << Val << "\n";
263 return 1;
264 }
265 Parser.getContext().setSymbolValue(Parser.getStreamer(), Sym, Value);
266 }
Colin LeMahieu229a1e62015-06-07 01:46:24 +0000267 return 0;
268}
269
NAKAMURA Takumi89b8c172014-01-22 03:12:43 +0000270static int AssembleInput(const char *ProgName, const Target *TheTarget,
Richard Bartondef81b92012-04-16 11:32:10 +0000271 SourceMgr &SrcMgr, MCContext &Ctx, MCStreamer &Str,
Eric Christopher23c6d1f2014-06-19 06:22:01 +0000272 MCAsmInfo &MAI, MCSubtargetInfo &STI,
Eric Christopher4c5bff32014-06-19 06:22:08 +0000273 MCInstrInfo &MCII, MCTargetOptions &MCOptions) {
Evgeniy Stepanov0a951b72014-04-23 11:16:03 +0000274 std::unique_ptr<MCAsmParser> Parser(
275 createMCAsmParser(SrcMgr, Ctx, Str, MAI));
Ahmed Charles56440fd2014-03-06 05:51:42 +0000276 std::unique_ptr<MCTargetAsmParser> TAP(
Eric Christopher4c5bff32014-06-19 06:22:08 +0000277 TheTarget->createMCAsmParser(STI, *Parser, MCII, MCOptions));
278
Richard Bartondef81b92012-04-16 11:32:10 +0000279 if (!TAP) {
280 errs() << ProgName
281 << ": error: this target does not support assembly parsing.\n";
282 return 1;
283 }
284
Colin LeMahieu229a1e62015-06-07 01:46:24 +0000285 int SymbolResult = fillCommandLineSymbols(*Parser);
286 if(SymbolResult)
287 return SymbolResult;
Richard Bartondef81b92012-04-16 11:32:10 +0000288 Parser->setShowParsedOperands(ShowInstOperands);
Craig Topper4e05fc32014-12-12 07:52:19 +0000289 Parser->setTargetParser(*TAP);
Richard Bartondef81b92012-04-16 11:32:10 +0000290
291 int Res = Parser->Run(NoInitialTextSection);
292
293 return Res;
294}
295
296int main(int argc, char **argv) {
297 // Print a stack trace if we signal out.
Richard Smith2ad6d482016-06-09 00:53:21 +0000298 sys::PrintStackTraceOnErrorSignal(argv[0]);
Richard Bartondef81b92012-04-16 11:32:10 +0000299 PrettyStackTraceProgram X(argc, argv);
300 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
301
302 // Initialize targets and assembly printers/parsers.
303 llvm::InitializeAllTargetInfos();
304 llvm::InitializeAllTargetMCs();
305 llvm::InitializeAllAsmParsers();
306 llvm::InitializeAllDisassemblers();
307
308 // Register the target printer for --version.
309 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
310
311 cl::ParseCommandLineOptions(argc, argv, "llvm machine code playground\n");
Eric Christopher4c5bff32014-06-19 06:22:08 +0000312 MCTargetOptions MCOptions = InitMCTargetOptionsFromFlags();
Richard Bartondef81b92012-04-16 11:32:10 +0000313 TripleName = Triple::normalize(TripleName);
314 setDwarfDebugFlags(argc, argv);
315
Kevin Enderbye82ada62013-01-16 17:46:23 +0000316 setDwarfDebugProducer();
317
Richard Bartondef81b92012-04-16 11:32:10 +0000318 const char *ProgName = argv[0];
Daniel Dunbar80d484e2009-08-14 03:48:55 +0000319 const Target *TheTarget = GetTarget(ProgName);
320 if (!TheTarget)
321 return 1;
Daniel Sandersc535d932015-06-16 09:57:38 +0000322 // Now that GetTarget() has (potentially) replaced TripleName, it's safe to
323 // construct the Triple object.
324 Triple TheTriple(TripleName);
Daniel Dunbar80d484e2009-08-14 03:48:55 +0000325
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000326 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferPtr =
327 MemoryBuffer::getFileOrSTDIN(InputFilename);
328 if (std::error_code EC = BufferPtr.getError()) {
Davide Italiano2c007d02015-09-14 17:10:01 +0000329 errs() << InputFilename << ": " << EC.message() << '\n';
Chris Lattnerb0133452009-06-21 20:16:42 +0000330 return 1;
331 }
David Blaikie1961f142014-08-21 20:44:56 +0000332 MemoryBuffer *Buffer = BufferPtr->get();
Jim Grosbach112a2de2011-05-09 20:05:25 +0000333
Chris Lattnerb0133452009-06-21 20:16:42 +0000334 SourceMgr SrcMgr;
Jim Grosbach112a2de2011-05-09 20:05:25 +0000335
Daniel Dunbar5c947db2009-08-19 16:25:53 +0000336 // Tell SrcMgr about this buffer, which is what the parser will pick up.
David Blaikie1961f142014-08-21 20:44:56 +0000337 SrcMgr.AddNewSourceBuffer(std::move(*BufferPtr), SMLoc());
Jim Grosbach112a2de2011-05-09 20:05:25 +0000338
Chris Lattnerb0133452009-06-21 20:16:42 +0000339 // Record the location of the include directories so that the lexer can find
340 // it later.
341 SrcMgr.setIncludeDirs(IncludeDirs);
Jim Grosbach112a2de2011-05-09 20:05:25 +0000342
Ahmed Charles56440fd2014-03-06 05:51:42 +0000343 std::unique_ptr<MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TripleName));
Evan Chengd60fa58b2011-07-18 20:57:22 +0000344 assert(MRI && "Unable to create target register info!");
345
Ahmed Charles56440fd2014-03-06 05:51:42 +0000346 std::unique_ptr<MCAsmInfo> MAI(TheTarget->createMCAsmInfo(*MRI, TripleName));
Rafael Espindola227144c2013-05-13 01:16:13 +0000347 assert(MAI && "Unable to create target asm info!");
348
Rafael Espindola9768d732016-05-29 01:11:00 +0000349 MAI->setRelaxELFRelocations(RelaxELFRel);
350
Saleem Abdulrasool1f62f572017-06-09 00:40:19 +0000351 if (CompressDebugSections != DebugCompressionType::None) {
David Blaikie9b620b42014-03-28 20:45:24 +0000352 if (!zlib::isAvailable()) {
Eric Christopher23c6d1f2014-06-19 06:22:01 +0000353 errs() << ProgName
354 << ": build tools with zlib to enable -compress-debug-sections";
David Blaikie9b620b42014-03-28 20:45:24 +0000355 return 1;
356 }
George Rimarc91e38c2016-05-27 12:27:32 +0000357 MAI->setCompressDebugSections(CompressDebugSections);
David Blaikie9b620b42014-03-28 20:45:24 +0000358 }
Nirav Dave53a72f42016-07-11 12:42:14 +0000359 MAI->setPreserveAsmComments(PreserveComments);
David Blaikie7400a972014-03-27 20:45:58 +0000360
Evan Cheng76792992011-07-20 05:58:47 +0000361 // FIXME: This is not pretty. MCContext has a ptr to MCObjectFileInfo and
362 // MCObjectFileInfo needs a MCContext reference in order to initialize itself.
Rafael Espindola75556bc2014-06-28 17:46:19 +0000363 MCObjectFileInfo MOFI;
364 MCContext Ctx(MAI.get(), MRI.get(), &MOFI, &SrcMgr);
Rafael Espindola9f929952017-08-02 20:32:26 +0000365 MOFI.InitMCObjectFileInfo(TheTriple, PIC, Ctx, LargeCodeModel);
Evan Cheng76792992011-07-20 05:58:47 +0000366
Daniel Dunbar4ee0d032011-03-28 22:49:15 +0000367 if (SaveTempLabels)
368 Ctx.setAllowTemporaryLabels(false);
Rafael Espindola0a017a62010-12-10 07:39:47 +0000369
Kevin Enderby6469fc22011-11-01 22:27:22 +0000370 Ctx.setGenDwarfForAssembly(GenDwarfForAssembly);
Eric Christopher4c5bff32014-06-19 06:22:08 +0000371 // Default to 4 for dwarf version.
372 unsigned DwarfVersion = MCOptions.DwarfVersion ? MCOptions.DwarfVersion : 4;
Paul Robinsondccb4fe2017-02-28 23:40:46 +0000373 if (DwarfVersion < 2 || DwarfVersion > 5) {
Oliver Stannard7eacbd52014-05-01 08:46:02 +0000374 errs() << ProgName << ": Dwarf version " << DwarfVersion
375 << " is not supported." << '\n';
376 return 1;
377 }
378 Ctx.setDwarfVersion(DwarfVersion);
Chandler Carruth10700aad2012-12-17 21:32:42 +0000379 if (!DwarfDebugFlags.empty())
Kevin Enderbye7739d42011-12-09 18:09:40 +0000380 Ctx.setDwarfDebugFlags(StringRef(DwarfDebugFlags));
Kevin Enderbye82ada62013-01-16 17:46:23 +0000381 if (!DwarfDebugProducer.empty())
382 Ctx.setDwarfDebugProducer(StringRef(DwarfDebugProducer));
Chandler Carruth10700aad2012-12-17 21:32:42 +0000383 if (!DebugCompilationDir.empty())
384 Ctx.setCompilationDir(DebugCompilationDir);
Justin Bogner8809c402016-03-22 22:24:29 +0000385 else {
386 // If no compilation dir is set, try to use the current directory.
387 SmallString<128> CWD;
388 if (!sys::fs::current_path(CWD))
389 Ctx.setCompilationDir(CWD);
390 }
Eric Christopher906da232012-12-18 00:31:01 +0000391 if (!MainFileName.empty())
392 Ctx.setMainFileName(MainFileName);
Paul Robinsonb271f312018-03-29 17:16:41 +0000393 if (DwarfVersion >= 5) {
394 // DWARF v5 needs the root file as well as the compilation directory.
395 // If we find a '.file 0' directive that will supersede these values.
396 MD5 Hash;
397 MD5::MD5Result *Cksum =
398 (MD5::MD5Result *)Ctx.allocate(sizeof(MD5::MD5Result), 1);
399 Hash.update(Buffer->getBuffer());
400 Hash.final(*Cksum);
401 Ctx.setMCLineTableRootFile(
402 /*CUID=*/0, Ctx.getCompilationDir(),
403 !MainFileName.empty() ? MainFileName : InputFilename, Cksum, None);
404 }
Kevin Enderby6469fc22011-11-01 22:27:22 +0000405
James Molloy4c493e82011-09-07 17:24:38 +0000406 // Package up features to be passed to target/subtarget
407 std::string FeaturesStr;
408 if (MAttrs.size()) {
409 SubtargetFeatures Features;
410 for (unsigned i = 0; i != MAttrs.size(); ++i)
411 Features.AddFeature(MAttrs[i]);
412 FeaturesStr = Features.getString();
413 }
414
Reid Kleckner3fc649c2017-09-23 01:03:17 +0000415 std::unique_ptr<ToolOutputFile> Out = GetOutputStream();
Dan Gohman268b0f42010-08-20 01:07:01 +0000416 if (!Out)
417 return 1;
418
Rafael Espindola5560a4c2015-04-14 22:14:34 +0000419 std::unique_ptr<buffer_ostream> BOS;
420 raw_pwrite_stream *OS = &Out->os();
Ahmed Charles56440fd2014-03-06 05:51:42 +0000421 std::unique_ptr<MCStreamer> Str;
Chris Lattnera61e93d2009-08-17 04:23:44 +0000422
Ahmed Charles56440fd2014-03-06 05:51:42 +0000423 std::unique_ptr<MCInstrInfo> MCII(TheTarget->createMCInstrInfo());
424 std::unique_ptr<MCSubtargetInfo> STI(
425 TheTarget->createMCSubtargetInfo(TripleName, MCPU, FeaturesStr));
Evan Cheng91111d22011-07-09 05:47:46 +0000426
Craig Toppere6cb63e2014-04-25 04:24:47 +0000427 MCInstPrinter *IP = nullptr;
Kevin Enderbyf92f9902009-09-04 21:45:34 +0000428 if (FileType == OFT_AssemblyFile) {
Daniel Sanders50f17232015-09-15 16:17:27 +0000429 IP = TheTarget->createMCInstPrinter(Triple(TripleName), OutputAsmVariant,
430 *MAI, *MCII, *MRI);
Jim Grosbach3fdf7cf2014-06-11 20:26:40 +0000431
Nirav Davea9395af2016-10-31 18:36:31 +0000432 if (!IP) {
433 errs()
434 << "error: unable to create instruction printer for target triple '"
435 << TheTriple.normalize() << "' with assembly variant "
436 << OutputAsmVariant << ".\n";
437 return 1;
438 }
439
Jim Grosbach3fdf7cf2014-06-11 20:26:40 +0000440 // Set the display preference for hex vs. decimal immediates.
441 IP->setPrintImmHex(PrintImmHex);
442
443 // Set up the AsmStreamer.
Craig Toppere6cb63e2014-04-25 04:24:47 +0000444 MCCodeEmitter *CE = nullptr;
445 MCAsmBackend *MAB = nullptr;
Daniel Dunbarecd0c8a2010-12-16 03:05:59 +0000446 if (ShowEncoding) {
Eric Christopher0169e422015-03-10 22:03:14 +0000447 CE = TheTarget->createMCCodeEmitter(*MCII, *MRI, Ctx);
Alex Bradburyb22f7512018-01-03 08:53:05 +0000448 MAB = TheTarget->createMCAsmBackend(*STI, *MRI, MCOptions);
Daniel Dunbarecd0c8a2010-12-16 03:05:59 +0000449 }
Rafael Espindola5560a4c2015-04-14 22:14:34 +0000450 auto FOut = llvm::make_unique<formatted_raw_ostream>(*OS);
Rafael Espindola5682ce22015-04-09 21:06:08 +0000451 Str.reset(TheTarget->createAsmStreamer(
452 Ctx, std::move(FOut), /*asmverbose*/ true,
453 /*useDwarfDirectory*/ true, IP, CE, MAB, ShowInst));
Jim Grosbach78309c42011-12-05 23:20:14 +0000454
Daniel Dunbarb09b8902010-03-23 23:47:12 +0000455 } else if (FileType == OFT_Null) {
Peter Collingbournef4498a42015-02-19 00:45:04 +0000456 Str.reset(TheTarget->createNullStreamer(Ctx));
Daniel Dunbar3016db32009-08-21 09:11:24 +0000457 } else {
458 assert(FileType == OFT_ObjectFile && "Invalid file type!");
Rafael Espindola5560a4c2015-04-14 22:14:34 +0000459
Rafael Espindolaf27fa2b2015-06-17 16:26:47 +0000460 // Don't waste memory on names of temp labels.
461 Ctx.setUseNamesOnTempLabels(false);
462
Rafael Espindola5560a4c2015-04-14 22:14:34 +0000463 if (!Out->os().supportsSeeking()) {
464 BOS = make_unique<buffer_ostream>(Out->os());
465 OS = BOS.get();
466 }
467
Eric Christopher0169e422015-03-10 22:03:14 +0000468 MCCodeEmitter *CE = TheTarget->createMCCodeEmitter(*MCII, *MRI, Ctx);
Alex Bradburyb22f7512018-01-03 08:53:05 +0000469 MCAsmBackend *MAB = TheTarget->createMCAsmBackend(*STI, *MRI, MCOptions);
David Majnemer03e2cc32015-12-21 22:09:27 +0000470 Str.reset(TheTarget->createMCObjectStreamer(
Lang Hames2241ffa2017-10-11 23:34:47 +0000471 TheTriple, Ctx, std::unique_ptr<MCAsmBackend>(MAB), *OS,
472 std::unique_ptr<MCCodeEmitter>(CE), *STI, MCOptions.MCRelaxAll,
473 MCOptions.MCIncrementalLinkerCompatible,
David Majnemer03e2cc32015-12-21 22:09:27 +0000474 /*DWARFMustBeAtTheEnd*/ false));
Rafael Espindola7b61ddf2014-10-15 16:12:52 +0000475 if (NoExecStack)
476 Str->InitSections(true);
Daniel Dunbar3016db32009-08-21 09:11:24 +0000477 }
Daniel Dunbara10e5192009-06-24 23:30:00 +0000478
Richard Bartondef81b92012-04-16 11:32:10 +0000479 int Res = 1;
Kevin Enderby168ffb32012-12-05 18:13:19 +0000480 bool disassemble = false;
Chris Lattnerd70e15b42009-06-21 05:22:37 +0000481 switch (Action) {
Chris Lattnerb0133452009-06-21 20:16:42 +0000482 case AC_AsLex:
Craig Topper4e05fc32014-12-12 07:52:19 +0000483 Res = AsLexInput(SrcMgr, *MAI, Out->os());
Richard Bartondef81b92012-04-16 11:32:10 +0000484 break;
Chris Lattnerd70e15b42009-06-21 05:22:37 +0000485 case AC_Assemble:
Eric Christopher23c6d1f2014-06-19 06:22:01 +0000486 Res = AssembleInput(ProgName, TheTarget, SrcMgr, Ctx, *Str, *MAI, *STI,
Eric Christopher4c5bff32014-06-19 06:22:08 +0000487 *MCII, MCOptions);
Richard Bartondef81b92012-04-16 11:32:10 +0000488 break;
Kevin Enderby62183c42012-10-22 22:31:46 +0000489 case AC_MDisassemble:
Eli Bendersky6f5d70e2013-02-26 23:04:17 +0000490 assert(IP && "Expected assembly output");
Kevin Enderby62183c42012-10-22 22:31:46 +0000491 IP->setUseMarkup(1);
Kevin Enderby168ffb32012-12-05 18:13:19 +0000492 disassemble = true;
493 break;
Sean Callanan7e645502009-12-17 01:49:59 +0000494 case AC_Disassemble:
Kevin Enderby168ffb32012-12-05 18:13:19 +0000495 disassemble = true;
Richard Bartondef81b92012-04-16 11:32:10 +0000496 break;
Chris Lattnerd70e15b42009-06-21 05:22:37 +0000497 }
Kevin Enderby168ffb32012-12-05 18:13:19 +0000498 if (disassemble)
499 Res = Disassembler::disassemble(*TheTarget, TripleName, *STI, *Str,
500 *Buffer, SrcMgr, Out->os());
Richard Bartondef81b92012-04-16 11:32:10 +0000501
502 // Keep output if no errors.
503 if (Res == 0) Out->keep();
504 return Res;
Chris Lattner8dd8a522009-06-18 23:04:45 +0000505}