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 "WebAssemblyISelLowering.h" 19 #include "WebAssemblyMachineFunctionInfo.h" 20 #include "WebAssemblyTargetObjectFile.h" 21 #include "WebAssemblyTargetTransformInfo.h" 22 #include "WebAssemblyUtilities.h" 23 #include "llvm/CodeGen/MIRParser/MIParser.h" 24 #include "llvm/CodeGen/MachineFunctionPass.h" 25 #include "llvm/CodeGen/Passes.h" 26 #include "llvm/CodeGen/RegAllocRegistry.h" 27 #include "llvm/CodeGen/TargetPassConfig.h" 28 #include "llvm/IR/Function.h" 29 #include "llvm/InitializePasses.h" 30 #include "llvm/MC/MCAsmInfo.h" 31 #include "llvm/MC/TargetRegistry.h" 32 #include "llvm/Target/TargetOptions.h" 33 #include "llvm/Transforms/Scalar.h" 34 #include "llvm/Transforms/Scalar/LowerAtomicPass.h" 35 #include "llvm/Transforms/Utils.h" 36 #include <optional> 37 using namespace llvm; 38 39 #define DEBUG_TYPE "wasm" 40 41 // A command-line option to keep implicit locals 42 // for the purpose of testing with lit/llc ONLY. 43 // This produces output which is not valid WebAssembly, and is not supported 44 // by assemblers/disassemblers and other MC based tools. 45 static cl::opt<bool> WasmDisableExplicitLocals( 46 "wasm-disable-explicit-locals", cl::Hidden, 47 cl::desc("WebAssembly: output implicit locals in" 48 " instruction output for test purposes only."), 49 cl::init(false)); 50 51 static cl::opt<bool> WasmDisableFixIrreducibleControlFlowPass( 52 "wasm-disable-fix-irreducible-control-flow-pass", cl::Hidden, 53 cl::desc("webassembly: disables the fix " 54 " irreducible control flow optimization pass"), 55 cl::init(false)); 56 57 extern "C" LLVM_EXTERNAL_VISIBILITY void LLVMInitializeWebAssemblyTarget() { 58 // Register the target. 59 RegisterTargetMachine<WebAssemblyTargetMachine> X( 60 getTheWebAssemblyTarget32()); 61 RegisterTargetMachine<WebAssemblyTargetMachine> Y( 62 getTheWebAssemblyTarget64()); 63 64 // Register backend passes 65 auto &PR = *PassRegistry::getPassRegistry(); 66 initializeWebAssemblyAddMissingPrototypesPass(PR); 67 initializeWebAssemblyLowerEmscriptenEHSjLjPass(PR); 68 initializeLowerGlobalDtorsLegacyPassPass(PR); 69 initializeFixFunctionBitcastsPass(PR); 70 initializeOptimizeReturnedPass(PR); 71 initializeWebAssemblyArgumentMovePass(PR); 72 initializeWebAssemblySetP2AlignOperandsPass(PR); 73 initializeWebAssemblyReplacePhysRegsPass(PR); 74 initializeWebAssemblyOptimizeLiveIntervalsPass(PR); 75 initializeWebAssemblyMemIntrinsicResultsPass(PR); 76 initializeWebAssemblyRegStackifyPass(PR); 77 initializeWebAssemblyRegColoringPass(PR); 78 initializeWebAssemblyNullifyDebugValueListsPass(PR); 79 initializeWebAssemblyFixIrreducibleControlFlowPass(PR); 80 initializeWebAssemblyLateEHPreparePass(PR); 81 initializeWebAssemblyExceptionInfoPass(PR); 82 initializeWebAssemblyCFGSortPass(PR); 83 initializeWebAssemblyCFGStackifyPass(PR); 84 initializeWebAssemblyExplicitLocalsPass(PR); 85 initializeWebAssemblyLowerBrUnlessPass(PR); 86 initializeWebAssemblyRegNumberingPass(PR); 87 initializeWebAssemblyDebugFixupPass(PR); 88 initializeWebAssemblyPeepholePass(PR); 89 initializeWebAssemblyMCLowerPrePassPass(PR); 90 initializeWebAssemblyLowerRefTypesIntPtrConvPass(PR); 91 initializeWebAssemblyFixBrTableDefaultsPass(PR); 92 initializeWebAssemblyDAGToDAGISelPass(PR); 93 } 94 95 //===----------------------------------------------------------------------===// 96 // WebAssembly Lowering public interface. 97 //===----------------------------------------------------------------------===// 98 99 static Reloc::Model getEffectiveRelocModel(std::optional<Reloc::Model> RM, 100 const Triple &TT) { 101 if (!RM) { 102 // Default to static relocation model. This should always be more optimial 103 // than PIC since the static linker can determine all global addresses and 104 // assume direct function calls. 105 return Reloc::Static; 106 } 107 108 return *RM; 109 } 110 111 /// Create an WebAssembly architecture model. 112 /// 113 WebAssemblyTargetMachine::WebAssemblyTargetMachine( 114 const Target &T, const Triple &TT, StringRef CPU, StringRef FS, 115 const TargetOptions &Options, std::optional<Reloc::Model> RM, 116 std::optional<CodeModel::Model> CM, CodeGenOptLevel OL, bool JIT) 117 : LLVMTargetMachine( 118 T, 119 TT.isArch64Bit() 120 ? (TT.isOSEmscripten() ? "e-m:e-p:64:64-p10:8:8-p20:8:8-i64:64-" 121 "f128:64-n32:64-S128-ni:1:10:20" 122 : "e-m:e-p:64:64-p10:8:8-p20:8:8-i64:64-" 123 "n32:64-S128-ni:1:10:20") 124 : (TT.isOSEmscripten() ? "e-m:e-p:32:32-p10:8:8-p20:8:8-i64:64-" 125 "f128:64-n32:64-S128-ni:1:10:20" 126 : "e-m:e-p:32:32-p10:8:8-p20:8:8-i64:64-" 127 "n32:64-S128-ni:1:10:20"), 128 TT, CPU, FS, Options, getEffectiveRelocModel(RM, TT), 129 getEffectiveCodeModel(CM, CodeModel::Large), OL), 130 TLOF(new WebAssemblyTargetObjectFile()) { 131 // WebAssembly type-checks instructions, but a noreturn function with a return 132 // type that doesn't match the context will cause a check failure. So we lower 133 // LLVM 'unreachable' to ISD::TRAP and then lower that to WebAssembly's 134 // 'unreachable' instructions which is meant for that case. 135 this->Options.TrapUnreachable = true; 136 this->Options.NoTrapAfterNoreturn = false; 137 138 // WebAssembly treats each function as an independent unit. Force 139 // -ffunction-sections, effectively, so that we can emit them independently. 140 this->Options.FunctionSections = true; 141 this->Options.DataSections = true; 142 this->Options.UniqueSectionNames = true; 143 144 initAsmInfo(); 145 146 // Note that we don't use setRequiresStructuredCFG(true). It disables 147 // optimizations than we're ok with, and want, such as critical edge 148 // splitting and tail merging. 149 } 150 151 WebAssemblyTargetMachine::~WebAssemblyTargetMachine() = default; // anchor. 152 153 const WebAssemblySubtarget *WebAssemblyTargetMachine::getSubtargetImpl() const { 154 return getSubtargetImpl(std::string(getTargetCPU()), 155 std::string(getTargetFeatureString())); 156 } 157 158 const WebAssemblySubtarget * 159 WebAssemblyTargetMachine::getSubtargetImpl(std::string CPU, 160 std::string FS) const { 161 auto &I = SubtargetMap[CPU + FS]; 162 if (!I) { 163 I = std::make_unique<WebAssemblySubtarget>(TargetTriple, CPU, FS, *this); 164 } 165 return I.get(); 166 } 167 168 const WebAssemblySubtarget * 169 WebAssemblyTargetMachine::getSubtargetImpl(const Function &F) const { 170 Attribute CPUAttr = F.getFnAttribute("target-cpu"); 171 Attribute FSAttr = F.getFnAttribute("target-features"); 172 173 std::string CPU = 174 CPUAttr.isValid() ? CPUAttr.getValueAsString().str() : TargetCPU; 175 std::string FS = 176 FSAttr.isValid() ? FSAttr.getValueAsString().str() : TargetFS; 177 178 // This needs to be done before we create a new subtarget since any 179 // creation will depend on the TM and the code generation flags on the 180 // function that reside in TargetOptions. 181 resetTargetOptions(F); 182 183 return getSubtargetImpl(CPU, FS); 184 } 185 186 namespace { 187 188 class CoalesceFeaturesAndStripAtomics final : public ModulePass { 189 // Take the union of all features used in the module and use it for each 190 // function individually, since having multiple feature sets in one module 191 // currently does not make sense for WebAssembly. If atomics are not enabled, 192 // also strip atomic operations and thread local storage. 193 static char ID; 194 WebAssemblyTargetMachine *WasmTM; 195 196 public: 197 CoalesceFeaturesAndStripAtomics(WebAssemblyTargetMachine *WasmTM) 198 : ModulePass(ID), WasmTM(WasmTM) {} 199 200 bool runOnModule(Module &M) override { 201 FeatureBitset Features = coalesceFeatures(M); 202 203 std::string FeatureStr = 204 getFeatureString(Features, WasmTM->getTargetFeatureString()); 205 WasmTM->setTargetFeatureString(FeatureStr); 206 for (auto &F : M) 207 replaceFeatures(F, FeatureStr); 208 209 bool StrippedAtomics = false; 210 bool StrippedTLS = false; 211 212 if (!Features[WebAssembly::FeatureAtomics]) { 213 StrippedAtomics = stripAtomics(M); 214 StrippedTLS = stripThreadLocals(M); 215 } else if (!Features[WebAssembly::FeatureBulkMemory]) { 216 StrippedTLS |= stripThreadLocals(M); 217 } 218 219 if (StrippedAtomics && !StrippedTLS) 220 stripThreadLocals(M); 221 else if (StrippedTLS && !StrippedAtomics) 222 stripAtomics(M); 223 224 recordFeatures(M, Features, StrippedAtomics || StrippedTLS); 225 226 // Conservatively assume we have made some change 227 return true; 228 } 229 230 private: 231 FeatureBitset coalesceFeatures(const Module &M) { 232 FeatureBitset Features = 233 WasmTM 234 ->getSubtargetImpl(std::string(WasmTM->getTargetCPU()), 235 std::string(WasmTM->getTargetFeatureString())) 236 ->getFeatureBits(); 237 for (auto &F : M) 238 Features |= WasmTM->getSubtargetImpl(F)->getFeatureBits(); 239 return Features; 240 } 241 242 static std::string getFeatureString(const FeatureBitset &Features, 243 StringRef TargetFS) { 244 std::string Ret; 245 for (const SubtargetFeatureKV &KV : WebAssemblyFeatureKV) { 246 if (Features[KV.Value]) 247 Ret += (StringRef("+") + KV.Key + ",").str(); 248 } 249 SubtargetFeatures TF{TargetFS}; 250 for (std::string const &F : TF.getFeatures()) 251 if (!SubtargetFeatures::isEnabled(F)) 252 Ret += F + ","; 253 return Ret; 254 } 255 256 void replaceFeatures(Function &F, const std::string &Features) { 257 F.removeFnAttr("target-features"); 258 F.removeFnAttr("target-cpu"); 259 F.addFnAttr("target-features", Features); 260 } 261 262 bool stripAtomics(Module &M) { 263 // Detect whether any atomics will be lowered, since there is no way to tell 264 // whether the LowerAtomic pass lowers e.g. stores. 265 bool Stripped = false; 266 for (auto &F : M) { 267 for (auto &B : F) { 268 for (auto &I : B) { 269 if (I.isAtomic()) { 270 Stripped = true; 271 goto done; 272 } 273 } 274 } 275 } 276 277 done: 278 if (!Stripped) 279 return false; 280 281 LowerAtomicPass Lowerer; 282 FunctionAnalysisManager FAM; 283 for (auto &F : M) 284 Lowerer.run(F, FAM); 285 286 return true; 287 } 288 289 bool stripThreadLocals(Module &M) { 290 bool Stripped = false; 291 for (auto &GV : M.globals()) { 292 if (GV.isThreadLocal()) { 293 Stripped = true; 294 GV.setThreadLocal(false); 295 } 296 } 297 return Stripped; 298 } 299 300 void recordFeatures(Module &M, const FeatureBitset &Features, bool Stripped) { 301 for (const SubtargetFeatureKV &KV : WebAssemblyFeatureKV) { 302 if (Features[KV.Value]) { 303 // Mark features as used 304 std::string MDKey = (StringRef("wasm-feature-") + KV.Key).str(); 305 M.addModuleFlag(Module::ModFlagBehavior::Error, MDKey, 306 wasm::WASM_FEATURE_PREFIX_USED); 307 } 308 } 309 // Code compiled without atomics or bulk-memory may have had its atomics or 310 // thread-local data lowered to nonatomic operations or non-thread-local 311 // data. In that case, we mark the pseudo-feature "shared-mem" as disallowed 312 // to tell the linker that it would be unsafe to allow this code ot be used 313 // in a module with shared memory. 314 if (Stripped) { 315 M.addModuleFlag(Module::ModFlagBehavior::Error, "wasm-feature-shared-mem", 316 wasm::WASM_FEATURE_PREFIX_DISALLOWED); 317 } 318 } 319 }; 320 char CoalesceFeaturesAndStripAtomics::ID = 0; 321 322 /// WebAssembly Code Generator Pass Configuration Options. 323 class WebAssemblyPassConfig final : public TargetPassConfig { 324 public: 325 WebAssemblyPassConfig(WebAssemblyTargetMachine &TM, PassManagerBase &PM) 326 : TargetPassConfig(TM, PM) {} 327 328 WebAssemblyTargetMachine &getWebAssemblyTargetMachine() const { 329 return getTM<WebAssemblyTargetMachine>(); 330 } 331 332 FunctionPass *createTargetRegisterAllocator(bool) override; 333 334 void addIRPasses() override; 335 void addISelPrepare() override; 336 bool addInstSelector() override; 337 void addOptimizedRegAlloc() override; 338 void addPostRegAlloc() override; 339 bool addGCPasses() override { return false; } 340 void addPreEmitPass() override; 341 bool addPreISel() override; 342 343 // No reg alloc 344 bool addRegAssignAndRewriteFast() override { return false; } 345 346 // No reg alloc 347 bool addRegAssignAndRewriteOptimized() override { return false; } 348 }; 349 } // end anonymous namespace 350 351 MachineFunctionInfo *WebAssemblyTargetMachine::createMachineFunctionInfo( 352 BumpPtrAllocator &Allocator, const Function &F, 353 const TargetSubtargetInfo *STI) const { 354 return WebAssemblyFunctionInfo::create<WebAssemblyFunctionInfo>(Allocator, F, 355 STI); 356 } 357 358 TargetTransformInfo 359 WebAssemblyTargetMachine::getTargetTransformInfo(const Function &F) const { 360 return TargetTransformInfo(WebAssemblyTTIImpl(this, F)); 361 } 362 363 TargetPassConfig * 364 WebAssemblyTargetMachine::createPassConfig(PassManagerBase &PM) { 365 return new WebAssemblyPassConfig(*this, PM); 366 } 367 368 FunctionPass *WebAssemblyPassConfig::createTargetRegisterAllocator(bool) { 369 return nullptr; // No reg alloc 370 } 371 372 using WebAssembly::WasmEnableEH; 373 using WebAssembly::WasmEnableEmEH; 374 using WebAssembly::WasmEnableEmSjLj; 375 using WebAssembly::WasmEnableSjLj; 376 377 static void basicCheckForEHAndSjLj(TargetMachine *TM) { 378 // Before checking, we make sure TargetOptions.ExceptionModel is the same as 379 // MCAsmInfo.ExceptionsType. Normally these have to be the same, because clang 380 // stores the exception model info in LangOptions, which is later transferred 381 // to TargetOptions and MCAsmInfo. But when clang compiles bitcode directly, 382 // clang's LangOptions is not used and thus the exception model info is not 383 // correctly transferred to TargetOptions and MCAsmInfo, so we make sure we 384 // have the correct exception model in WebAssemblyMCAsmInfo constructor. 385 // But in this case TargetOptions is still not updated, so we make sure they 386 // are the same. 387 TM->Options.ExceptionModel = TM->getMCAsmInfo()->getExceptionHandlingType(); 388 389 // Basic Correctness checking related to -exception-model 390 if (TM->Options.ExceptionModel != ExceptionHandling::None && 391 TM->Options.ExceptionModel != ExceptionHandling::Wasm) 392 report_fatal_error("-exception-model should be either 'none' or 'wasm'"); 393 if (WasmEnableEmEH && TM->Options.ExceptionModel == ExceptionHandling::Wasm) 394 report_fatal_error("-exception-model=wasm not allowed with " 395 "-enable-emscripten-cxx-exceptions"); 396 if (WasmEnableEH && TM->Options.ExceptionModel != ExceptionHandling::Wasm) 397 report_fatal_error( 398 "-wasm-enable-eh only allowed with -exception-model=wasm"); 399 if (WasmEnableSjLj && TM->Options.ExceptionModel != ExceptionHandling::Wasm) 400 report_fatal_error( 401 "-wasm-enable-sjlj only allowed with -exception-model=wasm"); 402 if ((!WasmEnableEH && !WasmEnableSjLj) && 403 TM->Options.ExceptionModel == ExceptionHandling::Wasm) 404 report_fatal_error( 405 "-exception-model=wasm only allowed with at least one of " 406 "-wasm-enable-eh or -wasm-enable-sjj"); 407 408 // You can't enable two modes of EH at the same time 409 if (WasmEnableEmEH && WasmEnableEH) 410 report_fatal_error( 411 "-enable-emscripten-cxx-exceptions not allowed with -wasm-enable-eh"); 412 // You can't enable two modes of SjLj at the same time 413 if (WasmEnableEmSjLj && WasmEnableSjLj) 414 report_fatal_error( 415 "-enable-emscripten-sjlj not allowed with -wasm-enable-sjlj"); 416 // You can't mix Emscripten EH with Wasm SjLj. 417 if (WasmEnableEmEH && WasmEnableSjLj) 418 report_fatal_error( 419 "-enable-emscripten-cxx-exceptions not allowed with -wasm-enable-sjlj"); 420 // Currently it is allowed to mix Wasm EH with Emscripten SjLj as an interim 421 // measure, but some code will error out at compile time in this combination. 422 // See WebAssemblyLowerEmscriptenEHSjLj pass for details. 423 } 424 425 //===----------------------------------------------------------------------===// 426 // The following functions are called from lib/CodeGen/Passes.cpp to modify 427 // the CodeGen pass sequence. 428 //===----------------------------------------------------------------------===// 429 430 void WebAssemblyPassConfig::addIRPasses() { 431 // Add signatures to prototype-less function declarations 432 addPass(createWebAssemblyAddMissingPrototypes()); 433 434 // Lower .llvm.global_dtors into .llvm.global_ctors with __cxa_atexit calls. 435 addPass(createLowerGlobalDtorsLegacyPass()); 436 437 // Fix function bitcasts, as WebAssembly requires caller and callee signatures 438 // to match. 439 addPass(createWebAssemblyFixFunctionBitcasts()); 440 441 // Optimize "returned" function attributes. 442 if (getOptLevel() != CodeGenOptLevel::None) 443 addPass(createWebAssemblyOptimizeReturned()); 444 445 basicCheckForEHAndSjLj(TM); 446 447 // If exception handling is not enabled and setjmp/longjmp handling is 448 // enabled, we lower invokes into calls and delete unreachable landingpad 449 // blocks. Lowering invokes when there is no EH support is done in 450 // TargetPassConfig::addPassesToHandleExceptions, but that runs after these IR 451 // passes and Emscripten SjLj handling expects all invokes to be lowered 452 // before. 453 if (!WasmEnableEmEH && !WasmEnableEH) { 454 addPass(createLowerInvokePass()); 455 // The lower invoke pass may create unreachable code. Remove it in order not 456 // to process dead blocks in setjmp/longjmp handling. 457 addPass(createUnreachableBlockEliminationPass()); 458 } 459 460 // Handle exceptions and setjmp/longjmp if enabled. Unlike Wasm EH preparation 461 // done in WasmEHPrepare pass, Wasm SjLj preparation shares libraries and 462 // transformation algorithms with Emscripten SjLj, so we run 463 // LowerEmscriptenEHSjLj pass also when Wasm SjLj is enabled. 464 if (WasmEnableEmEH || WasmEnableEmSjLj || WasmEnableSjLj) 465 addPass(createWebAssemblyLowerEmscriptenEHSjLj()); 466 467 // Expand indirectbr instructions to switches. 468 addPass(createIndirectBrExpandPass()); 469 470 TargetPassConfig::addIRPasses(); 471 } 472 473 void WebAssemblyPassConfig::addISelPrepare() { 474 WebAssemblyTargetMachine *WasmTM = 475 static_cast<WebAssemblyTargetMachine *>(TM); 476 const WebAssemblySubtarget *Subtarget = 477 WasmTM->getSubtargetImpl(std::string(WasmTM->getTargetCPU()), 478 std::string(WasmTM->getTargetFeatureString())); 479 if (Subtarget->hasReferenceTypes()) { 480 // We need to remove allocas for reference types 481 addPass(createPromoteMemoryToRegisterPass(true)); 482 } 483 // Lower atomics and TLS if necessary 484 addPass(new CoalesceFeaturesAndStripAtomics(&getWebAssemblyTargetMachine())); 485 486 // This is a no-op if atomics are not used in the module 487 addPass(createAtomicExpandPass()); 488 489 TargetPassConfig::addISelPrepare(); 490 } 491 492 bool WebAssemblyPassConfig::addInstSelector() { 493 (void)TargetPassConfig::addInstSelector(); 494 addPass( 495 createWebAssemblyISelDag(getWebAssemblyTargetMachine(), getOptLevel())); 496 // Run the argument-move pass immediately after the ScheduleDAG scheduler 497 // so that we can fix up the ARGUMENT instructions before anything else 498 // sees them in the wrong place. 499 addPass(createWebAssemblyArgumentMove()); 500 // Set the p2align operands. This information is present during ISel, however 501 // it's inconvenient to collect. Collect it now, and update the immediate 502 // operands. 503 addPass(createWebAssemblySetP2AlignOperands()); 504 505 // Eliminate range checks and add default targets to br_table instructions. 506 addPass(createWebAssemblyFixBrTableDefaults()); 507 508 return false; 509 } 510 511 void WebAssemblyPassConfig::addOptimizedRegAlloc() { 512 // Currently RegisterCoalesce degrades wasm debug info quality by a 513 // significant margin. As a quick fix, disable this for -O1, which is often 514 // used for debugging large applications. Disabling this increases code size 515 // of Emscripten core benchmarks by ~5%, which is acceptable for -O1, which is 516 // usually not used for production builds. 517 // TODO Investigate why RegisterCoalesce degrades debug info quality and fix 518 // it properly 519 if (getOptLevel() == CodeGenOptLevel::Less) 520 disablePass(&RegisterCoalescerID); 521 TargetPassConfig::addOptimizedRegAlloc(); 522 } 523 524 void WebAssemblyPassConfig::addPostRegAlloc() { 525 // TODO: The following CodeGen passes don't currently support code containing 526 // virtual registers. Consider removing their restrictions and re-enabling 527 // them. 528 529 // These functions all require the NoVRegs property. 530 disablePass(&MachineLateInstrsCleanupID); 531 disablePass(&MachineCopyPropagationID); 532 disablePass(&PostRAMachineSinkingID); 533 disablePass(&PostRASchedulerID); 534 disablePass(&FuncletLayoutID); 535 disablePass(&StackMapLivenessID); 536 disablePass(&PatchableFunctionID); 537 disablePass(&ShrinkWrapID); 538 539 // This pass hurts code size for wasm because it can generate irreducible 540 // control flow. 541 disablePass(&MachineBlockPlacementID); 542 543 TargetPassConfig::addPostRegAlloc(); 544 } 545 546 void WebAssemblyPassConfig::addPreEmitPass() { 547 TargetPassConfig::addPreEmitPass(); 548 549 // Nullify DBG_VALUE_LISTs that we cannot handle. 550 addPass(createWebAssemblyNullifyDebugValueLists()); 551 552 // Eliminate multiple-entry loops. 553 if (!WasmDisableFixIrreducibleControlFlowPass) 554 addPass(createWebAssemblyFixIrreducibleControlFlow()); 555 556 // Do various transformations for exception handling. 557 // Every CFG-changing optimizations should come before this. 558 if (TM->Options.ExceptionModel == ExceptionHandling::Wasm) 559 addPass(createWebAssemblyLateEHPrepare()); 560 561 // Now that we have a prologue and epilogue and all frame indices are 562 // rewritten, eliminate SP and FP. This allows them to be stackified, 563 // colored, and numbered with the rest of the registers. 564 addPass(createWebAssemblyReplacePhysRegs()); 565 566 // Preparations and optimizations related to register stackification. 567 if (getOptLevel() != CodeGenOptLevel::None) { 568 // Depend on LiveIntervals and perform some optimizations on it. 569 addPass(createWebAssemblyOptimizeLiveIntervals()); 570 571 // Prepare memory intrinsic calls for register stackifying. 572 addPass(createWebAssemblyMemIntrinsicResults()); 573 574 // Mark registers as representing wasm's value stack. This is a key 575 // code-compression technique in WebAssembly. We run this pass (and 576 // MemIntrinsicResults above) very late, so that it sees as much code as 577 // possible, including code emitted by PEI and expanded by late tail 578 // duplication. 579 addPass(createWebAssemblyRegStackify()); 580 581 // Run the register coloring pass to reduce the total number of registers. 582 // This runs after stackification so that it doesn't consider registers 583 // that become stackified. 584 addPass(createWebAssemblyRegColoring()); 585 } 586 587 // Sort the blocks of the CFG into topological order, a prerequisite for 588 // BLOCK and LOOP markers. 589 addPass(createWebAssemblyCFGSort()); 590 591 // Insert BLOCK and LOOP markers. 592 addPass(createWebAssemblyCFGStackify()); 593 594 // Insert explicit local.get and local.set operators. 595 if (!WasmDisableExplicitLocals) 596 addPass(createWebAssemblyExplicitLocals()); 597 598 // Lower br_unless into br_if. 599 addPass(createWebAssemblyLowerBrUnless()); 600 601 // Perform the very last peephole optimizations on the code. 602 if (getOptLevel() != CodeGenOptLevel::None) 603 addPass(createWebAssemblyPeephole()); 604 605 // Create a mapping from LLVM CodeGen virtual registers to wasm registers. 606 addPass(createWebAssemblyRegNumbering()); 607 608 // Fix debug_values whose defs have been stackified. 609 if (!WasmDisableExplicitLocals) 610 addPass(createWebAssemblyDebugFixup()); 611 612 // Collect information to prepare for MC lowering / asm printing. 613 addPass(createWebAssemblyMCLowerPrePass()); 614 } 615 616 bool WebAssemblyPassConfig::addPreISel() { 617 TargetPassConfig::addPreISel(); 618 addPass(createWebAssemblyLowerRefTypesIntPtrConv()); 619 return false; 620 } 621 622 yaml::MachineFunctionInfo * 623 WebAssemblyTargetMachine::createDefaultFuncInfoYAML() const { 624 return new yaml::WebAssemblyFunctionInfo(); 625 } 626 627 yaml::MachineFunctionInfo *WebAssemblyTargetMachine::convertFuncInfoToYAML( 628 const MachineFunction &MF) const { 629 const auto *MFI = MF.getInfo<WebAssemblyFunctionInfo>(); 630 return new yaml::WebAssemblyFunctionInfo(MF, *MFI); 631 } 632 633 bool WebAssemblyTargetMachine::parseMachineFunctionInfo( 634 const yaml::MachineFunctionInfo &MFI, PerFunctionMIParsingState &PFS, 635 SMDiagnostic &Error, SMRange &SourceRange) const { 636 const auto &YamlMFI = static_cast<const yaml::WebAssemblyFunctionInfo &>(MFI); 637 MachineFunction &MF = PFS.MF; 638 MF.getInfo<WebAssemblyFunctionInfo>()->initializeBaseYamlFields(MF, YamlMFI); 639 return false; 640 } 641