/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/tools/driver/cc1as_main.cpp
Line | Count | Source (jump to first uncovered line) |
1 | | //===-- cc1as_main.cpp - Clang Assembler ---------------------------------===// |
2 | | // |
3 | | // 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 |
6 | | // |
7 | | //===----------------------------------------------------------------------===// |
8 | | // |
9 | | // This is the entry point to the clang -cc1as functionality, which implements |
10 | | // the direct interface to the LLVM MC based assembler. |
11 | | // |
12 | | //===----------------------------------------------------------------------===// |
13 | | |
14 | | #include "clang/Basic/Diagnostic.h" |
15 | | #include "clang/Basic/DiagnosticOptions.h" |
16 | | #include "clang/Driver/DriverDiagnostic.h" |
17 | | #include "clang/Driver/Options.h" |
18 | | #include "clang/Frontend/FrontendDiagnostic.h" |
19 | | #include "clang/Frontend/TextDiagnosticPrinter.h" |
20 | | #include "clang/Frontend/Utils.h" |
21 | | #include "llvm/ADT/STLExtras.h" |
22 | | #include "llvm/ADT/StringSwitch.h" |
23 | | #include "llvm/ADT/Triple.h" |
24 | | #include "llvm/IR/DataLayout.h" |
25 | | #include "llvm/MC/MCAsmBackend.h" |
26 | | #include "llvm/MC/MCAsmInfo.h" |
27 | | #include "llvm/MC/MCCodeEmitter.h" |
28 | | #include "llvm/MC/MCContext.h" |
29 | | #include "llvm/MC/MCInstrInfo.h" |
30 | | #include "llvm/MC/MCObjectFileInfo.h" |
31 | | #include "llvm/MC/MCObjectWriter.h" |
32 | | #include "llvm/MC/MCParser/MCAsmParser.h" |
33 | | #include "llvm/MC/MCParser/MCTargetAsmParser.h" |
34 | | #include "llvm/MC/MCRegisterInfo.h" |
35 | | #include "llvm/MC/MCSectionMachO.h" |
36 | | #include "llvm/MC/MCStreamer.h" |
37 | | #include "llvm/MC/MCSubtargetInfo.h" |
38 | | #include "llvm/MC/MCTargetOptions.h" |
39 | | #include "llvm/Option/Arg.h" |
40 | | #include "llvm/Option/ArgList.h" |
41 | | #include "llvm/Option/OptTable.h" |
42 | | #include "llvm/Support/CommandLine.h" |
43 | | #include "llvm/Support/ErrorHandling.h" |
44 | | #include "llvm/Support/FileSystem.h" |
45 | | #include "llvm/Support/FormattedStream.h" |
46 | | #include "llvm/Support/Host.h" |
47 | | #include "llvm/Support/MemoryBuffer.h" |
48 | | #include "llvm/Support/Path.h" |
49 | | #include "llvm/Support/Process.h" |
50 | | #include "llvm/Support/Signals.h" |
51 | | #include "llvm/Support/SourceMgr.h" |
52 | | #include "llvm/Support/TargetRegistry.h" |
53 | | #include "llvm/Support/TargetSelect.h" |
54 | | #include "llvm/Support/Timer.h" |
55 | | #include "llvm/Support/raw_ostream.h" |
56 | | #include <memory> |
57 | | #include <system_error> |
58 | | using namespace clang; |
59 | | using namespace clang::driver; |
60 | | using namespace clang::driver::options; |
61 | | using namespace llvm; |
62 | | using namespace llvm::opt; |
63 | | |
64 | | namespace { |
65 | | |
66 | | /// Helper class for representing a single invocation of the assembler. |
67 | | struct AssemblerInvocation { |
68 | | /// @name Target Options |
69 | | /// @{ |
70 | | |
71 | | /// The name of the target triple to assemble for. |
72 | | std::string Triple; |
73 | | |
74 | | /// If given, the name of the target CPU to determine which instructions |
75 | | /// are legal. |
76 | | std::string CPU; |
77 | | |
78 | | /// The list of target specific features to enable or disable -- this should |
79 | | /// be a list of strings starting with '+' or '-'. |
80 | | std::vector<std::string> Features; |
81 | | |
82 | | /// The list of symbol definitions. |
83 | | std::vector<std::string> SymbolDefs; |
84 | | |
85 | | /// @} |
86 | | /// @name Language Options |
87 | | /// @{ |
88 | | |
89 | | std::vector<std::string> IncludePaths; |
90 | | unsigned NoInitialTextSection : 1; |
91 | | unsigned SaveTemporaryLabels : 1; |
92 | | unsigned GenDwarfForAssembly : 1; |
93 | | unsigned RelaxELFRelocations : 1; |
94 | | unsigned DwarfVersion; |
95 | | std::string DwarfDebugFlags; |
96 | | std::string DwarfDebugProducer; |
97 | | std::string DebugCompilationDir; |
98 | | std::map<const std::string, const std::string> DebugPrefixMap; |
99 | | llvm::DebugCompressionType CompressDebugSections = |
100 | | llvm::DebugCompressionType::None; |
101 | | std::string MainFileName; |
102 | | std::string SplitDwarfOutput; |
103 | | |
104 | | /// @} |
105 | | /// @name Frontend Options |
106 | | /// @{ |
107 | | |
108 | | std::string InputFile; |
109 | | std::vector<std::string> LLVMArgs; |
110 | | std::string OutputPath; |
111 | | enum FileType { |
112 | | FT_Asm, ///< Assembly (.s) output, transliterate mode. |
113 | | FT_Null, ///< No output, for timing purposes. |
114 | | FT_Obj ///< Object file output. |
115 | | }; |
116 | | FileType OutputType; |
117 | | unsigned ShowHelp : 1; |
118 | | unsigned ShowVersion : 1; |
119 | | |
120 | | /// @} |
121 | | /// @name Transliterate Options |
122 | | /// @{ |
123 | | |
124 | | unsigned OutputAsmVariant; |
125 | | unsigned ShowEncoding : 1; |
126 | | unsigned ShowInst : 1; |
127 | | |
128 | | /// @} |
129 | | /// @name Assembler Options |
130 | | /// @{ |
131 | | |
132 | | unsigned RelaxAll : 1; |
133 | | unsigned NoExecStack : 1; |
134 | | unsigned FatalWarnings : 1; |
135 | | unsigned NoWarn : 1; |
136 | | unsigned IncrementalLinkerCompatible : 1; |
137 | | unsigned EmbedBitcode : 1; |
138 | | |
139 | | /// The name of the relocation model to use. |
140 | | std::string RelocationModel; |
141 | | |
142 | | /// The ABI targeted by the backend. Specified using -target-abi. Empty |
143 | | /// otherwise. |
144 | | std::string TargetABI; |
145 | | |
146 | | /// @} |
147 | | |
148 | | public: |
149 | 48 | AssemblerInvocation() { |
150 | 48 | Triple = ""; |
151 | 48 | NoInitialTextSection = 0; |
152 | 48 | InputFile = "-"; |
153 | 48 | OutputPath = "-"; |
154 | 48 | OutputType = FT_Asm; |
155 | 48 | OutputAsmVariant = 0; |
156 | 48 | ShowInst = 0; |
157 | 48 | ShowEncoding = 0; |
158 | 48 | RelaxAll = 0; |
159 | 48 | NoExecStack = 0; |
160 | 48 | FatalWarnings = 0; |
161 | 48 | NoWarn = 0; |
162 | 48 | IncrementalLinkerCompatible = 0; |
163 | 48 | DwarfVersion = 0; |
164 | 48 | EmbedBitcode = 0; |
165 | 48 | } |
166 | | |
167 | | static bool CreateFromArgs(AssemblerInvocation &Res, |
168 | | ArrayRef<const char *> Argv, |
169 | | DiagnosticsEngine &Diags); |
170 | | }; |
171 | | |
172 | | } |
173 | | |
174 | | bool AssemblerInvocation::CreateFromArgs(AssemblerInvocation &Opts, |
175 | | ArrayRef<const char *> Argv, |
176 | 48 | DiagnosticsEngine &Diags) { |
177 | 48 | bool Success = true; |
178 | | |
179 | | // Parse the arguments. |
180 | 48 | const OptTable &OptTbl = getDriverOptTable(); |
181 | | |
182 | 48 | const unsigned IncludedFlagsBitmask = options::CC1AsOption; |
183 | 48 | unsigned MissingArgIndex, MissingArgCount; |
184 | 48 | InputArgList Args = OptTbl.ParseArgs(Argv, MissingArgIndex, MissingArgCount, |
185 | 48 | IncludedFlagsBitmask); |
186 | | |
187 | | // Check for missing argument error. |
188 | 48 | if (MissingArgCount) { |
189 | 0 | Diags.Report(diag::err_drv_missing_argument) |
190 | 0 | << Args.getArgString(MissingArgIndex) << MissingArgCount; |
191 | 0 | Success = false; |
192 | 0 | } |
193 | | |
194 | | // Issue errors on unknown arguments. |
195 | 2 | for (const Arg *A : Args.filtered(OPT_UNKNOWN)) { |
196 | 2 | auto ArgString = A->getAsString(Args); |
197 | 2 | std::string Nearest; |
198 | 2 | if (OptTbl.findNearest(ArgString, Nearest, IncludedFlagsBitmask) > 1) |
199 | 0 | Diags.Report(diag::err_drv_unknown_argument) << ArgString; |
200 | 2 | else |
201 | 2 | Diags.Report(diag::err_drv_unknown_argument_with_suggestion) |
202 | 2 | << ArgString << Nearest; |
203 | 2 | Success = false; |
204 | 2 | } |
205 | | |
206 | | // Construct the invocation. |
207 | | |
208 | | // Target Options |
209 | 48 | Opts.Triple = llvm::Triple::normalize(Args.getLastArgValue(OPT_triple)); |
210 | 48 | Opts.CPU = std::string(Args.getLastArgValue(OPT_target_cpu)); |
211 | 48 | Opts.Features = Args.getAllArgValues(OPT_target_feature); |
212 | | |
213 | | // Use the default target triple if unspecified. |
214 | 48 | if (Opts.Triple.empty()) |
215 | 0 | Opts.Triple = llvm::sys::getDefaultTargetTriple(); |
216 | | |
217 | | // Language Options |
218 | 48 | Opts.IncludePaths = Args.getAllArgValues(OPT_I); |
219 | 48 | Opts.NoInitialTextSection = Args.hasArg(OPT_n); |
220 | 48 | Opts.SaveTemporaryLabels = Args.hasArg(OPT_msave_temp_labels); |
221 | | // Any DebugInfoKind implies GenDwarfForAssembly. |
222 | 48 | Opts.GenDwarfForAssembly = Args.hasArg(OPT_debug_info_kind_EQ); |
223 | | |
224 | 48 | if (const Arg *A = Args.getLastArg(OPT_compress_debug_sections_EQ)) { |
225 | 2 | Opts.CompressDebugSections = |
226 | 2 | llvm::StringSwitch<llvm::DebugCompressionType>(A->getValue()) |
227 | 2 | .Case("none", llvm::DebugCompressionType::None) |
228 | 2 | .Case("zlib", llvm::DebugCompressionType::Z) |
229 | 2 | .Case("zlib-gnu", llvm::DebugCompressionType::GNU) |
230 | 2 | .Default(llvm::DebugCompressionType::None); |
231 | 2 | } |
232 | | |
233 | 48 | Opts.RelaxELFRelocations = Args.hasArg(OPT_mrelax_relocations); |
234 | 48 | Opts.DwarfVersion = getLastArgIntValue(Args, OPT_dwarf_version_EQ, 2, Diags); |
235 | 48 | Opts.DwarfDebugFlags = |
236 | 48 | std::string(Args.getLastArgValue(OPT_dwarf_debug_flags)); |
237 | 48 | Opts.DwarfDebugProducer = |
238 | 48 | std::string(Args.getLastArgValue(OPT_dwarf_debug_producer)); |
239 | 48 | Opts.DebugCompilationDir = |
240 | 48 | std::string(Args.getLastArgValue(OPT_fdebug_compilation_dir)); |
241 | 48 | Opts.MainFileName = std::string(Args.getLastArgValue(OPT_main_file_name)); |
242 | | |
243 | 0 | for (const auto &Arg : Args.getAllArgValues(OPT_fdebug_prefix_map_EQ)) { |
244 | 0 | auto Split = StringRef(Arg).split('='); |
245 | 0 | Opts.DebugPrefixMap.insert( |
246 | 0 | {std::string(Split.first), std::string(Split.second)}); |
247 | 0 | } |
248 | | |
249 | | // Frontend Options |
250 | 48 | if (Args.hasArg(OPT_INPUT)) { |
251 | 47 | bool First = true; |
252 | 47 | for (const Arg *A : Args.filtered(OPT_INPUT)) { |
253 | 47 | if (First) { |
254 | 47 | Opts.InputFile = A->getValue(); |
255 | 47 | First = false; |
256 | 0 | } else { |
257 | 0 | Diags.Report(diag::err_drv_unknown_argument) << A->getAsString(Args); |
258 | 0 | Success = false; |
259 | 0 | } |
260 | 47 | } |
261 | 47 | } |
262 | 48 | Opts.LLVMArgs = Args.getAllArgValues(OPT_mllvm); |
263 | 48 | Opts.OutputPath = std::string(Args.getLastArgValue(OPT_o)); |
264 | 48 | Opts.SplitDwarfOutput = |
265 | 48 | std::string(Args.getLastArgValue(OPT_split_dwarf_output)); |
266 | 48 | if (Arg *A = Args.getLastArg(OPT_filetype)) { |
267 | 45 | StringRef Name = A->getValue(); |
268 | 45 | unsigned OutputType = StringSwitch<unsigned>(Name) |
269 | 45 | .Case("asm", FT_Asm) |
270 | 45 | .Case("null", FT_Null) |
271 | 45 | .Case("obj", FT_Obj) |
272 | 45 | .Default(~0U); |
273 | 45 | if (OutputType == ~0U) { |
274 | 0 | Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Name; |
275 | 0 | Success = false; |
276 | 0 | } else |
277 | 45 | Opts.OutputType = FileType(OutputType); |
278 | 45 | } |
279 | 48 | Opts.ShowHelp = Args.hasArg(OPT_help); |
280 | 48 | Opts.ShowVersion = Args.hasArg(OPT_version); |
281 | | |
282 | | // Transliterate Options |
283 | 48 | Opts.OutputAsmVariant = |
284 | 48 | getLastArgIntValue(Args, OPT_output_asm_variant, 0, Diags); |
285 | 48 | Opts.ShowEncoding = Args.hasArg(OPT_show_encoding); |
286 | 48 | Opts.ShowInst = Args.hasArg(OPT_show_inst); |
287 | | |
288 | | // Assemble Options |
289 | 48 | Opts.RelaxAll = Args.hasArg(OPT_mrelax_all); |
290 | 48 | Opts.NoExecStack = Args.hasArg(OPT_mno_exec_stack); |
291 | 48 | Opts.FatalWarnings = Args.hasArg(OPT_massembler_fatal_warnings); |
292 | 48 | Opts.NoWarn = Args.hasArg(OPT_massembler_no_warn); |
293 | 48 | Opts.RelocationModel = |
294 | 48 | std::string(Args.getLastArgValue(OPT_mrelocation_model, "pic")); |
295 | 48 | Opts.TargetABI = std::string(Args.getLastArgValue(OPT_target_abi)); |
296 | 48 | Opts.IncrementalLinkerCompatible = |
297 | 48 | Args.hasArg(OPT_mincremental_linker_compatible); |
298 | 48 | Opts.SymbolDefs = Args.getAllArgValues(OPT_defsym); |
299 | | |
300 | | // EmbedBitcode Option. If -fembed-bitcode is enabled, set the flag. |
301 | | // EmbedBitcode behaves the same for all embed options for assembly files. |
302 | 48 | if (auto *A = Args.getLastArg(OPT_fembed_bitcode_EQ)) { |
303 | 1 | Opts.EmbedBitcode = llvm::StringSwitch<unsigned>(A->getValue()) |
304 | 1 | .Case("all", 1) |
305 | 1 | .Case("bitcode", 1) |
306 | 1 | .Case("marker", 1) |
307 | 1 | .Default(0); |
308 | 1 | } |
309 | | |
310 | 48 | return Success; |
311 | 48 | } |
312 | | |
313 | | static std::unique_ptr<raw_fd_ostream> |
314 | 48 | getOutputStream(StringRef Path, DiagnosticsEngine &Diags, bool Binary) { |
315 | | // Make sure that the Out file gets unlinked from the disk if we get a |
316 | | // SIGINT. |
317 | 48 | if (Path != "-") |
318 | 37 | sys::RemoveFileOnSignal(Path); |
319 | | |
320 | 48 | std::error_code EC; |
321 | 48 | auto Out = std::make_unique<raw_fd_ostream>( |
322 | 43 | Path, EC, (Binary ? sys::fs::OF_None : sys::fs::OF_Text5 )); |
323 | 48 | if (EC) { |
324 | 0 | Diags.Report(diag::err_fe_unable_to_open_output) << Path << EC.message(); |
325 | 0 | return nullptr; |
326 | 0 | } |
327 | | |
328 | 48 | return Out; |
329 | 48 | } |
330 | | |
331 | | static bool ExecuteAssembler(AssemblerInvocation &Opts, |
332 | 47 | DiagnosticsEngine &Diags) { |
333 | | // Get the target specific parser. |
334 | 47 | std::string Error; |
335 | 47 | const Target *TheTarget = TargetRegistry::lookupTarget(Opts.Triple, Error); |
336 | 47 | if (!TheTarget) |
337 | 0 | return Diags.Report(diag::err_target_unknown_triple) << Opts.Triple; |
338 | | |
339 | 47 | ErrorOr<std::unique_ptr<MemoryBuffer>> Buffer = |
340 | 47 | MemoryBuffer::getFileOrSTDIN(Opts.InputFile); |
341 | | |
342 | 47 | if (std::error_code EC = Buffer.getError()) { |
343 | 0 | Error = EC.message(); |
344 | 0 | return Diags.Report(diag::err_fe_error_reading) << Opts.InputFile; |
345 | 0 | } |
346 | | |
347 | 47 | SourceMgr SrcMgr; |
348 | | |
349 | | // Tell SrcMgr about this buffer, which is what the parser will pick up. |
350 | 47 | unsigned BufferIndex = SrcMgr.AddNewSourceBuffer(std::move(*Buffer), SMLoc()); |
351 | | |
352 | | // Record the location of the include directories so that the lexer can find |
353 | | // it later. |
354 | 47 | SrcMgr.setIncludeDirs(Opts.IncludePaths); |
355 | | |
356 | 47 | std::unique_ptr<MCRegisterInfo> MRI(TheTarget->createMCRegInfo(Opts.Triple)); |
357 | 47 | assert(MRI && "Unable to create target register info!"); |
358 | | |
359 | 47 | MCTargetOptions MCOptions; |
360 | 47 | std::unique_ptr<MCAsmInfo> MAI( |
361 | 47 | TheTarget->createMCAsmInfo(*MRI, Opts.Triple, MCOptions)); |
362 | 47 | assert(MAI && "Unable to create target asm info!"); |
363 | | |
364 | | // Ensure MCAsmInfo initialization occurs before any use, otherwise sections |
365 | | // may be created with a combination of default and explicit settings. |
366 | 47 | MAI->setCompressDebugSections(Opts.CompressDebugSections); |
367 | | |
368 | 47 | MAI->setRelaxELFRelocations(Opts.RelaxELFRelocations); |
369 | | |
370 | 47 | bool IsBinary = Opts.OutputType == AssemblerInvocation::FT_Obj; |
371 | 47 | if (Opts.OutputPath.empty()) |
372 | 3 | Opts.OutputPath = "-"; |
373 | 47 | std::unique_ptr<raw_fd_ostream> FDOS = |
374 | 47 | getOutputStream(Opts.OutputPath, Diags, IsBinary); |
375 | 47 | if (!FDOS) |
376 | 0 | return true; |
377 | 47 | std::unique_ptr<raw_fd_ostream> DwoOS; |
378 | 47 | if (!Opts.SplitDwarfOutput.empty()) |
379 | 1 | DwoOS = getOutputStream(Opts.SplitDwarfOutput, Diags, IsBinary); |
380 | | |
381 | | // FIXME: This is not pretty. MCContext has a ptr to MCObjectFileInfo and |
382 | | // MCObjectFileInfo needs a MCContext reference in order to initialize itself. |
383 | 47 | std::unique_ptr<MCObjectFileInfo> MOFI(new MCObjectFileInfo()); |
384 | | |
385 | 47 | MCContext Ctx(MAI.get(), MRI.get(), MOFI.get(), &SrcMgr, &MCOptions); |
386 | | |
387 | 47 | bool PIC = false; |
388 | 47 | if (Opts.RelocationModel == "static") { |
389 | 31 | PIC = false; |
390 | 16 | } else if (Opts.RelocationModel == "pic") { |
391 | 16 | PIC = true; |
392 | 0 | } else { |
393 | 0 | assert(Opts.RelocationModel == "dynamic-no-pic" && |
394 | 0 | "Invalid PIC model!"); |
395 | 0 | PIC = false; |
396 | 0 | } |
397 | | |
398 | 47 | MOFI->InitMCObjectFileInfo(Triple(Opts.Triple), PIC, Ctx); |
399 | 47 | if (Opts.SaveTemporaryLabels) |
400 | 0 | Ctx.setAllowTemporaryLabels(false); |
401 | 47 | if (Opts.GenDwarfForAssembly) |
402 | 3 | Ctx.setGenDwarfForAssembly(true); |
403 | 47 | if (!Opts.DwarfDebugFlags.empty()) |
404 | 0 | Ctx.setDwarfDebugFlags(StringRef(Opts.DwarfDebugFlags)); |
405 | 47 | if (!Opts.DwarfDebugProducer.empty()) |
406 | 30 | Ctx.setDwarfDebugProducer(StringRef(Opts.DwarfDebugProducer)); |
407 | 47 | if (!Opts.DebugCompilationDir.empty()) |
408 | 30 | Ctx.setCompilationDir(Opts.DebugCompilationDir); |
409 | 17 | else { |
410 | | // If no compilation dir is set, try to use the current directory. |
411 | 17 | SmallString<128> CWD; |
412 | 17 | if (!sys::fs::current_path(CWD)) |
413 | 17 | Ctx.setCompilationDir(CWD); |
414 | 17 | } |
415 | 47 | if (!Opts.DebugPrefixMap.empty()) |
416 | 0 | for (const auto &KV : Opts.DebugPrefixMap) |
417 | 0 | Ctx.addDebugPrefixMapEntry(KV.first, KV.second); |
418 | 47 | if (!Opts.MainFileName.empty()) |
419 | 38 | Ctx.setMainFileName(StringRef(Opts.MainFileName)); |
420 | 47 | Ctx.setDwarfVersion(Opts.DwarfVersion); |
421 | 47 | if (Opts.GenDwarfForAssembly) |
422 | 3 | Ctx.setGenDwarfRootFile(Opts.InputFile, |
423 | 3 | SrcMgr.getMemoryBuffer(BufferIndex)->getBuffer()); |
424 | | |
425 | | // Build up the feature string from the target feature list. |
426 | 47 | std::string FS = llvm::join(Opts.Features, ","); |
427 | | |
428 | 47 | std::unique_ptr<MCStreamer> Str; |
429 | | |
430 | 47 | std::unique_ptr<MCInstrInfo> MCII(TheTarget->createMCInstrInfo()); |
431 | 47 | assert(MCII && "Unable to create instruction info!"); |
432 | | |
433 | 47 | std::unique_ptr<MCSubtargetInfo> STI( |
434 | 47 | TheTarget->createMCSubtargetInfo(Opts.Triple, Opts.CPU, FS)); |
435 | 47 | assert(STI && "Unable to create subtarget info!"); |
436 | | |
437 | 47 | raw_pwrite_stream *Out = FDOS.get(); |
438 | 47 | std::unique_ptr<buffer_ostream> BOS; |
439 | | |
440 | 47 | MCOptions.MCNoWarn = Opts.NoWarn; |
441 | 47 | MCOptions.MCFatalWarnings = Opts.FatalWarnings; |
442 | 47 | MCOptions.ABIName = Opts.TargetABI; |
443 | | |
444 | | // FIXME: There is a bit of code duplication with addPassesToEmitFile. |
445 | 47 | if (Opts.OutputType == AssemblerInvocation::FT_Asm) { |
446 | 5 | MCInstPrinter *IP = TheTarget->createMCInstPrinter( |
447 | 5 | llvm::Triple(Opts.Triple), Opts.OutputAsmVariant, *MAI, *MCII, *MRI); |
448 | | |
449 | 5 | std::unique_ptr<MCCodeEmitter> CE; |
450 | 5 | if (Opts.ShowEncoding) |
451 | 0 | CE.reset(TheTarget->createMCCodeEmitter(*MCII, *MRI, Ctx)); |
452 | 5 | std::unique_ptr<MCAsmBackend> MAB( |
453 | 5 | TheTarget->createMCAsmBackend(*STI, *MRI, MCOptions)); |
454 | | |
455 | 5 | auto FOut = std::make_unique<formatted_raw_ostream>(*Out); |
456 | 5 | Str.reset(TheTarget->createAsmStreamer( |
457 | 5 | Ctx, std::move(FOut), /*asmverbose*/ true, |
458 | 5 | /*useDwarfDirectory*/ true, IP, std::move(CE), std::move(MAB), |
459 | 5 | Opts.ShowInst)); |
460 | 42 | } else if (Opts.OutputType == AssemblerInvocation::FT_Null) { |
461 | 0 | Str.reset(createNullStreamer(Ctx)); |
462 | 42 | } else { |
463 | 42 | assert(Opts.OutputType == AssemblerInvocation::FT_Obj && |
464 | 42 | "Invalid file type!"); |
465 | 42 | if (!FDOS->supportsSeeking()) { |
466 | 9 | BOS = std::make_unique<buffer_ostream>(*FDOS); |
467 | 9 | Out = BOS.get(); |
468 | 9 | } |
469 | | |
470 | 42 | std::unique_ptr<MCCodeEmitter> CE( |
471 | 42 | TheTarget->createMCCodeEmitter(*MCII, *MRI, Ctx)); |
472 | 42 | std::unique_ptr<MCAsmBackend> MAB( |
473 | 42 | TheTarget->createMCAsmBackend(*STI, *MRI, MCOptions)); |
474 | 42 | assert(MAB && "Unable to create asm backend!"); |
475 | | |
476 | 42 | std::unique_ptr<MCObjectWriter> OW = |
477 | 1 | DwoOS ? MAB->createDwoObjectWriter(*Out, *DwoOS) |
478 | 41 | : MAB->createObjectWriter(*Out); |
479 | | |
480 | 42 | Triple T(Opts.Triple); |
481 | 42 | Str.reset(TheTarget->createMCObjectStreamer( |
482 | 42 | T, Ctx, std::move(MAB), std::move(OW), std::move(CE), *STI, |
483 | 42 | Opts.RelaxAll, Opts.IncrementalLinkerCompatible, |
484 | 42 | /*DWARFMustBeAtTheEnd*/ true)); |
485 | 42 | Str.get()->InitSections(Opts.NoExecStack); |
486 | 42 | } |
487 | | |
488 | | // When -fembed-bitcode is passed to clang_as, a 1-byte marker |
489 | | // is emitted in __LLVM,__asm section if the object file is MachO format. |
490 | 47 | if (Opts.EmbedBitcode && Ctx.getObjectFileInfo()->getObjectFileType() == |
491 | 1 | MCObjectFileInfo::IsMachO) { |
492 | 1 | MCSection *AsmLabel = Ctx.getMachOSection( |
493 | 1 | "__LLVM", "__asm", MachO::S_REGULAR, 4, SectionKind::getReadOnly()); |
494 | 1 | Str.get()->SwitchSection(AsmLabel); |
495 | 1 | Str.get()->emitZeros(1); |
496 | 1 | } |
497 | | |
498 | | // Assembly to object compilation should leverage assembly info. |
499 | 47 | Str->setUseAssemblerInfoForParsing(true); |
500 | | |
501 | 47 | bool Failed = false; |
502 | | |
503 | 47 | std::unique_ptr<MCAsmParser> Parser( |
504 | 47 | createMCAsmParser(SrcMgr, Ctx, *Str.get(), *MAI)); |
505 | | |
506 | | // FIXME: init MCTargetOptions from sanitizer flags here. |
507 | 47 | std::unique_ptr<MCTargetAsmParser> TAP( |
508 | 47 | TheTarget->createMCAsmParser(*STI, *Parser, *MCII, MCOptions)); |
509 | 47 | if (!TAP) |
510 | 0 | Failed = Diags.Report(diag::err_target_unknown_triple) << Opts.Triple; |
511 | | |
512 | | // Set values for symbols, if any. |
513 | 0 | for (auto &S : Opts.SymbolDefs) { |
514 | 0 | auto Pair = StringRef(S).split('='); |
515 | 0 | auto Sym = Pair.first; |
516 | 0 | auto Val = Pair.second; |
517 | 0 | int64_t Value; |
518 | | // We have already error checked this in the driver. |
519 | 0 | Val.getAsInteger(0, Value); |
520 | 0 | Ctx.setSymbolValue(Parser->getStreamer(), Sym, Value); |
521 | 0 | } |
522 | | |
523 | 47 | if (!Failed) { |
524 | 47 | Parser->setTargetParser(*TAP.get()); |
525 | 47 | Failed = Parser->Run(Opts.NoInitialTextSection); |
526 | 47 | } |
527 | | |
528 | | // Parser has a reference to the output stream (Str), so close Parser first. |
529 | 47 | Parser.reset(); |
530 | 47 | Str.reset(); |
531 | | // Close the output stream early. |
532 | 47 | BOS.reset(); |
533 | 47 | FDOS.reset(); |
534 | | |
535 | | // Delete output file if there were errors. |
536 | 47 | if (Failed) { |
537 | 12 | if (Opts.OutputPath != "-") |
538 | 12 | sys::fs::remove(Opts.OutputPath); |
539 | 12 | if (!Opts.SplitDwarfOutput.empty() && Opts.SplitDwarfOutput != "-"0 ) |
540 | 0 | sys::fs::remove(Opts.SplitDwarfOutput); |
541 | 12 | } |
542 | | |
543 | 47 | return Failed; |
544 | 47 | } |
545 | | |
546 | | static void LLVMErrorHandler(void *UserData, const std::string &Message, |
547 | 0 | bool GenCrashDiag) { |
548 | 0 | DiagnosticsEngine &Diags = *static_cast<DiagnosticsEngine*>(UserData); |
549 | |
|
550 | 0 | Diags.Report(diag::err_fe_error_backend) << Message; |
551 | | |
552 | | // We cannot recover from llvm errors. |
553 | 0 | sys::Process::Exit(1); |
554 | 0 | } |
555 | | |
556 | 48 | int cc1as_main(ArrayRef<const char *> Argv, const char *Argv0, void *MainAddr) { |
557 | | // Initialize targets and assembly printers/parsers. |
558 | 48 | InitializeAllTargetInfos(); |
559 | 48 | InitializeAllTargetMCs(); |
560 | 48 | InitializeAllAsmParsers(); |
561 | | |
562 | | // Construct our diagnostic client. |
563 | 48 | IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions(); |
564 | 48 | TextDiagnosticPrinter *DiagClient |
565 | 48 | = new TextDiagnosticPrinter(errs(), &*DiagOpts); |
566 | 48 | DiagClient->setPrefix("clang -cc1as"); |
567 | 48 | IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs()); |
568 | 48 | DiagnosticsEngine Diags(DiagID, &*DiagOpts, DiagClient); |
569 | | |
570 | | // Set an error handler, so that any LLVM backend diagnostics go through our |
571 | | // error handler. |
572 | 48 | ScopedFatalErrorHandler FatalErrorHandler |
573 | 48 | (LLVMErrorHandler, static_cast<void*>(&Diags)); |
574 | | |
575 | | // Parse the arguments. |
576 | 48 | AssemblerInvocation Asm; |
577 | 48 | if (!AssemblerInvocation::CreateFromArgs(Asm, Argv, Diags)) |
578 | 1 | return 1; |
579 | | |
580 | 47 | if (Asm.ShowHelp) { |
581 | 0 | getDriverOptTable().PrintHelp( |
582 | 0 | llvm::outs(), "clang -cc1as [options] file...", |
583 | 0 | "Clang Integrated Assembler", |
584 | 0 | /*Include=*/driver::options::CC1AsOption, /*Exclude=*/0, |
585 | 0 | /*ShowAllAliases=*/false); |
586 | 0 | return 0; |
587 | 0 | } |
588 | | |
589 | | // Honor -version. |
590 | | // |
591 | | // FIXME: Use a better -version message? |
592 | 47 | if (Asm.ShowVersion) { |
593 | 0 | llvm::cl::PrintVersionMessage(); |
594 | 0 | return 0; |
595 | 0 | } |
596 | | |
597 | | // Honor -mllvm. |
598 | | // |
599 | | // FIXME: Remove this, one day. |
600 | 47 | if (!Asm.LLVMArgs.empty()) { |
601 | 17 | unsigned NumArgs = Asm.LLVMArgs.size(); |
602 | 17 | auto Args = std::make_unique<const char*[]>(NumArgs + 2); |
603 | 17 | Args[0] = "clang (LLVM option parsing)"; |
604 | 34 | for (unsigned i = 0; i != NumArgs; ++i17 ) |
605 | 17 | Args[i + 1] = Asm.LLVMArgs[i].c_str(); |
606 | 17 | Args[NumArgs + 1] = nullptr; |
607 | 17 | llvm::cl::ParseCommandLineOptions(NumArgs + 1, Args.get()); |
608 | 17 | } |
609 | | |
610 | | // Execute the invocation, unless there were parsing errors. |
611 | 47 | bool Failed = Diags.hasErrorOccurred() || ExecuteAssembler(Asm, Diags); |
612 | | |
613 | | // If any timers were active but haven't been destroyed yet, print their |
614 | | // results now. |
615 | 47 | TimerGroup::printAll(errs()); |
616 | 47 | TimerGroup::clearAll(); |
617 | | |
618 | 47 | return !!Failed; |
619 | 47 | } |