110e730a2SDan Gohman //===- WebAssemblyTargetMachine.cpp - Define TargetMachine for WebAssembly -==// 210e730a2SDan Gohman // 32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information. 52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 610e730a2SDan Gohman // 710e730a2SDan Gohman //===----------------------------------------------------------------------===// 810e730a2SDan Gohman /// 910e730a2SDan Gohman /// \file 105f8f34e4SAdrian Prantl /// This file defines the WebAssembly-specific subclass of TargetMachine. 1110e730a2SDan Gohman /// 1210e730a2SDan Gohman //===----------------------------------------------------------------------===// 1310e730a2SDan Gohman 1410e730a2SDan Gohman #include "WebAssemblyTargetMachine.h" 156bda14b3SChandler Carruth #include "MCTargetDesc/WebAssemblyMCTargetDesc.h" 16c6c42137SRichard Trieu #include "TargetInfo/WebAssemblyTargetInfo.h" 176bda14b3SChandler Carruth #include "WebAssembly.h" 1852221d56SHeejin Ahn #include "WebAssemblyMachineFunctionInfo.h" 195bf22fc8SDan Gohman #include "WebAssemblyTargetObjectFile.h" 2010e730a2SDan Gohman #include "WebAssemblyTargetTransformInfo.h" 2152221d56SHeejin Ahn #include "llvm/CodeGen/MIRParser/MIParser.h" 2210e730a2SDan Gohman #include "llvm/CodeGen/MachineFunctionPass.h" 2310e730a2SDan Gohman #include "llvm/CodeGen/Passes.h" 2410e730a2SDan Gohman #include "llvm/CodeGen/RegAllocRegistry.h" 2531d19d43SMatthias Braun #include "llvm/CodeGen/TargetPassConfig.h" 2610e730a2SDan Gohman #include "llvm/IR/Function.h" 2710e730a2SDan Gohman #include "llvm/Support/TargetRegistry.h" 2810e730a2SDan Gohman #include "llvm/Target/TargetOptions.h" 2903855df1SJF Bastien #include "llvm/Transforms/Scalar.h" 303f34e1b8SThomas Lively #include "llvm/Transforms/Scalar/LowerAtomic.h" 31a373d18eSDavid Blaikie #include "llvm/Transforms/Utils.h" 3210e730a2SDan Gohman using namespace llvm; 3310e730a2SDan Gohman 3410e730a2SDan Gohman #define DEBUG_TYPE "wasm" 3510e730a2SDan Gohman 36f41f67d3SDerek Schuff // Emscripten's asm.js-style exception handling 37ccdceda1SDerek Schuff static cl::opt<bool> EnableEmException( 3853b9af02SDerek Schuff "enable-emscripten-cxx-exceptions", 39f41f67d3SDerek Schuff cl::desc("WebAssembly Emscripten-style exception handling"), 40f41f67d3SDerek Schuff cl::init(false)); 41f41f67d3SDerek Schuff 42ccdceda1SDerek Schuff // Emscripten's asm.js-style setjmp/longjmp handling 43ccdceda1SDerek Schuff static cl::opt<bool> EnableEmSjLj( 44ccdceda1SDerek Schuff "enable-emscripten-sjlj", 45ccdceda1SDerek Schuff cl::desc("WebAssembly Emscripten-style setjmp/longjmp handling"), 46ccdceda1SDerek Schuff cl::init(false)); 47ccdceda1SDerek Schuff 480dbcb363STom Stellard extern "C" LLVM_EXTERNAL_VISIBILITY void LLVMInitializeWebAssemblyTarget() { 4910e730a2SDan Gohman // Register the target. 50f42454b9SMehdi Amini RegisterTargetMachine<WebAssemblyTargetMachine> X( 51f42454b9SMehdi Amini getTheWebAssemblyTarget32()); 52f42454b9SMehdi Amini RegisterTargetMachine<WebAssemblyTargetMachine> Y( 53f42454b9SMehdi Amini getTheWebAssemblyTarget64()); 54f41f67d3SDerek Schuff 5540926451SJacob Gravelle // Register backend passes 5640926451SJacob Gravelle auto &PR = *PassRegistry::getPassRegistry(); 5792617559SSam Clegg initializeWebAssemblyAddMissingPrototypesPass(PR); 5840926451SJacob Gravelle initializeWebAssemblyLowerEmscriptenEHSjLjPass(PR); 5940926451SJacob Gravelle initializeLowerGlobalDtorsPass(PR); 6040926451SJacob Gravelle initializeFixFunctionBitcastsPass(PR); 6140926451SJacob Gravelle initializeOptimizeReturnedPass(PR); 6240926451SJacob Gravelle initializeWebAssemblyArgumentMovePass(PR); 6340926451SJacob Gravelle initializeWebAssemblySetP2AlignOperandsPass(PR); 6440926451SJacob Gravelle initializeWebAssemblyReplacePhysRegsPass(PR); 6540926451SJacob Gravelle initializeWebAssemblyPrepareForLiveIntervalsPass(PR); 6640926451SJacob Gravelle initializeWebAssemblyOptimizeLiveIntervalsPass(PR); 67321d5220SHeejin Ahn initializeWebAssemblyMemIntrinsicResultsPass(PR); 6840926451SJacob Gravelle initializeWebAssemblyRegStackifyPass(PR); 6940926451SJacob Gravelle initializeWebAssemblyRegColoringPass(PR); 7040926451SJacob Gravelle initializeWebAssemblyFixIrreducibleControlFlowPass(PR); 714934f76bSHeejin Ahn initializeWebAssemblyLateEHPreparePass(PR); 7204c48949SHeejin Ahn initializeWebAssemblyExceptionInfoPass(PR); 7340926451SJacob Gravelle initializeWebAssemblyCFGSortPass(PR); 7440926451SJacob Gravelle initializeWebAssemblyCFGStackifyPass(PR); 75e9fd9073SHeejin Ahn initializeWebAssemblyExplicitLocalsPass(PR); 7640926451SJacob Gravelle initializeWebAssemblyLowerBrUnlessPass(PR); 7740926451SJacob Gravelle initializeWebAssemblyRegNumberingPass(PR); 7840926451SJacob Gravelle initializeWebAssemblyPeepholePass(PR); 7910e730a2SDan Gohman } 8010e730a2SDan Gohman 8110e730a2SDan Gohman //===----------------------------------------------------------------------===// 8210e730a2SDan Gohman // WebAssembly Lowering public interface. 8310e730a2SDan Gohman //===----------------------------------------------------------------------===// 8410e730a2SDan Gohman 8553572d04SDan Gohman static Reloc::Model getEffectiveRelocModel(Optional<Reloc::Model> RM, 8653572d04SDan Gohman const Triple &TT) { 8774f5fd4eSSam Clegg if (!RM.hasValue()) { 8874f5fd4eSSam Clegg // Default to static relocation model. This should always be more optimial 8974f5fd4eSSam Clegg // than PIC since the static linker can determine all global addresses and 9074f5fd4eSSam Clegg // assume direct function calls. 9174f5fd4eSSam Clegg return Reloc::Static; 9274f5fd4eSSam Clegg } 9353572d04SDan Gohman 9453572d04SDan Gohman if (!TT.isOSEmscripten()) { 9553572d04SDan Gohman // Relocation modes other than static are currently implemented in a way 9653572d04SDan Gohman // that only works for Emscripten, so disable them if we aren't targeting 9753572d04SDan Gohman // Emscripten. 9853572d04SDan Gohman return Reloc::Static; 9953572d04SDan Gohman } 10053572d04SDan Gohman 10141133a3eSDan Gohman return *RM; 10241133a3eSDan Gohman } 10341133a3eSDan Gohman 10410e730a2SDan Gohman /// Create an WebAssembly architecture model. 10510e730a2SDan Gohman /// 10610e730a2SDan Gohman WebAssemblyTargetMachine::WebAssemblyTargetMachine( 10710e730a2SDan Gohman const Target &T, const Triple &TT, StringRef CPU, StringRef FS, 10841133a3eSDan Gohman const TargetOptions &Options, Optional<Reloc::Model> RM, 109314ed201SDaniel Jasper Optional<CodeModel::Model> CM, CodeGenOpt::Level OL, bool JIT) 110bb8507e6SMatthias Braun : LLVMTargetMachine(T, 111bb8507e6SMatthias Braun TT.isArch64Bit() ? "e-m:e-p:64:64-i64:64-n32:64-S128" 1120c6f5ac5SDan Gohman : "e-m:e-p:32:32-i64:64-n32:64-S128", 11353572d04SDan Gohman TT, CPU, FS, Options, getEffectiveRelocModel(RM, TT), 114ca29c271SDavid Green getEffectiveCodeModel(CM, CodeModel::Large), OL), 115cf2a9e28SSam Clegg TLOF(new WebAssemblyTargetObjectFile()) { 116e040533eSDan Gohman // WebAssembly type-checks instructions, but a noreturn function with a return 117ffa143ceSDerek Schuff // type that doesn't match the context will cause a check failure. So we lower 118ffa143ceSDerek Schuff // LLVM 'unreachable' to ISD::TRAP and then lower that to WebAssembly's 119e040533eSDan Gohman // 'unreachable' instructions which is meant for that case. 120ffa143ceSDerek Schuff this->Options.TrapUnreachable = true; 121ffa143ceSDerek Schuff 122d934cb88SDan Gohman // WebAssembly treats each function as an independent unit. Force 123d934cb88SDan Gohman // -ffunction-sections, effectively, so that we can emit them independently. 124d934cb88SDan Gohman this->Options.FunctionSections = true; 125d934cb88SDan Gohman this->Options.DataSections = true; 126d934cb88SDan Gohman this->Options.UniqueSectionNames = true; 127d934cb88SDan Gohman 12810e730a2SDan Gohman initAsmInfo(); 12910e730a2SDan Gohman 130d85ab7fcSDan Gohman // Note that we don't use setRequiresStructuredCFG(true). It disables 131d85ab7fcSDan Gohman // optimizations than we're ok with, and want, such as critical edge 132d85ab7fcSDan Gohman // splitting and tail merging. 13310e730a2SDan Gohman } 13410e730a2SDan Gohman 13518c56a07SHeejin Ahn WebAssemblyTargetMachine::~WebAssemblyTargetMachine() = default; // anchor. 13610e730a2SDan Gohman 13710e730a2SDan Gohman const WebAssemblySubtarget * 138f3b4f990SThomas Lively WebAssemblyTargetMachine::getSubtargetImpl(std::string CPU, 139f3b4f990SThomas Lively std::string FS) const { 140f3b4f990SThomas Lively auto &I = SubtargetMap[CPU + FS]; 141f3b4f990SThomas Lively if (!I) { 1420eaee545SJonas Devlieghere I = std::make_unique<WebAssemblySubtarget>(TargetTriple, CPU, FS, *this); 143f3b4f990SThomas Lively } 144f3b4f990SThomas Lively return I.get(); 145f3b4f990SThomas Lively } 146f3b4f990SThomas Lively 147f3b4f990SThomas Lively const WebAssemblySubtarget * 14810e730a2SDan Gohman WebAssemblyTargetMachine::getSubtargetImpl(const Function &F) const { 14910e730a2SDan Gohman Attribute CPUAttr = F.getFnAttribute("target-cpu"); 15010e730a2SDan Gohman Attribute FSAttr = F.getFnAttribute("target-features"); 15110e730a2SDan Gohman 15210e730a2SDan Gohman std::string CPU = !CPUAttr.hasAttribute(Attribute::None) 15310e730a2SDan Gohman ? CPUAttr.getValueAsString().str() 15410e730a2SDan Gohman : TargetCPU; 15510e730a2SDan Gohman std::string FS = !FSAttr.hasAttribute(Attribute::None) 15610e730a2SDan Gohman ? FSAttr.getValueAsString().str() 15710e730a2SDan Gohman : TargetFS; 15810e730a2SDan Gohman 15910e730a2SDan Gohman // This needs to be done before we create a new subtarget since any 16010e730a2SDan Gohman // creation will depend on the TM and the code generation flags on the 16110e730a2SDan Gohman // function that reside in TargetOptions. 16210e730a2SDan Gohman resetTargetOptions(F); 163f3b4f990SThomas Lively 164f3b4f990SThomas Lively return getSubtargetImpl(CPU, FS); 16510e730a2SDan Gohman } 16610e730a2SDan Gohman 16710e730a2SDan Gohman namespace { 1683f34e1b8SThomas Lively 1693f34e1b8SThomas Lively class CoalesceFeaturesAndStripAtomics final : public ModulePass { 1703f34e1b8SThomas Lively // Take the union of all features used in the module and use it for each 1713f34e1b8SThomas Lively // function individually, since having multiple feature sets in one module 1723f34e1b8SThomas Lively // currently does not make sense for WebAssembly. If atomics are not enabled, 1733f34e1b8SThomas Lively // also strip atomic operations and thread local storage. 17439b5367cSDerek Schuff static char ID; 1753f34e1b8SThomas Lively WebAssemblyTargetMachine *WasmTM; 17639b5367cSDerek Schuff 17739b5367cSDerek Schuff public: 1783f34e1b8SThomas Lively CoalesceFeaturesAndStripAtomics(WebAssemblyTargetMachine *WasmTM) 1793f34e1b8SThomas Lively : ModulePass(ID), WasmTM(WasmTM) {} 1803f34e1b8SThomas Lively 18139b5367cSDerek Schuff bool runOnModule(Module &M) override { 1823f34e1b8SThomas Lively FeatureBitset Features = coalesceFeatures(M); 1833f34e1b8SThomas Lively 1843f34e1b8SThomas Lively std::string FeatureStr = getFeatureString(Features); 1853f34e1b8SThomas Lively for (auto &F : M) 1863f34e1b8SThomas Lively replaceFeatures(F, FeatureStr); 1873f34e1b8SThomas Lively 18842bba4b8SGuanzhong Chen bool StrippedAtomics = false; 18942bba4b8SGuanzhong Chen bool StrippedTLS = false; 1903f34e1b8SThomas Lively 19142bba4b8SGuanzhong Chen if (!Features[WebAssembly::FeatureAtomics]) 19242bba4b8SGuanzhong Chen StrippedAtomics = stripAtomics(M); 19342bba4b8SGuanzhong Chen 19442bba4b8SGuanzhong Chen if (!Features[WebAssembly::FeatureBulkMemory]) 19542bba4b8SGuanzhong Chen StrippedTLS = stripThreadLocals(M); 19642bba4b8SGuanzhong Chen 19742bba4b8SGuanzhong Chen if (StrippedAtomics && !StrippedTLS) 19842bba4b8SGuanzhong Chen stripThreadLocals(M); 19942bba4b8SGuanzhong Chen else if (StrippedTLS && !StrippedAtomics) 20042bba4b8SGuanzhong Chen stripAtomics(M); 20142bba4b8SGuanzhong Chen 20242bba4b8SGuanzhong Chen recordFeatures(M, Features, StrippedAtomics || StrippedTLS); 2033f34e1b8SThomas Lively 2043f34e1b8SThomas Lively // Conservatively assume we have made some change 20539b5367cSDerek Schuff return true; 20639b5367cSDerek Schuff } 2073f34e1b8SThomas Lively 2083f34e1b8SThomas Lively private: 2093f34e1b8SThomas Lively FeatureBitset coalesceFeatures(const Module &M) { 2103f34e1b8SThomas Lively FeatureBitset Features = 2113f34e1b8SThomas Lively WasmTM 212adcd0268SBenjamin Kramer ->getSubtargetImpl(std::string(WasmTM->getTargetCPU()), 213adcd0268SBenjamin Kramer std::string(WasmTM->getTargetFeatureString())) 2143f34e1b8SThomas Lively ->getFeatureBits(); 2153f34e1b8SThomas Lively for (auto &F : M) 2163f34e1b8SThomas Lively Features |= WasmTM->getSubtargetImpl(F)->getFeatureBits(); 2173f34e1b8SThomas Lively return Features; 2183f34e1b8SThomas Lively } 2193f34e1b8SThomas Lively 2203f34e1b8SThomas Lively std::string getFeatureString(const FeatureBitset &Features) { 2213f34e1b8SThomas Lively std::string Ret; 2223f34e1b8SThomas Lively for (const SubtargetFeatureKV &KV : WebAssemblyFeatureKV) { 2233f34e1b8SThomas Lively if (Features[KV.Value]) 2243f34e1b8SThomas Lively Ret += (StringRef("+") + KV.Key + ",").str(); 2253f34e1b8SThomas Lively } 2263f34e1b8SThomas Lively return Ret; 2273f34e1b8SThomas Lively } 2283f34e1b8SThomas Lively 2293f34e1b8SThomas Lively void replaceFeatures(Function &F, const std::string &Features) { 2303f34e1b8SThomas Lively F.removeFnAttr("target-features"); 2313f34e1b8SThomas Lively F.removeFnAttr("target-cpu"); 2323f34e1b8SThomas Lively F.addFnAttr("target-features", Features); 2333f34e1b8SThomas Lively } 2343f34e1b8SThomas Lively 2353f34e1b8SThomas Lively bool stripAtomics(Module &M) { 2363f34e1b8SThomas Lively // Detect whether any atomics will be lowered, since there is no way to tell 2373f34e1b8SThomas Lively // whether the LowerAtomic pass lowers e.g. stores. 2383f34e1b8SThomas Lively bool Stripped = false; 2393f34e1b8SThomas Lively for (auto &F : M) { 2403f34e1b8SThomas Lively for (auto &B : F) { 2413f34e1b8SThomas Lively for (auto &I : B) { 2423f34e1b8SThomas Lively if (I.isAtomic()) { 2433f34e1b8SThomas Lively Stripped = true; 2443f34e1b8SThomas Lively goto done; 2453f34e1b8SThomas Lively } 2463f34e1b8SThomas Lively } 2473f34e1b8SThomas Lively } 2483f34e1b8SThomas Lively } 2493f34e1b8SThomas Lively 2503f34e1b8SThomas Lively done: 2513f34e1b8SThomas Lively if (!Stripped) 2523f34e1b8SThomas Lively return false; 2533f34e1b8SThomas Lively 2543f34e1b8SThomas Lively LowerAtomicPass Lowerer; 2553f34e1b8SThomas Lively FunctionAnalysisManager FAM; 2563f34e1b8SThomas Lively for (auto &F : M) 2573f34e1b8SThomas Lively Lowerer.run(F, FAM); 2583f34e1b8SThomas Lively 2593f34e1b8SThomas Lively return true; 2603f34e1b8SThomas Lively } 2613f34e1b8SThomas Lively 2623f34e1b8SThomas Lively bool stripThreadLocals(Module &M) { 2633f34e1b8SThomas Lively bool Stripped = false; 2643f34e1b8SThomas Lively for (auto &GV : M.globals()) { 2653f34e1b8SThomas Lively if (GV.getThreadLocalMode() != 2663f34e1b8SThomas Lively GlobalValue::ThreadLocalMode::NotThreadLocal) { 2673f34e1b8SThomas Lively Stripped = true; 2683f34e1b8SThomas Lively GV.setThreadLocalMode(GlobalValue::ThreadLocalMode::NotThreadLocal); 2693f34e1b8SThomas Lively } 2703f34e1b8SThomas Lively } 2713f34e1b8SThomas Lively return Stripped; 2723f34e1b8SThomas Lively } 2733f34e1b8SThomas Lively 2743f34e1b8SThomas Lively void recordFeatures(Module &M, const FeatureBitset &Features, bool Stripped) { 2753f34e1b8SThomas Lively for (const SubtargetFeatureKV &KV : WebAssemblyFeatureKV) { 276*a1ae9566SThomas Lively if (Features[KV.Value]) { 277*a1ae9566SThomas Lively // Mark features as used 2783f34e1b8SThomas Lively std::string MDKey = (StringRef("wasm-feature-") + KV.Key).str(); 2793f34e1b8SThomas Lively M.addModuleFlag(Module::ModFlagBehavior::Error, MDKey, 2803f34e1b8SThomas Lively wasm::WASM_FEATURE_PREFIX_USED); 2813f34e1b8SThomas Lively } 2823f34e1b8SThomas Lively } 283*a1ae9566SThomas Lively // Code compiled without atomics or bulk-memory may have had its atomics or 284*a1ae9566SThomas Lively // thread-local data lowered to nonatomic operations or non-thread-local 285*a1ae9566SThomas Lively // data. In that case, we mark the pseudo-feature "shared-mem" as disallowed 286*a1ae9566SThomas Lively // to tell the linker that it would be unsafe to allow this code ot be used 287*a1ae9566SThomas Lively // in a module with shared memory. 288*a1ae9566SThomas Lively if (Stripped) { 289*a1ae9566SThomas Lively M.addModuleFlag(Module::ModFlagBehavior::Error, "wasm-feature-shared-mem", 290*a1ae9566SThomas Lively wasm::WASM_FEATURE_PREFIX_DISALLOWED); 291*a1ae9566SThomas Lively } 2923f34e1b8SThomas Lively } 29339b5367cSDerek Schuff }; 2943f34e1b8SThomas Lively char CoalesceFeaturesAndStripAtomics::ID = 0; 29539b5367cSDerek Schuff 29610e730a2SDan Gohman /// WebAssembly Code Generator Pass Configuration Options. 29710e730a2SDan Gohman class WebAssemblyPassConfig final : public TargetPassConfig { 29810e730a2SDan Gohman public: 2995e394c3dSMatthias Braun WebAssemblyPassConfig(WebAssemblyTargetMachine &TM, PassManagerBase &PM) 30010e730a2SDan Gohman : TargetPassConfig(TM, PM) {} 30110e730a2SDan Gohman 30210e730a2SDan Gohman WebAssemblyTargetMachine &getWebAssemblyTargetMachine() const { 30310e730a2SDan Gohman return getTM<WebAssemblyTargetMachine>(); 30410e730a2SDan Gohman } 30510e730a2SDan Gohman 30610e730a2SDan Gohman FunctionPass *createTargetRegisterAllocator(bool) override; 30710e730a2SDan Gohman 30810e730a2SDan Gohman void addIRPasses() override; 30910e730a2SDan Gohman bool addInstSelector() override; 31010e730a2SDan Gohman void addPostRegAlloc() override; 311ad154c83SDerek Schuff bool addGCPasses() override { return false; } 31210e730a2SDan Gohman void addPreEmitPass() override; 313cf55a657SMatt Arsenault 314cf55a657SMatt Arsenault // No reg alloc 315cf55a657SMatt Arsenault bool addRegAssignmentFast() override { return false; } 316cf55a657SMatt Arsenault 317cf55a657SMatt Arsenault // No reg alloc 318cf55a657SMatt Arsenault bool addRegAssignmentOptimized() override { return false; } 31910e730a2SDan Gohman }; 32010e730a2SDan Gohman } // end anonymous namespace 32110e730a2SDan Gohman 32226d11ca4SSanjoy Das TargetTransformInfo 32326d11ca4SSanjoy Das WebAssemblyTargetMachine::getTargetTransformInfo(const Function &F) { 32410e730a2SDan Gohman return TargetTransformInfo(WebAssemblyTTIImpl(this, F)); 32510e730a2SDan Gohman } 32610e730a2SDan Gohman 32710e730a2SDan Gohman TargetPassConfig * 32810e730a2SDan Gohman WebAssemblyTargetMachine::createPassConfig(PassManagerBase &PM) { 3295e394c3dSMatthias Braun return new WebAssemblyPassConfig(*this, PM); 33010e730a2SDan Gohman } 33110e730a2SDan Gohman 33210e730a2SDan Gohman FunctionPass *WebAssemblyPassConfig::createTargetRegisterAllocator(bool) { 33310e730a2SDan Gohman return nullptr; // No reg alloc 33410e730a2SDan Gohman } 33510e730a2SDan Gohman 33610e730a2SDan Gohman //===----------------------------------------------------------------------===// 33710e730a2SDan Gohman // The following functions are called from lib/CodeGen/Passes.cpp to modify 33810e730a2SDan Gohman // the CodeGen pass sequence. 33910e730a2SDan Gohman //===----------------------------------------------------------------------===// 34010e730a2SDan Gohman 34110e730a2SDan Gohman void WebAssemblyPassConfig::addIRPasses() { 3423f34e1b8SThomas Lively // Runs LowerAtomicPass if necessary 3433f34e1b8SThomas Lively addPass(new CoalesceFeaturesAndStripAtomics(&getWebAssemblyTargetMachine())); 3443f34e1b8SThomas Lively 3453f34e1b8SThomas Lively // This is a no-op if atomics are not used in the module 3468b61764cSFrancis Visoiu Mistrih addPass(createAtomicExpandPass()); 34710e730a2SDan Gohman 34892617559SSam Clegg // Add signatures to prototype-less function declarations 34992617559SSam Clegg addPass(createWebAssemblyAddMissingPrototypes()); 35092617559SSam Clegg 351bafe6902SSam Clegg // Lower .llvm.global_dtors into .llvm_global_ctors with __cxa_atexit calls. 352bafe6902SSam Clegg addPass(createWebAssemblyLowerGlobalDtors()); 353bafe6902SSam Clegg 3541b637458SDan Gohman // Fix function bitcasts, as WebAssembly requires caller and callee signatures 3551b637458SDan Gohman // to match. 3561b637458SDan Gohman addPass(createWebAssemblyFixFunctionBitcasts()); 3571b637458SDan Gohman 35881719f85SDan Gohman // Optimize "returned" function attributes. 359b13c91f1SDan Gohman if (getOptLevel() != CodeGenOpt::None) 36081719f85SDan Gohman addPass(createWebAssemblyOptimizeReturned()); 36181719f85SDan Gohman 362c0f18172SHeejin Ahn // If exception handling is not enabled and setjmp/longjmp handling is 363c0f18172SHeejin Ahn // enabled, we lower invokes into calls and delete unreachable landingpad 364c0f18172SHeejin Ahn // blocks. Lowering invokes when there is no EH support is done in 365c0f18172SHeejin Ahn // TargetPassConfig::addPassesToHandleExceptions, but this runs after this 366c0f18172SHeejin Ahn // function and SjLj handling expects all invokes to be lowered before. 3679386bde1SHeejin Ahn if (!EnableEmException && 3689386bde1SHeejin Ahn TM->Options.ExceptionModel == ExceptionHandling::None) { 369c0f18172SHeejin Ahn addPass(createLowerInvokePass()); 370c0f18172SHeejin Ahn // The lower invoke pass may create unreachable code. Remove it in order not 371c0f18172SHeejin Ahn // to process dead blocks in setjmp/longjmp handling. 372c0f18172SHeejin Ahn addPass(createUnreachableBlockEliminationPass()); 373c0f18172SHeejin Ahn } 374c0f18172SHeejin Ahn 375c0f18172SHeejin Ahn // Handle exceptions and setjmp/longjmp if enabled. 376ccdceda1SDerek Schuff if (EnableEmException || EnableEmSjLj) 377ccdceda1SDerek Schuff addPass(createWebAssemblyLowerEmscriptenEHSjLj(EnableEmException, 378ccdceda1SDerek Schuff EnableEmSjLj)); 379f41f67d3SDerek Schuff 380ec4be576SDerek Schuff // Expand indirectbr instructions to switches. 381ec4be576SDerek Schuff addPass(createIndirectBrExpandPass()); 382ec4be576SDerek Schuff 38310e730a2SDan Gohman TargetPassConfig::addIRPasses(); 38410e730a2SDan Gohman } 38510e730a2SDan Gohman 38610e730a2SDan Gohman bool WebAssemblyPassConfig::addInstSelector() { 387b0921ca9SDan Gohman (void)TargetPassConfig::addInstSelector(); 38810e730a2SDan Gohman addPass( 38910e730a2SDan Gohman createWebAssemblyISelDag(getWebAssemblyTargetMachine(), getOptLevel())); 3901cf96c0cSDan Gohman // Run the argument-move pass immediately after the ScheduleDAG scheduler 3911cf96c0cSDan Gohman // so that we can fix up the ARGUMENT instructions before anything else 3921cf96c0cSDan Gohman // sees them in the wrong place. 3931cf96c0cSDan Gohman addPass(createWebAssemblyArgumentMove()); 394bb372243SDan Gohman // Set the p2align operands. This information is present during ISel, however 395bb372243SDan Gohman // it's inconvenient to collect. Collect it now, and update the immediate 396bb372243SDan Gohman // operands. 397bb372243SDan Gohman addPass(createWebAssemblySetP2AlignOperands()); 39810e730a2SDan Gohman return false; 39910e730a2SDan Gohman } 40010e730a2SDan Gohman 401600aee98SJF Bastien void WebAssemblyPassConfig::addPostRegAlloc() { 4029c54d3b4SDan Gohman // TODO: The following CodeGen passes don't currently support code containing 4039c54d3b4SDan Gohman // virtual registers. Consider removing their restrictions and re-enabling 4049c54d3b4SDan Gohman // them. 405ad154c83SDerek Schuff 4061eb47368SMatthias Braun // These functions all require the NoVRegs property. 407600aee98SJF Bastien disablePass(&MachineCopyPropagationID); 4087ab1b32bSJun Bum Lim disablePass(&PostRAMachineSinkingID); 409ecabac62SDerek Schuff disablePass(&PostRASchedulerID); 410ecabac62SDerek Schuff disablePass(&FuncletLayoutID); 411ecabac62SDerek Schuff disablePass(&StackMapLivenessID); 412ecabac62SDerek Schuff disablePass(&LiveDebugValuesID); 413fe71ec77SSanjoy Das disablePass(&PatchableFunctionID); 4147ab1b32bSJun Bum Lim disablePass(&ShrinkWrapID); 415950a13cfSDan Gohman 416ef9d6aeaSHeejin Ahn // This pass hurts code size for wasm because it can generate irreducible 417ef9d6aeaSHeejin Ahn // control flow. 418ef9d6aeaSHeejin Ahn disablePass(&MachineBlockPlacementID); 419ef9d6aeaSHeejin Ahn 420b0921ca9SDan Gohman TargetPassConfig::addPostRegAlloc(); 421600aee98SJF Bastien } 42210e730a2SDan Gohman 423950a13cfSDan Gohman void WebAssemblyPassConfig::addPreEmitPass() { 424b0921ca9SDan Gohman TargetPassConfig::addPreEmitPass(); 425b0921ca9SDan Gohman 426e95056d6SHeejin Ahn // Eliminate multiple-entry loops. 427e95056d6SHeejin Ahn addPass(createWebAssemblyFixIrreducibleControlFlow()); 428e95056d6SHeejin Ahn 429e95056d6SHeejin Ahn // Do various transformations for exception handling. 430d6f48786SHeejin Ahn // Every CFG-changing optimizations should come before this. 431e95056d6SHeejin Ahn addPass(createWebAssemblyLateEHPrepare()); 432e95056d6SHeejin Ahn 4330bb98650SHeejin Ahn // Now that we have a prologue and epilogue and all frame indices are 4340bb98650SHeejin Ahn // rewritten, eliminate SP and FP. This allows them to be stackified, 4350bb98650SHeejin Ahn // colored, and numbered with the rest of the registers. 4360bb98650SHeejin Ahn addPass(createWebAssemblyReplacePhysRegs()); 4370bb98650SHeejin Ahn 438d6f48786SHeejin Ahn // Preparations and optimizations related to register stackification. 4390cfb5f85SDan Gohman if (getOptLevel() != CodeGenOpt::None) { 4400cfb5f85SDan Gohman // LiveIntervals isn't commonly run this late. Re-establish preconditions. 4410cfb5f85SDan Gohman addPass(createWebAssemblyPrepareForLiveIntervals()); 4420cfb5f85SDan Gohman 4430cfb5f85SDan Gohman // Depend on LiveIntervals and perform some optimizations on it. 4440cfb5f85SDan Gohman addPass(createWebAssemblyOptimizeLiveIntervals()); 4450cfb5f85SDan Gohman 446321d5220SHeejin Ahn // Prepare memory intrinsic calls for register stackifying. 447321d5220SHeejin Ahn addPass(createWebAssemblyMemIntrinsicResults()); 4480cfb5f85SDan Gohman 449e040533eSDan Gohman // Mark registers as representing wasm's value stack. This is a key 4500cfb5f85SDan Gohman // code-compression technique in WebAssembly. We run this pass (and 451321d5220SHeejin Ahn // MemIntrinsicResults above) very late, so that it sees as much code as 452321d5220SHeejin Ahn // possible, including code emitted by PEI and expanded by late tail 453321d5220SHeejin Ahn // duplication. 4540cfb5f85SDan Gohman addPass(createWebAssemblyRegStackify()); 4550cfb5f85SDan Gohman 4560cfb5f85SDan Gohman // Run the register coloring pass to reduce the total number of registers. 4570cfb5f85SDan Gohman // This runs after stackification so that it doesn't consider registers 4580cfb5f85SDan Gohman // that become stackified. 4590cfb5f85SDan Gohman addPass(createWebAssemblyRegColoring()); 4600cfb5f85SDan Gohman } 4610cfb5f85SDan Gohman 462f52ee17aSDan Gohman // Sort the blocks of the CFG into topological order, a prerequisite for 463f52ee17aSDan Gohman // BLOCK and LOOP markers. 464f52ee17aSDan Gohman addPass(createWebAssemblyCFGSort()); 465f52ee17aSDan Gohman 466f52ee17aSDan Gohman // Insert BLOCK and LOOP markers. 467950a13cfSDan Gohman addPass(createWebAssemblyCFGStackify()); 4685941bde0SDan Gohman 469e9fd9073SHeejin Ahn // Insert explicit local.get and local.set operators. 470e9fd9073SHeejin Ahn addPass(createWebAssemblyExplicitLocals()); 471e9fd9073SHeejin Ahn 472f0b165a7SDan Gohman // Lower br_unless into br_if. 473f0b165a7SDan Gohman addPass(createWebAssemblyLowerBrUnless()); 474f0b165a7SDan Gohman 4755941bde0SDan Gohman // Perform the very last peephole optimizations on the code. 476b13c91f1SDan Gohman if (getOptLevel() != CodeGenOpt::None) 47781719f85SDan Gohman addPass(createWebAssemblyPeephole()); 478b7c2400fSDan Gohman 479b7c2400fSDan Gohman // Create a mapping from LLVM CodeGen virtual registers to wasm registers. 480b7c2400fSDan Gohman addPass(createWebAssemblyRegNumbering()); 481950a13cfSDan Gohman } 48252221d56SHeejin Ahn 48352221d56SHeejin Ahn yaml::MachineFunctionInfo * 48452221d56SHeejin Ahn WebAssemblyTargetMachine::createDefaultFuncInfoYAML() const { 48552221d56SHeejin Ahn return new yaml::WebAssemblyFunctionInfo(); 48652221d56SHeejin Ahn } 48752221d56SHeejin Ahn 48852221d56SHeejin Ahn yaml::MachineFunctionInfo *WebAssemblyTargetMachine::convertFuncInfoToYAML( 48952221d56SHeejin Ahn const MachineFunction &MF) const { 49052221d56SHeejin Ahn const auto *MFI = MF.getInfo<WebAssemblyFunctionInfo>(); 49152221d56SHeejin Ahn return new yaml::WebAssemblyFunctionInfo(*MFI); 49252221d56SHeejin Ahn } 49352221d56SHeejin Ahn 49452221d56SHeejin Ahn bool WebAssemblyTargetMachine::parseMachineFunctionInfo( 49552221d56SHeejin Ahn const yaml::MachineFunctionInfo &MFI, PerFunctionMIParsingState &PFS, 49652221d56SHeejin Ahn SMDiagnostic &Error, SMRange &SourceRange) const { 49752221d56SHeejin Ahn const auto &YamlMFI = 49852221d56SHeejin Ahn reinterpret_cast<const yaml::WebAssemblyFunctionInfo &>(MFI); 49952221d56SHeejin Ahn MachineFunction &MF = PFS.MF; 50052221d56SHeejin Ahn MF.getInfo<WebAssemblyFunctionInfo>()->initializeBaseYamlFields(YamlMFI); 50152221d56SHeejin Ahn return false; 50252221d56SHeejin Ahn } 503