Derek Schuff | ccdceda | 2016-08-18 15:27:25 +0000 | [diff] [blame] | 1 | //=== WebAssemblyLowerEmscriptenEHSjLj.cpp - Lower exceptions for Emscripten =// |
Derek Schuff | f41f67d | 2016-08-01 21:34:04 +0000 | [diff] [blame] | 2 | // |
Chandler Carruth | 2946cd7 | 2019-01-19 08:50:56 +0000 | [diff] [blame] | 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 |
Derek Schuff | f41f67d | 2016-08-01 21:34:04 +0000 | [diff] [blame] | 6 | // |
| 7 | //===----------------------------------------------------------------------===// |
| 8 | /// |
| 9 | /// \file |
Adrian Prantl | 5f8f34e4 | 2018-05-01 15:54:18 +0000 | [diff] [blame] | 10 | /// This file lowers exception-related instructions and setjmp/longjmp |
Heejin Ahn | c0f1817 | 2016-09-01 21:05:15 +0000 | [diff] [blame] | 11 | /// function calls in order to use Emscripten's JavaScript try and catch |
| 12 | /// mechanism. |
Derek Schuff | f41f67d | 2016-08-01 21:34:04 +0000 | [diff] [blame] | 13 | /// |
Heejin Ahn | c0f1817 | 2016-09-01 21:05:15 +0000 | [diff] [blame] | 14 | /// To handle exceptions and setjmp/longjmps, this scheme relies on JavaScript's |
| 15 | /// try and catch syntax and relevant exception-related libraries implemented |
| 16 | /// in JavaScript glue code that will be produced by Emscripten. This is similar |
| 17 | /// to the current Emscripten asm.js exception handling in fastcomp. For |
| 18 | /// fastcomp's EH / SjLj scheme, see these files in fastcomp LLVM branch: |
Derek Schuff | f41f67d | 2016-08-01 21:34:04 +0000 | [diff] [blame] | 19 | /// (Location: https://github.com/kripken/emscripten-fastcomp) |
| 20 | /// lib/Target/JSBackend/NaCl/LowerEmExceptionsPass.cpp |
Heejin Ahn | c0f1817 | 2016-09-01 21:05:15 +0000 | [diff] [blame] | 21 | /// lib/Target/JSBackend/NaCl/LowerEmSetjmp.cpp |
Derek Schuff | f41f67d | 2016-08-01 21:34:04 +0000 | [diff] [blame] | 22 | /// lib/Target/JSBackend/JSBackend.cpp |
| 23 | /// lib/Target/JSBackend/CallHandlers.h |
| 24 | /// |
Heejin Ahn | c0f1817 | 2016-09-01 21:05:15 +0000 | [diff] [blame] | 25 | /// * Exception handling |
| 26 | /// This pass lowers invokes and landingpads into library functions in JS glue |
| 27 | /// code. Invokes are lowered into function wrappers called invoke wrappers that |
| 28 | /// exist in JS side, which wraps the original function call with JS try-catch. |
| 29 | /// If an exception occurred, cxa_throw() function in JS side sets some |
| 30 | /// variables (see below) so we can check whether an exception occurred from |
| 31 | /// wasm code and handle it appropriately. |
Derek Schuff | f41f67d | 2016-08-01 21:34:04 +0000 | [diff] [blame] | 32 | /// |
Heejin Ahn | c0f1817 | 2016-09-01 21:05:15 +0000 | [diff] [blame] | 33 | /// * Setjmp-longjmp handling |
| 34 | /// This pass lowers setjmp to a reasonably-performant approach for emscripten. |
| 35 | /// The idea is that each block with a setjmp is broken up into two parts: the |
| 36 | /// part containing setjmp and the part right after the setjmp. The latter part |
| 37 | /// is either reached from the setjmp, or later from a longjmp. To handle the |
| 38 | /// longjmp, all calls that might longjmp are also called using invoke wrappers |
| 39 | /// and thus JS / try-catch. JS longjmp() function also sets some variables so |
| 40 | /// we can check / whether a longjmp occurred from wasm code. Each block with a |
| 41 | /// function call that might longjmp is also split up after the longjmp call. |
| 42 | /// After the longjmp call, we check whether a longjmp occurred, and if it did, |
| 43 | /// which setjmp it corresponds to, and jump to the right post-setjmp block. |
| 44 | /// We assume setjmp-longjmp handling always run after EH handling, which means |
| 45 | /// we don't expect any exception-related instructions when SjLj runs. |
| 46 | /// FIXME Currently this scheme does not support indirect call of setjmp, |
| 47 | /// because of the limitation of the scheme itself. fastcomp does not support it |
| 48 | /// either. |
| 49 | /// |
| 50 | /// In detail, this pass does following things: |
| 51 | /// |
Sam Clegg | 4791a66 | 2018-11-20 19:25:07 +0000 | [diff] [blame] | 52 | /// 1) Assumes the existence of global variables: __THREW__, __threwValue |
| 53 | /// __THREW__ and __threwValue will be set in invoke wrappers |
Heejin Ahn | c0f1817 | 2016-09-01 21:05:15 +0000 | [diff] [blame] | 54 | /// in JS glue code. For what invoke wrappers are, refer to 3). These |
| 55 | /// variables are used for both exceptions and setjmp/longjmps. |
| 56 | /// __THREW__ indicates whether an exception or a longjmp occurred or not. 0 |
| 57 | /// means nothing occurred, 1 means an exception occurred, and other numbers |
Heejin Ahn | 99bd16b | 2016-09-10 02:33:47 +0000 | [diff] [blame] | 58 | /// mean a longjmp occurred. In the case of longjmp, __threwValue variable |
Heejin Ahn | c0f1817 | 2016-09-01 21:05:15 +0000 | [diff] [blame] | 59 | /// indicates the corresponding setjmp buffer the longjmp corresponds to. |
Heejin Ahn | c0f1817 | 2016-09-01 21:05:15 +0000 | [diff] [blame] | 60 | /// |
| 61 | /// * Exception handling |
Derek Schuff | f41f67d | 2016-08-01 21:34:04 +0000 | [diff] [blame] | 62 | /// |
Sam Clegg | 4791a66 | 2018-11-20 19:25:07 +0000 | [diff] [blame] | 63 | /// 2) We assume the existence of setThrew and setTempRet0/getTempRet0 functions |
| 64 | /// at link time. |
Sam Clegg | b2486f1 | 2018-10-02 22:12:15 +0000 | [diff] [blame] | 65 | /// The global variables in 1) will exist in wasm address space, |
| 66 | /// but their values should be set in JS code, so these functions |
Derek Schuff | f41f67d | 2016-08-01 21:34:04 +0000 | [diff] [blame] | 67 | /// as interfaces to JS glue code. These functions are equivalent to the |
| 68 | /// following JS functions, which actually exist in asm.js version of JS |
| 69 | /// library. |
| 70 | /// |
| 71 | /// function setThrew(threw, value) { |
| 72 | /// if (__THREW__ == 0) { |
| 73 | /// __THREW__ = threw; |
Derek Schuff | ccdceda | 2016-08-18 15:27:25 +0000 | [diff] [blame] | 74 | /// __threwValue = value; |
Derek Schuff | f41f67d | 2016-08-01 21:34:04 +0000 | [diff] [blame] | 75 | /// } |
| 76 | /// } |
Sam Clegg | 4791a66 | 2018-11-20 19:25:07 +0000 | [diff] [blame] | 77 | // |
| 78 | /// setTempRet0 is called from __cxa_find_matching_catch() in JS glue code. |
Derek Schuff | f41f67d | 2016-08-01 21:34:04 +0000 | [diff] [blame] | 79 | /// |
Sam Clegg | 4791a66 | 2018-11-20 19:25:07 +0000 | [diff] [blame] | 80 | /// In exception handling, getTempRet0 indicates the type of an exception |
| 81 | /// caught, and in setjmp/longjmp, it means the second argument to longjmp |
| 82 | /// function. |
Derek Schuff | f41f67d | 2016-08-01 21:34:04 +0000 | [diff] [blame] | 83 | /// |
| 84 | /// 3) Lower |
| 85 | /// invoke @func(arg1, arg2) to label %invoke.cont unwind label %lpad |
| 86 | /// into |
| 87 | /// __THREW__ = 0; |
Heejin Ahn | 99bd16b | 2016-09-10 02:33:47 +0000 | [diff] [blame] | 88 | /// call @__invoke_SIG(func, arg1, arg2) |
Derek Schuff | f41f67d | 2016-08-01 21:34:04 +0000 | [diff] [blame] | 89 | /// %__THREW__.val = __THREW__; |
| 90 | /// __THREW__ = 0; |
Heejin Ahn | 99bd16b | 2016-09-10 02:33:47 +0000 | [diff] [blame] | 91 | /// if (%__THREW__.val == 1) |
| 92 | /// goto %lpad |
| 93 | /// else |
| 94 | /// goto %invoke.cont |
Derek Schuff | f41f67d | 2016-08-01 21:34:04 +0000 | [diff] [blame] | 95 | /// SIG is a mangled string generated based on the LLVM IR-level function |
| 96 | /// signature. After LLVM IR types are lowered to the target wasm types, |
| 97 | /// the names for these wrappers will change based on wasm types as well, |
| 98 | /// as in invoke_vi (function takes an int and returns void). The bodies of |
| 99 | /// these wrappers will be generated in JS glue code, and inside those |
| 100 | /// wrappers we use JS try-catch to generate actual exception effects. It |
| 101 | /// also calls the original callee function. An example wrapper in JS code |
| 102 | /// would look like this: |
| 103 | /// function invoke_vi(index,a1) { |
| 104 | /// try { |
| 105 | /// Module["dynCall_vi"](index,a1); // This calls original callee |
| 106 | /// } catch(e) { |
| 107 | /// if (typeof e !== 'number' && e !== 'longjmp') throw e; |
| 108 | /// asm["setThrew"](1, 0); // setThrew is called here |
| 109 | /// } |
| 110 | /// } |
| 111 | /// If an exception is thrown, __THREW__ will be set to true in a wrapper, |
| 112 | /// so we can jump to the right BB based on this value. |
| 113 | /// |
| 114 | /// 4) Lower |
| 115 | /// %val = landingpad catch c1 catch c2 catch c3 ... |
| 116 | /// ... use %val ... |
| 117 | /// into |
Derek Schuff | 53b9af0 | 2016-08-09 00:29:55 +0000 | [diff] [blame] | 118 | /// %fmc = call @__cxa_find_matching_catch_N(c1, c2, c3, ...) |
Sam Clegg | 4791a66 | 2018-11-20 19:25:07 +0000 | [diff] [blame] | 119 | /// %val = {%fmc, getTempRet0()} |
Derek Schuff | f41f67d | 2016-08-01 21:34:04 +0000 | [diff] [blame] | 120 | /// ... use %val ... |
| 121 | /// Here N is a number calculated based on the number of clauses. |
Sam Clegg | 4791a66 | 2018-11-20 19:25:07 +0000 | [diff] [blame] | 122 | /// setTempRet0 is called from __cxa_find_matching_catch() in JS glue code. |
Derek Schuff | f41f67d | 2016-08-01 21:34:04 +0000 | [diff] [blame] | 123 | /// |
| 124 | /// 5) Lower |
| 125 | /// resume {%a, %b} |
| 126 | /// into |
Derek Schuff | 53b9af0 | 2016-08-09 00:29:55 +0000 | [diff] [blame] | 127 | /// call @__resumeException(%a) |
| 128 | /// where __resumeException() is a function in JS glue code. |
Derek Schuff | f41f67d | 2016-08-01 21:34:04 +0000 | [diff] [blame] | 129 | /// |
Derek Schuff | 53b9af0 | 2016-08-09 00:29:55 +0000 | [diff] [blame] | 130 | /// 6) Lower |
| 131 | /// call @llvm.eh.typeid.for(type) (intrinsic) |
| 132 | /// into |
| 133 | /// call @llvm_eh_typeid_for(type) |
| 134 | /// llvm_eh_typeid_for function will be generated in JS glue code. |
Derek Schuff | f41f67d | 2016-08-01 21:34:04 +0000 | [diff] [blame] | 135 | /// |
Heejin Ahn | c0f1817 | 2016-09-01 21:05:15 +0000 | [diff] [blame] | 136 | /// * Setjmp / Longjmp handling |
| 137 | /// |
Heejin Ahn | 0c68a87 | 2018-11-08 22:56:26 +0000 | [diff] [blame] | 138 | /// In case calls to longjmp() exists |
| 139 | /// |
| 140 | /// 1) Lower |
| 141 | /// longjmp(buf, value) |
| 142 | /// into |
| 143 | /// emscripten_longjmp_jmpbuf(buf, value) |
| 144 | /// emscripten_longjmp_jmpbuf will be lowered to emscripten_longjmp later. |
| 145 | /// |
| 146 | /// In case calls to setjmp() exists |
| 147 | /// |
| 148 | /// 2) In the function entry that calls setjmp, initialize setjmpTable and |
Heejin Ahn | c0f1817 | 2016-09-01 21:05:15 +0000 | [diff] [blame] | 149 | /// sejmpTableSize as follows: |
| 150 | /// setjmpTableSize = 4; |
| 151 | /// setjmpTable = (int *) malloc(40); |
| 152 | /// setjmpTable[0] = 0; |
| 153 | /// setjmpTable and setjmpTableSize are used in saveSetjmp() function in JS |
| 154 | /// code. |
| 155 | /// |
Heejin Ahn | 0c68a87 | 2018-11-08 22:56:26 +0000 | [diff] [blame] | 156 | /// 3) Lower |
Heejin Ahn | c0f1817 | 2016-09-01 21:05:15 +0000 | [diff] [blame] | 157 | /// setjmp(buf) |
| 158 | /// into |
| 159 | /// setjmpTable = saveSetjmp(buf, label, setjmpTable, setjmpTableSize); |
Sam Clegg | 4791a66 | 2018-11-20 19:25:07 +0000 | [diff] [blame] | 160 | /// setjmpTableSize = getTempRet0(); |
Heejin Ahn | c0f1817 | 2016-09-01 21:05:15 +0000 | [diff] [blame] | 161 | /// For each dynamic setjmp call, setjmpTable stores its ID (a number which |
| 162 | /// is incrementally assigned from 0) and its label (a unique number that |
| 163 | /// represents each callsite of setjmp). When we need more entries in |
| 164 | /// setjmpTable, it is reallocated in saveSetjmp() in JS code and it will |
| 165 | /// return the new table address, and assign the new table size in |
Sam Clegg | 4791a66 | 2018-11-20 19:25:07 +0000 | [diff] [blame] | 166 | /// setTempRet0(). saveSetjmp also stores the setjmp's ID into the buffer |
| 167 | /// buf. A BB with setjmp is split into two after setjmp call in order to |
| 168 | /// make the post-setjmp BB the possible destination of longjmp BB. |
Heejin Ahn | c0f1817 | 2016-09-01 21:05:15 +0000 | [diff] [blame] | 169 | /// |
Heejin Ahn | c0f1817 | 2016-09-01 21:05:15 +0000 | [diff] [blame] | 170 | /// |
Heejin Ahn | 0c68a87 | 2018-11-08 22:56:26 +0000 | [diff] [blame] | 171 | /// 4) Lower every call that might longjmp into |
Heejin Ahn | c0f1817 | 2016-09-01 21:05:15 +0000 | [diff] [blame] | 172 | /// __THREW__ = 0; |
Heejin Ahn | 99bd16b | 2016-09-10 02:33:47 +0000 | [diff] [blame] | 173 | /// call @__invoke_SIG(func, arg1, arg2) |
Heejin Ahn | c0f1817 | 2016-09-01 21:05:15 +0000 | [diff] [blame] | 174 | /// %__THREW__.val = __THREW__; |
| 175 | /// __THREW__ = 0; |
Heejin Ahn | 99bd16b | 2016-09-10 02:33:47 +0000 | [diff] [blame] | 176 | /// if (%__THREW__.val != 0 & __threwValue != 0) { |
Heejin Ahn | c0f1817 | 2016-09-01 21:05:15 +0000 | [diff] [blame] | 177 | /// %label = testSetjmp(mem[%__THREW__.val], setjmpTable, |
| 178 | /// setjmpTableSize); |
| 179 | /// if (%label == 0) |
Heejin Ahn | 99bd16b | 2016-09-10 02:33:47 +0000 | [diff] [blame] | 180 | /// emscripten_longjmp(%__THREW__.val, __threwValue); |
Sam Clegg | 4791a66 | 2018-11-20 19:25:07 +0000 | [diff] [blame] | 181 | /// setTempRet0(__threwValue); |
Heejin Ahn | c0f1817 | 2016-09-01 21:05:15 +0000 | [diff] [blame] | 182 | /// } else { |
| 183 | /// %label = -1; |
| 184 | /// } |
Sam Clegg | 4791a66 | 2018-11-20 19:25:07 +0000 | [diff] [blame] | 185 | /// longjmp_result = getTempRet0(); |
Heejin Ahn | c0f1817 | 2016-09-01 21:05:15 +0000 | [diff] [blame] | 186 | /// switch label { |
Heejin Ahn | 99bd16b | 2016-09-10 02:33:47 +0000 | [diff] [blame] | 187 | /// label 1: goto post-setjmp BB 1 |
| 188 | /// label 2: goto post-setjmp BB 2 |
Heejin Ahn | c0f1817 | 2016-09-01 21:05:15 +0000 | [diff] [blame] | 189 | /// ... |
Heejin Ahn | 99bd16b | 2016-09-10 02:33:47 +0000 | [diff] [blame] | 190 | /// default: goto splitted next BB |
Heejin Ahn | c0f1817 | 2016-09-01 21:05:15 +0000 | [diff] [blame] | 191 | /// } |
Heejin Ahn | 0c68a87 | 2018-11-08 22:56:26 +0000 | [diff] [blame] | 192 | /// testSetjmp examines setjmpTable to see if there is a matching setjmp |
| 193 | /// call. After calling an invoke wrapper, if a longjmp occurred, __THREW__ |
| 194 | /// will be the address of matching jmp_buf buffer and __threwValue be the |
| 195 | /// second argument to longjmp. mem[__THREW__.val] is a setjmp ID that is |
| 196 | /// stored in saveSetjmp. testSetjmp returns a setjmp label, a unique ID to |
| 197 | /// each setjmp callsite. Label 0 means this longjmp buffer does not |
| 198 | /// correspond to one of the setjmp callsites in this function, so in this |
| 199 | /// case we just chain the longjmp to the caller. (Here we call |
| 200 | /// emscripten_longjmp, which is different from emscripten_longjmp_jmpbuf. |
| 201 | /// emscripten_longjmp_jmpbuf takes jmp_buf as its first argument, while |
| 202 | /// emscripten_longjmp takes an int. Both of them will eventually be lowered |
| 203 | /// to emscripten_longjmp in s2wasm, but here we need two signatures - we |
| 204 | /// can't translate an int value to a jmp_buf.) |
| 205 | /// Label -1 means no longjmp occurred. Otherwise we jump to the right |
| 206 | /// post-setjmp BB based on the label. |
Heejin Ahn | c0f1817 | 2016-09-01 21:05:15 +0000 | [diff] [blame] | 207 | /// |
Derek Schuff | f41f67d | 2016-08-01 21:34:04 +0000 | [diff] [blame] | 208 | ///===----------------------------------------------------------------------===// |
| 209 | |
| 210 | #include "WebAssembly.h" |
Derek Schuff | 53b9af0 | 2016-08-09 00:29:55 +0000 | [diff] [blame] | 211 | #include "llvm/IR/CallSite.h" |
Heejin Ahn | c0f1817 | 2016-09-01 21:05:15 +0000 | [diff] [blame] | 212 | #include "llvm/IR/Dominators.h" |
Derek Schuff | f41f67d | 2016-08-01 21:34:04 +0000 | [diff] [blame] | 213 | #include "llvm/IR/IRBuilder.h" |
Heejin Ahn | c0f1817 | 2016-09-01 21:05:15 +0000 | [diff] [blame] | 214 | #include "llvm/Transforms/Utils/BasicBlockUtils.h" |
| 215 | #include "llvm/Transforms/Utils/SSAUpdater.h" |
Derek Schuff | f41f67d | 2016-08-01 21:34:04 +0000 | [diff] [blame] | 216 | |
| 217 | using namespace llvm; |
| 218 | |
Derek Schuff | ccdceda | 2016-08-18 15:27:25 +0000 | [diff] [blame] | 219 | #define DEBUG_TYPE "wasm-lower-em-ehsjlj" |
Derek Schuff | f41f67d | 2016-08-01 21:34:04 +0000 | [diff] [blame] | 220 | |
Derek Schuff | 6664132 | 2016-08-09 22:37:00 +0000 | [diff] [blame] | 221 | static cl::list<std::string> |
Derek Schuff | ccdceda | 2016-08-18 15:27:25 +0000 | [diff] [blame] | 222 | EHWhitelist("emscripten-cxx-exceptions-whitelist", |
| 223 | cl::desc("The list of function names in which Emscripten-style " |
| 224 | "exception handling is enabled (see emscripten " |
| 225 | "EMSCRIPTEN_CATCHING_WHITELIST options)"), |
| 226 | cl::CommaSeparated); |
Derek Schuff | 6664132 | 2016-08-09 22:37:00 +0000 | [diff] [blame] | 227 | |
Derek Schuff | f41f67d | 2016-08-01 21:34:04 +0000 | [diff] [blame] | 228 | namespace { |
Derek Schuff | ccdceda | 2016-08-18 15:27:25 +0000 | [diff] [blame] | 229 | class WebAssemblyLowerEmscriptenEHSjLj final : public ModulePass { |
Derek Schuff | ccdceda | 2016-08-18 15:27:25 +0000 | [diff] [blame] | 230 | static const char *ResumeFName; |
| 231 | static const char *EHTypeIDFName; |
Heejin Ahn | c0f1817 | 2016-09-01 21:05:15 +0000 | [diff] [blame] | 232 | static const char *EmLongjmpFName; |
| 233 | static const char *EmLongjmpJmpbufFName; |
| 234 | static const char *SaveSetjmpFName; |
| 235 | static const char *TestSetjmpFName; |
Derek Schuff | ccdceda | 2016-08-18 15:27:25 +0000 | [diff] [blame] | 236 | static const char *FindMatchingCatchPrefix; |
| 237 | static const char *InvokePrefix; |
| 238 | |
Heejin Ahn | c0f1817 | 2016-09-01 21:05:15 +0000 | [diff] [blame] | 239 | bool EnableEH; // Enable exception handling |
| 240 | bool EnableSjLj; // Enable setjmp/longjmp handling |
Derek Schuff | ccdceda | 2016-08-18 15:27:25 +0000 | [diff] [blame] | 241 | |
Heejin Ahn | 18c56a0 | 2019-02-04 19:13:39 +0000 | [diff] [blame] | 242 | GlobalVariable *ThrewGV = nullptr; |
| 243 | GlobalVariable *ThrewValueGV = nullptr; |
| 244 | Function *GetTempRet0Func = nullptr; |
| 245 | Function *SetTempRet0Func = nullptr; |
| 246 | Function *ResumeF = nullptr; |
| 247 | Function *EHTypeIDF = nullptr; |
| 248 | Function *EmLongjmpF = nullptr; |
| 249 | Function *EmLongjmpJmpbufF = nullptr; |
| 250 | Function *SaveSetjmpF = nullptr; |
| 251 | Function *TestSetjmpF = nullptr; |
Heejin Ahn | c0f1817 | 2016-09-01 21:05:15 +0000 | [diff] [blame] | 252 | |
Derek Schuff | ccdceda | 2016-08-18 15:27:25 +0000 | [diff] [blame] | 253 | // __cxa_find_matching_catch_N functions. |
| 254 | // Indexed by the number of clauses in an original landingpad instruction. |
| 255 | DenseMap<int, Function *> FindMatchingCatches; |
| 256 | // Map of <function signature string, invoke_ wrappers> |
| 257 | StringMap<Function *> InvokeWrappers; |
| 258 | // Set of whitelisted function names for exception handling |
| 259 | std::set<std::string> EHWhitelistSet; |
| 260 | |
Mehdi Amini | 117296c | 2016-10-01 02:56:57 +0000 | [diff] [blame] | 261 | StringRef getPassName() const override { |
Derek Schuff | f41f67d | 2016-08-01 21:34:04 +0000 | [diff] [blame] | 262 | return "WebAssembly Lower Emscripten Exceptions"; |
| 263 | } |
| 264 | |
Derek Schuff | ccdceda | 2016-08-18 15:27:25 +0000 | [diff] [blame] | 265 | bool runEHOnFunction(Function &F); |
| 266 | bool runSjLjOnFunction(Function &F); |
Derek Schuff | f41f67d | 2016-08-01 21:34:04 +0000 | [diff] [blame] | 267 | Function *getFindMatchingCatch(Module &M, unsigned NumClauses); |
| 268 | |
Heejin Ahn | c0f1817 | 2016-09-01 21:05:15 +0000 | [diff] [blame] | 269 | template <typename CallOrInvoke> Value *wrapInvoke(CallOrInvoke *CI); |
| 270 | void wrapTestSetjmp(BasicBlock *BB, Instruction *InsertPt, Value *Threw, |
| 271 | Value *SetjmpTable, Value *SetjmpTableSize, Value *&Label, |
| 272 | Value *&LongjmpResult, BasicBlock *&EndBB); |
| 273 | template <typename CallOrInvoke> Function *getInvokeWrapper(CallOrInvoke *CI); |
| 274 | |
Derek Schuff | ccdceda | 2016-08-18 15:27:25 +0000 | [diff] [blame] | 275 | bool areAllExceptionsAllowed() const { return EHWhitelistSet.empty(); } |
Heejin Ahn | c0f1817 | 2016-09-01 21:05:15 +0000 | [diff] [blame] | 276 | bool canLongjmp(Module &M, const Value *Callee) const; |
Guanzhong Chen | b1cb9fd | 2019-08-16 18:21:08 +0000 | [diff] [blame^] | 277 | bool isEmAsmCall(Module &M, const Value *Callee) const; |
Heejin Ahn | c0f1817 | 2016-09-01 21:05:15 +0000 | [diff] [blame] | 278 | |
Heejin Ahn | c0f1817 | 2016-09-01 21:05:15 +0000 | [diff] [blame] | 279 | void rebuildSSA(Function &F); |
Derek Schuff | f41f67d | 2016-08-01 21:34:04 +0000 | [diff] [blame] | 280 | |
| 281 | public: |
| 282 | static char ID; |
| 283 | |
Heejin Ahn | c0f1817 | 2016-09-01 21:05:15 +0000 | [diff] [blame] | 284 | WebAssemblyLowerEmscriptenEHSjLj(bool EnableEH = true, bool EnableSjLj = true) |
Heejin Ahn | 18c56a0 | 2019-02-04 19:13:39 +0000 | [diff] [blame] | 285 | : ModulePass(ID), EnableEH(EnableEH), EnableSjLj(EnableSjLj) { |
Derek Schuff | ccdceda | 2016-08-18 15:27:25 +0000 | [diff] [blame] | 286 | EHWhitelistSet.insert(EHWhitelist.begin(), EHWhitelist.end()); |
Derek Schuff | 6664132 | 2016-08-09 22:37:00 +0000 | [diff] [blame] | 287 | } |
Derek Schuff | f41f67d | 2016-08-01 21:34:04 +0000 | [diff] [blame] | 288 | bool runOnModule(Module &M) override; |
Heejin Ahn | c0f1817 | 2016-09-01 21:05:15 +0000 | [diff] [blame] | 289 | |
| 290 | void getAnalysisUsage(AnalysisUsage &AU) const override { |
| 291 | AU.addRequired<DominatorTreeWrapperPass>(); |
| 292 | } |
Derek Schuff | f41f67d | 2016-08-01 21:34:04 +0000 | [diff] [blame] | 293 | }; |
| 294 | } // End anonymous namespace |
| 295 | |
Derek Schuff | ccdceda | 2016-08-18 15:27:25 +0000 | [diff] [blame] | 296 | const char *WebAssemblyLowerEmscriptenEHSjLj::ResumeFName = "__resumeException"; |
| 297 | const char *WebAssemblyLowerEmscriptenEHSjLj::EHTypeIDFName = |
| 298 | "llvm_eh_typeid_for"; |
Heejin Ahn | c0f1817 | 2016-09-01 21:05:15 +0000 | [diff] [blame] | 299 | const char *WebAssemblyLowerEmscriptenEHSjLj::EmLongjmpFName = |
| 300 | "emscripten_longjmp"; |
| 301 | const char *WebAssemblyLowerEmscriptenEHSjLj::EmLongjmpJmpbufFName = |
| 302 | "emscripten_longjmp_jmpbuf"; |
| 303 | const char *WebAssemblyLowerEmscriptenEHSjLj::SaveSetjmpFName = "saveSetjmp"; |
| 304 | const char *WebAssemblyLowerEmscriptenEHSjLj::TestSetjmpFName = "testSetjmp"; |
Derek Schuff | ccdceda | 2016-08-18 15:27:25 +0000 | [diff] [blame] | 305 | const char *WebAssemblyLowerEmscriptenEHSjLj::FindMatchingCatchPrefix = |
| 306 | "__cxa_find_matching_catch_"; |
| 307 | const char *WebAssemblyLowerEmscriptenEHSjLj::InvokePrefix = "__invoke_"; |
Derek Schuff | f41f67d | 2016-08-01 21:34:04 +0000 | [diff] [blame] | 308 | |
Derek Schuff | ccdceda | 2016-08-18 15:27:25 +0000 | [diff] [blame] | 309 | char WebAssemblyLowerEmscriptenEHSjLj::ID = 0; |
| 310 | INITIALIZE_PASS(WebAssemblyLowerEmscriptenEHSjLj, DEBUG_TYPE, |
| 311 | "WebAssembly Lower Emscripten Exceptions / Setjmp / Longjmp", |
| 312 | false, false) |
| 313 | |
Heejin Ahn | c0f1817 | 2016-09-01 21:05:15 +0000 | [diff] [blame] | 314 | ModulePass *llvm::createWebAssemblyLowerEmscriptenEHSjLj(bool EnableEH, |
| 315 | bool EnableSjLj) { |
| 316 | return new WebAssemblyLowerEmscriptenEHSjLj(EnableEH, EnableSjLj); |
Derek Schuff | f41f67d | 2016-08-01 21:34:04 +0000 | [diff] [blame] | 317 | } |
| 318 | |
| 319 | static bool canThrow(const Value *V) { |
| 320 | if (const auto *F = dyn_cast<const Function>(V)) { |
| 321 | // Intrinsics cannot throw |
| 322 | if (F->isIntrinsic()) |
| 323 | return false; |
| 324 | StringRef Name = F->getName(); |
| 325 | // leave setjmp and longjmp (mostly) alone, we process them properly later |
| 326 | if (Name == "setjmp" || Name == "longjmp") |
| 327 | return false; |
Heejin Ahn | c0f1817 | 2016-09-01 21:05:15 +0000 | [diff] [blame] | 328 | return !F->doesNotThrow(); |
Derek Schuff | f41f67d | 2016-08-01 21:34:04 +0000 | [diff] [blame] | 329 | } |
Heejin Ahn | b6cd512 | 2016-08-24 22:53:00 +0000 | [diff] [blame] | 330 | // not a function, so an indirect call - can throw, we can't tell |
| 331 | return true; |
Derek Schuff | f41f67d | 2016-08-01 21:34:04 +0000 | [diff] [blame] | 332 | } |
| 333 | |
Sam Clegg | b2486f1 | 2018-10-02 22:12:15 +0000 | [diff] [blame] | 334 | // Get a global variable with the given name. If it doesn't exist declare it, |
| 335 | // which will generate an import and asssumes that it will exist at link time. |
| 336 | static GlobalVariable *getGlobalVariableI32(Module &M, IRBuilder<> &IRB, |
| 337 | const char *Name) { |
Sam Clegg | 28b3e99 | 2018-07-17 16:40:03 +0000 | [diff] [blame] | 338 | |
Sam Clegg | 12011fa | 2019-04-04 01:43:21 +0000 | [diff] [blame] | 339 | auto* GV = dyn_cast<GlobalVariable>(M.getOrInsertGlobal(Name, IRB.getInt32Ty())); |
| 340 | if (!GV) |
| 341 | report_fatal_error(Twine("unable to create global: ") + Name); |
| 342 | |
| 343 | return GV; |
Derek Schuff | f41f67d | 2016-08-01 21:34:04 +0000 | [diff] [blame] | 344 | } |
| 345 | |
| 346 | // Simple function name mangler. |
| 347 | // This function simply takes LLVM's string representation of parameter types |
Derek Schuff | 53b9af0 | 2016-08-09 00:29:55 +0000 | [diff] [blame] | 348 | // and concatenate them with '_'. There are non-alphanumeric characters but llc |
| 349 | // is ok with it, and we need to postprocess these names after the lowering |
| 350 | // phase anyway. |
Derek Schuff | f41f67d | 2016-08-01 21:34:04 +0000 | [diff] [blame] | 351 | static std::string getSignature(FunctionType *FTy) { |
| 352 | std::string Sig; |
| 353 | raw_string_ostream OS(Sig); |
| 354 | OS << *FTy->getReturnType(); |
| 355 | for (Type *ParamTy : FTy->params()) |
| 356 | OS << "_" << *ParamTy; |
| 357 | if (FTy->isVarArg()) |
| 358 | OS << "_..."; |
| 359 | Sig = OS.str(); |
David Majnemer | c700490 | 2016-08-12 04:32:37 +0000 | [diff] [blame] | 360 | Sig.erase(remove_if(Sig, isspace), Sig.end()); |
Derek Schuff | 53b9af0 | 2016-08-09 00:29:55 +0000 | [diff] [blame] | 361 | // When s2wasm parses .s file, a comma means the end of an argument. So a |
| 362 | // mangled function name can contain any character but a comma. |
| 363 | std::replace(Sig.begin(), Sig.end(), ',', '.'); |
Derek Schuff | f41f67d | 2016-08-01 21:34:04 +0000 | [diff] [blame] | 364 | return Sig; |
| 365 | } |
| 366 | |
Heejin Ahn | c0f1817 | 2016-09-01 21:05:15 +0000 | [diff] [blame] | 367 | // Returns __cxa_find_matching_catch_N function, where N = NumClauses + 2. |
| 368 | // This is because a landingpad instruction contains two more arguments, a |
| 369 | // personality function and a cleanup bit, and __cxa_find_matching_catch_N |
| 370 | // functions are named after the number of arguments in the original landingpad |
| 371 | // instruction. |
Derek Schuff | ccdceda | 2016-08-18 15:27:25 +0000 | [diff] [blame] | 372 | Function * |
| 373 | WebAssemblyLowerEmscriptenEHSjLj::getFindMatchingCatch(Module &M, |
| 374 | unsigned NumClauses) { |
Derek Schuff | f41f67d | 2016-08-01 21:34:04 +0000 | [diff] [blame] | 375 | if (FindMatchingCatches.count(NumClauses)) |
| 376 | return FindMatchingCatches[NumClauses]; |
| 377 | PointerType *Int8PtrTy = Type::getInt8PtrTy(M.getContext()); |
| 378 | SmallVector<Type *, 16> Args(NumClauses, Int8PtrTy); |
| 379 | FunctionType *FTy = FunctionType::get(Int8PtrTy, Args, false); |
Derek Schuff | ccdceda | 2016-08-18 15:27:25 +0000 | [diff] [blame] | 380 | Function *F = |
| 381 | Function::Create(FTy, GlobalValue::ExternalLinkage, |
| 382 | FindMatchingCatchPrefix + Twine(NumClauses + 2), &M); |
Derek Schuff | f41f67d | 2016-08-01 21:34:04 +0000 | [diff] [blame] | 383 | FindMatchingCatches[NumClauses] = F; |
| 384 | return F; |
| 385 | } |
| 386 | |
Heejin Ahn | c0f1817 | 2016-09-01 21:05:15 +0000 | [diff] [blame] | 387 | // Generate invoke wrapper seqence with preamble and postamble |
| 388 | // Preamble: |
| 389 | // __THREW__ = 0; |
| 390 | // Postamble: |
| 391 | // %__THREW__.val = __THREW__; __THREW__ = 0; |
| 392 | // Returns %__THREW__.val, which indicates whether an exception is thrown (or |
| 393 | // whether longjmp occurred), for future use. |
| 394 | template <typename CallOrInvoke> |
| 395 | Value *WebAssemblyLowerEmscriptenEHSjLj::wrapInvoke(CallOrInvoke *CI) { |
| 396 | LLVMContext &C = CI->getModule()->getContext(); |
| 397 | |
| 398 | // If we are calling a function that is noreturn, we must remove that |
| 399 | // attribute. The code we insert here does expect it to return, after we |
| 400 | // catch the exception. |
| 401 | if (CI->doesNotReturn()) { |
| 402 | if (auto *F = dyn_cast<Function>(CI->getCalledValue())) |
| 403 | F->removeFnAttr(Attribute::NoReturn); |
Reid Kleckner | b518054 | 2017-03-21 16:57:19 +0000 | [diff] [blame] | 404 | CI->removeAttribute(AttributeList::FunctionIndex, Attribute::NoReturn); |
Heejin Ahn | c0f1817 | 2016-09-01 21:05:15 +0000 | [diff] [blame] | 405 | } |
| 406 | |
| 407 | IRBuilder<> IRB(C); |
| 408 | IRB.SetInsertPoint(CI); |
| 409 | |
| 410 | // Pre-invoke |
| 411 | // __THREW__ = 0; |
| 412 | IRB.CreateStore(IRB.getInt32(0), ThrewGV); |
| 413 | |
| 414 | // Invoke function wrapper in JavaScript |
| 415 | SmallVector<Value *, 16> Args; |
| 416 | // Put the pointer to the callee as first argument, so it can be called |
| 417 | // within the invoke wrapper later |
| 418 | Args.push_back(CI->getCalledValue()); |
| 419 | Args.append(CI->arg_begin(), CI->arg_end()); |
| 420 | CallInst *NewCall = IRB.CreateCall(getInvokeWrapper(CI), Args); |
| 421 | NewCall->takeName(CI); |
Keno Fischer | 5c3cdef | 2019-08-05 21:36:09 +0000 | [diff] [blame] | 422 | NewCall->setCallingConv(CallingConv::WASM_EmscriptenInvoke); |
Heejin Ahn | c0f1817 | 2016-09-01 21:05:15 +0000 | [diff] [blame] | 423 | NewCall->setDebugLoc(CI->getDebugLoc()); |
| 424 | |
| 425 | // Because we added the pointer to the callee as first argument, all |
| 426 | // argument attribute indices have to be incremented by one. |
Reid Kleckner | 7f72033 | 2017-04-13 00:58:09 +0000 | [diff] [blame] | 427 | SmallVector<AttributeSet, 8> ArgAttributes; |
Derek Schuff | 0db0ca3 | 2017-04-12 16:03:00 +0000 | [diff] [blame] | 428 | const AttributeList &InvokeAL = CI->getAttributes(); |
| 429 | |
Derek Schuff | 0db0ca3 | 2017-04-12 16:03:00 +0000 | [diff] [blame] | 430 | // No attributes for the callee pointer. |
Reid Kleckner | 7f72033 | 2017-04-13 00:58:09 +0000 | [diff] [blame] | 431 | ArgAttributes.push_back(AttributeSet()); |
Derek Schuff | 0db0ca3 | 2017-04-12 16:03:00 +0000 | [diff] [blame] | 432 | // Copy the argument attributes from the original |
Heejin Ahn | 18c56a0 | 2019-02-04 19:13:39 +0000 | [diff] [blame] | 433 | for (unsigned I = 0, E = CI->getNumArgOperands(); I < E; ++I) |
| 434 | ArgAttributes.push_back(InvokeAL.getParamAttributes(I)); |
Derek Schuff | 0db0ca3 | 2017-04-12 16:03:00 +0000 | [diff] [blame] | 435 | |
Keno Fischer | 3c805d1 | 2019-08-03 21:38:19 +0000 | [diff] [blame] | 436 | AttrBuilder FnAttrs(InvokeAL.getFnAttributes()); |
| 437 | if (FnAttrs.contains(Attribute::AllocSize)) { |
| 438 | // The allocsize attribute (if any) referes to parameters by index and needs |
| 439 | // to be adjusted. |
| 440 | unsigned SizeArg; |
| 441 | Optional<unsigned> NEltArg; |
| 442 | std::tie(SizeArg, NEltArg) = FnAttrs.getAllocSizeArgs(); |
| 443 | SizeArg += 1; |
| 444 | if (NEltArg.hasValue()) |
| 445 | NEltArg = NEltArg.getValue() + 1; |
| 446 | FnAttrs.addAllocSizeAttr(SizeArg, NEltArg); |
| 447 | } |
| 448 | |
Heejin Ahn | c0f1817 | 2016-09-01 21:05:15 +0000 | [diff] [blame] | 449 | // Reconstruct the AttributesList based on the vector we constructed. |
Reid Kleckner | 7f72033 | 2017-04-13 00:58:09 +0000 | [diff] [blame] | 450 | AttributeList NewCallAL = |
Keno Fischer | 3c805d1 | 2019-08-03 21:38:19 +0000 | [diff] [blame] | 451 | AttributeList::get(C, AttributeSet::get(C, FnAttrs), |
Reid Kleckner | 7f72033 | 2017-04-13 00:58:09 +0000 | [diff] [blame] | 452 | InvokeAL.getRetAttributes(), ArgAttributes); |
Derek Schuff | 0db0ca3 | 2017-04-12 16:03:00 +0000 | [diff] [blame] | 453 | NewCall->setAttributes(NewCallAL); |
Heejin Ahn | c0f1817 | 2016-09-01 21:05:15 +0000 | [diff] [blame] | 454 | |
| 455 | CI->replaceAllUsesWith(NewCall); |
| 456 | |
| 457 | // Post-invoke |
| 458 | // %__THREW__.val = __THREW__; __THREW__ = 0; |
James Y Knight | 14359ef | 2019-02-01 20:44:24 +0000 | [diff] [blame] | 459 | Value *Threw = |
| 460 | IRB.CreateLoad(IRB.getInt32Ty(), ThrewGV, ThrewGV->getName() + ".val"); |
Heejin Ahn | c0f1817 | 2016-09-01 21:05:15 +0000 | [diff] [blame] | 461 | IRB.CreateStore(IRB.getInt32(0), ThrewGV); |
| 462 | return Threw; |
| 463 | } |
| 464 | |
| 465 | // Get matching invoke wrapper based on callee signature |
| 466 | template <typename CallOrInvoke> |
| 467 | Function *WebAssemblyLowerEmscriptenEHSjLj::getInvokeWrapper(CallOrInvoke *CI) { |
| 468 | Module *M = CI->getModule(); |
Derek Schuff | f41f67d | 2016-08-01 21:34:04 +0000 | [diff] [blame] | 469 | SmallVector<Type *, 16> ArgTys; |
Heejin Ahn | c0f1817 | 2016-09-01 21:05:15 +0000 | [diff] [blame] | 470 | Value *Callee = CI->getCalledValue(); |
Derek Schuff | f41f67d | 2016-08-01 21:34:04 +0000 | [diff] [blame] | 471 | FunctionType *CalleeFTy; |
| 472 | if (auto *F = dyn_cast<Function>(Callee)) |
| 473 | CalleeFTy = F->getFunctionType(); |
| 474 | else { |
Heejin Ahn | c0f1817 | 2016-09-01 21:05:15 +0000 | [diff] [blame] | 475 | auto *CalleeTy = cast<PointerType>(Callee->getType())->getElementType(); |
Derek Schuff | f41f67d | 2016-08-01 21:34:04 +0000 | [diff] [blame] | 476 | CalleeFTy = dyn_cast<FunctionType>(CalleeTy); |
| 477 | } |
| 478 | |
| 479 | std::string Sig = getSignature(CalleeFTy); |
| 480 | if (InvokeWrappers.find(Sig) != InvokeWrappers.end()) |
| 481 | return InvokeWrappers[Sig]; |
| 482 | |
| 483 | // Put the pointer to the callee as first argument |
| 484 | ArgTys.push_back(PointerType::getUnqual(CalleeFTy)); |
| 485 | // Add argument types |
| 486 | ArgTys.append(CalleeFTy->param_begin(), CalleeFTy->param_end()); |
| 487 | |
| 488 | FunctionType *FTy = FunctionType::get(CalleeFTy->getReturnType(), ArgTys, |
| 489 | CalleeFTy->isVarArg()); |
| 490 | Function *F = Function::Create(FTy, GlobalValue::ExternalLinkage, |
Heejin Ahn | c0f1817 | 2016-09-01 21:05:15 +0000 | [diff] [blame] | 491 | InvokePrefix + Sig, M); |
Derek Schuff | f41f67d | 2016-08-01 21:34:04 +0000 | [diff] [blame] | 492 | InvokeWrappers[Sig] = F; |
| 493 | return F; |
| 494 | } |
| 495 | |
Heejin Ahn | c0f1817 | 2016-09-01 21:05:15 +0000 | [diff] [blame] | 496 | bool WebAssemblyLowerEmscriptenEHSjLj::canLongjmp(Module &M, |
| 497 | const Value *Callee) const { |
| 498 | if (auto *CalleeF = dyn_cast<Function>(Callee)) |
| 499 | if (CalleeF->isIntrinsic()) |
| 500 | return false; |
Heejin Ahn | 23d5710 | 2016-08-31 22:40:34 +0000 | [diff] [blame] | 501 | |
Guanzhong Chen | b88ebe8 | 2019-07-03 00:37:49 +0000 | [diff] [blame] | 502 | // Attempting to transform inline assembly will result in something like: |
| 503 | // call void @__invoke_void(void ()* asm ...) |
| 504 | // which is invalid because inline assembly blocks do not have addresses |
| 505 | // and can't be passed by pointer. The result is a crash with illegal IR. |
| 506 | if (isa<InlineAsm>(Callee)) |
| 507 | return false; |
| 508 | |
Heejin Ahn | c0f1817 | 2016-09-01 21:05:15 +0000 | [diff] [blame] | 509 | // The reason we include malloc/free here is to exclude the malloc/free |
| 510 | // calls generated in setjmp prep / cleanup routines. |
| 511 | Function *SetjmpF = M.getFunction("setjmp"); |
| 512 | Function *MallocF = M.getFunction("malloc"); |
| 513 | Function *FreeF = M.getFunction("free"); |
| 514 | if (Callee == SetjmpF || Callee == MallocF || Callee == FreeF) |
Heejin Ahn | 10a7086 | 2016-09-01 00:44:37 +0000 | [diff] [blame] | 515 | return false; |
| 516 | |
Heejin Ahn | c0f1817 | 2016-09-01 21:05:15 +0000 | [diff] [blame] | 517 | // There are functions in JS glue code |
| 518 | if (Callee == ResumeF || Callee == EHTypeIDF || Callee == SaveSetjmpF || |
| 519 | Callee == TestSetjmpF) |
| 520 | return false; |
Heejin Ahn | 10a7086 | 2016-09-01 00:44:37 +0000 | [diff] [blame] | 521 | |
Heejin Ahn | c0f1817 | 2016-09-01 21:05:15 +0000 | [diff] [blame] | 522 | // __cxa_find_matching_catch_N functions cannot longjmp |
| 523 | if (Callee->getName().startswith(FindMatchingCatchPrefix)) |
| 524 | return false; |
| 525 | |
| 526 | // Exception-catching related functions |
| 527 | Function *BeginCatchF = M.getFunction("__cxa_begin_catch"); |
| 528 | Function *EndCatchF = M.getFunction("__cxa_end_catch"); |
| 529 | Function *AllocExceptionF = M.getFunction("__cxa_allocate_exception"); |
| 530 | Function *ThrowF = M.getFunction("__cxa_throw"); |
| 531 | Function *TerminateF = M.getFunction("__clang_call_terminate"); |
| 532 | if (Callee == BeginCatchF || Callee == EndCatchF || |
Sam Clegg | 4791a66 | 2018-11-20 19:25:07 +0000 | [diff] [blame] | 533 | Callee == AllocExceptionF || Callee == ThrowF || Callee == TerminateF || |
| 534 | Callee == GetTempRet0Func || Callee == SetTempRet0Func) |
Heejin Ahn | c0f1817 | 2016-09-01 21:05:15 +0000 | [diff] [blame] | 535 | return false; |
| 536 | |
| 537 | // Otherwise we don't know |
| 538 | return true; |
| 539 | } |
| 540 | |
Guanzhong Chen | b1cb9fd | 2019-08-16 18:21:08 +0000 | [diff] [blame^] | 541 | bool WebAssemblyLowerEmscriptenEHSjLj::isEmAsmCall(Module &M, |
| 542 | const Value *Callee) const { |
| 543 | // This is an exhaustive list from Emscripten's <emscripten/em_asm.h>. |
| 544 | Function *EmAsmConstIntF = M.getFunction("emscripten_asm_const_int"); |
| 545 | Function *EmAsmConstDoubleF = M.getFunction("emscripten_asm_const_double"); |
| 546 | Function *EmAsmConstIntSyncMainF = |
| 547 | M.getFunction("emscripten_asm_const_int_sync_on_main_thread"); |
| 548 | Function *EmAsmConstDoubleSyncMainF = |
| 549 | M.getFunction("emscripten_asm_const_double_sync_on_main_thread"); |
| 550 | Function *EmAsmConstAsyncMainF = |
| 551 | M.getFunction("emscripten_asm_const_async_on_main_thread"); |
| 552 | |
| 553 | return Callee == EmAsmConstIntF || Callee == EmAsmConstDoubleF || |
| 554 | Callee == EmAsmConstIntSyncMainF || |
| 555 | Callee == EmAsmConstDoubleSyncMainF || Callee == EmAsmConstAsyncMainF; |
| 556 | } |
| 557 | |
Heejin Ahn | c0f1817 | 2016-09-01 21:05:15 +0000 | [diff] [blame] | 558 | // Generate testSetjmp function call seqence with preamble and postamble. |
| 559 | // The code this generates is equivalent to the following JavaScript code: |
| 560 | // if (%__THREW__.val != 0 & threwValue != 0) { |
| 561 | // %label = _testSetjmp(mem[%__THREW__.val], setjmpTable, setjmpTableSize); |
| 562 | // if (%label == 0) |
| 563 | // emscripten_longjmp(%__THREW__.val, threwValue); |
Sam Clegg | 4791a66 | 2018-11-20 19:25:07 +0000 | [diff] [blame] | 564 | // setTempRet0(threwValue); |
Heejin Ahn | c0f1817 | 2016-09-01 21:05:15 +0000 | [diff] [blame] | 565 | // } else { |
| 566 | // %label = -1; |
| 567 | // } |
Sam Clegg | 4791a66 | 2018-11-20 19:25:07 +0000 | [diff] [blame] | 568 | // %longjmp_result = getTempRet0(); |
Heejin Ahn | c0f1817 | 2016-09-01 21:05:15 +0000 | [diff] [blame] | 569 | // |
| 570 | // As output parameters. returns %label, %longjmp_result, and the BB the last |
| 571 | // instruction (%longjmp_result = ...) is in. |
| 572 | void WebAssemblyLowerEmscriptenEHSjLj::wrapTestSetjmp( |
| 573 | BasicBlock *BB, Instruction *InsertPt, Value *Threw, Value *SetjmpTable, |
| 574 | Value *SetjmpTableSize, Value *&Label, Value *&LongjmpResult, |
| 575 | BasicBlock *&EndBB) { |
| 576 | Function *F = BB->getParent(); |
| 577 | LLVMContext &C = BB->getModule()->getContext(); |
| 578 | IRBuilder<> IRB(C); |
| 579 | IRB.SetInsertPoint(InsertPt); |
| 580 | |
| 581 | // if (%__THREW__.val != 0 & threwValue != 0) |
| 582 | IRB.SetInsertPoint(BB); |
| 583 | BasicBlock *ThenBB1 = BasicBlock::Create(C, "if.then1", F); |
| 584 | BasicBlock *ElseBB1 = BasicBlock::Create(C, "if.else1", F); |
| 585 | BasicBlock *EndBB1 = BasicBlock::Create(C, "if.end", F); |
| 586 | Value *ThrewCmp = IRB.CreateICmpNE(Threw, IRB.getInt32(0)); |
James Y Knight | 14359ef | 2019-02-01 20:44:24 +0000 | [diff] [blame] | 587 | Value *ThrewValue = IRB.CreateLoad(IRB.getInt32Ty(), ThrewValueGV, |
| 588 | ThrewValueGV->getName() + ".val"); |
Heejin Ahn | c0f1817 | 2016-09-01 21:05:15 +0000 | [diff] [blame] | 589 | Value *ThrewValueCmp = IRB.CreateICmpNE(ThrewValue, IRB.getInt32(0)); |
| 590 | Value *Cmp1 = IRB.CreateAnd(ThrewCmp, ThrewValueCmp, "cmp1"); |
| 591 | IRB.CreateCondBr(Cmp1, ThenBB1, ElseBB1); |
| 592 | |
| 593 | // %label = _testSetjmp(mem[%__THREW__.val], _setjmpTable, _setjmpTableSize); |
| 594 | // if (%label == 0) |
| 595 | IRB.SetInsertPoint(ThenBB1); |
| 596 | BasicBlock *ThenBB2 = BasicBlock::Create(C, "if.then2", F); |
| 597 | BasicBlock *EndBB2 = BasicBlock::Create(C, "if.end2", F); |
| 598 | Value *ThrewInt = IRB.CreateIntToPtr(Threw, Type::getInt32PtrTy(C), |
| 599 | Threw->getName() + ".i32p"); |
James Y Knight | 14359ef | 2019-02-01 20:44:24 +0000 | [diff] [blame] | 600 | Value *LoadedThrew = IRB.CreateLoad(IRB.getInt32Ty(), ThrewInt, |
| 601 | ThrewInt->getName() + ".loaded"); |
Heejin Ahn | c0f1817 | 2016-09-01 21:05:15 +0000 | [diff] [blame] | 602 | Value *ThenLabel = IRB.CreateCall( |
| 603 | TestSetjmpF, {LoadedThrew, SetjmpTable, SetjmpTableSize}, "label"); |
| 604 | Value *Cmp2 = IRB.CreateICmpEQ(ThenLabel, IRB.getInt32(0)); |
| 605 | IRB.CreateCondBr(Cmp2, ThenBB2, EndBB2); |
| 606 | |
| 607 | // emscripten_longjmp(%__THREW__.val, threwValue); |
| 608 | IRB.SetInsertPoint(ThenBB2); |
| 609 | IRB.CreateCall(EmLongjmpF, {Threw, ThrewValue}); |
| 610 | IRB.CreateUnreachable(); |
| 611 | |
Sam Clegg | 4791a66 | 2018-11-20 19:25:07 +0000 | [diff] [blame] | 612 | // setTempRet0(threwValue); |
Heejin Ahn | c0f1817 | 2016-09-01 21:05:15 +0000 | [diff] [blame] | 613 | IRB.SetInsertPoint(EndBB2); |
Sam Clegg | 4791a66 | 2018-11-20 19:25:07 +0000 | [diff] [blame] | 614 | IRB.CreateCall(SetTempRet0Func, ThrewValue); |
Heejin Ahn | c0f1817 | 2016-09-01 21:05:15 +0000 | [diff] [blame] | 615 | IRB.CreateBr(EndBB1); |
| 616 | |
| 617 | IRB.SetInsertPoint(ElseBB1); |
| 618 | IRB.CreateBr(EndBB1); |
| 619 | |
Sam Clegg | 4791a66 | 2018-11-20 19:25:07 +0000 | [diff] [blame] | 620 | // longjmp_result = getTempRet0(); |
Heejin Ahn | c0f1817 | 2016-09-01 21:05:15 +0000 | [diff] [blame] | 621 | IRB.SetInsertPoint(EndBB1); |
| 622 | PHINode *LabelPHI = IRB.CreatePHI(IRB.getInt32Ty(), 2, "label"); |
| 623 | LabelPHI->addIncoming(ThenLabel, EndBB2); |
| 624 | |
| 625 | LabelPHI->addIncoming(IRB.getInt32(-1), ElseBB1); |
| 626 | |
| 627 | // Output parameter assignment |
| 628 | Label = LabelPHI; |
| 629 | EndBB = EndBB1; |
Sam Clegg | 4791a66 | 2018-11-20 19:25:07 +0000 | [diff] [blame] | 630 | LongjmpResult = IRB.CreateCall(GetTempRet0Func, None, "longjmp_result"); |
Heejin Ahn | c0f1817 | 2016-09-01 21:05:15 +0000 | [diff] [blame] | 631 | } |
| 632 | |
Heejin Ahn | c0f1817 | 2016-09-01 21:05:15 +0000 | [diff] [blame] | 633 | void WebAssemblyLowerEmscriptenEHSjLj::rebuildSSA(Function &F) { |
| 634 | DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>(F).getDomTree(); |
| 635 | DT.recalculate(F); // CFG has been changed |
| 636 | SSAUpdater SSA; |
| 637 | for (BasicBlock &BB : F) { |
| 638 | for (Instruction &I : BB) { |
| 639 | for (auto UI = I.use_begin(), UE = I.use_end(); UI != UE;) { |
| 640 | Use &U = *UI; |
| 641 | ++UI; |
| 642 | SSA.Initialize(I.getType(), I.getName()); |
| 643 | SSA.AddAvailableValue(&BB, &I); |
Heejin Ahn | 18c56a0 | 2019-02-04 19:13:39 +0000 | [diff] [blame] | 644 | auto *User = cast<Instruction>(U.getUser()); |
Heejin Ahn | c0f1817 | 2016-09-01 21:05:15 +0000 | [diff] [blame] | 645 | if (User->getParent() == &BB) |
| 646 | continue; |
| 647 | |
Heejin Ahn | 18c56a0 | 2019-02-04 19:13:39 +0000 | [diff] [blame] | 648 | if (auto *UserPN = dyn_cast<PHINode>(User)) |
Heejin Ahn | c0f1817 | 2016-09-01 21:05:15 +0000 | [diff] [blame] | 649 | if (UserPN->getIncomingBlock(U) == &BB) |
| 650 | continue; |
| 651 | |
| 652 | if (DT.dominates(&I, User)) |
| 653 | continue; |
| 654 | SSA.RewriteUseAfterInsertions(U); |
| 655 | } |
| 656 | } |
| 657 | } |
| 658 | } |
| 659 | |
| 660 | bool WebAssemblyLowerEmscriptenEHSjLj::runOnModule(Module &M) { |
Heejin Ahn | 569f090 | 2019-01-09 23:05:21 +0000 | [diff] [blame] | 661 | LLVM_DEBUG(dbgs() << "********** Lower Emscripten EH & SjLj **********\n"); |
| 662 | |
Heejin Ahn | c0f1817 | 2016-09-01 21:05:15 +0000 | [diff] [blame] | 663 | LLVMContext &C = M.getContext(); |
| 664 | IRBuilder<> IRB(C); |
| 665 | |
| 666 | Function *SetjmpF = M.getFunction("setjmp"); |
| 667 | Function *LongjmpF = M.getFunction("longjmp"); |
| 668 | bool SetjmpUsed = SetjmpF && !SetjmpF->use_empty(); |
| 669 | bool LongjmpUsed = LongjmpF && !LongjmpF->use_empty(); |
| 670 | bool DoSjLj = EnableSjLj && (SetjmpUsed || LongjmpUsed); |
| 671 | |
Sam Clegg | 4791a66 | 2018-11-20 19:25:07 +0000 | [diff] [blame] | 672 | // Declare (or get) global variables __THREW__, __threwValue, and |
| 673 | // getTempRet0/setTempRet0 function which are used in common for both |
| 674 | // exception handling and setjmp/longjmp handling |
Sam Clegg | b2486f1 | 2018-10-02 22:12:15 +0000 | [diff] [blame] | 675 | ThrewGV = getGlobalVariableI32(M, IRB, "__THREW__"); |
| 676 | ThrewValueGV = getGlobalVariableI32(M, IRB, "__threwValue"); |
Sam Clegg | 4791a66 | 2018-11-20 19:25:07 +0000 | [diff] [blame] | 677 | GetTempRet0Func = |
| 678 | Function::Create(FunctionType::get(IRB.getInt32Ty(), false), |
| 679 | GlobalValue::ExternalLinkage, "getTempRet0", &M); |
| 680 | SetTempRet0Func = Function::Create( |
| 681 | FunctionType::get(IRB.getVoidTy(), IRB.getInt32Ty(), false), |
| 682 | GlobalValue::ExternalLinkage, "setTempRet0", &M); |
| 683 | GetTempRet0Func->setDoesNotThrow(); |
| 684 | SetTempRet0Func->setDoesNotThrow(); |
Heejin Ahn | c0f1817 | 2016-09-01 21:05:15 +0000 | [diff] [blame] | 685 | |
| 686 | bool Changed = false; |
| 687 | |
| 688 | // Exception handling |
| 689 | if (EnableEH) { |
| 690 | // Register __resumeException function |
| 691 | FunctionType *ResumeFTy = |
| 692 | FunctionType::get(IRB.getVoidTy(), IRB.getInt8PtrTy(), false); |
| 693 | ResumeF = Function::Create(ResumeFTy, GlobalValue::ExternalLinkage, |
| 694 | ResumeFName, &M); |
| 695 | |
| 696 | // Register llvm_eh_typeid_for function |
| 697 | FunctionType *EHTypeIDTy = |
| 698 | FunctionType::get(IRB.getInt32Ty(), IRB.getInt8PtrTy(), false); |
| 699 | EHTypeIDF = Function::Create(EHTypeIDTy, GlobalValue::ExternalLinkage, |
| 700 | EHTypeIDFName, &M); |
| 701 | |
| 702 | for (Function &F : M) { |
| 703 | if (F.isDeclaration()) |
| 704 | continue; |
| 705 | Changed |= runEHOnFunction(F); |
| 706 | } |
| 707 | } |
| 708 | |
| 709 | // Setjmp/longjmp handling |
| 710 | if (DoSjLj) { |
| 711 | Changed = true; // We have setjmp or longjmp somewhere |
| 712 | |
Heejin Ahn | c0f1817 | 2016-09-01 21:05:15 +0000 | [diff] [blame] | 713 | if (LongjmpF) { |
| 714 | // Replace all uses of longjmp with emscripten_longjmp_jmpbuf, which is |
| 715 | // defined in JS code |
| 716 | EmLongjmpJmpbufF = Function::Create(LongjmpF->getFunctionType(), |
| 717 | GlobalValue::ExternalLinkage, |
| 718 | EmLongjmpJmpbufFName, &M); |
| 719 | |
| 720 | LongjmpF->replaceAllUsesWith(EmLongjmpJmpbufF); |
| 721 | } |
Heejin Ahn | c0f1817 | 2016-09-01 21:05:15 +0000 | [diff] [blame] | 722 | |
Heejin Ahn | 0c68a87 | 2018-11-08 22:56:26 +0000 | [diff] [blame] | 723 | if (SetjmpF) { |
| 724 | // Register saveSetjmp function |
| 725 | FunctionType *SetjmpFTy = SetjmpF->getFunctionType(); |
| 726 | SmallVector<Type *, 4> Params = {SetjmpFTy->getParamType(0), |
| 727 | IRB.getInt32Ty(), Type::getInt32PtrTy(C), |
| 728 | IRB.getInt32Ty()}; |
| 729 | FunctionType *FTy = |
| 730 | FunctionType::get(Type::getInt32PtrTy(C), Params, false); |
| 731 | SaveSetjmpF = Function::Create(FTy, GlobalValue::ExternalLinkage, |
| 732 | SaveSetjmpFName, &M); |
| 733 | |
| 734 | // Register testSetjmp function |
| 735 | Params = {IRB.getInt32Ty(), Type::getInt32PtrTy(C), IRB.getInt32Ty()}; |
| 736 | FTy = FunctionType::get(IRB.getInt32Ty(), Params, false); |
| 737 | TestSetjmpF = Function::Create(FTy, GlobalValue::ExternalLinkage, |
| 738 | TestSetjmpFName, &M); |
| 739 | |
| 740 | FTy = FunctionType::get(IRB.getVoidTy(), |
| 741 | {IRB.getInt32Ty(), IRB.getInt32Ty()}, false); |
| 742 | EmLongjmpF = Function::Create(FTy, GlobalValue::ExternalLinkage, |
| 743 | EmLongjmpFName, &M); |
| 744 | |
| 745 | // Only traverse functions that uses setjmp in order not to insert |
| 746 | // unnecessary prep / cleanup code in every function |
| 747 | SmallPtrSet<Function *, 8> SetjmpUsers; |
| 748 | for (User *U : SetjmpF->users()) { |
| 749 | auto *UI = cast<Instruction>(U); |
| 750 | SetjmpUsers.insert(UI->getFunction()); |
| 751 | } |
| 752 | for (Function *F : SetjmpUsers) |
| 753 | runSjLjOnFunction(*F); |
Heejin Ahn | c0f1817 | 2016-09-01 21:05:15 +0000 | [diff] [blame] | 754 | } |
Heejin Ahn | c0f1817 | 2016-09-01 21:05:15 +0000 | [diff] [blame] | 755 | } |
| 756 | |
| 757 | if (!Changed) { |
| 758 | // Delete unused global variables and functions |
Heejin Ahn | c0f1817 | 2016-09-01 21:05:15 +0000 | [diff] [blame] | 759 | if (ResumeF) |
| 760 | ResumeF->eraseFromParent(); |
| 761 | if (EHTypeIDF) |
| 762 | EHTypeIDF->eraseFromParent(); |
| 763 | if (EmLongjmpF) |
| 764 | EmLongjmpF->eraseFromParent(); |
| 765 | if (SaveSetjmpF) |
| 766 | SaveSetjmpF->eraseFromParent(); |
| 767 | if (TestSetjmpF) |
| 768 | TestSetjmpF->eraseFromParent(); |
| 769 | return false; |
| 770 | } |
| 771 | |
Derek Schuff | f41f67d | 2016-08-01 21:34:04 +0000 | [diff] [blame] | 772 | return true; |
| 773 | } |
| 774 | |
Derek Schuff | ccdceda | 2016-08-18 15:27:25 +0000 | [diff] [blame] | 775 | bool WebAssemblyLowerEmscriptenEHSjLj::runEHOnFunction(Function &F) { |
Derek Schuff | f41f67d | 2016-08-01 21:34:04 +0000 | [diff] [blame] | 776 | Module &M = *F.getParent(); |
Derek Schuff | 53b9af0 | 2016-08-09 00:29:55 +0000 | [diff] [blame] | 777 | LLVMContext &C = F.getContext(); |
Derek Schuff | ccdceda | 2016-08-18 15:27:25 +0000 | [diff] [blame] | 778 | IRBuilder<> IRB(C); |
Derek Schuff | f41f67d | 2016-08-01 21:34:04 +0000 | [diff] [blame] | 779 | bool Changed = false; |
| 780 | SmallVector<Instruction *, 64> ToErase; |
| 781 | SmallPtrSet<LandingPadInst *, 32> LandingPads; |
Derek Schuff | 6664132 | 2016-08-09 22:37:00 +0000 | [diff] [blame] | 782 | bool AllowExceptions = |
Derek Schuff | ccdceda | 2016-08-18 15:27:25 +0000 | [diff] [blame] | 783 | areAllExceptionsAllowed() || EHWhitelistSet.count(F.getName()); |
Derek Schuff | f41f67d | 2016-08-01 21:34:04 +0000 | [diff] [blame] | 784 | |
| 785 | for (BasicBlock &BB : F) { |
| 786 | auto *II = dyn_cast<InvokeInst>(BB.getTerminator()); |
| 787 | if (!II) |
| 788 | continue; |
| 789 | Changed = true; |
| 790 | LandingPads.insert(II->getLandingPadInst()); |
Derek Schuff | ccdceda | 2016-08-18 15:27:25 +0000 | [diff] [blame] | 791 | IRB.SetInsertPoint(II); |
Derek Schuff | f41f67d | 2016-08-01 21:34:04 +0000 | [diff] [blame] | 792 | |
Derek Schuff | 53b9af0 | 2016-08-09 00:29:55 +0000 | [diff] [blame] | 793 | bool NeedInvoke = AllowExceptions && canThrow(II->getCalledValue()); |
| 794 | if (NeedInvoke) { |
Heejin Ahn | c0f1817 | 2016-09-01 21:05:15 +0000 | [diff] [blame] | 795 | // Wrap invoke with invoke wrapper and generate preamble/postamble |
| 796 | Value *Threw = wrapInvoke(II); |
Derek Schuff | f41f67d | 2016-08-01 21:34:04 +0000 | [diff] [blame] | 797 | ToErase.push_back(II); |
| 798 | |
Derek Schuff | f41f67d | 2016-08-01 21:34:04 +0000 | [diff] [blame] | 799 | // Insert a branch based on __THREW__ variable |
Heejin Ahn | c0f1817 | 2016-09-01 21:05:15 +0000 | [diff] [blame] | 800 | Value *Cmp = IRB.CreateICmpEQ(Threw, IRB.getInt32(1), "cmp"); |
| 801 | IRB.CreateCondBr(Cmp, II->getUnwindDest(), II->getNormalDest()); |
Derek Schuff | f41f67d | 2016-08-01 21:34:04 +0000 | [diff] [blame] | 802 | |
| 803 | } else { |
| 804 | // This can't throw, and we don't need this invoke, just replace it with a |
| 805 | // call+branch |
Heejin Ahn | c0f1817 | 2016-09-01 21:05:15 +0000 | [diff] [blame] | 806 | SmallVector<Value *, 16> Args(II->arg_begin(), II->arg_end()); |
James Y Knight | 7976eb5 | 2019-02-01 20:43:25 +0000 | [diff] [blame] | 807 | CallInst *NewCall = |
| 808 | IRB.CreateCall(II->getFunctionType(), II->getCalledValue(), Args); |
Derek Schuff | f41f67d | 2016-08-01 21:34:04 +0000 | [diff] [blame] | 809 | NewCall->takeName(II); |
| 810 | NewCall->setCallingConv(II->getCallingConv()); |
Derek Schuff | f41f67d | 2016-08-01 21:34:04 +0000 | [diff] [blame] | 811 | NewCall->setDebugLoc(II->getDebugLoc()); |
Derek Schuff | 53b9af0 | 2016-08-09 00:29:55 +0000 | [diff] [blame] | 812 | NewCall->setAttributes(II->getAttributes()); |
Derek Schuff | f41f67d | 2016-08-01 21:34:04 +0000 | [diff] [blame] | 813 | II->replaceAllUsesWith(NewCall); |
| 814 | ToErase.push_back(II); |
| 815 | |
Derek Schuff | ccdceda | 2016-08-18 15:27:25 +0000 | [diff] [blame] | 816 | IRB.CreateBr(II->getNormalDest()); |
Derek Schuff | f41f67d | 2016-08-01 21:34:04 +0000 | [diff] [blame] | 817 | |
| 818 | // Remove any PHI node entries from the exception destination |
| 819 | II->getUnwindDest()->removePredecessor(&BB); |
| 820 | } |
| 821 | } |
| 822 | |
| 823 | // Process resume instructions |
| 824 | for (BasicBlock &BB : F) { |
| 825 | // Scan the body of the basic block for resumes |
| 826 | for (Instruction &I : BB) { |
| 827 | auto *RI = dyn_cast<ResumeInst>(&I); |
| 828 | if (!RI) |
| 829 | continue; |
| 830 | |
| 831 | // Split the input into legal values |
| 832 | Value *Input = RI->getValue(); |
Derek Schuff | ccdceda | 2016-08-18 15:27:25 +0000 | [diff] [blame] | 833 | IRB.SetInsertPoint(RI); |
| 834 | Value *Low = IRB.CreateExtractValue(Input, 0, "low"); |
Derek Schuff | 53b9af0 | 2016-08-09 00:29:55 +0000 | [diff] [blame] | 835 | // Create a call to __resumeException function |
Heejin Ahn | c0f1817 | 2016-09-01 21:05:15 +0000 | [diff] [blame] | 836 | IRB.CreateCall(ResumeF, {Low}); |
Derek Schuff | f41f67d | 2016-08-01 21:34:04 +0000 | [diff] [blame] | 837 | // Add a terminator to the block |
Derek Schuff | ccdceda | 2016-08-18 15:27:25 +0000 | [diff] [blame] | 838 | IRB.CreateUnreachable(); |
Derek Schuff | f41f67d | 2016-08-01 21:34:04 +0000 | [diff] [blame] | 839 | ToErase.push_back(RI); |
| 840 | } |
| 841 | } |
| 842 | |
Derek Schuff | 53b9af0 | 2016-08-09 00:29:55 +0000 | [diff] [blame] | 843 | // Process llvm.eh.typeid.for intrinsics |
| 844 | for (BasicBlock &BB : F) { |
| 845 | for (Instruction &I : BB) { |
| 846 | auto *CI = dyn_cast<CallInst>(&I); |
| 847 | if (!CI) |
| 848 | continue; |
| 849 | const Function *Callee = CI->getCalledFunction(); |
| 850 | if (!Callee) |
| 851 | continue; |
| 852 | if (Callee->getIntrinsicID() != Intrinsic::eh_typeid_for) |
| 853 | continue; |
| 854 | |
Derek Schuff | ccdceda | 2016-08-18 15:27:25 +0000 | [diff] [blame] | 855 | IRB.SetInsertPoint(CI); |
Derek Schuff | 53b9af0 | 2016-08-09 00:29:55 +0000 | [diff] [blame] | 856 | CallInst *NewCI = |
Derek Schuff | ccdceda | 2016-08-18 15:27:25 +0000 | [diff] [blame] | 857 | IRB.CreateCall(EHTypeIDF, CI->getArgOperand(0), "typeid"); |
Derek Schuff | 53b9af0 | 2016-08-09 00:29:55 +0000 | [diff] [blame] | 858 | CI->replaceAllUsesWith(NewCI); |
| 859 | ToErase.push_back(CI); |
| 860 | } |
| 861 | } |
| 862 | |
Hiroshi Inoue | c396964 | 2017-06-30 07:17:53 +0000 | [diff] [blame] | 863 | // Look for orphan landingpads, can occur in blocks with no predecessors |
Derek Schuff | f41f67d | 2016-08-01 21:34:04 +0000 | [diff] [blame] | 864 | for (BasicBlock &BB : F) { |
| 865 | Instruction *I = BB.getFirstNonPHI(); |
| 866 | if (auto *LPI = dyn_cast<LandingPadInst>(I)) |
| 867 | LandingPads.insert(LPI); |
| 868 | } |
| 869 | |
| 870 | // Handle all the landingpad for this function together, as multiple invokes |
| 871 | // may share a single lp |
| 872 | for (LandingPadInst *LPI : LandingPads) { |
Derek Schuff | ccdceda | 2016-08-18 15:27:25 +0000 | [diff] [blame] | 873 | IRB.SetInsertPoint(LPI); |
Derek Schuff | f41f67d | 2016-08-01 21:34:04 +0000 | [diff] [blame] | 874 | SmallVector<Value *, 16> FMCArgs; |
Heejin Ahn | 18c56a0 | 2019-02-04 19:13:39 +0000 | [diff] [blame] | 875 | for (unsigned I = 0, E = LPI->getNumClauses(); I < E; ++I) { |
| 876 | Constant *Clause = LPI->getClause(I); |
Derek Schuff | f41f67d | 2016-08-01 21:34:04 +0000 | [diff] [blame] | 877 | // As a temporary workaround for the lack of aggregate varargs support |
| 878 | // in the interface between JS and wasm, break out filter operands into |
| 879 | // their component elements. |
Heejin Ahn | 18c56a0 | 2019-02-04 19:13:39 +0000 | [diff] [blame] | 880 | if (LPI->isFilter(I)) { |
Heejin Ahn | c0f1817 | 2016-09-01 21:05:15 +0000 | [diff] [blame] | 881 | auto *ATy = cast<ArrayType>(Clause->getType()); |
Heejin Ahn | 18c56a0 | 2019-02-04 19:13:39 +0000 | [diff] [blame] | 882 | for (unsigned J = 0, E = ATy->getNumElements(); J < E; ++J) { |
| 883 | Value *EV = IRB.CreateExtractValue(Clause, makeArrayRef(J), "filter"); |
Derek Schuff | f41f67d | 2016-08-01 21:34:04 +0000 | [diff] [blame] | 884 | FMCArgs.push_back(EV); |
| 885 | } |
| 886 | } else |
| 887 | FMCArgs.push_back(Clause); |
| 888 | } |
| 889 | |
Derek Schuff | 53b9af0 | 2016-08-09 00:29:55 +0000 | [diff] [blame] | 890 | // Create a call to __cxa_find_matching_catch_N function |
Derek Schuff | f41f67d | 2016-08-01 21:34:04 +0000 | [diff] [blame] | 891 | Function *FMCF = getFindMatchingCatch(M, FMCArgs.size()); |
Derek Schuff | ccdceda | 2016-08-18 15:27:25 +0000 | [diff] [blame] | 892 | CallInst *FMCI = IRB.CreateCall(FMCF, FMCArgs, "fmc"); |
Derek Schuff | f41f67d | 2016-08-01 21:34:04 +0000 | [diff] [blame] | 893 | Value *Undef = UndefValue::get(LPI->getType()); |
Derek Schuff | ccdceda | 2016-08-18 15:27:25 +0000 | [diff] [blame] | 894 | Value *Pair0 = IRB.CreateInsertValue(Undef, FMCI, 0, "pair0"); |
Sam Clegg | 4791a66 | 2018-11-20 19:25:07 +0000 | [diff] [blame] | 895 | Value *TempRet0 = IRB.CreateCall(GetTempRet0Func, None, "tempret0"); |
Derek Schuff | ccdceda | 2016-08-18 15:27:25 +0000 | [diff] [blame] | 896 | Value *Pair1 = IRB.CreateInsertValue(Pair0, TempRet0, 1, "pair1"); |
Derek Schuff | f41f67d | 2016-08-01 21:34:04 +0000 | [diff] [blame] | 897 | |
| 898 | LPI->replaceAllUsesWith(Pair1); |
| 899 | ToErase.push_back(LPI); |
| 900 | } |
| 901 | |
| 902 | // Erase everything we no longer need in this function |
| 903 | for (Instruction *I : ToErase) |
| 904 | I->eraseFromParent(); |
| 905 | |
| 906 | return Changed; |
| 907 | } |
Derek Schuff | ccdceda | 2016-08-18 15:27:25 +0000 | [diff] [blame] | 908 | |
| 909 | bool WebAssemblyLowerEmscriptenEHSjLj::runSjLjOnFunction(Function &F) { |
Heejin Ahn | c0f1817 | 2016-09-01 21:05:15 +0000 | [diff] [blame] | 910 | Module &M = *F.getParent(); |
| 911 | LLVMContext &C = F.getContext(); |
| 912 | IRBuilder<> IRB(C); |
| 913 | SmallVector<Instruction *, 64> ToErase; |
| 914 | // Vector of %setjmpTable values |
| 915 | std::vector<Instruction *> SetjmpTableInsts; |
| 916 | // Vector of %setjmpTableSize values |
| 917 | std::vector<Instruction *> SetjmpTableSizeInsts; |
| 918 | |
| 919 | // Setjmp preparation |
| 920 | |
| 921 | // This instruction effectively means %setjmpTableSize = 4. |
| 922 | // We create this as an instruction intentionally, and we don't want to fold |
| 923 | // this instruction to a constant 4, because this value will be used in |
| 924 | // SSAUpdater.AddAvailableValue(...) later. |
| 925 | BasicBlock &EntryBB = F.getEntryBlock(); |
| 926 | BinaryOperator *SetjmpTableSize = BinaryOperator::Create( |
| 927 | Instruction::Add, IRB.getInt32(4), IRB.getInt32(0), "setjmpTableSize", |
| 928 | &*EntryBB.getFirstInsertionPt()); |
| 929 | // setjmpTable = (int *) malloc(40); |
| 930 | Instruction *SetjmpTable = CallInst::CreateMalloc( |
| 931 | SetjmpTableSize, IRB.getInt32Ty(), IRB.getInt32Ty(), IRB.getInt32(40), |
| 932 | nullptr, nullptr, "setjmpTable"); |
| 933 | // setjmpTable[0] = 0; |
| 934 | IRB.SetInsertPoint(SetjmpTableSize); |
| 935 | IRB.CreateStore(IRB.getInt32(0), SetjmpTable); |
| 936 | SetjmpTableInsts.push_back(SetjmpTable); |
| 937 | SetjmpTableSizeInsts.push_back(SetjmpTableSize); |
| 938 | |
| 939 | // Setjmp transformation |
| 940 | std::vector<PHINode *> SetjmpRetPHIs; |
| 941 | Function *SetjmpF = M.getFunction("setjmp"); |
| 942 | for (User *U : SetjmpF->users()) { |
| 943 | auto *CI = dyn_cast<CallInst>(U); |
| 944 | if (!CI) |
| 945 | report_fatal_error("Does not support indirect calls to setjmp"); |
| 946 | |
| 947 | BasicBlock *BB = CI->getParent(); |
| 948 | if (BB->getParent() != &F) // in other function |
| 949 | continue; |
| 950 | |
| 951 | // The tail is everything right after the call, and will be reached once |
| 952 | // when setjmp is called, and later when longjmp returns to the setjmp |
| 953 | BasicBlock *Tail = SplitBlock(BB, CI->getNextNode()); |
| 954 | // Add a phi to the tail, which will be the output of setjmp, which |
| 955 | // indicates if this is the first call or a longjmp back. The phi directly |
| 956 | // uses the right value based on where we arrive from |
| 957 | IRB.SetInsertPoint(Tail->getFirstNonPHI()); |
| 958 | PHINode *SetjmpRet = IRB.CreatePHI(IRB.getInt32Ty(), 2, "setjmp.ret"); |
| 959 | |
| 960 | // setjmp initial call returns 0 |
| 961 | SetjmpRet->addIncoming(IRB.getInt32(0), BB); |
| 962 | // The proper output is now this, not the setjmp call itself |
| 963 | CI->replaceAllUsesWith(SetjmpRet); |
| 964 | // longjmp returns to the setjmp will add themselves to this phi |
| 965 | SetjmpRetPHIs.push_back(SetjmpRet); |
| 966 | |
| 967 | // Fix call target |
| 968 | // Our index in the function is our place in the array + 1 to avoid index |
| 969 | // 0, because index 0 means the longjmp is not ours to handle. |
| 970 | IRB.SetInsertPoint(CI); |
| 971 | Value *Args[] = {CI->getArgOperand(0), IRB.getInt32(SetjmpRetPHIs.size()), |
| 972 | SetjmpTable, SetjmpTableSize}; |
| 973 | Instruction *NewSetjmpTable = |
| 974 | IRB.CreateCall(SaveSetjmpF, Args, "setjmpTable"); |
| 975 | Instruction *NewSetjmpTableSize = |
Sam Clegg | 4791a66 | 2018-11-20 19:25:07 +0000 | [diff] [blame] | 976 | IRB.CreateCall(GetTempRet0Func, None, "setjmpTableSize"); |
Heejin Ahn | c0f1817 | 2016-09-01 21:05:15 +0000 | [diff] [blame] | 977 | SetjmpTableInsts.push_back(NewSetjmpTable); |
| 978 | SetjmpTableSizeInsts.push_back(NewSetjmpTableSize); |
| 979 | ToErase.push_back(CI); |
| 980 | } |
| 981 | |
| 982 | // Update each call that can longjmp so it can return to a setjmp where |
| 983 | // relevant. |
| 984 | |
| 985 | // Because we are creating new BBs while processing and don't want to make |
| 986 | // all these newly created BBs candidates again for longjmp processing, we |
| 987 | // first make the vector of candidate BBs. |
| 988 | std::vector<BasicBlock *> BBs; |
| 989 | for (BasicBlock &BB : F) |
| 990 | BBs.push_back(&BB); |
| 991 | |
| 992 | // BBs.size() will change within the loop, so we query it every time |
Heejin Ahn | 18c56a0 | 2019-02-04 19:13:39 +0000 | [diff] [blame] | 993 | for (unsigned I = 0; I < BBs.size(); I++) { |
| 994 | BasicBlock *BB = BBs[I]; |
Heejin Ahn | c0f1817 | 2016-09-01 21:05:15 +0000 | [diff] [blame] | 995 | for (Instruction &I : *BB) { |
| 996 | assert(!isa<InvokeInst>(&I)); |
| 997 | auto *CI = dyn_cast<CallInst>(&I); |
| 998 | if (!CI) |
| 999 | continue; |
| 1000 | |
| 1001 | const Value *Callee = CI->getCalledValue(); |
| 1002 | if (!canLongjmp(M, Callee)) |
| 1003 | continue; |
Guanzhong Chen | b1cb9fd | 2019-08-16 18:21:08 +0000 | [diff] [blame^] | 1004 | if (isEmAsmCall(M, Callee)) |
| 1005 | report_fatal_error("Cannot use EM_ASM* alongside setjmp/longjmp in " + |
| 1006 | F.getName() + |
| 1007 | ". Please consider using EM_JS, or move the " |
| 1008 | "EM_ASM into another function.", |
| 1009 | false); |
Heejin Ahn | c0f1817 | 2016-09-01 21:05:15 +0000 | [diff] [blame] | 1010 | |
| 1011 | Value *Threw = nullptr; |
| 1012 | BasicBlock *Tail; |
| 1013 | if (Callee->getName().startswith(InvokePrefix)) { |
| 1014 | // If invoke wrapper has already been generated for this call in |
| 1015 | // previous EH phase, search for the load instruction |
| 1016 | // %__THREW__.val = __THREW__; |
| 1017 | // in postamble after the invoke wrapper call |
| 1018 | LoadInst *ThrewLI = nullptr; |
| 1019 | StoreInst *ThrewResetSI = nullptr; |
| 1020 | for (auto I = std::next(BasicBlock::iterator(CI)), IE = BB->end(); |
| 1021 | I != IE; ++I) { |
| 1022 | if (auto *LI = dyn_cast<LoadInst>(I)) |
| 1023 | if (auto *GV = dyn_cast<GlobalVariable>(LI->getPointerOperand())) |
| 1024 | if (GV == ThrewGV) { |
| 1025 | Threw = ThrewLI = LI; |
| 1026 | break; |
| 1027 | } |
| 1028 | } |
| 1029 | // Search for the store instruction after the load above |
| 1030 | // __THREW__ = 0; |
| 1031 | for (auto I = std::next(BasicBlock::iterator(ThrewLI)), IE = BB->end(); |
| 1032 | I != IE; ++I) { |
| 1033 | if (auto *SI = dyn_cast<StoreInst>(I)) |
| 1034 | if (auto *GV = dyn_cast<GlobalVariable>(SI->getPointerOperand())) |
| 1035 | if (GV == ThrewGV && SI->getValueOperand() == IRB.getInt32(0)) { |
| 1036 | ThrewResetSI = SI; |
| 1037 | break; |
| 1038 | } |
| 1039 | } |
| 1040 | assert(Threw && ThrewLI && "Cannot find __THREW__ load after invoke"); |
| 1041 | assert(ThrewResetSI && "Cannot find __THREW__ store after invoke"); |
| 1042 | Tail = SplitBlock(BB, ThrewResetSI->getNextNode()); |
| 1043 | |
| 1044 | } else { |
| 1045 | // Wrap call with invoke wrapper and generate preamble/postamble |
| 1046 | Threw = wrapInvoke(CI); |
| 1047 | ToErase.push_back(CI); |
| 1048 | Tail = SplitBlock(BB, CI->getNextNode()); |
| 1049 | } |
| 1050 | |
| 1051 | // We need to replace the terminator in Tail - SplitBlock makes BB go |
| 1052 | // straight to Tail, we need to check if a longjmp occurred, and go to the |
| 1053 | // right setjmp-tail if so |
| 1054 | ToErase.push_back(BB->getTerminator()); |
| 1055 | |
| 1056 | // Generate a function call to testSetjmp function and preamble/postamble |
| 1057 | // code to figure out (1) whether longjmp occurred (2) if longjmp |
| 1058 | // occurred, which setjmp it corresponds to |
| 1059 | Value *Label = nullptr; |
| 1060 | Value *LongjmpResult = nullptr; |
| 1061 | BasicBlock *EndBB = nullptr; |
| 1062 | wrapTestSetjmp(BB, CI, Threw, SetjmpTable, SetjmpTableSize, Label, |
| 1063 | LongjmpResult, EndBB); |
| 1064 | assert(Label && LongjmpResult && EndBB); |
| 1065 | |
| 1066 | // Create switch instruction |
| 1067 | IRB.SetInsertPoint(EndBB); |
| 1068 | SwitchInst *SI = IRB.CreateSwitch(Label, Tail, SetjmpRetPHIs.size()); |
| 1069 | // -1 means no longjmp happened, continue normally (will hit the default |
| 1070 | // switch case). 0 means a longjmp that is not ours to handle, needs a |
| 1071 | // rethrow. Otherwise the index is the same as the index in P+1 (to avoid |
| 1072 | // 0). |
Heejin Ahn | 18c56a0 | 2019-02-04 19:13:39 +0000 | [diff] [blame] | 1073 | for (unsigned I = 0; I < SetjmpRetPHIs.size(); I++) { |
| 1074 | SI->addCase(IRB.getInt32(I + 1), SetjmpRetPHIs[I]->getParent()); |
| 1075 | SetjmpRetPHIs[I]->addIncoming(LongjmpResult, EndBB); |
Heejin Ahn | c0f1817 | 2016-09-01 21:05:15 +0000 | [diff] [blame] | 1076 | } |
| 1077 | |
| 1078 | // We are splitting the block here, and must continue to find other calls |
| 1079 | // in the block - which is now split. so continue to traverse in the Tail |
| 1080 | BBs.push_back(Tail); |
| 1081 | } |
| 1082 | } |
| 1083 | |
| 1084 | // Erase everything we no longer need in this function |
| 1085 | for (Instruction *I : ToErase) |
| 1086 | I->eraseFromParent(); |
| 1087 | |
| 1088 | // Free setjmpTable buffer before each return instruction |
| 1089 | for (BasicBlock &BB : F) { |
Chandler Carruth | edb12a8 | 2018-10-15 10:04:59 +0000 | [diff] [blame] | 1090 | Instruction *TI = BB.getTerminator(); |
Heejin Ahn | c0f1817 | 2016-09-01 21:05:15 +0000 | [diff] [blame] | 1091 | if (isa<ReturnInst>(TI)) |
| 1092 | CallInst::CreateFree(SetjmpTable, TI); |
| 1093 | } |
| 1094 | |
| 1095 | // Every call to saveSetjmp can change setjmpTable and setjmpTableSize |
| 1096 | // (when buffer reallocation occurs) |
| 1097 | // entry: |
| 1098 | // setjmpTableSize = 4; |
| 1099 | // setjmpTable = (int *) malloc(40); |
| 1100 | // setjmpTable[0] = 0; |
| 1101 | // ... |
| 1102 | // somebb: |
| 1103 | // setjmpTable = saveSetjmp(buf, label, setjmpTable, setjmpTableSize); |
Sam Clegg | 4791a66 | 2018-11-20 19:25:07 +0000 | [diff] [blame] | 1104 | // setjmpTableSize = getTempRet0(); |
Heejin Ahn | c0f1817 | 2016-09-01 21:05:15 +0000 | [diff] [blame] | 1105 | // So we need to make sure the SSA for these variables is valid so that every |
| 1106 | // saveSetjmp and testSetjmp calls have the correct arguments. |
| 1107 | SSAUpdater SetjmpTableSSA; |
| 1108 | SSAUpdater SetjmpTableSizeSSA; |
| 1109 | SetjmpTableSSA.Initialize(Type::getInt32PtrTy(C), "setjmpTable"); |
| 1110 | SetjmpTableSizeSSA.Initialize(Type::getInt32Ty(C), "setjmpTableSize"); |
| 1111 | for (Instruction *I : SetjmpTableInsts) |
| 1112 | SetjmpTableSSA.AddAvailableValue(I->getParent(), I); |
| 1113 | for (Instruction *I : SetjmpTableSizeInsts) |
| 1114 | SetjmpTableSizeSSA.AddAvailableValue(I->getParent(), I); |
| 1115 | |
| 1116 | for (auto UI = SetjmpTable->use_begin(), UE = SetjmpTable->use_end(); |
| 1117 | UI != UE;) { |
| 1118 | // Grab the use before incrementing the iterator. |
| 1119 | Use &U = *UI; |
| 1120 | // Increment the iterator before removing the use from the list. |
| 1121 | ++UI; |
Heejin Ahn | 18c56a0 | 2019-02-04 19:13:39 +0000 | [diff] [blame] | 1122 | if (auto *I = dyn_cast<Instruction>(U.getUser())) |
Heejin Ahn | c0f1817 | 2016-09-01 21:05:15 +0000 | [diff] [blame] | 1123 | if (I->getParent() != &EntryBB) |
| 1124 | SetjmpTableSSA.RewriteUse(U); |
| 1125 | } |
| 1126 | for (auto UI = SetjmpTableSize->use_begin(), UE = SetjmpTableSize->use_end(); |
| 1127 | UI != UE;) { |
| 1128 | Use &U = *UI; |
| 1129 | ++UI; |
Heejin Ahn | 18c56a0 | 2019-02-04 19:13:39 +0000 | [diff] [blame] | 1130 | if (auto *I = dyn_cast<Instruction>(U.getUser())) |
Heejin Ahn | c0f1817 | 2016-09-01 21:05:15 +0000 | [diff] [blame] | 1131 | if (I->getParent() != &EntryBB) |
| 1132 | SetjmpTableSizeSSA.RewriteUse(U); |
| 1133 | } |
| 1134 | |
| 1135 | // Finally, our modifications to the cfg can break dominance of SSA variables. |
| 1136 | // For example, in this code, |
| 1137 | // if (x()) { .. setjmp() .. } |
| 1138 | // if (y()) { .. longjmp() .. } |
| 1139 | // We must split the longjmp block, and it can jump into the block splitted |
| 1140 | // from setjmp one. But that means that when we split the setjmp block, it's |
| 1141 | // first part no longer dominates its second part - there is a theoretically |
| 1142 | // possible control flow path where x() is false, then y() is true and we |
| 1143 | // reach the second part of the setjmp block, without ever reaching the first |
| 1144 | // part. So, we rebuild SSA form here. |
| 1145 | rebuildSSA(F); |
| 1146 | return true; |
Derek Schuff | ccdceda | 2016-08-18 15:27:25 +0000 | [diff] [blame] | 1147 | } |