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