xref: /llvm-project/llvm/lib/Target/WebAssembly/WebAssemblyTargetMachine.cpp (revision d7086af2143d58a6535e0837c4d8789c69c6985f)
1 //===- WebAssemblyTargetMachine.cpp - Define TargetMachine for WebAssembly -==//
2 //
3 // 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
6 //
7 //===----------------------------------------------------------------------===//
8 ///
9 /// \file
10 /// This file defines the WebAssembly-specific subclass of TargetMachine.
11 ///
12 //===----------------------------------------------------------------------===//
13 
14 #include "WebAssemblyTargetMachine.h"
15 #include "MCTargetDesc/WebAssemblyMCTargetDesc.h"
16 #include "TargetInfo/WebAssemblyTargetInfo.h"
17 #include "WebAssembly.h"
18 #include "WebAssemblyMachineFunctionInfo.h"
19 #include "WebAssemblyTargetObjectFile.h"
20 #include "WebAssemblyTargetTransformInfo.h"
21 #include "llvm/CodeGen/MIRParser/MIParser.h"
22 #include "llvm/CodeGen/MachineFunctionPass.h"
23 #include "llvm/CodeGen/Passes.h"
24 #include "llvm/CodeGen/RegAllocRegistry.h"
25 #include "llvm/CodeGen/TargetPassConfig.h"
26 #include "llvm/IR/Function.h"
27 #include "llvm/Support/TargetRegistry.h"
28 #include "llvm/Target/TargetOptions.h"
29 #include "llvm/Transforms/Scalar.h"
30 #include "llvm/Transforms/Scalar/LowerAtomic.h"
31 #include "llvm/Transforms/Utils.h"
32 using namespace llvm;
33 
34 #define DEBUG_TYPE "wasm"
35 
36 // Emscripten's asm.js-style exception handling
37 cl::opt<bool> EnableEmException(
38     "enable-emscripten-cxx-exceptions",
39     cl::desc("WebAssembly Emscripten-style exception handling"),
40     cl::init(false));
41 
42 // Emscripten's asm.js-style setjmp/longjmp handling
43 cl::opt<bool> EnableEmSjLj(
44     "enable-emscripten-sjlj",
45     cl::desc("WebAssembly Emscripten-style setjmp/longjmp handling"),
46     cl::init(false));
47 
48 // A command-line option to keep implicit locals
49 // for the purpose of testing with lit/llc ONLY.
50 // This produces output which is not valid WebAssembly, and is not supported
51 // by assemblers/disassemblers and other MC based tools.
52 static cl::opt<bool> WasmDisableExplicitLocals(
53     "wasm-disable-explicit-locals", cl::Hidden,
54     cl::desc("WebAssembly: output implicit locals in"
55              " instruction output for test purposes only."),
56     cl::init(false));
57 
58 extern "C" LLVM_EXTERNAL_VISIBILITY void LLVMInitializeWebAssemblyTarget() {
59   // Register the target.
60   RegisterTargetMachine<WebAssemblyTargetMachine> X(
61       getTheWebAssemblyTarget32());
62   RegisterTargetMachine<WebAssemblyTargetMachine> Y(
63       getTheWebAssemblyTarget64());
64 
65   // Register backend passes
66   auto &PR = *PassRegistry::getPassRegistry();
67   initializeWebAssemblyAddMissingPrototypesPass(PR);
68   initializeWebAssemblyLowerEmscriptenEHSjLjPass(PR);
69   initializeLowerGlobalDtorsPass(PR);
70   initializeFixFunctionBitcastsPass(PR);
71   initializeOptimizeReturnedPass(PR);
72   initializeWebAssemblyArgumentMovePass(PR);
73   initializeWebAssemblySetP2AlignOperandsPass(PR);
74   initializeWebAssemblyReplacePhysRegsPass(PR);
75   initializeWebAssemblyPrepareForLiveIntervalsPass(PR);
76   initializeWebAssemblyOptimizeLiveIntervalsPass(PR);
77   initializeWebAssemblyMemIntrinsicResultsPass(PR);
78   initializeWebAssemblyRegStackifyPass(PR);
79   initializeWebAssemblyRegColoringPass(PR);
80   initializeWebAssemblyFixIrreducibleControlFlowPass(PR);
81   initializeWebAssemblyLateEHPreparePass(PR);
82   initializeWebAssemblyExceptionInfoPass(PR);
83   initializeWebAssemblyCFGSortPass(PR);
84   initializeWebAssemblyCFGStackifyPass(PR);
85   initializeWebAssemblyExplicitLocalsPass(PR);
86   initializeWebAssemblyLowerBrUnlessPass(PR);
87   initializeWebAssemblyRegNumberingPass(PR);
88   initializeWebAssemblyDebugFixupPass(PR);
89   initializeWebAssemblyPeepholePass(PR);
90 }
91 
92 //===----------------------------------------------------------------------===//
93 // WebAssembly Lowering public interface.
94 //===----------------------------------------------------------------------===//
95 
96 static Reloc::Model getEffectiveRelocModel(Optional<Reloc::Model> RM,
97                                            const Triple &TT) {
98   if (!RM.hasValue()) {
99     // Default to static relocation model.  This should always be more optimial
100     // than PIC since the static linker can determine all global addresses and
101     // assume direct function calls.
102     return Reloc::Static;
103   }
104 
105   if (!TT.isOSEmscripten()) {
106     // Relocation modes other than static are currently implemented in a way
107     // that only works for Emscripten, so disable them if we aren't targeting
108     // Emscripten.
109     return Reloc::Static;
110   }
111 
112   return *RM;
113 }
114 
115 /// Create an WebAssembly architecture model.
116 ///
117 WebAssemblyTargetMachine::WebAssemblyTargetMachine(
118     const Target &T, const Triple &TT, StringRef CPU, StringRef FS,
119     const TargetOptions &Options, Optional<Reloc::Model> RM,
120     Optional<CodeModel::Model> CM, CodeGenOpt::Level OL, bool JIT)
121     : LLVMTargetMachine(T,
122                         TT.isArch64Bit()
123                             ? "e-m:e-p:64:64-i64:64-n32:64-S128-ni:1"
124                             : "e-m:e-p:32:32-i64:64-n32:64-S128-ni:1",
125                         TT, CPU, FS, Options, getEffectiveRelocModel(RM, TT),
126                         getEffectiveCodeModel(CM, CodeModel::Large), OL),
127       TLOF(new WebAssemblyTargetObjectFile()) {
128   // WebAssembly type-checks instructions, but a noreturn function with a return
129   // type that doesn't match the context will cause a check failure. So we lower
130   // LLVM 'unreachable' to ISD::TRAP and then lower that to WebAssembly's
131   // 'unreachable' instructions which is meant for that case.
132   this->Options.TrapUnreachable = true;
133 
134   // WebAssembly treats each function as an independent unit. Force
135   // -ffunction-sections, effectively, so that we can emit them independently.
136   this->Options.FunctionSections = true;
137   this->Options.DataSections = true;
138   this->Options.UniqueSectionNames = true;
139 
140   initAsmInfo();
141 
142   // Note that we don't use setRequiresStructuredCFG(true). It disables
143   // optimizations than we're ok with, and want, such as critical edge
144   // splitting and tail merging.
145 }
146 
147 WebAssemblyTargetMachine::~WebAssemblyTargetMachine() = default; // anchor.
148 
149 const WebAssemblySubtarget *WebAssemblyTargetMachine::getSubtargetImpl() const {
150   return getSubtargetImpl(std::string(getTargetCPU()),
151                           std::string(getTargetFeatureString()));
152 }
153 
154 const WebAssemblySubtarget *
155 WebAssemblyTargetMachine::getSubtargetImpl(std::string CPU,
156                                            std::string FS) const {
157   auto &I = SubtargetMap[CPU + FS];
158   if (!I) {
159     I = std::make_unique<WebAssemblySubtarget>(TargetTriple, CPU, FS, *this);
160   }
161   return I.get();
162 }
163 
164 const WebAssemblySubtarget *
165 WebAssemblyTargetMachine::getSubtargetImpl(const Function &F) const {
166   Attribute CPUAttr = F.getFnAttribute("target-cpu");
167   Attribute FSAttr = F.getFnAttribute("target-features");
168 
169   std::string CPU =
170       CPUAttr.isValid() ? CPUAttr.getValueAsString().str() : TargetCPU;
171   std::string FS =
172       FSAttr.isValid() ? FSAttr.getValueAsString().str() : TargetFS;
173 
174   // This needs to be done before we create a new subtarget since any
175   // creation will depend on the TM and the code generation flags on the
176   // function that reside in TargetOptions.
177   resetTargetOptions(F);
178 
179   return getSubtargetImpl(CPU, FS);
180 }
181 
182 namespace {
183 
184 class CoalesceFeaturesAndStripAtomics final : public ModulePass {
185   // Take the union of all features used in the module and use it for each
186   // function individually, since having multiple feature sets in one module
187   // currently does not make sense for WebAssembly. If atomics are not enabled,
188   // also strip atomic operations and thread local storage.
189   static char ID;
190   WebAssemblyTargetMachine *WasmTM;
191 
192 public:
193   CoalesceFeaturesAndStripAtomics(WebAssemblyTargetMachine *WasmTM)
194       : ModulePass(ID), WasmTM(WasmTM) {}
195 
196   bool runOnModule(Module &M) override {
197     FeatureBitset Features = coalesceFeatures(M);
198 
199     std::string FeatureStr = getFeatureString(Features);
200     WasmTM->setTargetFeatureString(FeatureStr);
201     for (auto &F : M)
202       replaceFeatures(F, FeatureStr);
203 
204     bool StrippedAtomics = false;
205     bool StrippedTLS = false;
206 
207     if (!Features[WebAssembly::FeatureAtomics])
208       StrippedAtomics = stripAtomics(M);
209 
210     if (!Features[WebAssembly::FeatureBulkMemory])
211       StrippedTLS = stripThreadLocals(M);
212 
213     if (StrippedAtomics && !StrippedTLS)
214       stripThreadLocals(M);
215     else if (StrippedTLS && !StrippedAtomics)
216       stripAtomics(M);
217 
218     recordFeatures(M, Features, StrippedAtomics || StrippedTLS);
219 
220     // Conservatively assume we have made some change
221     return true;
222   }
223 
224 private:
225   FeatureBitset coalesceFeatures(const Module &M) {
226     FeatureBitset Features =
227         WasmTM
228             ->getSubtargetImpl(std::string(WasmTM->getTargetCPU()),
229                                std::string(WasmTM->getTargetFeatureString()))
230             ->getFeatureBits();
231     for (auto &F : M)
232       Features |= WasmTM->getSubtargetImpl(F)->getFeatureBits();
233     return Features;
234   }
235 
236   std::string getFeatureString(const FeatureBitset &Features) {
237     std::string Ret;
238     for (const SubtargetFeatureKV &KV : WebAssemblyFeatureKV) {
239       if (Features[KV.Value])
240         Ret += (StringRef("+") + KV.Key + ",").str();
241     }
242     return Ret;
243   }
244 
245   void replaceFeatures(Function &F, const std::string &Features) {
246     F.removeFnAttr("target-features");
247     F.removeFnAttr("target-cpu");
248     F.addFnAttr("target-features", Features);
249   }
250 
251   bool stripAtomics(Module &M) {
252     // Detect whether any atomics will be lowered, since there is no way to tell
253     // whether the LowerAtomic pass lowers e.g. stores.
254     bool Stripped = false;
255     for (auto &F : M) {
256       for (auto &B : F) {
257         for (auto &I : B) {
258           if (I.isAtomic()) {
259             Stripped = true;
260             goto done;
261           }
262         }
263       }
264     }
265 
266   done:
267     if (!Stripped)
268       return false;
269 
270     LowerAtomicPass Lowerer;
271     FunctionAnalysisManager FAM;
272     for (auto &F : M)
273       Lowerer.run(F, FAM);
274 
275     return true;
276   }
277 
278   bool stripThreadLocals(Module &M) {
279     bool Stripped = false;
280     for (auto &GV : M.globals()) {
281       if (GV.isThreadLocal()) {
282         Stripped = true;
283         GV.setThreadLocal(false);
284       }
285     }
286     return Stripped;
287   }
288 
289   void recordFeatures(Module &M, const FeatureBitset &Features, bool Stripped) {
290     for (const SubtargetFeatureKV &KV : WebAssemblyFeatureKV) {
291       if (Features[KV.Value]) {
292         // Mark features as used
293         std::string MDKey = (StringRef("wasm-feature-") + KV.Key).str();
294         M.addModuleFlag(Module::ModFlagBehavior::Error, MDKey,
295                         wasm::WASM_FEATURE_PREFIX_USED);
296       }
297     }
298     // Code compiled without atomics or bulk-memory may have had its atomics or
299     // thread-local data lowered to nonatomic operations or non-thread-local
300     // data. In that case, we mark the pseudo-feature "shared-mem" as disallowed
301     // to tell the linker that it would be unsafe to allow this code ot be used
302     // in a module with shared memory.
303     if (Stripped) {
304       M.addModuleFlag(Module::ModFlagBehavior::Error, "wasm-feature-shared-mem",
305                       wasm::WASM_FEATURE_PREFIX_DISALLOWED);
306     }
307   }
308 };
309 char CoalesceFeaturesAndStripAtomics::ID = 0;
310 
311 /// WebAssembly Code Generator Pass Configuration Options.
312 class WebAssemblyPassConfig final : public TargetPassConfig {
313 public:
314   WebAssemblyPassConfig(WebAssemblyTargetMachine &TM, PassManagerBase &PM)
315       : TargetPassConfig(TM, PM) {}
316 
317   WebAssemblyTargetMachine &getWebAssemblyTargetMachine() const {
318     return getTM<WebAssemblyTargetMachine>();
319   }
320 
321   FunctionPass *createTargetRegisterAllocator(bool) override;
322 
323   void addIRPasses() override;
324   bool addInstSelector() override;
325   void addPostRegAlloc() override;
326   bool addGCPasses() override { return false; }
327   void addPreEmitPass() override;
328 
329   // No reg alloc
330   bool addRegAssignAndRewriteFast() override { return false; }
331 
332   // No reg alloc
333   bool addRegAssignAndRewriteOptimized() override { return false; }
334 };
335 } // end anonymous namespace
336 
337 TargetTransformInfo
338 WebAssemblyTargetMachine::getTargetTransformInfo(const Function &F) {
339   return TargetTransformInfo(WebAssemblyTTIImpl(this, F));
340 }
341 
342 TargetPassConfig *
343 WebAssemblyTargetMachine::createPassConfig(PassManagerBase &PM) {
344   return new WebAssemblyPassConfig(*this, PM);
345 }
346 
347 FunctionPass *WebAssemblyPassConfig::createTargetRegisterAllocator(bool) {
348   return nullptr; // No reg alloc
349 }
350 
351 //===----------------------------------------------------------------------===//
352 // The following functions are called from lib/CodeGen/Passes.cpp to modify
353 // the CodeGen pass sequence.
354 //===----------------------------------------------------------------------===//
355 
356 void WebAssemblyPassConfig::addIRPasses() {
357   // Lower atomics and TLS if necessary
358   addPass(new CoalesceFeaturesAndStripAtomics(&getWebAssemblyTargetMachine()));
359 
360   // This is a no-op if atomics are not used in the module
361   addPass(createAtomicExpandPass());
362 
363   // Add signatures to prototype-less function declarations
364   addPass(createWebAssemblyAddMissingPrototypes());
365 
366   // Lower .llvm.global_dtors into .llvm_global_ctors with __cxa_atexit calls.
367   addPass(createWebAssemblyLowerGlobalDtors());
368 
369   // Fix function bitcasts, as WebAssembly requires caller and callee signatures
370   // to match.
371   addPass(createWebAssemblyFixFunctionBitcasts());
372 
373   // Optimize "returned" function attributes.
374   if (getOptLevel() != CodeGenOpt::None)
375     addPass(createWebAssemblyOptimizeReturned());
376 
377   // If exception handling is not enabled and setjmp/longjmp handling is
378   // enabled, we lower invokes into calls and delete unreachable landingpad
379   // blocks. Lowering invokes when there is no EH support is done in
380   // TargetPassConfig::addPassesToHandleExceptions, but this runs after this
381   // function and SjLj handling expects all invokes to be lowered before.
382   if (!EnableEmException &&
383       TM->Options.ExceptionModel == ExceptionHandling::None) {
384     addPass(createLowerInvokePass());
385     // The lower invoke pass may create unreachable code. Remove it in order not
386     // to process dead blocks in setjmp/longjmp handling.
387     addPass(createUnreachableBlockEliminationPass());
388   }
389 
390   // Handle exceptions and setjmp/longjmp if enabled.
391   if (EnableEmException || EnableEmSjLj)
392     addPass(createWebAssemblyLowerEmscriptenEHSjLj(EnableEmException,
393                                                    EnableEmSjLj));
394 
395   // Expand indirectbr instructions to switches.
396   addPass(createIndirectBrExpandPass());
397 
398   TargetPassConfig::addIRPasses();
399 }
400 
401 bool WebAssemblyPassConfig::addInstSelector() {
402   (void)TargetPassConfig::addInstSelector();
403   addPass(
404       createWebAssemblyISelDag(getWebAssemblyTargetMachine(), getOptLevel()));
405   // Run the argument-move pass immediately after the ScheduleDAG scheduler
406   // so that we can fix up the ARGUMENT instructions before anything else
407   // sees them in the wrong place.
408   addPass(createWebAssemblyArgumentMove());
409   // Set the p2align operands. This information is present during ISel, however
410   // it's inconvenient to collect. Collect it now, and update the immediate
411   // operands.
412   addPass(createWebAssemblySetP2AlignOperands());
413 
414   // Eliminate range checks and add default targets to br_table instructions.
415   addPass(createWebAssemblyFixBrTableDefaults());
416 
417   return false;
418 }
419 
420 void WebAssemblyPassConfig::addPostRegAlloc() {
421   // TODO: The following CodeGen passes don't currently support code containing
422   // virtual registers. Consider removing their restrictions and re-enabling
423   // them.
424 
425   // These functions all require the NoVRegs property.
426   disablePass(&MachineCopyPropagationID);
427   disablePass(&PostRAMachineSinkingID);
428   disablePass(&PostRASchedulerID);
429   disablePass(&FuncletLayoutID);
430   disablePass(&StackMapLivenessID);
431   disablePass(&LiveDebugValuesID);
432   disablePass(&PatchableFunctionID);
433   disablePass(&ShrinkWrapID);
434 
435   // This pass hurts code size for wasm because it can generate irreducible
436   // control flow.
437   disablePass(&MachineBlockPlacementID);
438 
439   TargetPassConfig::addPostRegAlloc();
440 }
441 
442 void WebAssemblyPassConfig::addPreEmitPass() {
443   TargetPassConfig::addPreEmitPass();
444 
445   // Eliminate multiple-entry loops.
446   addPass(createWebAssemblyFixIrreducibleControlFlow());
447 
448   // Do various transformations for exception handling.
449   // Every CFG-changing optimizations should come before this.
450   if (TM->Options.ExceptionModel == ExceptionHandling::Wasm)
451     addPass(createWebAssemblyLateEHPrepare());
452 
453   // Now that we have a prologue and epilogue and all frame indices are
454   // rewritten, eliminate SP and FP. This allows them to be stackified,
455   // colored, and numbered with the rest of the registers.
456   addPass(createWebAssemblyReplacePhysRegs());
457 
458   // Preparations and optimizations related to register stackification.
459   if (getOptLevel() != CodeGenOpt::None) {
460     // LiveIntervals isn't commonly run this late. Re-establish preconditions.
461     addPass(createWebAssemblyPrepareForLiveIntervals());
462 
463     // Depend on LiveIntervals and perform some optimizations on it.
464     addPass(createWebAssemblyOptimizeLiveIntervals());
465 
466     // Prepare memory intrinsic calls for register stackifying.
467     addPass(createWebAssemblyMemIntrinsicResults());
468 
469     // Mark registers as representing wasm's value stack. This is a key
470     // code-compression technique in WebAssembly. We run this pass (and
471     // MemIntrinsicResults above) very late, so that it sees as much code as
472     // possible, including code emitted by PEI and expanded by late tail
473     // duplication.
474     addPass(createWebAssemblyRegStackify());
475 
476     // Run the register coloring pass to reduce the total number of registers.
477     // This runs after stackification so that it doesn't consider registers
478     // that become stackified.
479     addPass(createWebAssemblyRegColoring());
480   }
481 
482   // Sort the blocks of the CFG into topological order, a prerequisite for
483   // BLOCK and LOOP markers.
484   addPass(createWebAssemblyCFGSort());
485 
486   // Insert BLOCK and LOOP markers.
487   addPass(createWebAssemblyCFGStackify());
488 
489   // Insert explicit local.get and local.set operators.
490   if (!WasmDisableExplicitLocals)
491     addPass(createWebAssemblyExplicitLocals());
492 
493   // Lower br_unless into br_if.
494   addPass(createWebAssemblyLowerBrUnless());
495 
496   // Perform the very last peephole optimizations on the code.
497   if (getOptLevel() != CodeGenOpt::None)
498     addPass(createWebAssemblyPeephole());
499 
500   // Create a mapping from LLVM CodeGen virtual registers to wasm registers.
501   addPass(createWebAssemblyRegNumbering());
502 
503   // Fix debug_values whose defs have been stackified.
504   if (!WasmDisableExplicitLocals)
505     addPass(createWebAssemblyDebugFixup());
506 }
507 
508 yaml::MachineFunctionInfo *
509 WebAssemblyTargetMachine::createDefaultFuncInfoYAML() const {
510   return new yaml::WebAssemblyFunctionInfo();
511 }
512 
513 yaml::MachineFunctionInfo *WebAssemblyTargetMachine::convertFuncInfoToYAML(
514     const MachineFunction &MF) const {
515   const auto *MFI = MF.getInfo<WebAssemblyFunctionInfo>();
516   return new yaml::WebAssemblyFunctionInfo(*MFI);
517 }
518 
519 bool WebAssemblyTargetMachine::parseMachineFunctionInfo(
520     const yaml::MachineFunctionInfo &MFI, PerFunctionMIParsingState &PFS,
521     SMDiagnostic &Error, SMRange &SourceRange) const {
522   const auto &YamlMFI =
523       reinterpret_cast<const yaml::WebAssemblyFunctionInfo &>(MFI);
524   MachineFunction &MF = PFS.MF;
525   MF.getInfo<WebAssemblyFunctionInfo>()->initializeBaseYamlFields(YamlMFI);
526   return false;
527 }
528