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