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