xref: /freebsd/contrib/llvm-project/llvm/lib/Target/WebAssembly/WebAssemblyTargetMachine.cpp (revision 349cc55c9796c4596a5b9904cd3281af295f878f)
10b57cec5SDimitry Andric //===- WebAssemblyTargetMachine.cpp - Define TargetMachine for WebAssembly -==//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric ///
90b57cec5SDimitry Andric /// \file
100b57cec5SDimitry Andric /// This file defines the WebAssembly-specific subclass of TargetMachine.
110b57cec5SDimitry Andric ///
120b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
130b57cec5SDimitry Andric 
140b57cec5SDimitry Andric #include "WebAssemblyTargetMachine.h"
150b57cec5SDimitry Andric #include "MCTargetDesc/WebAssemblyMCTargetDesc.h"
160b57cec5SDimitry Andric #include "TargetInfo/WebAssemblyTargetInfo.h"
170b57cec5SDimitry Andric #include "WebAssembly.h"
180b57cec5SDimitry Andric #include "WebAssemblyMachineFunctionInfo.h"
190b57cec5SDimitry Andric #include "WebAssemblyTargetObjectFile.h"
200b57cec5SDimitry Andric #include "WebAssemblyTargetTransformInfo.h"
210b57cec5SDimitry Andric #include "llvm/CodeGen/MIRParser/MIParser.h"
220b57cec5SDimitry Andric #include "llvm/CodeGen/MachineFunctionPass.h"
230b57cec5SDimitry Andric #include "llvm/CodeGen/Passes.h"
240b57cec5SDimitry Andric #include "llvm/CodeGen/RegAllocRegistry.h"
250b57cec5SDimitry Andric #include "llvm/CodeGen/TargetPassConfig.h"
260b57cec5SDimitry Andric #include "llvm/IR/Function.h"
27*349cc55cSDimitry Andric #include "llvm/MC/TargetRegistry.h"
280b57cec5SDimitry Andric #include "llvm/Target/TargetOptions.h"
290b57cec5SDimitry Andric #include "llvm/Transforms/Scalar.h"
300b57cec5SDimitry Andric #include "llvm/Transforms/Scalar/LowerAtomic.h"
310b57cec5SDimitry Andric #include "llvm/Transforms/Utils.h"
320b57cec5SDimitry Andric using namespace llvm;
330b57cec5SDimitry Andric 
340b57cec5SDimitry Andric #define DEBUG_TYPE "wasm"
350b57cec5SDimitry Andric 
360b57cec5SDimitry Andric // Emscripten's asm.js-style exception handling
37*349cc55cSDimitry Andric cl::opt<bool>
38*349cc55cSDimitry Andric     WasmEnableEmEH("enable-emscripten-cxx-exceptions",
390b57cec5SDimitry Andric                    cl::desc("WebAssembly Emscripten-style exception handling"),
400b57cec5SDimitry Andric                    cl::init(false));
410b57cec5SDimitry Andric 
420b57cec5SDimitry Andric // Emscripten's asm.js-style setjmp/longjmp handling
43*349cc55cSDimitry Andric cl::opt<bool> WasmEnableEmSjLj(
440b57cec5SDimitry Andric     "enable-emscripten-sjlj",
450b57cec5SDimitry Andric     cl::desc("WebAssembly Emscripten-style setjmp/longjmp handling"),
460b57cec5SDimitry Andric     cl::init(false));
470b57cec5SDimitry Andric 
48*349cc55cSDimitry Andric // Exception handling using wasm EH instructions
49*349cc55cSDimitry Andric cl::opt<bool> WasmEnableEH("wasm-enable-eh",
50*349cc55cSDimitry Andric                            cl::desc("WebAssembly exception handling"),
51*349cc55cSDimitry Andric                            cl::init(false));
52*349cc55cSDimitry Andric 
53*349cc55cSDimitry Andric // setjmp/longjmp handling using wasm EH instrutions
54*349cc55cSDimitry Andric cl::opt<bool> WasmEnableSjLj("wasm-enable-sjlj",
55*349cc55cSDimitry Andric                              cl::desc("WebAssembly setjmp/longjmp handling"),
56*349cc55cSDimitry Andric                              cl::init(false));
57*349cc55cSDimitry Andric 
585ffd83dbSDimitry Andric // A command-line option to keep implicit locals
595ffd83dbSDimitry Andric // for the purpose of testing with lit/llc ONLY.
605ffd83dbSDimitry Andric // This produces output which is not valid WebAssembly, and is not supported
615ffd83dbSDimitry Andric // by assemblers/disassemblers and other MC based tools.
625ffd83dbSDimitry Andric static cl::opt<bool> WasmDisableExplicitLocals(
635ffd83dbSDimitry Andric     "wasm-disable-explicit-locals", cl::Hidden,
645ffd83dbSDimitry Andric     cl::desc("WebAssembly: output implicit locals in"
655ffd83dbSDimitry Andric              " instruction output for test purposes only."),
665ffd83dbSDimitry Andric     cl::init(false));
675ffd83dbSDimitry Andric 
68480093f4SDimitry Andric extern "C" LLVM_EXTERNAL_VISIBILITY void LLVMInitializeWebAssemblyTarget() {
690b57cec5SDimitry Andric   // Register the target.
700b57cec5SDimitry Andric   RegisterTargetMachine<WebAssemblyTargetMachine> X(
710b57cec5SDimitry Andric       getTheWebAssemblyTarget32());
720b57cec5SDimitry Andric   RegisterTargetMachine<WebAssemblyTargetMachine> Y(
730b57cec5SDimitry Andric       getTheWebAssemblyTarget64());
740b57cec5SDimitry Andric 
750b57cec5SDimitry Andric   // Register backend passes
760b57cec5SDimitry Andric   auto &PR = *PassRegistry::getPassRegistry();
770b57cec5SDimitry Andric   initializeWebAssemblyAddMissingPrototypesPass(PR);
780b57cec5SDimitry Andric   initializeWebAssemblyLowerEmscriptenEHSjLjPass(PR);
790b57cec5SDimitry Andric   initializeLowerGlobalDtorsPass(PR);
800b57cec5SDimitry Andric   initializeFixFunctionBitcastsPass(PR);
810b57cec5SDimitry Andric   initializeOptimizeReturnedPass(PR);
820b57cec5SDimitry Andric   initializeWebAssemblyArgumentMovePass(PR);
830b57cec5SDimitry Andric   initializeWebAssemblySetP2AlignOperandsPass(PR);
840b57cec5SDimitry Andric   initializeWebAssemblyReplacePhysRegsPass(PR);
850b57cec5SDimitry Andric   initializeWebAssemblyPrepareForLiveIntervalsPass(PR);
860b57cec5SDimitry Andric   initializeWebAssemblyOptimizeLiveIntervalsPass(PR);
870b57cec5SDimitry Andric   initializeWebAssemblyMemIntrinsicResultsPass(PR);
880b57cec5SDimitry Andric   initializeWebAssemblyRegStackifyPass(PR);
890b57cec5SDimitry Andric   initializeWebAssemblyRegColoringPass(PR);
90fe6060f1SDimitry Andric   initializeWebAssemblyNullifyDebugValueListsPass(PR);
910b57cec5SDimitry Andric   initializeWebAssemblyFixIrreducibleControlFlowPass(PR);
920b57cec5SDimitry Andric   initializeWebAssemblyLateEHPreparePass(PR);
930b57cec5SDimitry Andric   initializeWebAssemblyExceptionInfoPass(PR);
940b57cec5SDimitry Andric   initializeWebAssemblyCFGSortPass(PR);
950b57cec5SDimitry Andric   initializeWebAssemblyCFGStackifyPass(PR);
960b57cec5SDimitry Andric   initializeWebAssemblyExplicitLocalsPass(PR);
970b57cec5SDimitry Andric   initializeWebAssemblyLowerBrUnlessPass(PR);
980b57cec5SDimitry Andric   initializeWebAssemblyRegNumberingPass(PR);
995ffd83dbSDimitry Andric   initializeWebAssemblyDebugFixupPass(PR);
1000b57cec5SDimitry Andric   initializeWebAssemblyPeepholePass(PR);
101fe6060f1SDimitry Andric   initializeWebAssemblyMCLowerPrePassPass(PR);
1020b57cec5SDimitry Andric }
1030b57cec5SDimitry Andric 
1040b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
1050b57cec5SDimitry Andric // WebAssembly Lowering public interface.
1060b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
1070b57cec5SDimitry Andric 
1080b57cec5SDimitry Andric static Reloc::Model getEffectiveRelocModel(Optional<Reloc::Model> RM,
1090b57cec5SDimitry Andric                                            const Triple &TT) {
1100b57cec5SDimitry Andric   if (!RM.hasValue()) {
1110b57cec5SDimitry Andric     // Default to static relocation model.  This should always be more optimial
1120b57cec5SDimitry Andric     // than PIC since the static linker can determine all global addresses and
1130b57cec5SDimitry Andric     // assume direct function calls.
1140b57cec5SDimitry Andric     return Reloc::Static;
1150b57cec5SDimitry Andric   }
1160b57cec5SDimitry Andric 
1170b57cec5SDimitry Andric   if (!TT.isOSEmscripten()) {
1180b57cec5SDimitry Andric     // Relocation modes other than static are currently implemented in a way
1190b57cec5SDimitry Andric     // that only works for Emscripten, so disable them if we aren't targeting
1200b57cec5SDimitry Andric     // Emscripten.
1210b57cec5SDimitry Andric     return Reloc::Static;
1220b57cec5SDimitry Andric   }
1230b57cec5SDimitry Andric 
1240b57cec5SDimitry Andric   return *RM;
1250b57cec5SDimitry Andric }
1260b57cec5SDimitry Andric 
1270b57cec5SDimitry Andric /// Create an WebAssembly architecture model.
1280b57cec5SDimitry Andric ///
1290b57cec5SDimitry Andric WebAssemblyTargetMachine::WebAssemblyTargetMachine(
1300b57cec5SDimitry Andric     const Target &T, const Triple &TT, StringRef CPU, StringRef FS,
1310b57cec5SDimitry Andric     const TargetOptions &Options, Optional<Reloc::Model> RM,
1320b57cec5SDimitry Andric     Optional<CodeModel::Model> CM, CodeGenOpt::Level OL, bool JIT)
133fe6060f1SDimitry Andric     : LLVMTargetMachine(
134fe6060f1SDimitry Andric           T,
135fe6060f1SDimitry Andric           TT.isArch64Bit()
136*349cc55cSDimitry Andric               ? (TT.isOSEmscripten() ? "e-m:e-p:64:64-p10:8:8-p20:8:8-i64:64-"
137*349cc55cSDimitry Andric                                        "f128:64-n32:64-S128-ni:1:10:20"
138*349cc55cSDimitry Andric                                      : "e-m:e-p:64:64-p10:8:8-p20:8:8-i64:64-"
139*349cc55cSDimitry Andric                                        "n32:64-S128-ni:1:10:20")
140*349cc55cSDimitry Andric               : (TT.isOSEmscripten() ? "e-m:e-p:32:32-p10:8:8-p20:8:8-i64:64-"
141*349cc55cSDimitry Andric                                        "f128:64-n32:64-S128-ni:1:10:20"
142*349cc55cSDimitry Andric                                      : "e-m:e-p:32:32-p10:8:8-p20:8:8-i64:64-"
143*349cc55cSDimitry Andric                                        "n32:64-S128-ni:1:10:20"),
1440b57cec5SDimitry Andric           TT, CPU, FS, Options, getEffectiveRelocModel(RM, TT),
1450b57cec5SDimitry Andric           getEffectiveCodeModel(CM, CodeModel::Large), OL),
1460b57cec5SDimitry Andric       TLOF(new WebAssemblyTargetObjectFile()) {
1470b57cec5SDimitry Andric   // WebAssembly type-checks instructions, but a noreturn function with a return
1480b57cec5SDimitry Andric   // type that doesn't match the context will cause a check failure. So we lower
1490b57cec5SDimitry Andric   // LLVM 'unreachable' to ISD::TRAP and then lower that to WebAssembly's
1500b57cec5SDimitry Andric   // 'unreachable' instructions which is meant for that case.
1510b57cec5SDimitry Andric   this->Options.TrapUnreachable = true;
1520b57cec5SDimitry Andric 
1530b57cec5SDimitry Andric   // WebAssembly treats each function as an independent unit. Force
1540b57cec5SDimitry Andric   // -ffunction-sections, effectively, so that we can emit them independently.
1550b57cec5SDimitry Andric   this->Options.FunctionSections = true;
1560b57cec5SDimitry Andric   this->Options.DataSections = true;
1570b57cec5SDimitry Andric   this->Options.UniqueSectionNames = true;
1580b57cec5SDimitry Andric 
1590b57cec5SDimitry Andric   initAsmInfo();
1600b57cec5SDimitry Andric 
1610b57cec5SDimitry Andric   // Note that we don't use setRequiresStructuredCFG(true). It disables
1620b57cec5SDimitry Andric   // optimizations than we're ok with, and want, such as critical edge
1630b57cec5SDimitry Andric   // splitting and tail merging.
1640b57cec5SDimitry Andric }
1650b57cec5SDimitry Andric 
1660b57cec5SDimitry Andric WebAssemblyTargetMachine::~WebAssemblyTargetMachine() = default; // anchor.
1670b57cec5SDimitry Andric 
168e8d8bef9SDimitry Andric const WebAssemblySubtarget *WebAssemblyTargetMachine::getSubtargetImpl() const {
169e8d8bef9SDimitry Andric   return getSubtargetImpl(std::string(getTargetCPU()),
170e8d8bef9SDimitry Andric                           std::string(getTargetFeatureString()));
171e8d8bef9SDimitry Andric }
172e8d8bef9SDimitry Andric 
1730b57cec5SDimitry Andric const WebAssemblySubtarget *
1740b57cec5SDimitry Andric WebAssemblyTargetMachine::getSubtargetImpl(std::string CPU,
1750b57cec5SDimitry Andric                                            std::string FS) const {
1760b57cec5SDimitry Andric   auto &I = SubtargetMap[CPU + FS];
1770b57cec5SDimitry Andric   if (!I) {
1788bcb0991SDimitry Andric     I = std::make_unique<WebAssemblySubtarget>(TargetTriple, CPU, FS, *this);
1790b57cec5SDimitry Andric   }
1800b57cec5SDimitry Andric   return I.get();
1810b57cec5SDimitry Andric }
1820b57cec5SDimitry Andric 
1830b57cec5SDimitry Andric const WebAssemblySubtarget *
1840b57cec5SDimitry Andric WebAssemblyTargetMachine::getSubtargetImpl(const Function &F) const {
1850b57cec5SDimitry Andric   Attribute CPUAttr = F.getFnAttribute("target-cpu");
1860b57cec5SDimitry Andric   Attribute FSAttr = F.getFnAttribute("target-features");
1870b57cec5SDimitry Andric 
188e8d8bef9SDimitry Andric   std::string CPU =
189e8d8bef9SDimitry Andric       CPUAttr.isValid() ? CPUAttr.getValueAsString().str() : TargetCPU;
190e8d8bef9SDimitry Andric   std::string FS =
191e8d8bef9SDimitry Andric       FSAttr.isValid() ? FSAttr.getValueAsString().str() : TargetFS;
1920b57cec5SDimitry Andric 
1930b57cec5SDimitry Andric   // This needs to be done before we create a new subtarget since any
1940b57cec5SDimitry Andric   // creation will depend on the TM and the code generation flags on the
1950b57cec5SDimitry Andric   // function that reside in TargetOptions.
1960b57cec5SDimitry Andric   resetTargetOptions(F);
1970b57cec5SDimitry Andric 
1980b57cec5SDimitry Andric   return getSubtargetImpl(CPU, FS);
1990b57cec5SDimitry Andric }
2000b57cec5SDimitry Andric 
2010b57cec5SDimitry Andric namespace {
2020b57cec5SDimitry Andric 
2030b57cec5SDimitry Andric class CoalesceFeaturesAndStripAtomics final : public ModulePass {
2040b57cec5SDimitry Andric   // Take the union of all features used in the module and use it for each
2050b57cec5SDimitry Andric   // function individually, since having multiple feature sets in one module
2060b57cec5SDimitry Andric   // currently does not make sense for WebAssembly. If atomics are not enabled,
2070b57cec5SDimitry Andric   // also strip atomic operations and thread local storage.
2080b57cec5SDimitry Andric   static char ID;
2090b57cec5SDimitry Andric   WebAssemblyTargetMachine *WasmTM;
2100b57cec5SDimitry Andric 
2110b57cec5SDimitry Andric public:
2120b57cec5SDimitry Andric   CoalesceFeaturesAndStripAtomics(WebAssemblyTargetMachine *WasmTM)
2130b57cec5SDimitry Andric       : ModulePass(ID), WasmTM(WasmTM) {}
2140b57cec5SDimitry Andric 
2150b57cec5SDimitry Andric   bool runOnModule(Module &M) override {
2160b57cec5SDimitry Andric     FeatureBitset Features = coalesceFeatures(M);
2170b57cec5SDimitry Andric 
2180b57cec5SDimitry Andric     std::string FeatureStr = getFeatureString(Features);
219e8d8bef9SDimitry Andric     WasmTM->setTargetFeatureString(FeatureStr);
2200b57cec5SDimitry Andric     for (auto &F : M)
2210b57cec5SDimitry Andric       replaceFeatures(F, FeatureStr);
2220b57cec5SDimitry Andric 
2230b57cec5SDimitry Andric     bool StrippedAtomics = false;
2240b57cec5SDimitry Andric     bool StrippedTLS = false;
2250b57cec5SDimitry Andric 
2260b57cec5SDimitry Andric     if (!Features[WebAssembly::FeatureAtomics])
2270b57cec5SDimitry Andric       StrippedAtomics = stripAtomics(M);
2280b57cec5SDimitry Andric 
2290b57cec5SDimitry Andric     if (!Features[WebAssembly::FeatureBulkMemory])
2300b57cec5SDimitry Andric       StrippedTLS = stripThreadLocals(M);
2310b57cec5SDimitry Andric 
2320b57cec5SDimitry Andric     if (StrippedAtomics && !StrippedTLS)
2330b57cec5SDimitry Andric       stripThreadLocals(M);
2340b57cec5SDimitry Andric     else if (StrippedTLS && !StrippedAtomics)
2350b57cec5SDimitry Andric       stripAtomics(M);
2360b57cec5SDimitry Andric 
2370b57cec5SDimitry Andric     recordFeatures(M, Features, StrippedAtomics || StrippedTLS);
2380b57cec5SDimitry Andric 
2390b57cec5SDimitry Andric     // Conservatively assume we have made some change
2400b57cec5SDimitry Andric     return true;
2410b57cec5SDimitry Andric   }
2420b57cec5SDimitry Andric 
2430b57cec5SDimitry Andric private:
2440b57cec5SDimitry Andric   FeatureBitset coalesceFeatures(const Module &M) {
2450b57cec5SDimitry Andric     FeatureBitset Features =
2460b57cec5SDimitry Andric         WasmTM
2475ffd83dbSDimitry Andric             ->getSubtargetImpl(std::string(WasmTM->getTargetCPU()),
2485ffd83dbSDimitry Andric                                std::string(WasmTM->getTargetFeatureString()))
2490b57cec5SDimitry Andric             ->getFeatureBits();
2500b57cec5SDimitry Andric     for (auto &F : M)
2510b57cec5SDimitry Andric       Features |= WasmTM->getSubtargetImpl(F)->getFeatureBits();
2520b57cec5SDimitry Andric     return Features;
2530b57cec5SDimitry Andric   }
2540b57cec5SDimitry Andric 
2550b57cec5SDimitry Andric   std::string getFeatureString(const FeatureBitset &Features) {
2560b57cec5SDimitry Andric     std::string Ret;
2570b57cec5SDimitry Andric     for (const SubtargetFeatureKV &KV : WebAssemblyFeatureKV) {
2580b57cec5SDimitry Andric       if (Features[KV.Value])
2590b57cec5SDimitry Andric         Ret += (StringRef("+") + KV.Key + ",").str();
2600b57cec5SDimitry Andric     }
2610b57cec5SDimitry Andric     return Ret;
2620b57cec5SDimitry Andric   }
2630b57cec5SDimitry Andric 
2640b57cec5SDimitry Andric   void replaceFeatures(Function &F, const std::string &Features) {
2650b57cec5SDimitry Andric     F.removeFnAttr("target-features");
2660b57cec5SDimitry Andric     F.removeFnAttr("target-cpu");
2670b57cec5SDimitry Andric     F.addFnAttr("target-features", Features);
2680b57cec5SDimitry Andric   }
2690b57cec5SDimitry Andric 
2700b57cec5SDimitry Andric   bool stripAtomics(Module &M) {
2710b57cec5SDimitry Andric     // Detect whether any atomics will be lowered, since there is no way to tell
2720b57cec5SDimitry Andric     // whether the LowerAtomic pass lowers e.g. stores.
2730b57cec5SDimitry Andric     bool Stripped = false;
2740b57cec5SDimitry Andric     for (auto &F : M) {
2750b57cec5SDimitry Andric       for (auto &B : F) {
2760b57cec5SDimitry Andric         for (auto &I : B) {
2770b57cec5SDimitry Andric           if (I.isAtomic()) {
2780b57cec5SDimitry Andric             Stripped = true;
2790b57cec5SDimitry Andric             goto done;
2800b57cec5SDimitry Andric           }
2810b57cec5SDimitry Andric         }
2820b57cec5SDimitry Andric       }
2830b57cec5SDimitry Andric     }
2840b57cec5SDimitry Andric 
2850b57cec5SDimitry Andric   done:
2860b57cec5SDimitry Andric     if (!Stripped)
2870b57cec5SDimitry Andric       return false;
2880b57cec5SDimitry Andric 
2890b57cec5SDimitry Andric     LowerAtomicPass Lowerer;
2900b57cec5SDimitry Andric     FunctionAnalysisManager FAM;
2910b57cec5SDimitry Andric     for (auto &F : M)
2920b57cec5SDimitry Andric       Lowerer.run(F, FAM);
2930b57cec5SDimitry Andric 
2940b57cec5SDimitry Andric     return true;
2950b57cec5SDimitry Andric   }
2960b57cec5SDimitry Andric 
2970b57cec5SDimitry Andric   bool stripThreadLocals(Module &M) {
2980b57cec5SDimitry Andric     bool Stripped = false;
2990b57cec5SDimitry Andric     for (auto &GV : M.globals()) {
300e8d8bef9SDimitry Andric       if (GV.isThreadLocal()) {
3010b57cec5SDimitry Andric         Stripped = true;
302e8d8bef9SDimitry Andric         GV.setThreadLocal(false);
3030b57cec5SDimitry Andric       }
3040b57cec5SDimitry Andric     }
3050b57cec5SDimitry Andric     return Stripped;
3060b57cec5SDimitry Andric   }
3070b57cec5SDimitry Andric 
3080b57cec5SDimitry Andric   void recordFeatures(Module &M, const FeatureBitset &Features, bool Stripped) {
3090b57cec5SDimitry Andric     for (const SubtargetFeatureKV &KV : WebAssemblyFeatureKV) {
3105ffd83dbSDimitry Andric       if (Features[KV.Value]) {
3115ffd83dbSDimitry Andric         // Mark features as used
3120b57cec5SDimitry Andric         std::string MDKey = (StringRef("wasm-feature-") + KV.Key).str();
3130b57cec5SDimitry Andric         M.addModuleFlag(Module::ModFlagBehavior::Error, MDKey,
3140b57cec5SDimitry Andric                         wasm::WASM_FEATURE_PREFIX_USED);
3150b57cec5SDimitry Andric       }
3160b57cec5SDimitry Andric     }
3175ffd83dbSDimitry Andric     // Code compiled without atomics or bulk-memory may have had its atomics or
3185ffd83dbSDimitry Andric     // thread-local data lowered to nonatomic operations or non-thread-local
3195ffd83dbSDimitry Andric     // data. In that case, we mark the pseudo-feature "shared-mem" as disallowed
3205ffd83dbSDimitry Andric     // to tell the linker that it would be unsafe to allow this code ot be used
3215ffd83dbSDimitry Andric     // in a module with shared memory.
3225ffd83dbSDimitry Andric     if (Stripped) {
3235ffd83dbSDimitry Andric       M.addModuleFlag(Module::ModFlagBehavior::Error, "wasm-feature-shared-mem",
3245ffd83dbSDimitry Andric                       wasm::WASM_FEATURE_PREFIX_DISALLOWED);
3255ffd83dbSDimitry Andric     }
3260b57cec5SDimitry Andric   }
3270b57cec5SDimitry Andric };
3280b57cec5SDimitry Andric char CoalesceFeaturesAndStripAtomics::ID = 0;
3290b57cec5SDimitry Andric 
3300b57cec5SDimitry Andric /// WebAssembly Code Generator Pass Configuration Options.
3310b57cec5SDimitry Andric class WebAssemblyPassConfig final : public TargetPassConfig {
3320b57cec5SDimitry Andric public:
3330b57cec5SDimitry Andric   WebAssemblyPassConfig(WebAssemblyTargetMachine &TM, PassManagerBase &PM)
3340b57cec5SDimitry Andric       : TargetPassConfig(TM, PM) {}
3350b57cec5SDimitry Andric 
3360b57cec5SDimitry Andric   WebAssemblyTargetMachine &getWebAssemblyTargetMachine() const {
3370b57cec5SDimitry Andric     return getTM<WebAssemblyTargetMachine>();
3380b57cec5SDimitry Andric   }
3390b57cec5SDimitry Andric 
3400b57cec5SDimitry Andric   FunctionPass *createTargetRegisterAllocator(bool) override;
3410b57cec5SDimitry Andric 
3420b57cec5SDimitry Andric   void addIRPasses() override;
3430b57cec5SDimitry Andric   bool addInstSelector() override;
3440b57cec5SDimitry Andric   void addPostRegAlloc() override;
3450b57cec5SDimitry Andric   bool addGCPasses() override { return false; }
3460b57cec5SDimitry Andric   void addPreEmitPass() override;
347*349cc55cSDimitry Andric   bool addPreISel() override;
3480b57cec5SDimitry Andric 
3490b57cec5SDimitry Andric   // No reg alloc
350e8d8bef9SDimitry Andric   bool addRegAssignAndRewriteFast() override { return false; }
3510b57cec5SDimitry Andric 
3520b57cec5SDimitry Andric   // No reg alloc
353e8d8bef9SDimitry Andric   bool addRegAssignAndRewriteOptimized() override { return false; }
3540b57cec5SDimitry Andric };
3550b57cec5SDimitry Andric } // end anonymous namespace
3560b57cec5SDimitry Andric 
3570b57cec5SDimitry Andric TargetTransformInfo
3580b57cec5SDimitry Andric WebAssemblyTargetMachine::getTargetTransformInfo(const Function &F) {
3590b57cec5SDimitry Andric   return TargetTransformInfo(WebAssemblyTTIImpl(this, F));
3600b57cec5SDimitry Andric }
3610b57cec5SDimitry Andric 
3620b57cec5SDimitry Andric TargetPassConfig *
3630b57cec5SDimitry Andric WebAssemblyTargetMachine::createPassConfig(PassManagerBase &PM) {
3640b57cec5SDimitry Andric   return new WebAssemblyPassConfig(*this, PM);
3650b57cec5SDimitry Andric }
3660b57cec5SDimitry Andric 
3670b57cec5SDimitry Andric FunctionPass *WebAssemblyPassConfig::createTargetRegisterAllocator(bool) {
3680b57cec5SDimitry Andric   return nullptr; // No reg alloc
3690b57cec5SDimitry Andric }
3700b57cec5SDimitry Andric 
371*349cc55cSDimitry Andric static void checkSanityForEHAndSjLj(const TargetMachine *TM) {
372*349cc55cSDimitry Andric   // Sanity checking related to -exception-model
373*349cc55cSDimitry Andric   if (TM->Options.ExceptionModel != ExceptionHandling::None &&
374*349cc55cSDimitry Andric       TM->Options.ExceptionModel != ExceptionHandling::Wasm)
375*349cc55cSDimitry Andric     report_fatal_error("-exception-model should be either 'none' or 'wasm'");
376*349cc55cSDimitry Andric   if (WasmEnableEmEH && TM->Options.ExceptionModel == ExceptionHandling::Wasm)
377*349cc55cSDimitry Andric     report_fatal_error("-exception-model=wasm not allowed with "
378*349cc55cSDimitry Andric                        "-enable-emscripten-cxx-exceptions");
379*349cc55cSDimitry Andric   if (WasmEnableEH && TM->Options.ExceptionModel != ExceptionHandling::Wasm)
380*349cc55cSDimitry Andric     report_fatal_error(
381*349cc55cSDimitry Andric         "-wasm-enable-eh only allowed with -exception-model=wasm");
382*349cc55cSDimitry Andric   if (WasmEnableSjLj && TM->Options.ExceptionModel != ExceptionHandling::Wasm)
383*349cc55cSDimitry Andric     report_fatal_error(
384*349cc55cSDimitry Andric         "-wasm-enable-sjlj only allowed with -exception-model=wasm");
385*349cc55cSDimitry Andric   if ((!WasmEnableEH && !WasmEnableSjLj) &&
386*349cc55cSDimitry Andric       TM->Options.ExceptionModel == ExceptionHandling::Wasm)
387*349cc55cSDimitry Andric     report_fatal_error(
388*349cc55cSDimitry Andric         "-exception-model=wasm only allowed with at least one of "
389*349cc55cSDimitry Andric         "-wasm-enable-eh or -wasm-enable-sjj");
390*349cc55cSDimitry Andric 
391*349cc55cSDimitry Andric   // You can't enable two modes of EH at the same time
392*349cc55cSDimitry Andric   if (WasmEnableEmEH && WasmEnableEH)
393*349cc55cSDimitry Andric     report_fatal_error(
394*349cc55cSDimitry Andric         "-enable-emscripten-cxx-exceptions not allowed with -wasm-enable-eh");
395*349cc55cSDimitry Andric   // You can't enable two modes of SjLj at the same time
396*349cc55cSDimitry Andric   if (WasmEnableEmSjLj && WasmEnableSjLj)
397*349cc55cSDimitry Andric     report_fatal_error(
398*349cc55cSDimitry Andric         "-enable-emscripten-sjlj not allowed with -wasm-enable-sjlj");
399*349cc55cSDimitry Andric   // You can't mix Emscripten EH with Wasm SjLj.
400*349cc55cSDimitry Andric   if (WasmEnableEmEH && WasmEnableSjLj)
401*349cc55cSDimitry Andric     report_fatal_error(
402*349cc55cSDimitry Andric         "-enable-emscripten-cxx-exceptions not allowed with -wasm-enable-sjlj");
403*349cc55cSDimitry Andric   // Currently it is allowed to mix Wasm EH with Emscripten SjLj as an interim
404*349cc55cSDimitry Andric   // measure, but some code will error out at compile time in this combination.
405*349cc55cSDimitry Andric   // See WebAssemblyLowerEmscriptenEHSjLj pass for details.
406*349cc55cSDimitry Andric }
407*349cc55cSDimitry Andric 
4080b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
4090b57cec5SDimitry Andric // The following functions are called from lib/CodeGen/Passes.cpp to modify
4100b57cec5SDimitry Andric // the CodeGen pass sequence.
4110b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
4120b57cec5SDimitry Andric 
4130b57cec5SDimitry Andric void WebAssemblyPassConfig::addIRPasses() {
414e8d8bef9SDimitry Andric   // Lower atomics and TLS if necessary
4150b57cec5SDimitry Andric   addPass(new CoalesceFeaturesAndStripAtomics(&getWebAssemblyTargetMachine()));
4160b57cec5SDimitry Andric 
4170b57cec5SDimitry Andric   // This is a no-op if atomics are not used in the module
4180b57cec5SDimitry Andric   addPass(createAtomicExpandPass());
4190b57cec5SDimitry Andric 
4200b57cec5SDimitry Andric   // Add signatures to prototype-less function declarations
4210b57cec5SDimitry Andric   addPass(createWebAssemblyAddMissingPrototypes());
4220b57cec5SDimitry Andric 
4230b57cec5SDimitry Andric   // Lower .llvm.global_dtors into .llvm_global_ctors with __cxa_atexit calls.
4240b57cec5SDimitry Andric   addPass(createWebAssemblyLowerGlobalDtors());
4250b57cec5SDimitry Andric 
4260b57cec5SDimitry Andric   // Fix function bitcasts, as WebAssembly requires caller and callee signatures
4270b57cec5SDimitry Andric   // to match.
4280b57cec5SDimitry Andric   addPass(createWebAssemblyFixFunctionBitcasts());
4290b57cec5SDimitry Andric 
4300b57cec5SDimitry Andric   // Optimize "returned" function attributes.
4310b57cec5SDimitry Andric   if (getOptLevel() != CodeGenOpt::None)
4320b57cec5SDimitry Andric     addPass(createWebAssemblyOptimizeReturned());
4330b57cec5SDimitry Andric 
434*349cc55cSDimitry Andric   checkSanityForEHAndSjLj(TM);
435*349cc55cSDimitry Andric 
4360b57cec5SDimitry Andric   // If exception handling is not enabled and setjmp/longjmp handling is
4370b57cec5SDimitry Andric   // enabled, we lower invokes into calls and delete unreachable landingpad
4380b57cec5SDimitry Andric   // blocks. Lowering invokes when there is no EH support is done in
439*349cc55cSDimitry Andric   // TargetPassConfig::addPassesToHandleExceptions, but that runs after these IR
440*349cc55cSDimitry Andric   // passes and Emscripten SjLj handling expects all invokes to be lowered
441*349cc55cSDimitry Andric   // before.
442*349cc55cSDimitry Andric   if (!WasmEnableEmEH && !WasmEnableEH) {
4430b57cec5SDimitry Andric     addPass(createLowerInvokePass());
4440b57cec5SDimitry Andric     // The lower invoke pass may create unreachable code. Remove it in order not
4450b57cec5SDimitry Andric     // to process dead blocks in setjmp/longjmp handling.
4460b57cec5SDimitry Andric     addPass(createUnreachableBlockEliminationPass());
4470b57cec5SDimitry Andric   }
4480b57cec5SDimitry Andric 
449*349cc55cSDimitry Andric   // Handle exceptions and setjmp/longjmp if enabled. Unlike Wasm EH preparation
450*349cc55cSDimitry Andric   // done in WasmEHPrepare pass, Wasm SjLj preparation shares libraries and
451*349cc55cSDimitry Andric   // transformation algorithms with Emscripten SjLj, so we run
452*349cc55cSDimitry Andric   // LowerEmscriptenEHSjLj pass also when Wasm SjLj is enabled.
453*349cc55cSDimitry Andric   if (WasmEnableEmEH || WasmEnableEmSjLj || WasmEnableSjLj)
454*349cc55cSDimitry Andric     addPass(createWebAssemblyLowerEmscriptenEHSjLj());
4550b57cec5SDimitry Andric 
4560b57cec5SDimitry Andric   // Expand indirectbr instructions to switches.
4570b57cec5SDimitry Andric   addPass(createIndirectBrExpandPass());
4580b57cec5SDimitry Andric 
4590b57cec5SDimitry Andric   TargetPassConfig::addIRPasses();
4600b57cec5SDimitry Andric }
4610b57cec5SDimitry Andric 
4620b57cec5SDimitry Andric bool WebAssemblyPassConfig::addInstSelector() {
4630b57cec5SDimitry Andric   (void)TargetPassConfig::addInstSelector();
4640b57cec5SDimitry Andric   addPass(
4650b57cec5SDimitry Andric       createWebAssemblyISelDag(getWebAssemblyTargetMachine(), getOptLevel()));
4660b57cec5SDimitry Andric   // Run the argument-move pass immediately after the ScheduleDAG scheduler
4670b57cec5SDimitry Andric   // so that we can fix up the ARGUMENT instructions before anything else
4680b57cec5SDimitry Andric   // sees them in the wrong place.
4690b57cec5SDimitry Andric   addPass(createWebAssemblyArgumentMove());
4700b57cec5SDimitry Andric   // Set the p2align operands. This information is present during ISel, however
4710b57cec5SDimitry Andric   // it's inconvenient to collect. Collect it now, and update the immediate
4720b57cec5SDimitry Andric   // operands.
4730b57cec5SDimitry Andric   addPass(createWebAssemblySetP2AlignOperands());
4745ffd83dbSDimitry Andric 
4755ffd83dbSDimitry Andric   // Eliminate range checks and add default targets to br_table instructions.
4765ffd83dbSDimitry Andric   addPass(createWebAssemblyFixBrTableDefaults());
4775ffd83dbSDimitry Andric 
4780b57cec5SDimitry Andric   return false;
4790b57cec5SDimitry Andric }
4800b57cec5SDimitry Andric 
4810b57cec5SDimitry Andric void WebAssemblyPassConfig::addPostRegAlloc() {
4820b57cec5SDimitry Andric   // TODO: The following CodeGen passes don't currently support code containing
4830b57cec5SDimitry Andric   // virtual registers. Consider removing their restrictions and re-enabling
4840b57cec5SDimitry Andric   // them.
4850b57cec5SDimitry Andric 
4860b57cec5SDimitry Andric   // These functions all require the NoVRegs property.
4870b57cec5SDimitry Andric   disablePass(&MachineCopyPropagationID);
4880b57cec5SDimitry Andric   disablePass(&PostRAMachineSinkingID);
4890b57cec5SDimitry Andric   disablePass(&PostRASchedulerID);
4900b57cec5SDimitry Andric   disablePass(&FuncletLayoutID);
4910b57cec5SDimitry Andric   disablePass(&StackMapLivenessID);
4920b57cec5SDimitry Andric   disablePass(&LiveDebugValuesID);
4930b57cec5SDimitry Andric   disablePass(&PatchableFunctionID);
4940b57cec5SDimitry Andric   disablePass(&ShrinkWrapID);
4950b57cec5SDimitry Andric 
4960b57cec5SDimitry Andric   // This pass hurts code size for wasm because it can generate irreducible
4970b57cec5SDimitry Andric   // control flow.
4980b57cec5SDimitry Andric   disablePass(&MachineBlockPlacementID);
4990b57cec5SDimitry Andric 
5000b57cec5SDimitry Andric   TargetPassConfig::addPostRegAlloc();
5010b57cec5SDimitry Andric }
5020b57cec5SDimitry Andric 
5030b57cec5SDimitry Andric void WebAssemblyPassConfig::addPreEmitPass() {
5040b57cec5SDimitry Andric   TargetPassConfig::addPreEmitPass();
5050b57cec5SDimitry Andric 
506fe6060f1SDimitry Andric   // Nullify DBG_VALUE_LISTs that we cannot handle.
507fe6060f1SDimitry Andric   addPass(createWebAssemblyNullifyDebugValueLists());
508fe6060f1SDimitry Andric 
5090b57cec5SDimitry Andric   // Eliminate multiple-entry loops.
5100b57cec5SDimitry Andric   addPass(createWebAssemblyFixIrreducibleControlFlow());
5110b57cec5SDimitry Andric 
5120b57cec5SDimitry Andric   // Do various transformations for exception handling.
5130b57cec5SDimitry Andric   // Every CFG-changing optimizations should come before this.
514e8d8bef9SDimitry Andric   if (TM->Options.ExceptionModel == ExceptionHandling::Wasm)
5150b57cec5SDimitry Andric     addPass(createWebAssemblyLateEHPrepare());
5160b57cec5SDimitry Andric 
5170b57cec5SDimitry Andric   // Now that we have a prologue and epilogue and all frame indices are
5180b57cec5SDimitry Andric   // rewritten, eliminate SP and FP. This allows them to be stackified,
5190b57cec5SDimitry Andric   // colored, and numbered with the rest of the registers.
5200b57cec5SDimitry Andric   addPass(createWebAssemblyReplacePhysRegs());
5210b57cec5SDimitry Andric 
5220b57cec5SDimitry Andric   // Preparations and optimizations related to register stackification.
5230b57cec5SDimitry Andric   if (getOptLevel() != CodeGenOpt::None) {
5240b57cec5SDimitry Andric     // LiveIntervals isn't commonly run this late. Re-establish preconditions.
5250b57cec5SDimitry Andric     addPass(createWebAssemblyPrepareForLiveIntervals());
5260b57cec5SDimitry Andric 
5270b57cec5SDimitry Andric     // Depend on LiveIntervals and perform some optimizations on it.
5280b57cec5SDimitry Andric     addPass(createWebAssemblyOptimizeLiveIntervals());
5290b57cec5SDimitry Andric 
5300b57cec5SDimitry Andric     // Prepare memory intrinsic calls for register stackifying.
5310b57cec5SDimitry Andric     addPass(createWebAssemblyMemIntrinsicResults());
5320b57cec5SDimitry Andric 
5330b57cec5SDimitry Andric     // Mark registers as representing wasm's value stack. This is a key
5340b57cec5SDimitry Andric     // code-compression technique in WebAssembly. We run this pass (and
5350b57cec5SDimitry Andric     // MemIntrinsicResults above) very late, so that it sees as much code as
5360b57cec5SDimitry Andric     // possible, including code emitted by PEI and expanded by late tail
5370b57cec5SDimitry Andric     // duplication.
5380b57cec5SDimitry Andric     addPass(createWebAssemblyRegStackify());
5390b57cec5SDimitry Andric 
5400b57cec5SDimitry Andric     // Run the register coloring pass to reduce the total number of registers.
5410b57cec5SDimitry Andric     // This runs after stackification so that it doesn't consider registers
5420b57cec5SDimitry Andric     // that become stackified.
5430b57cec5SDimitry Andric     addPass(createWebAssemblyRegColoring());
5440b57cec5SDimitry Andric   }
5450b57cec5SDimitry Andric 
5460b57cec5SDimitry Andric   // Sort the blocks of the CFG into topological order, a prerequisite for
5470b57cec5SDimitry Andric   // BLOCK and LOOP markers.
5480b57cec5SDimitry Andric   addPass(createWebAssemblyCFGSort());
5490b57cec5SDimitry Andric 
5500b57cec5SDimitry Andric   // Insert BLOCK and LOOP markers.
5510b57cec5SDimitry Andric   addPass(createWebAssemblyCFGStackify());
5520b57cec5SDimitry Andric 
5530b57cec5SDimitry Andric   // Insert explicit local.get and local.set operators.
5545ffd83dbSDimitry Andric   if (!WasmDisableExplicitLocals)
5550b57cec5SDimitry Andric     addPass(createWebAssemblyExplicitLocals());
5560b57cec5SDimitry Andric 
5570b57cec5SDimitry Andric   // Lower br_unless into br_if.
5580b57cec5SDimitry Andric   addPass(createWebAssemblyLowerBrUnless());
5590b57cec5SDimitry Andric 
5600b57cec5SDimitry Andric   // Perform the very last peephole optimizations on the code.
5610b57cec5SDimitry Andric   if (getOptLevel() != CodeGenOpt::None)
5620b57cec5SDimitry Andric     addPass(createWebAssemblyPeephole());
5630b57cec5SDimitry Andric 
5640b57cec5SDimitry Andric   // Create a mapping from LLVM CodeGen virtual registers to wasm registers.
5650b57cec5SDimitry Andric   addPass(createWebAssemblyRegNumbering());
5665ffd83dbSDimitry Andric 
5675ffd83dbSDimitry Andric   // Fix debug_values whose defs have been stackified.
5685ffd83dbSDimitry Andric   if (!WasmDisableExplicitLocals)
5695ffd83dbSDimitry Andric     addPass(createWebAssemblyDebugFixup());
570fe6060f1SDimitry Andric 
571fe6060f1SDimitry Andric   // Collect information to prepare for MC lowering / asm printing.
572fe6060f1SDimitry Andric   addPass(createWebAssemblyMCLowerPrePass());
5730b57cec5SDimitry Andric }
5740b57cec5SDimitry Andric 
575*349cc55cSDimitry Andric bool WebAssemblyPassConfig::addPreISel() {
576*349cc55cSDimitry Andric   TargetPassConfig::addPreISel();
577*349cc55cSDimitry Andric   addPass(createWebAssemblyLowerRefTypesIntPtrConv());
578*349cc55cSDimitry Andric   return false;
579*349cc55cSDimitry Andric }
580*349cc55cSDimitry Andric 
5810b57cec5SDimitry Andric yaml::MachineFunctionInfo *
5820b57cec5SDimitry Andric WebAssemblyTargetMachine::createDefaultFuncInfoYAML() const {
5830b57cec5SDimitry Andric   return new yaml::WebAssemblyFunctionInfo();
5840b57cec5SDimitry Andric }
5850b57cec5SDimitry Andric 
5860b57cec5SDimitry Andric yaml::MachineFunctionInfo *WebAssemblyTargetMachine::convertFuncInfoToYAML(
5870b57cec5SDimitry Andric     const MachineFunction &MF) const {
5880b57cec5SDimitry Andric   const auto *MFI = MF.getInfo<WebAssemblyFunctionInfo>();
5890b57cec5SDimitry Andric   return new yaml::WebAssemblyFunctionInfo(*MFI);
5900b57cec5SDimitry Andric }
5910b57cec5SDimitry Andric 
5920b57cec5SDimitry Andric bool WebAssemblyTargetMachine::parseMachineFunctionInfo(
5930b57cec5SDimitry Andric     const yaml::MachineFunctionInfo &MFI, PerFunctionMIParsingState &PFS,
5940b57cec5SDimitry Andric     SMDiagnostic &Error, SMRange &SourceRange) const {
5950b57cec5SDimitry Andric   const auto &YamlMFI =
5960b57cec5SDimitry Andric       reinterpret_cast<const yaml::WebAssemblyFunctionInfo &>(MFI);
5970b57cec5SDimitry Andric   MachineFunction &MF = PFS.MF;
5980b57cec5SDimitry Andric   MF.getInfo<WebAssemblyFunctionInfo>()->initializeBaseYamlFields(YamlMFI);
5990b57cec5SDimitry Andric   return false;
6000b57cec5SDimitry Andric }
601