Home | History | Annotate | Download | only in WebAssembly
      1 //===- WebAssemblyTargetMachine.cpp - Define TargetMachine for WebAssembly -==//
      2 //
      3 //                     The LLVM Compiler Infrastructure
      4 //
      5 // This file is distributed under the University of Illinois Open Source
      6 // License. See LICENSE.TXT for details.
      7 //
      8 //===----------------------------------------------------------------------===//
      9 ///
     10 /// \file
     11 /// \brief This file defines the WebAssembly-specific subclass of TargetMachine.
     12 ///
     13 //===----------------------------------------------------------------------===//
     14 
     15 #include "WebAssembly.h"
     16 #include "MCTargetDesc/WebAssemblyMCTargetDesc.h"
     17 #include "WebAssemblyTargetMachine.h"
     18 #include "WebAssemblyTargetObjectFile.h"
     19 #include "WebAssemblyTargetTransformInfo.h"
     20 #include "llvm/CodeGen/MachineFunctionPass.h"
     21 #include "llvm/CodeGen/Passes.h"
     22 #include "llvm/CodeGen/RegAllocRegistry.h"
     23 #include "llvm/IR/Function.h"
     24 #include "llvm/Support/CommandLine.h"
     25 #include "llvm/Support/TargetRegistry.h"
     26 #include "llvm/Target/TargetOptions.h"
     27 #include "llvm/Transforms/Scalar.h"
     28 using namespace llvm;
     29 
     30 #define DEBUG_TYPE "wasm"
     31 
     32 extern "C" void LLVMInitializeWebAssemblyTarget() {
     33   // Register the target.
     34   RegisterTargetMachine<WebAssemblyTargetMachine> X(TheWebAssemblyTarget32);
     35   RegisterTargetMachine<WebAssemblyTargetMachine> Y(TheWebAssemblyTarget64);
     36 }
     37 
     38 //===----------------------------------------------------------------------===//
     39 // WebAssembly Lowering public interface.
     40 //===----------------------------------------------------------------------===//
     41 
     42 /// Create an WebAssembly architecture model.
     43 ///
     44 WebAssemblyTargetMachine::WebAssemblyTargetMachine(
     45     const Target &T, const Triple &TT, StringRef CPU, StringRef FS,
     46     const TargetOptions &Options, Reloc::Model RM, CodeModel::Model CM,
     47     CodeGenOpt::Level OL)
     48     : LLVMTargetMachine(T, TT.isArch64Bit() ? "e-p:64:64-i64:64-n32:64-S128"
     49                                             : "e-p:32:32-i64:64-n32:64-S128",
     50                         TT, CPU, FS, Options, RM, CM, OL),
     51       TLOF(make_unique<WebAssemblyTargetObjectFile>()) {
     52   // WebAssembly type-checks expressions, but a noreturn function with a return
     53   // type that doesn't match the context will cause a check failure. So we lower
     54   // LLVM 'unreachable' to ISD::TRAP and then lower that to WebAssembly's
     55   // 'unreachable' expression which is meant for that case.
     56   this->Options.TrapUnreachable = true;
     57 
     58   initAsmInfo();
     59 
     60   // We need a reducible CFG, so disable some optimizations which tend to
     61   // introduce irreducibility.
     62   setRequiresStructuredCFG(true);
     63 }
     64 
     65 WebAssemblyTargetMachine::~WebAssemblyTargetMachine() {}
     66 
     67 const WebAssemblySubtarget *
     68 WebAssemblyTargetMachine::getSubtargetImpl(const Function &F) const {
     69   Attribute CPUAttr = F.getFnAttribute("target-cpu");
     70   Attribute FSAttr = F.getFnAttribute("target-features");
     71 
     72   std::string CPU = !CPUAttr.hasAttribute(Attribute::None)
     73                         ? CPUAttr.getValueAsString().str()
     74                         : TargetCPU;
     75   std::string FS = !FSAttr.hasAttribute(Attribute::None)
     76                        ? FSAttr.getValueAsString().str()
     77                        : TargetFS;
     78 
     79   auto &I = SubtargetMap[CPU + FS];
     80   if (!I) {
     81     // This needs to be done before we create a new subtarget since any
     82     // creation will depend on the TM and the code generation flags on the
     83     // function that reside in TargetOptions.
     84     resetTargetOptions(F);
     85     I = llvm::make_unique<WebAssemblySubtarget>(TargetTriple, CPU, FS, *this);
     86   }
     87   return I.get();
     88 }
     89 
     90 namespace {
     91 /// WebAssembly Code Generator Pass Configuration Options.
     92 class WebAssemblyPassConfig final : public TargetPassConfig {
     93 public:
     94   WebAssemblyPassConfig(WebAssemblyTargetMachine *TM, PassManagerBase &PM)
     95       : TargetPassConfig(TM, PM) {}
     96 
     97   WebAssemblyTargetMachine &getWebAssemblyTargetMachine() const {
     98     return getTM<WebAssemblyTargetMachine>();
     99   }
    100 
    101   FunctionPass *createTargetRegisterAllocator(bool) override;
    102 
    103   void addIRPasses() override;
    104   bool addInstSelector() override;
    105   bool addILPOpts() override;
    106   void addPreRegAlloc() override;
    107   void addPostRegAlloc() override;
    108   void addPreEmitPass() override;
    109 };
    110 } // end anonymous namespace
    111 
    112 TargetIRAnalysis WebAssemblyTargetMachine::getTargetIRAnalysis() {
    113   return TargetIRAnalysis([this](const Function &F) {
    114     return TargetTransformInfo(WebAssemblyTTIImpl(this, F));
    115   });
    116 }
    117 
    118 TargetPassConfig *
    119 WebAssemblyTargetMachine::createPassConfig(PassManagerBase &PM) {
    120   return new WebAssemblyPassConfig(this, PM);
    121 }
    122 
    123 FunctionPass *WebAssemblyPassConfig::createTargetRegisterAllocator(bool) {
    124   return nullptr; // No reg alloc
    125 }
    126 
    127 //===----------------------------------------------------------------------===//
    128 // The following functions are called from lib/CodeGen/Passes.cpp to modify
    129 // the CodeGen pass sequence.
    130 //===----------------------------------------------------------------------===//
    131 
    132 void WebAssemblyPassConfig::addIRPasses() {
    133   if (TM->Options.ThreadModel == ThreadModel::Single)
    134     // In "single" mode, atomics get lowered to non-atomics.
    135     addPass(createLowerAtomicPass());
    136   else
    137     // Expand some atomic operations. WebAssemblyTargetLowering has hooks which
    138     // control specifically what gets lowered.
    139     addPass(createAtomicExpandPass(TM));
    140 
    141   // Optimize "returned" function attributes.
    142   addPass(createWebAssemblyOptimizeReturned());
    143 
    144   TargetPassConfig::addIRPasses();
    145 }
    146 
    147 bool WebAssemblyPassConfig::addInstSelector() {
    148   (void)TargetPassConfig::addInstSelector();
    149   addPass(
    150       createWebAssemblyISelDag(getWebAssemblyTargetMachine(), getOptLevel()));
    151   // Run the argument-move pass immediately after the ScheduleDAG scheduler
    152   // so that we can fix up the ARGUMENT instructions before anything else
    153   // sees them in the wrong place.
    154   addPass(createWebAssemblyArgumentMove());
    155   return false;
    156 }
    157 
    158 bool WebAssemblyPassConfig::addILPOpts() {
    159   (void)TargetPassConfig::addILPOpts();
    160   return true;
    161 }
    162 
    163 void WebAssemblyPassConfig::addPreRegAlloc() {
    164   TargetPassConfig::addPreRegAlloc();
    165 
    166   // Prepare store instructions for register stackifying.
    167   addPass(createWebAssemblyStoreResults());
    168 
    169   // Mark registers as representing wasm's expression stack.
    170   addPass(createWebAssemblyRegStackify());
    171   // The register coalescing pass has a bad interaction with COPY MIs which have
    172   // EXPR_STACK as an extra operand
    173   // disablePass(&RegisterCoalescerID);
    174 }
    175 
    176 void WebAssemblyPassConfig::addPostRegAlloc() {
    177   // TODO: The following CodeGen passes don't currently support code containing
    178   // virtual registers. Consider removing their restrictions and re-enabling
    179   // them.
    180   //
    181   // We use our own PrologEpilogInserter which is very slightly modified to
    182   // tolerate virtual registers.
    183   disablePass(&PrologEpilogCodeInserterID);
    184   // Fails with: should be run after register allocation.
    185   disablePass(&MachineCopyPropagationID);
    186 
    187   // Run the register coloring pass to reduce the total number of registers.
    188   addPass(createWebAssemblyRegColoring());
    189 
    190   TargetPassConfig::addPostRegAlloc();
    191 
    192   // Run WebAssembly's version of the PrologEpilogInserter. Target-independent
    193   // PEI runs after PostRegAlloc and after ShrinkWrap. Putting it here will run
    194   // PEI before ShrinkWrap but otherwise in the same position in the order.
    195   addPass(createWebAssemblyPEI());
    196 }
    197 
    198 void WebAssemblyPassConfig::addPreEmitPass() {
    199   TargetPassConfig::addPreEmitPass();
    200 
    201   // Put the CFG in structured form; insert BLOCK and LOOP markers.
    202   addPass(createWebAssemblyCFGStackify());
    203 
    204   // Lower br_unless into br_if.
    205   addPass(createWebAssemblyLowerBrUnless());
    206 
    207   // Create a mapping from LLVM CodeGen virtual registers to wasm registers.
    208   addPass(createWebAssemblyRegNumbering());
    209 
    210   // Perform the very last peephole optimizations on the code.
    211   addPass(createWebAssemblyPeephole());
    212 }
    213