link_subcommand.cpp 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139
  1. // Part of the Carbon Language project, under the Apache License v2.0 with LLVM
  2. // Exceptions. See /LICENSE for license information.
  3. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  4. #include "toolchain/driver/link_subcommand.h"
  5. #include "llvm/TargetParser/Triple.h"
  6. #include "toolchain/driver/clang_runner.h"
  7. namespace Carbon {
  8. auto LinkOptions::Build(CommandLine::CommandBuilder& b) -> void {
  9. b.AddStringPositionalArg(
  10. {
  11. .name = "OBJECT_FILE",
  12. .help = R"""(
  13. The input object files.
  14. )""",
  15. },
  16. [&](auto& arg_b) {
  17. arg_b.Required(true);
  18. arg_b.Append(&object_filenames);
  19. });
  20. b.AddStringOption(
  21. {
  22. .name = "output",
  23. .value_name = "FILE",
  24. .help = R"""(
  25. The linked file name. The output is always a linked binary.
  26. )""",
  27. },
  28. [&](auto& arg_b) {
  29. arg_b.Required(true);
  30. arg_b.Set(&output_filename);
  31. });
  32. codegen_options.Build(b);
  33. }
  34. static void AddOSFlags(llvm::StringRef target,
  35. llvm::SmallVectorImpl<llvm::StringRef>& args) {
  36. llvm::Triple triple(target);
  37. switch (triple.getOS()) {
  38. case llvm::Triple::Darwin:
  39. case llvm::Triple::MacOSX:
  40. // On macOS we need to set the sysroot to a viable SDK. Currently, this
  41. // hard codes the path to be the unversioned symlink. The prefix is also
  42. // hard coded in Homebrew and so this seems likely to work reasonably
  43. // well. Homebrew and I suspect the Xcode Clang both have this hard coded
  44. // at build time, so this seems reasonably safe but we can revisit if/when
  45. // needed.
  46. args.push_back(
  47. "--sysroot=/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk");
  48. // We also need to insist on a modern linker, otherwise the driver tries
  49. // too old and deprecated flags. The specific number here comes from an
  50. // inspection of the Clang driver source code to understand where features
  51. // were enabled, and this appears to be the latest version to control
  52. // driver behavior.
  53. //
  54. // TODO: We should replace this with use of `lld` eventually.
  55. args.push_back("-mlinker-version=705");
  56. break;
  57. default:
  58. // By default, just let the Clang driver handle everything.
  59. break;
  60. }
  61. }
  62. static constexpr CommandLine::CommandInfo SubcommandInfo = {
  63. .name = "link",
  64. .help = R"""(
  65. Link Carbon executables.
  66. This subcommand links Carbon executables by combining object files.
  67. TODO: Support linking binary libraries, both archives and shared libraries.
  68. TODO: Support linking against binary libraries.
  69. )""",
  70. };
  71. LinkSubcommand::LinkSubcommand() : DriverSubcommand(SubcommandInfo) {}
  72. auto LinkSubcommand::Run(DriverEnv& driver_env) -> DriverResult {
  73. // TODO: Currently we use the Clang driver to link. This works well on Unix
  74. // OSes but we likely need to directly build logic to invoke `link.exe` on
  75. // Windows where `cl.exe` doesn't typically cover that logic.
  76. // Use a reasonably large small vector here to minimize allocations. We expect
  77. // to link reasonably large numbers of object files.
  78. llvm::SmallVector<llvm::StringRef, 128> clang_args;
  79. // We link using a C++ mode of the driver.
  80. clang_args.push_back("--driver-mode=g++");
  81. // Pass the target down to Clang to pick up the correct defaults.
  82. std::string target_arg =
  83. llvm::formatv("--target={0}", options_.codegen_options.target).str();
  84. clang_args.push_back(target_arg);
  85. // Use LLD, which we provide in our install directory, for linking.
  86. clang_args.push_back("-fuse-ld=lld");
  87. // Disable linking the C++ standard library until can build and ship it as
  88. // part of the Carbon toolchain. This clearly won't work once we get into
  89. // interop, but for now it avoids spurious failures and distraction. The plan
  90. // is to build and bundle libc++ at which point we can replace this with
  91. // pointing at our bundled library.
  92. // TODO: Replace this when ready.
  93. clang_args.push_back("-nostdlib++");
  94. // Add OS-specific flags based on the target.
  95. AddOSFlags(options_.codegen_options.target, clang_args);
  96. clang_args.push_back("-o");
  97. clang_args.push_back(options_.output_filename);
  98. clang_args.append(options_.object_filenames.begin(),
  99. options_.object_filenames.end());
  100. ClangRunner runner(driver_env.installation, driver_env.fs,
  101. driver_env.vlog_stream);
  102. ErrorOr<bool> run_result = runner.Run(clang_args, driver_env.runtimes_cache,
  103. *driver_env.thread_pool);
  104. if (!run_result.ok()) {
  105. // This is not a Clang failure, but a failure to even run Clang, so we need
  106. // to diagnose it here.
  107. CARBON_DIAGNOSTIC(FailureRunningClangToLink, Error,
  108. "failure running `clang` to perform linking: {0}",
  109. std::string);
  110. driver_env.emitter.Emit(FailureRunningClangToLink,
  111. run_result.error().message());
  112. return {.success = false};
  113. }
  114. // Successfully ran Clang to perform the link, return its result.
  115. return {.success = *run_result};
  116. }
  117. } // namespace Carbon