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