blob: 937d272d2139ba3ba443f446d7b37794a11f5390 [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"
Richard Trieuc6c42132019-05-15 01:03:00 +000016#include "TargetInfo/WebAssemblyTargetInfo.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000017#include "WebAssembly.h"
Heejin Ahn52221d52019-03-26 17:35:35 +000018#include "WebAssemblyMachineFunctionInfo.h"
Dan Gohman5bf22fc2015-12-17 04:55:44 +000019#include "WebAssemblyTargetObjectFile.h"
Dan Gohman10e730a2015-06-29 23:51:55 +000020#include "WebAssemblyTargetTransformInfo.h"
Heejin Ahn52221d52019-03-26 17:35:35 +000021#include "llvm/CodeGen/MIRParser/MIParser.h"
Dan Gohman10e730a2015-06-29 23:51:55 +000022#include "llvm/CodeGen/MachineFunctionPass.h"
23#include "llvm/CodeGen/Passes.h"
24#include "llvm/CodeGen/RegAllocRegistry.h"
Matthias Braun31d19d42016-05-10 03:21:59 +000025#include "llvm/CodeGen/TargetPassConfig.h"
Dan Gohman10e730a2015-06-29 23:51:55 +000026#include "llvm/IR/Function.h"
Dan Gohman10e730a2015-06-29 23:51:55 +000027#include "llvm/Support/TargetRegistry.h"
28#include "llvm/Target/TargetOptions.h"
JF Bastien03855df2015-07-01 23:41:25 +000029#include "llvm/Transforms/Scalar.h"
Thomas Lively3f34e1b82019-03-29 00:14:01 +000030#include "llvm/Transforms/Scalar/LowerAtomic.h"
David Blaikiea373d182018-03-28 17:44:36 +000031#include "llvm/Transforms/Utils.h"
Dan Gohman10e730a2015-06-29 23:51:55 +000032using namespace llvm;
33
34#define DEBUG_TYPE "wasm"
35
Derek Schufff41f67d2016-08-01 21:34:04 +000036// Emscripten's asm.js-style exception handling
Derek Schuffccdceda2016-08-18 15:27:25 +000037static cl::opt<bool> EnableEmException(
Derek Schuff53b9af02016-08-09 00:29:55 +000038 "enable-emscripten-cxx-exceptions",
Derek Schufff41f67d2016-08-01 21:34:04 +000039 cl::desc("WebAssembly Emscripten-style exception handling"),
40 cl::init(false));
41
Derek Schuffccdceda2016-08-18 15:27:25 +000042// Emscripten's asm.js-style setjmp/longjmp handling
43static cl::opt<bool> EnableEmSjLj(
44 "enable-emscripten-sjlj",
45 cl::desc("WebAssembly Emscripten-style setjmp/longjmp handling"),
46 cl::init(false));
47
Dan Gohman10e730a2015-06-29 23:51:55 +000048extern "C" void LLVMInitializeWebAssemblyTarget() {
49 // Register the target.
Mehdi Aminif42454b2016-10-09 23:00:34 +000050 RegisterTargetMachine<WebAssemblyTargetMachine> X(
51 getTheWebAssemblyTarget32());
52 RegisterTargetMachine<WebAssemblyTargetMachine> Y(
53 getTheWebAssemblyTarget64());
Derek Schufff41f67d2016-08-01 21:34:04 +000054
Jacob Gravelle40926452018-03-30 20:36:58 +000055 // Register backend passes
56 auto &PR = *PassRegistry::getPassRegistry();
Sam Clegg92617552018-07-11 04:29:36 +000057 initializeWebAssemblyAddMissingPrototypesPass(PR);
Jacob Gravelle40926452018-03-30 20:36:58 +000058 initializeWebAssemblyLowerEmscriptenEHSjLjPass(PR);
59 initializeLowerGlobalDtorsPass(PR);
60 initializeFixFunctionBitcastsPass(PR);
61 initializeOptimizeReturnedPass(PR);
62 initializeWebAssemblyArgumentMovePass(PR);
63 initializeWebAssemblySetP2AlignOperandsPass(PR);
64 initializeWebAssemblyReplacePhysRegsPass(PR);
65 initializeWebAssemblyPrepareForLiveIntervalsPass(PR);
66 initializeWebAssemblyOptimizeLiveIntervalsPass(PR);
Heejin Ahn321d5222019-01-08 22:35:18 +000067 initializeWebAssemblyMemIntrinsicResultsPass(PR);
Jacob Gravelle40926452018-03-30 20:36:58 +000068 initializeWebAssemblyRegStackifyPass(PR);
69 initializeWebAssemblyRegColoringPass(PR);
Jacob Gravelle40926452018-03-30 20:36:58 +000070 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);
Heejin Ahne9fd9072019-03-30 09:29:57 +000075 initializeWebAssemblyExplicitLocalsPass(PR);
Jacob Gravelle40926452018-03-30 20:36:58 +000076 initializeWebAssemblyLowerBrUnlessPass(PR);
77 initializeWebAssemblyRegNumberingPass(PR);
78 initializeWebAssemblyPeepholePass(PR);
79 initializeWebAssemblyCallIndirectFixupPass(PR);
Dan Gohman10e730a2015-06-29 23:51:55 +000080}
81
82//===----------------------------------------------------------------------===//
83// WebAssembly Lowering public interface.
84//===----------------------------------------------------------------------===//
85
Dan Gohman53572d02019-06-05 20:01:01 +000086static Reloc::Model getEffectiveRelocModel(Optional<Reloc::Model> RM,
87 const Triple &TT) {
Sam Clegg74f5fd42018-11-16 18:59:51 +000088 if (!RM.hasValue()) {
89 // Default to static relocation model. This should always be more optimial
90 // than PIC since the static linker can determine all global addresses and
91 // assume direct function calls.
92 return Reloc::Static;
93 }
Dan Gohman53572d02019-06-05 20:01:01 +000094
95 if (!TT.isOSEmscripten()) {
96 // Relocation modes other than static are currently implemented in a way
97 // that only works for Emscripten, so disable them if we aren't targeting
98 // Emscripten.
99 return Reloc::Static;
100 }
101
Dan Gohman41133a32016-05-19 03:00:05 +0000102 return *RM;
103}
104
Dan Gohman10e730a2015-06-29 23:51:55 +0000105/// Create an WebAssembly architecture model.
106///
107WebAssemblyTargetMachine::WebAssemblyTargetMachine(
108 const Target &T, const Triple &TT, StringRef CPU, StringRef FS,
Dan Gohman41133a32016-05-19 03:00:05 +0000109 const TargetOptions &Options, Optional<Reloc::Model> RM,
Daniel Jasper314ed202017-08-03 05:15:53 +0000110 Optional<CodeModel::Model> CM, CodeGenOpt::Level OL, bool JIT)
Matthias Braunbb8507e2017-10-12 22:57:28 +0000111 : LLVMTargetMachine(T,
112 TT.isArch64Bit() ? "e-m:e-p:64:64-i64:64-n32:64-S128"
113 : "e-m:e-p:32:32-i64:64-n32:64-S128",
Dan Gohman53572d02019-06-05 20:01:01 +0000114 TT, CPU, FS, Options, getEffectiveRelocModel(RM, TT),
David Greenca29c272018-12-07 12:10:23 +0000115 getEffectiveCodeModel(CM, CodeModel::Large), OL),
Sam Cleggcf2a9e22018-07-16 23:09:29 +0000116 TLOF(new WebAssemblyTargetObjectFile()) {
Dan Gohmane0405332016-10-03 22:43:53 +0000117 // WebAssembly type-checks instructions, but a noreturn function with a return
Derek Schuffffa143c2015-11-10 00:30:57 +0000118 // type that doesn't match the context will cause a check failure. So we lower
119 // LLVM 'unreachable' to ISD::TRAP and then lower that to WebAssembly's
Dan Gohmane0405332016-10-03 22:43:53 +0000120 // 'unreachable' instructions which is meant for that case.
Derek Schuffffa143c2015-11-10 00:30:57 +0000121 this->Options.TrapUnreachable = true;
122
Dan Gohmand934cb82017-02-24 23:18:00 +0000123 // WebAssembly treats each function as an independent unit. Force
124 // -ffunction-sections, effectively, so that we can emit them independently.
Sam Cleggcf2a9e22018-07-16 23:09:29 +0000125 this->Options.FunctionSections = true;
126 this->Options.DataSections = true;
127 this->Options.UniqueSectionNames = true;
Dan Gohmand934cb82017-02-24 23:18:00 +0000128
Dan Gohman10e730a2015-06-29 23:51:55 +0000129 initAsmInfo();
130
Dan Gohmand85ab7f2016-02-18 06:32:53 +0000131 // Note that we don't use setRequiresStructuredCFG(true). It disables
132 // optimizations than we're ok with, and want, such as critical edge
133 // splitting and tail merging.
Dan Gohman10e730a2015-06-29 23:51:55 +0000134}
135
Heejin Ahn18c56a02019-02-04 19:13:39 +0000136WebAssemblyTargetMachine::~WebAssemblyTargetMachine() = default; // anchor.
Dan Gohman10e730a2015-06-29 23:51:55 +0000137
138const WebAssemblySubtarget *
Thomas Livelyf3b4f992019-02-28 18:39:08 +0000139WebAssemblyTargetMachine::getSubtargetImpl(std::string CPU,
140 std::string FS) const {
141 auto &I = SubtargetMap[CPU + FS];
142 if (!I) {
143 I = llvm::make_unique<WebAssemblySubtarget>(TargetTriple, CPU, FS, *this);
Thomas Livelyf3b4f992019-02-28 18:39:08 +0000144 }
145 return I.get();
146}
147
148const WebAssemblySubtarget *
Dan Gohman10e730a2015-06-29 23:51:55 +0000149WebAssemblyTargetMachine::getSubtargetImpl(const Function &F) const {
150 Attribute CPUAttr = F.getFnAttribute("target-cpu");
151 Attribute FSAttr = F.getFnAttribute("target-features");
152
153 std::string CPU = !CPUAttr.hasAttribute(Attribute::None)
154 ? CPUAttr.getValueAsString().str()
155 : TargetCPU;
156 std::string FS = !FSAttr.hasAttribute(Attribute::None)
157 ? FSAttr.getValueAsString().str()
158 : TargetFS;
159
Thomas Livelyf3b4f992019-02-28 18:39:08 +0000160 // This needs to be done before we create a new subtarget since any
161 // creation will depend on the TM and the code generation flags on the
162 // function that reside in TargetOptions.
163 resetTargetOptions(F);
164
165 return getSubtargetImpl(CPU, FS);
Dan Gohman10e730a2015-06-29 23:51:55 +0000166}
167
168namespace {
Thomas Lively3f34e1b82019-03-29 00:14:01 +0000169
170class CoalesceFeaturesAndStripAtomics final : public ModulePass {
171 // Take the union of all features used in the module and use it for each
172 // function individually, since having multiple feature sets in one module
173 // currently does not make sense for WebAssembly. If atomics are not enabled,
174 // also strip atomic operations and thread local storage.
Derek Schuff39b53672018-03-20 22:01:32 +0000175 static char ID;
Thomas Lively3f34e1b82019-03-29 00:14:01 +0000176 WebAssemblyTargetMachine *WasmTM;
Derek Schuff39b53672018-03-20 22:01:32 +0000177
Heejin Ahnf208f632018-09-05 01:27:38 +0000178public:
Thomas Lively3f34e1b82019-03-29 00:14:01 +0000179 CoalesceFeaturesAndStripAtomics(WebAssemblyTargetMachine *WasmTM)
180 : ModulePass(ID), WasmTM(WasmTM) {}
181
Derek Schuff39b53672018-03-20 22:01:32 +0000182 bool runOnModule(Module &M) override {
Thomas Lively3f34e1b82019-03-29 00:14:01 +0000183 FeatureBitset Features = coalesceFeatures(M);
184
185 std::string FeatureStr = getFeatureString(Features);
186 for (auto &F : M)
187 replaceFeatures(F, FeatureStr);
188
189 bool Stripped = false;
190 if (!Features[WebAssembly::FeatureAtomics]) {
191 Stripped |= stripAtomics(M);
192 Stripped |= stripThreadLocals(M);
193 }
194
195 recordFeatures(M, Features, Stripped);
196
197 // Conservatively assume we have made some change
Derek Schuff39b53672018-03-20 22:01:32 +0000198 return true;
199 }
Thomas Lively3f34e1b82019-03-29 00:14:01 +0000200
201private:
202 FeatureBitset coalesceFeatures(const Module &M) {
203 FeatureBitset Features =
204 WasmTM
205 ->getSubtargetImpl(WasmTM->getTargetCPU(),
206 WasmTM->getTargetFeatureString())
207 ->getFeatureBits();
208 for (auto &F : M)
209 Features |= WasmTM->getSubtargetImpl(F)->getFeatureBits();
210 return Features;
211 }
212
213 std::string getFeatureString(const FeatureBitset &Features) {
214 std::string Ret;
215 for (const SubtargetFeatureKV &KV : WebAssemblyFeatureKV) {
216 if (Features[KV.Value])
217 Ret += (StringRef("+") + KV.Key + ",").str();
218 }
219 return Ret;
220 }
221
222 void replaceFeatures(Function &F, const std::string &Features) {
223 F.removeFnAttr("target-features");
224 F.removeFnAttr("target-cpu");
225 F.addFnAttr("target-features", Features);
226 }
227
228 bool stripAtomics(Module &M) {
229 // Detect whether any atomics will be lowered, since there is no way to tell
230 // whether the LowerAtomic pass lowers e.g. stores.
231 bool Stripped = false;
232 for (auto &F : M) {
233 for (auto &B : F) {
234 for (auto &I : B) {
235 if (I.isAtomic()) {
236 Stripped = true;
237 goto done;
238 }
239 }
240 }
241 }
242
243 done:
244 if (!Stripped)
245 return false;
246
247 LowerAtomicPass Lowerer;
248 FunctionAnalysisManager FAM;
249 for (auto &F : M)
250 Lowerer.run(F, FAM);
251
252 return true;
253 }
254
255 bool stripThreadLocals(Module &M) {
256 bool Stripped = false;
257 for (auto &GV : M.globals()) {
258 if (GV.getThreadLocalMode() !=
259 GlobalValue::ThreadLocalMode::NotThreadLocal) {
260 Stripped = true;
261 GV.setThreadLocalMode(GlobalValue::ThreadLocalMode::NotThreadLocal);
262 }
263 }
264 return Stripped;
265 }
266
267 void recordFeatures(Module &M, const FeatureBitset &Features, bool Stripped) {
268 for (const SubtargetFeatureKV &KV : WebAssemblyFeatureKV) {
269 std::string MDKey = (StringRef("wasm-feature-") + KV.Key).str();
270 if (KV.Value == WebAssembly::FeatureAtomics && Stripped) {
271 // "atomics" is special: code compiled without atomics may have had its
272 // atomics lowered to nonatomic operations. In that case, atomics is
273 // disallowed to prevent unsafe linking with atomics-enabled objects.
274 assert(!Features[WebAssembly::FeatureAtomics]);
275 M.addModuleFlag(Module::ModFlagBehavior::Error, MDKey,
276 wasm::WASM_FEATURE_PREFIX_DISALLOWED);
277 } else if (Features[KV.Value]) {
278 // Otherwise features are marked Used or not mentioned
279 M.addModuleFlag(Module::ModFlagBehavior::Error, MDKey,
280 wasm::WASM_FEATURE_PREFIX_USED);
281 }
282 }
283 }
Derek Schuff39b53672018-03-20 22:01:32 +0000284};
Thomas Lively3f34e1b82019-03-29 00:14:01 +0000285char CoalesceFeaturesAndStripAtomics::ID = 0;
Derek Schuff39b53672018-03-20 22:01:32 +0000286
Dan Gohman10e730a2015-06-29 23:51:55 +0000287/// WebAssembly Code Generator Pass Configuration Options.
288class WebAssemblyPassConfig final : public TargetPassConfig {
289public:
Matthias Braun5e394c32017-05-30 21:36:41 +0000290 WebAssemblyPassConfig(WebAssemblyTargetMachine &TM, PassManagerBase &PM)
Dan Gohman10e730a2015-06-29 23:51:55 +0000291 : TargetPassConfig(TM, PM) {}
292
293 WebAssemblyTargetMachine &getWebAssemblyTargetMachine() const {
294 return getTM<WebAssemblyTargetMachine>();
295 }
296
297 FunctionPass *createTargetRegisterAllocator(bool) override;
Dan Gohman10e730a2015-06-29 23:51:55 +0000298
299 void addIRPasses() override;
Dan Gohman10e730a2015-06-29 23:51:55 +0000300 bool addInstSelector() override;
Dan Gohman10e730a2015-06-29 23:51:55 +0000301 void addPostRegAlloc() override;
Derek Schuffad154c82016-03-28 17:05:30 +0000302 bool addGCPasses() override { return false; }
Dan Gohman10e730a2015-06-29 23:51:55 +0000303 void addPreEmitPass() override;
Matt Arsenaultcf55a652019-03-19 19:33:12 +0000304
305 // No reg alloc
306 bool addRegAssignmentFast() override { return false; }
307
308 // No reg alloc
309 bool addRegAssignmentOptimized() override { return false; }
Dan Gohman10e730a2015-06-29 23:51:55 +0000310};
311} // end anonymous namespace
312
Sanjoy Das26d11ca2017-12-22 18:21:59 +0000313TargetTransformInfo
314WebAssemblyTargetMachine::getTargetTransformInfo(const Function &F) {
315 return TargetTransformInfo(WebAssemblyTTIImpl(this, F));
Dan Gohman10e730a2015-06-29 23:51:55 +0000316}
317
318TargetPassConfig *
319WebAssemblyTargetMachine::createPassConfig(PassManagerBase &PM) {
Matthias Braun5e394c32017-05-30 21:36:41 +0000320 return new WebAssemblyPassConfig(*this, PM);
Dan Gohman10e730a2015-06-29 23:51:55 +0000321}
322
323FunctionPass *WebAssemblyPassConfig::createTargetRegisterAllocator(bool) {
324 return nullptr; // No reg alloc
325}
326
Dan Gohman10e730a2015-06-29 23:51:55 +0000327//===----------------------------------------------------------------------===//
328// The following functions are called from lib/CodeGen/Passes.cpp to modify
329// the CodeGen pass sequence.
330//===----------------------------------------------------------------------===//
331
332void WebAssemblyPassConfig::addIRPasses() {
Thomas Lively3f34e1b82019-03-29 00:14:01 +0000333 // Runs LowerAtomicPass if necessary
334 addPass(new CoalesceFeaturesAndStripAtomics(&getWebAssemblyTargetMachine()));
335
336 // This is a no-op if atomics are not used in the module
337 addPass(createAtomicExpandPass());
Dan Gohman10e730a2015-06-29 23:51:55 +0000338
Sam Clegg92617552018-07-11 04:29:36 +0000339 // Add signatures to prototype-less function declarations
340 addPass(createWebAssemblyAddMissingPrototypes());
341
Sam Cleggbafe6902017-12-15 00:17:10 +0000342 // Lower .llvm.global_dtors into .llvm_global_ctors with __cxa_atexit calls.
343 addPass(createWebAssemblyLowerGlobalDtors());
344
Dan Gohman1b637452017-01-07 00:34:54 +0000345 // Fix function bitcasts, as WebAssembly requires caller and callee signatures
346 // to match.
347 addPass(createWebAssemblyFixFunctionBitcasts());
348
Dan Gohman81719f82015-11-25 16:55:01 +0000349 // Optimize "returned" function attributes.
Dan Gohmanb13c91f2016-01-19 14:55:02 +0000350 if (getOptLevel() != CodeGenOpt::None)
351 addPass(createWebAssemblyOptimizeReturned());
Dan Gohman81719f82015-11-25 16:55:01 +0000352
Heejin Ahnc0f18172016-09-01 21:05:15 +0000353 // If exception handling is not enabled and setjmp/longjmp handling is
354 // enabled, we lower invokes into calls and delete unreachable landingpad
355 // blocks. Lowering invokes when there is no EH support is done in
356 // TargetPassConfig::addPassesToHandleExceptions, but this runs after this
357 // function and SjLj handling expects all invokes to be lowered before.
Heejin Ahn9386bde2018-02-24 00:40:50 +0000358 if (!EnableEmException &&
359 TM->Options.ExceptionModel == ExceptionHandling::None) {
Heejin Ahnc0f18172016-09-01 21:05:15 +0000360 addPass(createLowerInvokePass());
361 // The lower invoke pass may create unreachable code. Remove it in order not
362 // to process dead blocks in setjmp/longjmp handling.
363 addPass(createUnreachableBlockEliminationPass());
364 }
365
366 // Handle exceptions and setjmp/longjmp if enabled.
Derek Schuffccdceda2016-08-18 15:27:25 +0000367 if (EnableEmException || EnableEmSjLj)
368 addPass(createWebAssemblyLowerEmscriptenEHSjLj(EnableEmException,
369 EnableEmSjLj));
Derek Schufff41f67d2016-08-01 21:34:04 +0000370
Dan Gohman10e730a2015-06-29 23:51:55 +0000371 TargetPassConfig::addIRPasses();
372}
373
Dan Gohman10e730a2015-06-29 23:51:55 +0000374bool WebAssemblyPassConfig::addInstSelector() {
Dan Gohmanb0921ca2015-12-05 19:24:17 +0000375 (void)TargetPassConfig::addInstSelector();
Dan Gohman10e730a2015-06-29 23:51:55 +0000376 addPass(
377 createWebAssemblyISelDag(getWebAssemblyTargetMachine(), getOptLevel()));
Dan Gohman1cf96c02015-12-09 16:23:59 +0000378 // Run the argument-move pass immediately after the ScheduleDAG scheduler
379 // so that we can fix up the ARGUMENT instructions before anything else
380 // sees them in the wrong place.
381 addPass(createWebAssemblyArgumentMove());
Dan Gohmanbb372242016-01-26 03:39:31 +0000382 // Set the p2align operands. This information is present during ISel, however
383 // it's inconvenient to collect. Collect it now, and update the immediate
384 // operands.
385 addPass(createWebAssemblySetP2AlignOperands());
Dan Gohman10e730a2015-06-29 23:51:55 +0000386 return false;
387}
388
JF Bastien600aee92015-07-31 17:53:38 +0000389void WebAssemblyPassConfig::addPostRegAlloc() {
Dan Gohman9c54d3b2015-11-25 18:13:18 +0000390 // TODO: The following CodeGen passes don't currently support code containing
391 // virtual registers. Consider removing their restrictions and re-enabling
392 // them.
Derek Schuffad154c82016-03-28 17:05:30 +0000393
Matthias Braun1eb47362016-08-25 01:27:13 +0000394 // These functions all require the NoVRegs property.
JF Bastien600aee92015-07-31 17:53:38 +0000395 disablePass(&MachineCopyPropagationID);
Jun Bum Lim7ab1b322018-04-03 18:17:34 +0000396 disablePass(&PostRAMachineSinkingID);
Derek Schuffecabac62016-03-28 22:52:20 +0000397 disablePass(&PostRASchedulerID);
398 disablePass(&FuncletLayoutID);
399 disablePass(&StackMapLivenessID);
400 disablePass(&LiveDebugValuesID);
Sanjoy Dasfe71ec72016-04-19 06:24:58 +0000401 disablePass(&PatchableFunctionID);
Jun Bum Lim7ab1b322018-04-03 18:17:34 +0000402 disablePass(&ShrinkWrapID);
Dan Gohman950a13c2015-09-16 16:51:30 +0000403
Heejin Ahnef9d6ae2019-03-05 20:35:34 +0000404 // This pass hurts code size for wasm because it can generate irreducible
405 // control flow.
406 disablePass(&MachineBlockPlacementID);
407
Dan Gohmanb0921ca2015-12-05 19:24:17 +0000408 TargetPassConfig::addPostRegAlloc();
JF Bastien600aee92015-07-31 17:53:38 +0000409}
Dan Gohman10e730a2015-06-29 23:51:55 +0000410
Dan Gohman950a13c2015-09-16 16:51:30 +0000411void WebAssemblyPassConfig::addPreEmitPass() {
Dan Gohmanb0921ca2015-12-05 19:24:17 +0000412 TargetPassConfig::addPreEmitPass();
Dan Gohman05ac43f2015-12-17 01:39:00 +0000413
Derek Schuff6f697832016-10-21 16:38:07 +0000414 // Rewrite pseudo call_indirect instructions as real instructions.
415 // This needs to run before register stackification, because we change the
416 // order of the arguments.
417 addPass(createWebAssemblyCallIndirectFixup());
418
Heejin Ahne95056d2019-01-08 01:25:12 +0000419 // Eliminate multiple-entry loops.
420 addPass(createWebAssemblyFixIrreducibleControlFlow());
421
422 // Do various transformations for exception handling.
Heejin Ahnd6f48782019-01-30 03:21:57 +0000423 // Every CFG-changing optimizations should come before this.
Heejin Ahne95056d2019-01-08 01:25:12 +0000424 addPass(createWebAssemblyLateEHPrepare());
425
Heejin Ahn0bb98652019-01-30 22:44:45 +0000426 // Now that we have a prologue and epilogue and all frame indices are
427 // rewritten, eliminate SP and FP. This allows them to be stackified,
428 // colored, and numbered with the rest of the registers.
429 addPass(createWebAssemblyReplacePhysRegs());
430
Heejin Ahnd6f48782019-01-30 03:21:57 +0000431 // Preparations and optimizations related to register stackification.
Dan Gohman0cfb5f82016-05-10 04:24:02 +0000432 if (getOptLevel() != CodeGenOpt::None) {
433 // LiveIntervals isn't commonly run this late. Re-establish preconditions.
434 addPass(createWebAssemblyPrepareForLiveIntervals());
435
436 // Depend on LiveIntervals and perform some optimizations on it.
437 addPass(createWebAssemblyOptimizeLiveIntervals());
438
Heejin Ahn321d5222019-01-08 22:35:18 +0000439 // Prepare memory intrinsic calls for register stackifying.
440 addPass(createWebAssemblyMemIntrinsicResults());
Dan Gohman0cfb5f82016-05-10 04:24:02 +0000441
Dan Gohmane0405332016-10-03 22:43:53 +0000442 // Mark registers as representing wasm's value stack. This is a key
Dan Gohman0cfb5f82016-05-10 04:24:02 +0000443 // code-compression technique in WebAssembly. We run this pass (and
Heejin Ahn321d5222019-01-08 22:35:18 +0000444 // MemIntrinsicResults above) very late, so that it sees as much code as
445 // possible, including code emitted by PEI and expanded by late tail
446 // duplication.
Dan Gohman0cfb5f82016-05-10 04:24:02 +0000447 addPass(createWebAssemblyRegStackify());
448
449 // Run the register coloring pass to reduce the total number of registers.
450 // This runs after stackification so that it doesn't consider registers
451 // that become stackified.
452 addPass(createWebAssemblyRegColoring());
453 }
454
Dan Gohmanf52ee172017-02-27 22:38:58 +0000455 // Sort the blocks of the CFG into topological order, a prerequisite for
456 // BLOCK and LOOP markers.
457 addPass(createWebAssemblyCFGSort());
458
459 // Insert BLOCK and LOOP markers.
Dan Gohman950a13c2015-09-16 16:51:30 +0000460 addPass(createWebAssemblyCFGStackify());
Dan Gohman5941bde2015-11-25 21:32:06 +0000461
Heejin Ahne9fd9072019-03-30 09:29:57 +0000462 // Insert explicit local.get and local.set operators.
463 addPass(createWebAssemblyExplicitLocals());
464
Dan Gohmanf0b165a2015-12-05 03:03:35 +0000465 // Lower br_unless into br_if.
466 addPass(createWebAssemblyLowerBrUnless());
467
Dan Gohman5941bde2015-11-25 21:32:06 +0000468 // Perform the very last peephole optimizations on the code.
Dan Gohmanb13c91f2016-01-19 14:55:02 +0000469 if (getOptLevel() != CodeGenOpt::None)
470 addPass(createWebAssemblyPeephole());
Dan Gohmanb7c24002016-05-21 00:21:56 +0000471
472 // Create a mapping from LLVM CodeGen virtual registers to wasm registers.
473 addPass(createWebAssemblyRegNumbering());
Dan Gohman950a13c2015-09-16 16:51:30 +0000474}
Heejin Ahn52221d52019-03-26 17:35:35 +0000475
476yaml::MachineFunctionInfo *
477WebAssemblyTargetMachine::createDefaultFuncInfoYAML() const {
478 return new yaml::WebAssemblyFunctionInfo();
479}
480
481yaml::MachineFunctionInfo *WebAssemblyTargetMachine::convertFuncInfoToYAML(
482 const MachineFunction &MF) const {
483 const auto *MFI = MF.getInfo<WebAssemblyFunctionInfo>();
484 return new yaml::WebAssemblyFunctionInfo(*MFI);
485}
486
487bool WebAssemblyTargetMachine::parseMachineFunctionInfo(
488 const yaml::MachineFunctionInfo &MFI, PerFunctionMIParsingState &PFS,
489 SMDiagnostic &Error, SMRange &SourceRange) const {
490 const auto &YamlMFI =
491 reinterpret_cast<const yaml::WebAssemblyFunctionInfo &>(MFI);
492 MachineFunction &MF = PFS.MF;
493 MF.getInfo<WebAssemblyFunctionInfo>()->initializeBaseYamlFields(YamlMFI);
494 return false;
495}