xref: /llvm-project/llvm/lib/Target/WebAssembly/WebAssemblyISelLowering.cpp (revision f8f0a266e0c26cd940ccba9542aec4b5efed9821)
1 //=- WebAssemblyISelLowering.cpp - WebAssembly DAG Lowering Implementation -==//
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 implements the WebAssemblyTargetLowering class.
11 ///
12 //===----------------------------------------------------------------------===//
13 
14 #include "WebAssemblyISelLowering.h"
15 #include "MCTargetDesc/WebAssemblyMCTargetDesc.h"
16 #include "Utils/WebAssemblyTypeUtilities.h"
17 #include "WebAssemblyMachineFunctionInfo.h"
18 #include "WebAssemblySubtarget.h"
19 #include "WebAssemblyTargetMachine.h"
20 #include "WebAssemblyUtilities.h"
21 #include "llvm/CodeGen/CallingConvLower.h"
22 #include "llvm/CodeGen/MachineFrameInfo.h"
23 #include "llvm/CodeGen/MachineFunctionPass.h"
24 #include "llvm/CodeGen/MachineInstrBuilder.h"
25 #include "llvm/CodeGen/MachineJumpTableInfo.h"
26 #include "llvm/CodeGen/MachineModuleInfo.h"
27 #include "llvm/CodeGen/MachineRegisterInfo.h"
28 #include "llvm/CodeGen/SelectionDAG.h"
29 #include "llvm/CodeGen/SelectionDAGNodes.h"
30 #include "llvm/IR/DiagnosticInfo.h"
31 #include "llvm/IR/DiagnosticPrinter.h"
32 #include "llvm/IR/Function.h"
33 #include "llvm/IR/Intrinsics.h"
34 #include "llvm/IR/IntrinsicsWebAssembly.h"
35 #include "llvm/IR/PatternMatch.h"
36 #include "llvm/Support/Debug.h"
37 #include "llvm/Support/ErrorHandling.h"
38 #include "llvm/Support/KnownBits.h"
39 #include "llvm/Support/MathExtras.h"
40 #include "llvm/Support/raw_ostream.h"
41 #include "llvm/Target/TargetOptions.h"
42 using namespace llvm;
43 
44 #define DEBUG_TYPE "wasm-lower"
45 
46 WebAssemblyTargetLowering::WebAssemblyTargetLowering(
47     const TargetMachine &TM, const WebAssemblySubtarget &STI)
48     : TargetLowering(TM), Subtarget(&STI) {
49   auto MVTPtr = Subtarget->hasAddr64() ? MVT::i64 : MVT::i32;
50 
51   // Booleans always contain 0 or 1.
52   setBooleanContents(ZeroOrOneBooleanContent);
53   // Except in SIMD vectors
54   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
55   // We don't know the microarchitecture here, so just reduce register pressure.
56   setSchedulingPreference(Sched::RegPressure);
57   // Tell ISel that we have a stack pointer.
58   setStackPointerRegisterToSaveRestore(
59       Subtarget->hasAddr64() ? WebAssembly::SP64 : WebAssembly::SP32);
60   // Set up the register classes.
61   addRegisterClass(MVT::i32, &WebAssembly::I32RegClass);
62   addRegisterClass(MVT::i64, &WebAssembly::I64RegClass);
63   addRegisterClass(MVT::f32, &WebAssembly::F32RegClass);
64   addRegisterClass(MVT::f64, &WebAssembly::F64RegClass);
65   if (Subtarget->hasSIMD128()) {
66     addRegisterClass(MVT::v16i8, &WebAssembly::V128RegClass);
67     addRegisterClass(MVT::v8i16, &WebAssembly::V128RegClass);
68     addRegisterClass(MVT::v4i32, &WebAssembly::V128RegClass);
69     addRegisterClass(MVT::v4f32, &WebAssembly::V128RegClass);
70     addRegisterClass(MVT::v2i64, &WebAssembly::V128RegClass);
71     addRegisterClass(MVT::v2f64, &WebAssembly::V128RegClass);
72   }
73   if (Subtarget->hasFP16()) {
74     addRegisterClass(MVT::v8f16, &WebAssembly::V128RegClass);
75   }
76   if (Subtarget->hasReferenceTypes()) {
77     addRegisterClass(MVT::externref, &WebAssembly::EXTERNREFRegClass);
78     addRegisterClass(MVT::funcref, &WebAssembly::FUNCREFRegClass);
79     if (Subtarget->hasExceptionHandling()) {
80       addRegisterClass(MVT::exnref, &WebAssembly::EXNREFRegClass);
81     }
82   }
83   // Compute derived properties from the register classes.
84   computeRegisterProperties(Subtarget->getRegisterInfo());
85 
86   // Transform loads and stores to pointers in address space 1 to loads and
87   // stores to WebAssembly global variables, outside linear memory.
88   for (auto T : {MVT::i32, MVT::i64, MVT::f32, MVT::f64}) {
89     setOperationAction(ISD::LOAD, T, Custom);
90     setOperationAction(ISD::STORE, T, Custom);
91   }
92   if (Subtarget->hasSIMD128()) {
93     for (auto T : {MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v4f32, MVT::v2i64,
94                    MVT::v2f64}) {
95       setOperationAction(ISD::LOAD, T, Custom);
96       setOperationAction(ISD::STORE, T, Custom);
97     }
98   }
99   if (Subtarget->hasFP16()) {
100     setOperationAction(ISD::LOAD, MVT::v8f16, Custom);
101     setOperationAction(ISD::STORE, MVT::v8f16, Custom);
102   }
103   if (Subtarget->hasReferenceTypes()) {
104     // We need custom load and store lowering for both externref, funcref and
105     // Other. The MVT::Other here represents tables of reference types.
106     for (auto T : {MVT::externref, MVT::funcref, MVT::Other}) {
107       setOperationAction(ISD::LOAD, T, Custom);
108       setOperationAction(ISD::STORE, T, Custom);
109     }
110   }
111 
112   setOperationAction(ISD::GlobalAddress, MVTPtr, Custom);
113   setOperationAction(ISD::GlobalTLSAddress, MVTPtr, Custom);
114   setOperationAction(ISD::ExternalSymbol, MVTPtr, Custom);
115   setOperationAction(ISD::JumpTable, MVTPtr, Custom);
116   setOperationAction(ISD::BlockAddress, MVTPtr, Custom);
117   setOperationAction(ISD::BRIND, MVT::Other, Custom);
118   setOperationAction(ISD::CLEAR_CACHE, MVT::Other, Custom);
119 
120   // Take the default expansion for va_arg, va_copy, and va_end. There is no
121   // default action for va_start, so we do that custom.
122   setOperationAction(ISD::VASTART, MVT::Other, Custom);
123   setOperationAction(ISD::VAARG, MVT::Other, Expand);
124   setOperationAction(ISD::VACOPY, MVT::Other, Expand);
125   setOperationAction(ISD::VAEND, MVT::Other, Expand);
126 
127   for (auto T : {MVT::f32, MVT::f64, MVT::v4f32, MVT::v2f64}) {
128     // Don't expand the floating-point types to constant pools.
129     setOperationAction(ISD::ConstantFP, T, Legal);
130     // Expand floating-point comparisons.
131     for (auto CC : {ISD::SETO, ISD::SETUO, ISD::SETUEQ, ISD::SETONE,
132                     ISD::SETULT, ISD::SETULE, ISD::SETUGT, ISD::SETUGE})
133       setCondCodeAction(CC, T, Expand);
134     // Expand floating-point library function operators.
135     for (auto Op :
136          {ISD::FSIN, ISD::FCOS, ISD::FSINCOS, ISD::FPOW, ISD::FREM, ISD::FMA})
137       setOperationAction(Op, T, Expand);
138     // Note supported floating-point library function operators that otherwise
139     // default to expand.
140     for (auto Op : {ISD::FCEIL, ISD::FFLOOR, ISD::FTRUNC, ISD::FNEARBYINT,
141                     ISD::FRINT, ISD::FROUNDEVEN})
142       setOperationAction(Op, T, Legal);
143     // Support minimum and maximum, which otherwise default to expand.
144     setOperationAction(ISD::FMINIMUM, T, Legal);
145     setOperationAction(ISD::FMAXIMUM, T, Legal);
146     // WebAssembly currently has no builtin f16 support.
147     setOperationAction(ISD::FP16_TO_FP, T, Expand);
148     setOperationAction(ISD::FP_TO_FP16, T, Expand);
149     setLoadExtAction(ISD::EXTLOAD, T, MVT::f16, Expand);
150     setTruncStoreAction(T, MVT::f16, Expand);
151   }
152 
153   if (Subtarget->hasFP16()) {
154     setOperationAction(ISD::FMINIMUM, MVT::v8f16, Legal);
155     setOperationAction(ISD::FMAXIMUM, MVT::v8f16, Legal);
156   }
157 
158   // Expand unavailable integer operations.
159   for (auto Op :
160        {ISD::BSWAP, ISD::SMUL_LOHI, ISD::UMUL_LOHI, ISD::MULHS, ISD::MULHU,
161         ISD::SDIVREM, ISD::UDIVREM, ISD::SHL_PARTS, ISD::SRA_PARTS,
162         ISD::SRL_PARTS, ISD::ADDC, ISD::ADDE, ISD::SUBC, ISD::SUBE}) {
163     for (auto T : {MVT::i32, MVT::i64})
164       setOperationAction(Op, T, Expand);
165     if (Subtarget->hasSIMD128())
166       for (auto T : {MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64})
167         setOperationAction(Op, T, Expand);
168   }
169 
170   if (Subtarget->hasNontrappingFPToInt())
171     for (auto Op : {ISD::FP_TO_SINT_SAT, ISD::FP_TO_UINT_SAT})
172       for (auto T : {MVT::i32, MVT::i64})
173         setOperationAction(Op, T, Custom);
174 
175   // SIMD-specific configuration
176   if (Subtarget->hasSIMD128()) {
177     // Combine vector mask reductions into alltrue/anytrue
178     setTargetDAGCombine(ISD::SETCC);
179 
180     // Convert vector to integer bitcasts to bitmask
181     setTargetDAGCombine(ISD::BITCAST);
182 
183     // Hoist bitcasts out of shuffles
184     setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
185 
186     // Combine extends of extract_subvectors into widening ops
187     setTargetDAGCombine({ISD::SIGN_EXTEND, ISD::ZERO_EXTEND});
188 
189     // Combine int_to_fp or fp_extend of extract_vectors and vice versa into
190     // conversions ops
191     setTargetDAGCombine({ISD::SINT_TO_FP, ISD::UINT_TO_FP, ISD::FP_EXTEND,
192                          ISD::EXTRACT_SUBVECTOR});
193 
194     // Combine fp_to_{s,u}int_sat or fp_round of concat_vectors or vice versa
195     // into conversion ops
196     setTargetDAGCombine({ISD::FP_TO_SINT_SAT, ISD::FP_TO_UINT_SAT,
197                          ISD::FP_ROUND, ISD::CONCAT_VECTORS});
198 
199     setTargetDAGCombine(ISD::TRUNCATE);
200 
201     // Support saturating add/sub for i8x16 and i16x8
202     for (auto Op : {ISD::SADDSAT, ISD::UADDSAT, ISD::SSUBSAT, ISD::USUBSAT})
203       for (auto T : {MVT::v16i8, MVT::v8i16})
204         setOperationAction(Op, T, Legal);
205 
206     // Support integer abs
207     for (auto T : {MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64})
208       setOperationAction(ISD::ABS, T, Legal);
209 
210     // Custom lower BUILD_VECTORs to minimize number of replace_lanes
211     for (auto T : {MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v4f32, MVT::v2i64,
212                    MVT::v2f64})
213       setOperationAction(ISD::BUILD_VECTOR, T, Custom);
214 
215     if (Subtarget->hasFP16())
216       setOperationAction(ISD::BUILD_VECTOR, MVT::f16, Custom);
217 
218     // We have custom shuffle lowering to expose the shuffle mask
219     for (auto T : {MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v4f32, MVT::v2i64,
220                    MVT::v2f64})
221       setOperationAction(ISD::VECTOR_SHUFFLE, T, Custom);
222 
223     // Support splatting
224     for (auto T : {MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v4f32, MVT::v2i64,
225                    MVT::v2f64})
226       setOperationAction(ISD::SPLAT_VECTOR, T, Legal);
227 
228     // Custom lowering since wasm shifts must have a scalar shift amount
229     for (auto Op : {ISD::SHL, ISD::SRA, ISD::SRL})
230       for (auto T : {MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64})
231         setOperationAction(Op, T, Custom);
232 
233     // Custom lower lane accesses to expand out variable indices
234     for (auto Op : {ISD::EXTRACT_VECTOR_ELT, ISD::INSERT_VECTOR_ELT})
235       for (auto T : {MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v4f32, MVT::v2i64,
236                      MVT::v2f64})
237         setOperationAction(Op, T, Custom);
238 
239     // There is no i8x16.mul instruction
240     setOperationAction(ISD::MUL, MVT::v16i8, Expand);
241 
242     // There is no vector conditional select instruction
243     for (auto T : {MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v4f32, MVT::v2i64,
244                    MVT::v2f64})
245       setOperationAction(ISD::SELECT_CC, T, Expand);
246 
247     // Expand integer operations supported for scalars but not SIMD
248     for (auto Op :
249          {ISD::SDIV, ISD::UDIV, ISD::SREM, ISD::UREM, ISD::ROTL, ISD::ROTR})
250       for (auto T : {MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64})
251         setOperationAction(Op, T, Expand);
252 
253     // But we do have integer min and max operations
254     for (auto Op : {ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX})
255       for (auto T : {MVT::v16i8, MVT::v8i16, MVT::v4i32})
256         setOperationAction(Op, T, Legal);
257 
258     // And we have popcnt for i8x16. It can be used to expand ctlz/cttz.
259     setOperationAction(ISD::CTPOP, MVT::v16i8, Legal);
260     setOperationAction(ISD::CTLZ, MVT::v16i8, Expand);
261     setOperationAction(ISD::CTTZ, MVT::v16i8, Expand);
262 
263     // Custom lower bit counting operations for other types to scalarize them.
264     for (auto Op : {ISD::CTLZ, ISD::CTTZ, ISD::CTPOP})
265       for (auto T : {MVT::v8i16, MVT::v4i32, MVT::v2i64})
266         setOperationAction(Op, T, Custom);
267 
268     // Expand float operations supported for scalars but not SIMD
269     for (auto Op : {ISD::FCOPYSIGN, ISD::FLOG, ISD::FLOG2, ISD::FLOG10,
270                     ISD::FEXP, ISD::FEXP2})
271       for (auto T : {MVT::v4f32, MVT::v2f64})
272         setOperationAction(Op, T, Expand);
273 
274     // Unsigned comparison operations are unavailable for i64x2 vectors.
275     for (auto CC : {ISD::SETUGT, ISD::SETUGE, ISD::SETULT, ISD::SETULE})
276       setCondCodeAction(CC, MVT::v2i64, Custom);
277 
278     // 64x2 conversions are not in the spec
279     for (auto Op :
280          {ISD::SINT_TO_FP, ISD::UINT_TO_FP, ISD::FP_TO_SINT, ISD::FP_TO_UINT})
281       for (auto T : {MVT::v2i64, MVT::v2f64})
282         setOperationAction(Op, T, Expand);
283 
284     // But saturating fp_to_int converstions are
285     for (auto Op : {ISD::FP_TO_SINT_SAT, ISD::FP_TO_UINT_SAT}) {
286       setOperationAction(Op, MVT::v4i32, Custom);
287       if (Subtarget->hasFP16()) {
288         setOperationAction(Op, MVT::v8i16, Custom);
289       }
290     }
291 
292     // Support vector extending
293     for (auto T : MVT::integer_fixedlen_vector_valuetypes()) {
294       setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, T, Custom);
295       setOperationAction(ISD::ZERO_EXTEND_VECTOR_INREG, T, Custom);
296     }
297   }
298 
299   // As a special case, these operators use the type to mean the type to
300   // sign-extend from.
301   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
302   if (!Subtarget->hasSignExt()) {
303     // Sign extends are legal only when extending a vector extract
304     auto Action = Subtarget->hasSIMD128() ? Custom : Expand;
305     for (auto T : {MVT::i8, MVT::i16, MVT::i32})
306       setOperationAction(ISD::SIGN_EXTEND_INREG, T, Action);
307   }
308   for (auto T : MVT::integer_fixedlen_vector_valuetypes())
309     setOperationAction(ISD::SIGN_EXTEND_INREG, T, Expand);
310 
311   // Dynamic stack allocation: use the default expansion.
312   setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
313   setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
314   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVTPtr, Expand);
315 
316   setOperationAction(ISD::FrameIndex, MVT::i32, Custom);
317   setOperationAction(ISD::FrameIndex, MVT::i64, Custom);
318   setOperationAction(ISD::CopyToReg, MVT::Other, Custom);
319 
320   // Expand these forms; we pattern-match the forms that we can handle in isel.
321   for (auto T : {MVT::i32, MVT::i64, MVT::f32, MVT::f64})
322     for (auto Op : {ISD::BR_CC, ISD::SELECT_CC})
323       setOperationAction(Op, T, Expand);
324 
325   // We have custom switch handling.
326   setOperationAction(ISD::BR_JT, MVT::Other, Custom);
327 
328   // WebAssembly doesn't have:
329   //  - Floating-point extending loads.
330   //  - Floating-point truncating stores.
331   //  - i1 extending loads.
332   //  - truncating SIMD stores and most extending loads
333   setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f32, Expand);
334   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
335   for (auto T : MVT::integer_valuetypes())
336     for (auto Ext : {ISD::EXTLOAD, ISD::ZEXTLOAD, ISD::SEXTLOAD})
337       setLoadExtAction(Ext, T, MVT::i1, Promote);
338   if (Subtarget->hasSIMD128()) {
339     for (auto T : {MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64, MVT::v4f32,
340                    MVT::v2f64}) {
341       for (auto MemT : MVT::fixedlen_vector_valuetypes()) {
342         if (MVT(T) != MemT) {
343           setTruncStoreAction(T, MemT, Expand);
344           for (auto Ext : {ISD::EXTLOAD, ISD::ZEXTLOAD, ISD::SEXTLOAD})
345             setLoadExtAction(Ext, T, MemT, Expand);
346         }
347       }
348     }
349     // But some vector extending loads are legal
350     for (auto Ext : {ISD::EXTLOAD, ISD::SEXTLOAD, ISD::ZEXTLOAD}) {
351       setLoadExtAction(Ext, MVT::v8i16, MVT::v8i8, Legal);
352       setLoadExtAction(Ext, MVT::v4i32, MVT::v4i16, Legal);
353       setLoadExtAction(Ext, MVT::v2i64, MVT::v2i32, Legal);
354     }
355     setLoadExtAction(ISD::EXTLOAD, MVT::v2f64, MVT::v2f32, Legal);
356   }
357 
358   // Don't do anything clever with build_pairs
359   setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand);
360 
361   // Trap lowers to wasm unreachable
362   setOperationAction(ISD::TRAP, MVT::Other, Legal);
363   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
364 
365   // Exception handling intrinsics
366   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
367   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
368   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
369 
370   setMaxAtomicSizeInBitsSupported(64);
371 
372   // Override the __gnu_f2h_ieee/__gnu_h2f_ieee names so that the f32 name is
373   // consistent with the f64 and f128 names.
374   setLibcallName(RTLIB::FPEXT_F16_F32, "__extendhfsf2");
375   setLibcallName(RTLIB::FPROUND_F32_F16, "__truncsfhf2");
376 
377   // Define the emscripten name for return address helper.
378   // TODO: when implementing other Wasm backends, make this generic or only do
379   // this on emscripten depending on what they end up doing.
380   setLibcallName(RTLIB::RETURN_ADDRESS, "emscripten_return_address");
381 
382   // Always convert switches to br_tables unless there is only one case, which
383   // is equivalent to a simple branch. This reduces code size for wasm, and we
384   // defer possible jump table optimizations to the VM.
385   setMinimumJumpTableEntries(2);
386 }
387 
388 MVT WebAssemblyTargetLowering::getPointerTy(const DataLayout &DL,
389                                             uint32_t AS) const {
390   if (AS == WebAssembly::WasmAddressSpace::WASM_ADDRESS_SPACE_EXTERNREF)
391     return MVT::externref;
392   if (AS == WebAssembly::WasmAddressSpace::WASM_ADDRESS_SPACE_FUNCREF)
393     return MVT::funcref;
394   return TargetLowering::getPointerTy(DL, AS);
395 }
396 
397 MVT WebAssemblyTargetLowering::getPointerMemTy(const DataLayout &DL,
398                                                uint32_t AS) const {
399   if (AS == WebAssembly::WasmAddressSpace::WASM_ADDRESS_SPACE_EXTERNREF)
400     return MVT::externref;
401   if (AS == WebAssembly::WasmAddressSpace::WASM_ADDRESS_SPACE_FUNCREF)
402     return MVT::funcref;
403   return TargetLowering::getPointerMemTy(DL, AS);
404 }
405 
406 TargetLowering::AtomicExpansionKind
407 WebAssemblyTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
408   // We have wasm instructions for these
409   switch (AI->getOperation()) {
410   case AtomicRMWInst::Add:
411   case AtomicRMWInst::Sub:
412   case AtomicRMWInst::And:
413   case AtomicRMWInst::Or:
414   case AtomicRMWInst::Xor:
415   case AtomicRMWInst::Xchg:
416     return AtomicExpansionKind::None;
417   default:
418     break;
419   }
420   return AtomicExpansionKind::CmpXChg;
421 }
422 
423 bool WebAssemblyTargetLowering::shouldScalarizeBinop(SDValue VecOp) const {
424   // Implementation copied from X86TargetLowering.
425   unsigned Opc = VecOp.getOpcode();
426 
427   // Assume target opcodes can't be scalarized.
428   // TODO - do we have any exceptions?
429   if (Opc >= ISD::BUILTIN_OP_END)
430     return false;
431 
432   // If the vector op is not supported, try to convert to scalar.
433   EVT VecVT = VecOp.getValueType();
434   if (!isOperationLegalOrCustomOrPromote(Opc, VecVT))
435     return true;
436 
437   // If the vector op is supported, but the scalar op is not, the transform may
438   // not be worthwhile.
439   EVT ScalarVT = VecVT.getScalarType();
440   return isOperationLegalOrCustomOrPromote(Opc, ScalarVT);
441 }
442 
443 FastISel *WebAssemblyTargetLowering::createFastISel(
444     FunctionLoweringInfo &FuncInfo, const TargetLibraryInfo *LibInfo) const {
445   return WebAssembly::createFastISel(FuncInfo, LibInfo);
446 }
447 
448 MVT WebAssemblyTargetLowering::getScalarShiftAmountTy(const DataLayout & /*DL*/,
449                                                       EVT VT) const {
450   unsigned BitWidth = NextPowerOf2(VT.getSizeInBits() - 1);
451   if (BitWidth > 1 && BitWidth < 8)
452     BitWidth = 8;
453 
454   if (BitWidth > 64) {
455     // The shift will be lowered to a libcall, and compiler-rt libcalls expect
456     // the count to be an i32.
457     BitWidth = 32;
458     assert(BitWidth >= Log2_32_Ceil(VT.getSizeInBits()) &&
459            "32-bit shift counts ought to be enough for anyone");
460   }
461 
462   MVT Result = MVT::getIntegerVT(BitWidth);
463   assert(Result != MVT::INVALID_SIMPLE_VALUE_TYPE &&
464          "Unable to represent scalar shift amount type");
465   return Result;
466 }
467 
468 // Lower an fp-to-int conversion operator from the LLVM opcode, which has an
469 // undefined result on invalid/overflow, to the WebAssembly opcode, which
470 // traps on invalid/overflow.
471 static MachineBasicBlock *LowerFPToInt(MachineInstr &MI, DebugLoc DL,
472                                        MachineBasicBlock *BB,
473                                        const TargetInstrInfo &TII,
474                                        bool IsUnsigned, bool Int64,
475                                        bool Float64, unsigned LoweredOpcode) {
476   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
477 
478   Register OutReg = MI.getOperand(0).getReg();
479   Register InReg = MI.getOperand(1).getReg();
480 
481   unsigned Abs = Float64 ? WebAssembly::ABS_F64 : WebAssembly::ABS_F32;
482   unsigned FConst = Float64 ? WebAssembly::CONST_F64 : WebAssembly::CONST_F32;
483   unsigned LT = Float64 ? WebAssembly::LT_F64 : WebAssembly::LT_F32;
484   unsigned GE = Float64 ? WebAssembly::GE_F64 : WebAssembly::GE_F32;
485   unsigned IConst = Int64 ? WebAssembly::CONST_I64 : WebAssembly::CONST_I32;
486   unsigned Eqz = WebAssembly::EQZ_I32;
487   unsigned And = WebAssembly::AND_I32;
488   int64_t Limit = Int64 ? INT64_MIN : INT32_MIN;
489   int64_t Substitute = IsUnsigned ? 0 : Limit;
490   double CmpVal = IsUnsigned ? -(double)Limit * 2.0 : -(double)Limit;
491   auto &Context = BB->getParent()->getFunction().getContext();
492   Type *Ty = Float64 ? Type::getDoubleTy(Context) : Type::getFloatTy(Context);
493 
494   const BasicBlock *LLVMBB = BB->getBasicBlock();
495   MachineFunction *F = BB->getParent();
496   MachineBasicBlock *TrueMBB = F->CreateMachineBasicBlock(LLVMBB);
497   MachineBasicBlock *FalseMBB = F->CreateMachineBasicBlock(LLVMBB);
498   MachineBasicBlock *DoneMBB = F->CreateMachineBasicBlock(LLVMBB);
499 
500   MachineFunction::iterator It = ++BB->getIterator();
501   F->insert(It, FalseMBB);
502   F->insert(It, TrueMBB);
503   F->insert(It, DoneMBB);
504 
505   // Transfer the remainder of BB and its successor edges to DoneMBB.
506   DoneMBB->splice(DoneMBB->begin(), BB, std::next(MI.getIterator()), BB->end());
507   DoneMBB->transferSuccessorsAndUpdatePHIs(BB);
508 
509   BB->addSuccessor(TrueMBB);
510   BB->addSuccessor(FalseMBB);
511   TrueMBB->addSuccessor(DoneMBB);
512   FalseMBB->addSuccessor(DoneMBB);
513 
514   unsigned Tmp0, Tmp1, CmpReg, EqzReg, FalseReg, TrueReg;
515   Tmp0 = MRI.createVirtualRegister(MRI.getRegClass(InReg));
516   Tmp1 = MRI.createVirtualRegister(MRI.getRegClass(InReg));
517   CmpReg = MRI.createVirtualRegister(&WebAssembly::I32RegClass);
518   EqzReg = MRI.createVirtualRegister(&WebAssembly::I32RegClass);
519   FalseReg = MRI.createVirtualRegister(MRI.getRegClass(OutReg));
520   TrueReg = MRI.createVirtualRegister(MRI.getRegClass(OutReg));
521 
522   MI.eraseFromParent();
523   // For signed numbers, we can do a single comparison to determine whether
524   // fabs(x) is within range.
525   if (IsUnsigned) {
526     Tmp0 = InReg;
527   } else {
528     BuildMI(BB, DL, TII.get(Abs), Tmp0).addReg(InReg);
529   }
530   BuildMI(BB, DL, TII.get(FConst), Tmp1)
531       .addFPImm(cast<ConstantFP>(ConstantFP::get(Ty, CmpVal)));
532   BuildMI(BB, DL, TII.get(LT), CmpReg).addReg(Tmp0).addReg(Tmp1);
533 
534   // For unsigned numbers, we have to do a separate comparison with zero.
535   if (IsUnsigned) {
536     Tmp1 = MRI.createVirtualRegister(MRI.getRegClass(InReg));
537     Register SecondCmpReg =
538         MRI.createVirtualRegister(&WebAssembly::I32RegClass);
539     Register AndReg = MRI.createVirtualRegister(&WebAssembly::I32RegClass);
540     BuildMI(BB, DL, TII.get(FConst), Tmp1)
541         .addFPImm(cast<ConstantFP>(ConstantFP::get(Ty, 0.0)));
542     BuildMI(BB, DL, TII.get(GE), SecondCmpReg).addReg(Tmp0).addReg(Tmp1);
543     BuildMI(BB, DL, TII.get(And), AndReg).addReg(CmpReg).addReg(SecondCmpReg);
544     CmpReg = AndReg;
545   }
546 
547   BuildMI(BB, DL, TII.get(Eqz), EqzReg).addReg(CmpReg);
548 
549   // Create the CFG diamond to select between doing the conversion or using
550   // the substitute value.
551   BuildMI(BB, DL, TII.get(WebAssembly::BR_IF)).addMBB(TrueMBB).addReg(EqzReg);
552   BuildMI(FalseMBB, DL, TII.get(LoweredOpcode), FalseReg).addReg(InReg);
553   BuildMI(FalseMBB, DL, TII.get(WebAssembly::BR)).addMBB(DoneMBB);
554   BuildMI(TrueMBB, DL, TII.get(IConst), TrueReg).addImm(Substitute);
555   BuildMI(*DoneMBB, DoneMBB->begin(), DL, TII.get(TargetOpcode::PHI), OutReg)
556       .addReg(FalseReg)
557       .addMBB(FalseMBB)
558       .addReg(TrueReg)
559       .addMBB(TrueMBB);
560 
561   return DoneMBB;
562 }
563 
564 static MachineBasicBlock *
565 LowerCallResults(MachineInstr &CallResults, DebugLoc DL, MachineBasicBlock *BB,
566                  const WebAssemblySubtarget *Subtarget,
567                  const TargetInstrInfo &TII) {
568   MachineInstr &CallParams = *CallResults.getPrevNode();
569   assert(CallParams.getOpcode() == WebAssembly::CALL_PARAMS);
570   assert(CallResults.getOpcode() == WebAssembly::CALL_RESULTS ||
571          CallResults.getOpcode() == WebAssembly::RET_CALL_RESULTS);
572 
573   bool IsIndirect =
574       CallParams.getOperand(0).isReg() || CallParams.getOperand(0).isFI();
575   bool IsRetCall = CallResults.getOpcode() == WebAssembly::RET_CALL_RESULTS;
576 
577   bool IsFuncrefCall = false;
578   if (IsIndirect && CallParams.getOperand(0).isReg()) {
579     Register Reg = CallParams.getOperand(0).getReg();
580     const MachineFunction *MF = BB->getParent();
581     const MachineRegisterInfo &MRI = MF->getRegInfo();
582     const TargetRegisterClass *TRC = MRI.getRegClass(Reg);
583     IsFuncrefCall = (TRC == &WebAssembly::FUNCREFRegClass);
584     assert(!IsFuncrefCall || Subtarget->hasReferenceTypes());
585   }
586 
587   unsigned CallOp;
588   if (IsIndirect && IsRetCall) {
589     CallOp = WebAssembly::RET_CALL_INDIRECT;
590   } else if (IsIndirect) {
591     CallOp = WebAssembly::CALL_INDIRECT;
592   } else if (IsRetCall) {
593     CallOp = WebAssembly::RET_CALL;
594   } else {
595     CallOp = WebAssembly::CALL;
596   }
597 
598   MachineFunction &MF = *BB->getParent();
599   const MCInstrDesc &MCID = TII.get(CallOp);
600   MachineInstrBuilder MIB(MF, MF.CreateMachineInstr(MCID, DL));
601 
602   // Move the function pointer to the end of the arguments for indirect calls
603   if (IsIndirect) {
604     auto FnPtr = CallParams.getOperand(0);
605     CallParams.removeOperand(0);
606 
607     // For funcrefs, call_indirect is done through __funcref_call_table and the
608     // funcref is always installed in slot 0 of the table, therefore instead of
609     // having the function pointer added at the end of the params list, a zero
610     // (the index in
611     // __funcref_call_table is added).
612     if (IsFuncrefCall) {
613       Register RegZero =
614           MF.getRegInfo().createVirtualRegister(&WebAssembly::I32RegClass);
615       MachineInstrBuilder MIBC0 =
616           BuildMI(MF, DL, TII.get(WebAssembly::CONST_I32), RegZero).addImm(0);
617 
618       BB->insert(CallResults.getIterator(), MIBC0);
619       MachineInstrBuilder(MF, CallParams).addReg(RegZero);
620     } else
621       CallParams.addOperand(FnPtr);
622   }
623 
624   for (auto Def : CallResults.defs())
625     MIB.add(Def);
626 
627   if (IsIndirect) {
628     // Placeholder for the type index.
629     MIB.addImm(0);
630     // The table into which this call_indirect indexes.
631     MCSymbolWasm *Table = IsFuncrefCall
632                               ? WebAssembly::getOrCreateFuncrefCallTableSymbol(
633                                     MF.getContext(), Subtarget)
634                               : WebAssembly::getOrCreateFunctionTableSymbol(
635                                     MF.getContext(), Subtarget);
636     if (Subtarget->hasReferenceTypes()) {
637       MIB.addSym(Table);
638     } else {
639       // For the MVP there is at most one table whose number is 0, but we can't
640       // write a table symbol or issue relocations.  Instead we just ensure the
641       // table is live and write a zero.
642       Table->setNoStrip();
643       MIB.addImm(0);
644     }
645   }
646 
647   for (auto Use : CallParams.uses())
648     MIB.add(Use);
649 
650   BB->insert(CallResults.getIterator(), MIB);
651   CallParams.eraseFromParent();
652   CallResults.eraseFromParent();
653 
654   // If this is a funcref call, to avoid hidden GC roots, we need to clear the
655   // table slot with ref.null upon call_indirect return.
656   //
657   // This generates the following code, which comes right after a call_indirect
658   // of a funcref:
659   //
660   //    i32.const 0
661   //    ref.null func
662   //    table.set __funcref_call_table
663   if (IsIndirect && IsFuncrefCall) {
664     MCSymbolWasm *Table = WebAssembly::getOrCreateFuncrefCallTableSymbol(
665         MF.getContext(), Subtarget);
666     Register RegZero =
667         MF.getRegInfo().createVirtualRegister(&WebAssembly::I32RegClass);
668     MachineInstr *Const0 =
669         BuildMI(MF, DL, TII.get(WebAssembly::CONST_I32), RegZero).addImm(0);
670     BB->insertAfter(MIB.getInstr()->getIterator(), Const0);
671 
672     Register RegFuncref =
673         MF.getRegInfo().createVirtualRegister(&WebAssembly::FUNCREFRegClass);
674     MachineInstr *RefNull =
675         BuildMI(MF, DL, TII.get(WebAssembly::REF_NULL_FUNCREF), RegFuncref);
676     BB->insertAfter(Const0->getIterator(), RefNull);
677 
678     MachineInstr *TableSet =
679         BuildMI(MF, DL, TII.get(WebAssembly::TABLE_SET_FUNCREF))
680             .addSym(Table)
681             .addReg(RegZero)
682             .addReg(RegFuncref);
683     BB->insertAfter(RefNull->getIterator(), TableSet);
684   }
685 
686   return BB;
687 }
688 
689 MachineBasicBlock *WebAssemblyTargetLowering::EmitInstrWithCustomInserter(
690     MachineInstr &MI, MachineBasicBlock *BB) const {
691   const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
692   DebugLoc DL = MI.getDebugLoc();
693 
694   switch (MI.getOpcode()) {
695   default:
696     llvm_unreachable("Unexpected instr type to insert");
697   case WebAssembly::FP_TO_SINT_I32_F32:
698     return LowerFPToInt(MI, DL, BB, TII, false, false, false,
699                         WebAssembly::I32_TRUNC_S_F32);
700   case WebAssembly::FP_TO_UINT_I32_F32:
701     return LowerFPToInt(MI, DL, BB, TII, true, false, false,
702                         WebAssembly::I32_TRUNC_U_F32);
703   case WebAssembly::FP_TO_SINT_I64_F32:
704     return LowerFPToInt(MI, DL, BB, TII, false, true, false,
705                         WebAssembly::I64_TRUNC_S_F32);
706   case WebAssembly::FP_TO_UINT_I64_F32:
707     return LowerFPToInt(MI, DL, BB, TII, true, true, false,
708                         WebAssembly::I64_TRUNC_U_F32);
709   case WebAssembly::FP_TO_SINT_I32_F64:
710     return LowerFPToInt(MI, DL, BB, TII, false, false, true,
711                         WebAssembly::I32_TRUNC_S_F64);
712   case WebAssembly::FP_TO_UINT_I32_F64:
713     return LowerFPToInt(MI, DL, BB, TII, true, false, true,
714                         WebAssembly::I32_TRUNC_U_F64);
715   case WebAssembly::FP_TO_SINT_I64_F64:
716     return LowerFPToInt(MI, DL, BB, TII, false, true, true,
717                         WebAssembly::I64_TRUNC_S_F64);
718   case WebAssembly::FP_TO_UINT_I64_F64:
719     return LowerFPToInt(MI, DL, BB, TII, true, true, true,
720                         WebAssembly::I64_TRUNC_U_F64);
721   case WebAssembly::CALL_RESULTS:
722   case WebAssembly::RET_CALL_RESULTS:
723     return LowerCallResults(MI, DL, BB, Subtarget, TII);
724   }
725 }
726 
727 const char *
728 WebAssemblyTargetLowering::getTargetNodeName(unsigned Opcode) const {
729   switch (static_cast<WebAssemblyISD::NodeType>(Opcode)) {
730   case WebAssemblyISD::FIRST_NUMBER:
731   case WebAssemblyISD::FIRST_MEM_OPCODE:
732     break;
733 #define HANDLE_NODETYPE(NODE)                                                  \
734   case WebAssemblyISD::NODE:                                                   \
735     return "WebAssemblyISD::" #NODE;
736 #define HANDLE_MEM_NODETYPE(NODE) HANDLE_NODETYPE(NODE)
737 #include "WebAssemblyISD.def"
738 #undef HANDLE_MEM_NODETYPE
739 #undef HANDLE_NODETYPE
740   }
741   return nullptr;
742 }
743 
744 std::pair<unsigned, const TargetRegisterClass *>
745 WebAssemblyTargetLowering::getRegForInlineAsmConstraint(
746     const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
747   // First, see if this is a constraint that directly corresponds to a
748   // WebAssembly register class.
749   if (Constraint.size() == 1) {
750     switch (Constraint[0]) {
751     case 'r':
752       assert(VT != MVT::iPTR && "Pointer MVT not expected here");
753       if (Subtarget->hasSIMD128() && VT.isVector()) {
754         if (VT.getSizeInBits() == 128)
755           return std::make_pair(0U, &WebAssembly::V128RegClass);
756       }
757       if (VT.isInteger() && !VT.isVector()) {
758         if (VT.getSizeInBits() <= 32)
759           return std::make_pair(0U, &WebAssembly::I32RegClass);
760         if (VT.getSizeInBits() <= 64)
761           return std::make_pair(0U, &WebAssembly::I64RegClass);
762       }
763       if (VT.isFloatingPoint() && !VT.isVector()) {
764         switch (VT.getSizeInBits()) {
765         case 32:
766           return std::make_pair(0U, &WebAssembly::F32RegClass);
767         case 64:
768           return std::make_pair(0U, &WebAssembly::F64RegClass);
769         default:
770           break;
771         }
772       }
773       break;
774     default:
775       break;
776     }
777   }
778 
779   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
780 }
781 
782 bool WebAssemblyTargetLowering::isCheapToSpeculateCttz(Type *Ty) const {
783   // Assume ctz is a relatively cheap operation.
784   return true;
785 }
786 
787 bool WebAssemblyTargetLowering::isCheapToSpeculateCtlz(Type *Ty) const {
788   // Assume clz is a relatively cheap operation.
789   return true;
790 }
791 
792 bool WebAssemblyTargetLowering::isLegalAddressingMode(const DataLayout &DL,
793                                                       const AddrMode &AM,
794                                                       Type *Ty, unsigned AS,
795                                                       Instruction *I) const {
796   // WebAssembly offsets are added as unsigned without wrapping. The
797   // isLegalAddressingMode gives us no way to determine if wrapping could be
798   // happening, so we approximate this by accepting only non-negative offsets.
799   if (AM.BaseOffs < 0)
800     return false;
801 
802   // WebAssembly has no scale register operands.
803   if (AM.Scale != 0)
804     return false;
805 
806   // Everything else is legal.
807   return true;
808 }
809 
810 bool WebAssemblyTargetLowering::allowsMisalignedMemoryAccesses(
811     EVT /*VT*/, unsigned /*AddrSpace*/, Align /*Align*/,
812     MachineMemOperand::Flags /*Flags*/, unsigned *Fast) const {
813   // WebAssembly supports unaligned accesses, though it should be declared
814   // with the p2align attribute on loads and stores which do so, and there
815   // may be a performance impact. We tell LLVM they're "fast" because
816   // for the kinds of things that LLVM uses this for (merging adjacent stores
817   // of constants, etc.), WebAssembly implementations will either want the
818   // unaligned access or they'll split anyway.
819   if (Fast)
820     *Fast = 1;
821   return true;
822 }
823 
824 bool WebAssemblyTargetLowering::isIntDivCheap(EVT VT,
825                                               AttributeList Attr) const {
826   // The current thinking is that wasm engines will perform this optimization,
827   // so we can save on code size.
828   return true;
829 }
830 
831 bool WebAssemblyTargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const {
832   EVT ExtT = ExtVal.getValueType();
833   EVT MemT = cast<LoadSDNode>(ExtVal->getOperand(0))->getValueType(0);
834   return (ExtT == MVT::v8i16 && MemT == MVT::v8i8) ||
835          (ExtT == MVT::v4i32 && MemT == MVT::v4i16) ||
836          (ExtT == MVT::v2i64 && MemT == MVT::v2i32);
837 }
838 
839 bool WebAssemblyTargetLowering::isOffsetFoldingLegal(
840     const GlobalAddressSDNode *GA) const {
841   // Wasm doesn't support function addresses with offsets
842   const GlobalValue *GV = GA->getGlobal();
843   return isa<Function>(GV) ? false : TargetLowering::isOffsetFoldingLegal(GA);
844 }
845 
846 bool WebAssemblyTargetLowering::shouldSinkOperands(
847     Instruction *I, SmallVectorImpl<Use *> &Ops) const {
848   using namespace llvm::PatternMatch;
849 
850   if (!I->getType()->isVectorTy() || !I->isShift())
851     return false;
852 
853   Value *V = I->getOperand(1);
854   // We dont need to sink constant splat.
855   if (dyn_cast<Constant>(V))
856     return false;
857 
858   if (match(V, m_Shuffle(m_InsertElt(m_Value(), m_Value(), m_ZeroInt()),
859                          m_Value(), m_ZeroMask()))) {
860     // Sink insert
861     Ops.push_back(&cast<Instruction>(V)->getOperandUse(0));
862     // Sink shuffle
863     Ops.push_back(&I->getOperandUse(1));
864     return true;
865   }
866 
867   return false;
868 }
869 
870 EVT WebAssemblyTargetLowering::getSetCCResultType(const DataLayout &DL,
871                                                   LLVMContext &C,
872                                                   EVT VT) const {
873   if (VT.isVector())
874     return VT.changeVectorElementTypeToInteger();
875 
876   // So far, all branch instructions in Wasm take an I32 condition.
877   // The default TargetLowering::getSetCCResultType returns the pointer size,
878   // which would be useful to reduce instruction counts when testing
879   // against 64-bit pointers/values if at some point Wasm supports that.
880   return EVT::getIntegerVT(C, 32);
881 }
882 
883 bool WebAssemblyTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
884                                                    const CallInst &I,
885                                                    MachineFunction &MF,
886                                                    unsigned Intrinsic) const {
887   switch (Intrinsic) {
888   case Intrinsic::wasm_memory_atomic_notify:
889     Info.opc = ISD::INTRINSIC_W_CHAIN;
890     Info.memVT = MVT::i32;
891     Info.ptrVal = I.getArgOperand(0);
892     Info.offset = 0;
893     Info.align = Align(4);
894     // atomic.notify instruction does not really load the memory specified with
895     // this argument, but MachineMemOperand should either be load or store, so
896     // we set this to a load.
897     // FIXME Volatile isn't really correct, but currently all LLVM atomic
898     // instructions are treated as volatiles in the backend, so we should be
899     // consistent. The same applies for wasm_atomic_wait intrinsics too.
900     Info.flags = MachineMemOperand::MOVolatile | MachineMemOperand::MOLoad;
901     return true;
902   case Intrinsic::wasm_memory_atomic_wait32:
903     Info.opc = ISD::INTRINSIC_W_CHAIN;
904     Info.memVT = MVT::i32;
905     Info.ptrVal = I.getArgOperand(0);
906     Info.offset = 0;
907     Info.align = Align(4);
908     Info.flags = MachineMemOperand::MOVolatile | MachineMemOperand::MOLoad;
909     return true;
910   case Intrinsic::wasm_memory_atomic_wait64:
911     Info.opc = ISD::INTRINSIC_W_CHAIN;
912     Info.memVT = MVT::i64;
913     Info.ptrVal = I.getArgOperand(0);
914     Info.offset = 0;
915     Info.align = Align(8);
916     Info.flags = MachineMemOperand::MOVolatile | MachineMemOperand::MOLoad;
917     return true;
918   case Intrinsic::wasm_loadf16_f32:
919     Info.opc = ISD::INTRINSIC_W_CHAIN;
920     Info.memVT = MVT::f16;
921     Info.ptrVal = I.getArgOperand(0);
922     Info.offset = 0;
923     Info.align = Align(2);
924     Info.flags = MachineMemOperand::MOLoad;
925     return true;
926   case Intrinsic::wasm_storef16_f32:
927     Info.opc = ISD::INTRINSIC_VOID;
928     Info.memVT = MVT::f16;
929     Info.ptrVal = I.getArgOperand(1);
930     Info.offset = 0;
931     Info.align = Align(2);
932     Info.flags = MachineMemOperand::MOStore;
933     return true;
934   default:
935     return false;
936   }
937 }
938 
939 void WebAssemblyTargetLowering::computeKnownBitsForTargetNode(
940     const SDValue Op, KnownBits &Known, const APInt &DemandedElts,
941     const SelectionDAG &DAG, unsigned Depth) const {
942   switch (Op.getOpcode()) {
943   default:
944     break;
945   case ISD::INTRINSIC_WO_CHAIN: {
946     unsigned IntNo = Op.getConstantOperandVal(0);
947     switch (IntNo) {
948     default:
949       break;
950     case Intrinsic::wasm_bitmask: {
951       unsigned BitWidth = Known.getBitWidth();
952       EVT VT = Op.getOperand(1).getSimpleValueType();
953       unsigned PossibleBits = VT.getVectorNumElements();
954       APInt ZeroMask = APInt::getHighBitsSet(BitWidth, BitWidth - PossibleBits);
955       Known.Zero |= ZeroMask;
956       break;
957     }
958     }
959   }
960   }
961 }
962 
963 TargetLoweringBase::LegalizeTypeAction
964 WebAssemblyTargetLowering::getPreferredVectorAction(MVT VT) const {
965   if (VT.isFixedLengthVector()) {
966     MVT EltVT = VT.getVectorElementType();
967     // We have legal vector types with these lane types, so widening the
968     // vector would let us use some of the lanes directly without having to
969     // extend or truncate values.
970     if (EltVT == MVT::i8 || EltVT == MVT::i16 || EltVT == MVT::i32 ||
971         EltVT == MVT::i64 || EltVT == MVT::f32 || EltVT == MVT::f64)
972       return TypeWidenVector;
973   }
974 
975   return TargetLoweringBase::getPreferredVectorAction(VT);
976 }
977 
978 bool WebAssemblyTargetLowering::shouldSimplifyDemandedVectorElts(
979     SDValue Op, const TargetLoweringOpt &TLO) const {
980   // ISel process runs DAGCombiner after legalization; this step is called
981   // SelectionDAG optimization phase. This post-legalization combining process
982   // runs DAGCombiner on each node, and if there was a change to be made,
983   // re-runs legalization again on it and its user nodes to make sure
984   // everythiing is in a legalized state.
985   //
986   // The legalization calls lowering routines, and we do our custom lowering for
987   // build_vectors (LowerBUILD_VECTOR), which converts undef vector elements
988   // into zeros. But there is a set of routines in DAGCombiner that turns unused
989   // (= not demanded) nodes into undef, among which SimplifyDemandedVectorElts
990   // turns unused vector elements into undefs. But this routine does not work
991   // with our custom LowerBUILD_VECTOR, which turns undefs into zeros. This
992   // combination can result in a infinite loop, in which undefs are converted to
993   // zeros in legalization and back to undefs in combining.
994   //
995   // So after DAG is legalized, we prevent SimplifyDemandedVectorElts from
996   // running for build_vectors.
997   if (Op.getOpcode() == ISD::BUILD_VECTOR && TLO.LegalOps && TLO.LegalTys)
998     return false;
999   return true;
1000 }
1001 
1002 //===----------------------------------------------------------------------===//
1003 // WebAssembly Lowering private implementation.
1004 //===----------------------------------------------------------------------===//
1005 
1006 //===----------------------------------------------------------------------===//
1007 // Lowering Code
1008 //===----------------------------------------------------------------------===//
1009 
1010 static void fail(const SDLoc &DL, SelectionDAG &DAG, const char *Msg) {
1011   MachineFunction &MF = DAG.getMachineFunction();
1012   DAG.getContext()->diagnose(
1013       DiagnosticInfoUnsupported(MF.getFunction(), Msg, DL.getDebugLoc()));
1014 }
1015 
1016 // Test whether the given calling convention is supported.
1017 static bool callingConvSupported(CallingConv::ID CallConv) {
1018   // We currently support the language-independent target-independent
1019   // conventions. We don't yet have a way to annotate calls with properties like
1020   // "cold", and we don't have any call-clobbered registers, so these are mostly
1021   // all handled the same.
1022   return CallConv == CallingConv::C || CallConv == CallingConv::Fast ||
1023          CallConv == CallingConv::Cold ||
1024          CallConv == CallingConv::PreserveMost ||
1025          CallConv == CallingConv::PreserveAll ||
1026          CallConv == CallingConv::CXX_FAST_TLS ||
1027          CallConv == CallingConv::WASM_EmscriptenInvoke ||
1028          CallConv == CallingConv::Swift;
1029 }
1030 
1031 SDValue
1032 WebAssemblyTargetLowering::LowerCall(CallLoweringInfo &CLI,
1033                                      SmallVectorImpl<SDValue> &InVals) const {
1034   SelectionDAG &DAG = CLI.DAG;
1035   SDLoc DL = CLI.DL;
1036   SDValue Chain = CLI.Chain;
1037   SDValue Callee = CLI.Callee;
1038   MachineFunction &MF = DAG.getMachineFunction();
1039   auto Layout = MF.getDataLayout();
1040 
1041   CallingConv::ID CallConv = CLI.CallConv;
1042   if (!callingConvSupported(CallConv))
1043     fail(DL, DAG,
1044          "WebAssembly doesn't support language-specific or target-specific "
1045          "calling conventions yet");
1046   if (CLI.IsPatchPoint)
1047     fail(DL, DAG, "WebAssembly doesn't support patch point yet");
1048 
1049   if (CLI.IsTailCall) {
1050     auto NoTail = [&](const char *Msg) {
1051       if (CLI.CB && CLI.CB->isMustTailCall())
1052         fail(DL, DAG, Msg);
1053       CLI.IsTailCall = false;
1054     };
1055 
1056     if (!Subtarget->hasTailCall())
1057       NoTail("WebAssembly 'tail-call' feature not enabled");
1058 
1059     // Varargs calls cannot be tail calls because the buffer is on the stack
1060     if (CLI.IsVarArg)
1061       NoTail("WebAssembly does not support varargs tail calls");
1062 
1063     // Do not tail call unless caller and callee return types match
1064     const Function &F = MF.getFunction();
1065     const TargetMachine &TM = getTargetMachine();
1066     Type *RetTy = F.getReturnType();
1067     SmallVector<MVT, 4> CallerRetTys;
1068     SmallVector<MVT, 4> CalleeRetTys;
1069     computeLegalValueVTs(F, TM, RetTy, CallerRetTys);
1070     computeLegalValueVTs(F, TM, CLI.RetTy, CalleeRetTys);
1071     bool TypesMatch = CallerRetTys.size() == CalleeRetTys.size() &&
1072                       std::equal(CallerRetTys.begin(), CallerRetTys.end(),
1073                                  CalleeRetTys.begin());
1074     if (!TypesMatch)
1075       NoTail("WebAssembly tail call requires caller and callee return types to "
1076              "match");
1077 
1078     // If pointers to local stack values are passed, we cannot tail call
1079     if (CLI.CB) {
1080       for (auto &Arg : CLI.CB->args()) {
1081         Value *Val = Arg.get();
1082         // Trace the value back through pointer operations
1083         while (true) {
1084           Value *Src = Val->stripPointerCastsAndAliases();
1085           if (auto *GEP = dyn_cast<GetElementPtrInst>(Src))
1086             Src = GEP->getPointerOperand();
1087           if (Val == Src)
1088             break;
1089           Val = Src;
1090         }
1091         if (isa<AllocaInst>(Val)) {
1092           NoTail(
1093               "WebAssembly does not support tail calling with stack arguments");
1094           break;
1095         }
1096       }
1097     }
1098   }
1099 
1100   SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
1101   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1102   SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
1103 
1104   // The generic code may have added an sret argument. If we're lowering an
1105   // invoke function, the ABI requires that the function pointer be the first
1106   // argument, so we may have to swap the arguments.
1107   if (CallConv == CallingConv::WASM_EmscriptenInvoke && Outs.size() >= 2 &&
1108       Outs[0].Flags.isSRet()) {
1109     std::swap(Outs[0], Outs[1]);
1110     std::swap(OutVals[0], OutVals[1]);
1111   }
1112 
1113   bool HasSwiftSelfArg = false;
1114   bool HasSwiftErrorArg = false;
1115   unsigned NumFixedArgs = 0;
1116   for (unsigned I = 0; I < Outs.size(); ++I) {
1117     const ISD::OutputArg &Out = Outs[I];
1118     SDValue &OutVal = OutVals[I];
1119     HasSwiftSelfArg |= Out.Flags.isSwiftSelf();
1120     HasSwiftErrorArg |= Out.Flags.isSwiftError();
1121     if (Out.Flags.isNest())
1122       fail(DL, DAG, "WebAssembly hasn't implemented nest arguments");
1123     if (Out.Flags.isInAlloca())
1124       fail(DL, DAG, "WebAssembly hasn't implemented inalloca arguments");
1125     if (Out.Flags.isInConsecutiveRegs())
1126       fail(DL, DAG, "WebAssembly hasn't implemented cons regs arguments");
1127     if (Out.Flags.isInConsecutiveRegsLast())
1128       fail(DL, DAG, "WebAssembly hasn't implemented cons regs last arguments");
1129     if (Out.Flags.isByVal() && Out.Flags.getByValSize() != 0) {
1130       auto &MFI = MF.getFrameInfo();
1131       int FI = MFI.CreateStackObject(Out.Flags.getByValSize(),
1132                                      Out.Flags.getNonZeroByValAlign(),
1133                                      /*isSS=*/false);
1134       SDValue SizeNode =
1135           DAG.getConstant(Out.Flags.getByValSize(), DL, MVT::i32);
1136       SDValue FINode = DAG.getFrameIndex(FI, getPointerTy(Layout));
1137       Chain = DAG.getMemcpy(Chain, DL, FINode, OutVal, SizeNode,
1138                             Out.Flags.getNonZeroByValAlign(),
1139                             /*isVolatile*/ false, /*AlwaysInline=*/false,
1140                             /*CI=*/nullptr, std::nullopt, MachinePointerInfo(),
1141                             MachinePointerInfo());
1142       OutVal = FINode;
1143     }
1144     // Count the number of fixed args *after* legalization.
1145     NumFixedArgs += Out.IsFixed;
1146   }
1147 
1148   bool IsVarArg = CLI.IsVarArg;
1149   auto PtrVT = getPointerTy(Layout);
1150 
1151   // For swiftcc, emit additional swiftself and swifterror arguments
1152   // if there aren't. These additional arguments are also added for callee
1153   // signature They are necessary to match callee and caller signature for
1154   // indirect call.
1155   if (CallConv == CallingConv::Swift) {
1156     if (!HasSwiftSelfArg) {
1157       NumFixedArgs++;
1158       ISD::OutputArg Arg;
1159       Arg.Flags.setSwiftSelf();
1160       CLI.Outs.push_back(Arg);
1161       SDValue ArgVal = DAG.getUNDEF(PtrVT);
1162       CLI.OutVals.push_back(ArgVal);
1163     }
1164     if (!HasSwiftErrorArg) {
1165       NumFixedArgs++;
1166       ISD::OutputArg Arg;
1167       Arg.Flags.setSwiftError();
1168       CLI.Outs.push_back(Arg);
1169       SDValue ArgVal = DAG.getUNDEF(PtrVT);
1170       CLI.OutVals.push_back(ArgVal);
1171     }
1172   }
1173 
1174   // Analyze operands of the call, assigning locations to each operand.
1175   SmallVector<CCValAssign, 16> ArgLocs;
1176   CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
1177 
1178   if (IsVarArg) {
1179     // Outgoing non-fixed arguments are placed in a buffer. First
1180     // compute their offsets and the total amount of buffer space needed.
1181     for (unsigned I = NumFixedArgs; I < Outs.size(); ++I) {
1182       const ISD::OutputArg &Out = Outs[I];
1183       SDValue &Arg = OutVals[I];
1184       EVT VT = Arg.getValueType();
1185       assert(VT != MVT::iPTR && "Legalized args should be concrete");
1186       Type *Ty = VT.getTypeForEVT(*DAG.getContext());
1187       Align Alignment =
1188           std::max(Out.Flags.getNonZeroOrigAlign(), Layout.getABITypeAlign(Ty));
1189       unsigned Offset =
1190           CCInfo.AllocateStack(Layout.getTypeAllocSize(Ty), Alignment);
1191       CCInfo.addLoc(CCValAssign::getMem(ArgLocs.size(), VT.getSimpleVT(),
1192                                         Offset, VT.getSimpleVT(),
1193                                         CCValAssign::Full));
1194     }
1195   }
1196 
1197   unsigned NumBytes = CCInfo.getAlignedCallFrameSize();
1198 
1199   SDValue FINode;
1200   if (IsVarArg && NumBytes) {
1201     // For non-fixed arguments, next emit stores to store the argument values
1202     // to the stack buffer at the offsets computed above.
1203     MaybeAlign StackAlign = Layout.getStackAlignment();
1204     assert(StackAlign && "data layout string is missing stack alignment");
1205     int FI = MF.getFrameInfo().CreateStackObject(NumBytes, *StackAlign,
1206                                                  /*isSS=*/false);
1207     unsigned ValNo = 0;
1208     SmallVector<SDValue, 8> Chains;
1209     for (SDValue Arg : drop_begin(OutVals, NumFixedArgs)) {
1210       assert(ArgLocs[ValNo].getValNo() == ValNo &&
1211              "ArgLocs should remain in order and only hold varargs args");
1212       unsigned Offset = ArgLocs[ValNo++].getLocMemOffset();
1213       FINode = DAG.getFrameIndex(FI, getPointerTy(Layout));
1214       SDValue Add = DAG.getNode(ISD::ADD, DL, PtrVT, FINode,
1215                                 DAG.getConstant(Offset, DL, PtrVT));
1216       Chains.push_back(
1217           DAG.getStore(Chain, DL, Arg, Add,
1218                        MachinePointerInfo::getFixedStack(MF, FI, Offset)));
1219     }
1220     if (!Chains.empty())
1221       Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
1222   } else if (IsVarArg) {
1223     FINode = DAG.getIntPtrConstant(0, DL);
1224   }
1225 
1226   if (Callee->getOpcode() == ISD::GlobalAddress) {
1227     // If the callee is a GlobalAddress node (quite common, every direct call
1228     // is) turn it into a TargetGlobalAddress node so that LowerGlobalAddress
1229     // doesn't at MO_GOT which is not needed for direct calls.
1230     GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Callee);
1231     Callee = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
1232                                         getPointerTy(DAG.getDataLayout()),
1233                                         GA->getOffset());
1234     Callee = DAG.getNode(WebAssemblyISD::Wrapper, DL,
1235                          getPointerTy(DAG.getDataLayout()), Callee);
1236   }
1237 
1238   // Compute the operands for the CALLn node.
1239   SmallVector<SDValue, 16> Ops;
1240   Ops.push_back(Chain);
1241   Ops.push_back(Callee);
1242 
1243   // Add all fixed arguments. Note that for non-varargs calls, NumFixedArgs
1244   // isn't reliable.
1245   Ops.append(OutVals.begin(),
1246              IsVarArg ? OutVals.begin() + NumFixedArgs : OutVals.end());
1247   // Add a pointer to the vararg buffer.
1248   if (IsVarArg)
1249     Ops.push_back(FINode);
1250 
1251   SmallVector<EVT, 8> InTys;
1252   for (const auto &In : Ins) {
1253     assert(!In.Flags.isByVal() && "byval is not valid for return values");
1254     assert(!In.Flags.isNest() && "nest is not valid for return values");
1255     if (In.Flags.isInAlloca())
1256       fail(DL, DAG, "WebAssembly hasn't implemented inalloca return values");
1257     if (In.Flags.isInConsecutiveRegs())
1258       fail(DL, DAG, "WebAssembly hasn't implemented cons regs return values");
1259     if (In.Flags.isInConsecutiveRegsLast())
1260       fail(DL, DAG,
1261            "WebAssembly hasn't implemented cons regs last return values");
1262     // Ignore In.getNonZeroOrigAlign() because all our arguments are passed in
1263     // registers.
1264     InTys.push_back(In.VT);
1265   }
1266 
1267   // Lastly, if this is a call to a funcref we need to add an instruction
1268   // table.set to the chain and transform the call.
1269   if (CLI.CB && WebAssembly::isWebAssemblyFuncrefType(
1270                     CLI.CB->getCalledOperand()->getType())) {
1271     // In the absence of function references proposal where a funcref call is
1272     // lowered to call_ref, using reference types we generate a table.set to set
1273     // the funcref to a special table used solely for this purpose, followed by
1274     // a call_indirect. Here we just generate the table set, and return the
1275     // SDValue of the table.set so that LowerCall can finalize the lowering by
1276     // generating the call_indirect.
1277     SDValue Chain = Ops[0];
1278 
1279     MCSymbolWasm *Table = WebAssembly::getOrCreateFuncrefCallTableSymbol(
1280         MF.getContext(), Subtarget);
1281     SDValue Sym = DAG.getMCSymbol(Table, PtrVT);
1282     SDValue TableSlot = DAG.getConstant(0, DL, MVT::i32);
1283     SDValue TableSetOps[] = {Chain, Sym, TableSlot, Callee};
1284     SDValue TableSet = DAG.getMemIntrinsicNode(
1285         WebAssemblyISD::TABLE_SET, DL, DAG.getVTList(MVT::Other), TableSetOps,
1286         MVT::funcref,
1287         // Machine Mem Operand args
1288         MachinePointerInfo(
1289             WebAssembly::WasmAddressSpace::WASM_ADDRESS_SPACE_FUNCREF),
1290         CLI.CB->getCalledOperand()->getPointerAlignment(DAG.getDataLayout()),
1291         MachineMemOperand::MOStore);
1292 
1293     Ops[0] = TableSet; // The new chain is the TableSet itself
1294   }
1295 
1296   if (CLI.IsTailCall) {
1297     // ret_calls do not return values to the current frame
1298     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1299     return DAG.getNode(WebAssemblyISD::RET_CALL, DL, NodeTys, Ops);
1300   }
1301 
1302   InTys.push_back(MVT::Other);
1303   SDVTList InTyList = DAG.getVTList(InTys);
1304   SDValue Res = DAG.getNode(WebAssemblyISD::CALL, DL, InTyList, Ops);
1305 
1306   for (size_t I = 0; I < Ins.size(); ++I)
1307     InVals.push_back(Res.getValue(I));
1308 
1309   // Return the chain
1310   return Res.getValue(Ins.size());
1311 }
1312 
1313 bool WebAssemblyTargetLowering::CanLowerReturn(
1314     CallingConv::ID /*CallConv*/, MachineFunction & /*MF*/, bool /*IsVarArg*/,
1315     const SmallVectorImpl<ISD::OutputArg> &Outs,
1316     LLVMContext & /*Context*/) const {
1317   // WebAssembly can only handle returning tuples with multivalue enabled
1318   return WebAssembly::canLowerReturn(Outs.size(), Subtarget);
1319 }
1320 
1321 SDValue WebAssemblyTargetLowering::LowerReturn(
1322     SDValue Chain, CallingConv::ID CallConv, bool /*IsVarArg*/,
1323     const SmallVectorImpl<ISD::OutputArg> &Outs,
1324     const SmallVectorImpl<SDValue> &OutVals, const SDLoc &DL,
1325     SelectionDAG &DAG) const {
1326   assert(WebAssembly::canLowerReturn(Outs.size(), Subtarget) &&
1327          "MVP WebAssembly can only return up to one value");
1328   if (!callingConvSupported(CallConv))
1329     fail(DL, DAG, "WebAssembly doesn't support non-C calling conventions");
1330 
1331   SmallVector<SDValue, 4> RetOps(1, Chain);
1332   RetOps.append(OutVals.begin(), OutVals.end());
1333   Chain = DAG.getNode(WebAssemblyISD::RETURN, DL, MVT::Other, RetOps);
1334 
1335   // Record the number and types of the return values.
1336   for (const ISD::OutputArg &Out : Outs) {
1337     assert(!Out.Flags.isByVal() && "byval is not valid for return values");
1338     assert(!Out.Flags.isNest() && "nest is not valid for return values");
1339     assert(Out.IsFixed && "non-fixed return value is not valid");
1340     if (Out.Flags.isInAlloca())
1341       fail(DL, DAG, "WebAssembly hasn't implemented inalloca results");
1342     if (Out.Flags.isInConsecutiveRegs())
1343       fail(DL, DAG, "WebAssembly hasn't implemented cons regs results");
1344     if (Out.Flags.isInConsecutiveRegsLast())
1345       fail(DL, DAG, "WebAssembly hasn't implemented cons regs last results");
1346   }
1347 
1348   return Chain;
1349 }
1350 
1351 SDValue WebAssemblyTargetLowering::LowerFormalArguments(
1352     SDValue Chain, CallingConv::ID CallConv, bool IsVarArg,
1353     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
1354     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
1355   if (!callingConvSupported(CallConv))
1356     fail(DL, DAG, "WebAssembly doesn't support non-C calling conventions");
1357 
1358   MachineFunction &MF = DAG.getMachineFunction();
1359   auto *MFI = MF.getInfo<WebAssemblyFunctionInfo>();
1360 
1361   // Set up the incoming ARGUMENTS value, which serves to represent the liveness
1362   // of the incoming values before they're represented by virtual registers.
1363   MF.getRegInfo().addLiveIn(WebAssembly::ARGUMENTS);
1364 
1365   bool HasSwiftErrorArg = false;
1366   bool HasSwiftSelfArg = false;
1367   for (const ISD::InputArg &In : Ins) {
1368     HasSwiftSelfArg |= In.Flags.isSwiftSelf();
1369     HasSwiftErrorArg |= In.Flags.isSwiftError();
1370     if (In.Flags.isInAlloca())
1371       fail(DL, DAG, "WebAssembly hasn't implemented inalloca arguments");
1372     if (In.Flags.isNest())
1373       fail(DL, DAG, "WebAssembly hasn't implemented nest arguments");
1374     if (In.Flags.isInConsecutiveRegs())
1375       fail(DL, DAG, "WebAssembly hasn't implemented cons regs arguments");
1376     if (In.Flags.isInConsecutiveRegsLast())
1377       fail(DL, DAG, "WebAssembly hasn't implemented cons regs last arguments");
1378     // Ignore In.getNonZeroOrigAlign() because all our arguments are passed in
1379     // registers.
1380     InVals.push_back(In.Used ? DAG.getNode(WebAssemblyISD::ARGUMENT, DL, In.VT,
1381                                            DAG.getTargetConstant(InVals.size(),
1382                                                                  DL, MVT::i32))
1383                              : DAG.getUNDEF(In.VT));
1384 
1385     // Record the number and types of arguments.
1386     MFI->addParam(In.VT);
1387   }
1388 
1389   // For swiftcc, emit additional swiftself and swifterror arguments
1390   // if there aren't. These additional arguments are also added for callee
1391   // signature They are necessary to match callee and caller signature for
1392   // indirect call.
1393   auto PtrVT = getPointerTy(MF.getDataLayout());
1394   if (CallConv == CallingConv::Swift) {
1395     if (!HasSwiftSelfArg) {
1396       MFI->addParam(PtrVT);
1397     }
1398     if (!HasSwiftErrorArg) {
1399       MFI->addParam(PtrVT);
1400     }
1401   }
1402   // Varargs are copied into a buffer allocated by the caller, and a pointer to
1403   // the buffer is passed as an argument.
1404   if (IsVarArg) {
1405     MVT PtrVT = getPointerTy(MF.getDataLayout());
1406     Register VarargVreg =
1407         MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrVT));
1408     MFI->setVarargBufferVreg(VarargVreg);
1409     Chain = DAG.getCopyToReg(
1410         Chain, DL, VarargVreg,
1411         DAG.getNode(WebAssemblyISD::ARGUMENT, DL, PtrVT,
1412                     DAG.getTargetConstant(Ins.size(), DL, MVT::i32)));
1413     MFI->addParam(PtrVT);
1414   }
1415 
1416   // Record the number and types of arguments and results.
1417   SmallVector<MVT, 4> Params;
1418   SmallVector<MVT, 4> Results;
1419   computeSignatureVTs(MF.getFunction().getFunctionType(), &MF.getFunction(),
1420                       MF.getFunction(), DAG.getTarget(), Params, Results);
1421   for (MVT VT : Results)
1422     MFI->addResult(VT);
1423   // TODO: Use signatures in WebAssemblyMachineFunctionInfo too and unify
1424   // the param logic here with ComputeSignatureVTs
1425   assert(MFI->getParams().size() == Params.size() &&
1426          std::equal(MFI->getParams().begin(), MFI->getParams().end(),
1427                     Params.begin()));
1428 
1429   return Chain;
1430 }
1431 
1432 void WebAssemblyTargetLowering::ReplaceNodeResults(
1433     SDNode *N, SmallVectorImpl<SDValue> &Results, SelectionDAG &DAG) const {
1434   switch (N->getOpcode()) {
1435   case ISD::SIGN_EXTEND_INREG:
1436     // Do not add any results, signifying that N should not be custom lowered
1437     // after all. This happens because simd128 turns on custom lowering for
1438     // SIGN_EXTEND_INREG, but for non-vector sign extends the result might be an
1439     // illegal type.
1440     break;
1441   case ISD::SIGN_EXTEND_VECTOR_INREG:
1442   case ISD::ZERO_EXTEND_VECTOR_INREG:
1443     // Do not add any results, signifying that N should not be custom lowered.
1444     // EXTEND_VECTOR_INREG is implemented for some vectors, but not all.
1445     break;
1446   default:
1447     llvm_unreachable(
1448         "ReplaceNodeResults not implemented for this op for WebAssembly!");
1449   }
1450 }
1451 
1452 //===----------------------------------------------------------------------===//
1453 //  Custom lowering hooks.
1454 //===----------------------------------------------------------------------===//
1455 
1456 SDValue WebAssemblyTargetLowering::LowerOperation(SDValue Op,
1457                                                   SelectionDAG &DAG) const {
1458   SDLoc DL(Op);
1459   switch (Op.getOpcode()) {
1460   default:
1461     llvm_unreachable("unimplemented operation lowering");
1462     return SDValue();
1463   case ISD::FrameIndex:
1464     return LowerFrameIndex(Op, DAG);
1465   case ISD::GlobalAddress:
1466     return LowerGlobalAddress(Op, DAG);
1467   case ISD::GlobalTLSAddress:
1468     return LowerGlobalTLSAddress(Op, DAG);
1469   case ISD::ExternalSymbol:
1470     return LowerExternalSymbol(Op, DAG);
1471   case ISD::JumpTable:
1472     return LowerJumpTable(Op, DAG);
1473   case ISD::BR_JT:
1474     return LowerBR_JT(Op, DAG);
1475   case ISD::VASTART:
1476     return LowerVASTART(Op, DAG);
1477   case ISD::BlockAddress:
1478   case ISD::BRIND:
1479     fail(DL, DAG, "WebAssembly hasn't implemented computed gotos");
1480     return SDValue();
1481   case ISD::RETURNADDR:
1482     return LowerRETURNADDR(Op, DAG);
1483   case ISD::FRAMEADDR:
1484     return LowerFRAMEADDR(Op, DAG);
1485   case ISD::CopyToReg:
1486     return LowerCopyToReg(Op, DAG);
1487   case ISD::EXTRACT_VECTOR_ELT:
1488   case ISD::INSERT_VECTOR_ELT:
1489     return LowerAccessVectorElement(Op, DAG);
1490   case ISD::INTRINSIC_VOID:
1491   case ISD::INTRINSIC_WO_CHAIN:
1492   case ISD::INTRINSIC_W_CHAIN:
1493     return LowerIntrinsic(Op, DAG);
1494   case ISD::SIGN_EXTEND_INREG:
1495     return LowerSIGN_EXTEND_INREG(Op, DAG);
1496   case ISD::ZERO_EXTEND_VECTOR_INREG:
1497   case ISD::SIGN_EXTEND_VECTOR_INREG:
1498     return LowerEXTEND_VECTOR_INREG(Op, DAG);
1499   case ISD::BUILD_VECTOR:
1500     return LowerBUILD_VECTOR(Op, DAG);
1501   case ISD::VECTOR_SHUFFLE:
1502     return LowerVECTOR_SHUFFLE(Op, DAG);
1503   case ISD::SETCC:
1504     return LowerSETCC(Op, DAG);
1505   case ISD::SHL:
1506   case ISD::SRA:
1507   case ISD::SRL:
1508     return LowerShift(Op, DAG);
1509   case ISD::FP_TO_SINT_SAT:
1510   case ISD::FP_TO_UINT_SAT:
1511     return LowerFP_TO_INT_SAT(Op, DAG);
1512   case ISD::LOAD:
1513     return LowerLoad(Op, DAG);
1514   case ISD::STORE:
1515     return LowerStore(Op, DAG);
1516   case ISD::CTPOP:
1517   case ISD::CTLZ:
1518   case ISD::CTTZ:
1519     return DAG.UnrollVectorOp(Op.getNode());
1520   case ISD::CLEAR_CACHE:
1521     report_fatal_error("llvm.clear_cache is not supported on wasm");
1522   }
1523 }
1524 
1525 static bool IsWebAssemblyGlobal(SDValue Op) {
1526   if (const GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op))
1527     return WebAssembly::isWasmVarAddressSpace(GA->getAddressSpace());
1528 
1529   return false;
1530 }
1531 
1532 static std::optional<unsigned> IsWebAssemblyLocal(SDValue Op,
1533                                                   SelectionDAG &DAG) {
1534   const FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Op);
1535   if (!FI)
1536     return std::nullopt;
1537 
1538   auto &MF = DAG.getMachineFunction();
1539   return WebAssemblyFrameLowering::getLocalForStackObject(MF, FI->getIndex());
1540 }
1541 
1542 SDValue WebAssemblyTargetLowering::LowerStore(SDValue Op,
1543                                               SelectionDAG &DAG) const {
1544   SDLoc DL(Op);
1545   StoreSDNode *SN = cast<StoreSDNode>(Op.getNode());
1546   const SDValue &Value = SN->getValue();
1547   const SDValue &Base = SN->getBasePtr();
1548   const SDValue &Offset = SN->getOffset();
1549 
1550   if (IsWebAssemblyGlobal(Base)) {
1551     if (!Offset->isUndef())
1552       report_fatal_error("unexpected offset when storing to webassembly global",
1553                          false);
1554 
1555     SDVTList Tys = DAG.getVTList(MVT::Other);
1556     SDValue Ops[] = {SN->getChain(), Value, Base};
1557     return DAG.getMemIntrinsicNode(WebAssemblyISD::GLOBAL_SET, DL, Tys, Ops,
1558                                    SN->getMemoryVT(), SN->getMemOperand());
1559   }
1560 
1561   if (std::optional<unsigned> Local = IsWebAssemblyLocal(Base, DAG)) {
1562     if (!Offset->isUndef())
1563       report_fatal_error("unexpected offset when storing to webassembly local",
1564                          false);
1565 
1566     SDValue Idx = DAG.getTargetConstant(*Local, Base, MVT::i32);
1567     SDVTList Tys = DAG.getVTList(MVT::Other); // The chain.
1568     SDValue Ops[] = {SN->getChain(), Idx, Value};
1569     return DAG.getNode(WebAssemblyISD::LOCAL_SET, DL, Tys, Ops);
1570   }
1571 
1572   if (WebAssembly::isWasmVarAddressSpace(SN->getAddressSpace()))
1573     report_fatal_error(
1574         "Encountered an unlowerable store to the wasm_var address space",
1575         false);
1576 
1577   return Op;
1578 }
1579 
1580 SDValue WebAssemblyTargetLowering::LowerLoad(SDValue Op,
1581                                              SelectionDAG &DAG) const {
1582   SDLoc DL(Op);
1583   LoadSDNode *LN = cast<LoadSDNode>(Op.getNode());
1584   const SDValue &Base = LN->getBasePtr();
1585   const SDValue &Offset = LN->getOffset();
1586 
1587   if (IsWebAssemblyGlobal(Base)) {
1588     if (!Offset->isUndef())
1589       report_fatal_error(
1590           "unexpected offset when loading from webassembly global", false);
1591 
1592     SDVTList Tys = DAG.getVTList(LN->getValueType(0), MVT::Other);
1593     SDValue Ops[] = {LN->getChain(), Base};
1594     return DAG.getMemIntrinsicNode(WebAssemblyISD::GLOBAL_GET, DL, Tys, Ops,
1595                                    LN->getMemoryVT(), LN->getMemOperand());
1596   }
1597 
1598   if (std::optional<unsigned> Local = IsWebAssemblyLocal(Base, DAG)) {
1599     if (!Offset->isUndef())
1600       report_fatal_error(
1601           "unexpected offset when loading from webassembly local", false);
1602 
1603     SDValue Idx = DAG.getTargetConstant(*Local, Base, MVT::i32);
1604     EVT LocalVT = LN->getValueType(0);
1605     SDValue LocalGet = DAG.getNode(WebAssemblyISD::LOCAL_GET, DL, LocalVT,
1606                                    {LN->getChain(), Idx});
1607     SDValue Result = DAG.getMergeValues({LocalGet, LN->getChain()}, DL);
1608     assert(Result->getNumValues() == 2 && "Loads must carry a chain!");
1609     return Result;
1610   }
1611 
1612   if (WebAssembly::isWasmVarAddressSpace(LN->getAddressSpace()))
1613     report_fatal_error(
1614         "Encountered an unlowerable load from the wasm_var address space",
1615         false);
1616 
1617   return Op;
1618 }
1619 
1620 SDValue WebAssemblyTargetLowering::LowerCopyToReg(SDValue Op,
1621                                                   SelectionDAG &DAG) const {
1622   SDValue Src = Op.getOperand(2);
1623   if (isa<FrameIndexSDNode>(Src.getNode())) {
1624     // CopyToReg nodes don't support FrameIndex operands. Other targets select
1625     // the FI to some LEA-like instruction, but since we don't have that, we
1626     // need to insert some kind of instruction that can take an FI operand and
1627     // produces a value usable by CopyToReg (i.e. in a vreg). So insert a dummy
1628     // local.copy between Op and its FI operand.
1629     SDValue Chain = Op.getOperand(0);
1630     SDLoc DL(Op);
1631     Register Reg = cast<RegisterSDNode>(Op.getOperand(1))->getReg();
1632     EVT VT = Src.getValueType();
1633     SDValue Copy(DAG.getMachineNode(VT == MVT::i32 ? WebAssembly::COPY_I32
1634                                                    : WebAssembly::COPY_I64,
1635                                     DL, VT, Src),
1636                  0);
1637     return Op.getNode()->getNumValues() == 1
1638                ? DAG.getCopyToReg(Chain, DL, Reg, Copy)
1639                : DAG.getCopyToReg(Chain, DL, Reg, Copy,
1640                                   Op.getNumOperands() == 4 ? Op.getOperand(3)
1641                                                            : SDValue());
1642   }
1643   return SDValue();
1644 }
1645 
1646 SDValue WebAssemblyTargetLowering::LowerFrameIndex(SDValue Op,
1647                                                    SelectionDAG &DAG) const {
1648   int FI = cast<FrameIndexSDNode>(Op)->getIndex();
1649   return DAG.getTargetFrameIndex(FI, Op.getValueType());
1650 }
1651 
1652 SDValue WebAssemblyTargetLowering::LowerRETURNADDR(SDValue Op,
1653                                                    SelectionDAG &DAG) const {
1654   SDLoc DL(Op);
1655 
1656   if (!Subtarget->getTargetTriple().isOSEmscripten()) {
1657     fail(DL, DAG,
1658          "Non-Emscripten WebAssembly hasn't implemented "
1659          "__builtin_return_address");
1660     return SDValue();
1661   }
1662 
1663   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
1664     return SDValue();
1665 
1666   unsigned Depth = Op.getConstantOperandVal(0);
1667   MakeLibCallOptions CallOptions;
1668   return makeLibCall(DAG, RTLIB::RETURN_ADDRESS, Op.getValueType(),
1669                      {DAG.getConstant(Depth, DL, MVT::i32)}, CallOptions, DL)
1670       .first;
1671 }
1672 
1673 SDValue WebAssemblyTargetLowering::LowerFRAMEADDR(SDValue Op,
1674                                                   SelectionDAG &DAG) const {
1675   // Non-zero depths are not supported by WebAssembly currently. Use the
1676   // legalizer's default expansion, which is to return 0 (what this function is
1677   // documented to do).
1678   if (Op.getConstantOperandVal(0) > 0)
1679     return SDValue();
1680 
1681   DAG.getMachineFunction().getFrameInfo().setFrameAddressIsTaken(true);
1682   EVT VT = Op.getValueType();
1683   Register FP =
1684       Subtarget->getRegisterInfo()->getFrameRegister(DAG.getMachineFunction());
1685   return DAG.getCopyFromReg(DAG.getEntryNode(), SDLoc(Op), FP, VT);
1686 }
1687 
1688 SDValue
1689 WebAssemblyTargetLowering::LowerGlobalTLSAddress(SDValue Op,
1690                                                  SelectionDAG &DAG) const {
1691   SDLoc DL(Op);
1692   const auto *GA = cast<GlobalAddressSDNode>(Op);
1693 
1694   MachineFunction &MF = DAG.getMachineFunction();
1695   if (!MF.getSubtarget<WebAssemblySubtarget>().hasBulkMemory())
1696     report_fatal_error("cannot use thread-local storage without bulk memory",
1697                        false);
1698 
1699   const GlobalValue *GV = GA->getGlobal();
1700 
1701   // Currently only Emscripten supports dynamic linking with threads. Therefore,
1702   // on other targets, if we have thread-local storage, only the local-exec
1703   // model is possible.
1704   auto model = Subtarget->getTargetTriple().isOSEmscripten()
1705                    ? GV->getThreadLocalMode()
1706                    : GlobalValue::LocalExecTLSModel;
1707 
1708   // Unsupported TLS modes
1709   assert(model != GlobalValue::NotThreadLocal);
1710   assert(model != GlobalValue::InitialExecTLSModel);
1711 
1712   if (model == GlobalValue::LocalExecTLSModel ||
1713       model == GlobalValue::LocalDynamicTLSModel ||
1714       (model == GlobalValue::GeneralDynamicTLSModel &&
1715        getTargetMachine().shouldAssumeDSOLocal(GV))) {
1716     // For DSO-local TLS variables we use offset from __tls_base
1717 
1718     MVT PtrVT = getPointerTy(DAG.getDataLayout());
1719     auto GlobalGet = PtrVT == MVT::i64 ? WebAssembly::GLOBAL_GET_I64
1720                                        : WebAssembly::GLOBAL_GET_I32;
1721     const char *BaseName = MF.createExternalSymbolName("__tls_base");
1722 
1723     SDValue BaseAddr(
1724         DAG.getMachineNode(GlobalGet, DL, PtrVT,
1725                            DAG.getTargetExternalSymbol(BaseName, PtrVT)),
1726         0);
1727 
1728     SDValue TLSOffset = DAG.getTargetGlobalAddress(
1729         GV, DL, PtrVT, GA->getOffset(), WebAssemblyII::MO_TLS_BASE_REL);
1730     SDValue SymOffset =
1731         DAG.getNode(WebAssemblyISD::WrapperREL, DL, PtrVT, TLSOffset);
1732 
1733     return DAG.getNode(ISD::ADD, DL, PtrVT, BaseAddr, SymOffset);
1734   }
1735 
1736   assert(model == GlobalValue::GeneralDynamicTLSModel);
1737 
1738   EVT VT = Op.getValueType();
1739   return DAG.getNode(WebAssemblyISD::Wrapper, DL, VT,
1740                      DAG.getTargetGlobalAddress(GA->getGlobal(), DL, VT,
1741                                                 GA->getOffset(),
1742                                                 WebAssemblyII::MO_GOT_TLS));
1743 }
1744 
1745 SDValue WebAssemblyTargetLowering::LowerGlobalAddress(SDValue Op,
1746                                                       SelectionDAG &DAG) const {
1747   SDLoc DL(Op);
1748   const auto *GA = cast<GlobalAddressSDNode>(Op);
1749   EVT VT = Op.getValueType();
1750   assert(GA->getTargetFlags() == 0 &&
1751          "Unexpected target flags on generic GlobalAddressSDNode");
1752   if (!WebAssembly::isValidAddressSpace(GA->getAddressSpace()))
1753     fail(DL, DAG, "Invalid address space for WebAssembly target");
1754 
1755   unsigned OperandFlags = 0;
1756   const GlobalValue *GV = GA->getGlobal();
1757   // Since WebAssembly tables cannot yet be shared accross modules, we don't
1758   // need special treatment for tables in PIC mode.
1759   if (isPositionIndependent() &&
1760       !WebAssembly::isWebAssemblyTableType(GV->getValueType())) {
1761     if (getTargetMachine().shouldAssumeDSOLocal(GV)) {
1762       MachineFunction &MF = DAG.getMachineFunction();
1763       MVT PtrVT = getPointerTy(MF.getDataLayout());
1764       const char *BaseName;
1765       if (GV->getValueType()->isFunctionTy()) {
1766         BaseName = MF.createExternalSymbolName("__table_base");
1767         OperandFlags = WebAssemblyII::MO_TABLE_BASE_REL;
1768       } else {
1769         BaseName = MF.createExternalSymbolName("__memory_base");
1770         OperandFlags = WebAssemblyII::MO_MEMORY_BASE_REL;
1771       }
1772       SDValue BaseAddr =
1773           DAG.getNode(WebAssemblyISD::Wrapper, DL, PtrVT,
1774                       DAG.getTargetExternalSymbol(BaseName, PtrVT));
1775 
1776       SDValue SymAddr = DAG.getNode(
1777           WebAssemblyISD::WrapperREL, DL, VT,
1778           DAG.getTargetGlobalAddress(GA->getGlobal(), DL, VT, GA->getOffset(),
1779                                      OperandFlags));
1780 
1781       return DAG.getNode(ISD::ADD, DL, VT, BaseAddr, SymAddr);
1782     }
1783     OperandFlags = WebAssemblyII::MO_GOT;
1784   }
1785 
1786   return DAG.getNode(WebAssemblyISD::Wrapper, DL, VT,
1787                      DAG.getTargetGlobalAddress(GA->getGlobal(), DL, VT,
1788                                                 GA->getOffset(), OperandFlags));
1789 }
1790 
1791 SDValue
1792 WebAssemblyTargetLowering::LowerExternalSymbol(SDValue Op,
1793                                                SelectionDAG &DAG) const {
1794   SDLoc DL(Op);
1795   const auto *ES = cast<ExternalSymbolSDNode>(Op);
1796   EVT VT = Op.getValueType();
1797   assert(ES->getTargetFlags() == 0 &&
1798          "Unexpected target flags on generic ExternalSymbolSDNode");
1799   return DAG.getNode(WebAssemblyISD::Wrapper, DL, VT,
1800                      DAG.getTargetExternalSymbol(ES->getSymbol(), VT));
1801 }
1802 
1803 SDValue WebAssemblyTargetLowering::LowerJumpTable(SDValue Op,
1804                                                   SelectionDAG &DAG) const {
1805   // There's no need for a Wrapper node because we always incorporate a jump
1806   // table operand into a BR_TABLE instruction, rather than ever
1807   // materializing it in a register.
1808   const JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
1809   return DAG.getTargetJumpTable(JT->getIndex(), Op.getValueType(),
1810                                 JT->getTargetFlags());
1811 }
1812 
1813 SDValue WebAssemblyTargetLowering::LowerBR_JT(SDValue Op,
1814                                               SelectionDAG &DAG) const {
1815   SDLoc DL(Op);
1816   SDValue Chain = Op.getOperand(0);
1817   const auto *JT = cast<JumpTableSDNode>(Op.getOperand(1));
1818   SDValue Index = Op.getOperand(2);
1819   assert(JT->getTargetFlags() == 0 && "WebAssembly doesn't set target flags");
1820 
1821   SmallVector<SDValue, 8> Ops;
1822   Ops.push_back(Chain);
1823   Ops.push_back(Index);
1824 
1825   MachineJumpTableInfo *MJTI = DAG.getMachineFunction().getJumpTableInfo();
1826   const auto &MBBs = MJTI->getJumpTables()[JT->getIndex()].MBBs;
1827 
1828   // Add an operand for each case.
1829   for (auto *MBB : MBBs)
1830     Ops.push_back(DAG.getBasicBlock(MBB));
1831 
1832   // Add the first MBB as a dummy default target for now. This will be replaced
1833   // with the proper default target (and the preceding range check eliminated)
1834   // if possible by WebAssemblyFixBrTableDefaults.
1835   Ops.push_back(DAG.getBasicBlock(*MBBs.begin()));
1836   return DAG.getNode(WebAssemblyISD::BR_TABLE, DL, MVT::Other, Ops);
1837 }
1838 
1839 SDValue WebAssemblyTargetLowering::LowerVASTART(SDValue Op,
1840                                                 SelectionDAG &DAG) const {
1841   SDLoc DL(Op);
1842   EVT PtrVT = getPointerTy(DAG.getMachineFunction().getDataLayout());
1843 
1844   auto *MFI = DAG.getMachineFunction().getInfo<WebAssemblyFunctionInfo>();
1845   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
1846 
1847   SDValue ArgN = DAG.getCopyFromReg(DAG.getEntryNode(), DL,
1848                                     MFI->getVarargBufferVreg(), PtrVT);
1849   return DAG.getStore(Op.getOperand(0), DL, ArgN, Op.getOperand(1),
1850                       MachinePointerInfo(SV));
1851 }
1852 
1853 SDValue WebAssemblyTargetLowering::LowerIntrinsic(SDValue Op,
1854                                                   SelectionDAG &DAG) const {
1855   MachineFunction &MF = DAG.getMachineFunction();
1856   unsigned IntNo;
1857   switch (Op.getOpcode()) {
1858   case ISD::INTRINSIC_VOID:
1859   case ISD::INTRINSIC_W_CHAIN:
1860     IntNo = Op.getConstantOperandVal(1);
1861     break;
1862   case ISD::INTRINSIC_WO_CHAIN:
1863     IntNo = Op.getConstantOperandVal(0);
1864     break;
1865   default:
1866     llvm_unreachable("Invalid intrinsic");
1867   }
1868   SDLoc DL(Op);
1869 
1870   switch (IntNo) {
1871   default:
1872     return SDValue(); // Don't custom lower most intrinsics.
1873 
1874   case Intrinsic::wasm_lsda: {
1875     auto PtrVT = getPointerTy(MF.getDataLayout());
1876     const char *SymName = MF.createExternalSymbolName(
1877         "GCC_except_table" + std::to_string(MF.getFunctionNumber()));
1878     if (isPositionIndependent()) {
1879       SDValue Node = DAG.getTargetExternalSymbol(
1880           SymName, PtrVT, WebAssemblyII::MO_MEMORY_BASE_REL);
1881       const char *BaseName = MF.createExternalSymbolName("__memory_base");
1882       SDValue BaseAddr =
1883           DAG.getNode(WebAssemblyISD::Wrapper, DL, PtrVT,
1884                       DAG.getTargetExternalSymbol(BaseName, PtrVT));
1885       SDValue SymAddr =
1886           DAG.getNode(WebAssemblyISD::WrapperREL, DL, PtrVT, Node);
1887       return DAG.getNode(ISD::ADD, DL, PtrVT, BaseAddr, SymAddr);
1888     }
1889     SDValue Node = DAG.getTargetExternalSymbol(SymName, PtrVT);
1890     return DAG.getNode(WebAssemblyISD::Wrapper, DL, PtrVT, Node);
1891   }
1892 
1893   case Intrinsic::wasm_shuffle: {
1894     // Drop in-chain and replace undefs, but otherwise pass through unchanged
1895     SDValue Ops[18];
1896     size_t OpIdx = 0;
1897     Ops[OpIdx++] = Op.getOperand(1);
1898     Ops[OpIdx++] = Op.getOperand(2);
1899     while (OpIdx < 18) {
1900       const SDValue &MaskIdx = Op.getOperand(OpIdx + 1);
1901       if (MaskIdx.isUndef() || MaskIdx.getNode()->getAsZExtVal() >= 32) {
1902         bool isTarget = MaskIdx.getNode()->getOpcode() == ISD::TargetConstant;
1903         Ops[OpIdx++] = DAG.getConstant(0, DL, MVT::i32, isTarget);
1904       } else {
1905         Ops[OpIdx++] = MaskIdx;
1906       }
1907     }
1908     return DAG.getNode(WebAssemblyISD::SHUFFLE, DL, Op.getValueType(), Ops);
1909   }
1910   }
1911 }
1912 
1913 SDValue
1914 WebAssemblyTargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
1915                                                   SelectionDAG &DAG) const {
1916   SDLoc DL(Op);
1917   // If sign extension operations are disabled, allow sext_inreg only if operand
1918   // is a vector extract of an i8 or i16 lane. SIMD does not depend on sign
1919   // extension operations, but allowing sext_inreg in this context lets us have
1920   // simple patterns to select extract_lane_s instructions. Expanding sext_inreg
1921   // everywhere would be simpler in this file, but would necessitate large and
1922   // brittle patterns to undo the expansion and select extract_lane_s
1923   // instructions.
1924   assert(!Subtarget->hasSignExt() && Subtarget->hasSIMD128());
1925   if (Op.getOperand(0).getOpcode() != ISD::EXTRACT_VECTOR_ELT)
1926     return SDValue();
1927 
1928   const SDValue &Extract = Op.getOperand(0);
1929   MVT VecT = Extract.getOperand(0).getSimpleValueType();
1930   if (VecT.getVectorElementType().getSizeInBits() > 32)
1931     return SDValue();
1932   MVT ExtractedLaneT =
1933       cast<VTSDNode>(Op.getOperand(1).getNode())->getVT().getSimpleVT();
1934   MVT ExtractedVecT =
1935       MVT::getVectorVT(ExtractedLaneT, 128 / ExtractedLaneT.getSizeInBits());
1936   if (ExtractedVecT == VecT)
1937     return Op;
1938 
1939   // Bitcast vector to appropriate type to ensure ISel pattern coverage
1940   const SDNode *Index = Extract.getOperand(1).getNode();
1941   if (!isa<ConstantSDNode>(Index))
1942     return SDValue();
1943   unsigned IndexVal = Index->getAsZExtVal();
1944   unsigned Scale =
1945       ExtractedVecT.getVectorNumElements() / VecT.getVectorNumElements();
1946   assert(Scale > 1);
1947   SDValue NewIndex =
1948       DAG.getConstant(IndexVal * Scale, DL, Index->getValueType(0));
1949   SDValue NewExtract = DAG.getNode(
1950       ISD::EXTRACT_VECTOR_ELT, DL, Extract.getValueType(),
1951       DAG.getBitcast(ExtractedVecT, Extract.getOperand(0)), NewIndex);
1952   return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, Op.getValueType(), NewExtract,
1953                      Op.getOperand(1));
1954 }
1955 
1956 SDValue
1957 WebAssemblyTargetLowering::LowerEXTEND_VECTOR_INREG(SDValue Op,
1958                                                     SelectionDAG &DAG) const {
1959   SDLoc DL(Op);
1960   EVT VT = Op.getValueType();
1961   SDValue Src = Op.getOperand(0);
1962   EVT SrcVT = Src.getValueType();
1963 
1964   if (SrcVT.getVectorElementType() == MVT::i1 ||
1965       SrcVT.getVectorElementType() == MVT::i64)
1966     return SDValue();
1967 
1968   assert(VT.getScalarSizeInBits() % SrcVT.getScalarSizeInBits() == 0 &&
1969          "Unexpected extension factor.");
1970   unsigned Scale = VT.getScalarSizeInBits() / SrcVT.getScalarSizeInBits();
1971 
1972   if (Scale != 2 && Scale != 4 && Scale != 8)
1973     return SDValue();
1974 
1975   unsigned Ext;
1976   switch (Op.getOpcode()) {
1977   case ISD::ZERO_EXTEND_VECTOR_INREG:
1978     Ext = WebAssemblyISD::EXTEND_LOW_U;
1979     break;
1980   case ISD::SIGN_EXTEND_VECTOR_INREG:
1981     Ext = WebAssemblyISD::EXTEND_LOW_S;
1982     break;
1983   }
1984 
1985   SDValue Ret = Src;
1986   while (Scale != 1) {
1987     Ret = DAG.getNode(Ext, DL,
1988                       Ret.getValueType()
1989                           .widenIntegerVectorElementType(*DAG.getContext())
1990                           .getHalfNumVectorElementsVT(*DAG.getContext()),
1991                       Ret);
1992     Scale /= 2;
1993   }
1994   assert(Ret.getValueType() == VT);
1995   return Ret;
1996 }
1997 
1998 static SDValue LowerConvertLow(SDValue Op, SelectionDAG &DAG) {
1999   SDLoc DL(Op);
2000   if (Op.getValueType() != MVT::v2f64)
2001     return SDValue();
2002 
2003   auto GetConvertedLane = [](SDValue Op, unsigned &Opcode, SDValue &SrcVec,
2004                              unsigned &Index) -> bool {
2005     switch (Op.getOpcode()) {
2006     case ISD::SINT_TO_FP:
2007       Opcode = WebAssemblyISD::CONVERT_LOW_S;
2008       break;
2009     case ISD::UINT_TO_FP:
2010       Opcode = WebAssemblyISD::CONVERT_LOW_U;
2011       break;
2012     case ISD::FP_EXTEND:
2013       Opcode = WebAssemblyISD::PROMOTE_LOW;
2014       break;
2015     default:
2016       return false;
2017     }
2018 
2019     auto ExtractVector = Op.getOperand(0);
2020     if (ExtractVector.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
2021       return false;
2022 
2023     if (!isa<ConstantSDNode>(ExtractVector.getOperand(1).getNode()))
2024       return false;
2025 
2026     SrcVec = ExtractVector.getOperand(0);
2027     Index = ExtractVector.getConstantOperandVal(1);
2028     return true;
2029   };
2030 
2031   unsigned LHSOpcode, RHSOpcode, LHSIndex, RHSIndex;
2032   SDValue LHSSrcVec, RHSSrcVec;
2033   if (!GetConvertedLane(Op.getOperand(0), LHSOpcode, LHSSrcVec, LHSIndex) ||
2034       !GetConvertedLane(Op.getOperand(1), RHSOpcode, RHSSrcVec, RHSIndex))
2035     return SDValue();
2036 
2037   if (LHSOpcode != RHSOpcode)
2038     return SDValue();
2039 
2040   MVT ExpectedSrcVT;
2041   switch (LHSOpcode) {
2042   case WebAssemblyISD::CONVERT_LOW_S:
2043   case WebAssemblyISD::CONVERT_LOW_U:
2044     ExpectedSrcVT = MVT::v4i32;
2045     break;
2046   case WebAssemblyISD::PROMOTE_LOW:
2047     ExpectedSrcVT = MVT::v4f32;
2048     break;
2049   }
2050   if (LHSSrcVec.getValueType() != ExpectedSrcVT)
2051     return SDValue();
2052 
2053   auto Src = LHSSrcVec;
2054   if (LHSIndex != 0 || RHSIndex != 1 || LHSSrcVec != RHSSrcVec) {
2055     // Shuffle the source vector so that the converted lanes are the low lanes.
2056     Src = DAG.getVectorShuffle(
2057         ExpectedSrcVT, DL, LHSSrcVec, RHSSrcVec,
2058         {static_cast<int>(LHSIndex), static_cast<int>(RHSIndex) + 4, -1, -1});
2059   }
2060   return DAG.getNode(LHSOpcode, DL, MVT::v2f64, Src);
2061 }
2062 
2063 SDValue WebAssemblyTargetLowering::LowerBUILD_VECTOR(SDValue Op,
2064                                                      SelectionDAG &DAG) const {
2065   MVT VT = Op.getSimpleValueType();
2066   if (VT == MVT::v8f16) {
2067     // BUILD_VECTOR can't handle FP16 operands since Wasm doesn't have a scaler
2068     // FP16 type, so cast them to I16s.
2069     MVT IVT = VT.changeVectorElementType(MVT::i16);
2070     SmallVector<SDValue, 8> NewOps;
2071     for (unsigned I = 0, E = Op.getNumOperands(); I < E; ++I)
2072       NewOps.push_back(DAG.getBitcast(MVT::i16, Op.getOperand(I)));
2073     SDValue Res = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(), IVT, NewOps);
2074     return DAG.getBitcast(VT, Res);
2075   }
2076 
2077   if (auto ConvertLow = LowerConvertLow(Op, DAG))
2078     return ConvertLow;
2079 
2080   SDLoc DL(Op);
2081   const EVT VecT = Op.getValueType();
2082   const EVT LaneT = Op.getOperand(0).getValueType();
2083   const size_t Lanes = Op.getNumOperands();
2084   bool CanSwizzle = VecT == MVT::v16i8;
2085 
2086   // BUILD_VECTORs are lowered to the instruction that initializes the highest
2087   // possible number of lanes at once followed by a sequence of replace_lane
2088   // instructions to individually initialize any remaining lanes.
2089 
2090   // TODO: Tune this. For example, lanewise swizzling is very expensive, so
2091   // swizzled lanes should be given greater weight.
2092 
2093   // TODO: Investigate looping rather than always extracting/replacing specific
2094   // lanes to fill gaps.
2095 
2096   auto IsConstant = [](const SDValue &V) {
2097     return V.getOpcode() == ISD::Constant || V.getOpcode() == ISD::ConstantFP;
2098   };
2099 
2100   // Returns the source vector and index vector pair if they exist. Checks for:
2101   //   (extract_vector_elt
2102   //     $src,
2103   //     (sign_extend_inreg (extract_vector_elt $indices, $i))
2104   //   )
2105   auto GetSwizzleSrcs = [](size_t I, const SDValue &Lane) {
2106     auto Bail = std::make_pair(SDValue(), SDValue());
2107     if (Lane->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
2108       return Bail;
2109     const SDValue &SwizzleSrc = Lane->getOperand(0);
2110     const SDValue &IndexExt = Lane->getOperand(1);
2111     if (IndexExt->getOpcode() != ISD::SIGN_EXTEND_INREG)
2112       return Bail;
2113     const SDValue &Index = IndexExt->getOperand(0);
2114     if (Index->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
2115       return Bail;
2116     const SDValue &SwizzleIndices = Index->getOperand(0);
2117     if (SwizzleSrc.getValueType() != MVT::v16i8 ||
2118         SwizzleIndices.getValueType() != MVT::v16i8 ||
2119         Index->getOperand(1)->getOpcode() != ISD::Constant ||
2120         Index->getConstantOperandVal(1) != I)
2121       return Bail;
2122     return std::make_pair(SwizzleSrc, SwizzleIndices);
2123   };
2124 
2125   // If the lane is extracted from another vector at a constant index, return
2126   // that vector. The source vector must not have more lanes than the dest
2127   // because the shufflevector indices are in terms of the destination lanes and
2128   // would not be able to address the smaller individual source lanes.
2129   auto GetShuffleSrc = [&](const SDValue &Lane) {
2130     if (Lane->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
2131       return SDValue();
2132     if (!isa<ConstantSDNode>(Lane->getOperand(1).getNode()))
2133       return SDValue();
2134     if (Lane->getOperand(0).getValueType().getVectorNumElements() >
2135         VecT.getVectorNumElements())
2136       return SDValue();
2137     return Lane->getOperand(0);
2138   };
2139 
2140   using ValueEntry = std::pair<SDValue, size_t>;
2141   SmallVector<ValueEntry, 16> SplatValueCounts;
2142 
2143   using SwizzleEntry = std::pair<std::pair<SDValue, SDValue>, size_t>;
2144   SmallVector<SwizzleEntry, 16> SwizzleCounts;
2145 
2146   using ShuffleEntry = std::pair<SDValue, size_t>;
2147   SmallVector<ShuffleEntry, 16> ShuffleCounts;
2148 
2149   auto AddCount = [](auto &Counts, const auto &Val) {
2150     auto CountIt =
2151         llvm::find_if(Counts, [&Val](auto E) { return E.first == Val; });
2152     if (CountIt == Counts.end()) {
2153       Counts.emplace_back(Val, 1);
2154     } else {
2155       CountIt->second++;
2156     }
2157   };
2158 
2159   auto GetMostCommon = [](auto &Counts) {
2160     auto CommonIt =
2161         std::max_element(Counts.begin(), Counts.end(), llvm::less_second());
2162     assert(CommonIt != Counts.end() && "Unexpected all-undef build_vector");
2163     return *CommonIt;
2164   };
2165 
2166   size_t NumConstantLanes = 0;
2167 
2168   // Count eligible lanes for each type of vector creation op
2169   for (size_t I = 0; I < Lanes; ++I) {
2170     const SDValue &Lane = Op->getOperand(I);
2171     if (Lane.isUndef())
2172       continue;
2173 
2174     AddCount(SplatValueCounts, Lane);
2175 
2176     if (IsConstant(Lane))
2177       NumConstantLanes++;
2178     if (auto ShuffleSrc = GetShuffleSrc(Lane))
2179       AddCount(ShuffleCounts, ShuffleSrc);
2180     if (CanSwizzle) {
2181       auto SwizzleSrcs = GetSwizzleSrcs(I, Lane);
2182       if (SwizzleSrcs.first)
2183         AddCount(SwizzleCounts, SwizzleSrcs);
2184     }
2185   }
2186 
2187   SDValue SplatValue;
2188   size_t NumSplatLanes;
2189   std::tie(SplatValue, NumSplatLanes) = GetMostCommon(SplatValueCounts);
2190 
2191   SDValue SwizzleSrc;
2192   SDValue SwizzleIndices;
2193   size_t NumSwizzleLanes = 0;
2194   if (SwizzleCounts.size())
2195     std::forward_as_tuple(std::tie(SwizzleSrc, SwizzleIndices),
2196                           NumSwizzleLanes) = GetMostCommon(SwizzleCounts);
2197 
2198   // Shuffles can draw from up to two vectors, so find the two most common
2199   // sources.
2200   SDValue ShuffleSrc1, ShuffleSrc2;
2201   size_t NumShuffleLanes = 0;
2202   if (ShuffleCounts.size()) {
2203     std::tie(ShuffleSrc1, NumShuffleLanes) = GetMostCommon(ShuffleCounts);
2204     llvm::erase_if(ShuffleCounts,
2205                    [&](const auto &Pair) { return Pair.first == ShuffleSrc1; });
2206   }
2207   if (ShuffleCounts.size()) {
2208     size_t AdditionalShuffleLanes;
2209     std::tie(ShuffleSrc2, AdditionalShuffleLanes) =
2210         GetMostCommon(ShuffleCounts);
2211     NumShuffleLanes += AdditionalShuffleLanes;
2212   }
2213 
2214   // Predicate returning true if the lane is properly initialized by the
2215   // original instruction
2216   std::function<bool(size_t, const SDValue &)> IsLaneConstructed;
2217   SDValue Result;
2218   // Prefer swizzles over shuffles over vector consts over splats
2219   if (NumSwizzleLanes >= NumShuffleLanes &&
2220       NumSwizzleLanes >= NumConstantLanes && NumSwizzleLanes >= NumSplatLanes) {
2221     Result = DAG.getNode(WebAssemblyISD::SWIZZLE, DL, VecT, SwizzleSrc,
2222                          SwizzleIndices);
2223     auto Swizzled = std::make_pair(SwizzleSrc, SwizzleIndices);
2224     IsLaneConstructed = [&, Swizzled](size_t I, const SDValue &Lane) {
2225       return Swizzled == GetSwizzleSrcs(I, Lane);
2226     };
2227   } else if (NumShuffleLanes >= NumConstantLanes &&
2228              NumShuffleLanes >= NumSplatLanes) {
2229     size_t DestLaneSize = VecT.getVectorElementType().getFixedSizeInBits() / 8;
2230     size_t DestLaneCount = VecT.getVectorNumElements();
2231     size_t Scale1 = 1;
2232     size_t Scale2 = 1;
2233     SDValue Src1 = ShuffleSrc1;
2234     SDValue Src2 = ShuffleSrc2 ? ShuffleSrc2 : DAG.getUNDEF(VecT);
2235     if (Src1.getValueType() != VecT) {
2236       size_t LaneSize =
2237           Src1.getValueType().getVectorElementType().getFixedSizeInBits() / 8;
2238       assert(LaneSize > DestLaneSize);
2239       Scale1 = LaneSize / DestLaneSize;
2240       Src1 = DAG.getBitcast(VecT, Src1);
2241     }
2242     if (Src2.getValueType() != VecT) {
2243       size_t LaneSize =
2244           Src2.getValueType().getVectorElementType().getFixedSizeInBits() / 8;
2245       assert(LaneSize > DestLaneSize);
2246       Scale2 = LaneSize / DestLaneSize;
2247       Src2 = DAG.getBitcast(VecT, Src2);
2248     }
2249 
2250     int Mask[16];
2251     assert(DestLaneCount <= 16);
2252     for (size_t I = 0; I < DestLaneCount; ++I) {
2253       const SDValue &Lane = Op->getOperand(I);
2254       SDValue Src = GetShuffleSrc(Lane);
2255       if (Src == ShuffleSrc1) {
2256         Mask[I] = Lane->getConstantOperandVal(1) * Scale1;
2257       } else if (Src && Src == ShuffleSrc2) {
2258         Mask[I] = DestLaneCount + Lane->getConstantOperandVal(1) * Scale2;
2259       } else {
2260         Mask[I] = -1;
2261       }
2262     }
2263     ArrayRef<int> MaskRef(Mask, DestLaneCount);
2264     Result = DAG.getVectorShuffle(VecT, DL, Src1, Src2, MaskRef);
2265     IsLaneConstructed = [&](size_t, const SDValue &Lane) {
2266       auto Src = GetShuffleSrc(Lane);
2267       return Src == ShuffleSrc1 || (Src && Src == ShuffleSrc2);
2268     };
2269   } else if (NumConstantLanes >= NumSplatLanes) {
2270     SmallVector<SDValue, 16> ConstLanes;
2271     for (const SDValue &Lane : Op->op_values()) {
2272       if (IsConstant(Lane)) {
2273         // Values may need to be fixed so that they will sign extend to be
2274         // within the expected range during ISel. Check whether the value is in
2275         // bounds based on the lane bit width and if it is out of bounds, lop
2276         // off the extra bits and subtract 2^n to reflect giving the high bit
2277         // value -2^(n-1) rather than +2^(n-1). Skip the i64 case because it
2278         // cannot possibly be out of range.
2279         auto *Const = dyn_cast<ConstantSDNode>(Lane.getNode());
2280         int64_t Val = Const ? Const->getSExtValue() : 0;
2281         uint64_t LaneBits = 128 / Lanes;
2282         assert((LaneBits == 64 || Val >= -(1ll << (LaneBits - 1))) &&
2283                "Unexpected out of bounds negative value");
2284         if (Const && LaneBits != 64 && Val > (1ll << (LaneBits - 1)) - 1) {
2285           uint64_t Mask = (1ll << LaneBits) - 1;
2286           auto NewVal = (((uint64_t)Val & Mask) - (1ll << LaneBits)) & Mask;
2287           ConstLanes.push_back(DAG.getConstant(NewVal, SDLoc(Lane), LaneT));
2288         } else {
2289           ConstLanes.push_back(Lane);
2290         }
2291       } else if (LaneT.isFloatingPoint()) {
2292         ConstLanes.push_back(DAG.getConstantFP(0, DL, LaneT));
2293       } else {
2294         ConstLanes.push_back(DAG.getConstant(0, DL, LaneT));
2295       }
2296     }
2297     Result = DAG.getBuildVector(VecT, DL, ConstLanes);
2298     IsLaneConstructed = [&IsConstant](size_t _, const SDValue &Lane) {
2299       return IsConstant(Lane);
2300     };
2301   } else {
2302     size_t DestLaneSize = VecT.getVectorElementType().getFixedSizeInBits();
2303     if (NumSplatLanes == 1 && Op->getOperand(0) == SplatValue &&
2304         (DestLaneSize == 32 || DestLaneSize == 64)) {
2305       // Could be selected to load_zero.
2306       Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecT, SplatValue);
2307     } else {
2308       // Use a splat (which might be selected as a load splat)
2309       Result = DAG.getSplatBuildVector(VecT, DL, SplatValue);
2310     }
2311     IsLaneConstructed = [&SplatValue](size_t _, const SDValue &Lane) {
2312       return Lane == SplatValue;
2313     };
2314   }
2315 
2316   assert(Result);
2317   assert(IsLaneConstructed);
2318 
2319   // Add replace_lane instructions for any unhandled values
2320   for (size_t I = 0; I < Lanes; ++I) {
2321     const SDValue &Lane = Op->getOperand(I);
2322     if (!Lane.isUndef() && !IsLaneConstructed(I, Lane))
2323       Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VecT, Result, Lane,
2324                            DAG.getConstant(I, DL, MVT::i32));
2325   }
2326 
2327   return Result;
2328 }
2329 
2330 SDValue
2331 WebAssemblyTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
2332                                                SelectionDAG &DAG) const {
2333   SDLoc DL(Op);
2334   ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Op.getNode())->getMask();
2335   MVT VecType = Op.getOperand(0).getSimpleValueType();
2336   assert(VecType.is128BitVector() && "Unexpected shuffle vector type");
2337   size_t LaneBytes = VecType.getVectorElementType().getSizeInBits() / 8;
2338 
2339   // Space for two vector args and sixteen mask indices
2340   SDValue Ops[18];
2341   size_t OpIdx = 0;
2342   Ops[OpIdx++] = Op.getOperand(0);
2343   Ops[OpIdx++] = Op.getOperand(1);
2344 
2345   // Expand mask indices to byte indices and materialize them as operands
2346   for (int M : Mask) {
2347     for (size_t J = 0; J < LaneBytes; ++J) {
2348       // Lower undefs (represented by -1 in mask) to {0..J}, which use a
2349       // whole lane of vector input, to allow further reduction at VM. E.g.
2350       // match an 8x16 byte shuffle to an equivalent cheaper 32x4 shuffle.
2351       uint64_t ByteIndex = M == -1 ? J : (uint64_t)M * LaneBytes + J;
2352       Ops[OpIdx++] = DAG.getConstant(ByteIndex, DL, MVT::i32);
2353     }
2354   }
2355 
2356   return DAG.getNode(WebAssemblyISD::SHUFFLE, DL, Op.getValueType(), Ops);
2357 }
2358 
2359 SDValue WebAssemblyTargetLowering::LowerSETCC(SDValue Op,
2360                                               SelectionDAG &DAG) const {
2361   SDLoc DL(Op);
2362   // The legalizer does not know how to expand the unsupported comparison modes
2363   // of i64x2 vectors, so we manually unroll them here.
2364   assert(Op->getOperand(0)->getSimpleValueType(0) == MVT::v2i64);
2365   SmallVector<SDValue, 2> LHS, RHS;
2366   DAG.ExtractVectorElements(Op->getOperand(0), LHS);
2367   DAG.ExtractVectorElements(Op->getOperand(1), RHS);
2368   const SDValue &CC = Op->getOperand(2);
2369   auto MakeLane = [&](unsigned I) {
2370     return DAG.getNode(ISD::SELECT_CC, DL, MVT::i64, LHS[I], RHS[I],
2371                        DAG.getConstant(uint64_t(-1), DL, MVT::i64),
2372                        DAG.getConstant(uint64_t(0), DL, MVT::i64), CC);
2373   };
2374   return DAG.getBuildVector(Op->getValueType(0), DL,
2375                             {MakeLane(0), MakeLane(1)});
2376 }
2377 
2378 SDValue
2379 WebAssemblyTargetLowering::LowerAccessVectorElement(SDValue Op,
2380                                                     SelectionDAG &DAG) const {
2381   // Allow constant lane indices, expand variable lane indices
2382   SDNode *IdxNode = Op.getOperand(Op.getNumOperands() - 1).getNode();
2383   if (isa<ConstantSDNode>(IdxNode)) {
2384     // Ensure the index type is i32 to match the tablegen patterns
2385     uint64_t Idx = IdxNode->getAsZExtVal();
2386     SmallVector<SDValue, 3> Ops(Op.getNode()->ops());
2387     Ops[Op.getNumOperands() - 1] =
2388         DAG.getConstant(Idx, SDLoc(IdxNode), MVT::i32);
2389     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(), Ops);
2390   }
2391   // Perform default expansion
2392   return SDValue();
2393 }
2394 
2395 static SDValue unrollVectorShift(SDValue Op, SelectionDAG &DAG) {
2396   EVT LaneT = Op.getSimpleValueType().getVectorElementType();
2397   // 32-bit and 64-bit unrolled shifts will have proper semantics
2398   if (LaneT.bitsGE(MVT::i32))
2399     return DAG.UnrollVectorOp(Op.getNode());
2400   // Otherwise mask the shift value to get proper semantics from 32-bit shift
2401   SDLoc DL(Op);
2402   size_t NumLanes = Op.getSimpleValueType().getVectorNumElements();
2403   SDValue Mask = DAG.getConstant(LaneT.getSizeInBits() - 1, DL, MVT::i32);
2404   unsigned ShiftOpcode = Op.getOpcode();
2405   SmallVector<SDValue, 16> ShiftedElements;
2406   DAG.ExtractVectorElements(Op.getOperand(0), ShiftedElements, 0, 0, MVT::i32);
2407   SmallVector<SDValue, 16> ShiftElements;
2408   DAG.ExtractVectorElements(Op.getOperand(1), ShiftElements, 0, 0, MVT::i32);
2409   SmallVector<SDValue, 16> UnrolledOps;
2410   for (size_t i = 0; i < NumLanes; ++i) {
2411     SDValue MaskedShiftValue =
2412         DAG.getNode(ISD::AND, DL, MVT::i32, ShiftElements[i], Mask);
2413     SDValue ShiftedValue = ShiftedElements[i];
2414     if (ShiftOpcode == ISD::SRA)
2415       ShiftedValue = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i32,
2416                                  ShiftedValue, DAG.getValueType(LaneT));
2417     UnrolledOps.push_back(
2418         DAG.getNode(ShiftOpcode, DL, MVT::i32, ShiftedValue, MaskedShiftValue));
2419   }
2420   return DAG.getBuildVector(Op.getValueType(), DL, UnrolledOps);
2421 }
2422 
2423 SDValue WebAssemblyTargetLowering::LowerShift(SDValue Op,
2424                                               SelectionDAG &DAG) const {
2425   SDLoc DL(Op);
2426 
2427   // Only manually lower vector shifts
2428   assert(Op.getSimpleValueType().isVector());
2429 
2430   uint64_t LaneBits = Op.getValueType().getScalarSizeInBits();
2431   auto ShiftVal = Op.getOperand(1);
2432 
2433   // Try to skip bitmask operation since it is implied inside shift instruction
2434   auto SkipImpliedMask = [](SDValue MaskOp, uint64_t MaskBits) {
2435     if (MaskOp.getOpcode() != ISD::AND)
2436       return MaskOp;
2437     SDValue LHS = MaskOp.getOperand(0);
2438     SDValue RHS = MaskOp.getOperand(1);
2439     if (MaskOp.getValueType().isVector()) {
2440       APInt MaskVal;
2441       if (!ISD::isConstantSplatVector(RHS.getNode(), MaskVal))
2442         std::swap(LHS, RHS);
2443 
2444       if (ISD::isConstantSplatVector(RHS.getNode(), MaskVal) &&
2445           MaskVal == MaskBits)
2446         MaskOp = LHS;
2447     } else {
2448       if (!isa<ConstantSDNode>(RHS.getNode()))
2449         std::swap(LHS, RHS);
2450 
2451       auto ConstantRHS = dyn_cast<ConstantSDNode>(RHS.getNode());
2452       if (ConstantRHS && ConstantRHS->getAPIntValue() == MaskBits)
2453         MaskOp = LHS;
2454     }
2455 
2456     return MaskOp;
2457   };
2458 
2459   // Skip vector and operation
2460   ShiftVal = SkipImpliedMask(ShiftVal, LaneBits - 1);
2461   ShiftVal = DAG.getSplatValue(ShiftVal);
2462   if (!ShiftVal)
2463     return unrollVectorShift(Op, DAG);
2464 
2465   // Skip scalar and operation
2466   ShiftVal = SkipImpliedMask(ShiftVal, LaneBits - 1);
2467   // Use anyext because none of the high bits can affect the shift
2468   ShiftVal = DAG.getAnyExtOrTrunc(ShiftVal, DL, MVT::i32);
2469 
2470   unsigned Opcode;
2471   switch (Op.getOpcode()) {
2472   case ISD::SHL:
2473     Opcode = WebAssemblyISD::VEC_SHL;
2474     break;
2475   case ISD::SRA:
2476     Opcode = WebAssemblyISD::VEC_SHR_S;
2477     break;
2478   case ISD::SRL:
2479     Opcode = WebAssemblyISD::VEC_SHR_U;
2480     break;
2481   default:
2482     llvm_unreachable("unexpected opcode");
2483   }
2484 
2485   return DAG.getNode(Opcode, DL, Op.getValueType(), Op.getOperand(0), ShiftVal);
2486 }
2487 
2488 SDValue WebAssemblyTargetLowering::LowerFP_TO_INT_SAT(SDValue Op,
2489                                                       SelectionDAG &DAG) const {
2490   SDLoc DL(Op);
2491   EVT ResT = Op.getValueType();
2492   EVT SatVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
2493 
2494   if ((ResT == MVT::i32 || ResT == MVT::i64) &&
2495       (SatVT == MVT::i32 || SatVT == MVT::i64))
2496     return Op;
2497 
2498   if (ResT == MVT::v4i32 && SatVT == MVT::i32)
2499     return Op;
2500 
2501   if (ResT == MVT::v8i16 && SatVT == MVT::i16)
2502     return Op;
2503 
2504   return SDValue();
2505 }
2506 
2507 //===----------------------------------------------------------------------===//
2508 //   Custom DAG combine hooks
2509 //===----------------------------------------------------------------------===//
2510 static SDValue
2511 performVECTOR_SHUFFLECombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
2512   auto &DAG = DCI.DAG;
2513   auto Shuffle = cast<ShuffleVectorSDNode>(N);
2514 
2515   // Hoist vector bitcasts that don't change the number of lanes out of unary
2516   // shuffles, where they are less likely to get in the way of other combines.
2517   // (shuffle (vNxT1 (bitcast (vNxT0 x))), undef, mask) ->
2518   //  (vNxT1 (bitcast (vNxT0 (shuffle x, undef, mask))))
2519   SDValue Bitcast = N->getOperand(0);
2520   if (Bitcast.getOpcode() != ISD::BITCAST)
2521     return SDValue();
2522   if (!N->getOperand(1).isUndef())
2523     return SDValue();
2524   SDValue CastOp = Bitcast.getOperand(0);
2525   EVT SrcType = CastOp.getValueType();
2526   EVT DstType = Bitcast.getValueType();
2527   if (!SrcType.is128BitVector() ||
2528       SrcType.getVectorNumElements() != DstType.getVectorNumElements())
2529     return SDValue();
2530   SDValue NewShuffle = DAG.getVectorShuffle(
2531       SrcType, SDLoc(N), CastOp, DAG.getUNDEF(SrcType), Shuffle->getMask());
2532   return DAG.getBitcast(DstType, NewShuffle);
2533 }
2534 
2535 /// Convert ({u,s}itofp vec) --> ({u,s}itofp ({s,z}ext vec)) so it doesn't get
2536 /// split up into scalar instructions during legalization, and the vector
2537 /// extending instructions are selected in performVectorExtendCombine below.
2538 static SDValue
2539 performVectorExtendToFPCombine(SDNode *N,
2540                                TargetLowering::DAGCombinerInfo &DCI) {
2541   auto &DAG = DCI.DAG;
2542   assert(N->getOpcode() == ISD::UINT_TO_FP ||
2543          N->getOpcode() == ISD::SINT_TO_FP);
2544 
2545   EVT InVT = N->getOperand(0)->getValueType(0);
2546   EVT ResVT = N->getValueType(0);
2547   MVT ExtVT;
2548   if (ResVT == MVT::v4f32 && (InVT == MVT::v4i16 || InVT == MVT::v4i8))
2549     ExtVT = MVT::v4i32;
2550   else if (ResVT == MVT::v2f64 && (InVT == MVT::v2i16 || InVT == MVT::v2i8))
2551     ExtVT = MVT::v2i32;
2552   else
2553     return SDValue();
2554 
2555   unsigned Op =
2556       N->getOpcode() == ISD::UINT_TO_FP ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
2557   SDValue Conv = DAG.getNode(Op, SDLoc(N), ExtVT, N->getOperand(0));
2558   return DAG.getNode(N->getOpcode(), SDLoc(N), ResVT, Conv);
2559 }
2560 
2561 static SDValue
2562 performVectorExtendCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
2563   auto &DAG = DCI.DAG;
2564   assert(N->getOpcode() == ISD::SIGN_EXTEND ||
2565          N->getOpcode() == ISD::ZERO_EXTEND);
2566 
2567   // Combine ({s,z}ext (extract_subvector src, i)) into a widening operation if
2568   // possible before the extract_subvector can be expanded.
2569   auto Extract = N->getOperand(0);
2570   if (Extract.getOpcode() != ISD::EXTRACT_SUBVECTOR)
2571     return SDValue();
2572   auto Source = Extract.getOperand(0);
2573   auto *IndexNode = dyn_cast<ConstantSDNode>(Extract.getOperand(1));
2574   if (IndexNode == nullptr)
2575     return SDValue();
2576   auto Index = IndexNode->getZExtValue();
2577 
2578   // Only v8i8, v4i16, and v2i32 extracts can be widened, and only if the
2579   // extracted subvector is the low or high half of its source.
2580   EVT ResVT = N->getValueType(0);
2581   if (ResVT == MVT::v8i16) {
2582     if (Extract.getValueType() != MVT::v8i8 ||
2583         Source.getValueType() != MVT::v16i8 || (Index != 0 && Index != 8))
2584       return SDValue();
2585   } else if (ResVT == MVT::v4i32) {
2586     if (Extract.getValueType() != MVT::v4i16 ||
2587         Source.getValueType() != MVT::v8i16 || (Index != 0 && Index != 4))
2588       return SDValue();
2589   } else if (ResVT == MVT::v2i64) {
2590     if (Extract.getValueType() != MVT::v2i32 ||
2591         Source.getValueType() != MVT::v4i32 || (Index != 0 && Index != 2))
2592       return SDValue();
2593   } else {
2594     return SDValue();
2595   }
2596 
2597   bool IsSext = N->getOpcode() == ISD::SIGN_EXTEND;
2598   bool IsLow = Index == 0;
2599 
2600   unsigned Op = IsSext ? (IsLow ? WebAssemblyISD::EXTEND_LOW_S
2601                                 : WebAssemblyISD::EXTEND_HIGH_S)
2602                        : (IsLow ? WebAssemblyISD::EXTEND_LOW_U
2603                                 : WebAssemblyISD::EXTEND_HIGH_U);
2604 
2605   return DAG.getNode(Op, SDLoc(N), ResVT, Source);
2606 }
2607 
2608 static SDValue
2609 performVectorTruncZeroCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
2610   auto &DAG = DCI.DAG;
2611 
2612   auto GetWasmConversionOp = [](unsigned Op) {
2613     switch (Op) {
2614     case ISD::FP_TO_SINT_SAT:
2615       return WebAssemblyISD::TRUNC_SAT_ZERO_S;
2616     case ISD::FP_TO_UINT_SAT:
2617       return WebAssemblyISD::TRUNC_SAT_ZERO_U;
2618     case ISD::FP_ROUND:
2619       return WebAssemblyISD::DEMOTE_ZERO;
2620     }
2621     llvm_unreachable("unexpected op");
2622   };
2623 
2624   auto IsZeroSplat = [](SDValue SplatVal) {
2625     auto *Splat = dyn_cast<BuildVectorSDNode>(SplatVal.getNode());
2626     APInt SplatValue, SplatUndef;
2627     unsigned SplatBitSize;
2628     bool HasAnyUndefs;
2629     // Endianness doesn't matter in this context because we are looking for
2630     // an all-zero value.
2631     return Splat &&
2632            Splat->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
2633                                   HasAnyUndefs) &&
2634            SplatValue == 0;
2635   };
2636 
2637   if (N->getOpcode() == ISD::CONCAT_VECTORS) {
2638     // Combine this:
2639     //
2640     //   (concat_vectors (v2i32 (fp_to_{s,u}int_sat $x, 32)), (v2i32 (splat 0)))
2641     //
2642     // into (i32x4.trunc_sat_f64x2_zero_{s,u} $x).
2643     //
2644     // Or this:
2645     //
2646     //   (concat_vectors (v2f32 (fp_round (v2f64 $x))), (v2f32 (splat 0)))
2647     //
2648     // into (f32x4.demote_zero_f64x2 $x).
2649     EVT ResVT;
2650     EVT ExpectedConversionType;
2651     auto Conversion = N->getOperand(0);
2652     auto ConversionOp = Conversion.getOpcode();
2653     switch (ConversionOp) {
2654     case ISD::FP_TO_SINT_SAT:
2655     case ISD::FP_TO_UINT_SAT:
2656       ResVT = MVT::v4i32;
2657       ExpectedConversionType = MVT::v2i32;
2658       break;
2659     case ISD::FP_ROUND:
2660       ResVT = MVT::v4f32;
2661       ExpectedConversionType = MVT::v2f32;
2662       break;
2663     default:
2664       return SDValue();
2665     }
2666 
2667     if (N->getValueType(0) != ResVT)
2668       return SDValue();
2669 
2670     if (Conversion.getValueType() != ExpectedConversionType)
2671       return SDValue();
2672 
2673     auto Source = Conversion.getOperand(0);
2674     if (Source.getValueType() != MVT::v2f64)
2675       return SDValue();
2676 
2677     if (!IsZeroSplat(N->getOperand(1)) ||
2678         N->getOperand(1).getValueType() != ExpectedConversionType)
2679       return SDValue();
2680 
2681     unsigned Op = GetWasmConversionOp(ConversionOp);
2682     return DAG.getNode(Op, SDLoc(N), ResVT, Source);
2683   }
2684 
2685   // Combine this:
2686   //
2687   //   (fp_to_{s,u}int_sat (concat_vectors $x, (v2f64 (splat 0))), 32)
2688   //
2689   // into (i32x4.trunc_sat_f64x2_zero_{s,u} $x).
2690   //
2691   // Or this:
2692   //
2693   //   (v4f32 (fp_round (concat_vectors $x, (v2f64 (splat 0)))))
2694   //
2695   // into (f32x4.demote_zero_f64x2 $x).
2696   EVT ResVT;
2697   auto ConversionOp = N->getOpcode();
2698   switch (ConversionOp) {
2699   case ISD::FP_TO_SINT_SAT:
2700   case ISD::FP_TO_UINT_SAT:
2701     ResVT = MVT::v4i32;
2702     break;
2703   case ISD::FP_ROUND:
2704     ResVT = MVT::v4f32;
2705     break;
2706   default:
2707     llvm_unreachable("unexpected op");
2708   }
2709 
2710   if (N->getValueType(0) != ResVT)
2711     return SDValue();
2712 
2713   auto Concat = N->getOperand(0);
2714   if (Concat.getValueType() != MVT::v4f64)
2715     return SDValue();
2716 
2717   auto Source = Concat.getOperand(0);
2718   if (Source.getValueType() != MVT::v2f64)
2719     return SDValue();
2720 
2721   if (!IsZeroSplat(Concat.getOperand(1)) ||
2722       Concat.getOperand(1).getValueType() != MVT::v2f64)
2723     return SDValue();
2724 
2725   unsigned Op = GetWasmConversionOp(ConversionOp);
2726   return DAG.getNode(Op, SDLoc(N), ResVT, Source);
2727 }
2728 
2729 // Helper to extract VectorWidth bits from Vec, starting from IdxVal.
2730 static SDValue extractSubVector(SDValue Vec, unsigned IdxVal, SelectionDAG &DAG,
2731                                 const SDLoc &DL, unsigned VectorWidth) {
2732   EVT VT = Vec.getValueType();
2733   EVT ElVT = VT.getVectorElementType();
2734   unsigned Factor = VT.getSizeInBits() / VectorWidth;
2735   EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
2736                                   VT.getVectorNumElements() / Factor);
2737 
2738   // Extract the relevant VectorWidth bits.  Generate an EXTRACT_SUBVECTOR
2739   unsigned ElemsPerChunk = VectorWidth / ElVT.getSizeInBits();
2740   assert(isPowerOf2_32(ElemsPerChunk) && "Elements per chunk not power of 2");
2741 
2742   // This is the index of the first element of the VectorWidth-bit chunk
2743   // we want. Since ElemsPerChunk is a power of 2 just need to clear bits.
2744   IdxVal &= ~(ElemsPerChunk - 1);
2745 
2746   // If the input is a buildvector just emit a smaller one.
2747   if (Vec.getOpcode() == ISD::BUILD_VECTOR)
2748     return DAG.getBuildVector(ResultVT, DL,
2749                               Vec->ops().slice(IdxVal, ElemsPerChunk));
2750 
2751   SDValue VecIdx = DAG.getIntPtrConstant(IdxVal, DL);
2752   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ResultVT, Vec, VecIdx);
2753 }
2754 
2755 // Helper to recursively truncate vector elements in half with NARROW_U. DstVT
2756 // is the expected destination value type after recursion. In is the initial
2757 // input. Note that the input should have enough leading zero bits to prevent
2758 // NARROW_U from saturating results.
2759 static SDValue truncateVectorWithNARROW(EVT DstVT, SDValue In, const SDLoc &DL,
2760                                         SelectionDAG &DAG) {
2761   EVT SrcVT = In.getValueType();
2762 
2763   // No truncation required, we might get here due to recursive calls.
2764   if (SrcVT == DstVT)
2765     return In;
2766 
2767   unsigned SrcSizeInBits = SrcVT.getSizeInBits();
2768   unsigned NumElems = SrcVT.getVectorNumElements();
2769   if (!isPowerOf2_32(NumElems))
2770     return SDValue();
2771   assert(DstVT.getVectorNumElements() == NumElems && "Illegal truncation");
2772   assert(SrcSizeInBits > DstVT.getSizeInBits() && "Illegal truncation");
2773 
2774   LLVMContext &Ctx = *DAG.getContext();
2775   EVT PackedSVT = EVT::getIntegerVT(Ctx, SrcVT.getScalarSizeInBits() / 2);
2776 
2777   // Narrow to the largest type possible:
2778   // vXi64/vXi32 -> i16x8.narrow_i32x4_u and vXi16 -> i8x16.narrow_i16x8_u.
2779   EVT InVT = MVT::i16, OutVT = MVT::i8;
2780   if (SrcVT.getScalarSizeInBits() > 16) {
2781     InVT = MVT::i32;
2782     OutVT = MVT::i16;
2783   }
2784   unsigned SubSizeInBits = SrcSizeInBits / 2;
2785   InVT = EVT::getVectorVT(Ctx, InVT, SubSizeInBits / InVT.getSizeInBits());
2786   OutVT = EVT::getVectorVT(Ctx, OutVT, SubSizeInBits / OutVT.getSizeInBits());
2787 
2788   // Split lower/upper subvectors.
2789   SDValue Lo = extractSubVector(In, 0, DAG, DL, SubSizeInBits);
2790   SDValue Hi = extractSubVector(In, NumElems / 2, DAG, DL, SubSizeInBits);
2791 
2792   // 256bit -> 128bit truncate - Narrow lower/upper 128-bit subvectors.
2793   if (SrcVT.is256BitVector() && DstVT.is128BitVector()) {
2794     Lo = DAG.getBitcast(InVT, Lo);
2795     Hi = DAG.getBitcast(InVT, Hi);
2796     SDValue Res = DAG.getNode(WebAssemblyISD::NARROW_U, DL, OutVT, Lo, Hi);
2797     return DAG.getBitcast(DstVT, Res);
2798   }
2799 
2800   // Recursively narrow lower/upper subvectors, concat result and narrow again.
2801   EVT PackedVT = EVT::getVectorVT(Ctx, PackedSVT, NumElems / 2);
2802   Lo = truncateVectorWithNARROW(PackedVT, Lo, DL, DAG);
2803   Hi = truncateVectorWithNARROW(PackedVT, Hi, DL, DAG);
2804 
2805   PackedVT = EVT::getVectorVT(Ctx, PackedSVT, NumElems);
2806   SDValue Res = DAG.getNode(ISD::CONCAT_VECTORS, DL, PackedVT, Lo, Hi);
2807   return truncateVectorWithNARROW(DstVT, Res, DL, DAG);
2808 }
2809 
2810 static SDValue performTruncateCombine(SDNode *N,
2811                                       TargetLowering::DAGCombinerInfo &DCI) {
2812   auto &DAG = DCI.DAG;
2813 
2814   SDValue In = N->getOperand(0);
2815   EVT InVT = In.getValueType();
2816   if (!InVT.isSimple())
2817     return SDValue();
2818 
2819   EVT OutVT = N->getValueType(0);
2820   if (!OutVT.isVector())
2821     return SDValue();
2822 
2823   EVT OutSVT = OutVT.getVectorElementType();
2824   EVT InSVT = InVT.getVectorElementType();
2825   // Currently only cover truncate to v16i8 or v8i16.
2826   if (!((InSVT == MVT::i16 || InSVT == MVT::i32 || InSVT == MVT::i64) &&
2827         (OutSVT == MVT::i8 || OutSVT == MVT::i16) && OutVT.is128BitVector()))
2828     return SDValue();
2829 
2830   SDLoc DL(N);
2831   APInt Mask = APInt::getLowBitsSet(InVT.getScalarSizeInBits(),
2832                                     OutVT.getScalarSizeInBits());
2833   In = DAG.getNode(ISD::AND, DL, InVT, In, DAG.getConstant(Mask, DL, InVT));
2834   return truncateVectorWithNARROW(OutVT, In, DL, DAG);
2835 }
2836 
2837 static SDValue performBitcastCombine(SDNode *N,
2838                                      TargetLowering::DAGCombinerInfo &DCI) {
2839   auto &DAG = DCI.DAG;
2840   SDLoc DL(N);
2841   SDValue Src = N->getOperand(0);
2842   EVT VT = N->getValueType(0);
2843   EVT SrcVT = Src.getValueType();
2844 
2845   // bitcast <N x i1> to iN
2846   //   ==> bitmask
2847   if (DCI.isBeforeLegalize() && VT.isScalarInteger() &&
2848       SrcVT.isFixedLengthVector() && SrcVT.getScalarType() == MVT::i1) {
2849     unsigned NumElts = SrcVT.getVectorNumElements();
2850     if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2851       return SDValue();
2852     EVT Width = MVT::getIntegerVT(128 / NumElts);
2853     return DAG.getZExtOrTrunc(
2854         DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, MVT::i32,
2855                     {DAG.getConstant(Intrinsic::wasm_bitmask, DL, MVT::i32),
2856                      DAG.getSExtOrTrunc(N->getOperand(0), DL,
2857                                         SrcVT.changeVectorElementType(Width))}),
2858         DL, VT);
2859   }
2860 
2861   return SDValue();
2862 }
2863 
2864 static SDValue performSETCCCombine(SDNode *N,
2865                                    TargetLowering::DAGCombinerInfo &DCI) {
2866   auto &DAG = DCI.DAG;
2867 
2868   SDValue LHS = N->getOperand(0);
2869   SDValue RHS = N->getOperand(1);
2870   ISD::CondCode Cond = cast<CondCodeSDNode>(N->getOperand(2))->get();
2871   SDLoc DL(N);
2872   EVT VT = N->getValueType(0);
2873 
2874   // setcc (iN (bitcast (vNi1 X))), 0, ne
2875   //   ==> any_true (vNi1 X)
2876   // setcc (iN (bitcast (vNi1 X))), 0, eq
2877   //   ==> xor (any_true (vNi1 X)), -1
2878   // setcc (iN (bitcast (vNi1 X))), -1, eq
2879   //   ==> all_true (vNi1 X)
2880   // setcc (iN (bitcast (vNi1 X))), -1, ne
2881   //   ==> xor (all_true (vNi1 X)), -1
2882   if (DCI.isBeforeLegalize() && VT.isScalarInteger() &&
2883       (Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
2884       (isNullConstant(RHS) || isAllOnesConstant(RHS)) &&
2885       LHS->getOpcode() == ISD::BITCAST) {
2886     EVT FromVT = LHS->getOperand(0).getValueType();
2887     if (FromVT.isFixedLengthVector() &&
2888         FromVT.getVectorElementType() == MVT::i1) {
2889       int Intrin = isNullConstant(RHS) ? Intrinsic::wasm_anytrue
2890                                        : Intrinsic::wasm_alltrue;
2891       unsigned NumElts = FromVT.getVectorNumElements();
2892       if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2893         return SDValue();
2894       EVT Width = MVT::getIntegerVT(128 / NumElts);
2895       SDValue Ret = DAG.getZExtOrTrunc(
2896           DAG.getNode(
2897               ISD::INTRINSIC_WO_CHAIN, DL, MVT::i32,
2898               {DAG.getConstant(Intrin, DL, MVT::i32),
2899                DAG.getSExtOrTrunc(LHS->getOperand(0), DL,
2900                                   FromVT.changeVectorElementType(Width))}),
2901           DL, MVT::i1);
2902       if ((isNullConstant(RHS) && (Cond == ISD::SETEQ)) ||
2903           (isAllOnesConstant(RHS) && (Cond == ISD::SETNE))) {
2904         Ret = DAG.getNOT(DL, Ret, MVT::i1);
2905       }
2906       return DAG.getZExtOrTrunc(Ret, DL, VT);
2907     }
2908   }
2909 
2910   return SDValue();
2911 }
2912 
2913 SDValue
2914 WebAssemblyTargetLowering::PerformDAGCombine(SDNode *N,
2915                                              DAGCombinerInfo &DCI) const {
2916   switch (N->getOpcode()) {
2917   default:
2918     return SDValue();
2919   case ISD::BITCAST:
2920     return performBitcastCombine(N, DCI);
2921   case ISD::SETCC:
2922     return performSETCCCombine(N, DCI);
2923   case ISD::VECTOR_SHUFFLE:
2924     return performVECTOR_SHUFFLECombine(N, DCI);
2925   case ISD::SIGN_EXTEND:
2926   case ISD::ZERO_EXTEND:
2927     return performVectorExtendCombine(N, DCI);
2928   case ISD::UINT_TO_FP:
2929   case ISD::SINT_TO_FP:
2930     return performVectorExtendToFPCombine(N, DCI);
2931   case ISD::FP_TO_SINT_SAT:
2932   case ISD::FP_TO_UINT_SAT:
2933   case ISD::FP_ROUND:
2934   case ISD::CONCAT_VECTORS:
2935     return performVectorTruncZeroCombine(N, DCI);
2936   case ISD::TRUNCATE:
2937     return performTruncateCombine(N, DCI);
2938   }
2939 }
2940