Coverage Report

Created: 2018-07-21 08:31

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