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" 16*c6c42137SRichard 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 4810e730a2SDan Gohman extern "C" 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); 7940926451SJacob Gravelle initializeWebAssemblyCallIndirectFixupPass(PR); 8010e730a2SDan Gohman } 8110e730a2SDan Gohman 8210e730a2SDan Gohman //===----------------------------------------------------------------------===// 8310e730a2SDan Gohman // WebAssembly Lowering public interface. 8410e730a2SDan Gohman //===----------------------------------------------------------------------===// 8510e730a2SDan Gohman 8641133a3eSDan Gohman static Reloc::Model getEffectiveRelocModel(Optional<Reloc::Model> RM) { 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 } 9341133a3eSDan Gohman return *RM; 9441133a3eSDan Gohman } 9541133a3eSDan Gohman 9610e730a2SDan Gohman /// Create an WebAssembly architecture model. 9710e730a2SDan Gohman /// 9810e730a2SDan Gohman WebAssemblyTargetMachine::WebAssemblyTargetMachine( 9910e730a2SDan Gohman const Target &T, const Triple &TT, StringRef CPU, StringRef FS, 10041133a3eSDan Gohman const TargetOptions &Options, Optional<Reloc::Model> RM, 101314ed201SDaniel Jasper Optional<CodeModel::Model> CM, CodeGenOpt::Level OL, bool JIT) 102bb8507e6SMatthias Braun : LLVMTargetMachine(T, 103bb8507e6SMatthias Braun TT.isArch64Bit() ? "e-m:e-p:64:64-i64:64-n32:64-S128" 1040c6f5ac5SDan Gohman : "e-m:e-p:32:32-i64:64-n32:64-S128", 10541133a3eSDan Gohman TT, CPU, FS, Options, getEffectiveRelocModel(RM), 106ca29c271SDavid Green getEffectiveCodeModel(CM, CodeModel::Large), OL), 107cf2a9e28SSam Clegg TLOF(new WebAssemblyTargetObjectFile()) { 108e040533eSDan Gohman // WebAssembly type-checks instructions, but a noreturn function with a return 109ffa143ceSDerek Schuff // type that doesn't match the context will cause a check failure. So we lower 110ffa143ceSDerek Schuff // LLVM 'unreachable' to ISD::TRAP and then lower that to WebAssembly's 111e040533eSDan Gohman // 'unreachable' instructions which is meant for that case. 112ffa143ceSDerek Schuff this->Options.TrapUnreachable = true; 113ffa143ceSDerek Schuff 114d934cb88SDan Gohman // WebAssembly treats each function as an independent unit. Force 115d934cb88SDan Gohman // -ffunction-sections, effectively, so that we can emit them independently. 116d934cb88SDan Gohman this->Options.FunctionSections = true; 117d934cb88SDan Gohman this->Options.DataSections = true; 118d934cb88SDan Gohman this->Options.UniqueSectionNames = true; 119d934cb88SDan Gohman 12010e730a2SDan Gohman initAsmInfo(); 12110e730a2SDan Gohman 122d85ab7fcSDan Gohman // Note that we don't use setRequiresStructuredCFG(true). It disables 123d85ab7fcSDan Gohman // optimizations than we're ok with, and want, such as critical edge 124d85ab7fcSDan Gohman // splitting and tail merging. 12510e730a2SDan Gohman } 12610e730a2SDan Gohman 12718c56a07SHeejin Ahn WebAssemblyTargetMachine::~WebAssemblyTargetMachine() = default; // anchor. 12810e730a2SDan Gohman 12910e730a2SDan Gohman const WebAssemblySubtarget * 130f3b4f990SThomas Lively WebAssemblyTargetMachine::getSubtargetImpl(std::string CPU, 131f3b4f990SThomas Lively std::string FS) const { 132f3b4f990SThomas Lively auto &I = SubtargetMap[CPU + FS]; 133f3b4f990SThomas Lively if (!I) { 134f3b4f990SThomas Lively I = llvm::make_unique<WebAssemblySubtarget>(TargetTriple, CPU, FS, *this); 135f3b4f990SThomas Lively } 136f3b4f990SThomas Lively return I.get(); 137f3b4f990SThomas Lively } 138f3b4f990SThomas Lively 139f3b4f990SThomas Lively const WebAssemblySubtarget * 14010e730a2SDan Gohman WebAssemblyTargetMachine::getSubtargetImpl(const Function &F) const { 14110e730a2SDan Gohman Attribute CPUAttr = F.getFnAttribute("target-cpu"); 14210e730a2SDan Gohman Attribute FSAttr = F.getFnAttribute("target-features"); 14310e730a2SDan Gohman 14410e730a2SDan Gohman std::string CPU = !CPUAttr.hasAttribute(Attribute::None) 14510e730a2SDan Gohman ? CPUAttr.getValueAsString().str() 14610e730a2SDan Gohman : TargetCPU; 14710e730a2SDan Gohman std::string FS = !FSAttr.hasAttribute(Attribute::None) 14810e730a2SDan Gohman ? FSAttr.getValueAsString().str() 14910e730a2SDan Gohman : TargetFS; 15010e730a2SDan Gohman 15110e730a2SDan Gohman // This needs to be done before we create a new subtarget since any 15210e730a2SDan Gohman // creation will depend on the TM and the code generation flags on the 15310e730a2SDan Gohman // function that reside in TargetOptions. 15410e730a2SDan Gohman resetTargetOptions(F); 155f3b4f990SThomas Lively 156f3b4f990SThomas Lively return getSubtargetImpl(CPU, FS); 15710e730a2SDan Gohman } 15810e730a2SDan Gohman 15910e730a2SDan Gohman namespace { 1603f34e1b8SThomas Lively 1613f34e1b8SThomas Lively class CoalesceFeaturesAndStripAtomics final : public ModulePass { 1623f34e1b8SThomas Lively // Take the union of all features used in the module and use it for each 1633f34e1b8SThomas Lively // function individually, since having multiple feature sets in one module 1643f34e1b8SThomas Lively // currently does not make sense for WebAssembly. If atomics are not enabled, 1653f34e1b8SThomas Lively // also strip atomic operations and thread local storage. 16639b5367cSDerek Schuff static char ID; 1673f34e1b8SThomas Lively WebAssemblyTargetMachine *WasmTM; 16839b5367cSDerek Schuff 16939b5367cSDerek Schuff public: 1703f34e1b8SThomas Lively CoalesceFeaturesAndStripAtomics(WebAssemblyTargetMachine *WasmTM) 1713f34e1b8SThomas Lively : ModulePass(ID), WasmTM(WasmTM) {} 1723f34e1b8SThomas Lively 17339b5367cSDerek Schuff bool runOnModule(Module &M) override { 1743f34e1b8SThomas Lively FeatureBitset Features = coalesceFeatures(M); 1753f34e1b8SThomas Lively 1763f34e1b8SThomas Lively std::string FeatureStr = getFeatureString(Features); 1773f34e1b8SThomas Lively for (auto &F : M) 1783f34e1b8SThomas Lively replaceFeatures(F, FeatureStr); 1793f34e1b8SThomas Lively 1803f34e1b8SThomas Lively bool Stripped = false; 1813f34e1b8SThomas Lively if (!Features[WebAssembly::FeatureAtomics]) { 1823f34e1b8SThomas Lively Stripped |= stripAtomics(M); 1833f34e1b8SThomas Lively Stripped |= stripThreadLocals(M); 1843f34e1b8SThomas Lively } 1853f34e1b8SThomas Lively 1863f34e1b8SThomas Lively recordFeatures(M, Features, Stripped); 1873f34e1b8SThomas Lively 1883f34e1b8SThomas Lively // Conservatively assume we have made some change 18939b5367cSDerek Schuff return true; 19039b5367cSDerek Schuff } 1913f34e1b8SThomas Lively 1923f34e1b8SThomas Lively private: 1933f34e1b8SThomas Lively FeatureBitset coalesceFeatures(const Module &M) { 1943f34e1b8SThomas Lively FeatureBitset Features = 1953f34e1b8SThomas Lively WasmTM 1963f34e1b8SThomas Lively ->getSubtargetImpl(WasmTM->getTargetCPU(), 1973f34e1b8SThomas Lively WasmTM->getTargetFeatureString()) 1983f34e1b8SThomas Lively ->getFeatureBits(); 1993f34e1b8SThomas Lively for (auto &F : M) 2003f34e1b8SThomas Lively Features |= WasmTM->getSubtargetImpl(F)->getFeatureBits(); 2013f34e1b8SThomas Lively return Features; 2023f34e1b8SThomas Lively } 2033f34e1b8SThomas Lively 2043f34e1b8SThomas Lively std::string getFeatureString(const FeatureBitset &Features) { 2053f34e1b8SThomas Lively std::string Ret; 2063f34e1b8SThomas Lively for (const SubtargetFeatureKV &KV : WebAssemblyFeatureKV) { 2073f34e1b8SThomas Lively if (Features[KV.Value]) 2083f34e1b8SThomas Lively Ret += (StringRef("+") + KV.Key + ",").str(); 2093f34e1b8SThomas Lively } 2103f34e1b8SThomas Lively return Ret; 2113f34e1b8SThomas Lively } 2123f34e1b8SThomas Lively 2133f34e1b8SThomas Lively void replaceFeatures(Function &F, const std::string &Features) { 2143f34e1b8SThomas Lively F.removeFnAttr("target-features"); 2153f34e1b8SThomas Lively F.removeFnAttr("target-cpu"); 2163f34e1b8SThomas Lively F.addFnAttr("target-features", Features); 2173f34e1b8SThomas Lively } 2183f34e1b8SThomas Lively 2193f34e1b8SThomas Lively bool stripAtomics(Module &M) { 2203f34e1b8SThomas Lively // Detect whether any atomics will be lowered, since there is no way to tell 2213f34e1b8SThomas Lively // whether the LowerAtomic pass lowers e.g. stores. 2223f34e1b8SThomas Lively bool Stripped = false; 2233f34e1b8SThomas Lively for (auto &F : M) { 2243f34e1b8SThomas Lively for (auto &B : F) { 2253f34e1b8SThomas Lively for (auto &I : B) { 2263f34e1b8SThomas Lively if (I.isAtomic()) { 2273f34e1b8SThomas Lively Stripped = true; 2283f34e1b8SThomas Lively goto done; 2293f34e1b8SThomas Lively } 2303f34e1b8SThomas Lively } 2313f34e1b8SThomas Lively } 2323f34e1b8SThomas Lively } 2333f34e1b8SThomas Lively 2343f34e1b8SThomas Lively done: 2353f34e1b8SThomas Lively if (!Stripped) 2363f34e1b8SThomas Lively return false; 2373f34e1b8SThomas Lively 2383f34e1b8SThomas Lively LowerAtomicPass Lowerer; 2393f34e1b8SThomas Lively FunctionAnalysisManager FAM; 2403f34e1b8SThomas Lively for (auto &F : M) 2413f34e1b8SThomas Lively Lowerer.run(F, FAM); 2423f34e1b8SThomas Lively 2433f34e1b8SThomas Lively return true; 2443f34e1b8SThomas Lively } 2453f34e1b8SThomas Lively 2463f34e1b8SThomas Lively bool stripThreadLocals(Module &M) { 2473f34e1b8SThomas Lively bool Stripped = false; 2483f34e1b8SThomas Lively for (auto &GV : M.globals()) { 2493f34e1b8SThomas Lively if (GV.getThreadLocalMode() != 2503f34e1b8SThomas Lively GlobalValue::ThreadLocalMode::NotThreadLocal) { 2513f34e1b8SThomas Lively Stripped = true; 2523f34e1b8SThomas Lively GV.setThreadLocalMode(GlobalValue::ThreadLocalMode::NotThreadLocal); 2533f34e1b8SThomas Lively } 2543f34e1b8SThomas Lively } 2553f34e1b8SThomas Lively return Stripped; 2563f34e1b8SThomas Lively } 2573f34e1b8SThomas Lively 2583f34e1b8SThomas Lively void recordFeatures(Module &M, const FeatureBitset &Features, bool Stripped) { 2593f34e1b8SThomas Lively for (const SubtargetFeatureKV &KV : WebAssemblyFeatureKV) { 2603f34e1b8SThomas Lively std::string MDKey = (StringRef("wasm-feature-") + KV.Key).str(); 2613f34e1b8SThomas Lively if (KV.Value == WebAssembly::FeatureAtomics && Stripped) { 2623f34e1b8SThomas Lively // "atomics" is special: code compiled without atomics may have had its 2633f34e1b8SThomas Lively // atomics lowered to nonatomic operations. In that case, atomics is 2643f34e1b8SThomas Lively // disallowed to prevent unsafe linking with atomics-enabled objects. 2653f34e1b8SThomas Lively assert(!Features[WebAssembly::FeatureAtomics]); 2663f34e1b8SThomas Lively M.addModuleFlag(Module::ModFlagBehavior::Error, MDKey, 2673f34e1b8SThomas Lively wasm::WASM_FEATURE_PREFIX_DISALLOWED); 2683f34e1b8SThomas Lively } else if (Features[KV.Value]) { 2693f34e1b8SThomas Lively // Otherwise features are marked Used or not mentioned 2703f34e1b8SThomas Lively M.addModuleFlag(Module::ModFlagBehavior::Error, MDKey, 2713f34e1b8SThomas Lively wasm::WASM_FEATURE_PREFIX_USED); 2723f34e1b8SThomas Lively } 2733f34e1b8SThomas Lively } 2743f34e1b8SThomas Lively } 27539b5367cSDerek Schuff }; 2763f34e1b8SThomas Lively char CoalesceFeaturesAndStripAtomics::ID = 0; 27739b5367cSDerek Schuff 27810e730a2SDan Gohman /// WebAssembly Code Generator Pass Configuration Options. 27910e730a2SDan Gohman class WebAssemblyPassConfig final : public TargetPassConfig { 28010e730a2SDan Gohman public: 2815e394c3dSMatthias Braun WebAssemblyPassConfig(WebAssemblyTargetMachine &TM, PassManagerBase &PM) 28210e730a2SDan Gohman : TargetPassConfig(TM, PM) {} 28310e730a2SDan Gohman 28410e730a2SDan Gohman WebAssemblyTargetMachine &getWebAssemblyTargetMachine() const { 28510e730a2SDan Gohman return getTM<WebAssemblyTargetMachine>(); 28610e730a2SDan Gohman } 28710e730a2SDan Gohman 28810e730a2SDan Gohman FunctionPass *createTargetRegisterAllocator(bool) override; 28910e730a2SDan Gohman 29010e730a2SDan Gohman void addIRPasses() override; 29110e730a2SDan Gohman bool addInstSelector() override; 29210e730a2SDan Gohman void addPostRegAlloc() override; 293ad154c83SDerek Schuff bool addGCPasses() override { return false; } 29410e730a2SDan Gohman void addPreEmitPass() override; 295cf55a657SMatt Arsenault 296cf55a657SMatt Arsenault // No reg alloc 297cf55a657SMatt Arsenault bool addRegAssignmentFast() override { return false; } 298cf55a657SMatt Arsenault 299cf55a657SMatt Arsenault // No reg alloc 300cf55a657SMatt Arsenault bool addRegAssignmentOptimized() override { return false; } 30110e730a2SDan Gohman }; 30210e730a2SDan Gohman } // end anonymous namespace 30310e730a2SDan Gohman 30426d11ca4SSanjoy Das TargetTransformInfo 30526d11ca4SSanjoy Das WebAssemblyTargetMachine::getTargetTransformInfo(const Function &F) { 30610e730a2SDan Gohman return TargetTransformInfo(WebAssemblyTTIImpl(this, F)); 30710e730a2SDan Gohman } 30810e730a2SDan Gohman 30910e730a2SDan Gohman TargetPassConfig * 31010e730a2SDan Gohman WebAssemblyTargetMachine::createPassConfig(PassManagerBase &PM) { 3115e394c3dSMatthias Braun return new WebAssemblyPassConfig(*this, PM); 31210e730a2SDan Gohman } 31310e730a2SDan Gohman 31410e730a2SDan Gohman FunctionPass *WebAssemblyPassConfig::createTargetRegisterAllocator(bool) { 31510e730a2SDan Gohman return nullptr; // No reg alloc 31610e730a2SDan Gohman } 31710e730a2SDan Gohman 31810e730a2SDan Gohman //===----------------------------------------------------------------------===// 31910e730a2SDan Gohman // The following functions are called from lib/CodeGen/Passes.cpp to modify 32010e730a2SDan Gohman // the CodeGen pass sequence. 32110e730a2SDan Gohman //===----------------------------------------------------------------------===// 32210e730a2SDan Gohman 32310e730a2SDan Gohman void WebAssemblyPassConfig::addIRPasses() { 3243f34e1b8SThomas Lively // Runs LowerAtomicPass if necessary 3253f34e1b8SThomas Lively addPass(new CoalesceFeaturesAndStripAtomics(&getWebAssemblyTargetMachine())); 3263f34e1b8SThomas Lively 3273f34e1b8SThomas Lively // This is a no-op if atomics are not used in the module 3288b61764cSFrancis Visoiu Mistrih addPass(createAtomicExpandPass()); 32910e730a2SDan Gohman 33092617559SSam Clegg // Add signatures to prototype-less function declarations 33192617559SSam Clegg addPass(createWebAssemblyAddMissingPrototypes()); 33292617559SSam Clegg 333bafe6902SSam Clegg // Lower .llvm.global_dtors into .llvm_global_ctors with __cxa_atexit calls. 334bafe6902SSam Clegg addPass(createWebAssemblyLowerGlobalDtors()); 335bafe6902SSam Clegg 3361b637458SDan Gohman // Fix function bitcasts, as WebAssembly requires caller and callee signatures 3371b637458SDan Gohman // to match. 3381b637458SDan Gohman addPass(createWebAssemblyFixFunctionBitcasts()); 3391b637458SDan Gohman 34081719f85SDan Gohman // Optimize "returned" function attributes. 341b13c91f1SDan Gohman if (getOptLevel() != CodeGenOpt::None) 34281719f85SDan Gohman addPass(createWebAssemblyOptimizeReturned()); 34381719f85SDan Gohman 344c0f18172SHeejin Ahn // If exception handling is not enabled and setjmp/longjmp handling is 345c0f18172SHeejin Ahn // enabled, we lower invokes into calls and delete unreachable landingpad 346c0f18172SHeejin Ahn // blocks. Lowering invokes when there is no EH support is done in 347c0f18172SHeejin Ahn // TargetPassConfig::addPassesToHandleExceptions, but this runs after this 348c0f18172SHeejin Ahn // function and SjLj handling expects all invokes to be lowered before. 3499386bde1SHeejin Ahn if (!EnableEmException && 3509386bde1SHeejin Ahn TM->Options.ExceptionModel == ExceptionHandling::None) { 351c0f18172SHeejin Ahn addPass(createLowerInvokePass()); 352c0f18172SHeejin Ahn // The lower invoke pass may create unreachable code. Remove it in order not 353c0f18172SHeejin Ahn // to process dead blocks in setjmp/longjmp handling. 354c0f18172SHeejin Ahn addPass(createUnreachableBlockEliminationPass()); 355c0f18172SHeejin Ahn } 356c0f18172SHeejin Ahn 357c0f18172SHeejin Ahn // Handle exceptions and setjmp/longjmp if enabled. 358ccdceda1SDerek Schuff if (EnableEmException || EnableEmSjLj) 359ccdceda1SDerek Schuff addPass(createWebAssemblyLowerEmscriptenEHSjLj(EnableEmException, 360ccdceda1SDerek Schuff EnableEmSjLj)); 361f41f67d3SDerek Schuff 36210e730a2SDan Gohman TargetPassConfig::addIRPasses(); 36310e730a2SDan Gohman } 36410e730a2SDan Gohman 36510e730a2SDan Gohman bool WebAssemblyPassConfig::addInstSelector() { 366b0921ca9SDan Gohman (void)TargetPassConfig::addInstSelector(); 36710e730a2SDan Gohman addPass( 36810e730a2SDan Gohman createWebAssemblyISelDag(getWebAssemblyTargetMachine(), getOptLevel())); 3691cf96c0cSDan Gohman // Run the argument-move pass immediately after the ScheduleDAG scheduler 3701cf96c0cSDan Gohman // so that we can fix up the ARGUMENT instructions before anything else 3711cf96c0cSDan Gohman // sees them in the wrong place. 3721cf96c0cSDan Gohman addPass(createWebAssemblyArgumentMove()); 373bb372243SDan Gohman // Set the p2align operands. This information is present during ISel, however 374bb372243SDan Gohman // it's inconvenient to collect. Collect it now, and update the immediate 375bb372243SDan Gohman // operands. 376bb372243SDan Gohman addPass(createWebAssemblySetP2AlignOperands()); 37710e730a2SDan Gohman return false; 37810e730a2SDan Gohman } 37910e730a2SDan Gohman 380600aee98SJF Bastien void WebAssemblyPassConfig::addPostRegAlloc() { 3819c54d3b4SDan Gohman // TODO: The following CodeGen passes don't currently support code containing 3829c54d3b4SDan Gohman // virtual registers. Consider removing their restrictions and re-enabling 3839c54d3b4SDan Gohman // them. 384ad154c83SDerek Schuff 3851eb47368SMatthias Braun // These functions all require the NoVRegs property. 386600aee98SJF Bastien disablePass(&MachineCopyPropagationID); 3877ab1b32bSJun Bum Lim disablePass(&PostRAMachineSinkingID); 388ecabac62SDerek Schuff disablePass(&PostRASchedulerID); 389ecabac62SDerek Schuff disablePass(&FuncletLayoutID); 390ecabac62SDerek Schuff disablePass(&StackMapLivenessID); 391ecabac62SDerek Schuff disablePass(&LiveDebugValuesID); 392fe71ec77SSanjoy Das disablePass(&PatchableFunctionID); 3937ab1b32bSJun Bum Lim disablePass(&ShrinkWrapID); 394950a13cfSDan Gohman 395ef9d6aeaSHeejin Ahn // This pass hurts code size for wasm because it can generate irreducible 396ef9d6aeaSHeejin Ahn // control flow. 397ef9d6aeaSHeejin Ahn disablePass(&MachineBlockPlacementID); 398ef9d6aeaSHeejin Ahn 399b0921ca9SDan Gohman TargetPassConfig::addPostRegAlloc(); 400600aee98SJF Bastien } 40110e730a2SDan Gohman 402950a13cfSDan Gohman void WebAssemblyPassConfig::addPreEmitPass() { 403b0921ca9SDan Gohman TargetPassConfig::addPreEmitPass(); 404b0921ca9SDan Gohman 4056f69783fSDerek Schuff // Rewrite pseudo call_indirect instructions as real instructions. 4066f69783fSDerek Schuff // This needs to run before register stackification, because we change the 4076f69783fSDerek Schuff // order of the arguments. 4086f69783fSDerek Schuff addPass(createWebAssemblyCallIndirectFixup()); 4096f69783fSDerek Schuff 410e95056d6SHeejin Ahn // Eliminate multiple-entry loops. 411e95056d6SHeejin Ahn addPass(createWebAssemblyFixIrreducibleControlFlow()); 412e95056d6SHeejin Ahn 413e95056d6SHeejin Ahn // Do various transformations for exception handling. 414d6f48786SHeejin Ahn // Every CFG-changing optimizations should come before this. 415e95056d6SHeejin Ahn addPass(createWebAssemblyLateEHPrepare()); 416e95056d6SHeejin Ahn 4170bb98650SHeejin Ahn // Now that we have a prologue and epilogue and all frame indices are 4180bb98650SHeejin Ahn // rewritten, eliminate SP and FP. This allows them to be stackified, 4190bb98650SHeejin Ahn // colored, and numbered with the rest of the registers. 4200bb98650SHeejin Ahn addPass(createWebAssemblyReplacePhysRegs()); 4210bb98650SHeejin Ahn 422d6f48786SHeejin Ahn // Preparations and optimizations related to register stackification. 4230cfb5f85SDan Gohman if (getOptLevel() != CodeGenOpt::None) { 4240cfb5f85SDan Gohman // LiveIntervals isn't commonly run this late. Re-establish preconditions. 4250cfb5f85SDan Gohman addPass(createWebAssemblyPrepareForLiveIntervals()); 4260cfb5f85SDan Gohman 4270cfb5f85SDan Gohman // Depend on LiveIntervals and perform some optimizations on it. 4280cfb5f85SDan Gohman addPass(createWebAssemblyOptimizeLiveIntervals()); 4290cfb5f85SDan Gohman 430321d5220SHeejin Ahn // Prepare memory intrinsic calls for register stackifying. 431321d5220SHeejin Ahn addPass(createWebAssemblyMemIntrinsicResults()); 4320cfb5f85SDan Gohman 433e040533eSDan Gohman // Mark registers as representing wasm's value stack. This is a key 4340cfb5f85SDan Gohman // code-compression technique in WebAssembly. We run this pass (and 435321d5220SHeejin Ahn // MemIntrinsicResults above) very late, so that it sees as much code as 436321d5220SHeejin Ahn // possible, including code emitted by PEI and expanded by late tail 437321d5220SHeejin Ahn // duplication. 4380cfb5f85SDan Gohman addPass(createWebAssemblyRegStackify()); 4390cfb5f85SDan Gohman 4400cfb5f85SDan Gohman // Run the register coloring pass to reduce the total number of registers. 4410cfb5f85SDan Gohman // This runs after stackification so that it doesn't consider registers 4420cfb5f85SDan Gohman // that become stackified. 4430cfb5f85SDan Gohman addPass(createWebAssemblyRegColoring()); 4440cfb5f85SDan Gohman } 4450cfb5f85SDan Gohman 446f52ee17aSDan Gohman // Sort the blocks of the CFG into topological order, a prerequisite for 447f52ee17aSDan Gohman // BLOCK and LOOP markers. 448f52ee17aSDan Gohman addPass(createWebAssemblyCFGSort()); 449f52ee17aSDan Gohman 450f52ee17aSDan Gohman // Insert BLOCK and LOOP markers. 451950a13cfSDan Gohman addPass(createWebAssemblyCFGStackify()); 4525941bde0SDan Gohman 453e9fd9073SHeejin Ahn // Insert explicit local.get and local.set operators. 454e9fd9073SHeejin Ahn addPass(createWebAssemblyExplicitLocals()); 455e9fd9073SHeejin Ahn 456f0b165a7SDan Gohman // Lower br_unless into br_if. 457f0b165a7SDan Gohman addPass(createWebAssemblyLowerBrUnless()); 458f0b165a7SDan Gohman 4595941bde0SDan Gohman // Perform the very last peephole optimizations on the code. 460b13c91f1SDan Gohman if (getOptLevel() != CodeGenOpt::None) 46181719f85SDan Gohman addPass(createWebAssemblyPeephole()); 462b7c2400fSDan Gohman 463b7c2400fSDan Gohman // Create a mapping from LLVM CodeGen virtual registers to wasm registers. 464b7c2400fSDan Gohman addPass(createWebAssemblyRegNumbering()); 465950a13cfSDan Gohman } 46652221d56SHeejin Ahn 46752221d56SHeejin Ahn yaml::MachineFunctionInfo * 46852221d56SHeejin Ahn WebAssemblyTargetMachine::createDefaultFuncInfoYAML() const { 46952221d56SHeejin Ahn return new yaml::WebAssemblyFunctionInfo(); 47052221d56SHeejin Ahn } 47152221d56SHeejin Ahn 47252221d56SHeejin Ahn yaml::MachineFunctionInfo *WebAssemblyTargetMachine::convertFuncInfoToYAML( 47352221d56SHeejin Ahn const MachineFunction &MF) const { 47452221d56SHeejin Ahn const auto *MFI = MF.getInfo<WebAssemblyFunctionInfo>(); 47552221d56SHeejin Ahn return new yaml::WebAssemblyFunctionInfo(*MFI); 47652221d56SHeejin Ahn } 47752221d56SHeejin Ahn 47852221d56SHeejin Ahn bool WebAssemblyTargetMachine::parseMachineFunctionInfo( 47952221d56SHeejin Ahn const yaml::MachineFunctionInfo &MFI, PerFunctionMIParsingState &PFS, 48052221d56SHeejin Ahn SMDiagnostic &Error, SMRange &SourceRange) const { 48152221d56SHeejin Ahn const auto &YamlMFI = 48252221d56SHeejin Ahn reinterpret_cast<const yaml::WebAssemblyFunctionInfo &>(MFI); 48352221d56SHeejin Ahn MachineFunction &MF = PFS.MF; 48452221d56SHeejin Ahn MF.getInfo<WebAssemblyFunctionInfo>()->initializeBaseYamlFields(YamlMFI); 48552221d56SHeejin Ahn return false; 48652221d56SHeejin Ahn } 487