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