[WebAssembly] Support for register stackifying with load and store instructions.
[oota-llvm.git] / lib / Target / WebAssembly / WebAssemblyPeephole.cpp
1 //===-- WebAssemblyPeephole.cpp - WebAssembly Peephole Optimiztions -------===//
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 Late peephole optimizations for WebAssembly.
12 ///
13 //===----------------------------------------------------------------------===//
14
15 #include "WebAssembly.h"
16 #include "MCTargetDesc/WebAssemblyMCTargetDesc.h"
17 #include "WebAssemblyMachineFunctionInfo.h"
18 #include "llvm/CodeGen/MachineFunctionPass.h"
19 using namespace llvm;
20
21 #define DEBUG_TYPE "wasm-peephole"
22
23 namespace {
24 class WebAssemblyPeephole final : public MachineFunctionPass {
25   const char *getPassName() const override {
26     return "WebAssembly late peephole optimizer";
27   }
28
29   bool runOnMachineFunction(MachineFunction &MF) override;
30
31 public:
32   static char ID;
33   WebAssemblyPeephole() : MachineFunctionPass(ID) {}
34 };
35 } // end anonymous namespace
36
37 char WebAssemblyPeephole::ID = 0;
38 FunctionPass *llvm::createWebAssemblyPeephole() {
39   return new WebAssemblyPeephole();
40 }
41
42 bool WebAssemblyPeephole::runOnMachineFunction(MachineFunction &MF) {
43   bool Changed = false;
44
45   MachineRegisterInfo &MRI = MF.getRegInfo();
46   WebAssemblyFunctionInfo &MFI = *MF.getInfo<WebAssemblyFunctionInfo>();
47
48   for (auto &MBB : MF)
49     for (auto &MI : MBB)
50       switch (MI.getOpcode()) {
51       default:
52         break;
53       case WebAssembly::STORE8_I32:
54       case WebAssembly::STORE16_I32:
55       case WebAssembly::STORE8_I64:
56       case WebAssembly::STORE16_I64:
57       case WebAssembly::STORE32_I64:
58       case WebAssembly::STORE_F32:
59       case WebAssembly::STORE_F64:
60       case WebAssembly::STORE_I32:
61       case WebAssembly::STORE_I64: {
62         // Store instructions return their value operand. If we ended up using
63         // the same register for both, replace it with a dead def so that it
64         // can use $discard instead.
65         MachineOperand &MO = MI.getOperand(0);
66         unsigned OldReg = MO.getReg();
67         if (OldReg == MI.getOperand(2).getReg()) {
68           unsigned NewReg = MRI.createVirtualRegister(MRI.getRegClass(OldReg));
69           MO.setReg(NewReg);
70           MO.setIsDead();
71           MFI.stackifyVReg(NewReg);
72         }
73       }
74       }
75
76   return Changed;
77 }