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
373bba91f6SHeejin Ahn 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
433bba91f6SHeejin Ahn 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 
482b7fe086SWouter van Oortmerssen // A command-line option to keep implicit locals
492b7fe086SWouter van Oortmerssen // for the purpose of testing with lit/llc ONLY.
502b7fe086SWouter van Oortmerssen // This produces output which is not valid WebAssembly, and is not supported
512b7fe086SWouter van Oortmerssen // by assemblers/disassemblers and other MC based tools.
522b7fe086SWouter van Oortmerssen static cl::opt<bool> WasmDisableExplicitLocals(
532b7fe086SWouter van Oortmerssen     "wasm-disable-explicit-locals", cl::Hidden,
542b7fe086SWouter van Oortmerssen     cl::desc("WebAssembly: output implicit locals in"
552b7fe086SWouter van Oortmerssen              " instruction output for test purposes only."),
562b7fe086SWouter van Oortmerssen     cl::init(false));
572b7fe086SWouter van Oortmerssen 
580dbcb363STom Stellard extern "C" LLVM_EXTERNAL_VISIBILITY void LLVMInitializeWebAssemblyTarget() {
5910e730a2SDan Gohman   // Register the target.
60f42454b9SMehdi Amini   RegisterTargetMachine<WebAssemblyTargetMachine> X(
61f42454b9SMehdi Amini       getTheWebAssemblyTarget32());
62f42454b9SMehdi Amini   RegisterTargetMachine<WebAssemblyTargetMachine> Y(
63f42454b9SMehdi Amini       getTheWebAssemblyTarget64());
64f41f67d3SDerek Schuff 
6540926451SJacob Gravelle   // Register backend passes
6640926451SJacob Gravelle   auto &PR = *PassRegistry::getPassRegistry();
6792617559SSam Clegg   initializeWebAssemblyAddMissingPrototypesPass(PR);
6840926451SJacob Gravelle   initializeWebAssemblyLowerEmscriptenEHSjLjPass(PR);
6940926451SJacob Gravelle   initializeLowerGlobalDtorsPass(PR);
7040926451SJacob Gravelle   initializeFixFunctionBitcastsPass(PR);
7140926451SJacob Gravelle   initializeOptimizeReturnedPass(PR);
7240926451SJacob Gravelle   initializeWebAssemblyArgumentMovePass(PR);
7340926451SJacob Gravelle   initializeWebAssemblySetP2AlignOperandsPass(PR);
7440926451SJacob Gravelle   initializeWebAssemblyReplacePhysRegsPass(PR);
7540926451SJacob Gravelle   initializeWebAssemblyPrepareForLiveIntervalsPass(PR);
7640926451SJacob Gravelle   initializeWebAssemblyOptimizeLiveIntervalsPass(PR);
77321d5220SHeejin Ahn   initializeWebAssemblyMemIntrinsicResultsPass(PR);
7840926451SJacob Gravelle   initializeWebAssemblyRegStackifyPass(PR);
7940926451SJacob Gravelle   initializeWebAssemblyRegColoringPass(PR);
80a64ebb86SHeejin Ahn   initializeWebAssemblyNullifyDebugValueListsPass(PR);
8140926451SJacob Gravelle   initializeWebAssemblyFixIrreducibleControlFlowPass(PR);
824934f76bSHeejin Ahn   initializeWebAssemblyLateEHPreparePass(PR);
8304c48949SHeejin Ahn   initializeWebAssemblyExceptionInfoPass(PR);
8440926451SJacob Gravelle   initializeWebAssemblyCFGSortPass(PR);
8540926451SJacob Gravelle   initializeWebAssemblyCFGStackifyPass(PR);
86e9fd9073SHeejin Ahn   initializeWebAssemblyExplicitLocalsPass(PR);
8740926451SJacob Gravelle   initializeWebAssemblyLowerBrUnlessPass(PR);
8840926451SJacob Gravelle   initializeWebAssemblyRegNumberingPass(PR);
892b7fe086SWouter van Oortmerssen   initializeWebAssemblyDebugFixupPass(PR);
9040926451SJacob Gravelle   initializeWebAssemblyPeepholePass(PR);
919647a6f7SWouter van Oortmerssen   initializeWebAssemblyMCLowerPrePassPass(PR);
9210e730a2SDan Gohman }
9310e730a2SDan Gohman 
9410e730a2SDan Gohman //===----------------------------------------------------------------------===//
9510e730a2SDan Gohman // WebAssembly Lowering public interface.
9610e730a2SDan Gohman //===----------------------------------------------------------------------===//
9710e730a2SDan Gohman 
9853572d04SDan Gohman static Reloc::Model getEffectiveRelocModel(Optional<Reloc::Model> RM,
9953572d04SDan Gohman                                            const Triple &TT) {
10074f5fd4eSSam Clegg   if (!RM.hasValue()) {
10174f5fd4eSSam Clegg     // Default to static relocation model.  This should always be more optimial
10274f5fd4eSSam Clegg     // than PIC since the static linker can determine all global addresses and
10374f5fd4eSSam Clegg     // assume direct function calls.
10474f5fd4eSSam Clegg     return Reloc::Static;
10574f5fd4eSSam Clegg   }
10653572d04SDan Gohman 
10753572d04SDan Gohman   if (!TT.isOSEmscripten()) {
10853572d04SDan Gohman     // Relocation modes other than static are currently implemented in a way
10953572d04SDan Gohman     // that only works for Emscripten, so disable them if we aren't targeting
11053572d04SDan Gohman     // Emscripten.
11153572d04SDan Gohman     return Reloc::Static;
11253572d04SDan Gohman   }
11353572d04SDan Gohman 
11441133a3eSDan Gohman   return *RM;
11541133a3eSDan Gohman }
11641133a3eSDan Gohman 
11710e730a2SDan Gohman /// Create an WebAssembly architecture model.
11810e730a2SDan Gohman ///
11910e730a2SDan Gohman WebAssemblyTargetMachine::WebAssemblyTargetMachine(
12010e730a2SDan Gohman     const Target &T, const Triple &TT, StringRef CPU, StringRef FS,
12141133a3eSDan Gohman     const TargetOptions &Options, Optional<Reloc::Model> RM,
122314ed201SDaniel Jasper     Optional<CodeModel::Model> CM, CodeGenOpt::Level OL, bool JIT)
123*ac02baabSDerek Schuff     : LLVMTargetMachine(
124*ac02baabSDerek Schuff           T,
125d7086af2SPaulo Matos           TT.isArch64Bit()
126*ac02baabSDerek Schuff               ? (TT.isOSEmscripten()
127*ac02baabSDerek Schuff                      ? "e-m:e-p:64:64-i64:64-f128:64-n32:64-S128-ni:1"
128*ac02baabSDerek Schuff                      : "e-m:e-p:64:64-i64:64-n32:64-S128-ni:1")
129*ac02baabSDerek Schuff               : (TT.isOSEmscripten()
130*ac02baabSDerek Schuff                      ? "e-m:e-p:32:32-i64:64-f128:64-n32:64-S128-ni:1"
131*ac02baabSDerek Schuff                      : "e-m:e-p:32:32-i64:64-n32:64-S128-ni:1"),
13253572d04SDan Gohman           TT, CPU, FS, Options, getEffectiveRelocModel(RM, TT),
133ca29c271SDavid Green           getEffectiveCodeModel(CM, CodeModel::Large), OL),
134cf2a9e28SSam Clegg       TLOF(new WebAssemblyTargetObjectFile()) {
135e040533eSDan Gohman   // WebAssembly type-checks instructions, but a noreturn function with a return
136ffa143ceSDerek Schuff   // type that doesn't match the context will cause a check failure. So we lower
137ffa143ceSDerek Schuff   // LLVM 'unreachable' to ISD::TRAP and then lower that to WebAssembly's
138e040533eSDan Gohman   // 'unreachable' instructions which is meant for that case.
139ffa143ceSDerek Schuff   this->Options.TrapUnreachable = true;
140ffa143ceSDerek Schuff 
141d934cb88SDan Gohman   // WebAssembly treats each function as an independent unit. Force
142d934cb88SDan Gohman   // -ffunction-sections, effectively, so that we can emit them independently.
143d934cb88SDan Gohman   this->Options.FunctionSections = true;
144d934cb88SDan Gohman   this->Options.DataSections = true;
145d934cb88SDan Gohman   this->Options.UniqueSectionNames = true;
146d934cb88SDan Gohman 
14710e730a2SDan Gohman   initAsmInfo();
14810e730a2SDan Gohman 
149d85ab7fcSDan Gohman   // Note that we don't use setRequiresStructuredCFG(true). It disables
150d85ab7fcSDan Gohman   // optimizations than we're ok with, and want, such as critical edge
151d85ab7fcSDan Gohman   // splitting and tail merging.
15210e730a2SDan Gohman }
15310e730a2SDan Gohman 
15418c56a07SHeejin Ahn WebAssemblyTargetMachine::~WebAssemblyTargetMachine() = default; // anchor.
15510e730a2SDan Gohman 
15689fe083cSThomas Lively const WebAssemblySubtarget *WebAssemblyTargetMachine::getSubtargetImpl() const {
15789fe083cSThomas Lively   return getSubtargetImpl(std::string(getTargetCPU()),
15889fe083cSThomas Lively                           std::string(getTargetFeatureString()));
15989fe083cSThomas Lively }
16089fe083cSThomas Lively 
16110e730a2SDan Gohman const WebAssemblySubtarget *
162f3b4f990SThomas Lively WebAssemblyTargetMachine::getSubtargetImpl(std::string CPU,
163f3b4f990SThomas Lively                                            std::string FS) const {
164f3b4f990SThomas Lively   auto &I = SubtargetMap[CPU + FS];
165f3b4f990SThomas Lively   if (!I) {
1660eaee545SJonas Devlieghere     I = std::make_unique<WebAssemblySubtarget>(TargetTriple, CPU, FS, *this);
167f3b4f990SThomas Lively   }
168f3b4f990SThomas Lively   return I.get();
169f3b4f990SThomas Lively }
170f3b4f990SThomas Lively 
171f3b4f990SThomas Lively const WebAssemblySubtarget *
17210e730a2SDan Gohman WebAssemblyTargetMachine::getSubtargetImpl(const Function &F) const {
17310e730a2SDan Gohman   Attribute CPUAttr = F.getFnAttribute("target-cpu");
17410e730a2SDan Gohman   Attribute FSAttr = F.getFnAttribute("target-features");
17510e730a2SDan Gohman 
176aab90384SCraig Topper   std::string CPU =
177aab90384SCraig Topper       CPUAttr.isValid() ? CPUAttr.getValueAsString().str() : TargetCPU;
178aab90384SCraig Topper   std::string FS =
179aab90384SCraig Topper       FSAttr.isValid() ? FSAttr.getValueAsString().str() : TargetFS;
18010e730a2SDan Gohman 
18110e730a2SDan Gohman   // This needs to be done before we create a new subtarget since any
18210e730a2SDan Gohman   // creation will depend on the TM and the code generation flags on the
18310e730a2SDan Gohman   // function that reside in TargetOptions.
18410e730a2SDan Gohman   resetTargetOptions(F);
185f3b4f990SThomas Lively 
186f3b4f990SThomas Lively   return getSubtargetImpl(CPU, FS);
18710e730a2SDan Gohman }
18810e730a2SDan Gohman 
18910e730a2SDan Gohman namespace {
1903f34e1b8SThomas Lively 
1913f34e1b8SThomas Lively class CoalesceFeaturesAndStripAtomics final : public ModulePass {
1923f34e1b8SThomas Lively   // Take the union of all features used in the module and use it for each
1933f34e1b8SThomas Lively   // function individually, since having multiple feature sets in one module
1943f34e1b8SThomas Lively   // currently does not make sense for WebAssembly. If atomics are not enabled,
1953f34e1b8SThomas Lively   // also strip atomic operations and thread local storage.
19639b5367cSDerek Schuff   static char ID;
1973f34e1b8SThomas Lively   WebAssemblyTargetMachine *WasmTM;
19839b5367cSDerek Schuff 
19939b5367cSDerek Schuff public:
2003f34e1b8SThomas Lively   CoalesceFeaturesAndStripAtomics(WebAssemblyTargetMachine *WasmTM)
2013f34e1b8SThomas Lively       : ModulePass(ID), WasmTM(WasmTM) {}
2023f34e1b8SThomas Lively 
20339b5367cSDerek Schuff   bool runOnModule(Module &M) override {
2043f34e1b8SThomas Lively     FeatureBitset Features = coalesceFeatures(M);
2053f34e1b8SThomas Lively 
2063f34e1b8SThomas Lively     std::string FeatureStr = getFeatureString(Features);
20789fe083cSThomas Lively     WasmTM->setTargetFeatureString(FeatureStr);
2083f34e1b8SThomas Lively     for (auto &F : M)
2093f34e1b8SThomas Lively       replaceFeatures(F, FeatureStr);
2103f34e1b8SThomas Lively 
21142bba4b8SGuanzhong Chen     bool StrippedAtomics = false;
21242bba4b8SGuanzhong Chen     bool StrippedTLS = false;
2133f34e1b8SThomas Lively 
21442bba4b8SGuanzhong Chen     if (!Features[WebAssembly::FeatureAtomics])
21542bba4b8SGuanzhong Chen       StrippedAtomics = stripAtomics(M);
21642bba4b8SGuanzhong Chen 
21742bba4b8SGuanzhong Chen     if (!Features[WebAssembly::FeatureBulkMemory])
21842bba4b8SGuanzhong Chen       StrippedTLS = stripThreadLocals(M);
21942bba4b8SGuanzhong Chen 
22042bba4b8SGuanzhong Chen     if (StrippedAtomics && !StrippedTLS)
22142bba4b8SGuanzhong Chen       stripThreadLocals(M);
22242bba4b8SGuanzhong Chen     else if (StrippedTLS && !StrippedAtomics)
22342bba4b8SGuanzhong Chen       stripAtomics(M);
22442bba4b8SGuanzhong Chen 
22542bba4b8SGuanzhong Chen     recordFeatures(M, Features, StrippedAtomics || StrippedTLS);
2263f34e1b8SThomas Lively 
2273f34e1b8SThomas Lively     // Conservatively assume we have made some change
22839b5367cSDerek Schuff     return true;
22939b5367cSDerek Schuff   }
2303f34e1b8SThomas Lively 
2313f34e1b8SThomas Lively private:
2323f34e1b8SThomas Lively   FeatureBitset coalesceFeatures(const Module &M) {
2333f34e1b8SThomas Lively     FeatureBitset Features =
2343f34e1b8SThomas Lively         WasmTM
235adcd0268SBenjamin Kramer             ->getSubtargetImpl(std::string(WasmTM->getTargetCPU()),
236adcd0268SBenjamin Kramer                                std::string(WasmTM->getTargetFeatureString()))
2373f34e1b8SThomas Lively             ->getFeatureBits();
2383f34e1b8SThomas Lively     for (auto &F : M)
2393f34e1b8SThomas Lively       Features |= WasmTM->getSubtargetImpl(F)->getFeatureBits();
2403f34e1b8SThomas Lively     return Features;
2413f34e1b8SThomas Lively   }
2423f34e1b8SThomas Lively 
2433f34e1b8SThomas Lively   std::string getFeatureString(const FeatureBitset &Features) {
2443f34e1b8SThomas Lively     std::string Ret;
2453f34e1b8SThomas Lively     for (const SubtargetFeatureKV &KV : WebAssemblyFeatureKV) {
2463f34e1b8SThomas Lively       if (Features[KV.Value])
2473f34e1b8SThomas Lively         Ret += (StringRef("+") + KV.Key + ",").str();
2483f34e1b8SThomas Lively     }
2493f34e1b8SThomas Lively     return Ret;
2503f34e1b8SThomas Lively   }
2513f34e1b8SThomas Lively 
2523f34e1b8SThomas Lively   void replaceFeatures(Function &F, const std::string &Features) {
2533f34e1b8SThomas Lively     F.removeFnAttr("target-features");
2543f34e1b8SThomas Lively     F.removeFnAttr("target-cpu");
2553f34e1b8SThomas Lively     F.addFnAttr("target-features", Features);
2563f34e1b8SThomas Lively   }
2573f34e1b8SThomas Lively 
2583f34e1b8SThomas Lively   bool stripAtomics(Module &M) {
2593f34e1b8SThomas Lively     // Detect whether any atomics will be lowered, since there is no way to tell
2603f34e1b8SThomas Lively     // whether the LowerAtomic pass lowers e.g. stores.
2613f34e1b8SThomas Lively     bool Stripped = false;
2623f34e1b8SThomas Lively     for (auto &F : M) {
2633f34e1b8SThomas Lively       for (auto &B : F) {
2643f34e1b8SThomas Lively         for (auto &I : B) {
2653f34e1b8SThomas Lively           if (I.isAtomic()) {
2663f34e1b8SThomas Lively             Stripped = true;
2673f34e1b8SThomas Lively             goto done;
2683f34e1b8SThomas Lively           }
2693f34e1b8SThomas Lively         }
2703f34e1b8SThomas Lively       }
2713f34e1b8SThomas Lively     }
2723f34e1b8SThomas Lively 
2733f34e1b8SThomas Lively   done:
2743f34e1b8SThomas Lively     if (!Stripped)
2753f34e1b8SThomas Lively       return false;
2763f34e1b8SThomas Lively 
2773f34e1b8SThomas Lively     LowerAtomicPass Lowerer;
2783f34e1b8SThomas Lively     FunctionAnalysisManager FAM;
2793f34e1b8SThomas Lively     for (auto &F : M)
2803f34e1b8SThomas Lively       Lowerer.run(F, FAM);
2813f34e1b8SThomas Lively 
2823f34e1b8SThomas Lively     return true;
2833f34e1b8SThomas Lively   }
2843f34e1b8SThomas Lively 
2853f34e1b8SThomas Lively   bool stripThreadLocals(Module &M) {
2863f34e1b8SThomas Lively     bool Stripped = false;
2873f34e1b8SThomas Lively     for (auto &GV : M.globals()) {
288a28a4662SSam Clegg       if (GV.isThreadLocal()) {
2893f34e1b8SThomas Lively         Stripped = true;
290a28a4662SSam Clegg         GV.setThreadLocal(false);
2913f34e1b8SThomas Lively       }
2923f34e1b8SThomas Lively     }
2933f34e1b8SThomas Lively     return Stripped;
2943f34e1b8SThomas Lively   }
2953f34e1b8SThomas Lively 
2963f34e1b8SThomas Lively   void recordFeatures(Module &M, const FeatureBitset &Features, bool Stripped) {
2973f34e1b8SThomas Lively     for (const SubtargetFeatureKV &KV : WebAssemblyFeatureKV) {
298a1ae9566SThomas Lively       if (Features[KV.Value]) {
299a1ae9566SThomas Lively         // Mark features as used
3003f34e1b8SThomas Lively         std::string MDKey = (StringRef("wasm-feature-") + KV.Key).str();
3013f34e1b8SThomas Lively         M.addModuleFlag(Module::ModFlagBehavior::Error, MDKey,
3023f34e1b8SThomas Lively                         wasm::WASM_FEATURE_PREFIX_USED);
3033f34e1b8SThomas Lively       }
3043f34e1b8SThomas Lively     }
305a1ae9566SThomas Lively     // Code compiled without atomics or bulk-memory may have had its atomics or
306a1ae9566SThomas Lively     // thread-local data lowered to nonatomic operations or non-thread-local
307a1ae9566SThomas Lively     // data. In that case, we mark the pseudo-feature "shared-mem" as disallowed
308a1ae9566SThomas Lively     // to tell the linker that it would be unsafe to allow this code ot be used
309a1ae9566SThomas Lively     // in a module with shared memory.
310a1ae9566SThomas Lively     if (Stripped) {
311a1ae9566SThomas Lively       M.addModuleFlag(Module::ModFlagBehavior::Error, "wasm-feature-shared-mem",
312a1ae9566SThomas Lively                       wasm::WASM_FEATURE_PREFIX_DISALLOWED);
313a1ae9566SThomas Lively     }
3143f34e1b8SThomas Lively   }
31539b5367cSDerek Schuff };
3163f34e1b8SThomas Lively char CoalesceFeaturesAndStripAtomics::ID = 0;
31739b5367cSDerek Schuff 
31810e730a2SDan Gohman /// WebAssembly Code Generator Pass Configuration Options.
31910e730a2SDan Gohman class WebAssemblyPassConfig final : public TargetPassConfig {
32010e730a2SDan Gohman public:
3215e394c3dSMatthias Braun   WebAssemblyPassConfig(WebAssemblyTargetMachine &TM, PassManagerBase &PM)
32210e730a2SDan Gohman       : TargetPassConfig(TM, PM) {}
32310e730a2SDan Gohman 
32410e730a2SDan Gohman   WebAssemblyTargetMachine &getWebAssemblyTargetMachine() const {
32510e730a2SDan Gohman     return getTM<WebAssemblyTargetMachine>();
32610e730a2SDan Gohman   }
32710e730a2SDan Gohman 
32810e730a2SDan Gohman   FunctionPass *createTargetRegisterAllocator(bool) override;
32910e730a2SDan Gohman 
33010e730a2SDan Gohman   void addIRPasses() override;
33110e730a2SDan Gohman   bool addInstSelector() override;
33210e730a2SDan Gohman   void addPostRegAlloc() override;
333ad154c83SDerek Schuff   bool addGCPasses() override { return false; }
33410e730a2SDan Gohman   void addPreEmitPass() override;
335cf55a657SMatt Arsenault 
336cf55a657SMatt Arsenault   // No reg alloc
337c9122ddeSMatt Arsenault   bool addRegAssignAndRewriteFast() override { return false; }
338cf55a657SMatt Arsenault 
339cf55a657SMatt Arsenault   // No reg alloc
340c9122ddeSMatt Arsenault   bool addRegAssignAndRewriteOptimized() override { return false; }
34110e730a2SDan Gohman };
34210e730a2SDan Gohman } // end anonymous namespace
34310e730a2SDan Gohman 
34426d11ca4SSanjoy Das TargetTransformInfo
34526d11ca4SSanjoy Das WebAssemblyTargetMachine::getTargetTransformInfo(const Function &F) {
34610e730a2SDan Gohman   return TargetTransformInfo(WebAssemblyTTIImpl(this, F));
34710e730a2SDan Gohman }
34810e730a2SDan Gohman 
34910e730a2SDan Gohman TargetPassConfig *
35010e730a2SDan Gohman WebAssemblyTargetMachine::createPassConfig(PassManagerBase &PM) {
3515e394c3dSMatthias Braun   return new WebAssemblyPassConfig(*this, PM);
35210e730a2SDan Gohman }
35310e730a2SDan Gohman 
35410e730a2SDan Gohman FunctionPass *WebAssemblyPassConfig::createTargetRegisterAllocator(bool) {
35510e730a2SDan Gohman   return nullptr; // No reg alloc
35610e730a2SDan Gohman }
35710e730a2SDan Gohman 
35810e730a2SDan Gohman //===----------------------------------------------------------------------===//
35910e730a2SDan Gohman // The following functions are called from lib/CodeGen/Passes.cpp to modify
36010e730a2SDan Gohman // the CodeGen pass sequence.
36110e730a2SDan Gohman //===----------------------------------------------------------------------===//
36210e730a2SDan Gohman 
36310e730a2SDan Gohman void WebAssemblyPassConfig::addIRPasses() {
36489fe083cSThomas Lively   // Lower atomics and TLS if necessary
36589fe083cSThomas Lively   addPass(new CoalesceFeaturesAndStripAtomics(&getWebAssemblyTargetMachine()));
36689fe083cSThomas Lively 
36789fe083cSThomas Lively   // This is a no-op if atomics are not used in the module
36889fe083cSThomas Lively   addPass(createAtomicExpandPass());
36989fe083cSThomas Lively 
37092617559SSam Clegg   // Add signatures to prototype-less function declarations
37192617559SSam Clegg   addPass(createWebAssemblyAddMissingPrototypes());
37292617559SSam Clegg 
373bafe6902SSam Clegg   // Lower .llvm.global_dtors into .llvm_global_ctors with __cxa_atexit calls.
374bafe6902SSam Clegg   addPass(createWebAssemblyLowerGlobalDtors());
375bafe6902SSam Clegg 
3761b637458SDan Gohman   // Fix function bitcasts, as WebAssembly requires caller and callee signatures
3771b637458SDan Gohman   // to match.
3781b637458SDan Gohman   addPass(createWebAssemblyFixFunctionBitcasts());
3791b637458SDan Gohman 
38081719f85SDan Gohman   // Optimize "returned" function attributes.
381b13c91f1SDan Gohman   if (getOptLevel() != CodeGenOpt::None)
38281719f85SDan Gohman     addPass(createWebAssemblyOptimizeReturned());
38381719f85SDan Gohman 
384c0f18172SHeejin Ahn   // If exception handling is not enabled and setjmp/longjmp handling is
385c0f18172SHeejin Ahn   // enabled, we lower invokes into calls and delete unreachable landingpad
386c0f18172SHeejin Ahn   // blocks. Lowering invokes when there is no EH support is done in
387c0f18172SHeejin Ahn   // TargetPassConfig::addPassesToHandleExceptions, but this runs after this
388c0f18172SHeejin Ahn   // function and SjLj handling expects all invokes to be lowered before.
3899386bde1SHeejin Ahn   if (!EnableEmException &&
3909386bde1SHeejin Ahn       TM->Options.ExceptionModel == ExceptionHandling::None) {
391c0f18172SHeejin Ahn     addPass(createLowerInvokePass());
392c0f18172SHeejin Ahn     // The lower invoke pass may create unreachable code. Remove it in order not
393c0f18172SHeejin Ahn     // to process dead blocks in setjmp/longjmp handling.
394c0f18172SHeejin Ahn     addPass(createUnreachableBlockEliminationPass());
395c0f18172SHeejin Ahn   }
396c0f18172SHeejin Ahn 
397c0f18172SHeejin Ahn   // Handle exceptions and setjmp/longjmp if enabled.
398ccdceda1SDerek Schuff   if (EnableEmException || EnableEmSjLj)
399ccdceda1SDerek Schuff     addPass(createWebAssemblyLowerEmscriptenEHSjLj(EnableEmException,
400ccdceda1SDerek Schuff                                                    EnableEmSjLj));
401f41f67d3SDerek Schuff 
402ec4be576SDerek Schuff   // Expand indirectbr instructions to switches.
403ec4be576SDerek Schuff   addPass(createIndirectBrExpandPass());
404ec4be576SDerek Schuff 
40510e730a2SDan Gohman   TargetPassConfig::addIRPasses();
40610e730a2SDan Gohman }
40710e730a2SDan Gohman 
40810e730a2SDan Gohman bool WebAssemblyPassConfig::addInstSelector() {
409b0921ca9SDan Gohman   (void)TargetPassConfig::addInstSelector();
41010e730a2SDan Gohman   addPass(
41110e730a2SDan Gohman       createWebAssemblyISelDag(getWebAssemblyTargetMachine(), getOptLevel()));
4121cf96c0cSDan Gohman   // Run the argument-move pass immediately after the ScheduleDAG scheduler
4131cf96c0cSDan Gohman   // so that we can fix up the ARGUMENT instructions before anything else
4141cf96c0cSDan Gohman   // sees them in the wrong place.
4151cf96c0cSDan Gohman   addPass(createWebAssemblyArgumentMove());
416bb372243SDan Gohman   // Set the p2align operands. This information is present during ISel, however
417bb372243SDan Gohman   // it's inconvenient to collect. Collect it now, and update the immediate
418bb372243SDan Gohman   // operands.
419bb372243SDan Gohman   addPass(createWebAssemblySetP2AlignOperands());
4207f50c15bSThomas Lively 
4217f50c15bSThomas Lively   // Eliminate range checks and add default targets to br_table instructions.
4227f50c15bSThomas Lively   addPass(createWebAssemblyFixBrTableDefaults());
4237f50c15bSThomas Lively 
42410e730a2SDan Gohman   return false;
42510e730a2SDan Gohman }
42610e730a2SDan Gohman 
427600aee98SJF Bastien void WebAssemblyPassConfig::addPostRegAlloc() {
4289c54d3b4SDan Gohman   // TODO: The following CodeGen passes don't currently support code containing
4299c54d3b4SDan Gohman   // virtual registers. Consider removing their restrictions and re-enabling
4309c54d3b4SDan Gohman   // them.
431ad154c83SDerek Schuff 
4321eb47368SMatthias Braun   // These functions all require the NoVRegs property.
433600aee98SJF Bastien   disablePass(&MachineCopyPropagationID);
4347ab1b32bSJun Bum Lim   disablePass(&PostRAMachineSinkingID);
435ecabac62SDerek Schuff   disablePass(&PostRASchedulerID);
436ecabac62SDerek Schuff   disablePass(&FuncletLayoutID);
437ecabac62SDerek Schuff   disablePass(&StackMapLivenessID);
438ecabac62SDerek Schuff   disablePass(&LiveDebugValuesID);
439fe71ec77SSanjoy Das   disablePass(&PatchableFunctionID);
4407ab1b32bSJun Bum Lim   disablePass(&ShrinkWrapID);
441950a13cfSDan Gohman 
442ef9d6aeaSHeejin Ahn   // This pass hurts code size for wasm because it can generate irreducible
443ef9d6aeaSHeejin Ahn   // control flow.
444ef9d6aeaSHeejin Ahn   disablePass(&MachineBlockPlacementID);
445ef9d6aeaSHeejin Ahn 
446b0921ca9SDan Gohman   TargetPassConfig::addPostRegAlloc();
447600aee98SJF Bastien }
44810e730a2SDan Gohman 
449950a13cfSDan Gohman void WebAssemblyPassConfig::addPreEmitPass() {
450b0921ca9SDan Gohman   TargetPassConfig::addPreEmitPass();
451b0921ca9SDan Gohman 
452a64ebb86SHeejin Ahn   // Nullify DBG_VALUE_LISTs that we cannot handle.
453a64ebb86SHeejin Ahn   addPass(createWebAssemblyNullifyDebugValueLists());
454a64ebb86SHeejin Ahn 
455e95056d6SHeejin Ahn   // Eliminate multiple-entry loops.
456e95056d6SHeejin Ahn   addPass(createWebAssemblyFixIrreducibleControlFlow());
457e95056d6SHeejin Ahn 
458e95056d6SHeejin Ahn   // Do various transformations for exception handling.
459d6f48786SHeejin Ahn   // Every CFG-changing optimizations should come before this.
4609e4eadebSHeejin Ahn   if (TM->Options.ExceptionModel == ExceptionHandling::Wasm)
461e95056d6SHeejin Ahn     addPass(createWebAssemblyLateEHPrepare());
462e95056d6SHeejin Ahn 
4630bb98650SHeejin Ahn   // Now that we have a prologue and epilogue and all frame indices are
4640bb98650SHeejin Ahn   // rewritten, eliminate SP and FP. This allows them to be stackified,
4650bb98650SHeejin Ahn   // colored, and numbered with the rest of the registers.
4660bb98650SHeejin Ahn   addPass(createWebAssemblyReplacePhysRegs());
4670bb98650SHeejin Ahn 
468d6f48786SHeejin Ahn   // Preparations and optimizations related to register stackification.
4690cfb5f85SDan Gohman   if (getOptLevel() != CodeGenOpt::None) {
4700cfb5f85SDan Gohman     // LiveIntervals isn't commonly run this late. Re-establish preconditions.
4710cfb5f85SDan Gohman     addPass(createWebAssemblyPrepareForLiveIntervals());
4720cfb5f85SDan Gohman 
4730cfb5f85SDan Gohman     // Depend on LiveIntervals and perform some optimizations on it.
4740cfb5f85SDan Gohman     addPass(createWebAssemblyOptimizeLiveIntervals());
4750cfb5f85SDan Gohman 
476321d5220SHeejin Ahn     // Prepare memory intrinsic calls for register stackifying.
477321d5220SHeejin Ahn     addPass(createWebAssemblyMemIntrinsicResults());
4780cfb5f85SDan Gohman 
479e040533eSDan Gohman     // Mark registers as representing wasm's value stack. This is a key
4800cfb5f85SDan Gohman     // code-compression technique in WebAssembly. We run this pass (and
481321d5220SHeejin Ahn     // MemIntrinsicResults above) very late, so that it sees as much code as
482321d5220SHeejin Ahn     // possible, including code emitted by PEI and expanded by late tail
483321d5220SHeejin Ahn     // duplication.
4840cfb5f85SDan Gohman     addPass(createWebAssemblyRegStackify());
4850cfb5f85SDan Gohman 
4860cfb5f85SDan Gohman     // Run the register coloring pass to reduce the total number of registers.
4870cfb5f85SDan Gohman     // This runs after stackification so that it doesn't consider registers
4880cfb5f85SDan Gohman     // that become stackified.
4890cfb5f85SDan Gohman     addPass(createWebAssemblyRegColoring());
4900cfb5f85SDan Gohman   }
4910cfb5f85SDan Gohman 
492f52ee17aSDan Gohman   // Sort the blocks of the CFG into topological order, a prerequisite for
493f52ee17aSDan Gohman   // BLOCK and LOOP markers.
494f52ee17aSDan Gohman   addPass(createWebAssemblyCFGSort());
495f52ee17aSDan Gohman 
496f52ee17aSDan Gohman   // Insert BLOCK and LOOP markers.
497950a13cfSDan Gohman   addPass(createWebAssemblyCFGStackify());
4985941bde0SDan Gohman 
499e9fd9073SHeejin Ahn   // Insert explicit local.get and local.set operators.
5002b7fe086SWouter van Oortmerssen   if (!WasmDisableExplicitLocals)
501e9fd9073SHeejin Ahn     addPass(createWebAssemblyExplicitLocals());
502e9fd9073SHeejin Ahn 
503f0b165a7SDan Gohman   // Lower br_unless into br_if.
504f0b165a7SDan Gohman   addPass(createWebAssemblyLowerBrUnless());
505f0b165a7SDan Gohman 
5065941bde0SDan Gohman   // Perform the very last peephole optimizations on the code.
507b13c91f1SDan Gohman   if (getOptLevel() != CodeGenOpt::None)
50881719f85SDan Gohman     addPass(createWebAssemblyPeephole());
509b7c2400fSDan Gohman 
510b7c2400fSDan Gohman   // Create a mapping from LLVM CodeGen virtual registers to wasm registers.
511b7c2400fSDan Gohman   addPass(createWebAssemblyRegNumbering());
5122b7fe086SWouter van Oortmerssen 
5132b7fe086SWouter van Oortmerssen   // Fix debug_values whose defs have been stackified.
5142b7fe086SWouter van Oortmerssen   if (!WasmDisableExplicitLocals)
5152b7fe086SWouter van Oortmerssen     addPass(createWebAssemblyDebugFixup());
5169647a6f7SWouter van Oortmerssen 
5179647a6f7SWouter van Oortmerssen   // Collect information to prepare for MC lowering / asm printing.
5189647a6f7SWouter van Oortmerssen   addPass(createWebAssemblyMCLowerPrePass());
519950a13cfSDan Gohman }
52052221d56SHeejin Ahn 
52152221d56SHeejin Ahn yaml::MachineFunctionInfo *
52252221d56SHeejin Ahn WebAssemblyTargetMachine::createDefaultFuncInfoYAML() const {
52352221d56SHeejin Ahn   return new yaml::WebAssemblyFunctionInfo();
52452221d56SHeejin Ahn }
52552221d56SHeejin Ahn 
52652221d56SHeejin Ahn yaml::MachineFunctionInfo *WebAssemblyTargetMachine::convertFuncInfoToYAML(
52752221d56SHeejin Ahn     const MachineFunction &MF) const {
52852221d56SHeejin Ahn   const auto *MFI = MF.getInfo<WebAssemblyFunctionInfo>();
52952221d56SHeejin Ahn   return new yaml::WebAssemblyFunctionInfo(*MFI);
53052221d56SHeejin Ahn }
53152221d56SHeejin Ahn 
53252221d56SHeejin Ahn bool WebAssemblyTargetMachine::parseMachineFunctionInfo(
53352221d56SHeejin Ahn     const yaml::MachineFunctionInfo &MFI, PerFunctionMIParsingState &PFS,
53452221d56SHeejin Ahn     SMDiagnostic &Error, SMRange &SourceRange) const {
53552221d56SHeejin Ahn   const auto &YamlMFI =
53652221d56SHeejin Ahn       reinterpret_cast<const yaml::WebAssemblyFunctionInfo &>(MFI);
53752221d56SHeejin Ahn   MachineFunction &MF = PFS.MF;
53852221d56SHeejin Ahn   MF.getInfo<WebAssemblyFunctionInfo>()->initializeBaseYamlFields(YamlMFI);
53952221d56SHeejin Ahn   return false;
54052221d56SHeejin Ahn }
541