Coverage Report

Created: 2022-07-16 07:03

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