110e730a2SDan Gohman //===- WebAssemblyTargetMachine.cpp - Define TargetMachine for WebAssembly -==//
210e730a2SDan Gohman //
310e730a2SDan Gohman //                     The LLVM Compiler Infrastructure
410e730a2SDan Gohman //
510e730a2SDan Gohman // This file is distributed under the University of Illinois Open Source
610e730a2SDan Gohman // License. See LICENSE.TXT for details.
710e730a2SDan Gohman //
810e730a2SDan Gohman //===----------------------------------------------------------------------===//
910e730a2SDan Gohman ///
1010e730a2SDan Gohman /// \file
1110e730a2SDan Gohman /// \brief This file defines the WebAssembly-specific subclass of TargetMachine.
1210e730a2SDan Gohman ///
1310e730a2SDan Gohman //===----------------------------------------------------------------------===//
1410e730a2SDan Gohman 
1510e730a2SDan Gohman #include "WebAssembly.h"
1610e730a2SDan Gohman #include "MCTargetDesc/WebAssemblyMCTargetDesc.h"
1710e730a2SDan Gohman #include "WebAssemblyTargetMachine.h"
185bf22fc8SDan Gohman #include "WebAssemblyTargetObjectFile.h"
1910e730a2SDan Gohman #include "WebAssemblyTargetTransformInfo.h"
2010e730a2SDan Gohman #include "llvm/CodeGen/MachineFunctionPass.h"
2110e730a2SDan Gohman #include "llvm/CodeGen/Passes.h"
2210e730a2SDan Gohman #include "llvm/CodeGen/RegAllocRegistry.h"
2331d19d43SMatthias Braun #include "llvm/CodeGen/TargetPassConfig.h"
2410e730a2SDan Gohman #include "llvm/IR/Function.h"
2510e730a2SDan Gohman #include "llvm/Support/TargetRegistry.h"
2610e730a2SDan Gohman #include "llvm/Target/TargetOptions.h"
2703855df1SJF Bastien #include "llvm/Transforms/Scalar.h"
2810e730a2SDan Gohman using namespace llvm;
2910e730a2SDan Gohman 
3010e730a2SDan Gohman #define DEBUG_TYPE "wasm"
3110e730a2SDan Gohman 
32*f41f67d3SDerek Schuff // Emscripten's asm.js-style exception handling
33*f41f67d3SDerek Schuff static cl::opt<bool> EnableEmExceptionHandling(
34*f41f67d3SDerek Schuff     "wasm-em-exception-handling",
35*f41f67d3SDerek Schuff     cl::desc("WebAssembly Emscripten-style exception handling"),
36*f41f67d3SDerek Schuff     cl::init(false));
37*f41f67d3SDerek Schuff 
3810e730a2SDan Gohman extern "C" void LLVMInitializeWebAssemblyTarget() {
3910e730a2SDan Gohman   // Register the target.
40d82494bbSDan Gohman   RegisterTargetMachine<WebAssemblyTargetMachine> X(TheWebAssemblyTarget32);
41d82494bbSDan Gohman   RegisterTargetMachine<WebAssemblyTargetMachine> Y(TheWebAssemblyTarget64);
42*f41f67d3SDerek Schuff 
43*f41f67d3SDerek Schuff   // Register exception handling pass to opt
44*f41f67d3SDerek Schuff   initializeWebAssemblyLowerEmscriptenExceptionsPass(
45*f41f67d3SDerek Schuff       *PassRegistry::getPassRegistry());
4610e730a2SDan Gohman }
4710e730a2SDan Gohman 
4810e730a2SDan Gohman //===----------------------------------------------------------------------===//
4910e730a2SDan Gohman // WebAssembly Lowering public interface.
5010e730a2SDan Gohman //===----------------------------------------------------------------------===//
5110e730a2SDan Gohman 
5241133a3eSDan Gohman static Reloc::Model getEffectiveRelocModel(Optional<Reloc::Model> RM) {
5341133a3eSDan Gohman   if (!RM.hasValue())
5441133a3eSDan Gohman     return Reloc::PIC_;
5541133a3eSDan Gohman   return *RM;
5641133a3eSDan Gohman }
5741133a3eSDan Gohman 
5810e730a2SDan Gohman /// Create an WebAssembly architecture model.
5910e730a2SDan Gohman ///
6010e730a2SDan Gohman WebAssemblyTargetMachine::WebAssemblyTargetMachine(
6110e730a2SDan Gohman     const Target &T, const Triple &TT, StringRef CPU, StringRef FS,
6241133a3eSDan Gohman     const TargetOptions &Options, Optional<Reloc::Model> RM,
6341133a3eSDan Gohman     CodeModel::Model CM, CodeGenOpt::Level OL)
640c6f5ac5SDan Gohman     : LLVMTargetMachine(T,
650c6f5ac5SDan Gohman                         TT.isArch64Bit() ? "e-m:e-p:64:64-i64:64-n32:64-S128"
660c6f5ac5SDan Gohman                                          : "e-m:e-p:32:32-i64:64-n32:64-S128",
6741133a3eSDan Gohman                         TT, CPU, FS, Options, getEffectiveRelocModel(RM),
6841133a3eSDan Gohman                         CM, OL),
695bf22fc8SDan Gohman       TLOF(make_unique<WebAssemblyTargetObjectFile>()) {
70ffa143ceSDerek Schuff   // WebAssembly type-checks expressions, but a noreturn function with a return
71ffa143ceSDerek Schuff   // type that doesn't match the context will cause a check failure. So we lower
72ffa143ceSDerek Schuff   // LLVM 'unreachable' to ISD::TRAP and then lower that to WebAssembly's
73ffa143ceSDerek Schuff   // 'unreachable' expression which is meant for that case.
74ffa143ceSDerek Schuff   this->Options.TrapUnreachable = true;
75ffa143ceSDerek Schuff 
7610e730a2SDan Gohman   initAsmInfo();
7710e730a2SDan Gohman 
78d85ab7fcSDan Gohman   // Note that we don't use setRequiresStructuredCFG(true). It disables
79d85ab7fcSDan Gohman   // optimizations than we're ok with, and want, such as critical edge
80d85ab7fcSDan Gohman   // splitting and tail merging.
8110e730a2SDan Gohman }
8210e730a2SDan Gohman 
8310e730a2SDan Gohman WebAssemblyTargetMachine::~WebAssemblyTargetMachine() {}
8410e730a2SDan Gohman 
8510e730a2SDan Gohman const WebAssemblySubtarget *
8610e730a2SDan Gohman WebAssemblyTargetMachine::getSubtargetImpl(const Function &F) const {
8710e730a2SDan Gohman   Attribute CPUAttr = F.getFnAttribute("target-cpu");
8810e730a2SDan Gohman   Attribute FSAttr = F.getFnAttribute("target-features");
8910e730a2SDan Gohman 
9010e730a2SDan Gohman   std::string CPU = !CPUAttr.hasAttribute(Attribute::None)
9110e730a2SDan Gohman                         ? CPUAttr.getValueAsString().str()
9210e730a2SDan Gohman                         : TargetCPU;
9310e730a2SDan Gohman   std::string FS = !FSAttr.hasAttribute(Attribute::None)
9410e730a2SDan Gohman                        ? FSAttr.getValueAsString().str()
9510e730a2SDan Gohman                        : TargetFS;
9610e730a2SDan Gohman 
9710e730a2SDan Gohman   auto &I = SubtargetMap[CPU + FS];
9810e730a2SDan Gohman   if (!I) {
9910e730a2SDan Gohman     // This needs to be done before we create a new subtarget since any
10010e730a2SDan Gohman     // creation will depend on the TM and the code generation flags on the
10110e730a2SDan Gohman     // function that reside in TargetOptions.
10210e730a2SDan Gohman     resetTargetOptions(F);
1033adc7ce9SRafael Espindola     I = llvm::make_unique<WebAssemblySubtarget>(TargetTriple, CPU, FS, *this);
10410e730a2SDan Gohman   }
10510e730a2SDan Gohman   return I.get();
10610e730a2SDan Gohman }
10710e730a2SDan Gohman 
10810e730a2SDan Gohman namespace {
10910e730a2SDan Gohman /// WebAssembly Code Generator Pass Configuration Options.
11010e730a2SDan Gohman class WebAssemblyPassConfig final : public TargetPassConfig {
11110e730a2SDan Gohman public:
11210e730a2SDan Gohman   WebAssemblyPassConfig(WebAssemblyTargetMachine *TM, PassManagerBase &PM)
11310e730a2SDan Gohman       : TargetPassConfig(TM, PM) {}
11410e730a2SDan Gohman 
11510e730a2SDan Gohman   WebAssemblyTargetMachine &getWebAssemblyTargetMachine() const {
11610e730a2SDan Gohman     return getTM<WebAssemblyTargetMachine>();
11710e730a2SDan Gohman   }
11810e730a2SDan Gohman 
11910e730a2SDan Gohman   FunctionPass *createTargetRegisterAllocator(bool) override;
12010e730a2SDan Gohman 
12110e730a2SDan Gohman   void addIRPasses() override;
12210e730a2SDan Gohman   bool addInstSelector() override;
12310e730a2SDan Gohman   void addPostRegAlloc() override;
124ad154c83SDerek Schuff   bool addGCPasses() override { return false; }
12510e730a2SDan Gohman   void addPreEmitPass() override;
12610e730a2SDan Gohman };
12710e730a2SDan Gohman } // end anonymous namespace
12810e730a2SDan Gohman 
12910e730a2SDan Gohman TargetIRAnalysis WebAssemblyTargetMachine::getTargetIRAnalysis() {
1309099b5e6SHans Wennborg   return TargetIRAnalysis([this](const Function &F) {
13110e730a2SDan Gohman     return TargetTransformInfo(WebAssemblyTTIImpl(this, F));
13210e730a2SDan Gohman   });
13310e730a2SDan Gohman }
13410e730a2SDan Gohman 
13510e730a2SDan Gohman TargetPassConfig *
13610e730a2SDan Gohman WebAssemblyTargetMachine::createPassConfig(PassManagerBase &PM) {
13710e730a2SDan Gohman   return new WebAssemblyPassConfig(this, PM);
13810e730a2SDan Gohman }
13910e730a2SDan Gohman 
14010e730a2SDan Gohman FunctionPass *WebAssemblyPassConfig::createTargetRegisterAllocator(bool) {
14110e730a2SDan Gohman   return nullptr; // No reg alloc
14210e730a2SDan Gohman }
14310e730a2SDan Gohman 
14410e730a2SDan Gohman //===----------------------------------------------------------------------===//
14510e730a2SDan Gohman // The following functions are called from lib/CodeGen/Passes.cpp to modify
14610e730a2SDan Gohman // the CodeGen pass sequence.
14710e730a2SDan Gohman //===----------------------------------------------------------------------===//
14810e730a2SDan Gohman 
14910e730a2SDan Gohman void WebAssemblyPassConfig::addIRPasses() {
15003855df1SJF Bastien   if (TM->Options.ThreadModel == ThreadModel::Single)
1519c54d3b4SDan Gohman     // In "single" mode, atomics get lowered to non-atomics.
15203855df1SJF Bastien     addPass(createLowerAtomicPass());
15303855df1SJF Bastien   else
15410e730a2SDan Gohman     // Expand some atomic operations. WebAssemblyTargetLowering has hooks which
15510e730a2SDan Gohman     // control specifically what gets lowered.
15603855df1SJF Bastien     addPass(createAtomicExpandPass(TM));
15710e730a2SDan Gohman 
15881719f85SDan Gohman   // Optimize "returned" function attributes.
159b13c91f1SDan Gohman   if (getOptLevel() != CodeGenOpt::None)
16081719f85SDan Gohman     addPass(createWebAssemblyOptimizeReturned());
16181719f85SDan Gohman 
162*f41f67d3SDerek Schuff   // Handle exceptions.
163*f41f67d3SDerek Schuff   if (EnableEmExceptionHandling)
164*f41f67d3SDerek Schuff     addPass(createWebAssemblyLowerEmscriptenExceptions());
165*f41f67d3SDerek Schuff 
16610e730a2SDan Gohman   TargetPassConfig::addIRPasses();
16710e730a2SDan Gohman }
16810e730a2SDan Gohman 
16910e730a2SDan Gohman bool WebAssemblyPassConfig::addInstSelector() {
170b0921ca9SDan Gohman   (void)TargetPassConfig::addInstSelector();
17110e730a2SDan Gohman   addPass(
17210e730a2SDan Gohman       createWebAssemblyISelDag(getWebAssemblyTargetMachine(), getOptLevel()));
1731cf96c0cSDan Gohman   // Run the argument-move pass immediately after the ScheduleDAG scheduler
1741cf96c0cSDan Gohman   // so that we can fix up the ARGUMENT instructions before anything else
1751cf96c0cSDan Gohman   // sees them in the wrong place.
1761cf96c0cSDan Gohman   addPass(createWebAssemblyArgumentMove());
177bb372243SDan Gohman   // Set the p2align operands. This information is present during ISel, however
178bb372243SDan Gohman   // it's inconvenient to collect. Collect it now, and update the immediate
179bb372243SDan Gohman   // operands.
180bb372243SDan Gohman   addPass(createWebAssemblySetP2AlignOperands());
18110e730a2SDan Gohman   return false;
18210e730a2SDan Gohman }
18310e730a2SDan Gohman 
184600aee98SJF Bastien void WebAssemblyPassConfig::addPostRegAlloc() {
1859c54d3b4SDan Gohman   // TODO: The following CodeGen passes don't currently support code containing
1869c54d3b4SDan Gohman   // virtual registers. Consider removing their restrictions and re-enabling
1879c54d3b4SDan Gohman   // them.
188ad154c83SDerek Schuff 
189ad154c83SDerek Schuff   // Has no asserts of its own, but was not written to handle virtual regs.
190ad154c83SDerek Schuff   disablePass(&ShrinkWrapID);
191ecabac62SDerek Schuff 
192ecabac62SDerek Schuff   // These functions all require the AllVRegsAllocated property.
193600aee98SJF Bastien   disablePass(&MachineCopyPropagationID);
194ecabac62SDerek Schuff   disablePass(&PostRASchedulerID);
195ecabac62SDerek Schuff   disablePass(&FuncletLayoutID);
196ecabac62SDerek Schuff   disablePass(&StackMapLivenessID);
197ecabac62SDerek Schuff   disablePass(&LiveDebugValuesID);
198fe71ec77SSanjoy Das   disablePass(&PatchableFunctionID);
199950a13cfSDan Gohman 
200b0921ca9SDan Gohman   TargetPassConfig::addPostRegAlloc();
201600aee98SJF Bastien }
20210e730a2SDan Gohman 
203950a13cfSDan Gohman void WebAssemblyPassConfig::addPreEmitPass() {
204b0921ca9SDan Gohman   TargetPassConfig::addPreEmitPass();
205b0921ca9SDan Gohman 
2060cfb5f85SDan Gohman   // Now that we have a prologue and epilogue and all frame indices are
2070cfb5f85SDan Gohman   // rewritten, eliminate SP and FP. This allows them to be stackified,
2080cfb5f85SDan Gohman   // colored, and numbered with the rest of the registers.
2090cfb5f85SDan Gohman   addPass(createWebAssemblyReplacePhysRegs());
2100cfb5f85SDan Gohman 
2110cfb5f85SDan Gohman   if (getOptLevel() != CodeGenOpt::None) {
2120cfb5f85SDan Gohman     // LiveIntervals isn't commonly run this late. Re-establish preconditions.
2130cfb5f85SDan Gohman     addPass(createWebAssemblyPrepareForLiveIntervals());
2140cfb5f85SDan Gohman 
2150cfb5f85SDan Gohman     // Depend on LiveIntervals and perform some optimizations on it.
2160cfb5f85SDan Gohman     addPass(createWebAssemblyOptimizeLiveIntervals());
2170cfb5f85SDan Gohman 
2180cfb5f85SDan Gohman     // Prepare store instructions for register stackifying.
2190cfb5f85SDan Gohman     addPass(createWebAssemblyStoreResults());
2200cfb5f85SDan Gohman 
2210cfb5f85SDan Gohman     // Mark registers as representing wasm's expression stack. This is a key
2220cfb5f85SDan Gohman     // code-compression technique in WebAssembly. We run this pass (and
2230cfb5f85SDan Gohman     // StoreResults above) very late, so that it sees as much code as possible,
2240cfb5f85SDan Gohman     // including code emitted by PEI and expanded by late tail duplication.
2250cfb5f85SDan Gohman     addPass(createWebAssemblyRegStackify());
2260cfb5f85SDan Gohman 
2270cfb5f85SDan Gohman     // Run the register coloring pass to reduce the total number of registers.
2280cfb5f85SDan Gohman     // This runs after stackification so that it doesn't consider registers
2290cfb5f85SDan Gohman     // that become stackified.
2300cfb5f85SDan Gohman     addPass(createWebAssemblyRegColoring());
2310cfb5f85SDan Gohman   }
2320cfb5f85SDan Gohman 
233d7a2eea6SDan Gohman   // Eliminate multiple-entry loops.
234d7a2eea6SDan Gohman   addPass(createWebAssemblyFixIrreducibleControlFlow());
235d7a2eea6SDan Gohman 
2365941bde0SDan Gohman   // Put the CFG in structured form; insert BLOCK and LOOP markers.
237950a13cfSDan Gohman   addPass(createWebAssemblyCFGStackify());
2385941bde0SDan Gohman 
239f0b165a7SDan Gohman   // Lower br_unless into br_if.
240f0b165a7SDan Gohman   addPass(createWebAssemblyLowerBrUnless());
241f0b165a7SDan Gohman 
2425941bde0SDan Gohman   // Perform the very last peephole optimizations on the code.
243b13c91f1SDan Gohman   if (getOptLevel() != CodeGenOpt::None)
24481719f85SDan Gohman     addPass(createWebAssemblyPeephole());
245b7c2400fSDan Gohman 
246b7c2400fSDan Gohman   // Create a mapping from LLVM CodeGen virtual registers to wasm registers.
247b7c2400fSDan Gohman   addPass(createWebAssemblyRegNumbering());
248950a13cfSDan Gohman }
249