blob: c23740a3094df9dc953ccfeb6690f7d701197af7 [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//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Chris Lattner8dd8a522009-06-18 23:04:45 +00006//
7//===----------------------------------------------------------------------===//
8//
Chris Lattnerc7ab9532009-06-18 23:05:21 +00009// This utility is a simple driver that allows command line hacking on machine
10// code.
Chris Lattner8dd8a522009-06-18 23:04:45 +000011//
12//===----------------------------------------------------------------------===//
13
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000014#include "Disassembler.h"
Evan Cheng5928e692011-07-25 23:24:55 +000015#include "llvm/MC/MCAsmBackend.h"
Craig Toppera6e377f2012-04-15 22:00:22 +000016#include "llvm/MC/MCAsmInfo.h"
Lang Hames2241ffa2017-10-11 23:34:47 +000017#include "llvm/MC/MCCodeEmitter.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"
Peter Collingbournef7b81db2018-05-18 18:26:45 +000022#include "llvm/MC/MCObjectWriter.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"
Rui Ueyama197194b2018-04-13 18:26:06 +000034#include "llvm/Support/InitLLVM.h"
Chris Lattner8dd8a522009-06-18 23:04:45 +000035#include "llvm/Support/MemoryBuffer.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000036#include "llvm/Support/SourceMgr.h"
Evan Cheng2bb40352011-08-24 18:08:43 +000037#include "llvm/Support/TargetRegistry.h"
38#include "llvm/Support/TargetSelect.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000039#include "llvm/Support/ToolOutputFile.h"
Jonas Devliegherec976aa72018-04-22 08:01:35 +000040#include "llvm/Support/WithColor.h"
Eugene Zelenkoffec81c2015-11-04 22:32:32 +000041
Chris Lattner8dd8a522009-06-18 23:04:45 +000042using namespace llvm;
43
44static cl::opt<std::string>
45InputFilename(cl::Positional, cl::desc("<input file>"), cl::init("-"));
46
Peter Collingbourne63062d92018-05-21 19:44:54 +000047static cl::opt<std::string> OutputFilename("o", cl::desc("Output filename"),
48 cl::value_desc("filename"),
49 cl::init("-"));
50
51static cl::opt<std::string> SplitDwarfFile("split-dwarf-file",
52 cl::desc("DWO output filename"),
53 cl::value_desc("filename"));
Chris Lattner8dd8a522009-06-18 23:04:45 +000054
Daniel Dunbard18dd1d2009-08-27 07:56:39 +000055static cl::opt<bool>
56ShowEncoding("show-encoding", cl::desc("Show instruction encodings"));
57
Rafael Espindolae021e852016-06-17 17:04:56 +000058static cl::opt<bool> RelaxELFRel(
59 "relax-relocations", cl::init(true),
60 cl::desc("Emit R_X86_64_GOTPCRELX instead of R_X86_64_GOTPCREL"));
Rafael Espindola9768d732016-05-29 01:11:00 +000061
Saleem Abdulrasool1f62f572017-06-09 00:40:19 +000062static cl::opt<DebugCompressionType> CompressDebugSections(
63 "compress-debug-sections", cl::ValueOptional,
64 cl::init(DebugCompressionType::None),
65 cl::desc("Choose DWARF debug sections compression:"),
66 cl::values(clEnumValN(DebugCompressionType::None, "none", "No compression"),
67 clEnumValN(DebugCompressionType::Z, "zlib",
68 "Use zlib compression"),
69 clEnumValN(DebugCompressionType::GNU, "zlib-gnu",
70 "Use zlib-gnu compression (deprecated)")));
David Blaikie7400a972014-03-27 20:45:58 +000071
72static cl::opt<bool>
Daniel Dunbare3ee3322010-02-03 18:18:30 +000073ShowInst("show-inst", cl::desc("Show internal instruction representation"));
74
Daniel Dunbar2eca0252010-08-11 06:37:09 +000075static cl::opt<bool>
76ShowInstOperands("show-inst-operands",
77 cl::desc("Show instructions operands as parsed"));
78
Chris Lattner44790342009-09-20 07:17:49 +000079static cl::opt<unsigned>
80OutputAsmVariant("output-asm-variant",
81 cl::desc("Syntax variant to use for output printing"));
82
Jim Grosbach3fdf7cf2014-06-11 20:26:40 +000083static cl::opt<bool>
84PrintImmHex("print-imm-hex", cl::init(false),
85 cl::desc("Prefer hex format for immediate values"));
86
Colin LeMahieu229a1e62015-06-07 01:46:24 +000087static cl::list<std::string>
88DefineSymbol("defsym", cl::desc("Defines a symbol to be an integer constant"));
89
Nirav Dave53a72f42016-07-11 12:42:14 +000090static cl::opt<bool>
91 PreserveComments("preserve-comments",
92 cl::desc("Preserve Comments in outputted assembly"));
93
Daniel Dunbar3016db32009-08-21 09:11:24 +000094enum OutputFileType {
Daniel Dunbarb09b8902010-03-23 23:47:12 +000095 OFT_Null,
Daniel Dunbar3016db32009-08-21 09:11:24 +000096 OFT_AssemblyFile,
97 OFT_ObjectFile
98};
99static cl::opt<OutputFileType>
100FileType("filetype", cl::init(OFT_AssemblyFile),
101 cl::desc("Choose an output file type:"),
102 cl::values(
103 clEnumValN(OFT_AssemblyFile, "asm",
104 "Emit an assembly ('.s') file"),
Daniel Dunbarb09b8902010-03-23 23:47:12 +0000105 clEnumValN(OFT_Null, "null",
106 "Don't emit anything (for timing purposes)"),
Daniel Dunbar3016db32009-08-21 09:11:24 +0000107 clEnumValN(OFT_ObjectFile, "obj",
Mehdi Amini732afdd2016-10-08 19:41:06 +0000108 "Emit a native object ('.o') file")));
Daniel Dunbar3016db32009-08-21 09:11:24 +0000109
Chris Lattnerd70e15b42009-06-21 05:22:37 +0000110static cl::list<std::string>
111IncludeDirs("I", cl::desc("Directory of include files"),
112 cl::value_desc("directory"), cl::Prefix);
Chris Lattner8dd8a522009-06-18 23:04:45 +0000113
Daniel Dunbar8c6bad22009-07-17 22:38:58 +0000114static cl::opt<std::string>
Daniel Dunbar46892112010-03-13 02:20:38 +0000115ArchName("arch", cl::desc("Target arch to assemble for, "
Bill Wendlinge3031142011-06-17 20:35:21 +0000116 "see -version for available targets"));
Daniel Dunbar46892112010-03-13 02:20:38 +0000117
118static cl::opt<std::string>
Nick Lewyckyb2449092009-11-01 22:07:54 +0000119TripleName("triple", cl::desc("Target triple to assemble for, "
Daniel Dunbar46892112010-03-13 02:20:38 +0000120 "see -version for available targets"));
Daniel Dunbar8c6bad22009-07-17 22:38:58 +0000121
Jim Grosbach685b7732010-10-30 15:57:50 +0000122static cl::opt<std::string>
123MCPU("mcpu",
124 cl::desc("Target a specific cpu type (-mcpu=help for details)"),
125 cl::value_desc("cpu-name"),
126 cl::init(""));
127
James Molloy4c493e82011-09-07 17:24:38 +0000128static cl::list<std::string>
129MAttrs("mattr",
130 cl::CommaSeparated,
131 cl::desc("Target specific attributes (-mattr=help for details)"),
132 cl::value_desc("a1,+a2,-a3,..."));
133
Rafael Espindola699281c2016-05-18 11:58:50 +0000134static cl::opt<bool> PIC("position-independent",
135 cl::desc("Position independent"), cl::init(false));
Evan Cheng2129f592011-07-19 06:37:02 +0000136
Rafael Espindola9f929952017-08-02 20:32:26 +0000137static cl::opt<bool>
138 LargeCodeModel("large-code-model",
139 cl::desc("Create cfi directives that assume the code might "
140 "be more than 2gb away"));
Evan Chengefd9b422011-07-20 07:51:56 +0000141
Daniel Dunbar322fec62010-03-13 02:20:57 +0000142static cl::opt<bool>
Bill Wendlinge3031142011-06-17 20:35:21 +0000143NoInitialTextSection("n", cl::desc("Don't assume assembly file starts "
144 "in the text section"));
Daniel Dunbar322fec62010-03-13 02:20:57 +0000145
Daniel Dunbar4ee0d032011-03-28 22:49:15 +0000146static cl::opt<bool>
Kevin Enderby6469fc22011-11-01 22:27:22 +0000147GenDwarfForAssembly("g", cl::desc("Generate dwarf debugging info for assembly "
148 "source files"));
149
Chandler Carruth10700aad2012-12-17 21:32:42 +0000150static cl::opt<std::string>
151DebugCompilationDir("fdebug-compilation-dir",
152 cl::desc("Specifies the debug info's compilation dir"));
153
Paul Robinsonc17c8bf2018-07-10 14:41:54 +0000154static cl::list<std::string>
155DebugPrefixMap("fdebug-prefix-map",
156 cl::desc("Map file source paths in debug info"),
157 cl::value_desc("= separated key-value pairs"));
158
Eric Christopher906da232012-12-18 00:31:01 +0000159static cl::opt<std::string>
160MainFileName("main-file-name",
161 cl::desc("Specifies the name we should consider the input file"));
162
Eric Christopherdc3e9c72014-05-21 00:20:01 +0000163static cl::opt<bool> SaveTempLabels("save-temp-labels",
164 cl::desc("Don't discard temporary labels"));
165
Reid Kleckner953bdce2018-10-24 20:23:57 +0000166static cl::opt<bool> LexMasmIntegers(
167 "masm-integers",
168 cl::desc("Enable binary and hex masm integers (0b110 and 0ABCh)"));
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) {
Jonas Devliegherec976aa72018-04-22 08:01:35 +0000203 WithColor::error(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
Kai Nackec9ddda82019-10-08 08:21:20 +0000212static std::unique_ptr<ToolOutputFile> GetOutputStream(StringRef Path,
213 sys::fs::OpenFlags Flags) {
Rafael Espindola3fd1e992014-08-25 18:16:47 +0000214 std::error_code EC;
Kai Nackec9ddda82019-10-08 08:21:20 +0000215 auto Out = std::make_unique<ToolOutputFile>(Path, EC, Flags);
Rafael Espindola3fd1e992014-08-25 18:16:47 +0000216 if (EC) {
Jonas Devliegherec976aa72018-04-22 08:01:35 +0000217 WithColor::error() << EC.message() << '\n';
Craig Toppere6cb63e2014-04-25 04:24:47 +0000218 return nullptr;
Dan Gohman268b0f42010-08-20 01:07:01 +0000219 }
Dan Gohmana2233f22010-09-01 14:20:41 +0000220
221 return Out;
Dan Gohman268b0f42010-08-20 01:07:01 +0000222}
223
Kevin Enderbye7739d42011-12-09 18:09:40 +0000224static std::string DwarfDebugFlags;
225static 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
Kevin Enderbye82ada62013-01-16 17:46:23 +0000235static std::string DwarfDebugProducer;
Eugene Zelenkoffec81c2015-11-04 22:32:32 +0000236static void setDwarfDebugProducer() {
Kevin Enderbye82ada62013-01-16 17:46:23 +0000237 if(!getenv("DEBUG_PRODUCER"))
238 return;
239 DwarfDebugProducer += getenv("DEBUG_PRODUCER");
240}
241
Eric Christopher23c6d1f2014-06-19 06:22:01 +0000242static int AsLexInput(SourceMgr &SrcMgr, MCAsmInfo &MAI,
Craig Topper4e05fc32014-12-12 07:52:19 +0000243 raw_ostream &OS) {
Chris Lattnerd70e15b42009-06-21 05:22:37 +0000244
Richard Bartondef81b92012-04-16 11:32:10 +0000245 AsmLexer Lexer(MAI);
Rafael Espindola8026bd02014-07-06 14:17:29 +0000246 Lexer.setBuffer(SrcMgr.getMemoryBuffer(SrcMgr.getMainFileID())->getBuffer());
Daniel Dunbar7a85f9c2010-07-18 18:31:28 +0000247
Chris Lattnerb0133452009-06-21 20:16:42 +0000248 bool Error = false;
Daniel Dunbarbc798162009-07-28 16:56:42 +0000249 while (Lexer.Lex().isNot(AsmToken::Eof)) {
Oliver Stannard5c032ce2018-03-06 14:02:14 +0000250 Lexer.getTok().dump(OS);
251 OS << "\n";
252 if (Lexer.getTok().getKind() == AsmToken::Error)
Chris Lattnerb0133452009-06-21 20:16:42 +0000253 Error = true;
Chris Lattnerc8dfbcb2009-06-21 07:19:10 +0000254 }
Dan Gohman268b0f42010-08-20 01:07:01 +0000255
Chris Lattnerb0133452009-06-21 20:16:42 +0000256 return Error;
Chris Lattnerd70e15b42009-06-21 05:22:37 +0000257}
258
Mandeep Singh Grang32360072016-12-01 18:42:04 +0000259static int fillCommandLineSymbols(MCAsmParser &Parser) {
Mandeep Singh Grang9a561aa2016-12-06 02:49:17 +0000260 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()) {
Jonas Devliegherec976aa72018-04-22 08:01:35 +0000266 WithColor::error() << "defsym must be of the form: sym=value: " << I
267 << "\n";
Colin LeMahieu229a1e62015-06-07 01:46:24 +0000268 return 1;
Mandeep Singh Grang9a561aa2016-12-06 02:49:17 +0000269 }
270 int64_t Value;
271 if (Val.getAsInteger(0, Value)) {
Jonas Devliegherec976aa72018-04-22 08:01:35 +0000272 WithColor::error() << "value is not an integer: " << Val << "\n";
Mandeep Singh Grang9a561aa2016-12-06 02:49:17 +0000273 return 1;
274 }
275 Parser.getContext().setSymbolValue(Parser.getStreamer(), Sym, Value);
276 }
Colin LeMahieu229a1e62015-06-07 01:46:24 +0000277 return 0;
278}
279
NAKAMURA Takumi89b8c172014-01-22 03:12:43 +0000280static int AssembleInput(const char *ProgName, const Target *TheTarget,
Richard Bartondef81b92012-04-16 11:32:10 +0000281 SourceMgr &SrcMgr, MCContext &Ctx, MCStreamer &Str,
Eric Christopher23c6d1f2014-06-19 06:22:01 +0000282 MCAsmInfo &MAI, MCSubtargetInfo &STI,
Brian Cain6dbbd0f2019-08-08 19:13:23 +0000283 MCInstrInfo &MCII, MCTargetOptions const &MCOptions) {
Evgeniy Stepanov0a951b72014-04-23 11:16:03 +0000284 std::unique_ptr<MCAsmParser> Parser(
285 createMCAsmParser(SrcMgr, Ctx, Str, MAI));
Ahmed Charles56440fd2014-03-06 05:51:42 +0000286 std::unique_ptr<MCTargetAsmParser> TAP(
Eric Christopher4c5bff32014-06-19 06:22:08 +0000287 TheTarget->createMCAsmParser(STI, *Parser, MCII, MCOptions));
288
Richard Bartondef81b92012-04-16 11:32:10 +0000289 if (!TAP) {
Jonas Devliegherec976aa72018-04-22 08:01:35 +0000290 WithColor::error(errs(), ProgName)
291 << "this target does not support assembly parsing.\n";
Richard Bartondef81b92012-04-16 11:32:10 +0000292 return 1;
293 }
294
Colin LeMahieu229a1e62015-06-07 01:46:24 +0000295 int SymbolResult = fillCommandLineSymbols(*Parser);
296 if(SymbolResult)
297 return SymbolResult;
Richard Bartondef81b92012-04-16 11:32:10 +0000298 Parser->setShowParsedOperands(ShowInstOperands);
Craig Topper4e05fc32014-12-12 07:52:19 +0000299 Parser->setTargetParser(*TAP);
Reid Kleckner953bdce2018-10-24 20:23:57 +0000300 Parser->getLexer().setLexMasmIntegers(LexMasmIntegers);
Richard Bartondef81b92012-04-16 11:32:10 +0000301
302 int Res = Parser->Run(NoInitialTextSection);
303
304 return Res;
305}
306
307int main(int argc, char **argv) {
Rui Ueyama197194b2018-04-13 18:26:06 +0000308 InitLLVM X(argc, argv);
Richard Bartondef81b92012-04-16 11:32:10 +0000309
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");
Brian Cain6dbbd0f2019-08-08 19:13:23 +0000320 const MCTargetOptions MCOptions = InitMCTargetOptionsFromFlags();
Richard Bartondef81b92012-04-16 11:32:10 +0000321 setDwarfDebugFlags(argc, argv);
322
Kevin Enderbye82ada62013-01-16 17:46:23 +0000323 setDwarfDebugProducer();
324
Richard Bartondef81b92012-04-16 11:32:10 +0000325 const char *ProgName = argv[0];
Daniel Dunbar80d484e2009-08-14 03:48:55 +0000326 const Target *TheTarget = GetTarget(ProgName);
327 if (!TheTarget)
328 return 1;
Daniel Sandersc535d932015-06-16 09:57:38 +0000329 // Now that GetTarget() has (potentially) replaced TripleName, it's safe to
330 // construct the Triple object.
331 Triple TheTriple(TripleName);
Daniel Dunbar80d484e2009-08-14 03:48:55 +0000332
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000333 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferPtr =
334 MemoryBuffer::getFileOrSTDIN(InputFilename);
335 if (std::error_code EC = BufferPtr.getError()) {
Jonas Devliegherec976aa72018-04-22 08:01:35 +0000336 WithColor::error(errs(), ProgName)
337 << InputFilename << ": " << EC.message() << '\n';
Chris Lattnerb0133452009-06-21 20:16:42 +0000338 return 1;
339 }
David Blaikie1961f142014-08-21 20:44:56 +0000340 MemoryBuffer *Buffer = BufferPtr->get();
Jim Grosbach112a2de2011-05-09 20:05:25 +0000341
Chris Lattnerb0133452009-06-21 20:16:42 +0000342 SourceMgr SrcMgr;
Jim Grosbach112a2de2011-05-09 20:05:25 +0000343
Daniel Dunbar5c947db2009-08-19 16:25:53 +0000344 // Tell SrcMgr about this buffer, which is what the parser will pick up.
David Blaikie1961f142014-08-21 20:44:56 +0000345 SrcMgr.AddNewSourceBuffer(std::move(*BufferPtr), SMLoc());
Jim Grosbach112a2de2011-05-09 20:05:25 +0000346
Chris Lattnerb0133452009-06-21 20:16:42 +0000347 // Record the location of the include directories so that the lexer can find
348 // it later.
349 SrcMgr.setIncludeDirs(IncludeDirs);
Jim Grosbach112a2de2011-05-09 20:05:25 +0000350
Ahmed Charles56440fd2014-03-06 05:51:42 +0000351 std::unique_ptr<MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TripleName));
Evan Chengd60fa58b2011-07-18 20:57:22 +0000352 assert(MRI && "Unable to create target register info!");
353
Ahmed Charles56440fd2014-03-06 05:51:42 +0000354 std::unique_ptr<MCAsmInfo> MAI(TheTarget->createMCAsmInfo(*MRI, TripleName));
Rafael Espindola227144c2013-05-13 01:16:13 +0000355 assert(MAI && "Unable to create target asm info!");
356
Rafael Espindola9768d732016-05-29 01:11:00 +0000357 MAI->setRelaxELFRelocations(RelaxELFRel);
358
Saleem Abdulrasool1f62f572017-06-09 00:40:19 +0000359 if (CompressDebugSections != DebugCompressionType::None) {
David Blaikie9b620b42014-03-28 20:45:24 +0000360 if (!zlib::isAvailable()) {
Jonas Devliegherec976aa72018-04-22 08:01:35 +0000361 WithColor::error(errs(), ProgName)
362 << "build tools with zlib to enable -compress-debug-sections";
David Blaikie9b620b42014-03-28 20:45:24 +0000363 return 1;
364 }
George Rimarc91e38c2016-05-27 12:27:32 +0000365 MAI->setCompressDebugSections(CompressDebugSections);
David Blaikie9b620b42014-03-28 20:45:24 +0000366 }
Nirav Dave53a72f42016-07-11 12:42:14 +0000367 MAI->setPreserveAsmComments(PreserveComments);
David Blaikie7400a972014-03-27 20:45:58 +0000368
Evan Cheng76792992011-07-20 05:58:47 +0000369 // FIXME: This is not pretty. MCContext has a ptr to MCObjectFileInfo and
370 // MCObjectFileInfo needs a MCContext reference in order to initialize itself.
Rafael Espindola75556bc2014-06-28 17:46:19 +0000371 MCObjectFileInfo MOFI;
Brian Cain6dbbd0f2019-08-08 19:13:23 +0000372 MCContext Ctx(MAI.get(), MRI.get(), &MOFI, &SrcMgr, &MCOptions);
Rafael Espindola9f929952017-08-02 20:32:26 +0000373 MOFI.InitMCObjectFileInfo(TheTriple, PIC, Ctx, LargeCodeModel);
Evan Cheng76792992011-07-20 05:58:47 +0000374
Daniel Dunbar4ee0d032011-03-28 22:49:15 +0000375 if (SaveTempLabels)
376 Ctx.setAllowTemporaryLabels(false);
Rafael Espindola0a017a62010-12-10 07:39:47 +0000377
Kevin Enderby6469fc22011-11-01 22:27:22 +0000378 Ctx.setGenDwarfForAssembly(GenDwarfForAssembly);
Eric Christopher4c5bff32014-06-19 06:22:08 +0000379 // Default to 4 for dwarf version.
380 unsigned DwarfVersion = MCOptions.DwarfVersion ? MCOptions.DwarfVersion : 4;
Paul Robinsondccb4fe2017-02-28 23:40:46 +0000381 if (DwarfVersion < 2 || DwarfVersion > 5) {
Oliver Stannard7eacbd52014-05-01 08:46:02 +0000382 errs() << ProgName << ": Dwarf version " << DwarfVersion
383 << " is not supported." << '\n';
384 return 1;
385 }
386 Ctx.setDwarfVersion(DwarfVersion);
Chandler Carruth10700aad2012-12-17 21:32:42 +0000387 if (!DwarfDebugFlags.empty())
Kevin Enderbye7739d42011-12-09 18:09:40 +0000388 Ctx.setDwarfDebugFlags(StringRef(DwarfDebugFlags));
Kevin Enderbye82ada62013-01-16 17:46:23 +0000389 if (!DwarfDebugProducer.empty())
390 Ctx.setDwarfDebugProducer(StringRef(DwarfDebugProducer));
Chandler Carruth10700aad2012-12-17 21:32:42 +0000391 if (!DebugCompilationDir.empty())
392 Ctx.setCompilationDir(DebugCompilationDir);
Justin Bogner8809c402016-03-22 22:24:29 +0000393 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 }
Paul Robinsonc17c8bf2018-07-10 14:41:54 +0000399 for (const auto &Arg : DebugPrefixMap) {
400 const auto &KV = StringRef(Arg).split('=');
401 Ctx.addDebugPrefixMapEntry(KV.first, KV.second);
402 }
Eric Christopher906da232012-12-18 00:31:01 +0000403 if (!MainFileName.empty())
404 Ctx.setMainFileName(MainFileName);
Paul Robinson1ca25762019-03-01 20:58:04 +0000405 if (GenDwarfForAssembly)
406 Ctx.setGenDwarfRootFile(InputFilename, Buffer->getBuffer());
Kevin Enderby6469fc22011-11-01 22:27:22 +0000407
James Molloy4c493e82011-09-07 17:24:38 +0000408 // Package up features to be passed to target/subtarget
409 std::string FeaturesStr;
410 if (MAttrs.size()) {
411 SubtargetFeatures Features;
412 for (unsigned i = 0; i != MAttrs.size(); ++i)
413 Features.AddFeature(MAttrs[i]);
414 FeaturesStr = Features.getString();
415 }
416
Kai Nackec9ddda82019-10-08 08:21:20 +0000417 sys::fs::OpenFlags Flags = (FileType == OFT_AssemblyFile) ? sys::fs::OF_Text
418 : sys::fs::OF_None;
419 std::unique_ptr<ToolOutputFile> Out = GetOutputStream(OutputFilename, Flags);
Dan Gohman268b0f42010-08-20 01:07:01 +0000420 if (!Out)
421 return 1;
422
Peter Collingbourne63062d92018-05-21 19:44:54 +0000423 std::unique_ptr<ToolOutputFile> DwoOut;
424 if (!SplitDwarfFile.empty()) {
425 if (FileType != OFT_ObjectFile) {
426 WithColor::error() << "dwo output only supported with object files\n";
427 return 1;
428 }
Kai Nackec9ddda82019-10-08 08:21:20 +0000429 DwoOut = GetOutputStream(SplitDwarfFile, sys::fs::OF_None);
Peter Collingbourne63062d92018-05-21 19:44:54 +0000430 if (!DwoOut)
431 return 1;
432 }
433
Rafael Espindola5560a4c2015-04-14 22:14:34 +0000434 std::unique_ptr<buffer_ostream> BOS;
435 raw_pwrite_stream *OS = &Out->os();
Ahmed Charles56440fd2014-03-06 05:51:42 +0000436 std::unique_ptr<MCStreamer> Str;
Chris Lattnera61e93d2009-08-17 04:23:44 +0000437
Ahmed Charles56440fd2014-03-06 05:51:42 +0000438 std::unique_ptr<MCInstrInfo> MCII(TheTarget->createMCInstrInfo());
439 std::unique_ptr<MCSubtargetInfo> STI(
440 TheTarget->createMCSubtargetInfo(TripleName, MCPU, FeaturesStr));
Evan Cheng91111d22011-07-09 05:47:46 +0000441
Craig Toppere6cb63e2014-04-25 04:24:47 +0000442 MCInstPrinter *IP = nullptr;
Kevin Enderbyf92f9902009-09-04 21:45:34 +0000443 if (FileType == OFT_AssemblyFile) {
Daniel Sanders50f17232015-09-15 16:17:27 +0000444 IP = TheTarget->createMCInstPrinter(Triple(TripleName), OutputAsmVariant,
445 *MAI, *MCII, *MRI);
Jim Grosbach3fdf7cf2014-06-11 20:26:40 +0000446
Nirav Davea9395af2016-10-31 18:36:31 +0000447 if (!IP) {
Jonas Devliegherec976aa72018-04-22 08:01:35 +0000448 WithColor::error()
449 << "unable to create instruction printer for target triple '"
Nirav Davea9395af2016-10-31 18:36:31 +0000450 << TheTriple.normalize() << "' with assembly variant "
451 << OutputAsmVariant << ".\n";
452 return 1;
453 }
454
Jim Grosbach3fdf7cf2014-06-11 20:26:40 +0000455 // Set the display preference for hex vs. decimal immediates.
456 IP->setPrintImmHex(PrintImmHex);
457
458 // Set up the AsmStreamer.
Nirav Dave1b5533c2018-04-27 15:45:54 +0000459 std::unique_ptr<MCCodeEmitter> CE;
460 if (ShowEncoding)
461 CE.reset(TheTarget->createMCCodeEmitter(*MCII, *MRI, Ctx));
462
463 std::unique_ptr<MCAsmBackend> MAB(
464 TheTarget->createMCAsmBackend(*STI, *MRI, MCOptions));
Jonas Devlieghere0eaee542019-08-15 15:54:37 +0000465 auto FOut = std::make_unique<formatted_raw_ostream>(*OS);
Nirav Dave1b5533c2018-04-27 15:45:54 +0000466 Str.reset(
467 TheTarget->createAsmStreamer(Ctx, std::move(FOut), /*asmverbose*/ true,
468 /*useDwarfDirectory*/ true, IP,
469 std::move(CE), std::move(MAB), ShowInst));
Jim Grosbach78309c42011-12-05 23:20:14 +0000470
Daniel Dunbarb09b8902010-03-23 23:47:12 +0000471 } else if (FileType == OFT_Null) {
Peter Collingbournef4498a42015-02-19 00:45:04 +0000472 Str.reset(TheTarget->createNullStreamer(Ctx));
Daniel Dunbar3016db32009-08-21 09:11:24 +0000473 } else {
474 assert(FileType == OFT_ObjectFile && "Invalid file type!");
Rafael Espindola5560a4c2015-04-14 22:14:34 +0000475
Rafael Espindolaf27fa2b2015-06-17 16:26:47 +0000476 // Don't waste memory on names of temp labels.
477 Ctx.setUseNamesOnTempLabels(false);
478
Rafael Espindola5560a4c2015-04-14 22:14:34 +0000479 if (!Out->os().supportsSeeking()) {
Jonas Devlieghere0eaee542019-08-15 15:54:37 +0000480 BOS = std::make_unique<buffer_ostream>(Out->os());
Rafael Espindola5560a4c2015-04-14 22:14:34 +0000481 OS = BOS.get();
482 }
483
Eric Christopher0169e422015-03-10 22:03:14 +0000484 MCCodeEmitter *CE = TheTarget->createMCCodeEmitter(*MCII, *MRI, Ctx);
Alex Bradburyb22f7512018-01-03 08:53:05 +0000485 MCAsmBackend *MAB = TheTarget->createMCAsmBackend(*STI, *MRI, MCOptions);
David Majnemer03e2cc32015-12-21 22:09:27 +0000486 Str.reset(TheTarget->createMCObjectStreamer(
Peter Collingbournef7b81db2018-05-18 18:26:45 +0000487 TheTriple, Ctx, std::unique_ptr<MCAsmBackend>(MAB),
Peter Collingbourne63062d92018-05-21 19:44:54 +0000488 DwoOut ? MAB->createDwoObjectWriter(*OS, DwoOut->os())
489 : MAB->createObjectWriter(*OS),
490 std::unique_ptr<MCCodeEmitter>(CE), *STI, MCOptions.MCRelaxAll,
491 MCOptions.MCIncrementalLinkerCompatible,
David Majnemer03e2cc32015-12-21 22:09:27 +0000492 /*DWARFMustBeAtTheEnd*/ false));
Rafael Espindola7b61ddf2014-10-15 16:12:52 +0000493 if (NoExecStack)
494 Str->InitSections(true);
Daniel Dunbar3016db32009-08-21 09:11:24 +0000495 }
Daniel Dunbara10e5192009-06-24 23:30:00 +0000496
Nirav Dave6c0665e2018-04-30 19:22:40 +0000497 // Use Assembler information for parsing.
498 Str->setUseAssemblerInfoForParsing(true);
499
Richard Bartondef81b92012-04-16 11:32:10 +0000500 int Res = 1;
Kevin Enderby168ffb32012-12-05 18:13:19 +0000501 bool disassemble = false;
Chris Lattnerd70e15b42009-06-21 05:22:37 +0000502 switch (Action) {
Chris Lattnerb0133452009-06-21 20:16:42 +0000503 case AC_AsLex:
Craig Topper4e05fc32014-12-12 07:52:19 +0000504 Res = AsLexInput(SrcMgr, *MAI, Out->os());
Richard Bartondef81b92012-04-16 11:32:10 +0000505 break;
Chris Lattnerd70e15b42009-06-21 05:22:37 +0000506 case AC_Assemble:
Eric Christopher23c6d1f2014-06-19 06:22:01 +0000507 Res = AssembleInput(ProgName, TheTarget, SrcMgr, Ctx, *Str, *MAI, *STI,
Eric Christopher4c5bff32014-06-19 06:22:08 +0000508 *MCII, MCOptions);
Richard Bartondef81b92012-04-16 11:32:10 +0000509 break;
Kevin Enderby62183c42012-10-22 22:31:46 +0000510 case AC_MDisassemble:
Eli Bendersky6f5d70e2013-02-26 23:04:17 +0000511 assert(IP && "Expected assembly output");
Fangrui Song05885882019-07-25 09:54:12 +0000512 IP->setUseMarkup(true);
Kevin Enderby168ffb32012-12-05 18:13:19 +0000513 disassemble = true;
514 break;
Sean Callanan7e645502009-12-17 01:49:59 +0000515 case AC_Disassemble:
Kevin Enderby168ffb32012-12-05 18:13:19 +0000516 disassemble = true;
Richard Bartondef81b92012-04-16 11:32:10 +0000517 break;
Chris Lattnerd70e15b42009-06-21 05:22:37 +0000518 }
Kevin Enderby168ffb32012-12-05 18:13:19 +0000519 if (disassemble)
Thomas Lively2cb27072019-10-15 18:28:22 +0000520 Res = Disassembler::disassemble(*TheTarget, TripleName, *STI, *Str, *Buffer,
521 SrcMgr, Ctx, Out->os());
Richard Bartondef81b92012-04-16 11:32:10 +0000522
523 // Keep output if no errors.
Peter Collingbourne63062d92018-05-21 19:44:54 +0000524 if (Res == 0) {
525 Out->keep();
526 if (DwoOut)
527 DwoOut->keep();
528 }
Richard Bartondef81b92012-04-16 11:32:10 +0000529 return Res;
Chris Lattner8dd8a522009-06-18 23:04:45 +0000530}