WebAssemblyTargetMachine.cpp 18 KB

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