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