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"
12#include "clang/Driver/CommonArgs.h"
13#include "clang/Driver/Compilation.h"
14#include "clang/Driver/Driver.h"
15#include "clang/Options/Options.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(Ids: options::OPT_fwasm_exceptions))
42 return "eh";
43 return "noeh";
44}
45
46std::string wasm::Linker::getLinkerPath(const ArgList &Args) const {
47 const ToolChain &ToolChain = getToolChain();
48 if (const Arg* A = Args.getLastArg(Ids: options::OPT_fuse_ld_EQ)) {
49 StringRef UseLinker = A->getValue();
50 if (!UseLinker.empty()) {
51 if (llvm::sys::path::is_absolute(path: UseLinker) &&
52 llvm::sys::fs::can_execute(Path: 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(Name: "wasm-ld");
60 }
61
62 // Allow 'ld' as an alias for the default linker
63 if (UseLinker != "ld")
64 ToolChain.getDriver().Diag(DiagID: diag::err_drv_invalid_linker_name)
65 << A->getAsString(Args);
66 }
67 }
68
69 return ToolChain.GetProgramPath(Name: ToolChain.getDefaultLinker());
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(Ids: 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
104void wasm::Linker::ConstructJob(Compilation &C, const JobAction &JA,
105 const InputInfo &Output,
106 const InputInfoList &Inputs,
107 const ArgList &Args,
108 const char *LinkingOutput) const {
109
110 const ToolChain &ToolChain = getToolChain();
111 const char *Linker = Args.MakeArgString(Str: getLinkerPath(Args));
112 ArgStringList CmdArgs;
113
114 CmdArgs.push_back(Elt: "-m");
115 if (ToolChain.getTriple().isArch64Bit())
116 CmdArgs.push_back(Elt: "wasm64");
117 else
118 CmdArgs.push_back(Elt: "wasm32");
119
120 if (Args.hasArg(Ids: options::OPT_s))
121 CmdArgs.push_back(Elt: "--strip-all");
122
123 if (Args.hasArg(Ids: options::OPT_Z_Xlinker__no_demangle))
124 CmdArgs.push_back(Elt: "--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(path: Linker).ends_with_insensitive(
131 Suffix: "wasm-component-ld")) {
132 CmdArgs.push_back(Elt: "--wasm-ld-path");
133 CmdArgs.push_back(Elt: Args.MakeArgString(Str: ToolChain.GetProgramPath(Name: "wasm-ld")));
134 }
135
136 Args.addAllArgs(Output&: CmdArgs, Ids: {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(Ids: options::OPT_shared))
147 IsCommand = false;
148
149 if (const Arg *A = Args.getLastArg(Ids: 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(DiagID: 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(Name: "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(Ids: options::OPT_nostdlib, Ids: options::OPT_nostartfiles))
177 CmdArgs.push_back(Elt: Args.MakeArgString(Str: ToolChain.GetFilePath(Name: Crt1)));
178 if (Entry) {
179 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "--entry"));
180 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Entry));
181 }
182
183 if (Args.hasArg(Ids: options::OPT_shared))
184 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-shared"));
185
186 AddLinkerInputs(TC: ToolChain, Inputs, Args, CmdArgs, JA);
187
188 if (WantsCooperativeMultithreading(Triple: ToolChain.getTriple(), Args))
189 CmdArgs.push_back(Elt: "--cooperative-threading");
190
191 if (WantsSharedMemory(Triple: ToolChain.getTriple(), Args))
192 CmdArgs.push_back(Elt: "--shared-memory");
193
194 if (!Args.hasArg(Ids: options::OPT_nostdlib, Ids: options::OPT_nodefaultlibs)) {
195 if (ToolChain.ShouldLinkCXXStdlib(Args))
196 ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
197
198 if (WantsPthread(Triple: ToolChain.getTriple(), Args))
199 CmdArgs.push_back(Elt: "-lpthread");
200
201 CmdArgs.push_back(Elt: "-lc");
202 AddRunTimeLibs(TC: ToolChain, D: ToolChain.getDriver(), CmdArgs, Args);
203 }
204
205 ToolChain.addProfileRTLibs(Args, CmdArgs);
206
207 CmdArgs.push_back(Elt: "-o");
208 CmdArgs.push_back(Elt: 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(TargetTriple: ToolChain.getTriple());
214 bool RunWasmOpt = Args.hasFlag(Pos: options::OPT_wasm_opt,
215 Neg: options::OPT_no_wasm_opt, Default: 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(Ids: options::OPT_O_Group)) {
221 WasmOptPath = ToolChain.GetProgramPath(Name: "wasm-opt");
222 if (WasmOptPath == "wasm-opt") {
223 WasmOptPath = {};
224 }
225 }
226
227 if (!WasmOptPath.empty()) {
228 CmdArgs.push_back(Elt: "--keep-section=target_features");
229 }
230
231 C.addCommand(Cmd: std::make_unique<Command>(args: JA, args: *this,
232 args: ResponseFileSupport::AtFileCurCP(),
233 args&: Linker, args&: CmdArgs, args: Inputs, args: Output));
234
235 if (Arg *A = Args.getLastArg(Ids: options::OPT_O_Group)) {
236 if (!WasmOptPath.empty()) {
237 StringRef OOpt = "s";
238 if (A->getOption().matches(ID: options::OPT_O4) ||
239 A->getOption().matches(ID: options::OPT_Ofast))
240 OOpt = "4";
241 else if (A->getOption().matches(ID: options::OPT_O0))
242 OOpt = "0";
243 else if (A->getOption().matches(ID: options::OPT_O))
244 OOpt = A->getValue();
245
246 if (OOpt != "0") {
247 const char *WasmOpt = Args.MakeArgString(Str: WasmOptPath);
248 ArgStringList OptArgs;
249 OptArgs.push_back(Elt: Output.getFilename());
250 OptArgs.push_back(Elt: Args.MakeArgString(Str: llvm::Twine("-O") + OOpt));
251 OptArgs.push_back(Elt: "-o");
252 OptArgs.push_back(Elt: Output.getFilename());
253 C.addCommand(Cmd: std::make_unique<Command>(
254 args: JA, args: *this, args: ResponseFileSupport::AtFileCurCP(), args&: WasmOpt, args&: OptArgs,
255 args: Inputs, args: Output));
256 }
257 }
258 }
259}
260
261/// Append `Dir` to `Paths`, but also include the LTO directories before that if
262/// LTO is enabled.
263static void AppendLibDirAndLTODir(ToolChain::path_list &Paths,
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(Elt: Dir + "/llvm-lto/" LLVM_VERSION_STRING);
271 }
272 Paths.push_back(Elt: 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(Elt: 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(Elt: SysRoot + "/lib");
290 } else {
291 const std::string MultiarchTriple =
292 getMultiarchTriple(D: getDriver(), TargetTriple: 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(Paths&: getFilePaths(), TC: *this, Args,
300 Dir: TripleLibDir + "/" + GetCXXExceptionsDir(DriverArgs: Args));
301 AppendLibDirAndLTODir(Paths&: getFilePaths(), TC: *this, Args, Dir: TripleLibDir);
302 }
303
304 if (getTriple().getOS() == llvm::Triple::WASI) {
305 D.Diag(DiagID: diag::warn_drv_deprecated_custom)
306 << "--target=wasm32-wasi"
307 << "use --target=wasm32-wasip1 instead";
308 }
309}
310
311const char *WebAssembly::getDefaultLinker() const {
312 if (TargetBuildsComponents(TargetTriple: getTriple()))
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(Pos: options::OPT_fuse_init_array,
342 Neg: options::OPT_fno_use_init_array, Default: true))
343 CC1Args.push_back(Elt: "-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(Triple: getTriple(), Args: DriverArgs)) {
349 if (!WantsCooperativeMultithreading(Triple: getTriple(), Args: DriverArgs) &&
350 DriverArgs.hasFlag(Pos: options::OPT_mno_atomics, Neg: options::OPT_matomics,
351 Default: false))
352 getDriver().Diag(DiagID: diag::err_drv_argument_not_allowed_with)
353 << "-pthread"
354 << "-mno-atomics";
355 if (DriverArgs.hasFlag(Pos: options::OPT_mno_bulk_memory,
356 Neg: options::OPT_mbulk_memory, Default: false))
357 getDriver().Diag(DiagID: diag::err_drv_argument_not_allowed_with)
358 << "-pthread"
359 << "-mno-bulk-memory";
360 if (DriverArgs.hasFlag(Pos: options::OPT_mno_mutable_globals,
361 Neg: options::OPT_mmutable_globals, Default: false))
362 getDriver().Diag(DiagID: diag::err_drv_argument_not_allowed_with)
363 << "-pthread"
364 << "-mno-mutable-globals";
365 if (DriverArgs.hasFlag(Pos: options::OPT_mno_sign_ext, Neg: options::OPT_msign_ext,
366 Default: false))
367 getDriver().Diag(DiagID: diag::err_drv_argument_not_allowed_with)
368 << "-pthread"
369 << "-mno-sign-ext";
370 if (!WantsCooperativeMultithreading(Triple: getTriple(), Args: DriverArgs)) {
371 CC1Args.push_back(Elt: "-target-feature");
372 CC1Args.push_back(Elt: "+atomics");
373 }
374 CC1Args.push_back(Elt: "-target-feature");
375 CC1Args.push_back(Elt: "+bulk-memory");
376 CC1Args.push_back(Elt: "-target-feature");
377 CC1Args.push_back(Elt: "+mutable-globals");
378 CC1Args.push_back(Elt: "-target-feature");
379 CC1Args.push_back(Elt: "+sign-ext");
380 }
381
382 if (!DriverArgs.hasFlag(Pos: options::OPT_mmutable_globals,
383 Neg: options::OPT_mno_mutable_globals, Default: 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(args&: RelocationModel, args&: PICLevel, args&: IsPIE) =
390 ParsePICArgs(ToolChain: *this, Args: DriverArgs);
391 if (RelocationModel == llvm::Reloc::PIC_) {
392 if (DriverArgs.hasFlag(Pos: options::OPT_mno_mutable_globals,
393 Neg: options::OPT_mmutable_globals, Default: false)) {
394 getDriver().Diag(DiagID: diag::err_drv_argument_not_allowed_with)
395 << "-fPIC"
396 << "-mno-mutable-globals";
397 }
398 CC1Args.push_back(Elt: "-target-feature");
399 CC1Args.push_back(Elt: "+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(Pos: options::OPT_mno_exception_handing,
413 Neg: options::OPT_mexception_handing, Default: false))
414 getDriver().Diag(DiagID: 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(Pos: options::OPT_mno_multivalue,
418 Neg: options::OPT_mmultivalue, Default: false))
419 getDriver().Diag(DiagID: diag::err_drv_argument_not_allowed_with)
420 << CurOption << "-mno-multivalue";
421 if (DriverArgs.hasFlag(Pos: options::OPT_mno_reference_types,
422 Neg: options::OPT_mreference_types, Default: false))
423 getDriver().Diag(DiagID: diag::err_drv_argument_not_allowed_with)
424 << CurOption << "-mno-reference-types";
425
426 for (const Arg *A : DriverArgs.filtered(Ids: 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(N: 0)) == Option)
431 getDriver().Diag(DiagID: 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(Elt: "-target-feature");
443 CC1Args.push_back(Elt: "+exception-handling");
444 // The standardized Wasm EH spec requires multivalue and reference-types.
445 CC1Args.push_back(Elt: "-target-feature");
446 CC1Args.push_back(Elt: "+multivalue");
447 CC1Args.push_back(Elt: "-target-feature");
448 CC1Args.push_back(Elt: "+reference-types");
449 // Backend needs '-exception-model=wasm' to use Wasm EH instructions
450 CC1Args.push_back(Elt: "-exception-model=wasm");
451 };
452
453 if (DriverArgs.getLastArg(Ids: options::OPT_fwasm_exceptions)) {
454 BanIncompatibleOptionsForWasmEHSjLj("-fwasm-exceptions");
455 EnableFeaturesForWasmEHSjLj();
456 // Backend needs -wasm-enable-eh to enable Wasm EH
457 CC1Args.push_back(Elt: "-mllvm");
458 CC1Args.push_back(Elt: "-wasm-enable-eh");
459 }
460
461 for (const Arg *A : DriverArgs.filtered(Ids: options::OPT_mllvm)) {
462 StringRef Opt = A->getValue(N: 0);
463 if (Opt.starts_with(Prefix: "-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(Ids: options::OPT_mllvm)) {
468 if (StringRef(A->getValue(N: 0)) == "-enable-emscripten-cxx-exceptions") {
469 EmEHArgExists = true;
470 break;
471 }
472 }
473 if (!EmEHArgExists)
474 getDriver().Diag(DiagID: 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(Separator: '=').second;
481 SmallVector<StringRef, 4> FuncNames;
482 FuncNamesStr.split(A&: FuncNames, Separator: ',');
483 for (auto Name : FuncNames) {
484 CC1Args.push_back(Elt: "-mllvm");
485 CC1Args.push_back(Elt: DriverArgs.MakeArgString(Str: "--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(Prefix: Option)) {
493 BanIncompatibleOptionsForWasmEHSjLj(Option);
494 EnableFeaturesForWasmEHSjLj();
495 }
496 }
497 }
498}
499
500ToolChain::RuntimeLibType WebAssembly::GetDefaultRuntimeLibType() const {
501 return ToolChain::RLT_CompilerRT;
502}
503
504ToolChain::CXXStdlibType
505WebAssembly::GetCXXStdlibType(const ArgList &Args) const {
506 if (Arg *A = Args.getLastArg(Ids: options::OPT_stdlib_EQ)) {
507 StringRef Value = A->getValue();
508 if (Value == "libc++")
509 return ToolChain::CST_Libcxx;
510 else if (Value == "libstdc++")
511 return ToolChain::CST_Libstdcxx;
512 else
513 getDriver().Diag(DiagID: diag::err_drv_invalid_stdlib_name)
514 << A->getAsString(Args);
515 }
516 return ToolChain::CST_Libcxx;
517}
518
519void WebAssembly::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
520 ArgStringList &CC1Args) const {
521 if (DriverArgs.hasArg(Ids: options::OPT_nostdinc))
522 return;
523
524 const Driver &D = getDriver();
525
526 if (!DriverArgs.hasArg(Ids: options::OPT_nobuiltininc)) {
527 SmallString<128> P(D.ResourceDir);
528 llvm::sys::path::append(path&: P, a: "include");
529 addSystemInclude(DriverArgs, CC1Args, Path: P);
530 }
531
532 if (DriverArgs.hasArg(Ids: 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(A&: dirs, Separator: ":");
540 for (StringRef dir : dirs) {
541 StringRef Prefix =
542 llvm::sys::path::is_absolute(path: dir) ? "" : StringRef(D.SysRoot);
543 addExternCSystemInclude(DriverArgs, CC1Args, Path: Prefix + dir);
544 }
545 return;
546 }
547
548 if (getTriple().getOS() != llvm::Triple::UnknownOS) {
549 const std::string MultiarchTriple =
550 getMultiarchTriple(D, TargetTriple: getTriple(), SysRoot: D.SysRoot);
551 addSystemInclude(DriverArgs, CC1Args, Path: D.SysRoot + "/include/" + MultiarchTriple);
552 }
553 addSystemInclude(DriverArgs, CC1Args, Path: D.SysRoot + "/include");
554}
555
556void WebAssembly::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
557 ArgStringList &CC1Args) const {
558
559 if (DriverArgs.hasArg(Ids: options::OPT_nostdlibinc, Ids: options::OPT_nostdinc,
560 Ids: options::OPT_nostdincxx))
561 return;
562
563 switch (GetCXXStdlibType(Args: DriverArgs)) {
564 case ToolChain::CST_Libcxx:
565 addLibCxxIncludePaths(DriverArgs, CC1Args);
566 break;
567 case ToolChain::CST_Libstdcxx:
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)) {
577 case ToolChain::CST_Libcxx:
578 CmdArgs.push_back(Elt: "-lc++");
579 if (Args.hasArg(Ids: options::OPT_fexperimental_library))
580 CmdArgs.push_back(Elt: "-lc++experimental");
581 CmdArgs.push_back(Elt: "-lc++abi");
582 break;
583 case ToolChain::CST_Libstdcxx:
584 CmdArgs.push_back(Elt: "-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, TargetTriple: getTriple(), SysRoot);
618 bool IsKnownOs = (getTriple().getOS() != llvm::Triple::UnknownOS);
619
620 std::string Version = detectLibcxxVersion(IncludePath: 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 Path: TargetDir + "/" + GetCXXExceptionsDir(DriverArgs) +
631 Suffix);
632 addSystemInclude(DriverArgs, CC1Args, Path: TargetDir + Suffix);
633 }
634
635 // Third add the generic one.
636 addSystemInclude(DriverArgs, CC1Args, Path: 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, TargetTriple: 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 =
658 Generic_GCC::GCCVersion::Parse(VersionText: "0.0.0");
659 SmallString<128> Path(LibPath);
660 llvm::sys::path::append(path&: Path, a: "c++");
661 for (llvm::vfs::directory_iterator LI = getVFS().dir_begin(Dir: Path, EC), LE;
662 !EC && LI != LE; LI = LI.increment(EC)) {
663 StringRef VersionText = llvm::sys::path::filename(path: 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, Path: TargetDir);
681 }
682
683 // Second add the generic one.
684 addSystemInclude(DriverArgs, CC1Args, Path: LibPath + "/c++/" + Version);
685 // Third the backward one.
686 addSystemInclude(DriverArgs, CC1Args, Path: LibPath + "/c++/" + Version + "/backward");
687}
688