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