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