Coverage Report

Created: 2020-09-22 08:39

/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,
225
2
                                     OPT_compress_debug_sections_EQ)) {
226
2
    if (A->getOption().getID() == OPT_compress_debug_sections) {
227
2
      Opts.CompressDebugSections = llvm::DebugCompressionType::Z;
228
0
    } else {
229
0
      Opts.CompressDebugSections =
230
0
          llvm::StringSwitch<llvm::DebugCompressionType>(A->getValue())
231
0
              .Case("none", llvm::DebugCompressionType::None)
232
0
              .Case("zlib", llvm::DebugCompressionType::Z)
233
0
              .Case("zlib-gnu", llvm::DebugCompressionType::GNU)
234
0
              .Default(llvm::DebugCompressionType::None);
235
0
    }
236
2
  }
237
238
48
  Opts.RelaxELFRelocations = Args.hasArg(OPT_mrelax_relocations);
239
48
  Opts.DwarfVersion = getLastArgIntValue(Args, OPT_dwarf_version_EQ, 2, Diags);
240
48
  Opts.DwarfDebugFlags =
241
48
      std::string(Args.getLastArgValue(OPT_dwarf_debug_flags));
242
48
  Opts.DwarfDebugProducer =
243
48
      std::string(Args.getLastArgValue(OPT_dwarf_debug_producer));
244
48
  Opts.DebugCompilationDir =
245
48
      std::string(Args.getLastArgValue(OPT_fdebug_compilation_dir));
246
48
  Opts.MainFileName = std::string(Args.getLastArgValue(OPT_main_file_name));
247
248
0
  for (const auto &Arg : Args.getAllArgValues(OPT_fdebug_prefix_map_EQ)) {
249
0
    auto Split = StringRef(Arg).split('=');
250
0
    Opts.DebugPrefixMap.insert(
251
0
        {std::string(Split.first), std::string(Split.second)});
252
0
  }
253
254
  // Frontend Options
255
48
  if (Args.hasArg(OPT_INPUT)) {
256
47
    bool First = true;
257
47
    for (const Arg *A : Args.filtered(OPT_INPUT)) {
258
47
      if (First) {
259
47
        Opts.InputFile = A->getValue();
260
47
        First = false;
261
0
      } else {
262
0
        Diags.Report(diag::err_drv_unknown_argument) << A->getAsString(Args);
263
0
        Success = false;
264
0
      }
265
47
    }
266
47
  }
267
48
  Opts.LLVMArgs = Args.getAllArgValues(OPT_mllvm);
268
48
  Opts.OutputPath = std::string(Args.getLastArgValue(OPT_o));
269
48
  Opts.SplitDwarfOutput =
270
48
      std::string(Args.getLastArgValue(OPT_split_dwarf_output));
271
48
  if (Arg *A = Args.getLastArg(OPT_filetype)) {
272
47
    StringRef Name = A->getValue();
273
47
    unsigned OutputType = StringSwitch<unsigned>(Name)
274
47
      .Case("asm", FT_Asm)
275
47
      .Case("null", FT_Null)
276
47
      .Case("obj", FT_Obj)
277
47
      .Default(~0U);
278
47
    if (OutputType == ~0U) {
279
0
      Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Name;
280
0
      Success = false;
281
0
    } else
282
47
      Opts.OutputType = FileType(OutputType);
283
47
  }
284
48
  Opts.ShowHelp = Args.hasArg(OPT_help);
285
48
  Opts.ShowVersion = Args.hasArg(OPT_version);
286
287
  // Transliterate Options
288
48
  Opts.OutputAsmVariant =
289
48
      getLastArgIntValue(Args, OPT_output_asm_variant, 0, Diags);
290
48
  Opts.ShowEncoding = Args.hasArg(OPT_show_encoding);
291
48
  Opts.ShowInst = Args.hasArg(OPT_show_inst);
292
293
  // Assemble Options
294
48
  Opts.RelaxAll = Args.hasArg(OPT_mrelax_all);
295
48
  Opts.NoExecStack = Args.hasArg(OPT_mno_exec_stack);
296
48
  Opts.FatalWarnings = Args.hasArg(OPT_massembler_fatal_warnings);
297
48
  Opts.NoWarn = Args.hasArg(OPT_massembler_no_warn);
298
48
  Opts.RelocationModel =
299
48
      std::string(Args.getLastArgValue(OPT_mrelocation_model, "pic"));
300
48
  Opts.TargetABI = std::string(Args.getLastArgValue(OPT_target_abi));
301
48
  Opts.IncrementalLinkerCompatible =
302
48
      Args.hasArg(OPT_mincremental_linker_compatible);
303
48
  Opts.SymbolDefs = Args.getAllArgValues(OPT_defsym);
304
305
  // EmbedBitcode Option. If -fembed-bitcode is enabled, set the flag.
