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