clang 23.0.0git
WebAssembly.cpp
Go to the documentation of this file.
1//===--- WebAssembly.cpp - WebAssembly ToolChain Implementation -*- C++ -*-===//
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#include "WebAssembly.h"
10#include "Gnu.h"
11#include "clang/Config/config.h"
14#include "clang/Driver/Driver.h"
16#include "llvm/Config/llvm-config.h" // for LLVM_VERSION_STRING
17#include "llvm/Option/ArgList.h"
18#include "llvm/Support/FileSystem.h"
19#include "llvm/Support/Path.h"
20#include "llvm/Support/VirtualFileSystem.h"
21
22using namespace clang::driver;
23using namespace clang::driver::tools;
24using namespace clang::driver::toolchains;
25using namespace clang;
26using namespace llvm::opt;
27
28/// Following the conventions in https://wiki.debian.org/Multiarch/Tuples,
29/// we remove the vendor field to form the multiarch triple.
30std::string WebAssembly::getMultiarchTriple(const Driver &D,
31 const llvm::Triple &TargetTriple,
32 StringRef SysRoot) const {
33 return (TargetTriple.getArchName() + "-" +
34 TargetTriple.getOSAndEnvironmentName()).str();
35}
36
37/// Returns a directory name in which separate objects compile with/without
38/// exceptions may lie. This is used both for `#include` paths as well as lib
39/// paths.
40static std::string GetCXXExceptionsDir(const ArgList &DriverArgs) {
41 if (DriverArgs.getLastArg(options::OPT_fwasm_exceptions))
42 return "eh";
43 return "noeh";
44}
45
46std::string wasm::Linker::getLinkerPath(const ArgList &Args) const {
48 if (const Arg* A = Args.getLastArg(options::OPT_fuse_ld_EQ)) {
49 StringRef UseLinker = A->getValue();
50 if (!UseLinker.empty()) {
51 if (llvm::sys::path::is_absolute(UseLinker) &&
52 llvm::sys::fs::can_execute(UseLinker))
53 return std::string(UseLinker);
54
55 // Interpret 'lld' as explicitly requesting `wasm-ld`, so look for that
56 // linker. Note that for `wasm32-wasip2` this overrides the default linker
57 // of `wasm-component-ld`.
58 if (UseLinker == "lld") {
59 return ToolChain.GetProgramPath("wasm-ld");
60 }
61
62 // Allow 'ld' as an alias for the default linker
63 if (UseLinker != "ld")
64 ToolChain.getDriver().Diag(diag::err_drv_invalid_linker_name)
65 << A->getAsString(Args);
66 }
67 }
68
70}
71
72static bool TargetBuildsComponents(const llvm::Triple &TargetTriple) {
73 // WASIp2 and above are all based on components, so test for WASI but exclude
74 // the original `wasi` target in addition to the `wasip1` name.
75 return TargetTriple.isOSWASI() && TargetTriple.getOSName() != "wasip1" &&
76 TargetTriple.getOSName() != "wasi";
77}
78
79static bool WantsPthread(const llvm::Triple &Triple, const ArgList &Args) {
80 bool WantsPthread =
81 Args.hasFlag(options::OPT_pthread, options::OPT_no_pthread, false);
82
83 // If the WASI environment is "threads" then enable pthreads support
84 // without requiring -pthread, in order to prevent user error
85 if (Triple.isOSWASI() && Triple.getEnvironmentName() == "threads")
86 WantsPthread = true;
87
88 return WantsPthread;
89}
90
91static bool WantsLibcallThreadContext(const llvm::Triple &Triple,
92 const ArgList &Args) {
93 return Triple.getOS() == llvm::Triple::WASIp3;
94}
95
97 const InputInfo &Output,
98 const InputInfoList &Inputs,
99 const ArgList &Args,
100 const char *LinkingOutput) const {
101
103 const char *Linker = Args.MakeArgString(getLinkerPath(Args));
104 ArgStringList CmdArgs;
105
106 CmdArgs.push_back("-m");
107 if (ToolChain.getTriple().isArch64Bit())
108 CmdArgs.push_back("wasm64");
109 else
110 CmdArgs.push_back("wasm32");
111
112 if (Args.hasArg(options::OPT_s))
113 CmdArgs.push_back("--strip-all");
114
115 // On `wasip2` the default linker is `wasm-component-ld` which wraps the
116 // execution of `wasm-ld`. Find `wasm-ld` and pass it as an argument of where
117 // to find it to avoid it needing to hunt and rediscover or search `PATH` for
118 // where it is.
119 if (llvm::sys::path::stem(Linker).ends_with_insensitive(
120 "wasm-component-ld")) {
121 CmdArgs.push_back("--wasm-ld-path");
122 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetProgramPath("wasm-ld")));
123 }
124
125 Args.addAllArgs(CmdArgs, {options::OPT_L, options::OPT_u});
126
127 ToolChain.AddFilePathLibArgs(Args, CmdArgs);
128
129 bool IsCommand = true;
130 const char *Crt1;
131 const char *Entry = nullptr;
132
133 // When -shared is specified, use the reactor exec model unless
134 // specified otherwise.
135 if (Args.hasArg(options::OPT_shared))
136 IsCommand = false;
137
138 if (const Arg *A = Args.getLastArg(options::OPT_mexec_model_EQ)) {
139 StringRef CM = A->getValue();
140 if (CM == "command") {
141 IsCommand = true;
142 } else if (CM == "reactor") {
143 IsCommand = false;
144 } else {
145 ToolChain.getDriver().Diag(diag::err_drv_invalid_argument_to_option)
146 << CM << A->getOption().getName();
147 }
148 }
149
150 if (IsCommand) {
151 // If crt1-command.o exists, it supports new-style commands, so use it.
152 // Otherwise, use the old crt1.o. This is a temporary transition measure.
153 // Once WASI libc no longer needs to support LLVM versions which lack
154 // support for new-style command, it can make crt1.o the same as
155 // crt1-command.o. And once LLVM no longer needs to support WASI libc
156 // versions before that, it can switch to using crt1-command.o.
157 Crt1 = "crt1.o";
158 if (ToolChain.GetFilePath("crt1-command.o") != "crt1-command.o")
159 Crt1 = "crt1-command.o";
160 } else {
161 Crt1 = "crt1-reactor.o";
162 Entry = "_initialize";
163 }
164
165 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles))
166 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(Crt1)));
167 if (Entry) {
168 CmdArgs.push_back(Args.MakeArgString("--entry"));
169 CmdArgs.push_back(Args.MakeArgString(Entry));
170 }
171
172 if (Args.hasArg(options::OPT_shared))
173 CmdArgs.push_back(Args.MakeArgString("-shared"));
174
175 AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs, JA);
176
178 CmdArgs.push_back("--libcall-thread-context");
179
180 if (WantsPthread(ToolChain.getTriple(), Args))
181 CmdArgs.push_back("--shared-memory");
182
183 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
185 ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
186
187 if (WantsPthread(ToolChain.getTriple(), Args))
188 CmdArgs.push_back("-lpthread");
189
190 CmdArgs.push_back("-lc");
191 AddRunTimeLibs(ToolChain, ToolChain.getDriver(), CmdArgs, Args);
192 }
193
194 ToolChain.addProfileRTLibs(Args, CmdArgs);
195
196 CmdArgs.push_back("-o");
197 CmdArgs.push_back(Output.getFilename());
198
199 // Don't use wasm-opt by default on `wasip2` as it doesn't have support for
200 // components at this time. Retain the historical default otherwise, though,
201 // of running `wasm-opt` by default.
202 bool WasmOptDefault = !TargetBuildsComponents(ToolChain.getTriple());
203 bool RunWasmOpt = Args.hasFlag(options::OPT_wasm_opt,
204 options::OPT_no_wasm_opt, WasmOptDefault);
205
206 // If wasm-opt is enabled and optimizations are happening look for the
207 // `wasm-opt` program. If it's not found auto-disable it.
208 std::string WasmOptPath;
209 if (RunWasmOpt && Args.getLastArg(options::OPT_O_Group)) {
210 WasmOptPath = ToolChain.GetProgramPath("wasm-opt");
211 if (WasmOptPath == "wasm-opt") {
212 WasmOptPath = {};
213 }
214 }
215
216 if (!WasmOptPath.empty()) {
217 CmdArgs.push_back("--keep-section=target_features");
218 }
219
220 C.addCommand(std::make_unique<Command>(JA, *this,
222 Linker, CmdArgs, Inputs, Output));
223
224 if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
225 if (!WasmOptPath.empty()) {
226 StringRef OOpt = "s";
227 if (A->getOption().matches(options::OPT_O4) ||
228 A->getOption().matches(options::OPT_Ofast))
229 OOpt = "4";
230 else if (A->getOption().matches(options::OPT_O0))
231 OOpt = "0";
232 else if (A->getOption().matches(options::OPT_O))
233 OOpt = A->getValue();
234
235 if (OOpt != "0") {
236 const char *WasmOpt = Args.MakeArgString(WasmOptPath);
237 ArgStringList OptArgs;
238 OptArgs.push_back(Output.getFilename());
239 OptArgs.push_back(Args.MakeArgString(llvm::Twine("-O") + OOpt));
240 OptArgs.push_back("-o");
241 OptArgs.push_back(Output.getFilename());
242 C.addCommand(std::make_unique<Command>(
243 JA, *this, ResponseFileSupport::AtFileCurCP(), WasmOpt, OptArgs,
244 Inputs, Output));
245 }
246 }
247 }
248}
249
250/// Append `Dir` to `Paths`, but also include the LTO directories before that if
251/// LTO is enabled.
253 const ToolChain &TC,
254 const llvm::opt::ArgList &Args,
255 const std::string &Dir) {
256 if (TC.isUsingLTO(Args)) {
257 // The version allows the path to be keyed to the specific version of
258 // LLVM in used, as the bitcode format is not stable.
259 Paths.push_back(Dir + "/llvm-lto/" LLVM_VERSION_STRING);
260 }
261 Paths.push_back(Dir);
262}
263
264WebAssembly::WebAssembly(const Driver &D, const llvm::Triple &Triple,
265 const llvm::opt::ArgList &Args)
266 : ToolChain(D, Triple, Args) {
267
268 assert(Triple.isArch32Bit() != Triple.isArch64Bit());
269
270 getProgramPaths().push_back(getDriver().Dir);
271
272 auto SysRoot = getDriver().SysRoot;
273 if (getTriple().getOS() == llvm::Triple::UnknownOS) {
274 // Theoretically an "unknown" OS should mean no standard libraries, however
275 // it could also mean that a custom set of libraries is in use, so just add
276 // /lib to the search path. Disable multiarch in this case, to discourage
277 // paths containing "unknown" from acquiring meanings.
278 getFilePaths().push_back(SysRoot + "/lib");
279 } else {
280 const std::string MultiarchTriple =
281 getMultiarchTriple(getDriver(), Triple, SysRoot);
282 std::string TripleLibDir = SysRoot + "/lib/" + MultiarchTriple;
283 // Allow sysroots to segregate objects based on whether exceptions are
284 // enabled or not. This is intended to assist with distribution of pre-built
285 // sysroots that contain libraries that are capable of producing binaries
286 // entirely without exception-handling instructions but also with if
287 // exceptions are enabled, for example.
288 AppendLibDirAndLTODir(getFilePaths(), *this, Args,
289 TripleLibDir + "/" + GetCXXExceptionsDir(Args));
290 AppendLibDirAndLTODir(getFilePaths(), *this, Args, TripleLibDir);
291 }
292
293 if (getTriple().getOS() == llvm::Triple::WASI) {
294 D.Diag(diag::warn_drv_deprecated_custom)
295 << "--target=wasm32-wasi"
296 << "use --target=wasm32-wasip1 instead";
297 }
298}
299
300const char *WebAssembly::getDefaultLinker() const {
302 return "wasm-component-ld";
303 return "wasm-ld";
304}
305
306bool WebAssembly::IsMathErrnoDefault() const { return false; }
307
308bool WebAssembly::IsObjCNonFragileABIDefault() const { return true; }
309
310bool WebAssembly::UseObjCMixedDispatch() const { return true; }
311
312bool WebAssembly::isPICDefault() const { return false; }
313
314bool WebAssembly::isPIEDefault(const llvm::opt::ArgList &Args) const {
315 return false;
316}
317
318bool WebAssembly::isPICDefaultForced() const { return false; }
319
320bool WebAssembly::hasBlocksRuntime() const { return false; }
321
322// TODO: Support profiling.
323bool WebAssembly::SupportsProfiling() const { return false; }
324
325bool WebAssembly::HasNativeLLVMSupport() const { return true; }
326
327void WebAssembly::addClangTargetOptions(const ArgList &DriverArgs,
328 ArgStringList &CC1Args,
329 StringRef BoundArch,
330 Action::OffloadKind) const {
331 if (!DriverArgs.hasFlag(options::OPT_fuse_init_array,
332 options::OPT_fno_use_init_array, true))
333 CC1Args.push_back("-fno-use-init-array");
334
335 // '-pthread' implies atomics, bulk-memory, mutable-globals, and sign-ext
336 if (WantsPthread(getTriple(), DriverArgs)) {
337 if (DriverArgs.hasFlag(options::OPT_mno_atomics, options::OPT_matomics,
338 false))
339 getDriver().Diag(diag::err_drv_argument_not_allowed_with)
340 << "-pthread"
341 << "-mno-atomics";
342 if (DriverArgs.hasFlag(options::OPT_mno_bulk_memory,
343 options::OPT_mbulk_memory, false))
344 getDriver().Diag(diag::err_drv_argument_not_allowed_with)
345 << "-pthread"
346 << "-mno-bulk-memory";
347 if (DriverArgs.hasFlag(options::OPT_mno_mutable_globals,
348 options::OPT_mmutable_globals, false))
349 getDriver().Diag(diag::err_drv_argument_not_allowed_with)
350 << "-pthread"
351 << "-mno-mutable-globals";
352 if (DriverArgs.hasFlag(options::OPT_mno_sign_ext, options::OPT_msign_ext,
353 false))
354 getDriver().Diag(diag::err_drv_argument_not_allowed_with)
355 << "-pthread"
356 << "-mno-sign-ext";
357 CC1Args.push_back("-target-feature");
358 CC1Args.push_back("+atomics");
359 CC1Args.push_back("-target-feature");
360 CC1Args.push_back("+bulk-memory");
361 CC1Args.push_back("-target-feature");
362 CC1Args.push_back("+mutable-globals");
363 CC1Args.push_back("-target-feature");
364 CC1Args.push_back("+sign-ext");
365 }
366
367 if (!DriverArgs.hasFlag(options::OPT_mmutable_globals,
368 options::OPT_mno_mutable_globals, false)) {
369 // -fPIC implies +mutable-globals because the PIC ABI used by the linker
370 // depends on importing and exporting mutable globals.
371 llvm::Reloc::Model RelocationModel;
372 unsigned PICLevel;
373 bool IsPIE;
374 std::tie(RelocationModel, PICLevel, IsPIE) =
375 ParsePICArgs(*this, DriverArgs);
376 if (RelocationModel == llvm::Reloc::PIC_) {
377 if (DriverArgs.hasFlag(options::OPT_mno_mutable_globals,
378 options::OPT_mmutable_globals, false)) {
379 getDriver().Diag(diag::err_drv_argument_not_allowed_with)
380 << "-fPIC"
381 << "-mno-mutable-globals";
382 }
383 CC1Args.push_back("-target-feature");
384 CC1Args.push_back("+mutable-globals");
385 }
386 }
387
388 bool HasBannedIncompatibleOptionsForWasmEHSjLj = false;
389 bool HasEnabledFeaturesForWasmEHSjLj = false;
390
391 // Bans incompatible options for Wasm EH / SjLj. We don't allow using
392 // different modes for EH and SjLj.
393 auto BanIncompatibleOptionsForWasmEHSjLj = [&](StringRef CurOption) {
394 if (HasBannedIncompatibleOptionsForWasmEHSjLj)
395 return;
396 HasBannedIncompatibleOptionsForWasmEHSjLj = true;
397 if (DriverArgs.hasFlag(options::OPT_mno_exception_handing,
398 options::OPT_mexception_handing, false))
399 getDriver().Diag(diag::err_drv_argument_not_allowed_with)
400 << CurOption << "-mno-exception-handling";
401 // The standardized Wasm EH spec requires multivalue and reference-types.
402 if (DriverArgs.hasFlag(options::OPT_mno_multivalue,
403 options::OPT_mmultivalue, false))
404 getDriver().Diag(diag::err_drv_argument_not_allowed_with)
405 << CurOption << "-mno-multivalue";
406 if (DriverArgs.hasFlag(options::OPT_mno_reference_types,
407 options::OPT_mreference_types, false))
408 getDriver().Diag(diag::err_drv_argument_not_allowed_with)
409 << CurOption << "-mno-reference-types";
410
411 for (const Arg *A : DriverArgs.filtered(options::OPT_mllvm)) {
412 for (const auto *Option :
413 {"-enable-emscripten-cxx-exceptions", "-enable-emscripten-sjlj",
414 "-emscripten-cxx-exceptions-allowed"}) {
415 if (StringRef(A->getValue(0)) == Option)
416 getDriver().Diag(diag::err_drv_argument_not_allowed_with)
417 << CurOption << Option;
418 }
419 }
420 };
421
422 // Enable necessary features for Wasm EH / SjLj in the backend.
423 auto EnableFeaturesForWasmEHSjLj = [&]() {
424 if (HasEnabledFeaturesForWasmEHSjLj)
425 return;
426 HasEnabledFeaturesForWasmEHSjLj = true;
427 CC1Args.push_back("-target-feature");
428 CC1Args.push_back("+exception-handling");
429 // The standardized Wasm EH spec requires multivalue and reference-types.
430 CC1Args.push_back("-target-feature");
431 CC1Args.push_back("+multivalue");
432 CC1Args.push_back("-target-feature");
433 CC1Args.push_back("+reference-types");
434 // Backend needs '-exception-model=wasm' to use Wasm EH instructions
435 CC1Args.push_back("-exception-model=wasm");
436 };
437
438 if (DriverArgs.getLastArg(options::OPT_fwasm_exceptions)) {
439 BanIncompatibleOptionsForWasmEHSjLj("-fwasm-exceptions");
440 EnableFeaturesForWasmEHSjLj();
441 // Backend needs -wasm-enable-eh to enable Wasm EH
442 CC1Args.push_back("-mllvm");
443 CC1Args.push_back("-wasm-enable-eh");
444 }
445
446 for (const Arg *A : DriverArgs.filtered(options::OPT_mllvm)) {
447 StringRef Opt = A->getValue(0);
448 if (Opt.starts_with("-emscripten-cxx-exceptions-allowed")) {
449 // '-mllvm -emscripten-cxx-exceptions-allowed' should be used with
450 // '-mllvm -enable-emscripten-cxx-exceptions'
451 bool EmEHArgExists = false;
452 for (const Arg *A : DriverArgs.filtered(options::OPT_mllvm)) {
453 if (StringRef(A->getValue(0)) == "-enable-emscripten-cxx-exceptions") {
454 EmEHArgExists = true;
455 break;
456 }
457 }
458 if (!EmEHArgExists)
459 getDriver().Diag(diag::err_drv_argument_only_allowed_with)
460 << "-mllvm -emscripten-cxx-exceptions-allowed"
461 << "-mllvm -enable-emscripten-cxx-exceptions";
462
463 // Prevent functions specified in -emscripten-cxx-exceptions-allowed list
464 // from being inlined before reaching the wasm backend.
465 StringRef FuncNamesStr = Opt.split('=').second;
466 SmallVector<StringRef, 4> FuncNames;
467 FuncNamesStr.split(FuncNames, ',');
468 for (auto Name : FuncNames) {
469 CC1Args.push_back("-mllvm");
470 CC1Args.push_back(DriverArgs.MakeArgString("--force-attribute=" + Name +
471 ":noinline"));
472 }
473 }
474
475 for (const auto *Option :
476 {"-wasm-enable-eh", "-wasm-enable-sjlj", "-wasm-use-legacy-eh"}) {
477 if (Opt.starts_with(Option)) {
478 BanIncompatibleOptionsForWasmEHSjLj(Option);
479 EnableFeaturesForWasmEHSjLj();
480 }
481 }
482 }
483}
484
487}
488
490WebAssembly::GetCXXStdlibType(const ArgList &Args) const {
491 if (Arg *A = Args.getLastArg(options::OPT_stdlib_EQ)) {
492 StringRef Value = A->getValue();
493 if (Value == "libc++")
495 else if (Value == "libstdc++")
497 else
498 getDriver().Diag(diag::err_drv_invalid_stdlib_name)
499 << A->getAsString(Args);
500 }
502}
503
504void WebAssembly::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
505 ArgStringList &CC1Args) const {
506 if (DriverArgs.hasArg(options::OPT_nostdinc))
507 return;
508
509 const Driver &D = getDriver();
510
511 if (!DriverArgs.hasArg(options::OPT_nobuiltininc)) {
512 SmallString<128> P(D.ResourceDir);
513 llvm::sys::path::append(P, "include");
514 addSystemInclude(DriverArgs, CC1Args, P);
515 }
516
517 if (DriverArgs.hasArg(options::OPT_nostdlibinc))
518 return;
519
520 // Check for configure-time C include directories.
521 StringRef CIncludeDirs(C_INCLUDE_DIRS);
522 if (CIncludeDirs != "") {
523 SmallVector<StringRef, 5> dirs;
524 CIncludeDirs.split(dirs, ":");
525 for (StringRef dir : dirs) {
526 StringRef Prefix =
527 llvm::sys::path::is_absolute(dir) ? "" : StringRef(D.SysRoot);
528 addExternCSystemInclude(DriverArgs, CC1Args, Prefix + dir);
529 }
530 return;
531 }
532
533 if (getTriple().getOS() != llvm::Triple::UnknownOS) {
534 const std::string MultiarchTriple =
535 getMultiarchTriple(D, getTriple(), D.SysRoot);
536 addSystemInclude(DriverArgs, CC1Args, D.SysRoot + "/include/" + MultiarchTriple);
537 }
538 addSystemInclude(DriverArgs, CC1Args, D.SysRoot + "/include");
539}
540
541void WebAssembly::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
542 ArgStringList &CC1Args) const {
543
544 if (DriverArgs.hasArg(options::OPT_nostdlibinc, options::OPT_nostdinc,
545 options::OPT_nostdincxx))
546 return;
547
548 switch (GetCXXStdlibType(DriverArgs)) {
550 addLibCxxIncludePaths(DriverArgs, CC1Args);
551 break;
553 addLibStdCXXIncludePaths(DriverArgs, CC1Args);
554 break;
555 }
556}
557
558void WebAssembly::AddCXXStdlibLibArgs(const llvm::opt::ArgList &Args,
559 llvm::opt::ArgStringList &CmdArgs) const {
560
561 switch (GetCXXStdlibType(Args)) {
563 CmdArgs.push_back("-lc++");
564 if (Args.hasArg(options::OPT_fexperimental_library))
565 CmdArgs.push_back("-lc++experimental");
566 CmdArgs.push_back("-lc++abi");
567 break;
569 CmdArgs.push_back("-lstdc++");
570 break;
571 }
572}
573
574SanitizerMask WebAssembly::getSupportedSanitizers(
575 StringRef BoundArch, Action::OffloadKind DeviceOffloadKind) const {
576 SanitizerMask Res =
577 ToolChain::getSupportedSanitizers(BoundArch, DeviceOffloadKind);
578 if (getTriple().isOSEmscripten()) {
579 Res |= SanitizerKind::Vptr | SanitizerKind::Leak;
580 }
581
582 if (getTriple().isOSEmscripten() || getTriple().isOSWASI()) {
583 Res |= SanitizerKind::Address;
584 }
585
586 // -fsanitize=function places two words before the function label, which are
587 // -unsupported.
588 Res &= ~SanitizerKind::Function;
589 return Res;
590}
591
592Tool *WebAssembly::buildLinker() const {
593 return new tools::wasm::Linker(*this);
594}
595
596void WebAssembly::addLibCxxIncludePaths(
597 const llvm::opt::ArgList &DriverArgs,
598 llvm::opt::ArgStringList &CC1Args) const {
599 const Driver &D = getDriver();
600 std::string SysRoot = computeSysRoot();
601 std::string LibPath = SysRoot + "/include";
602 const std::string MultiarchTriple =
603 getMultiarchTriple(D, getTriple(), SysRoot);
604 bool IsKnownOs = (getTriple().getOS() != llvm::Triple::UnknownOS);
605
606 std::string Version = detectLibcxxVersion(LibPath);
607 if (Version.empty())
608 return;
609
610 // First add the per-target-per-exception-handling include path if the
611 // OS is known, then second add the per-target include path.
612 if (IsKnownOs) {
613 std::string TargetDir = LibPath + "/" + MultiarchTriple;
614 std::string Suffix = "/c++/" + Version;
615 addSystemInclude(DriverArgs, CC1Args,
616 TargetDir + "/" + GetCXXExceptionsDir(DriverArgs) +
617 Suffix);
618 addSystemInclude(DriverArgs, CC1Args, TargetDir + Suffix);
619 }
620
621 // Third add the generic one.
622 addSystemInclude(DriverArgs, CC1Args, LibPath + "/c++/" + Version);
623}
624
625void WebAssembly::addLibStdCXXIncludePaths(
626 const llvm::opt::ArgList &DriverArgs,
627 llvm::opt::ArgStringList &CC1Args) const {
628 // We cannot use GCCInstallationDetector here as the sysroot usually does
629 // not contain a full GCC installation.
630 // Instead, we search the given sysroot for /usr/include/xx, similar
631 // to how we do it for libc++.
632 const Driver &D = getDriver();
633 std::string SysRoot = computeSysRoot();
634 std::string LibPath = SysRoot + "/include";
635 const std::string MultiarchTriple =
636 getMultiarchTriple(D, getTriple(), SysRoot);
637 bool IsKnownOs = (getTriple().getOS() != llvm::Triple::UnknownOS);
638
639 // This is similar to detectLibcxxVersion()
640 std::string Version;
641 {
642 std::error_code EC;
643 Generic_GCC::GCCVersion MaxVersion =
645 SmallString<128> Path(LibPath);
646 llvm::sys::path::append(Path, "c++");
647 for (llvm::vfs::directory_iterator LI = getVFS().dir_begin(Path, EC), LE;
648 !EC && LI != LE; LI = LI.increment(EC)) {
649 StringRef VersionText = llvm::sys::path::filename(LI->path());
650 if (VersionText[0] != 'v') {
651 auto Version = Generic_GCC::GCCVersion::Parse(VersionText);
652 if (Version > MaxVersion)
653 MaxVersion = Version;
654 }
655 }
656 if (MaxVersion.Major > 0)
657 Version = MaxVersion.Text;
658 }
659
660 if (Version.empty())
661 return;
662
663 // First add the per-target include path if the OS is known.
664 if (IsKnownOs) {
665 std::string TargetDir = LibPath + "/c++/" + Version + "/" + MultiarchTriple;
666 addSystemInclude(DriverArgs, CC1Args, TargetDir);
667 }
668
669 // Second add the generic one.
670 addSystemInclude(DriverArgs, CC1Args, LibPath + "/c++/" + Version);
671 // Third the backward one.
672 addSystemInclude(DriverArgs, CC1Args, LibPath + "/c++/" + Version + "/backward");
673}
static std::string GetCXXExceptionsDir(const ArgList &DriverArgs)
Returns a directory name in which separate objects compile with/without exceptions may lie.
static void AppendLibDirAndLTODir(ToolChain::path_list &Paths, const ToolChain &TC, const llvm::opt::ArgList &Args, const std::string &Dir)
Append Dir to Paths, but also include the LTO directories before that if LTO is enabled.
static bool WantsPthread(const llvm::Triple &Triple, const ArgList &Args)
static bool TargetBuildsComponents(const llvm::Triple &TargetTriple)
static bool WantsLibcallThreadContext(const llvm::Triple &Triple, const ArgList &Args)
static StringRef getTriple(const Command &Job)
Compilation - A set of tasks to perform for a single driver invocation.
Definition Compilation.h:45
Driver - Encapsulate logic for constructing compilation processes from a set of gcc-driver-like comma...
Definition Driver.h:94
DiagnosticBuilder Diag(unsigned DiagID) const
Definition Driver.h:158
InputInfo - Wrapper for information about an input source.
Definition InputInfo.h:22
const char * getFilename() const
Definition InputInfo.h:83
ToolChain - Access to tools for a single platform.
Definition ToolChain.h:95
static void addSystemInclude(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args, const Twine &Path)
Utility function to add a system include directory to CC1 arguments.
bool isUsingLTO(const llvm::opt::ArgList &Args, Action::OffloadKind Kind=Action::OFK_None) const
Returns true if LTO is active for this toolchain given the args.
virtual std::string computeSysRoot() const
Return the sysroot, possibly searching for a default sysroot using target-specific logic.
bool ShouldLinkCXXStdlib(const llvm::opt::ArgList &Args) const
Returns if the C++ standard library should be linked in.
static void addExternCSystemInclude(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args, const Twine &Path)
Utility function to add a system include directory with extern "C" semantics to CC1 arguments.
std::string GetFilePath(const char *Name) const
StringRef getOS() const
Definition ToolChain.h:304
virtual bool IsObjCNonFragileABIDefault() const
IsObjCNonFragileABIDefault - Does this tool chain set -fobjc-nonfragile-abi by default.
Definition ToolChain.h:520
const Driver & getDriver() const
Definition ToolChain.h:285
virtual std::string detectLibcxxVersion(StringRef IncludePath) const
llvm::vfs::FileSystem & getVFS() const
virtual bool isPICDefaultForced() const =0
Tests whether this toolchain forces its default for PIC, PIE or non-PIC.
virtual SanitizerMask getSupportedSanitizers(StringRef BoundArch, Action::OffloadKind DeviceOffloadKind) const
Return sanitizers which are available in this toolchain.
virtual bool IsMathErrnoDefault() const
IsMathErrnoDefault - Does this tool chain use -fmath-errno by default.
Definition ToolChain.h:512
virtual void AddCXXStdlibLibArgs(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs) const
AddCXXStdlibLibArgs - Add the system specific linker arguments to use for the given C++ standard libr...
virtual const char * getDefaultLinker() const
GetDefaultLinker - Get the default linker to use.
Definition ToolChain.h:546
virtual Tool * buildLinker() const
const llvm::Triple & getTriple() const
Definition ToolChain.h:287
virtual bool HasNativeLLVMSupport() const
HasNativeLTOLinker - Check whether the linker and related tools have native LLVM support.
virtual void addProfileRTLibs(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs) const
addProfileRTLibs - When -fprofile-instr-profile is specified, try to pass a suitable profile runtime ...
std::string GetProgramPath(const char *Name) const
virtual bool hasBlocksRuntime() const
hasBlocksRuntime - Given that the user is compiling with -fblocks, does this tool chain guarantee the...
Definition ToolChain.h:742
virtual bool SupportsProfiling() const
SupportsProfiling - Does this tool chain support -pg.
Definition ToolChain.h:642
virtual bool UseObjCMixedDispatch() const
UseObjCMixedDispatchDefault - When using non-legacy dispatch, should the mixed dispatch method be use...
Definition ToolChain.h:524
virtual void AddFilePathLibArgs(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs) const
AddFilePathLibArgs - Add each thing in getFilePaths() as a "-L" option.
virtual RuntimeLibType GetDefaultRuntimeLibType() const
GetDefaultRuntimeLibType - Get the default runtime library variant to use.
Definition ToolChain.h:549
virtual bool isPICDefault() const =0
Test whether this toolchain defaults to PIC.
SmallVector< std::string, 16 > path_list
Definition ToolChain.h:97
const ToolChain & getToolChain() const
Definition Tool.h:52
WebAssembly(const Driver &D, const llvm::Triple &Triple, const llvm::opt::ArgList &Args)
std::string getLinkerPath(const llvm::opt::ArgList &Args) const
void ConstructJob(Compilation &C, const JobAction &JA, const InputInfo &Output, const InputInfoList &Inputs, const llvm::opt::ArgList &TCArgs, const char *LinkingOutput) const override
ConstructJob - Construct jobs to perform the action JA, writing to Output and with Inputs,...
void AddRunTimeLibs(const ToolChain &TC, const Driver &D, llvm::opt::ArgStringList &CmdArgs, const llvm::opt::ArgList &Args)
std::tuple< llvm::Reloc::Model, unsigned, bool > ParsePICArgs(const ToolChain &ToolChain, const llvm::opt::ArgList &Args)
void AddLinkerInputs(const ToolChain &TC, const InputInfoList &Inputs, const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs, const JobAction &JA)
SmallVector< InputInfo, 4 > InputInfoList
Definition Driver.h:50
bool LE(InterpState &S, CodePtr OpPC)
Definition Interp.h:1513
The JSON file list parser is used to communicate input to InstallAPI.
bool(*)(llvm::ArrayRef< const char * >, llvm::raw_ostream &, llvm::raw_ostream &, bool, bool) Driver
Definition Wasm.cpp:36
static constexpr ResponseFileSupport AtFileCurCP()
Definition Job.h:92
int Major
The parsed major, minor, and patch numbers.
Definition Gnu.h:168
std::string Text
The unparsed text of the version.
Definition Gnu.h:165
static GCCVersion Parse(StringRef VersionText)
Parse a GCCVersion object out of a string of text.
Definition Gnu.cpp:1991