blob: 05edb9f4386e0755029f4b9702f0e8eeb02c7522 [file] [log] [blame]
Daniel Dunbar2fcaa542010-05-20 17:49:16 +00001//===-- cc1as_main.cpp - Clang Assembler ---------------------------------===//
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 is the entry point to the clang -cc1as functionality, which implements
11// the direct interface to the LLVM MC based assembler.
12//
13//===----------------------------------------------------------------------===//
14
15#include "clang/Basic/Diagnostic.h"
Chandler Carruthcc0694c2012-12-04 09:25:21 +000016#include "clang/Basic/DiagnosticOptions.h"
Chandler Carruthcc0694c2012-12-04 09:25:21 +000017#include "clang/Driver/DriverDiagnostic.h"
Daniel Dunbar2fcaa542010-05-20 17:49:16 +000018#include "clang/Driver/Options.h"
Daniel Dunbar2fcaa542010-05-20 17:49:16 +000019#include "clang/Frontend/FrontendDiagnostic.h"
20#include "clang/Frontend/TextDiagnosticPrinter.h"
Reid Kleckner898229a2013-06-14 17:17:23 +000021#include "clang/Frontend/Utils.h"
Rafael Espindola4dedcd72015-04-09 21:06:11 +000022#include "llvm/ADT/STLExtras.h"
Daniel Dunbar2fcaa542010-05-20 17:49:16 +000023#include "llvm/ADT/StringSwitch.h"
Duncan Sandsf610b5b2010-08-30 09:42:39 +000024#include "llvm/ADT/Triple.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000025#include "llvm/IR/DataLayout.h"
Chandler Carruthcc0694c2012-12-04 09:25:21 +000026#include "llvm/MC/MCAsmBackend.h"
Daniel Dunbar05474282010-07-17 02:26:21 +000027#include "llvm/MC/MCAsmInfo.h"
Daniel Dunbar2fcaa542010-05-20 17:49:16 +000028#include "llvm/MC/MCCodeEmitter.h"
29#include "llvm/MC/MCContext.h"
Evan Cheng279f2902011-07-11 04:24:19 +000030#include "llvm/MC/MCInstrInfo.h"
Evan Cheng347033f2011-07-20 06:22:27 +000031#include "llvm/MC/MCObjectFileInfo.h"
Peter Collingbournef7b81db2018-05-18 18:26:45 +000032#include "llvm/MC/MCObjectWriter.h"
Chandler Carruthcc0694c2012-12-04 09:25:21 +000033#include "llvm/MC/MCParser/MCAsmParser.h"
Benjamin Kramer5e456302016-01-27 10:01:30 +000034#include "llvm/MC/MCParser/MCTargetAsmParser.h"
Evan Chengb505ace2011-07-18 20:57:51 +000035#include "llvm/MC/MCRegisterInfo.h"
Daniel Dunbar2fcaa542010-05-20 17:49:16 +000036#include "llvm/MC/MCStreamer.h"
Evan Chengdec31872011-07-09 06:04:17 +000037#include "llvm/MC/MCSubtargetInfo.h"
Evgeniy Stepanoveeb820f2014-04-23 11:15:49 +000038#include "llvm/MC/MCTargetOptions.h"
Reid Kleckner898229a2013-06-14 17:17:23 +000039#include "llvm/Option/Arg.h"
40#include "llvm/Option/ArgList.h"
41#include "llvm/Option/OptTable.h"
Daniel Dunbar0454f652010-05-20 18:15:20 +000042#include "llvm/Support/CommandLine.h"
Daniel Dunbar2fcaa542010-05-20 17:49:16 +000043#include "llvm/Support/ErrorHandling.h"
Rafael Espindolaccc6ea62013-06-26 12:48:34 +000044#include "llvm/Support/FileSystem.h"
Chandler Carruthcc0694c2012-12-04 09:25:21 +000045#include "llvm/Support/FormattedStream.h"
46#include "llvm/Support/Host.h"
Daniel Dunbar2fcaa542010-05-20 17:49:16 +000047#include "llvm/Support/MemoryBuffer.h"
Michael J. Spencer8aaf4992010-11-29 18:12:39 +000048#include "llvm/Support/Path.h"
49#include "llvm/Support/Signals.h"
Chandler Carruthcc0694c2012-12-04 09:25:21 +000050#include "llvm/Support/SourceMgr.h"
Evan Cheng494eb062011-08-24 18:09:14 +000051#include "llvm/Support/TargetRegistry.h"
52#include "llvm/Support/TargetSelect.h"
53#include "llvm/Support/Timer.h"
54#include "llvm/Support/raw_ostream.h"
Ahmed Charlesdfca6f92014-03-09 11:36:40 +000055#include <memory>
Rafael Espindola8a8e5542014-06-12 17:19:42 +000056#include <system_error>
Daniel Dunbar2fcaa542010-05-20 17:49:16 +000057using namespace clang;
58using namespace clang::driver;
Alp Toker61dad752014-07-09 14:05:11 +000059using namespace clang::driver::options;
Daniel Dunbar2fcaa542010-05-20 17:49:16 +000060using namespace llvm;
Reid Kleckner898229a2013-06-14 17:17:23 +000061using namespace llvm::opt;
Daniel Dunbar2fcaa542010-05-20 17:49:16 +000062
63namespace {
64
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000065/// Helper class for representing a single invocation of the assembler.
Daniel Dunbar2fcaa542010-05-20 17:49:16 +000066struct AssemblerInvocation {
67 /// @name Target Options
68 /// @{
69
Jim Grosbach576452b2012-02-10 20:37:10 +000070 /// The name of the target triple to assemble for.
Daniel Dunbar2fcaa542010-05-20 17:49:16 +000071 std::string Triple;
72
Jim Grosbach576452b2012-02-10 20:37:10 +000073 /// If given, the name of the target CPU to determine which instructions
74 /// are legal.
75 std::string CPU;
76
77 /// The list of target specific features to enable or disable -- this should
78 /// be a list of strings starting with '+' or '-'.
79 std::vector<std::string> Features;
80
Mandeep Singh Grang358faec2016-12-01 18:42:16 +000081 /// The list of symbol definitions.
82 std::vector<std::string> SymbolDefs;
83
Daniel Dunbar2fcaa542010-05-20 17:49:16 +000084 /// @}
85 /// @name Language Options
86 /// @{
87
88 std::vector<std::string> IncludePaths;
89 unsigned NoInitialTextSection : 1;
Daniel Dunbar9cf7bc72011-03-28 22:49:24 +000090 unsigned SaveTemporaryLabels : 1;
Kevin Enderby292dc082011-12-22 19:31:58 +000091 unsigned GenDwarfForAssembly : 1;
Rafael Espindolaf8f01c32016-05-29 02:01:14 +000092 unsigned RelaxELFRelocations : 1;
Oliver Stannard9b2a7d42014-05-19 13:39:13 +000093 unsigned DwarfVersion;
Kevin Enderby292dc082011-12-22 19:31:58 +000094 std::string DwarfDebugFlags;
Kevin Enderbyae2ec472013-01-17 21:38:06 +000095 std::string DwarfDebugProducer;
Chandler Carruth4d5e1a92012-12-17 21:40:04 +000096 std::string DebugCompilationDir;
Saleem Abdulrasool54448902017-06-09 00:40:30 +000097 llvm::DebugCompressionType CompressDebugSections =
98 llvm::DebugCompressionType::None;
Eric Christopher45f2e712012-12-18 00:31:10 +000099 std::string MainFileName;
Peter Collingbourne47bc0172018-05-21 20:31:59 +0000100 std::string SplitDwarfFile;
Daniel Dunbar2fcaa542010-05-20 17:49:16 +0000101
102 /// @}
103 /// @name Frontend Options
104 /// @{
105
106 std::string InputFile;
Daniel Dunbar0454f652010-05-20 18:15:20 +0000107 std::vector<std::string> LLVMArgs;
Daniel Dunbar2fcaa542010-05-20 17:49:16 +0000108 std::string OutputPath;
109 enum FileType {
110 FT_Asm, ///< Assembly (.s) output, transliterate mode.
111 FT_Null, ///< No output, for timing purposes.
112 FT_Obj ///< Object file output.
113 };
114 FileType OutputType;
Daniel Dunbar0454f652010-05-20 18:15:20 +0000115 unsigned ShowHelp : 1;
116 unsigned ShowVersion : 1;
Daniel Dunbar2fcaa542010-05-20 17:49:16 +0000117
118 /// @}
119 /// @name Transliterate Options
120 /// @{
121
122 unsigned OutputAsmVariant;
123 unsigned ShowEncoding : 1;
124 unsigned ShowInst : 1;
125
126 /// @}
127 /// @name Assembler Options
128 /// @{
129
130 unsigned RelaxAll : 1;
Rafael Espindola148141c2011-01-23 17:58:26 +0000131 unsigned NoExecStack : 1;
Joerg Sonnenbergera43604a2014-08-26 18:40:25 +0000132 unsigned FatalWarnings : 1;
David Majnemer2b9349d2015-12-21 22:09:34 +0000133 unsigned IncrementalLinkerCompatible : 1;
Daniel Dunbar2fcaa542010-05-20 17:49:16 +0000134
Joerg Sonnenberger924f6ad2015-09-18 11:13:43 +0000135 /// The name of the relocation model to use.
136 std::string RelocationModel;
137
Daniel Dunbar2fcaa542010-05-20 17:49:16 +0000138 /// @}
139
140public:
141 AssemblerInvocation() {
142 Triple = "";
143 NoInitialTextSection = 0;
144 InputFile = "-";
Daniel Dunbar0454f652010-05-20 18:15:20 +0000145 OutputPath = "-";
Daniel Dunbar2fcaa542010-05-20 17:49:16 +0000146 OutputType = FT_Asm;
147 OutputAsmVariant = 0;
148 ShowInst = 0;
149 ShowEncoding = 0;
150 RelaxAll = 0;
Rafael Espindola148141c2011-01-23 17:58:26 +0000151 NoExecStack = 0;
Joerg Sonnenbergera43604a2014-08-26 18:40:25 +0000152 FatalWarnings = 0;
David Majnemer2b9349d2015-12-21 22:09:34 +0000153 IncrementalLinkerCompatible = 0;
Douglas Katzman722bcb02015-10-13 16:22:51 +0000154 DwarfVersion = 0;
Daniel Dunbar2fcaa542010-05-20 17:49:16 +0000155 }
156
Sean Silva070cd2d2014-08-15 21:38:36 +0000157 static bool CreateFromArgs(AssemblerInvocation &Res,
158 ArrayRef<const char *> Argv,
159 DiagnosticsEngine &Diags);
Daniel Dunbar2fcaa542010-05-20 17:49:16 +0000160};
161
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000162}
Daniel Dunbar2fcaa542010-05-20 17:49:16 +0000163
Dylan Noblesmithe99b27f2011-12-23 03:05:38 +0000164bool AssemblerInvocation::CreateFromArgs(AssemblerInvocation &Opts,
Sean Silva070cd2d2014-08-15 21:38:36 +0000165 ArrayRef<const char *> Argv,
David Blaikie9c902b52011-09-25 23:23:43 +0000166 DiagnosticsEngine &Diags) {
Dylan Noblesmithe99b27f2011-12-23 03:05:38 +0000167 bool Success = true;
168
Daniel Dunbar2fcaa542010-05-20 17:49:16 +0000169 // Parse the arguments.
Alp Toker61dad752014-07-09 14:05:11 +0000170 std::unique_ptr<OptTable> OptTbl(createDriverOptTable());
171
172 const unsigned IncludedFlagsBitmask = options::CC1AsOption;
Daniel Dunbar2fcaa542010-05-20 17:49:16 +0000173 unsigned MissingArgIndex, MissingArgCount;
David Blaikie69a1d8c2015-06-22 22:07:27 +0000174 InputArgList Args = OptTbl->ParseArgs(Argv, MissingArgIndex, MissingArgCount,
175 IncludedFlagsBitmask);
Daniel Dunbar2fcaa542010-05-20 17:49:16 +0000176
177 // Check for missing argument error.
Dylan Noblesmithe99b27f2011-12-23 03:05:38 +0000178 if (MissingArgCount) {
Daniel Dunbar2fcaa542010-05-20 17:49:16 +0000179 Diags.Report(diag::err_drv_missing_argument)
David Blaikie69a1d8c2015-06-22 22:07:27 +0000180 << Args.getArgString(MissingArgIndex) << MissingArgCount;
Dylan Noblesmithe99b27f2011-12-23 03:05:38 +0000181 Success = false;
182 }
Daniel Dunbar2fcaa542010-05-20 17:49:16 +0000183
184 // Issue errors on unknown arguments.
David Blaikie69a1d8c2015-06-22 22:07:27 +0000185 for (const Arg *A : Args.filtered(OPT_UNKNOWN)) {
Brian Gesiakceb987f2018-01-13 17:09:11 +0000186 auto ArgString = A->getAsString(Args);
187 std::string Nearest;
188 if (OptTbl->findNearest(ArgString, Nearest, IncludedFlagsBitmask) > 1)
189 Diags.Report(diag::err_drv_unknown_argument) << ArgString;
190 else
191 Diags.Report(diag::err_drv_unknown_argument_with_suggestion)
192 << ArgString << Nearest;
Dylan Noblesmithe99b27f2011-12-23 03:05:38 +0000193 Success = false;
194 }
Daniel Dunbar2fcaa542010-05-20 17:49:16 +0000195
196 // Construct the invocation.
197
198 // Target Options
David Blaikie69a1d8c2015-06-22 22:07:27 +0000199 Opts.Triple = llvm::Triple::normalize(Args.getLastArgValue(OPT_triple));
200 Opts.CPU = Args.getLastArgValue(OPT_target_cpu);
201 Opts.Features = Args.getAllArgValues(OPT_target_feature);
Jim Grosbach576452b2012-02-10 20:37:10 +0000202
203 // Use the default target triple if unspecified.
204 if (Opts.Triple.empty())
205 Opts.Triple = llvm::sys::getDefaultTargetTriple();
Daniel Dunbar2fcaa542010-05-20 17:49:16 +0000206
207 // Language Options
David Blaikie69a1d8c2015-06-22 22:07:27 +0000208 Opts.IncludePaths = Args.getAllArgValues(OPT_I);
209 Opts.NoInitialTextSection = Args.hasArg(OPT_n);
210 Opts.SaveTemporaryLabels = Args.hasArg(OPT_msave_temp_labels);
Douglas Katzman3459ce22015-10-08 04:24:12 +0000211 // Any DebugInfoKind implies GenDwarfForAssembly.
212 Opts.GenDwarfForAssembly = Args.hasArg(OPT_debug_info_kind_EQ);
Saleem Abdulrasoold064e912017-06-23 15:34:16 +0000213
214 if (const Arg *A = Args.getLastArg(OPT_compress_debug_sections,
215 OPT_compress_debug_sections_EQ)) {
216 if (A->getOption().getID() == OPT_compress_debug_sections) {
217 // TODO: be more clever about the compression type auto-detection
218 Opts.CompressDebugSections = llvm::DebugCompressionType::GNU;
219 } else {
220 Opts.CompressDebugSections =
221 llvm::StringSwitch<llvm::DebugCompressionType>(A->getValue())
222 .Case("none", llvm::DebugCompressionType::None)
223 .Case("zlib", llvm::DebugCompressionType::Z)
224 .Case("zlib-gnu", llvm::DebugCompressionType::GNU)
225 .Default(llvm::DebugCompressionType::None);
226 }
227 }
228
Rafael Espindolaf8f01c32016-05-29 02:01:14 +0000229 Opts.RelaxELFRelocations = Args.hasArg(OPT_mrelax_relocations);
Adrian Prantlae39ccc2016-04-19 20:31:19 +0000230 Opts.DwarfVersion = getLastArgIntValue(Args, OPT_dwarf_version_EQ, 2, Diags);
David Blaikie69a1d8c2015-06-22 22:07:27 +0000231 Opts.DwarfDebugFlags = Args.getLastArgValue(OPT_dwarf_debug_flags);
232 Opts.DwarfDebugProducer = Args.getLastArgValue(OPT_dwarf_debug_producer);
233 Opts.DebugCompilationDir = Args.getLastArgValue(OPT_fdebug_compilation_dir);
234 Opts.MainFileName = Args.getLastArgValue(OPT_main_file_name);
Daniel Dunbar2fcaa542010-05-20 17:49:16 +0000235
236 // Frontend Options
David Blaikie69a1d8c2015-06-22 22:07:27 +0000237 if (Args.hasArg(OPT_INPUT)) {
Daniel Dunbar2fcaa542010-05-20 17:49:16 +0000238 bool First = true;
Richard Smith0aef3052017-02-18 01:14:43 +0000239 for (const Arg *A : Args.filtered(OPT_INPUT)) {
240 if (First) {
Richard Smithbd55daf2012-11-01 04:30:05 +0000241 Opts.InputFile = A->getValue();
Richard Smith0aef3052017-02-18 01:14:43 +0000242 First = false;
243 } else {
David Blaikie69a1d8c2015-06-22 22:07:27 +0000244 Diags.Report(diag::err_drv_unknown_argument) << A->getAsString(Args);
Dylan Noblesmithe99b27f2011-12-23 03:05:38 +0000245 Success = false;
246 }
Daniel Dunbar2fcaa542010-05-20 17:49:16 +0000247 }
248 }
David Blaikie69a1d8c2015-06-22 22:07:27 +0000249 Opts.LLVMArgs = Args.getAllArgValues(OPT_mllvm);
250 Opts.OutputPath = Args.getLastArgValue(OPT_o);
Peter Collingbourne47bc0172018-05-21 20:31:59 +0000251 Opts.SplitDwarfFile = Args.getLastArgValue(OPT_split_dwarf_file);
David Blaikie69a1d8c2015-06-22 22:07:27 +0000252 if (Arg *A = Args.getLastArg(OPT_filetype)) {
Richard Smithbd55daf2012-11-01 04:30:05 +0000253 StringRef Name = A->getValue();
Daniel Dunbar2fcaa542010-05-20 17:49:16 +0000254 unsigned OutputType = StringSwitch<unsigned>(Name)
255 .Case("asm", FT_Asm)
256 .Case("null", FT_Null)
257 .Case("obj", FT_Obj)
258 .Default(~0U);
Dylan Noblesmithe99b27f2011-12-23 03:05:38 +0000259 if (OutputType == ~0U) {
David Blaikie69a1d8c2015-06-22 22:07:27 +0000260 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Name;
Dylan Noblesmithe99b27f2011-12-23 03:05:38 +0000261 Success = false;
262 } else
Daniel Dunbar2fcaa542010-05-20 17:49:16 +0000263 Opts.OutputType = FileType(OutputType);
264 }
David Blaikie69a1d8c2015-06-22 22:07:27 +0000265 Opts.ShowHelp = Args.hasArg(OPT_help);
266 Opts.ShowVersion = Args.hasArg(OPT_version);
Daniel Dunbar2fcaa542010-05-20 17:49:16 +0000267
268 // Transliterate Options
Reid Kleckner898229a2013-06-14 17:17:23 +0000269 Opts.OutputAsmVariant =
David Blaikie69a1d8c2015-06-22 22:07:27 +0000270 getLastArgIntValue(Args, OPT_output_asm_variant, 0, Diags);
271 Opts.ShowEncoding = Args.hasArg(OPT_show_encoding);
272 Opts.ShowInst = Args.hasArg(OPT_show_inst);
Daniel Dunbar2fcaa542010-05-20 17:49:16 +0000273
274 // Assemble Options
David Blaikie69a1d8c2015-06-22 22:07:27 +0000275 Opts.RelaxAll = Args.hasArg(OPT_mrelax_all);
276 Opts.NoExecStack = Args.hasArg(OPT_mno_exec_stack);
277 Opts.FatalWarnings = Args.hasArg(OPT_massembler_fatal_warnings);
Joerg Sonnenberger924f6ad2015-09-18 11:13:43 +0000278 Opts.RelocationModel = Args.getLastArgValue(OPT_mrelocation_model, "pic");
David Majnemer2b9349d2015-12-21 22:09:34 +0000279 Opts.IncrementalLinkerCompatible =
280 Args.hasArg(OPT_mincremental_linker_compatible);
Mandeep Singh Grang358faec2016-12-01 18:42:16 +0000281 Opts.SymbolDefs = Args.getAllArgValues(OPT_defsym);
Dylan Noblesmithe99b27f2011-12-23 03:05:38 +0000282
Dylan Noblesmith68207c02011-12-26 19:29:47 +0000283 return Success;
Daniel Dunbar2fcaa542010-05-20 17:49:16 +0000284}
285
Rafael Espindola7e556ad2015-04-09 21:50:11 +0000286static std::unique_ptr<raw_fd_ostream>
Peter Collingbourne47bc0172018-05-21 20:31:59 +0000287getOutputStream(StringRef Path, DiagnosticsEngine &Diags, bool Binary) {
Daniel Dunbar2fcaa542010-05-20 17:49:16 +0000288 // Make sure that the Out file gets unlinked from the disk if we get a
289 // SIGINT.
Peter Collingbourne47bc0172018-05-21 20:31:59 +0000290 if (Path != "-")
291 sys::RemoveFileOnSignal(Path);
Daniel Dunbar2fcaa542010-05-20 17:49:16 +0000292
Rafael Espindoladae941a2014-08-25 18:17:04 +0000293 std::error_code EC;
Rafael Espindola7e556ad2015-04-09 21:50:11 +0000294 auto Out = llvm::make_unique<raw_fd_ostream>(
Peter Collingbourne47bc0172018-05-21 20:31:59 +0000295 Path, EC, (Binary ? sys::fs::F_None : sys::fs::F_Text));
Rafael Espindoladae941a2014-08-25 18:17:04 +0000296 if (EC) {
Peter Collingbourne47bc0172018-05-21 20:31:59 +0000297 Diags.Report(diag::err_fe_unable_to_open_output) << Path << EC.message();
Craig Topper69186e72014-06-08 08:38:04 +0000298 return nullptr;
Daniel Dunbar2fcaa542010-05-20 17:49:16 +0000299 }
300
Rafael Espindola4dedcd72015-04-09 21:06:11 +0000301 return Out;
Daniel Dunbar2fcaa542010-05-20 17:49:16 +0000302}
303
David Blaikie9c902b52011-09-25 23:23:43 +0000304static bool ExecuteAssembler(AssemblerInvocation &Opts,
305 DiagnosticsEngine &Diags) {
Daniel Dunbar2fcaa542010-05-20 17:49:16 +0000306 // Get the target specific parser.
307 std::string Error;
Alp Tokere98ea7c2014-05-31 00:02:21 +0000308 const Target *TheTarget = TargetRegistry::lookupTarget(Opts.Triple, Error);
Alp Toker44293142014-05-31 00:02:27 +0000309 if (!TheTarget)
310 return Diags.Report(diag::err_target_unknown_triple) << Opts.Triple;
Daniel Dunbar2fcaa542010-05-20 17:49:16 +0000311
Rafael Espindola2d2b4202014-07-06 17:43:24 +0000312 ErrorOr<std::unique_ptr<MemoryBuffer>> Buffer =
313 MemoryBuffer::getFileOrSTDIN(Opts.InputFile);
314
315 if (std::error_code EC = Buffer.getError()) {
316 Error = EC.message();
Alp Toker44293142014-05-31 00:02:27 +0000317 return Diags.Report(diag::err_fe_error_reading) << Opts.InputFile;
Daniel Dunbar2fcaa542010-05-20 17:49:16 +0000318 }
319
320 SourceMgr SrcMgr;
321
322 // Tell SrcMgr about this buffer, which is what the parser will pick up.
David Blaikie9e095d92014-08-21 21:01:00 +0000323 SrcMgr.AddNewSourceBuffer(std::move(*Buffer), SMLoc());
Daniel Dunbar2fcaa542010-05-20 17:49:16 +0000324
325 // Record the location of the include directories so that the lexer can find
326 // it later.
327 SrcMgr.setIncludeDirs(Opts.IncludePaths);
328
Ahmed Charlesb8984322014-03-07 20:03:18 +0000329 std::unique_ptr<MCRegisterInfo> MRI(TheTarget->createMCRegInfo(Opts.Triple));
Evan Chengb505ace2011-07-18 20:57:51 +0000330 assert(MRI && "Unable to create target register info!");
331
Ahmed Charlesb8984322014-03-07 20:03:18 +0000332 std::unique_ptr<MCAsmInfo> MAI(TheTarget->createMCAsmInfo(*MRI, Opts.Triple));
Rafael Espindola77056232013-05-13 01:24:18 +0000333 assert(MAI && "Unable to create target asm info!");
334
David Blaikieb31e1d12014-03-31 23:47:13 +0000335 // Ensure MCAsmInfo initialization occurs before any use, otherwise sections
336 // may be created with a combination of default and explicit settings.
Saleem Abdulrasool54448902017-06-09 00:40:30 +0000337 MAI->setCompressDebugSections(Opts.CompressDebugSections);
David Blaikieb31e1d12014-03-31 23:47:13 +0000338
Rafael Espindolaf8f01c32016-05-29 02:01:14 +0000339 MAI->setRelaxELFRelocations(Opts.RelaxELFRelocations);
340
Daniel Dunbar2fcaa542010-05-20 17:49:16 +0000341 bool IsBinary = Opts.OutputType == AssemblerInvocation::FT_Obj;
Peter Collingbourne47bc0172018-05-21 20:31:59 +0000342 if (Opts.OutputPath.empty())
343 Opts.OutputPath = "-";
344 std::unique_ptr<raw_fd_ostream> FDOS =
345 getOutputStream(Opts.OutputPath, Diags, IsBinary);
Rafael Espindola2f16bc12015-04-14 15:15:49 +0000346 if (!FDOS)
Alp Toker44293142014-05-31 00:02:27 +0000347 return true;
Peter Collingbourne47bc0172018-05-21 20:31:59 +0000348 std::unique_ptr<raw_fd_ostream> DwoOS;
349 if (!Opts.SplitDwarfFile.empty())
350 DwoOS = getOutputStream(Opts.SplitDwarfFile, Diags, IsBinary);
Daniel Dunbar2fcaa542010-05-20 17:49:16 +0000351
Evan Cheng347033f2011-07-20 06:22:27 +0000352 // FIXME: This is not pretty. MCContext has a ptr to MCObjectFileInfo and
353 // MCObjectFileInfo needs a MCContext reference in order to initialize itself.
Ahmed Charlesb8984322014-03-07 20:03:18 +0000354 std::unique_ptr<MCObjectFileInfo> MOFI(new MCObjectFileInfo());
David Blaikie07b8d4e2014-03-31 23:13:30 +0000355
Bill Wendlingda1e3e72013-06-18 07:22:05 +0000356 MCContext Ctx(MAI.get(), MRI.get(), MOFI.get(), &SrcMgr);
Joerg Sonnenberger924f6ad2015-09-18 11:13:43 +0000357
Rafael Espindolae64e2302016-05-18 11:58:56 +0000358 bool PIC = false;
Joerg Sonnenberger924f6ad2015-09-18 11:13:43 +0000359 if (Opts.RelocationModel == "static") {
Rafael Espindolae64e2302016-05-18 11:58:56 +0000360 PIC = false;
Joerg Sonnenberger924f6ad2015-09-18 11:13:43 +0000361 } else if (Opts.RelocationModel == "pic") {
Rafael Espindolae64e2302016-05-18 11:58:56 +0000362 PIC = true;
Joerg Sonnenberger924f6ad2015-09-18 11:13:43 +0000363 } else {
364 assert(Opts.RelocationModel == "dynamic-no-pic" &&
365 "Invalid PIC model!");
Rafael Espindolae64e2302016-05-18 11:58:56 +0000366 PIC = false;
Joerg Sonnenberger924f6ad2015-09-18 11:13:43 +0000367 }
368
Rafael Espindola2e8a7d32017-08-02 20:32:35 +0000369 MOFI->InitMCObjectFileInfo(Triple(Opts.Triple), PIC, Ctx);
Daniel Dunbar9cf7bc72011-03-28 22:49:24 +0000370 if (Opts.SaveTemporaryLabels)
371 Ctx.setAllowTemporaryLabels(false);
Kevin Enderby292dc082011-12-22 19:31:58 +0000372 if (Opts.GenDwarfForAssembly)
373 Ctx.setGenDwarfForAssembly(true);
374 if (!Opts.DwarfDebugFlags.empty())
375 Ctx.setDwarfDebugFlags(StringRef(Opts.DwarfDebugFlags));
Kevin Enderbyae2ec472013-01-17 21:38:06 +0000376 if (!Opts.DwarfDebugProducer.empty())
377 Ctx.setDwarfDebugProducer(StringRef(Opts.DwarfDebugProducer));
Chandler Carruth4d5e1a92012-12-17 21:40:04 +0000378 if (!Opts.DebugCompilationDir.empty())
379 Ctx.setCompilationDir(Opts.DebugCompilationDir);
Eric Christopher45f2e712012-12-18 00:31:10 +0000380 if (!Opts.MainFileName.empty())
381 Ctx.setMainFileName(StringRef(Opts.MainFileName));
Oliver Stannard9b2a7d42014-05-19 13:39:13 +0000382 Ctx.setDwarfVersion(Opts.DwarfVersion);
Rafael Espindola86f2c572010-12-10 07:40:14 +0000383
Jim Grosbach576452b2012-02-10 20:37:10 +0000384 // Build up the feature string from the target feature list.
385 std::string FS;
386 if (!Opts.Features.empty()) {
387 FS = Opts.Features[0];
388 for (unsigned i = 1, e = Opts.Features.size(); i != e; ++i)
389 FS += "," + Opts.Features[i];
390 }
391
Ahmed Charlesb8984322014-03-07 20:03:18 +0000392 std::unique_ptr<MCStreamer> Str;
Daniel Dunbar2fcaa542010-05-20 17:49:16 +0000393
Ahmed Charlesb8984322014-03-07 20:03:18 +0000394 std::unique_ptr<MCInstrInfo> MCII(TheTarget->createMCInstrInfo());
395 std::unique_ptr<MCSubtargetInfo> STI(
396 TheTarget->createMCSubtargetInfo(Opts.Triple, Opts.CPU, FS));
Evan Cheng279f2902011-07-11 04:24:19 +0000397
Rafael Espindola2f16bc12015-04-14 15:15:49 +0000398 raw_pwrite_stream *Out = FDOS.get();
399 std::unique_ptr<buffer_ostream> BOS;
400
Rafael Espindola148141c2011-01-23 17:58:26 +0000401 // FIXME: There is a bit of code duplication with addPassesToEmitFile.
Daniel Dunbar2fcaa542010-05-20 17:49:16 +0000402 if (Opts.OutputType == AssemblerInvocation::FT_Asm) {
Eric Christopher7e0fadf2015-03-31 00:10:23 +0000403 MCInstPrinter *IP = TheTarget->createMCInstPrinter(
Daniel Sanders50f17232015-09-15 16:17:27 +0000404 llvm::Triple(Opts.Triple), Opts.OutputAsmVariant, *MAI, *MCII, *MRI);
Nirav Dave1b5533c2018-04-27 15:45:54 +0000405
406 std::unique_ptr<MCCodeEmitter> CE;
407 if (Opts.ShowEncoding)
408 CE.reset(TheTarget->createMCCodeEmitter(*MCII, *MRI, Ctx));
409 MCTargetOptions MCOptions;
410 std::unique_ptr<MCAsmBackend> MAB(
411 TheTarget->createMCAsmBackend(*STI, *MRI, MCOptions));
412
Rafael Espindola4dedcd72015-04-09 21:06:11 +0000413 auto FOut = llvm::make_unique<formatted_raw_ostream>(*Out);
414 Str.reset(TheTarget->createAsmStreamer(
415 Ctx, std::move(FOut), /*asmverbose*/ true,
Nirav Dave1b5533c2018-04-27 15:45:54 +0000416 /*useDwarfDirectory*/ true, IP, std::move(CE), std::move(MAB),
417 Opts.ShowInst));
Daniel Dunbar2fcaa542010-05-20 17:49:16 +0000418 } else if (Opts.OutputType == AssemblerInvocation::FT_Null) {
419 Str.reset(createNullStreamer(Ctx));
420 } else {
421 assert(Opts.OutputType == AssemblerInvocation::FT_Obj &&
422 "Invalid file type!");
Rafael Espindola2f16bc12015-04-14 15:15:49 +0000423 if (!FDOS->supportsSeeking()) {
424 BOS = make_unique<buffer_ostream>(*FDOS);
425 Out = BOS.get();
426 }
427
Nirav Dave1b5533c2018-04-27 15:45:54 +0000428 std::unique_ptr<MCCodeEmitter> CE(
429 TheTarget->createMCCodeEmitter(*MCII, *MRI, Ctx));
430 MCTargetOptions MCOptions;
431 std::unique_ptr<MCAsmBackend> MAB(
432 TheTarget->createMCAsmBackend(*STI, *MRI, MCOptions));
Peter Collingbourne47bc0172018-05-21 20:31:59 +0000433 std::unique_ptr<MCObjectWriter> OW =
434 DwoOS ? MAB->createDwoObjectWriter(*Out, *DwoOS)
435 : MAB->createObjectWriter(*Out);
Nirav Dave1b5533c2018-04-27 15:45:54 +0000436
Daniel Sanders50f17232015-09-15 16:17:27 +0000437 Triple T(Opts.Triple);
David Majnemer2b9349d2015-12-21 22:09:34 +0000438 Str.reset(TheTarget->createMCObjectStreamer(
Peter Collingbournef7b81db2018-05-18 18:26:45 +0000439 T, Ctx, std::move(MAB), std::move(OW), std::move(CE), *STI,
440 Opts.RelaxAll, Opts.IncrementalLinkerCompatible,
David Majnemer2b9349d2015-12-21 22:09:34 +0000441 /*DWARFMustBeAtTheEnd*/ true));
Rafael Espindolad465be82014-10-15 16:12:57 +0000442 Str.get()->InitSections(Opts.NoExecStack);
Daniel Dunbar2fcaa542010-05-20 17:49:16 +0000443 }
444
Nirav Dave6c0665e2018-04-30 19:22:40 +0000445 // Assembly to object compilation should leverage assembly info.
446 Str->setUseAssemblerInfoForParsing(true);
447
Alp Toker44293142014-05-31 00:02:27 +0000448 bool Failed = false;
Alp Tokere98ea7c2014-05-31 00:02:21 +0000449
Ahmed Charlesb8984322014-03-07 20:03:18 +0000450 std::unique_ptr<MCAsmParser> Parser(
451 createMCAsmParser(SrcMgr, Ctx, *Str.get(), *MAI));
Evgeniy Stepanoveeb820f2014-04-23 11:15:49 +0000452
453 // FIXME: init MCTargetOptions from sanitizer flags here.
454 MCTargetOptions Options;
Ahmed Charlesb8984322014-03-07 20:03:18 +0000455 std::unique_ptr<MCTargetAsmParser> TAP(
Evgeniy Stepanoveeb820f2014-04-23 11:15:49 +0000456 TheTarget->createMCAsmParser(*STI, *Parser, *MCII, Options));
Alp Toker44293142014-05-31 00:02:27 +0000457 if (!TAP)
458 Failed = Diags.Report(diag::err_target_unknown_triple) << Opts.Triple;
Daniel Dunbar2fcaa542010-05-20 17:49:16 +0000459
Mandeep Singh Grang358faec2016-12-01 18:42:16 +0000460 // Set values for symbols, if any.
461 for (auto &S : Opts.SymbolDefs) {
Mandeep Singh Grang6d1d36c2016-12-06 02:49:16 +0000462 auto Pair = StringRef(S).split('=');
463 auto Sym = Pair.first;
464 auto Val = Pair.second;
465 int64_t Value;
466 // We have already error checked this in the driver.
467 Val.getAsInteger(0, Value);
468 Ctx.setSymbolValue(Parser->getStreamer(), Sym, Value);
Mandeep Singh Grang358faec2016-12-01 18:42:16 +0000469 }
470
Alp Toker44293142014-05-31 00:02:27 +0000471 if (!Failed) {
Alp Tokere98ea7c2014-05-31 00:02:21 +0000472 Parser->setTargetParser(*TAP.get());
Alp Toker44293142014-05-31 00:02:27 +0000473 Failed = Parser->Run(Opts.NoInitialTextSection);
Alp Tokere98ea7c2014-05-31 00:02:21 +0000474 }
Daniel Dunbar2fcaa542010-05-20 17:49:16 +0000475
Steven Wuae480ec2015-07-24 02:12:43 +0000476 // Close Streamer first.
477 // It might have a reference to the output stream.
478 Str.reset();
Alp Tokere98ea7c2014-05-31 00:02:21 +0000479 // Close the output stream early.
Rafael Espindola2f16bc12015-04-14 15:15:49 +0000480 BOS.reset();
481 FDOS.reset();
Daniel Dunbar2fcaa542010-05-20 17:49:16 +0000482
Alp Tokere98ea7c2014-05-31 00:02:21 +0000483 // Delete output file if there were errors.
Peter Collingbourne47bc0172018-05-21 20:31:59 +0000484 if (Failed) {
485 if (Opts.OutputPath != "-")
486 sys::fs::remove(Opts.OutputPath);
487 if (!Opts.SplitDwarfFile.empty() && Opts.SplitDwarfFile != "-")
488 sys::fs::remove(Opts.SplitDwarfFile);
489 }
Daniel Dunbar2fcaa542010-05-20 17:49:16 +0000490
Alp Toker44293142014-05-31 00:02:27 +0000491 return Failed;
Daniel Dunbar2fcaa542010-05-20 17:49:16 +0000492}
493
Chad Rosier05c71aa2013-03-27 18:28:23 +0000494static void LLVMErrorHandler(void *UserData, const std::string &Message,
495 bool GenCrashDiag) {
David Blaikie9c902b52011-09-25 23:23:43 +0000496 DiagnosticsEngine &Diags = *static_cast<DiagnosticsEngine*>(UserData);
Daniel Dunbar2fcaa542010-05-20 17:49:16 +0000497
498 Diags.Report(diag::err_fe_error_backend) << Message;
499
500 // We cannot recover from llvm errors.
501 exit(1);
502}
503
Sean Silva070cd2d2014-08-15 21:38:36 +0000504int cc1as_main(ArrayRef<const char *> Argv, const char *Argv0, void *MainAddr) {
Daniel Dunbar2fcaa542010-05-20 17:49:16 +0000505 // Initialize targets and assembly printers/parsers.
506 InitializeAllTargetInfos();
Evan Chengc391a582011-07-22 21:59:11 +0000507 InitializeAllTargetMCs();
Daniel Dunbar2fcaa542010-05-20 17:49:16 +0000508 InitializeAllAsmParsers();
509
510 // Construct our diagnostic client.
Douglas Gregor811db4e2012-10-23 22:26:28 +0000511 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
Douglas Gregor2dd19f12010-08-18 22:29:43 +0000512 TextDiagnosticPrinter *DiagClient
Douglas Gregor811db4e2012-10-23 22:26:28 +0000513 = new TextDiagnosticPrinter(errs(), &*DiagOpts);
Douglas Gregor2dd19f12010-08-18 22:29:43 +0000514 DiagClient->setPrefix("clang -cc1as");
Dylan Noblesmithc95d8192012-02-20 14:00:23 +0000515 IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
Douglas Gregor811db4e2012-10-23 22:26:28 +0000516 DiagnosticsEngine Diags(DiagID, &*DiagOpts, DiagClient);
Daniel Dunbar2fcaa542010-05-20 17:49:16 +0000517
518 // Set an error handler, so that any LLVM backend diagnostics go through our
519 // error handler.
Dan Gohmanb37af7d2010-08-18 21:23:17 +0000520 ScopedFatalErrorHandler FatalErrorHandler
521 (LLVMErrorHandler, static_cast<void*>(&Diags));
Daniel Dunbar2fcaa542010-05-20 17:49:16 +0000522
523 // Parse the arguments.
524 AssemblerInvocation Asm;
Sean Silva070cd2d2014-08-15 21:38:36 +0000525 if (!AssemblerInvocation::CreateFromArgs(Asm, Argv, Diags))
Dylan Noblesmithe99b27f2011-12-23 03:05:38 +0000526 return 1;
Daniel Dunbar2fcaa542010-05-20 17:49:16 +0000527
Daniel Dunbar0454f652010-05-20 18:15:20 +0000528 if (Asm.ShowHelp) {
Alp Toker61dad752014-07-09 14:05:11 +0000529 std::unique_ptr<OptTable> Opts(driver::createDriverOptTable());
Alp Toker532e5b92014-07-09 14:09:52 +0000530 Opts->PrintHelp(llvm::outs(), "clang -cc1as", "Clang Integrated Assembler",
George Rimar5dbfa4e2017-07-26 09:10:17 +0000531 /*Include=*/driver::options::CC1AsOption, /*Exclude=*/0,
532 /*ShowAllAliases=*/false);
Daniel Dunbar0454f652010-05-20 18:15:20 +0000533 return 0;
534 }
535
536 // Honor -version.
537 //
538 // FIXME: Use a better -version message?
539 if (Asm.ShowVersion) {
540 llvm::cl::PrintVersionMessage();
541 return 0;
542 }
543
544 // Honor -mllvm.
545 //
546 // FIXME: Remove this, one day.
547 if (!Asm.LLVMArgs.empty()) {
548 unsigned NumArgs = Asm.LLVMArgs.size();
Kostya Serebryany5af45152017-04-19 20:57:13 +0000549 auto Args = llvm::make_unique<const char*[]>(NumArgs + 2);
Daniel Dunbar0454f652010-05-20 18:15:20 +0000550 Args[0] = "clang (LLVM option parsing)";
551 for (unsigned i = 0; i != NumArgs; ++i)
552 Args[i + 1] = Asm.LLVMArgs[i].c_str();
Craig Topper69186e72014-06-08 08:38:04 +0000553 Args[NumArgs + 1] = nullptr;
Kostya Serebryany5af45152017-04-19 20:57:13 +0000554 llvm::cl::ParseCommandLineOptions(NumArgs + 1, Args.get());
Daniel Dunbar0454f652010-05-20 18:15:20 +0000555 }
556
Daniel Dunbar2fcaa542010-05-20 17:49:16 +0000557 // Execute the invocation, unless there were parsing errors.
Alp Toker44293142014-05-31 00:02:27 +0000558 bool Failed = Diags.hasErrorOccurred() || ExecuteAssembler(Asm, Diags);
Daniel Dunbar2fcaa542010-05-20 17:49:16 +0000559
560 // If any timers were active but haven't been destroyed yet, print their
561 // results now.
562 TimerGroup::printAll(errs());
563
Alp Toker44293142014-05-31 00:02:27 +0000564 return !!Failed;
Daniel Dunbar2fcaa542010-05-20 17:49:16 +0000565}