306
  // EmbedBitcode behaves the same for all embed options for assembly files.
307
48
  if (auto *A = Args.getLastArg(OPT_fembed_bitcode_EQ)) {
308
1
    Opts.EmbedBitcode = llvm::StringSwitch<unsigned>(A->getValue())
309
1
                            .Case("all", 1)
310
1
                            .Case("bitcode", 1)
311
1
                            .Case("marker", 1)
312
1
                            .Default(0);
313
1
  }
314
315
48
  return Success;
316
48
}
317
318
static std::unique_ptr<raw_fd_ostream>
319
48
getOutputStream(StringRef Path, DiagnosticsEngine &Diags, bool Binary) {
320
  // Make sure that the Out file gets unlinked from the disk if we get a
321
  // SIGINT.
322
48
  if (Path != "-")
323
37
    sys::RemoveFileOnSignal(Path);
324
325
48
  std::error_code EC;
326
48
  auto Out = std::make_unique<raw_fd_ostream>(
327
43
      Path, EC, (Binary ? sys::fs::OF_None : 
sys::fs::OF_Text5
));
328
48
  if (EC) {
329
0
    Diags.Report(diag::err_fe_unable_to_open_output) << Path << EC.message();
330
0
    return nullptr;
331
0
  }
332
333
48
  return Out;
334
48
}
335
336
static bool ExecuteAssembler(AssemblerInvocation &Opts,
337
47
                             DiagnosticsEngine &Diags) {
338
  // Get the target specific parser.
339
47
  std::string Error;
340
47
  const Target *TheTarget = TargetRegistry::lookupTarget(Opts.Triple, Error);
341
47
  if (!TheTarget)
342
0
    return Diags.Report(diag::err_target_unknown_triple) << Opts.Triple;
343
344
47
  ErrorOr<std::unique_ptr<MemoryBuffer>> Buffer =
345
47
      MemoryBuffer::getFileOrSTDIN(Opts.InputFile);
346
347
47
  if (std::error_code EC = Buffer.getError()) {
348
0
    Error = EC.message();
349
0
    return Diags.Report(diag::err_fe_error_reading) << Opts.InputFile;
350
0
  }
351
352
47
  SourceMgr SrcMgr;
353
354
  // Tell SrcMgr about this buffer, which is what the parser will pick up.
355
47
  unsigned BufferIndex = SrcMgr.AddNewSourceBuffer(std::move(*Buffer), SMLoc());
356
357
  // Record the location of the include directories so that the lexer can find
358
  // it later.
359
47
  SrcMgr.setIncludeDirs(Opts.IncludePaths);
360
361
47
  std::unique_ptr<MCRegisterInfo> MRI(TheTarget->createMCRegInfo(Opts.Triple));
362
47
  assert(MRI && "Unable to create target register info!");
363
364
47
  MCTargetOptions MCOptions;
365
47
  std::unique_ptr<MCAsmInfo> MAI(
366
47
      TheTarget->createMCAsmInfo(*MRI, Opts.Triple, MCOptions));
367
47
  assert(MAI && "Unable to create target asm info!");
368
369
  // Ensure MCAsmInfo initialization occurs before any use, otherwise sections
370
  // may be created with a combination of default and explicit settings.
371
47
  MAI->setCompressDebugSections(Opts.CompressDebugSections);
372
373
47
  MAI->setRelaxELFRelocations(Opts.RelaxELFRelocations);
374
375
47
  bool IsBinary = Opts.OutputType == AssemblerInvocation::FT_Obj;
376
47
  if (Opts.OutputPath.empty())
377
3
    Opts.OutputPath = "-";
378
47
  std::unique_ptr<raw_fd_ostream> FDOS =
379
47
      getOutputStream(Opts.OutputPath, Diags, IsBinary);
380
47
  if (!FDOS)
381
0
    return true;
382
47
  std::unique_ptr<raw_fd_ostream> DwoOS;
383
47
  if (!Opts.SplitDwarfOutput.empty())
384
1
    DwoOS = getOutputStream(Opts.SplitDwarfOutput, Diags, IsBinary);
385
386
  // FIXME: This is not pretty. MCContext has a ptr to MCObjectFileInfo and
387
  // MCObjectFileInfo needs a MCContext reference in order to initialize itself.
388
47
  std::unique_ptr<MCObjectFileInfo> MOFI(new MCObjectFileInfo());
389
390
47
  MCContext Ctx(MAI.get(), MRI.get(), MOFI.get(), &SrcMgr, &MCOptions);
391
392
47
  bool PIC = false;
393
47
  if (Opts.RelocationModel == "static") {
394
31
    PIC = false;
395
16
  } else if (Opts.RelocationModel == "pic") {
396
16
    PIC = true;
397
0
  } else {
398
0
    assert(Opts.RelocationModel == "dynamic-no-pic" &&
399
0
           "Invalid PIC model!");
400
0
    PIC = false;
401
0
  }
402
403
47
  MOFI->InitMCObjectFileInfo(Triple(Opts.Triple), PIC, Ctx);
404
47
  if (Opts.SaveTemporaryLabels)
405
0
    Ctx.setAllowTemporaryLabels(false);
406
47
  if (Opts.GenDwarfForAssembly)
407
3
    Ctx.setGenDwarfForAssembly(true);
408
47
  if (!Opts.DwarfDebugFlags.empty())
409
0
    Ctx.setDwarfDebugFlags(StringRef(Opts.DwarfDebugFlags));
410
47
  if (!Opts.DwarfDebugProducer.empty())
411
30
    Ctx.setDwarfDebugProducer(StringRef(Opts.DwarfDebugProducer));
412
47
  if (!Opts.DebugCompilationDir.empty())
413
30
    Ctx.setCompilationDir(Opts.DebugCompilationDir);
414
17
  else {
415
    // If no compilation dir is set, try to use the current directory.
416
17
    SmallString<128> CWD;
417
17
    if (!sys::fs::current_path(CWD))
418
17
      Ctx.setCompilationDir(CWD);
419
17
  }
420
47
  if (!Opts.DebugPrefixMap.empty())
421
0
    for (const auto &KV : Opts.DebugPrefixMap)
422
0
      Ctx.addDebugPrefixMapEntry(KV.first, KV.second);
423
47
  if (!Opts.MainFileName.empty())
424
38
    Ctx.setMainFileName(StringRef(Opts.MainFileName));
425
47
  Ctx.setDwarfVersion(Opts.DwarfVersion);
426
47
  if (Opts.GenDwarfForAssembly)
427
3
    Ctx.setGenDwarfRootFile(Opts.InputFile,
428
3
                            SrcMgr.getMemoryBuffer(BufferIndex)->getBuffer());
429
430
  // Build up the feature string from the target feature list.
431
47
  std::string FS = llvm::join(Opts.Features, ",");
432
433
47
  std::unique_ptr<MCStreamer> Str;
434
435
47
  std::unique_ptr<MCInstrInfo> MCII(TheTarget->createMCInstrInfo());
436
47
  std::unique_ptr<MCSubtargetInfo> STI(
437
47
      TheTarget->createMCSubtargetInfo(Opts.Triple, Opts.CPU, FS));
438
439
47
  raw_pwrite_stream *Out = FDOS.get();
440
47
  std::unique_ptr<buffer_ostream> BOS;
441
442
47
  MCOptions.MCNoWarn = Opts.NoWarn;
443
47
  MCOptions.MCFatalWarnings = Opts.FatalWarnings;
444
47
  MCOptions.ABIName = Opts.TargetABI;
445
446
  // FIXME: There is a bit of code duplication with addPassesToEmitFile.
447
47
  if (Opts.OutputType == AssemblerInvocation::FT_Asm) {
448
5
    MCInstPrinter *IP = TheTarget->createMCInstPrinter(
449
5
        llvm::Triple(Opts.Triple), Opts.OutputAsmVariant, *MAI, *MCII, *MRI);
450
451
5
    std::unique_ptr<MCCodeEmitter> CE;
452
5
    if (Opts.ShowEncoding)
453
0
      CE.reset(TheTarget->createMCCodeEmitter(*MCII, *MRI, Ctx));
454
5
    std::unique_ptr<MCAsmBackend> MAB(
455
5
        TheTarget->createMCAsmBackend(*STI, *MRI, MCOptions));
456
457
5
    auto FOut = std::make_unique<formatted_raw_ostream>(*Out);
458
5
    Str.reset(TheTarget->createAsmStreamer(
459
5
        Ctx, std::move(FOut), /*asmverbose*/ true,
460
5
        /*useDwarfDirectory*/ true, IP, std::move(CE), std::move(MAB),
461
5
        Opts.ShowInst));
462
42
  } else if (Opts.OutputType == AssemblerInvocation::FT_Null) {
463
0
    Str.reset(createNullStreamer(Ctx));
464
42
  } else {
465
42
    assert(Opts.OutputType == AssemblerInvocation::FT_Obj &&
466
42
           "Invalid file type!");
467
42
    if (!FDOS->supportsSeeking()) {
468
9
      BOS = std::make_unique<buffer_ostream>(*FDOS);
469
9
      Out = BOS.get();
470
9
    }
471
472
42
    std::unique_ptr<MCCodeEmitter> CE(
473
42
        TheTarget->createMCCodeEmitter(*MCII, *MRI, Ctx));
474
42
    std::unique_ptr<MCAsmBackend> MAB(
475
42
        TheTarget->createMCAsmBackend(*STI, *MRI, MCOptions));
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
  // Close Streamer first.
529
  // It might have a reference to the output stream.
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
}