1 //===--- WebAssembly.cpp - WebAssembly ToolChain Implementation -*- C++ -*-===//
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
7 //===----------------------------------------------------------------------===//
9 #include "WebAssembly.h"
10 #include "CommonArgs.h"
12 #include "clang/Basic/Version.h"
13 #include "clang/Config/config.h"
14 #include "clang/Driver/Compilation.h"
15 #include "clang/Driver/Driver.h"
16 #include "clang/Driver/DriverDiagnostic.h"
17 #include "clang/Driver/Options.h"
18 #include "llvm/Option/ArgList.h"
19 #include "llvm/Support/FileSystem.h"
20 #include "llvm/Support/Path.h"
21 #include "llvm/Support/VirtualFileSystem.h"
23 using namespace clang::driver;
24 using namespace clang::driver::tools;
25 using namespace clang::driver::toolchains;
26 using namespace clang;
27 using namespace llvm::opt;
29 /// Following the conventions in https://wiki.debian.org/Multiarch/Tuples,
30 /// we remove the vendor field to form the multiarch triple.
31 std::string WebAssembly::getMultiarchTriple(const Driver &D,
32 const llvm::Triple &TargetTriple,
33 StringRef SysRoot) const {
34 return (TargetTriple.getArchName() + "-" +
35 TargetTriple.getOSAndEnvironmentName()).str();
38 std::string wasm::Linker::getLinkerPath(const ArgList &Args) const {
39 const ToolChain &ToolChain = getToolChain();
40 if (const Arg* A = Args.getLastArg(options::OPT_fuse_ld_EQ)) {
41 StringRef UseLinker = A->getValue();
42 if (!UseLinker.empty()) {
43 if (llvm::sys::path::is_absolute(UseLinker) &&
44 llvm::sys::fs::can_execute(UseLinker))
45 return std::string(UseLinker);
47 // Accept 'lld', and 'ld' as aliases for the default linker
48 if (UseLinker != "lld" && UseLinker != "ld")
49 ToolChain.getDriver().Diag(diag::err_drv_invalid_linker_name)
50 << A->getAsString(Args);
54 return ToolChain.GetProgramPath(ToolChain.getDefaultLinker());
57 void wasm::Linker::ConstructJob(Compilation &C, const JobAction &JA,
58 const InputInfo &Output,
59 const InputInfoList &Inputs,
61 const char *LinkingOutput) const {
63 const ToolChain &ToolChain = getToolChain();
64 const char *Linker = Args.MakeArgString(getLinkerPath(Args));
65 ArgStringList CmdArgs;
67 CmdArgs.push_back("-m");
68 if (ToolChain.getTriple().isArch64Bit())
69 CmdArgs.push_back("wasm64");
71 CmdArgs.push_back("wasm32");
73 if (Args.hasArg(options::OPT_s))
74 CmdArgs.push_back("--strip-all");
76 Args.AddAllArgs(CmdArgs, options::OPT_L);
77 Args.AddAllArgs(CmdArgs, options::OPT_u);
78 ToolChain.AddFilePathLibArgs(Args, CmdArgs);
80 bool IsCommand = true;
82 const char *Entry = nullptr;
84 // When -shared is specified, use the reactor exec model unless
85 // specified otherwise.
86 if (Args.hasArg(options::OPT_shared))
89 if (const Arg *A = Args.getLastArg(options::OPT_mexec_model_EQ)) {
90 StringRef CM = A->getValue();
91 if (CM == "command") {
93 } else if (CM == "reactor") {
96 ToolChain.getDriver().Diag(diag::err_drv_invalid_argument_to_option)
97 << CM << A->getOption().getName();
102 // If crt1-command.o exists, it supports new-style commands, so use it.
103 // Otherwise, use the old crt1.o. This is a temporary transition measure.
104 // Once WASI libc no longer needs to support LLVM versions which lack
105 // support for new-style command, it can make crt1.o the same as
106 // crt1-command.o. And once LLVM no longer needs to support WASI libc
107 // versions before that, it can switch to using crt1-command.o.
109 if (ToolChain.GetFilePath("crt1-command.o") != "crt1-command.o")
110 Crt1 = "crt1-command.o";
112 Crt1 = "crt1-reactor.o";
113 Entry = "_initialize";
116 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles))
117 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(Crt1)));
119 CmdArgs.push_back(Args.MakeArgString("--entry"));
120 CmdArgs.push_back(Args.MakeArgString(Entry));
123 if (Args.hasArg(options::OPT_shared))
124 CmdArgs.push_back(Args.MakeArgString("-shared"));
126 AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs, JA);
128 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
129 if (ToolChain.ShouldLinkCXXStdlib(Args))
130 ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
132 if (Args.hasArg(options::OPT_pthread)) {
133 CmdArgs.push_back("-lpthread");
134 CmdArgs.push_back("--shared-memory");
137 CmdArgs.push_back("-lc");
138 AddRunTimeLibs(ToolChain, ToolChain.getDriver(), CmdArgs, Args);
141 CmdArgs.push_back("-o");
142 CmdArgs.push_back(Output.getFilename());
144 C.addCommand(std::make_unique<Command>(JA, *this,
145 ResponseFileSupport::AtFileCurCP(),
146 Linker, CmdArgs, Inputs, Output));
148 // When optimizing, if wasm-opt is available, run it.
149 if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
150 auto WasmOptPath = ToolChain.GetProgramPath("wasm-opt");
151 if (WasmOptPath != "wasm-opt") {
152 StringRef OOpt = "s";
153 if (A->getOption().matches(options::OPT_O4) ||
154 A->getOption().matches(options::OPT_Ofast))
156 else if (A->getOption().matches(options::OPT_O0))
158 else if (A->getOption().matches(options::OPT_O))
159 OOpt = A->getValue();
162 const char *WasmOpt = Args.MakeArgString(WasmOptPath);
163 ArgStringList CmdArgs;
164 CmdArgs.push_back(Output.getFilename());
165 CmdArgs.push_back(Args.MakeArgString(llvm::Twine("-O") + OOpt));
166 CmdArgs.push_back("-o");
167 CmdArgs.push_back(Output.getFilename());
168 C.addCommand(std::make_unique<Command>(
169 JA, *this, ResponseFileSupport::AtFileCurCP(), WasmOpt, CmdArgs,
176 /// Given a base library directory, append path components to form the
178 static std::string AppendLTOLibDir(const std::string &Dir) {
179 // The version allows the path to be keyed to the specific version of
180 // LLVM in used, as the bitcode format is not stable.
181 return Dir + "/llvm-lto/" LLVM_VERSION_STRING;
184 WebAssembly::WebAssembly(const Driver &D, const llvm::Triple &Triple,
185 const llvm::opt::ArgList &Args)
186 : ToolChain(D, Triple, Args) {
188 assert(Triple.isArch32Bit() != Triple.isArch64Bit());
190 getProgramPaths().push_back(getDriver().getInstalledDir());
192 auto SysRoot = getDriver().SysRoot;
193 if (getTriple().getOS() == llvm::Triple::UnknownOS) {
194 // Theoretically an "unknown" OS should mean no standard libraries, however
195 // it could also mean that a custom set of libraries is in use, so just add
196 // /lib to the search path. Disable multiarch in this case, to discourage
197 // paths containing "unknown" from acquiring meanings.
198 getFilePaths().push_back(SysRoot + "/lib");
200 const std::string MultiarchTriple =
201 getMultiarchTriple(getDriver(), Triple, SysRoot);
202 if (D.isUsingLTO()) {
203 // For LTO, enable use of lto-enabled sysroot libraries too, if available.
204 // Note that the directory is keyed to the LLVM revision, as LLVM's
205 // bitcode format is not stable.
206 auto Dir = AppendLTOLibDir(SysRoot + "/lib/" + MultiarchTriple);
207 getFilePaths().push_back(Dir);
209 getFilePaths().push_back(SysRoot + "/lib/" + MultiarchTriple);
213 bool WebAssembly::IsMathErrnoDefault() const { return false; }
215 bool WebAssembly::IsObjCNonFragileABIDefault() const { return true; }
217 bool WebAssembly::UseObjCMixedDispatch() const { return true; }
219 bool WebAssembly::isPICDefault() const { return false; }
221 bool WebAssembly::isPIEDefault(const llvm::opt::ArgList &Args) const {
225 bool WebAssembly::isPICDefaultForced() const { return false; }
227 bool WebAssembly::hasBlocksRuntime() const { return false; }
229 // TODO: Support profiling.
230 bool WebAssembly::SupportsProfiling() const { return false; }
232 bool WebAssembly::HasNativeLLVMSupport() const { return true; }
234 void WebAssembly::addClangTargetOptions(const ArgList &DriverArgs,
235 ArgStringList &CC1Args,
236 Action::OffloadKind) const {
237 if (!DriverArgs.hasFlag(clang::driver::options::OPT_fuse_init_array,
238 options::OPT_fno_use_init_array, true))
239 CC1Args.push_back("-fno-use-init-array");
241 // '-pthread' implies atomics, bulk-memory, mutable-globals, and sign-ext
242 if (DriverArgs.hasFlag(options::OPT_pthread, options::OPT_no_pthread,
244 if (DriverArgs.hasFlag(options::OPT_mno_atomics, options::OPT_matomics,
246 getDriver().Diag(diag::err_drv_argument_not_allowed_with)
249 if (DriverArgs.hasFlag(options::OPT_mno_bulk_memory,
250 options::OPT_mbulk_memory, false))
251 getDriver().Diag(diag::err_drv_argument_not_allowed_with)
253 << "-mno-bulk-memory";
254 if (DriverArgs.hasFlag(options::OPT_mno_mutable_globals,
255 options::OPT_mmutable_globals, false))
256 getDriver().Diag(diag::err_drv_argument_not_allowed_with)
258 << "-mno-mutable-globals";
259 if (DriverArgs.hasFlag(options::OPT_mno_sign_ext, options::OPT_msign_ext,
261 getDriver().Diag(diag::err_drv_argument_not_allowed_with)
264 CC1Args.push_back("-target-feature");
265 CC1Args.push_back("+atomics");
266 CC1Args.push_back("-target-feature");
267 CC1Args.push_back("+bulk-memory");
268 CC1Args.push_back("-target-feature");
269 CC1Args.push_back("+mutable-globals");
270 CC1Args.push_back("-target-feature");
271 CC1Args.push_back("+sign-ext");
274 if (!DriverArgs.hasFlag(options::OPT_mmutable_globals,
275 options::OPT_mno_mutable_globals, false)) {
276 // -fPIC implies +mutable-globals because the PIC ABI used by the linker
277 // depends on importing and exporting mutable globals.
278 llvm::Reloc::Model RelocationModel;
281 std::tie(RelocationModel, PICLevel, IsPIE) =
282 ParsePICArgs(*this, DriverArgs);
283 if (RelocationModel == llvm::Reloc::PIC_) {
284 if (DriverArgs.hasFlag(options::OPT_mno_mutable_globals,
285 options::OPT_mmutable_globals, false)) {
286 getDriver().Diag(diag::err_drv_argument_not_allowed_with)
288 << "-mno-mutable-globals";
290 CC1Args.push_back("-target-feature");
291 CC1Args.push_back("+mutable-globals");
295 if (DriverArgs.getLastArg(options::OPT_fwasm_exceptions)) {
296 // '-fwasm-exceptions' is not compatible with '-mno-exception-handling'
297 if (DriverArgs.hasFlag(options::OPT_mno_exception_handing,
298 options::OPT_mexception_handing, false))
299 getDriver().Diag(diag::err_drv_argument_not_allowed_with)
300 << "-fwasm-exceptions"
301 << "-mno-exception-handling";
302 // '-fwasm-exceptions' is not compatible with
303 // '-mllvm -enable-emscripten-cxx-exceptions'
304 for (const Arg *A : DriverArgs.filtered(options::OPT_mllvm)) {
305 if (StringRef(A->getValue(0)) == "-enable-emscripten-cxx-exceptions")
306 getDriver().Diag(diag::err_drv_argument_not_allowed_with)
307 << "-fwasm-exceptions"
308 << "-mllvm -enable-emscripten-cxx-exceptions";
310 // '-fwasm-exceptions' implies exception-handling feature
311 CC1Args.push_back("-target-feature");
312 CC1Args.push_back("+exception-handling");
313 // Backend needs -wasm-enable-eh to enable Wasm EH
314 CC1Args.push_back("-mllvm");
315 CC1Args.push_back("-wasm-enable-eh");
318 for (const Arg *A : DriverArgs.filtered(options::OPT_mllvm)) {
319 StringRef Opt = A->getValue(0);
320 if (Opt.startswith("-emscripten-cxx-exceptions-allowed")) {
321 // '-mllvm -emscripten-cxx-exceptions-allowed' should be used with
322 // '-mllvm -enable-emscripten-cxx-exceptions'
323 bool EmEHArgExists = false;
324 for (const Arg *A : DriverArgs.filtered(options::OPT_mllvm)) {
325 if (StringRef(A->getValue(0)) == "-enable-emscripten-cxx-exceptions") {
326 EmEHArgExists = true;
331 getDriver().Diag(diag::err_drv_argument_only_allowed_with)
332 << "-mllvm -emscripten-cxx-exceptions-allowed"
333 << "-mllvm -enable-emscripten-cxx-exceptions";
335 // Prevent functions specified in -emscripten-cxx-exceptions-allowed list
336 // from being inlined before reaching the wasm backend.
337 StringRef FuncNamesStr = Opt.split('=').second;
338 SmallVector<StringRef, 4> FuncNames;
339 FuncNamesStr.split(FuncNames, ',');
340 for (auto Name : FuncNames) {
341 CC1Args.push_back("-mllvm");
342 CC1Args.push_back(DriverArgs.MakeArgString("--force-attribute=" + Name +
347 if (Opt.startswith("-wasm-enable-sjlj")) {
348 // '-mllvm -wasm-enable-sjlj' is not compatible with
349 // '-mno-exception-handling'
350 if (DriverArgs.hasFlag(options::OPT_mno_exception_handing,
351 options::OPT_mexception_handing, false))
352 getDriver().Diag(diag::err_drv_argument_not_allowed_with)
353 << "-mllvm -wasm-enable-sjlj"
354 << "-mno-exception-handling";
355 // '-mllvm -wasm-enable-sjlj' is not compatible with
356 // '-mllvm -enable-emscripten-cxx-exceptions'
357 // because we don't allow Emscripten EH + Wasm SjLj
358 for (const Arg *A : DriverArgs.filtered(options::OPT_mllvm)) {
359 if (StringRef(A->getValue(0)) == "-enable-emscripten-cxx-exceptions")
360 getDriver().Diag(diag::err_drv_argument_not_allowed_with)
361 << "-mllvm -wasm-enable-sjlj"
362 << "-mllvm -enable-emscripten-cxx-exceptions";
364 // '-mllvm -wasm-enable-sjlj' is not compatible with
365 // '-mllvm -enable-emscripten-sjlj'
366 for (const Arg *A : DriverArgs.filtered(options::OPT_mllvm)) {
367 if (StringRef(A->getValue(0)) == "-enable-emscripten-sjlj")
368 getDriver().Diag(diag::err_drv_argument_not_allowed_with)
369 << "-mllvm -wasm-enable-sjlj"
370 << "-mllvm -enable-emscripten-sjlj";
372 // '-mllvm -wasm-enable-sjlj' implies exception-handling feature
373 CC1Args.push_back("-target-feature");
374 CC1Args.push_back("+exception-handling");
375 // Backend needs '-exception-model=wasm' to use Wasm EH instructions
376 CC1Args.push_back("-exception-model=wasm");
381 ToolChain::RuntimeLibType WebAssembly::GetDefaultRuntimeLibType() const {
382 return ToolChain::RLT_CompilerRT;
385 ToolChain::CXXStdlibType
386 WebAssembly::GetCXXStdlibType(const ArgList &Args) const {
387 if (Arg *A = Args.getLastArg(options::OPT_stdlib_EQ)) {
388 StringRef Value = A->getValue();
389 if (Value == "libc++")
390 return ToolChain::CST_Libcxx;
391 else if (Value == "libstdc++")
392 return ToolChain::CST_Libstdcxx;
394 getDriver().Diag(diag::err_drv_invalid_stdlib_name)
395 << A->getAsString(Args);
397 return ToolChain::CST_Libcxx;
400 void WebAssembly::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
401 ArgStringList &CC1Args) const {
402 if (DriverArgs.hasArg(clang::driver::options::OPT_nostdinc))
405 const Driver &D = getDriver();
407 if (!DriverArgs.hasArg(options::OPT_nobuiltininc)) {
408 SmallString<128> P(D.ResourceDir);
409 llvm::sys::path::append(P, "include");
410 addSystemInclude(DriverArgs, CC1Args, P);
413 if (DriverArgs.hasArg(options::OPT_nostdlibinc))
416 // Check for configure-time C include directories.
417 StringRef CIncludeDirs(C_INCLUDE_DIRS);
418 if (CIncludeDirs != "") {
419 SmallVector<StringRef, 5> dirs;
420 CIncludeDirs.split(dirs, ":");
421 for (StringRef dir : dirs) {
423 llvm::sys::path::is_absolute(dir) ? "" : StringRef(D.SysRoot);
424 addExternCSystemInclude(DriverArgs, CC1Args, Prefix + dir);
429 if (getTriple().getOS() != llvm::Triple::UnknownOS) {
430 const std::string MultiarchTriple =
431 getMultiarchTriple(D, getTriple(), D.SysRoot);
432 addSystemInclude(DriverArgs, CC1Args, D.SysRoot + "/include/" + MultiarchTriple);
434 addSystemInclude(DriverArgs, CC1Args, D.SysRoot + "/include");
437 void WebAssembly::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
438 ArgStringList &CC1Args) const {
440 if (DriverArgs.hasArg(options::OPT_nostdlibinc, options::OPT_nostdinc,
441 options::OPT_nostdincxx))
444 switch (GetCXXStdlibType(DriverArgs)) {
445 case ToolChain::CST_Libcxx:
446 addLibCxxIncludePaths(DriverArgs, CC1Args);
448 case ToolChain::CST_Libstdcxx:
449 addLibStdCXXIncludePaths(DriverArgs, CC1Args);
454 void WebAssembly::AddCXXStdlibLibArgs(const llvm::opt::ArgList &Args,
455 llvm::opt::ArgStringList &CmdArgs) const {
457 switch (GetCXXStdlibType(Args)) {
458 case ToolChain::CST_Libcxx:
459 CmdArgs.push_back("-lc++");
460 if (Args.hasArg(options::OPT_fexperimental_library))
461 CmdArgs.push_back("-lc++experimental");
462 CmdArgs.push_back("-lc++abi");
464 case ToolChain::CST_Libstdcxx:
465 CmdArgs.push_back("-lstdc++");
470 SanitizerMask WebAssembly::getSupportedSanitizers() const {
471 SanitizerMask Res = ToolChain::getSupportedSanitizers();
472 if (getTriple().isOSEmscripten()) {
473 Res |= SanitizerKind::Vptr | SanitizerKind::Leak | SanitizerKind::Address;
475 // -fsanitize=function places two words before the function label, which are
477 Res &= ~SanitizerKind::Function;
481 Tool *WebAssembly::buildLinker() const {
482 return new tools::wasm::Linker(*this);
485 void WebAssembly::addLibCxxIncludePaths(
486 const llvm::opt::ArgList &DriverArgs,
487 llvm::opt::ArgStringList &CC1Args) const {
488 const Driver &D = getDriver();
489 std::string SysRoot = computeSysRoot();
490 std::string LibPath = SysRoot + "/include";
491 const std::string MultiarchTriple =
492 getMultiarchTriple(D, getTriple(), SysRoot);
493 bool IsKnownOs = (getTriple().getOS() != llvm::Triple::UnknownOS);
495 std::string Version = detectLibcxxVersion(LibPath);
499 // First add the per-target include path if the OS is known.
501 std::string TargetDir = LibPath + "/" + MultiarchTriple + "/c++/" + Version;
502 addSystemInclude(DriverArgs, CC1Args, TargetDir);
505 // Second add the generic one.
506 addSystemInclude(DriverArgs, CC1Args, LibPath + "/c++/" + Version);
509 void WebAssembly::addLibStdCXXIncludePaths(
510 const llvm::opt::ArgList &DriverArgs,
511 llvm::opt::ArgStringList &CC1Args) const {
512 // We cannot use GCCInstallationDetector here as the sysroot usually does
513 // not contain a full GCC installation.
514 // Instead, we search the given sysroot for /usr/include/xx, similar
515 // to how we do it for libc++.
516 const Driver &D = getDriver();
517 std::string SysRoot = computeSysRoot();
518 std::string LibPath = SysRoot + "/include";
519 const std::string MultiarchTriple =
520 getMultiarchTriple(D, getTriple(), SysRoot);
521 bool IsKnownOs = (getTriple().getOS() != llvm::Triple::UnknownOS);
523 // This is similar to detectLibcxxVersion()
527 Generic_GCC::GCCVersion MaxVersion =
528 Generic_GCC::GCCVersion::Parse("0.0.0");
529 SmallString<128> Path(LibPath);
530 llvm::sys::path::append(Path, "c++");
531 for (llvm::vfs::directory_iterator LI = getVFS().dir_begin(Path, EC), LE;
532 !EC && LI != LE; LI = LI.increment(EC)) {
533 StringRef VersionText = llvm::sys::path::filename(LI->path());
534 if (VersionText[0] != 'v') {
535 auto Version = Generic_GCC::GCCVersion::Parse(VersionText);
536 if (Version > MaxVersion)
537 MaxVersion = Version;
540 if (MaxVersion.Major > 0)
541 Version = MaxVersion.Text;
547 // First add the per-target include path if the OS is known.
549 std::string TargetDir = LibPath + "/c++/" + Version + "/" + MultiarchTriple;
550 addSystemInclude(DriverArgs, CC1Args, TargetDir);
553 // Second add the generic one.
554 addSystemInclude(DriverArgs, CC1Args, LibPath + "/c++/" + Version);
555 // Third the backward one.
556 addSystemInclude(DriverArgs, CC1Args, LibPath + "/c++/" + Version + "/backward");