xref: /llvm-project/llvm/lib/Target/WebAssembly/WebAssemblyTargetMachine.cpp (revision 1aaf87e91de46f251193664f3eed180c8609e403)
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/CodeGen/TargetPassConfig.h"
24 #include "llvm/IR/Function.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,
49                         TT.isArch64Bit() ? "e-m:e-p:64:64-i64:64-n32:64-S128"
50                                          : "e-m:e-p:32:32-i64:64-n32:64-S128",
51                         TT, CPU, FS, Options, RM, CM, OL),
52       TLOF(make_unique<WebAssemblyTargetObjectFile>()) {
53   // WebAssembly type-checks expressions, but a noreturn function with a return
54   // type that doesn't match the context will cause a check failure. So we lower
55   // LLVM 'unreachable' to ISD::TRAP and then lower that to WebAssembly's
56   // 'unreachable' expression which is meant for that case.
57   this->Options.TrapUnreachable = true;
58 
59   initAsmInfo();
60 
61   // Note that we don't use setRequiresStructuredCFG(true). It disables
62   // optimizations than we're ok with, and want, such as critical edge
63   // splitting and tail merging.
64 }
65 
66 WebAssemblyTargetMachine::~WebAssemblyTargetMachine() {}
67 
68 const WebAssemblySubtarget *
69 WebAssemblyTargetMachine::getSubtargetImpl(const Function &F) const {
70   Attribute CPUAttr = F.getFnAttribute("target-cpu");
71   Attribute FSAttr = F.getFnAttribute("target-features");
72 
73   std::string CPU = !CPUAttr.hasAttribute(Attribute::None)
74                         ? CPUAttr.getValueAsString().str()
75                         : TargetCPU;
76   std::string FS = !FSAttr.hasAttribute(Attribute::None)
77                        ? FSAttr.getValueAsString().str()
78                        : TargetFS;
79 
80   auto &I = SubtargetMap[CPU + FS];
81   if (!I) {
82     // This needs to be done before we create a new subtarget since any
83     // creation will depend on the TM and the code generation flags on the
84     // function that reside in TargetOptions.
85     resetTargetOptions(F);
86     I = llvm::make_unique<WebAssemblySubtarget>(TargetTriple, CPU, FS, *this);
87   }
88   return I.get();
89 }
90 
91 namespace {
92 /// WebAssembly Code Generator Pass Configuration Options.
93 class WebAssemblyPassConfig final : public TargetPassConfig {
94 public:
95   WebAssemblyPassConfig(WebAssemblyTargetMachine *TM, PassManagerBase &PM)
96       : TargetPassConfig(TM, PM) {}
97 
98   WebAssemblyTargetMachine &getWebAssemblyTargetMachine() const {
99     return getTM<WebAssemblyTargetMachine>();
100   }
101 
102   FunctionPass *createTargetRegisterAllocator(bool) override;
103 
104   void addIRPasses() override;
105   bool addInstSelector() override;
106   void addPostRegAlloc() override;
107   bool addGCPasses() override { return false; }
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   if (getOptLevel() != CodeGenOpt::None)
143     addPass(createWebAssemblyOptimizeReturned());
144 
145   TargetPassConfig::addIRPasses();
146 }
147 
148 bool WebAssemblyPassConfig::addInstSelector() {
149   (void)TargetPassConfig::addInstSelector();
150   addPass(
151       createWebAssemblyISelDag(getWebAssemblyTargetMachine(), getOptLevel()));
152   // Run the argument-move pass immediately after the ScheduleDAG scheduler
153   // so that we can fix up the ARGUMENT instructions before anything else
154   // sees them in the wrong place.
155   addPass(createWebAssemblyArgumentMove());
156   // Set the p2align operands. This information is present during ISel, however
157   // it's inconvenient to collect. Collect it now, and update the immediate
158   // operands.
159   addPass(createWebAssemblySetP2AlignOperands());
160   return false;
161 }
162 
163 void WebAssemblyPassConfig::addPostRegAlloc() {
164   // TODO: The following CodeGen passes don't currently support code containing
165   // virtual registers. Consider removing their restrictions and re-enabling
166   // them.
167 
168   // Has no asserts of its own, but was not written to handle virtual regs.
169   disablePass(&ShrinkWrapID);
170 
171   // These functions all require the AllVRegsAllocated property.
172   disablePass(&MachineCopyPropagationID);
173   disablePass(&PostRASchedulerID);
174   disablePass(&FuncletLayoutID);
175   disablePass(&StackMapLivenessID);
176   disablePass(&LiveDebugValuesID);
177   disablePass(&PatchableFunctionID);
178 
179   TargetPassConfig::addPostRegAlloc();
180 }
181 
182 void WebAssemblyPassConfig::addPreEmitPass() {
183   TargetPassConfig::addPreEmitPass();
184 
185   // Now that we have a prologue and epilogue and all frame indices are
186   // rewritten, eliminate SP and FP. This allows them to be stackified,
187   // colored, and numbered with the rest of the registers.
188   addPass(createWebAssemblyReplacePhysRegs());
189 
190   if (getOptLevel() != CodeGenOpt::None) {
191     // LiveIntervals isn't commonly run this late. Re-establish preconditions.
192     addPass(createWebAssemblyPrepareForLiveIntervals());
193 
194     // Depend on LiveIntervals and perform some optimizations on it.
195     addPass(createWebAssemblyOptimizeLiveIntervals());
196 
197     // Prepare store instructions for register stackifying.
198     addPass(createWebAssemblyStoreResults());
199 
200     // Mark registers as representing wasm's expression stack. This is a key
201     // code-compression technique in WebAssembly. We run this pass (and
202     // StoreResults above) very late, so that it sees as much code as possible,
203     // including code emitted by PEI and expanded by late tail duplication.
204     addPass(createWebAssemblyRegStackify());
205 
206     // Run the register coloring pass to reduce the total number of registers.
207     // This runs after stackification so that it doesn't consider registers
208     // that become stackified.
209     addPass(createWebAssemblyRegColoring());
210   }
211 
212   // Eliminate multiple-entry loops.
213   addPass(createWebAssemblyFixIrreducibleControlFlow());
214 
215   // Put the CFG in structured form; insert BLOCK and LOOP markers.
216   addPass(createWebAssemblyCFGStackify());
217 
218   // Lower br_unless into br_if.
219   addPass(createWebAssemblyLowerBrUnless());
220 
221   // Create a mapping from LLVM CodeGen virtual registers to wasm registers.
222   addPass(createWebAssemblyRegNumbering());
223 
224   // Perform the very last peephole optimizations on the code.
225   if (getOptLevel() != CodeGenOpt::None)
226     addPass(createWebAssemblyPeephole());
227 }
228