blob: 8a768dbc1046e69bc415840456aea4163523c1b4 [file] [log] [blame]
Dan Gohman10e730a2015-06-29 23:51:55 +00001//===- WebAssemblyTargetMachine.cpp - Define TargetMachine for WebAssembly -==//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Dan Gohman10e730a2015-06-29 23:51:55 +00006//
7//===----------------------------------------------------------------------===//
8///
9/// \file
Adrian Prantl5f8f34e42018-05-01 15:54:18 +000010/// This file defines the WebAssembly-specific subclass of TargetMachine.
Dan Gohman10e730a2015-06-29 23:51:55 +000011///
12//===----------------------------------------------------------------------===//
13
Dan Gohman10e730a2015-06-29 23:51:55 +000014#include "WebAssemblyTargetMachine.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000015#include "MCTargetDesc/WebAssemblyMCTargetDesc.h"
16#include "WebAssembly.h"
Heejin Ahn52221d52019-03-26 17:35:35 +000017#include "WebAssemblyMachineFunctionInfo.h"
Dan Gohman5bf22fc2015-12-17 04:55:44 +000018#include "WebAssemblyTargetObjectFile.h"
Dan Gohman10e730a2015-06-29 23:51:55 +000019#include "WebAssemblyTargetTransformInfo.h"
Heejin Ahn52221d52019-03-26 17:35:35 +000020#include "llvm/CodeGen/MIRParser/MIParser.h"
Dan Gohman10e730a2015-06-29 23:51:55 +000021#include "llvm/CodeGen/MachineFunctionPass.h"
22#include "llvm/CodeGen/Passes.h"
23#include "llvm/CodeGen/RegAllocRegistry.h"
Matthias Braun31d19d42016-05-10 03:21:59 +000024#include "llvm/CodeGen/TargetPassConfig.h"
Dan Gohman10e730a2015-06-29 23:51:55 +000025#include "llvm/IR/Function.h"
Dan Gohman10e730a2015-06-29 23:51:55 +000026#include "llvm/Support/TargetRegistry.h"
27#include "llvm/Target/TargetOptions.h"
JF Bastien03855df2015-07-01 23:41:25 +000028#include "llvm/Transforms/Scalar.h"
Thomas Lively3f34e1b82019-03-29 00:14:01 +000029#include "llvm/Transforms/Scalar/LowerAtomic.h"
David Blaikiea373d182018-03-28 17:44:36 +000030#include "llvm/Transforms/Utils.h"
Dan Gohman10e730a2015-06-29 23:51:55 +000031using namespace llvm;
32
33#define DEBUG_TYPE "wasm"
34
Derek Schufff41f67d2016-08-01 21:34:04 +000035// Emscripten's asm.js-style exception handling
Derek Schuffccdceda2016-08-18 15:27:25 +000036static cl::opt<bool> EnableEmException(
Derek Schuff53b9af02016-08-09 00:29:55 +000037 "enable-emscripten-cxx-exceptions",
Derek Schufff41f67d2016-08-01 21:34:04 +000038 cl::desc("WebAssembly Emscripten-style exception handling"),
39 cl::init(false));
40
Derek Schuffccdceda2016-08-18 15:27:25 +000041// Emscripten's asm.js-style setjmp/longjmp handling
42static cl::opt<bool> EnableEmSjLj(
43 "enable-emscripten-sjlj",
44 cl::desc("WebAssembly Emscripten-style setjmp/longjmp handling"),
45 cl::init(false));
46
Dan Gohman10e730a2015-06-29 23:51:55 +000047extern "C" void LLVMInitializeWebAssemblyTarget() {
48 // Register the target.
Mehdi Aminif42454b2016-10-09 23:00:34 +000049 RegisterTargetMachine<WebAssemblyTargetMachine> X(
50 getTheWebAssemblyTarget32());
51 RegisterTargetMachine<WebAssemblyTargetMachine> Y(
52 getTheWebAssemblyTarget64());
Derek Schufff41f67d2016-08-01 21:34:04 +000053
Jacob Gravelle40926452018-03-30 20:36:58 +000054 // Register backend passes
55 auto &PR = *PassRegistry::getPassRegistry();
Sam Clegg92617552018-07-11 04:29:36 +000056 initializeWebAssemblyAddMissingPrototypesPass(PR);
Jacob Gravelle40926452018-03-30 20:36:58 +000057 initializeWebAssemblyLowerEmscriptenEHSjLjPass(PR);
58 initializeLowerGlobalDtorsPass(PR);
59 initializeFixFunctionBitcastsPass(PR);
60 initializeOptimizeReturnedPass(PR);
61 initializeWebAssemblyArgumentMovePass(PR);
62 initializeWebAssemblySetP2AlignOperandsPass(PR);
63 initializeWebAssemblyReplacePhysRegsPass(PR);
64 initializeWebAssemblyPrepareForLiveIntervalsPass(PR);
65 initializeWebAssemblyOptimizeLiveIntervalsPass(PR);
Heejin Ahn321d5222019-01-08 22:35:18 +000066 initializeWebAssemblyMemIntrinsicResultsPass(PR);
Jacob Gravelle40926452018-03-30 20:36:58 +000067 initializeWebAssemblyRegStackifyPass(PR);
68 initializeWebAssemblyRegColoringPass(PR);
69 initializeWebAssemblyExplicitLocalsPass(PR);
70 initializeWebAssemblyFixIrreducibleControlFlowPass(PR);
Heejin Ahn4934f762018-06-25 01:07:11 +000071 initializeWebAssemblyLateEHPreparePass(PR);
Heejin Ahn04c48942018-06-25 01:20:21 +000072 initializeWebAssemblyExceptionInfoPass(PR);
Jacob Gravelle40926452018-03-30 20:36:58 +000073 initializeWebAssemblyCFGSortPass(PR);
74 initializeWebAssemblyCFGStackifyPass(PR);
75 initializeWebAssemblyLowerBrUnlessPass(PR);
76 initializeWebAssemblyRegNumberingPass(PR);
77 initializeWebAssemblyPeepholePass(PR);
78 initializeWebAssemblyCallIndirectFixupPass(PR);
Dan Gohman10e730a2015-06-29 23:51:55 +000079}
80
81//===----------------------------------------------------------------------===//
82// WebAssembly Lowering public interface.
83//===----------------------------------------------------------------------===//
84
Dan Gohman41133a32016-05-19 03:00:05 +000085static Reloc::Model getEffectiveRelocModel(Optional<Reloc::Model> RM) {
Sam Clegg74f5fd42018-11-16 18:59:51 +000086 if (!RM.hasValue()) {
87 // Default to static relocation model. This should always be more optimial
88 // than PIC since the static linker can determine all global addresses and
89 // assume direct function calls.
90 return Reloc::Static;
91 }
Dan Gohman41133a32016-05-19 03:00:05 +000092 return *RM;
93}
94
Dan Gohman10e730a2015-06-29 23:51:55 +000095/// Create an WebAssembly architecture model.
96///
97WebAssemblyTargetMachine::WebAssemblyTargetMachine(
98 const Target &T, const Triple &TT, StringRef CPU, StringRef FS,
Dan Gohman41133a32016-05-19 03:00:05 +000099 const TargetOptions &Options, Optional<Reloc::Model> RM,
Daniel Jasper314ed202017-08-03 05:15:53 +0000100 Optional<CodeModel::Model> CM, CodeGenOpt::Level OL, bool JIT)
Matthias Braunbb8507e2017-10-12 22:57:28 +0000101 : LLVMTargetMachine(T,
102 TT.isArch64Bit() ? "e-m:e-p:64:64-i64:64-n32:64-S128"
103 : "e-m:e-p:32:32-i64:64-n32:64-S128",
104 TT, CPU, FS, Options, getEffectiveRelocModel(RM),
David Greenca29c272018-12-07 12:10:23 +0000105 getEffectiveCodeModel(CM, CodeModel::Large), OL),
Sam Cleggcf2a9e22018-07-16 23:09:29 +0000106 TLOF(new WebAssemblyTargetObjectFile()) {
Dan Gohmane0405332016-10-03 22:43:53 +0000107 // WebAssembly type-checks instructions, but a noreturn function with a return
Derek Schuffffa143c2015-11-10 00:30:57 +0000108 // type that doesn't match the context will cause a check failure. So we lower
109 // LLVM 'unreachable' to ISD::TRAP and then lower that to WebAssembly's
Dan Gohmane0405332016-10-03 22:43:53 +0000110 // 'unreachable' instructions which is meant for that case.
Derek Schuffffa143c2015-11-10 00:30:57 +0000111 this->Options.TrapUnreachable = true;
112
Dan Gohmand934cb82017-02-24 23:18:00 +0000113 // WebAssembly treats each function as an independent unit. Force
114 // -ffunction-sections, effectively, so that we can emit them independently.
Sam Cleggcf2a9e22018-07-16 23:09:29 +0000115 this->Options.FunctionSections = true;
116 this->Options.DataSections = true;
117 this->Options.UniqueSectionNames = true;
Dan Gohmand934cb82017-02-24 23:18:00 +0000118
Dan Gohman10e730a2015-06-29 23:51:55 +0000119 initAsmInfo();
120
Dan Gohmand85ab7f2016-02-18 06:32:53 +0000121 // Note that we don't use setRequiresStructuredCFG(true). It disables
122 // optimizations than we're ok with, and want, such as critical edge
123 // splitting and tail merging.
Dan Gohman10e730a2015-06-29 23:51:55 +0000124}
125
Heejin Ahn18c56a02019-02-04 19:13:39 +0000126WebAssemblyTargetMachine::~WebAssemblyTargetMachine() = default; // anchor.
Dan Gohman10e730a2015-06-29 23:51:55 +0000127
128const WebAssemblySubtarget *
Thomas Livelyf3b4f992019-02-28 18:39:08 +0000129WebAssemblyTargetMachine::getSubtargetImpl(std::string CPU,
130 std::string FS) const {
131 auto &I = SubtargetMap[CPU + FS];
132 if (!I) {
133 I = llvm::make_unique<WebAssemblySubtarget>(TargetTriple, CPU, FS, *this);
Thomas Livelyf3b4f992019-02-28 18:39:08 +0000134 }
135 return I.get();
136}
137
138const WebAssemblySubtarget *
Dan Gohman10e730a2015-06-29 23:51:55 +0000139WebAssemblyTargetMachine::getSubtargetImpl(const Function &F) const {
140 Attribute CPUAttr = F.getFnAttribute("target-cpu");
141 Attribute FSAttr = F.getFnAttribute("target-features");
142
143 std::string CPU = !CPUAttr.hasAttribute(Attribute::None)
144 ? CPUAttr.getValueAsString().str()
145 : TargetCPU;
146 std::string FS = !FSAttr.hasAttribute(Attribute::None)
147 ? FSAttr.getValueAsString().str()
148 : TargetFS;
149
Thomas Livelyf3b4f992019-02-28 18:39:08 +0000150 // This needs to be done before we create a new subtarget since any
151 // creation will depend on the TM and the code generation flags on the
152 // function that reside in TargetOptions.
153 resetTargetOptions(F);
154
155 return getSubtargetImpl(CPU, FS);
Dan Gohman10e730a2015-06-29 23:51:55 +0000156}
157
158namespace {
Thomas Lively3f34e1b82019-03-29 00:14:01 +0000159
160class CoalesceFeaturesAndStripAtomics final : public ModulePass {
161 // Take the union of all features used in the module and use it for each
162 // function individually, since having multiple feature sets in one module
163 // currently does not make sense for WebAssembly. If atomics are not enabled,
164 // also strip atomic operations and thread local storage.
Derek Schuff39b53672018-03-20 22:01:32 +0000165 static char ID;
Thomas Lively3f34e1b82019-03-29 00:14:01 +0000166 WebAssemblyTargetMachine *WasmTM;
Derek Schuff39b53672018-03-20 22:01:32 +0000167
Heejin Ahnf208f632018-09-05 01:27:38 +0000168public:
Thomas Lively3f34e1b82019-03-29 00:14:01 +0000169 CoalesceFeaturesAndStripAtomics(WebAssemblyTargetMachine *WasmTM)
170 : ModulePass(ID), WasmTM(WasmTM) {}
171
Derek Schuff39b53672018-03-20 22:01:32 +0000172 bool runOnModule(Module &M) override {
Thomas Lively3f34e1b82019-03-29 00:14:01 +0000173 FeatureBitset Features = coalesceFeatures(M);
174
175 std::string FeatureStr = getFeatureString(Features);
176 for (auto &F : M)
177 replaceFeatures(F, FeatureStr);
178
179 bool Stripped = false;
180 if (!Features[WebAssembly::FeatureAtomics]) {
181 Stripped |= stripAtomics(M);
182 Stripped |= stripThreadLocals(M);
183 }
184
185 recordFeatures(M, Features, Stripped);
186
187 // Conservatively assume we have made some change
Derek Schuff39b53672018-03-20 22:01:32 +0000188 return true;
189 }
Thomas Lively3f34e1b82019-03-29 00:14:01 +0000190
191private:
192 FeatureBitset coalesceFeatures(const Module &M) {
193 FeatureBitset Features =
194 WasmTM
195 ->getSubtargetImpl(WasmTM->getTargetCPU(),
196 WasmTM->getTargetFeatureString())
197 ->getFeatureBits();
198 for (auto &F : M)
199 Features |= WasmTM->getSubtargetImpl(F)->getFeatureBits();
200 return Features;
201 }
202
203 std::string getFeatureString(const FeatureBitset &Features) {
204 std::string Ret;
205 for (const SubtargetFeatureKV &KV : WebAssemblyFeatureKV) {
206 if (Features[KV.Value])
207 Ret += (StringRef("+") + KV.Key + ",").str();
208 }
209 return Ret;
210 }
211
212 void replaceFeatures(Function &F, const std::string &Features) {
213 F.removeFnAttr("target-features");
214 F.removeFnAttr("target-cpu");
215 F.addFnAttr("target-features", Features);
216 }
217
218 bool stripAtomics(Module &M) {
219 // Detect whether any atomics will be lowered, since there is no way to tell
220 // whether the LowerAtomic pass lowers e.g. stores.
221 bool Stripped = false;
222 for (auto &F : M) {
223 for (auto &B : F) {
224 for (auto &I : B) {
225 if (I.isAtomic()) {
226 Stripped = true;
227 goto done;
228 }
229 }
230 }
231 }
232
233 done:
234 if (!Stripped)
235 return false;
236
237 LowerAtomicPass Lowerer;
238 FunctionAnalysisManager FAM;
239 for (auto &F : M)
240 Lowerer.run(F, FAM);
241
242 return true;
243 }
244
245 bool stripThreadLocals(Module &M) {
246 bool Stripped = false;
247 for (auto &GV : M.globals()) {
248 if (GV.getThreadLocalMode() !=
249 GlobalValue::ThreadLocalMode::NotThreadLocal) {
250 Stripped = true;
251 GV.setThreadLocalMode(GlobalValue::ThreadLocalMode::NotThreadLocal);
252 }
253 }
254 return Stripped;
255 }
256
257 void recordFeatures(Module &M, const FeatureBitset &Features, bool Stripped) {
258 for (const SubtargetFeatureKV &KV : WebAssemblyFeatureKV) {
259 std::string MDKey = (StringRef("wasm-feature-") + KV.Key).str();
260 if (KV.Value == WebAssembly::FeatureAtomics && Stripped) {
261 // "atomics" is special: code compiled without atomics may have had its
262 // atomics lowered to nonatomic operations. In that case, atomics is
263 // disallowed to prevent unsafe linking with atomics-enabled objects.
264 assert(!Features[WebAssembly::FeatureAtomics]);
265 M.addModuleFlag(Module::ModFlagBehavior::Error, MDKey,
266 wasm::WASM_FEATURE_PREFIX_DISALLOWED);
267 } else if (Features[KV.Value]) {
268 // Otherwise features are marked Used or not mentioned
269 M.addModuleFlag(Module::ModFlagBehavior::Error, MDKey,
270 wasm::WASM_FEATURE_PREFIX_USED);
271 }
272 }
273 }
Derek Schuff39b53672018-03-20 22:01:32 +0000274};
Thomas Lively3f34e1b82019-03-29 00:14:01 +0000275char CoalesceFeaturesAndStripAtomics::ID = 0;
Derek Schuff39b53672018-03-20 22:01:32 +0000276
Dan Gohman10e730a2015-06-29 23:51:55 +0000277/// WebAssembly Code Generator Pass Configuration Options.
278class WebAssemblyPassConfig final : public TargetPassConfig {
279public:
Matthias Braun5e394c32017-05-30 21:36:41 +0000280 WebAssemblyPassConfig(WebAssemblyTargetMachine &TM, PassManagerBase &PM)
Dan Gohman10e730a2015-06-29 23:51:55 +0000281 : TargetPassConfig(TM, PM) {}
282
283 WebAssemblyTargetMachine &getWebAssemblyTargetMachine() const {
284 return getTM<WebAssemblyTargetMachine>();
285 }
286
287 FunctionPass *createTargetRegisterAllocator(bool) override;
Dan Gohman10e730a2015-06-29 23:51:55 +0000288
289 void addIRPasses() override;
Dan Gohman10e730a2015-06-29 23:51:55 +0000290 bool addInstSelector() override;
Dan Gohman10e730a2015-06-29 23:51:55 +0000291 void addPostRegAlloc() override;
Derek Schuffad154c82016-03-28 17:05:30 +0000292 bool addGCPasses() override { return false; }
Dan Gohman10e730a2015-06-29 23:51:55 +0000293 void addPreEmitPass() override;
Matt Arsenaultcf55a652019-03-19 19:33:12 +0000294
295 // No reg alloc
296 bool addRegAssignmentFast() override { return false; }
297
298 // No reg alloc
299 bool addRegAssignmentOptimized() override { return false; }
Dan Gohman10e730a2015-06-29 23:51:55 +0000300};
301} // end anonymous namespace
302
Sanjoy Das26d11ca2017-12-22 18:21:59 +0000303TargetTransformInfo
304WebAssemblyTargetMachine::getTargetTransformInfo(const Function &F) {
305 return TargetTransformInfo(WebAssemblyTTIImpl(this, F));
Dan Gohman10e730a2015-06-29 23:51:55 +0000306}
307
308TargetPassConfig *
309WebAssemblyTargetMachine::createPassConfig(PassManagerBase &PM) {
Matthias Braun5e394c32017-05-30 21:36:41 +0000310 return new WebAssemblyPassConfig(*this, PM);
Dan Gohman10e730a2015-06-29 23:51:55 +0000311}
312
313FunctionPass *WebAssemblyPassConfig::createTargetRegisterAllocator(bool) {
314 return nullptr; // No reg alloc
315}
316
Dan Gohman10e730a2015-06-29 23:51:55 +0000317//===----------------------------------------------------------------------===//
318// The following functions are called from lib/CodeGen/Passes.cpp to modify
319// the CodeGen pass sequence.
320//===----------------------------------------------------------------------===//
321
322void WebAssemblyPassConfig::addIRPasses() {
Thomas Lively3f34e1b82019-03-29 00:14:01 +0000323 // Runs LowerAtomicPass if necessary
324 addPass(new CoalesceFeaturesAndStripAtomics(&getWebAssemblyTargetMachine()));
325
326 // This is a no-op if atomics are not used in the module
327 addPass(createAtomicExpandPass());
Dan Gohman10e730a2015-06-29 23:51:55 +0000328
Sam Clegg92617552018-07-11 04:29:36 +0000329 // Add signatures to prototype-less function declarations
330 addPass(createWebAssemblyAddMissingPrototypes());
331
Sam Cleggbafe6902017-12-15 00:17:10 +0000332 // Lower .llvm.global_dtors into .llvm_global_ctors with __cxa_atexit calls.
333 addPass(createWebAssemblyLowerGlobalDtors());
334
Dan Gohman1b637452017-01-07 00:34:54 +0000335 // Fix function bitcasts, as WebAssembly requires caller and callee signatures
336 // to match.
337 addPass(createWebAssemblyFixFunctionBitcasts());
338
Dan Gohman81719f82015-11-25 16:55:01 +0000339 // Optimize "returned" function attributes.
Dan Gohmanb13c91f2016-01-19 14:55:02 +0000340 if (getOptLevel() != CodeGenOpt::None)
341 addPass(createWebAssemblyOptimizeReturned());
Dan Gohman81719f82015-11-25 16:55:01 +0000342
Heejin Ahnc0f18172016-09-01 21:05:15 +0000343 // If exception handling is not enabled and setjmp/longjmp handling is
344 // enabled, we lower invokes into calls and delete unreachable landingpad
345 // blocks. Lowering invokes when there is no EH support is done in
346 // TargetPassConfig::addPassesToHandleExceptions, but this runs after this
347 // function and SjLj handling expects all invokes to be lowered before.
Heejin Ahn9386bde2018-02-24 00:40:50 +0000348 if (!EnableEmException &&
349 TM->Options.ExceptionModel == ExceptionHandling::None) {
Heejin Ahnc0f18172016-09-01 21:05:15 +0000350 addPass(createLowerInvokePass());
351 // The lower invoke pass may create unreachable code. Remove it in order not
352 // to process dead blocks in setjmp/longjmp handling.
353 addPass(createUnreachableBlockEliminationPass());
354 }
355
356 // Handle exceptions and setjmp/longjmp if enabled.
Derek Schuffccdceda2016-08-18 15:27:25 +0000357 if (EnableEmException || EnableEmSjLj)
358 addPass(createWebAssemblyLowerEmscriptenEHSjLj(EnableEmException,
359 EnableEmSjLj));
Derek Schufff41f67d2016-08-01 21:34:04 +0000360
Dan Gohman10e730a2015-06-29 23:51:55 +0000361 TargetPassConfig::addIRPasses();
362}
363
Dan Gohman10e730a2015-06-29 23:51:55 +0000364bool WebAssemblyPassConfig::addInstSelector() {
Dan Gohmanb0921ca2015-12-05 19:24:17 +0000365 (void)TargetPassConfig::addInstSelector();
Dan Gohman10e730a2015-06-29 23:51:55 +0000366 addPass(
367 createWebAssemblyISelDag(getWebAssemblyTargetMachine(), getOptLevel()));
Dan Gohman1cf96c02015-12-09 16:23:59 +0000368 // Run the argument-move pass immediately after the ScheduleDAG scheduler
369 // so that we can fix up the ARGUMENT instructions before anything else
370 // sees them in the wrong place.
371 addPass(createWebAssemblyArgumentMove());
Dan Gohmanbb372242016-01-26 03:39:31 +0000372 // Set the p2align operands. This information is present during ISel, however
373 // it's inconvenient to collect. Collect it now, and update the immediate
374 // operands.
375 addPass(createWebAssemblySetP2AlignOperands());
Dan Gohman10e730a2015-06-29 23:51:55 +0000376 return false;
377}
378
JF Bastien600aee92015-07-31 17:53:38 +0000379void WebAssemblyPassConfig::addPostRegAlloc() {
Dan Gohman9c54d3b2015-11-25 18:13:18 +0000380 // TODO: The following CodeGen passes don't currently support code containing
381 // virtual registers. Consider removing their restrictions and re-enabling
382 // them.
Derek Schuffad154c82016-03-28 17:05:30 +0000383
Matthias Braun1eb47362016-08-25 01:27:13 +0000384 // These functions all require the NoVRegs property.
JF Bastien600aee92015-07-31 17:53:38 +0000385 disablePass(&MachineCopyPropagationID);
Jun Bum Lim7ab1b322018-04-03 18:17:34 +0000386 disablePass(&PostRAMachineSinkingID);
Derek Schuffecabac62016-03-28 22:52:20 +0000387 disablePass(&PostRASchedulerID);
388 disablePass(&FuncletLayoutID);
389 disablePass(&StackMapLivenessID);
390 disablePass(&LiveDebugValuesID);
Sanjoy Dasfe71ec72016-04-19 06:24:58 +0000391 disablePass(&PatchableFunctionID);
Jun Bum Lim7ab1b322018-04-03 18:17:34 +0000392 disablePass(&ShrinkWrapID);
Dan Gohman950a13c2015-09-16 16:51:30 +0000393
Heejin Ahnef9d6ae2019-03-05 20:35:34 +0000394 // This pass hurts code size for wasm because it can generate irreducible
395 // control flow.
396 disablePass(&MachineBlockPlacementID);
397
Dan Gohmanb0921ca2015-12-05 19:24:17 +0000398 TargetPassConfig::addPostRegAlloc();
JF Bastien600aee92015-07-31 17:53:38 +0000399}
Dan Gohman10e730a2015-06-29 23:51:55 +0000400
Dan Gohman950a13c2015-09-16 16:51:30 +0000401void WebAssemblyPassConfig::addPreEmitPass() {
Dan Gohmanb0921ca2015-12-05 19:24:17 +0000402 TargetPassConfig::addPreEmitPass();
Dan Gohman05ac43f2015-12-17 01:39:00 +0000403
Derek Schuff6f697832016-10-21 16:38:07 +0000404 // Rewrite pseudo call_indirect instructions as real instructions.
405 // This needs to run before register stackification, because we change the
406 // order of the arguments.
407 addPass(createWebAssemblyCallIndirectFixup());
408
Heejin Ahne95056d2019-01-08 01:25:12 +0000409 // Eliminate multiple-entry loops.
410 addPass(createWebAssemblyFixIrreducibleControlFlow());
411
412 // Do various transformations for exception handling.
Heejin Ahnd6f48782019-01-30 03:21:57 +0000413 // Every CFG-changing optimizations should come before this.
Heejin Ahne95056d2019-01-08 01:25:12 +0000414 addPass(createWebAssemblyLateEHPrepare());
415
Heejin Ahn0bb98652019-01-30 22:44:45 +0000416 // Now that we have a prologue and epilogue and all frame indices are
417 // rewritten, eliminate SP and FP. This allows them to be stackified,
418 // colored, and numbered with the rest of the registers.
419 addPass(createWebAssemblyReplacePhysRegs());
420
Heejin Ahnd6f48782019-01-30 03:21:57 +0000421 // Preparations and optimizations related to register stackification.
Dan Gohman0cfb5f82016-05-10 04:24:02 +0000422 if (getOptLevel() != CodeGenOpt::None) {
423 // LiveIntervals isn't commonly run this late. Re-establish preconditions.
424 addPass(createWebAssemblyPrepareForLiveIntervals());
425
426 // Depend on LiveIntervals and perform some optimizations on it.
427 addPass(createWebAssemblyOptimizeLiveIntervals());
428
Heejin Ahn321d5222019-01-08 22:35:18 +0000429 // Prepare memory intrinsic calls for register stackifying.
430 addPass(createWebAssemblyMemIntrinsicResults());
Dan Gohman0cfb5f82016-05-10 04:24:02 +0000431
Dan Gohmane0405332016-10-03 22:43:53 +0000432 // Mark registers as representing wasm's value stack. This is a key
Dan Gohman0cfb5f82016-05-10 04:24:02 +0000433 // code-compression technique in WebAssembly. We run this pass (and
Heejin Ahn321d5222019-01-08 22:35:18 +0000434 // MemIntrinsicResults above) very late, so that it sees as much code as
435 // possible, including code emitted by PEI and expanded by late tail
436 // duplication.
Dan Gohman0cfb5f82016-05-10 04:24:02 +0000437 addPass(createWebAssemblyRegStackify());
438
439 // Run the register coloring pass to reduce the total number of registers.
440 // This runs after stackification so that it doesn't consider registers
441 // that become stackified.
442 addPass(createWebAssemblyRegColoring());
443 }
444
Thomas Lively6a87dda2019-01-08 06:25:55 +0000445 // Insert explicit local.get and local.set operators.
Wouter van Oortmerssena7be3752018-08-13 23:12:49 +0000446 addPass(createWebAssemblyExplicitLocals());
447
Dan Gohmanf52ee172017-02-27 22:38:58 +0000448 // Sort the blocks of the CFG into topological order, a prerequisite for
449 // BLOCK and LOOP markers.
450 addPass(createWebAssemblyCFGSort());
451
452 // Insert BLOCK and LOOP markers.
Dan Gohman950a13c2015-09-16 16:51:30 +0000453 addPass(createWebAssemblyCFGStackify());
Dan Gohman5941bde2015-11-25 21:32:06 +0000454
Dan Gohmanf0b165a2015-12-05 03:03:35 +0000455 // Lower br_unless into br_if.
456 addPass(createWebAssemblyLowerBrUnless());
457
Dan Gohman5941bde2015-11-25 21:32:06 +0000458 // Perform the very last peephole optimizations on the code.
Dan Gohmanb13c91f2016-01-19 14:55:02 +0000459 if (getOptLevel() != CodeGenOpt::None)
460 addPass(createWebAssemblyPeephole());
Dan Gohmanb7c24002016-05-21 00:21:56 +0000461
462 // Create a mapping from LLVM CodeGen virtual registers to wasm registers.
463 addPass(createWebAssemblyRegNumbering());
Dan Gohman950a13c2015-09-16 16:51:30 +0000464}
Heejin Ahn52221d52019-03-26 17:35:35 +0000465
466yaml::MachineFunctionInfo *
467WebAssemblyTargetMachine::createDefaultFuncInfoYAML() const {
468 return new yaml::WebAssemblyFunctionInfo();
469}
470
471yaml::MachineFunctionInfo *WebAssemblyTargetMachine::convertFuncInfoToYAML(
472 const MachineFunction &MF) const {
473 const auto *MFI = MF.getInfo<WebAssemblyFunctionInfo>();
474 return new yaml::WebAssemblyFunctionInfo(*MFI);
475}
476
477bool WebAssemblyTargetMachine::parseMachineFunctionInfo(
478 const yaml::MachineFunctionInfo &MFI, PerFunctionMIParsingState &PFS,
479 SMDiagnostic &Error, SMRange &SourceRange) const {
480 const auto &YamlMFI =
481 reinterpret_cast<const yaml::WebAssemblyFunctionInfo &>(MFI);
482 MachineFunction &MF = PFS.MF;
483 MF.getInfo<WebAssemblyFunctionInfo>()->initializeBaseYamlFields(YamlMFI);
484 return false;
485}