xref: /freebsd/contrib/llvm-project/llvm/lib/Target/WebAssembly/WebAssemblyISelLowering.cpp (revision 349cc55c9796c4596a5b9904cd3281af295f878f)
10b57cec5SDimitry Andric //=- WebAssemblyISelLowering.cpp - WebAssembly DAG Lowering Implementation -==//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric ///
90b57cec5SDimitry Andric /// \file
100b57cec5SDimitry Andric /// This file implements the WebAssemblyTargetLowering class.
110b57cec5SDimitry Andric ///
120b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
130b57cec5SDimitry Andric 
140b57cec5SDimitry Andric #include "WebAssemblyISelLowering.h"
150b57cec5SDimitry Andric #include "MCTargetDesc/WebAssemblyMCTargetDesc.h"
16fe6060f1SDimitry Andric #include "Utils/WebAssemblyTypeUtilities.h"
17fe6060f1SDimitry Andric #include "Utils/WebAssemblyUtilities.h"
180b57cec5SDimitry Andric #include "WebAssemblyMachineFunctionInfo.h"
190b57cec5SDimitry Andric #include "WebAssemblySubtarget.h"
200b57cec5SDimitry Andric #include "WebAssemblyTargetMachine.h"
210b57cec5SDimitry Andric #include "llvm/CodeGen/CallingConvLower.h"
220b57cec5SDimitry Andric #include "llvm/CodeGen/MachineInstrBuilder.h"
230b57cec5SDimitry Andric #include "llvm/CodeGen/MachineJumpTableInfo.h"
240b57cec5SDimitry Andric #include "llvm/CodeGen/MachineModuleInfo.h"
250b57cec5SDimitry Andric #include "llvm/CodeGen/MachineRegisterInfo.h"
260b57cec5SDimitry Andric #include "llvm/CodeGen/SelectionDAG.h"
27fe6060f1SDimitry Andric #include "llvm/CodeGen/SelectionDAGNodes.h"
280b57cec5SDimitry Andric #include "llvm/IR/DiagnosticInfo.h"
290b57cec5SDimitry Andric #include "llvm/IR/DiagnosticPrinter.h"
300b57cec5SDimitry Andric #include "llvm/IR/Function.h"
310b57cec5SDimitry Andric #include "llvm/IR/Intrinsics.h"
32480093f4SDimitry Andric #include "llvm/IR/IntrinsicsWebAssembly.h"
330b57cec5SDimitry Andric #include "llvm/Support/Debug.h"
340b57cec5SDimitry Andric #include "llvm/Support/ErrorHandling.h"
35*349cc55cSDimitry Andric #include "llvm/Support/KnownBits.h"
36e8d8bef9SDimitry Andric #include "llvm/Support/MathExtras.h"
370b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h"
380b57cec5SDimitry Andric #include "llvm/Target/TargetOptions.h"
390b57cec5SDimitry Andric using namespace llvm;
400b57cec5SDimitry Andric 
410b57cec5SDimitry Andric #define DEBUG_TYPE "wasm-lower"
420b57cec5SDimitry Andric 
430b57cec5SDimitry Andric WebAssemblyTargetLowering::WebAssemblyTargetLowering(
440b57cec5SDimitry Andric     const TargetMachine &TM, const WebAssemblySubtarget &STI)
450b57cec5SDimitry Andric     : TargetLowering(TM), Subtarget(&STI) {
460b57cec5SDimitry Andric   auto MVTPtr = Subtarget->hasAddr64() ? MVT::i64 : MVT::i32;
470b57cec5SDimitry Andric 
480b57cec5SDimitry Andric   // Booleans always contain 0 or 1.
490b57cec5SDimitry Andric   setBooleanContents(ZeroOrOneBooleanContent);
500b57cec5SDimitry Andric   // Except in SIMD vectors
510b57cec5SDimitry Andric   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
520b57cec5SDimitry Andric   // We don't know the microarchitecture here, so just reduce register pressure.
530b57cec5SDimitry Andric   setSchedulingPreference(Sched::RegPressure);
540b57cec5SDimitry Andric   // Tell ISel that we have a stack pointer.
550b57cec5SDimitry Andric   setStackPointerRegisterToSaveRestore(
560b57cec5SDimitry Andric       Subtarget->hasAddr64() ? WebAssembly::SP64 : WebAssembly::SP32);
570b57cec5SDimitry Andric   // Set up the register classes.
580b57cec5SDimitry Andric   addRegisterClass(MVT::i32, &WebAssembly::I32RegClass);
590b57cec5SDimitry Andric   addRegisterClass(MVT::i64, &WebAssembly::I64RegClass);
600b57cec5SDimitry Andric   addRegisterClass(MVT::f32, &WebAssembly::F32RegClass);
610b57cec5SDimitry Andric   addRegisterClass(MVT::f64, &WebAssembly::F64RegClass);
620b57cec5SDimitry Andric   if (Subtarget->hasSIMD128()) {
630b57cec5SDimitry Andric     addRegisterClass(MVT::v16i8, &WebAssembly::V128RegClass);
640b57cec5SDimitry Andric     addRegisterClass(MVT::v8i16, &WebAssembly::V128RegClass);
650b57cec5SDimitry Andric     addRegisterClass(MVT::v4i32, &WebAssembly::V128RegClass);
660b57cec5SDimitry Andric     addRegisterClass(MVT::v4f32, &WebAssembly::V128RegClass);
670b57cec5SDimitry Andric     addRegisterClass(MVT::v2i64, &WebAssembly::V128RegClass);
680b57cec5SDimitry Andric     addRegisterClass(MVT::v2f64, &WebAssembly::V128RegClass);
690b57cec5SDimitry Andric   }
70fe6060f1SDimitry Andric   if (Subtarget->hasReferenceTypes()) {
71fe6060f1SDimitry Andric     addRegisterClass(MVT::externref, &WebAssembly::EXTERNREFRegClass);
72fe6060f1SDimitry Andric     addRegisterClass(MVT::funcref, &WebAssembly::FUNCREFRegClass);
73fe6060f1SDimitry Andric   }
740b57cec5SDimitry Andric   // Compute derived properties from the register classes.
750b57cec5SDimitry Andric   computeRegisterProperties(Subtarget->getRegisterInfo());
760b57cec5SDimitry Andric 
77fe6060f1SDimitry Andric   // Transform loads and stores to pointers in address space 1 to loads and
78fe6060f1SDimitry Andric   // stores to WebAssembly global variables, outside linear memory.
79fe6060f1SDimitry Andric   for (auto T : {MVT::i32, MVT::i64, MVT::f32, MVT::f64}) {
80fe6060f1SDimitry Andric     setOperationAction(ISD::LOAD, T, Custom);
81fe6060f1SDimitry Andric     setOperationAction(ISD::STORE, T, Custom);
82fe6060f1SDimitry Andric   }
83fe6060f1SDimitry Andric   if (Subtarget->hasSIMD128()) {
84fe6060f1SDimitry Andric     for (auto T : {MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v4f32, MVT::v2i64,
85fe6060f1SDimitry Andric                    MVT::v2f64}) {
86fe6060f1SDimitry Andric       setOperationAction(ISD::LOAD, T, Custom);
87fe6060f1SDimitry Andric       setOperationAction(ISD::STORE, T, Custom);
88fe6060f1SDimitry Andric     }
89fe6060f1SDimitry Andric   }
90fe6060f1SDimitry Andric   if (Subtarget->hasReferenceTypes()) {
91*349cc55cSDimitry Andric     // We need custom load and store lowering for both externref, funcref and
92*349cc55cSDimitry Andric     // Other. The MVT::Other here represents tables of reference types.
93*349cc55cSDimitry Andric     for (auto T : {MVT::externref, MVT::funcref, MVT::Other}) {
94fe6060f1SDimitry Andric       setOperationAction(ISD::LOAD, T, Custom);
95fe6060f1SDimitry Andric       setOperationAction(ISD::STORE, T, Custom);
96fe6060f1SDimitry Andric     }
97fe6060f1SDimitry Andric   }
98fe6060f1SDimitry Andric 
990b57cec5SDimitry Andric   setOperationAction(ISD::GlobalAddress, MVTPtr, Custom);
100e8d8bef9SDimitry Andric   setOperationAction(ISD::GlobalTLSAddress, MVTPtr, Custom);
1010b57cec5SDimitry Andric   setOperationAction(ISD::ExternalSymbol, MVTPtr, Custom);
1020b57cec5SDimitry Andric   setOperationAction(ISD::JumpTable, MVTPtr, Custom);
1030b57cec5SDimitry Andric   setOperationAction(ISD::BlockAddress, MVTPtr, Custom);
1040b57cec5SDimitry Andric   setOperationAction(ISD::BRIND, MVT::Other, Custom);
1050b57cec5SDimitry Andric 
1060b57cec5SDimitry Andric   // Take the default expansion for va_arg, va_copy, and va_end. There is no
1070b57cec5SDimitry Andric   // default action for va_start, so we do that custom.
1080b57cec5SDimitry Andric   setOperationAction(ISD::VASTART, MVT::Other, Custom);
1090b57cec5SDimitry Andric   setOperationAction(ISD::VAARG, MVT::Other, Expand);
1100b57cec5SDimitry Andric   setOperationAction(ISD::VACOPY, MVT::Other, Expand);
1110b57cec5SDimitry Andric   setOperationAction(ISD::VAEND, MVT::Other, Expand);
1120b57cec5SDimitry Andric 
1130b57cec5SDimitry Andric   for (auto T : {MVT::f32, MVT::f64, MVT::v4f32, MVT::v2f64}) {
1140b57cec5SDimitry Andric     // Don't expand the floating-point types to constant pools.
1150b57cec5SDimitry Andric     setOperationAction(ISD::ConstantFP, T, Legal);
1160b57cec5SDimitry Andric     // Expand floating-point comparisons.
1170b57cec5SDimitry Andric     for (auto CC : {ISD::SETO, ISD::SETUO, ISD::SETUEQ, ISD::SETONE,
1180b57cec5SDimitry Andric                     ISD::SETULT, ISD::SETULE, ISD::SETUGT, ISD::SETUGE})
1190b57cec5SDimitry Andric       setCondCodeAction(CC, T, Expand);
1200b57cec5SDimitry Andric     // Expand floating-point library function operators.
1210b57cec5SDimitry Andric     for (auto Op :
1220b57cec5SDimitry Andric          {ISD::FSIN, ISD::FCOS, ISD::FSINCOS, ISD::FPOW, ISD::FREM, ISD::FMA})
1230b57cec5SDimitry Andric       setOperationAction(Op, T, Expand);
1240b57cec5SDimitry Andric     // Note supported floating-point library function operators that otherwise
1250b57cec5SDimitry Andric     // default to expand.
1260b57cec5SDimitry Andric     for (auto Op :
1270b57cec5SDimitry Andric          {ISD::FCEIL, ISD::FFLOOR, ISD::FTRUNC, ISD::FNEARBYINT, ISD::FRINT})
1280b57cec5SDimitry Andric       setOperationAction(Op, T, Legal);
1290b57cec5SDimitry Andric     // Support minimum and maximum, which otherwise default to expand.
1300b57cec5SDimitry Andric     setOperationAction(ISD::FMINIMUM, T, Legal);
1310b57cec5SDimitry Andric     setOperationAction(ISD::FMAXIMUM, T, Legal);
1320b57cec5SDimitry Andric     // WebAssembly currently has no builtin f16 support.
1330b57cec5SDimitry Andric     setOperationAction(ISD::FP16_TO_FP, T, Expand);
1340b57cec5SDimitry Andric     setOperationAction(ISD::FP_TO_FP16, T, Expand);
1350b57cec5SDimitry Andric     setLoadExtAction(ISD::EXTLOAD, T, MVT::f16, Expand);
1360b57cec5SDimitry Andric     setTruncStoreAction(T, MVT::f16, Expand);
1370b57cec5SDimitry Andric   }
1380b57cec5SDimitry Andric 
1390b57cec5SDimitry Andric   // Expand unavailable integer operations.
1400b57cec5SDimitry Andric   for (auto Op :
1410b57cec5SDimitry Andric        {ISD::BSWAP, ISD::SMUL_LOHI, ISD::UMUL_LOHI, ISD::MULHS, ISD::MULHU,
1420b57cec5SDimitry Andric         ISD::SDIVREM, ISD::UDIVREM, ISD::SHL_PARTS, ISD::SRA_PARTS,
1430b57cec5SDimitry Andric         ISD::SRL_PARTS, ISD::ADDC, ISD::ADDE, ISD::SUBC, ISD::SUBE}) {
1440b57cec5SDimitry Andric     for (auto T : {MVT::i32, MVT::i64})
1450b57cec5SDimitry Andric       setOperationAction(Op, T, Expand);
1460b57cec5SDimitry Andric     if (Subtarget->hasSIMD128())
1475ffd83dbSDimitry Andric       for (auto T : {MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64})
1480b57cec5SDimitry Andric         setOperationAction(Op, T, Expand);
1490b57cec5SDimitry Andric   }
1500b57cec5SDimitry Andric 
151fe6060f1SDimitry Andric   if (Subtarget->hasNontrappingFPToInt())
152fe6060f1SDimitry Andric     for (auto Op : {ISD::FP_TO_SINT_SAT, ISD::FP_TO_UINT_SAT})
153fe6060f1SDimitry Andric       for (auto T : {MVT::i32, MVT::i64})
154fe6060f1SDimitry Andric         setOperationAction(Op, T, Custom);
155fe6060f1SDimitry Andric 
1560b57cec5SDimitry Andric   // SIMD-specific configuration
1570b57cec5SDimitry Andric   if (Subtarget->hasSIMD128()) {
1585ffd83dbSDimitry Andric     // Hoist bitcasts out of shuffles
1595ffd83dbSDimitry Andric     setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1605ffd83dbSDimitry Andric 
161e8d8bef9SDimitry Andric     // Combine extends of extract_subvectors into widening ops
162e8d8bef9SDimitry Andric     setTargetDAGCombine(ISD::SIGN_EXTEND);
163e8d8bef9SDimitry Andric     setTargetDAGCombine(ISD::ZERO_EXTEND);
164e8d8bef9SDimitry Andric 
165fe6060f1SDimitry Andric     // Combine int_to_fp or fp_extend of extract_vectors and vice versa into
166fe6060f1SDimitry Andric     // conversions ops
167fe6060f1SDimitry Andric     setTargetDAGCombine(ISD::SINT_TO_FP);
168fe6060f1SDimitry Andric     setTargetDAGCombine(ISD::UINT_TO_FP);
169fe6060f1SDimitry Andric     setTargetDAGCombine(ISD::FP_EXTEND);
170fe6060f1SDimitry Andric     setTargetDAGCombine(ISD::EXTRACT_SUBVECTOR);
171fe6060f1SDimitry Andric 
172fe6060f1SDimitry Andric     // Combine fp_to_{s,u}int_sat or fp_round of concat_vectors or vice versa
173fe6060f1SDimitry Andric     // into conversion ops
174fe6060f1SDimitry Andric     setTargetDAGCombine(ISD::FP_TO_SINT_SAT);
175fe6060f1SDimitry Andric     setTargetDAGCombine(ISD::FP_TO_UINT_SAT);
176fe6060f1SDimitry Andric     setTargetDAGCombine(ISD::FP_ROUND);
177fe6060f1SDimitry Andric     setTargetDAGCombine(ISD::CONCAT_VECTORS);
178fe6060f1SDimitry Andric 
1790b57cec5SDimitry Andric     // Support saturating add for i8x16 and i16x8
1800b57cec5SDimitry Andric     for (auto Op : {ISD::SADDSAT, ISD::UADDSAT})
1810b57cec5SDimitry Andric       for (auto T : {MVT::v16i8, MVT::v8i16})
1820b57cec5SDimitry Andric         setOperationAction(Op, T, Legal);
1830b57cec5SDimitry Andric 
1845ffd83dbSDimitry Andric     // Support integer abs
185fe6060f1SDimitry Andric     for (auto T : {MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64})
1865ffd83dbSDimitry Andric       setOperationAction(ISD::ABS, T, Legal);
1875ffd83dbSDimitry Andric 
1880b57cec5SDimitry Andric     // Custom lower BUILD_VECTORs to minimize number of replace_lanes
1895ffd83dbSDimitry Andric     for (auto T : {MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v4f32, MVT::v2i64,
1905ffd83dbSDimitry Andric                    MVT::v2f64})
1910b57cec5SDimitry Andric       setOperationAction(ISD::BUILD_VECTOR, T, Custom);
1920b57cec5SDimitry Andric 
1930b57cec5SDimitry Andric     // We have custom shuffle lowering to expose the shuffle mask
1945ffd83dbSDimitry Andric     for (auto T : {MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v4f32, MVT::v2i64,
1955ffd83dbSDimitry Andric                    MVT::v2f64})
1960b57cec5SDimitry Andric       setOperationAction(ISD::VECTOR_SHUFFLE, T, Custom);
1970b57cec5SDimitry Andric 
1980b57cec5SDimitry Andric     // Custom lowering since wasm shifts must have a scalar shift amount
1995ffd83dbSDimitry Andric     for (auto Op : {ISD::SHL, ISD::SRA, ISD::SRL})
2005ffd83dbSDimitry Andric       for (auto T : {MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64})
2010b57cec5SDimitry Andric         setOperationAction(Op, T, Custom);
2020b57cec5SDimitry Andric 
2030b57cec5SDimitry Andric     // Custom lower lane accesses to expand out variable indices
2045ffd83dbSDimitry Andric     for (auto Op : {ISD::EXTRACT_VECTOR_ELT, ISD::INSERT_VECTOR_ELT})
2055ffd83dbSDimitry Andric       for (auto T : {MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v4f32, MVT::v2i64,
2065ffd83dbSDimitry Andric                      MVT::v2f64})
2070b57cec5SDimitry Andric         setOperationAction(Op, T, Custom);
2080b57cec5SDimitry Andric 
2095ffd83dbSDimitry Andric     // There is no i8x16.mul instruction
2105ffd83dbSDimitry Andric     setOperationAction(ISD::MUL, MVT::v16i8, Expand);
2110b57cec5SDimitry Andric 
212e8d8bef9SDimitry Andric     // There is no vector conditional select instruction
2135ffd83dbSDimitry Andric     for (auto T : {MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v4f32, MVT::v2i64,
2145ffd83dbSDimitry Andric                    MVT::v2f64})
215e8d8bef9SDimitry Andric       setOperationAction(ISD::SELECT_CC, T, Expand);
2160b57cec5SDimitry Andric 
2170b57cec5SDimitry Andric     // Expand integer operations supported for scalars but not SIMD
218*349cc55cSDimitry Andric     for (auto Op :
219*349cc55cSDimitry Andric          {ISD::SDIV, ISD::UDIV, ISD::SREM, ISD::UREM, ISD::ROTL, ISD::ROTR})
2205ffd83dbSDimitry Andric       for (auto T : {MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64})
2210b57cec5SDimitry Andric         setOperationAction(Op, T, Expand);
2220b57cec5SDimitry Andric 
223480093f4SDimitry Andric     // But we do have integer min and max operations
224480093f4SDimitry Andric     for (auto Op : {ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX})
225480093f4SDimitry Andric       for (auto T : {MVT::v16i8, MVT::v8i16, MVT::v4i32})
226480093f4SDimitry Andric         setOperationAction(Op, T, Legal);
227480093f4SDimitry Andric 
228*349cc55cSDimitry Andric     // And we have popcnt for i8x16. It can be used to expand ctlz/cttz.
229fe6060f1SDimitry Andric     setOperationAction(ISD::CTPOP, MVT::v16i8, Legal);
230*349cc55cSDimitry Andric     setOperationAction(ISD::CTLZ, MVT::v16i8, Expand);
231*349cc55cSDimitry Andric     setOperationAction(ISD::CTTZ, MVT::v16i8, Expand);
232*349cc55cSDimitry Andric 
233*349cc55cSDimitry Andric     // Custom lower bit counting operations for other types to scalarize them.
234*349cc55cSDimitry Andric     for (auto Op : {ISD::CTLZ, ISD::CTTZ, ISD::CTPOP})
235*349cc55cSDimitry Andric       for (auto T : {MVT::v8i16, MVT::v4i32, MVT::v2i64})
236*349cc55cSDimitry Andric         setOperationAction(Op, T, Custom);
237fe6060f1SDimitry Andric 
2380b57cec5SDimitry Andric     // Expand float operations supported for scalars but not SIMD
239fe6060f1SDimitry Andric     for (auto Op : {ISD::FCOPYSIGN, ISD::FLOG, ISD::FLOG2, ISD::FLOG10,
2405ffd83dbSDimitry Andric                     ISD::FEXP, ISD::FEXP2, ISD::FRINT})
2415ffd83dbSDimitry Andric       for (auto T : {MVT::v4f32, MVT::v2f64})
2425ffd83dbSDimitry Andric         setOperationAction(Op, T, Expand);
2430b57cec5SDimitry Andric 
244fe6060f1SDimitry Andric     // Unsigned comparison operations are unavailable for i64x2 vectors.
245fe6060f1SDimitry Andric     for (auto CC : {ISD::SETUGT, ISD::SETUGE, ISD::SETULT, ISD::SETULE})
246fe6060f1SDimitry Andric       setCondCodeAction(CC, MVT::v2i64, Custom);
247480093f4SDimitry Andric 
2485ffd83dbSDimitry Andric     // 64x2 conversions are not in the spec
2495ffd83dbSDimitry Andric     for (auto Op :
2505ffd83dbSDimitry Andric          {ISD::SINT_TO_FP, ISD::UINT_TO_FP, ISD::FP_TO_SINT, ISD::FP_TO_UINT})
2515ffd83dbSDimitry Andric       for (auto T : {MVT::v2i64, MVT::v2f64})
2525ffd83dbSDimitry Andric         setOperationAction(Op, T, Expand);
253fe6060f1SDimitry Andric 
254fe6060f1SDimitry Andric     // But saturating fp_to_int converstions are
255fe6060f1SDimitry Andric     for (auto Op : {ISD::FP_TO_SINT_SAT, ISD::FP_TO_UINT_SAT})
256fe6060f1SDimitry Andric       setOperationAction(Op, MVT::v4i32, Custom);
2570b57cec5SDimitry Andric   }
2580b57cec5SDimitry Andric 
2590b57cec5SDimitry Andric   // As a special case, these operators use the type to mean the type to
2600b57cec5SDimitry Andric   // sign-extend from.
2610b57cec5SDimitry Andric   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
2620b57cec5SDimitry Andric   if (!Subtarget->hasSignExt()) {
2630b57cec5SDimitry Andric     // Sign extends are legal only when extending a vector extract
2640b57cec5SDimitry Andric     auto Action = Subtarget->hasSIMD128() ? Custom : Expand;
2650b57cec5SDimitry Andric     for (auto T : {MVT::i8, MVT::i16, MVT::i32})
2660b57cec5SDimitry Andric       setOperationAction(ISD::SIGN_EXTEND_INREG, T, Action);
2670b57cec5SDimitry Andric   }
2688bcb0991SDimitry Andric   for (auto T : MVT::integer_fixedlen_vector_valuetypes())
2690b57cec5SDimitry Andric     setOperationAction(ISD::SIGN_EXTEND_INREG, T, Expand);
2700b57cec5SDimitry Andric 
2710b57cec5SDimitry Andric   // Dynamic stack allocation: use the default expansion.
2720b57cec5SDimitry Andric   setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
2730b57cec5SDimitry Andric   setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
2740b57cec5SDimitry Andric   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVTPtr, Expand);
2750b57cec5SDimitry Andric 
2760b57cec5SDimitry Andric   setOperationAction(ISD::FrameIndex, MVT::i32, Custom);
2775ffd83dbSDimitry Andric   setOperationAction(ISD::FrameIndex, MVT::i64, Custom);
2780b57cec5SDimitry Andric   setOperationAction(ISD::CopyToReg, MVT::Other, Custom);
2790b57cec5SDimitry Andric 
2800b57cec5SDimitry Andric   // Expand these forms; we pattern-match the forms that we can handle in isel.
2810b57cec5SDimitry Andric   for (auto T : {MVT::i32, MVT::i64, MVT::f32, MVT::f64})
2820b57cec5SDimitry Andric     for (auto Op : {ISD::BR_CC, ISD::SELECT_CC})
2830b57cec5SDimitry Andric       setOperationAction(Op, T, Expand);
2840b57cec5SDimitry Andric 
2850b57cec5SDimitry Andric   // We have custom switch handling.
2860b57cec5SDimitry Andric   setOperationAction(ISD::BR_JT, MVT::Other, Custom);
2870b57cec5SDimitry Andric 
2880b57cec5SDimitry Andric   // WebAssembly doesn't have:
2890b57cec5SDimitry Andric   //  - Floating-point extending loads.
2900b57cec5SDimitry Andric   //  - Floating-point truncating stores.
2910b57cec5SDimitry Andric   //  - i1 extending loads.
2928bcb0991SDimitry Andric   //  - truncating SIMD stores and most extending loads
2930b57cec5SDimitry Andric   setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f32, Expand);
2940b57cec5SDimitry Andric   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
2950b57cec5SDimitry Andric   for (auto T : MVT::integer_valuetypes())
2960b57cec5SDimitry Andric     for (auto Ext : {ISD::EXTLOAD, ISD::ZEXTLOAD, ISD::SEXTLOAD})
2970b57cec5SDimitry Andric       setLoadExtAction(Ext, T, MVT::i1, Promote);
2980b57cec5SDimitry Andric   if (Subtarget->hasSIMD128()) {
2990b57cec5SDimitry Andric     for (auto T : {MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64, MVT::v4f32,
3000b57cec5SDimitry Andric                    MVT::v2f64}) {
3018bcb0991SDimitry Andric       for (auto MemT : MVT::fixedlen_vector_valuetypes()) {
3020b57cec5SDimitry Andric         if (MVT(T) != MemT) {
3030b57cec5SDimitry Andric           setTruncStoreAction(T, MemT, Expand);
3040b57cec5SDimitry Andric           for (auto Ext : {ISD::EXTLOAD, ISD::ZEXTLOAD, ISD::SEXTLOAD})
3050b57cec5SDimitry Andric             setLoadExtAction(Ext, T, MemT, Expand);
3060b57cec5SDimitry Andric         }
3070b57cec5SDimitry Andric       }
3080b57cec5SDimitry Andric     }
3098bcb0991SDimitry Andric     // But some vector extending loads are legal
3108bcb0991SDimitry Andric     for (auto Ext : {ISD::EXTLOAD, ISD::SEXTLOAD, ISD::ZEXTLOAD}) {
3118bcb0991SDimitry Andric       setLoadExtAction(Ext, MVT::v8i16, MVT::v8i8, Legal);
3128bcb0991SDimitry Andric       setLoadExtAction(Ext, MVT::v4i32, MVT::v4i16, Legal);
3138bcb0991SDimitry Andric       setLoadExtAction(Ext, MVT::v2i64, MVT::v2i32, Legal);
3148bcb0991SDimitry Andric     }
315*349cc55cSDimitry Andric     setLoadExtAction(ISD::EXTLOAD, MVT::v2f64, MVT::v2f32, Legal);
3168bcb0991SDimitry Andric   }
3170b57cec5SDimitry Andric 
3180b57cec5SDimitry Andric   // Don't do anything clever with build_pairs
3190b57cec5SDimitry Andric   setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand);
3200b57cec5SDimitry Andric 
3210b57cec5SDimitry Andric   // Trap lowers to wasm unreachable
3220b57cec5SDimitry Andric   setOperationAction(ISD::TRAP, MVT::Other, Legal);
3235ffd83dbSDimitry Andric   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
3240b57cec5SDimitry Andric 
3250b57cec5SDimitry Andric   // Exception handling intrinsics
3260b57cec5SDimitry Andric   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
327e8d8bef9SDimitry Andric   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
3280b57cec5SDimitry Andric   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
3290b57cec5SDimitry Andric 
3300b57cec5SDimitry Andric   setMaxAtomicSizeInBitsSupported(64);
3310b57cec5SDimitry Andric 
3320b57cec5SDimitry Andric   // Override the __gnu_f2h_ieee/__gnu_h2f_ieee names so that the f32 name is
3330b57cec5SDimitry Andric   // consistent with the f64 and f128 names.
3340b57cec5SDimitry Andric   setLibcallName(RTLIB::FPEXT_F16_F32, "__extendhfsf2");
3350b57cec5SDimitry Andric   setLibcallName(RTLIB::FPROUND_F32_F16, "__truncsfhf2");
3360b57cec5SDimitry Andric 
3370b57cec5SDimitry Andric   // Define the emscripten name for return address helper.
338e8d8bef9SDimitry Andric   // TODO: when implementing other Wasm backends, make this generic or only do
3390b57cec5SDimitry Andric   // this on emscripten depending on what they end up doing.
3400b57cec5SDimitry Andric   setLibcallName(RTLIB::RETURN_ADDRESS, "emscripten_return_address");
3410b57cec5SDimitry Andric 
3420b57cec5SDimitry Andric   // Always convert switches to br_tables unless there is only one case, which
3430b57cec5SDimitry Andric   // is equivalent to a simple branch. This reduces code size for wasm, and we
3440b57cec5SDimitry Andric   // defer possible jump table optimizations to the VM.
3450b57cec5SDimitry Andric   setMinimumJumpTableEntries(2);
3460b57cec5SDimitry Andric }
3470b57cec5SDimitry Andric 
348*349cc55cSDimitry Andric MVT WebAssemblyTargetLowering::getPointerTy(const DataLayout &DL,
349*349cc55cSDimitry Andric                                             uint32_t AS) const {
350*349cc55cSDimitry Andric   if (AS == WebAssembly::WasmAddressSpace::WASM_ADDRESS_SPACE_EXTERNREF)
351*349cc55cSDimitry Andric     return MVT::externref;
352*349cc55cSDimitry Andric   if (AS == WebAssembly::WasmAddressSpace::WASM_ADDRESS_SPACE_FUNCREF)
353*349cc55cSDimitry Andric     return MVT::funcref;
354*349cc55cSDimitry Andric   return TargetLowering::getPointerTy(DL, AS);
355*349cc55cSDimitry Andric }
356*349cc55cSDimitry Andric 
357*349cc55cSDimitry Andric MVT WebAssemblyTargetLowering::getPointerMemTy(const DataLayout &DL,
358*349cc55cSDimitry Andric                                                uint32_t AS) const {
359*349cc55cSDimitry Andric   if (AS == WebAssembly::WasmAddressSpace::WASM_ADDRESS_SPACE_EXTERNREF)
360*349cc55cSDimitry Andric     return MVT::externref;
361*349cc55cSDimitry Andric   if (AS == WebAssembly::WasmAddressSpace::WASM_ADDRESS_SPACE_FUNCREF)
362*349cc55cSDimitry Andric     return MVT::funcref;
363*349cc55cSDimitry Andric   return TargetLowering::getPointerMemTy(DL, AS);
364*349cc55cSDimitry Andric }
365*349cc55cSDimitry Andric 
3660b57cec5SDimitry Andric TargetLowering::AtomicExpansionKind
3670b57cec5SDimitry Andric WebAssemblyTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
3680b57cec5SDimitry Andric   // We have wasm instructions for these
3690b57cec5SDimitry Andric   switch (AI->getOperation()) {
3700b57cec5SDimitry Andric   case AtomicRMWInst::Add:
3710b57cec5SDimitry Andric   case AtomicRMWInst::Sub:
3720b57cec5SDimitry Andric   case AtomicRMWInst::And:
3730b57cec5SDimitry Andric   case AtomicRMWInst::Or:
3740b57cec5SDimitry Andric   case AtomicRMWInst::Xor:
3750b57cec5SDimitry Andric   case AtomicRMWInst::Xchg:
3760b57cec5SDimitry Andric     return AtomicExpansionKind::None;
3770b57cec5SDimitry Andric   default:
3780b57cec5SDimitry Andric     break;
3790b57cec5SDimitry Andric   }
3800b57cec5SDimitry Andric   return AtomicExpansionKind::CmpXChg;
3810b57cec5SDimitry Andric }
3820b57cec5SDimitry Andric 
383fe6060f1SDimitry Andric bool WebAssemblyTargetLowering::shouldScalarizeBinop(SDValue VecOp) const {
384fe6060f1SDimitry Andric   // Implementation copied from X86TargetLowering.
385fe6060f1SDimitry Andric   unsigned Opc = VecOp.getOpcode();
386fe6060f1SDimitry Andric 
387fe6060f1SDimitry Andric   // Assume target opcodes can't be scalarized.
388fe6060f1SDimitry Andric   // TODO - do we have any exceptions?
389fe6060f1SDimitry Andric   if (Opc >= ISD::BUILTIN_OP_END)
390fe6060f1SDimitry Andric     return false;
391fe6060f1SDimitry Andric 
392fe6060f1SDimitry Andric   // If the vector op is not supported, try to convert to scalar.
393fe6060f1SDimitry Andric   EVT VecVT = VecOp.getValueType();
394fe6060f1SDimitry Andric   if (!isOperationLegalOrCustomOrPromote(Opc, VecVT))
395fe6060f1SDimitry Andric     return true;
396fe6060f1SDimitry Andric 
397fe6060f1SDimitry Andric   // If the vector op is supported, but the scalar op is not, the transform may
398fe6060f1SDimitry Andric   // not be worthwhile.
399fe6060f1SDimitry Andric   EVT ScalarVT = VecVT.getScalarType();
400fe6060f1SDimitry Andric   return isOperationLegalOrCustomOrPromote(Opc, ScalarVT);
401fe6060f1SDimitry Andric }
402fe6060f1SDimitry Andric 
4030b57cec5SDimitry Andric FastISel *WebAssemblyTargetLowering::createFastISel(
4040b57cec5SDimitry Andric     FunctionLoweringInfo &FuncInfo, const TargetLibraryInfo *LibInfo) const {
4050b57cec5SDimitry Andric   return WebAssembly::createFastISel(FuncInfo, LibInfo);
4060b57cec5SDimitry Andric }
4070b57cec5SDimitry Andric 
4080b57cec5SDimitry Andric MVT WebAssemblyTargetLowering::getScalarShiftAmountTy(const DataLayout & /*DL*/,
4090b57cec5SDimitry Andric                                                       EVT VT) const {
4100b57cec5SDimitry Andric   unsigned BitWidth = NextPowerOf2(VT.getSizeInBits() - 1);
4110b57cec5SDimitry Andric   if (BitWidth > 1 && BitWidth < 8)
4120b57cec5SDimitry Andric     BitWidth = 8;
4130b57cec5SDimitry Andric 
4140b57cec5SDimitry Andric   if (BitWidth > 64) {
4150b57cec5SDimitry Andric     // The shift will be lowered to a libcall, and compiler-rt libcalls expect
4160b57cec5SDimitry Andric     // the count to be an i32.
4170b57cec5SDimitry Andric     BitWidth = 32;
4180b57cec5SDimitry Andric     assert(BitWidth >= Log2_32_Ceil(VT.getSizeInBits()) &&
4190b57cec5SDimitry Andric            "32-bit shift counts ought to be enough for anyone");
4200b57cec5SDimitry Andric   }
4210b57cec5SDimitry Andric 
4220b57cec5SDimitry Andric   MVT Result = MVT::getIntegerVT(BitWidth);
4230b57cec5SDimitry Andric   assert(Result != MVT::INVALID_SIMPLE_VALUE_TYPE &&
4240b57cec5SDimitry Andric          "Unable to represent scalar shift amount type");
4250b57cec5SDimitry Andric   return Result;
4260b57cec5SDimitry Andric }
4270b57cec5SDimitry Andric 
4280b57cec5SDimitry Andric // Lower an fp-to-int conversion operator from the LLVM opcode, which has an
4290b57cec5SDimitry Andric // undefined result on invalid/overflow, to the WebAssembly opcode, which
4300b57cec5SDimitry Andric // traps on invalid/overflow.
4310b57cec5SDimitry Andric static MachineBasicBlock *LowerFPToInt(MachineInstr &MI, DebugLoc DL,
4320b57cec5SDimitry Andric                                        MachineBasicBlock *BB,
4330b57cec5SDimitry Andric                                        const TargetInstrInfo &TII,
4340b57cec5SDimitry Andric                                        bool IsUnsigned, bool Int64,
4350b57cec5SDimitry Andric                                        bool Float64, unsigned LoweredOpcode) {
4360b57cec5SDimitry Andric   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4370b57cec5SDimitry Andric 
4388bcb0991SDimitry Andric   Register OutReg = MI.getOperand(0).getReg();
4398bcb0991SDimitry Andric   Register InReg = MI.getOperand(1).getReg();
4400b57cec5SDimitry Andric 
4410b57cec5SDimitry Andric   unsigned Abs = Float64 ? WebAssembly::ABS_F64 : WebAssembly::ABS_F32;
4420b57cec5SDimitry Andric   unsigned FConst = Float64 ? WebAssembly::CONST_F64 : WebAssembly::CONST_F32;
4430b57cec5SDimitry Andric   unsigned LT = Float64 ? WebAssembly::LT_F64 : WebAssembly::LT_F32;
4440b57cec5SDimitry Andric   unsigned GE = Float64 ? WebAssembly::GE_F64 : WebAssembly::GE_F32;
4450b57cec5SDimitry Andric   unsigned IConst = Int64 ? WebAssembly::CONST_I64 : WebAssembly::CONST_I32;
4460b57cec5SDimitry Andric   unsigned Eqz = WebAssembly::EQZ_I32;
4470b57cec5SDimitry Andric   unsigned And = WebAssembly::AND_I32;
4480b57cec5SDimitry Andric   int64_t Limit = Int64 ? INT64_MIN : INT32_MIN;
4490b57cec5SDimitry Andric   int64_t Substitute = IsUnsigned ? 0 : Limit;
4500b57cec5SDimitry Andric   double CmpVal = IsUnsigned ? -(double)Limit * 2.0 : -(double)Limit;
4510b57cec5SDimitry Andric   auto &Context = BB->getParent()->getFunction().getContext();
4520b57cec5SDimitry Andric   Type *Ty = Float64 ? Type::getDoubleTy(Context) : Type::getFloatTy(Context);
4530b57cec5SDimitry Andric 
4540b57cec5SDimitry Andric   const BasicBlock *LLVMBB = BB->getBasicBlock();
4550b57cec5SDimitry Andric   MachineFunction *F = BB->getParent();
4560b57cec5SDimitry Andric   MachineBasicBlock *TrueMBB = F->CreateMachineBasicBlock(LLVMBB);
4570b57cec5SDimitry Andric   MachineBasicBlock *FalseMBB = F->CreateMachineBasicBlock(LLVMBB);
4580b57cec5SDimitry Andric   MachineBasicBlock *DoneMBB = F->CreateMachineBasicBlock(LLVMBB);
4590b57cec5SDimitry Andric 
4600b57cec5SDimitry Andric   MachineFunction::iterator It = ++BB->getIterator();
4610b57cec5SDimitry Andric   F->insert(It, FalseMBB);
4620b57cec5SDimitry Andric   F->insert(It, TrueMBB);
4630b57cec5SDimitry Andric   F->insert(It, DoneMBB);
4640b57cec5SDimitry Andric 
4650b57cec5SDimitry Andric   // Transfer the remainder of BB and its successor edges to DoneMBB.
4660b57cec5SDimitry Andric   DoneMBB->splice(DoneMBB->begin(), BB, std::next(MI.getIterator()), BB->end());
4670b57cec5SDimitry Andric   DoneMBB->transferSuccessorsAndUpdatePHIs(BB);
4680b57cec5SDimitry Andric 
4690b57cec5SDimitry Andric   BB->addSuccessor(TrueMBB);
4700b57cec5SDimitry Andric   BB->addSuccessor(FalseMBB);
4710b57cec5SDimitry Andric   TrueMBB->addSuccessor(DoneMBB);
4720b57cec5SDimitry Andric   FalseMBB->addSuccessor(DoneMBB);
4730b57cec5SDimitry Andric 
4740b57cec5SDimitry Andric   unsigned Tmp0, Tmp1, CmpReg, EqzReg, FalseReg, TrueReg;
4750b57cec5SDimitry Andric   Tmp0 = MRI.createVirtualRegister(MRI.getRegClass(InReg));
4760b57cec5SDimitry Andric   Tmp1 = MRI.createVirtualRegister(MRI.getRegClass(InReg));
4770b57cec5SDimitry Andric   CmpReg = MRI.createVirtualRegister(&WebAssembly::I32RegClass);
4780b57cec5SDimitry Andric   EqzReg = MRI.createVirtualRegister(&WebAssembly::I32RegClass);
4790b57cec5SDimitry Andric   FalseReg = MRI.createVirtualRegister(MRI.getRegClass(OutReg));
4800b57cec5SDimitry Andric   TrueReg = MRI.createVirtualRegister(MRI.getRegClass(OutReg));
4810b57cec5SDimitry Andric 
4820b57cec5SDimitry Andric   MI.eraseFromParent();
4830b57cec5SDimitry Andric   // For signed numbers, we can do a single comparison to determine whether
4840b57cec5SDimitry Andric   // fabs(x) is within range.
4850b57cec5SDimitry Andric   if (IsUnsigned) {
4860b57cec5SDimitry Andric     Tmp0 = InReg;
4870b57cec5SDimitry Andric   } else {
4880b57cec5SDimitry Andric     BuildMI(BB, DL, TII.get(Abs), Tmp0).addReg(InReg);
4890b57cec5SDimitry Andric   }
4900b57cec5SDimitry Andric   BuildMI(BB, DL, TII.get(FConst), Tmp1)
4910b57cec5SDimitry Andric       .addFPImm(cast<ConstantFP>(ConstantFP::get(Ty, CmpVal)));
4920b57cec5SDimitry Andric   BuildMI(BB, DL, TII.get(LT), CmpReg).addReg(Tmp0).addReg(Tmp1);
4930b57cec5SDimitry Andric 
4940b57cec5SDimitry Andric   // For unsigned numbers, we have to do a separate comparison with zero.
4950b57cec5SDimitry Andric   if (IsUnsigned) {
4960b57cec5SDimitry Andric     Tmp1 = MRI.createVirtualRegister(MRI.getRegClass(InReg));
4978bcb0991SDimitry Andric     Register SecondCmpReg =
4980b57cec5SDimitry Andric         MRI.createVirtualRegister(&WebAssembly::I32RegClass);
4998bcb0991SDimitry Andric     Register AndReg = MRI.createVirtualRegister(&WebAssembly::I32RegClass);
5000b57cec5SDimitry Andric     BuildMI(BB, DL, TII.get(FConst), Tmp1)
5010b57cec5SDimitry Andric         .addFPImm(cast<ConstantFP>(ConstantFP::get(Ty, 0.0)));
5020b57cec5SDimitry Andric     BuildMI(BB, DL, TII.get(GE), SecondCmpReg).addReg(Tmp0).addReg(Tmp1);
5030b57cec5SDimitry Andric     BuildMI(BB, DL, TII.get(And), AndReg).addReg(CmpReg).addReg(SecondCmpReg);
5040b57cec5SDimitry Andric     CmpReg = AndReg;
5050b57cec5SDimitry Andric   }
5060b57cec5SDimitry Andric 
5070b57cec5SDimitry Andric   BuildMI(BB, DL, TII.get(Eqz), EqzReg).addReg(CmpReg);
5080b57cec5SDimitry Andric 
5090b57cec5SDimitry Andric   // Create the CFG diamond to select between doing the conversion or using
5100b57cec5SDimitry Andric   // the substitute value.
5110b57cec5SDimitry Andric   BuildMI(BB, DL, TII.get(WebAssembly::BR_IF)).addMBB(TrueMBB).addReg(EqzReg);
5120b57cec5SDimitry Andric   BuildMI(FalseMBB, DL, TII.get(LoweredOpcode), FalseReg).addReg(InReg);
5130b57cec5SDimitry Andric   BuildMI(FalseMBB, DL, TII.get(WebAssembly::BR)).addMBB(DoneMBB);
5140b57cec5SDimitry Andric   BuildMI(TrueMBB, DL, TII.get(IConst), TrueReg).addImm(Substitute);
5150b57cec5SDimitry Andric   BuildMI(*DoneMBB, DoneMBB->begin(), DL, TII.get(TargetOpcode::PHI), OutReg)
5160b57cec5SDimitry Andric       .addReg(FalseReg)
5170b57cec5SDimitry Andric       .addMBB(FalseMBB)
5180b57cec5SDimitry Andric       .addReg(TrueReg)
5190b57cec5SDimitry Andric       .addMBB(TrueMBB);
5200b57cec5SDimitry Andric 
5210b57cec5SDimitry Andric   return DoneMBB;
5220b57cec5SDimitry Andric }
5230b57cec5SDimitry Andric 
524fe6060f1SDimitry Andric static MachineBasicBlock *
525fe6060f1SDimitry Andric LowerCallResults(MachineInstr &CallResults, DebugLoc DL, MachineBasicBlock *BB,
526fe6060f1SDimitry Andric                  const WebAssemblySubtarget *Subtarget,
5275ffd83dbSDimitry Andric                  const TargetInstrInfo &TII) {
5285ffd83dbSDimitry Andric   MachineInstr &CallParams = *CallResults.getPrevNode();
5295ffd83dbSDimitry Andric   assert(CallParams.getOpcode() == WebAssembly::CALL_PARAMS);
5305ffd83dbSDimitry Andric   assert(CallResults.getOpcode() == WebAssembly::CALL_RESULTS ||
5315ffd83dbSDimitry Andric          CallResults.getOpcode() == WebAssembly::RET_CALL_RESULTS);
5325ffd83dbSDimitry Andric 
5335ffd83dbSDimitry Andric   bool IsIndirect = CallParams.getOperand(0).isReg();
5345ffd83dbSDimitry Andric   bool IsRetCall = CallResults.getOpcode() == WebAssembly::RET_CALL_RESULTS;
5355ffd83dbSDimitry Andric 
536fe6060f1SDimitry Andric   bool IsFuncrefCall = false;
537fe6060f1SDimitry Andric   if (IsIndirect) {
538fe6060f1SDimitry Andric     Register Reg = CallParams.getOperand(0).getReg();
539fe6060f1SDimitry Andric     const MachineFunction *MF = BB->getParent();
540fe6060f1SDimitry Andric     const MachineRegisterInfo &MRI = MF->getRegInfo();
541fe6060f1SDimitry Andric     const TargetRegisterClass *TRC = MRI.getRegClass(Reg);
542fe6060f1SDimitry Andric     IsFuncrefCall = (TRC == &WebAssembly::FUNCREFRegClass);
543fe6060f1SDimitry Andric     assert(!IsFuncrefCall || Subtarget->hasReferenceTypes());
544fe6060f1SDimitry Andric   }
545fe6060f1SDimitry Andric 
5465ffd83dbSDimitry Andric   unsigned CallOp;
5475ffd83dbSDimitry Andric   if (IsIndirect && IsRetCall) {
5485ffd83dbSDimitry Andric     CallOp = WebAssembly::RET_CALL_INDIRECT;
5495ffd83dbSDimitry Andric   } else if (IsIndirect) {
5505ffd83dbSDimitry Andric     CallOp = WebAssembly::CALL_INDIRECT;
5515ffd83dbSDimitry Andric   } else if (IsRetCall) {
5525ffd83dbSDimitry Andric     CallOp = WebAssembly::RET_CALL;
5535ffd83dbSDimitry Andric   } else {
5545ffd83dbSDimitry Andric     CallOp = WebAssembly::CALL;
5555ffd83dbSDimitry Andric   }
5565ffd83dbSDimitry Andric 
5575ffd83dbSDimitry Andric   MachineFunction &MF = *BB->getParent();
5585ffd83dbSDimitry Andric   const MCInstrDesc &MCID = TII.get(CallOp);
5595ffd83dbSDimitry Andric   MachineInstrBuilder MIB(MF, MF.CreateMachineInstr(MCID, DL));
5605ffd83dbSDimitry Andric 
561e8d8bef9SDimitry Andric   // See if we must truncate the function pointer.
562e8d8bef9SDimitry Andric   // CALL_INDIRECT takes an i32, but in wasm64 we represent function pointers
563e8d8bef9SDimitry Andric   // as 64-bit for uniformity with other pointer types.
564fe6060f1SDimitry Andric   // See also: WebAssemblyFastISel::selectCall
565e8d8bef9SDimitry Andric   if (IsIndirect && MF.getSubtarget<WebAssemblySubtarget>().hasAddr64()) {
566e8d8bef9SDimitry Andric     Register Reg32 =
567e8d8bef9SDimitry Andric         MF.getRegInfo().createVirtualRegister(&WebAssembly::I32RegClass);
568e8d8bef9SDimitry Andric     auto &FnPtr = CallParams.getOperand(0);
569e8d8bef9SDimitry Andric     BuildMI(*BB, CallResults.getIterator(), DL,
570e8d8bef9SDimitry Andric             TII.get(WebAssembly::I32_WRAP_I64), Reg32)
571e8d8bef9SDimitry Andric         .addReg(FnPtr.getReg());
572e8d8bef9SDimitry Andric     FnPtr.setReg(Reg32);
573e8d8bef9SDimitry Andric   }
574e8d8bef9SDimitry Andric 
5755ffd83dbSDimitry Andric   // Move the function pointer to the end of the arguments for indirect calls
5765ffd83dbSDimitry Andric   if (IsIndirect) {
5775ffd83dbSDimitry Andric     auto FnPtr = CallParams.getOperand(0);
5785ffd83dbSDimitry Andric     CallParams.RemoveOperand(0);
579*349cc55cSDimitry Andric 
580*349cc55cSDimitry Andric     // For funcrefs, call_indirect is done through __funcref_call_table and the
581*349cc55cSDimitry Andric     // funcref is always installed in slot 0 of the table, therefore instead of having
582*349cc55cSDimitry Andric     // the function pointer added at the end of the params list, a zero (the index in
583*349cc55cSDimitry Andric     // __funcref_call_table is added).
584*349cc55cSDimitry Andric     if (IsFuncrefCall) {
585*349cc55cSDimitry Andric       Register RegZero =
586*349cc55cSDimitry Andric           MF.getRegInfo().createVirtualRegister(&WebAssembly::I32RegClass);
587*349cc55cSDimitry Andric       MachineInstrBuilder MIBC0 =
588*349cc55cSDimitry Andric           BuildMI(MF, DL, TII.get(WebAssembly::CONST_I32), RegZero).addImm(0);
589*349cc55cSDimitry Andric 
590*349cc55cSDimitry Andric       BB->insert(CallResults.getIterator(), MIBC0);
591*349cc55cSDimitry Andric       MachineInstrBuilder(MF, CallParams).addReg(RegZero);
592*349cc55cSDimitry Andric     } else
5935ffd83dbSDimitry Andric       CallParams.addOperand(FnPtr);
5945ffd83dbSDimitry Andric   }
5955ffd83dbSDimitry Andric 
5965ffd83dbSDimitry Andric   for (auto Def : CallResults.defs())
5975ffd83dbSDimitry Andric     MIB.add(Def);
5985ffd83dbSDimitry Andric 
5995ffd83dbSDimitry Andric   if (IsIndirect) {
600fe6060f1SDimitry Andric     // Placeholder for the type index.
6015ffd83dbSDimitry Andric     MIB.addImm(0);
602fe6060f1SDimitry Andric     // The table into which this call_indirect indexes.
603fe6060f1SDimitry Andric     MCSymbolWasm *Table = IsFuncrefCall
604fe6060f1SDimitry Andric                               ? WebAssembly::getOrCreateFuncrefCallTableSymbol(
605fe6060f1SDimitry Andric                                     MF.getContext(), Subtarget)
606fe6060f1SDimitry Andric                               : WebAssembly::getOrCreateFunctionTableSymbol(
607fe6060f1SDimitry Andric                                     MF.getContext(), Subtarget);
608fe6060f1SDimitry Andric     if (Subtarget->hasReferenceTypes()) {
609fe6060f1SDimitry Andric       MIB.addSym(Table);
610fe6060f1SDimitry Andric     } else {
611fe6060f1SDimitry Andric       // For the MVP there is at most one table whose number is 0, but we can't
612fe6060f1SDimitry Andric       // write a table symbol or issue relocations.  Instead we just ensure the
613fe6060f1SDimitry Andric       // table is live and write a zero.
614fe6060f1SDimitry Andric       Table->setNoStrip();
6155ffd83dbSDimitry Andric       MIB.addImm(0);
616fe6060f1SDimitry Andric     }
6175ffd83dbSDimitry Andric   }
6185ffd83dbSDimitry Andric 
6195ffd83dbSDimitry Andric   for (auto Use : CallParams.uses())
6205ffd83dbSDimitry Andric     MIB.add(Use);
6215ffd83dbSDimitry Andric 
6225ffd83dbSDimitry Andric   BB->insert(CallResults.getIterator(), MIB);
6235ffd83dbSDimitry Andric   CallParams.eraseFromParent();
6245ffd83dbSDimitry Andric   CallResults.eraseFromParent();
6255ffd83dbSDimitry Andric 
626fe6060f1SDimitry Andric   // If this is a funcref call, to avoid hidden GC roots, we need to clear the
627fe6060f1SDimitry Andric   // table slot with ref.null upon call_indirect return.
628fe6060f1SDimitry Andric   //
629fe6060f1SDimitry Andric   // This generates the following code, which comes right after a call_indirect
630fe6060f1SDimitry Andric   // of a funcref:
631fe6060f1SDimitry Andric   //
632fe6060f1SDimitry Andric   //    i32.const 0
633fe6060f1SDimitry Andric   //    ref.null func
634fe6060f1SDimitry Andric   //    table.set __funcref_call_table
635fe6060f1SDimitry Andric   if (IsIndirect && IsFuncrefCall) {
636fe6060f1SDimitry Andric     MCSymbolWasm *Table = WebAssembly::getOrCreateFuncrefCallTableSymbol(
637fe6060f1SDimitry Andric         MF.getContext(), Subtarget);
638fe6060f1SDimitry Andric     Register RegZero =
639fe6060f1SDimitry Andric         MF.getRegInfo().createVirtualRegister(&WebAssembly::I32RegClass);
640fe6060f1SDimitry Andric     MachineInstr *Const0 =
641fe6060f1SDimitry Andric         BuildMI(MF, DL, TII.get(WebAssembly::CONST_I32), RegZero).addImm(0);
642fe6060f1SDimitry Andric     BB->insertAfter(MIB.getInstr()->getIterator(), Const0);
643fe6060f1SDimitry Andric 
644fe6060f1SDimitry Andric     Register RegFuncref =
645fe6060f1SDimitry Andric         MF.getRegInfo().createVirtualRegister(&WebAssembly::FUNCREFRegClass);
646fe6060f1SDimitry Andric     MachineInstr *RefNull =
647fe6060f1SDimitry Andric         BuildMI(MF, DL, TII.get(WebAssembly::REF_NULL_FUNCREF), RegFuncref)
648fe6060f1SDimitry Andric             .addImm(static_cast<int32_t>(WebAssembly::HeapType::Funcref));
649fe6060f1SDimitry Andric     BB->insertAfter(Const0->getIterator(), RefNull);
650fe6060f1SDimitry Andric 
651fe6060f1SDimitry Andric     MachineInstr *TableSet =
652fe6060f1SDimitry Andric         BuildMI(MF, DL, TII.get(WebAssembly::TABLE_SET_FUNCREF))
653fe6060f1SDimitry Andric             .addSym(Table)
654fe6060f1SDimitry Andric             .addReg(RegZero)
655fe6060f1SDimitry Andric             .addReg(RegFuncref);
656fe6060f1SDimitry Andric     BB->insertAfter(RefNull->getIterator(), TableSet);
657fe6060f1SDimitry Andric   }
658fe6060f1SDimitry Andric 
6595ffd83dbSDimitry Andric   return BB;
6605ffd83dbSDimitry Andric }
6615ffd83dbSDimitry Andric 
6620b57cec5SDimitry Andric MachineBasicBlock *WebAssemblyTargetLowering::EmitInstrWithCustomInserter(
6630b57cec5SDimitry Andric     MachineInstr &MI, MachineBasicBlock *BB) const {
6640b57cec5SDimitry Andric   const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
6650b57cec5SDimitry Andric   DebugLoc DL = MI.getDebugLoc();
6660b57cec5SDimitry Andric 
6670b57cec5SDimitry Andric   switch (MI.getOpcode()) {
6680b57cec5SDimitry Andric   default:
6690b57cec5SDimitry Andric     llvm_unreachable("Unexpected instr type to insert");
6700b57cec5SDimitry Andric   case WebAssembly::FP_TO_SINT_I32_F32:
6710b57cec5SDimitry Andric     return LowerFPToInt(MI, DL, BB, TII, false, false, false,
6720b57cec5SDimitry Andric                         WebAssembly::I32_TRUNC_S_F32);
6730b57cec5SDimitry Andric   case WebAssembly::FP_TO_UINT_I32_F32:
6740b57cec5SDimitry Andric     return LowerFPToInt(MI, DL, BB, TII, true, false, false,
6750b57cec5SDimitry Andric                         WebAssembly::I32_TRUNC_U_F32);
6760b57cec5SDimitry Andric   case WebAssembly::FP_TO_SINT_I64_F32:
6770b57cec5SDimitry Andric     return LowerFPToInt(MI, DL, BB, TII, false, true, false,
6780b57cec5SDimitry Andric                         WebAssembly::I64_TRUNC_S_F32);
6790b57cec5SDimitry Andric   case WebAssembly::FP_TO_UINT_I64_F32:
6800b57cec5SDimitry Andric     return LowerFPToInt(MI, DL, BB, TII, true, true, false,
6810b57cec5SDimitry Andric                         WebAssembly::I64_TRUNC_U_F32);
6820b57cec5SDimitry Andric   case WebAssembly::FP_TO_SINT_I32_F64:
6830b57cec5SDimitry Andric     return LowerFPToInt(MI, DL, BB, TII, false, false, true,
6840b57cec5SDimitry Andric                         WebAssembly::I32_TRUNC_S_F64);
6850b57cec5SDimitry Andric   case WebAssembly::FP_TO_UINT_I32_F64:
6860b57cec5SDimitry Andric     return LowerFPToInt(MI, DL, BB, TII, true, false, true,
6870b57cec5SDimitry Andric                         WebAssembly::I32_TRUNC_U_F64);
6880b57cec5SDimitry Andric   case WebAssembly::FP_TO_SINT_I64_F64:
6890b57cec5SDimitry Andric     return LowerFPToInt(MI, DL, BB, TII, false, true, true,
6900b57cec5SDimitry Andric                         WebAssembly::I64_TRUNC_S_F64);
6910b57cec5SDimitry Andric   case WebAssembly::FP_TO_UINT_I64_F64:
6920b57cec5SDimitry Andric     return LowerFPToInt(MI, DL, BB, TII, true, true, true,
6930b57cec5SDimitry Andric                         WebAssembly::I64_TRUNC_U_F64);
6945ffd83dbSDimitry Andric   case WebAssembly::CALL_RESULTS:
6955ffd83dbSDimitry Andric   case WebAssembly::RET_CALL_RESULTS:
696fe6060f1SDimitry Andric     return LowerCallResults(MI, DL, BB, Subtarget, TII);
6970b57cec5SDimitry Andric   }
6980b57cec5SDimitry Andric }
6990b57cec5SDimitry Andric 
7000b57cec5SDimitry Andric const char *
7010b57cec5SDimitry Andric WebAssemblyTargetLowering::getTargetNodeName(unsigned Opcode) const {
7020b57cec5SDimitry Andric   switch (static_cast<WebAssemblyISD::NodeType>(Opcode)) {
7030b57cec5SDimitry Andric   case WebAssemblyISD::FIRST_NUMBER:
704480093f4SDimitry Andric   case WebAssemblyISD::FIRST_MEM_OPCODE:
7050b57cec5SDimitry Andric     break;
7060b57cec5SDimitry Andric #define HANDLE_NODETYPE(NODE)                                                  \
7070b57cec5SDimitry Andric   case WebAssemblyISD::NODE:                                                   \
7080b57cec5SDimitry Andric     return "WebAssemblyISD::" #NODE;
709480093f4SDimitry Andric #define HANDLE_MEM_NODETYPE(NODE) HANDLE_NODETYPE(NODE)
7100b57cec5SDimitry Andric #include "WebAssemblyISD.def"
711480093f4SDimitry Andric #undef HANDLE_MEM_NODETYPE
7120b57cec5SDimitry Andric #undef HANDLE_NODETYPE
7130b57cec5SDimitry Andric   }
7140b57cec5SDimitry Andric   return nullptr;
7150b57cec5SDimitry Andric }
7160b57cec5SDimitry Andric 
7170b57cec5SDimitry Andric std::pair<unsigned, const TargetRegisterClass *>
7180b57cec5SDimitry Andric WebAssemblyTargetLowering::getRegForInlineAsmConstraint(
7190b57cec5SDimitry Andric     const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
7200b57cec5SDimitry Andric   // First, see if this is a constraint that directly corresponds to a
7210b57cec5SDimitry Andric   // WebAssembly register class.
7220b57cec5SDimitry Andric   if (Constraint.size() == 1) {
7230b57cec5SDimitry Andric     switch (Constraint[0]) {
7240b57cec5SDimitry Andric     case 'r':
7250b57cec5SDimitry Andric       assert(VT != MVT::iPTR && "Pointer MVT not expected here");
7260b57cec5SDimitry Andric       if (Subtarget->hasSIMD128() && VT.isVector()) {
7270b57cec5SDimitry Andric         if (VT.getSizeInBits() == 128)
7280b57cec5SDimitry Andric           return std::make_pair(0U, &WebAssembly::V128RegClass);
7290b57cec5SDimitry Andric       }
7300b57cec5SDimitry Andric       if (VT.isInteger() && !VT.isVector()) {
7310b57cec5SDimitry Andric         if (VT.getSizeInBits() <= 32)
7320b57cec5SDimitry Andric           return std::make_pair(0U, &WebAssembly::I32RegClass);
7330b57cec5SDimitry Andric         if (VT.getSizeInBits() <= 64)
7340b57cec5SDimitry Andric           return std::make_pair(0U, &WebAssembly::I64RegClass);
7350b57cec5SDimitry Andric       }
736e8d8bef9SDimitry Andric       if (VT.isFloatingPoint() && !VT.isVector()) {
737e8d8bef9SDimitry Andric         switch (VT.getSizeInBits()) {
738e8d8bef9SDimitry Andric         case 32:
739e8d8bef9SDimitry Andric           return std::make_pair(0U, &WebAssembly::F32RegClass);
740e8d8bef9SDimitry Andric         case 64:
741e8d8bef9SDimitry Andric           return std::make_pair(0U, &WebAssembly::F64RegClass);
742e8d8bef9SDimitry Andric         default:
743e8d8bef9SDimitry Andric           break;
744e8d8bef9SDimitry Andric         }
745e8d8bef9SDimitry Andric       }
7460b57cec5SDimitry Andric       break;
7470b57cec5SDimitry Andric     default:
7480b57cec5SDimitry Andric       break;
7490b57cec5SDimitry Andric     }
7500b57cec5SDimitry Andric   }
7510b57cec5SDimitry Andric 
7520b57cec5SDimitry Andric   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
7530b57cec5SDimitry Andric }
7540b57cec5SDimitry Andric 
7550b57cec5SDimitry Andric bool WebAssemblyTargetLowering::isCheapToSpeculateCttz() const {
7560b57cec5SDimitry Andric   // Assume ctz is a relatively cheap operation.
7570b57cec5SDimitry Andric   return true;
7580b57cec5SDimitry Andric }
7590b57cec5SDimitry Andric 
7600b57cec5SDimitry Andric bool WebAssemblyTargetLowering::isCheapToSpeculateCtlz() const {
7610b57cec5SDimitry Andric   // Assume clz is a relatively cheap operation.
7620b57cec5SDimitry Andric   return true;
7630b57cec5SDimitry Andric }
7640b57cec5SDimitry Andric 
7650b57cec5SDimitry Andric bool WebAssemblyTargetLowering::isLegalAddressingMode(const DataLayout &DL,
7660b57cec5SDimitry Andric                                                       const AddrMode &AM,
7670b57cec5SDimitry Andric                                                       Type *Ty, unsigned AS,
7680b57cec5SDimitry Andric                                                       Instruction *I) const {
7690b57cec5SDimitry Andric   // WebAssembly offsets are added as unsigned without wrapping. The
7700b57cec5SDimitry Andric   // isLegalAddressingMode gives us no way to determine if wrapping could be
7710b57cec5SDimitry Andric   // happening, so we approximate this by accepting only non-negative offsets.
7720b57cec5SDimitry Andric   if (AM.BaseOffs < 0)
7730b57cec5SDimitry Andric     return false;
7740b57cec5SDimitry Andric 
7750b57cec5SDimitry Andric   // WebAssembly has no scale register operands.
7760b57cec5SDimitry Andric   if (AM.Scale != 0)
7770b57cec5SDimitry Andric     return false;
7780b57cec5SDimitry Andric 
7790b57cec5SDimitry Andric   // Everything else is legal.
7800b57cec5SDimitry Andric   return true;
7810b57cec5SDimitry Andric }
7820b57cec5SDimitry Andric 
7830b57cec5SDimitry Andric bool WebAssemblyTargetLowering::allowsMisalignedMemoryAccesses(
784fe6060f1SDimitry Andric     EVT /*VT*/, unsigned /*AddrSpace*/, Align /*Align*/,
7850b57cec5SDimitry Andric     MachineMemOperand::Flags /*Flags*/, bool *Fast) const {
7860b57cec5SDimitry Andric   // WebAssembly supports unaligned accesses, though it should be declared
7870b57cec5SDimitry Andric   // with the p2align attribute on loads and stores which do so, and there
7880b57cec5SDimitry Andric   // may be a performance impact. We tell LLVM they're "fast" because
7890b57cec5SDimitry Andric   // for the kinds of things that LLVM uses this for (merging adjacent stores
7900b57cec5SDimitry Andric   // of constants, etc.), WebAssembly implementations will either want the
7910b57cec5SDimitry Andric   // unaligned access or they'll split anyway.
7920b57cec5SDimitry Andric   if (Fast)
7930b57cec5SDimitry Andric     *Fast = true;
7940b57cec5SDimitry Andric   return true;
7950b57cec5SDimitry Andric }
7960b57cec5SDimitry Andric 
7970b57cec5SDimitry Andric bool WebAssemblyTargetLowering::isIntDivCheap(EVT VT,
7980b57cec5SDimitry Andric                                               AttributeList Attr) const {
7990b57cec5SDimitry Andric   // The current thinking is that wasm engines will perform this optimization,
8000b57cec5SDimitry Andric   // so we can save on code size.
8010b57cec5SDimitry Andric   return true;
8020b57cec5SDimitry Andric }
8030b57cec5SDimitry Andric 
8048bcb0991SDimitry Andric bool WebAssemblyTargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const {
80516d6b3b3SDimitry Andric   EVT ExtT = ExtVal.getValueType();
80616d6b3b3SDimitry Andric   EVT MemT = cast<LoadSDNode>(ExtVal->getOperand(0))->getValueType(0);
8078bcb0991SDimitry Andric   return (ExtT == MVT::v8i16 && MemT == MVT::v8i8) ||
8088bcb0991SDimitry Andric          (ExtT == MVT::v4i32 && MemT == MVT::v4i16) ||
8098bcb0991SDimitry Andric          (ExtT == MVT::v2i64 && MemT == MVT::v2i32);
8108bcb0991SDimitry Andric }
8118bcb0991SDimitry Andric 
812*349cc55cSDimitry Andric bool WebAssemblyTargetLowering::isOffsetFoldingLegal(
813*349cc55cSDimitry Andric     const GlobalAddressSDNode *GA) const {
814*349cc55cSDimitry Andric   // Wasm doesn't support function addresses with offsets
815*349cc55cSDimitry Andric   const GlobalValue *GV = GA->getGlobal();
816*349cc55cSDimitry Andric   return isa<Function>(GV) ? false : TargetLowering::isOffsetFoldingLegal(GA);
817*349cc55cSDimitry Andric }
818*349cc55cSDimitry Andric 
8190b57cec5SDimitry Andric EVT WebAssemblyTargetLowering::getSetCCResultType(const DataLayout &DL,
8200b57cec5SDimitry Andric                                                   LLVMContext &C,
8210b57cec5SDimitry Andric                                                   EVT VT) const {
8220b57cec5SDimitry Andric   if (VT.isVector())
8230b57cec5SDimitry Andric     return VT.changeVectorElementTypeToInteger();
8240b57cec5SDimitry Andric 
8255ffd83dbSDimitry Andric   // So far, all branch instructions in Wasm take an I32 condition.
8265ffd83dbSDimitry Andric   // The default TargetLowering::getSetCCResultType returns the pointer size,
8275ffd83dbSDimitry Andric   // which would be useful to reduce instruction counts when testing
8285ffd83dbSDimitry Andric   // against 64-bit pointers/values if at some point Wasm supports that.
8295ffd83dbSDimitry Andric   return EVT::getIntegerVT(C, 32);
8300b57cec5SDimitry Andric }
8310b57cec5SDimitry Andric 
8320b57cec5SDimitry Andric bool WebAssemblyTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
8330b57cec5SDimitry Andric                                                    const CallInst &I,
8340b57cec5SDimitry Andric                                                    MachineFunction &MF,
8350b57cec5SDimitry Andric                                                    unsigned Intrinsic) const {
8360b57cec5SDimitry Andric   switch (Intrinsic) {
837e8d8bef9SDimitry Andric   case Intrinsic::wasm_memory_atomic_notify:
8380b57cec5SDimitry Andric     Info.opc = ISD::INTRINSIC_W_CHAIN;
8390b57cec5SDimitry Andric     Info.memVT = MVT::i32;
8400b57cec5SDimitry Andric     Info.ptrVal = I.getArgOperand(0);
8410b57cec5SDimitry Andric     Info.offset = 0;
8428bcb0991SDimitry Andric     Info.align = Align(4);
8430b57cec5SDimitry Andric     // atomic.notify instruction does not really load the memory specified with
8440b57cec5SDimitry Andric     // this argument, but MachineMemOperand should either be load or store, so
8450b57cec5SDimitry Andric     // we set this to a load.
8460b57cec5SDimitry Andric     // FIXME Volatile isn't really correct, but currently all LLVM atomic
8470b57cec5SDimitry Andric     // instructions are treated as volatiles in the backend, so we should be
8480b57cec5SDimitry Andric     // consistent. The same applies for wasm_atomic_wait intrinsics too.
8490b57cec5SDimitry Andric     Info.flags = MachineMemOperand::MOVolatile | MachineMemOperand::MOLoad;
8500b57cec5SDimitry Andric     return true;
851e8d8bef9SDimitry Andric   case Intrinsic::wasm_memory_atomic_wait32:
8520b57cec5SDimitry Andric     Info.opc = ISD::INTRINSIC_W_CHAIN;
8530b57cec5SDimitry Andric     Info.memVT = MVT::i32;
8540b57cec5SDimitry Andric     Info.ptrVal = I.getArgOperand(0);
8550b57cec5SDimitry Andric     Info.offset = 0;
8568bcb0991SDimitry Andric     Info.align = Align(4);
8570b57cec5SDimitry Andric     Info.flags = MachineMemOperand::MOVolatile | MachineMemOperand::MOLoad;
8580b57cec5SDimitry Andric     return true;
859e8d8bef9SDimitry Andric   case Intrinsic::wasm_memory_atomic_wait64:
8600b57cec5SDimitry Andric     Info.opc = ISD::INTRINSIC_W_CHAIN;
8610b57cec5SDimitry Andric     Info.memVT = MVT::i64;
8620b57cec5SDimitry Andric     Info.ptrVal = I.getArgOperand(0);
8630b57cec5SDimitry Andric     Info.offset = 0;
8648bcb0991SDimitry Andric     Info.align = Align(8);
8650b57cec5SDimitry Andric     Info.flags = MachineMemOperand::MOVolatile | MachineMemOperand::MOLoad;
8660b57cec5SDimitry Andric     return true;
8670b57cec5SDimitry Andric   default:
8680b57cec5SDimitry Andric     return false;
8690b57cec5SDimitry Andric   }
8700b57cec5SDimitry Andric }
8710b57cec5SDimitry Andric 
872*349cc55cSDimitry Andric void WebAssemblyTargetLowering::computeKnownBitsForTargetNode(
873*349cc55cSDimitry Andric     const SDValue Op, KnownBits &Known, const APInt &DemandedElts,
874*349cc55cSDimitry Andric     const SelectionDAG &DAG, unsigned Depth) const {
875*349cc55cSDimitry Andric   switch (Op.getOpcode()) {
876*349cc55cSDimitry Andric   default:
877*349cc55cSDimitry Andric     break;
878*349cc55cSDimitry Andric   case ISD::INTRINSIC_WO_CHAIN: {
879*349cc55cSDimitry Andric     unsigned IntNo = Op.getConstantOperandVal(0);
880*349cc55cSDimitry Andric     switch (IntNo) {
881*349cc55cSDimitry Andric     default:
882*349cc55cSDimitry Andric       break;
883*349cc55cSDimitry Andric     case Intrinsic::wasm_bitmask: {
884*349cc55cSDimitry Andric       unsigned BitWidth = Known.getBitWidth();
885*349cc55cSDimitry Andric       EVT VT = Op.getOperand(1).getSimpleValueType();
886*349cc55cSDimitry Andric       unsigned PossibleBits = VT.getVectorNumElements();
887*349cc55cSDimitry Andric       APInt ZeroMask = APInt::getHighBitsSet(BitWidth, BitWidth - PossibleBits);
888*349cc55cSDimitry Andric       Known.Zero |= ZeroMask;
889*349cc55cSDimitry Andric       break;
890*349cc55cSDimitry Andric     }
891*349cc55cSDimitry Andric     }
892*349cc55cSDimitry Andric   }
893*349cc55cSDimitry Andric   }
894*349cc55cSDimitry Andric }
895*349cc55cSDimitry Andric 
896*349cc55cSDimitry Andric TargetLoweringBase::LegalizeTypeAction
897*349cc55cSDimitry Andric WebAssemblyTargetLowering::getPreferredVectorAction(MVT VT) const {
898*349cc55cSDimitry Andric   if (VT.isFixedLengthVector()) {
899*349cc55cSDimitry Andric     MVT EltVT = VT.getVectorElementType();
900*349cc55cSDimitry Andric     // We have legal vector types with these lane types, so widening the
901*349cc55cSDimitry Andric     // vector would let us use some of the lanes directly without having to
902*349cc55cSDimitry Andric     // extend or truncate values.
903*349cc55cSDimitry Andric     if (EltVT == MVT::i8 || EltVT == MVT::i16 || EltVT == MVT::i32 ||
904*349cc55cSDimitry Andric         EltVT == MVT::i64 || EltVT == MVT::f32 || EltVT == MVT::f64)
905*349cc55cSDimitry Andric       return TypeWidenVector;
906*349cc55cSDimitry Andric   }
907*349cc55cSDimitry Andric 
908*349cc55cSDimitry Andric   return TargetLoweringBase::getPreferredVectorAction(VT);
909*349cc55cSDimitry Andric }
910*349cc55cSDimitry Andric 
9110b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
9120b57cec5SDimitry Andric // WebAssembly Lowering private implementation.
9130b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
9140b57cec5SDimitry Andric 
9150b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
9160b57cec5SDimitry Andric // Lowering Code
9170b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
9180b57cec5SDimitry Andric 
9190b57cec5SDimitry Andric static void fail(const SDLoc &DL, SelectionDAG &DAG, const char *Msg) {
9200b57cec5SDimitry Andric   MachineFunction &MF = DAG.getMachineFunction();
9210b57cec5SDimitry Andric   DAG.getContext()->diagnose(
9220b57cec5SDimitry Andric       DiagnosticInfoUnsupported(MF.getFunction(), Msg, DL.getDebugLoc()));
9230b57cec5SDimitry Andric }
9240b57cec5SDimitry Andric 
9250b57cec5SDimitry Andric // Test whether the given calling convention is supported.
9260b57cec5SDimitry Andric static bool callingConvSupported(CallingConv::ID CallConv) {
9270b57cec5SDimitry Andric   // We currently support the language-independent target-independent
9280b57cec5SDimitry Andric   // conventions. We don't yet have a way to annotate calls with properties like
9290b57cec5SDimitry Andric   // "cold", and we don't have any call-clobbered registers, so these are mostly
9300b57cec5SDimitry Andric   // all handled the same.
9310b57cec5SDimitry Andric   return CallConv == CallingConv::C || CallConv == CallingConv::Fast ||
9320b57cec5SDimitry Andric          CallConv == CallingConv::Cold ||
9330b57cec5SDimitry Andric          CallConv == CallingConv::PreserveMost ||
9340b57cec5SDimitry Andric          CallConv == CallingConv::PreserveAll ||
9358bcb0991SDimitry Andric          CallConv == CallingConv::CXX_FAST_TLS ||
9365ffd83dbSDimitry Andric          CallConv == CallingConv::WASM_EmscriptenInvoke ||
9375ffd83dbSDimitry Andric          CallConv == CallingConv::Swift;
9380b57cec5SDimitry Andric }
9390b57cec5SDimitry Andric 
9400b57cec5SDimitry Andric SDValue
9410b57cec5SDimitry Andric WebAssemblyTargetLowering::LowerCall(CallLoweringInfo &CLI,
9420b57cec5SDimitry Andric                                      SmallVectorImpl<SDValue> &InVals) const {
9430b57cec5SDimitry Andric   SelectionDAG &DAG = CLI.DAG;
9440b57cec5SDimitry Andric   SDLoc DL = CLI.DL;
9450b57cec5SDimitry Andric   SDValue Chain = CLI.Chain;
9460b57cec5SDimitry Andric   SDValue Callee = CLI.Callee;
9470b57cec5SDimitry Andric   MachineFunction &MF = DAG.getMachineFunction();
9480b57cec5SDimitry Andric   auto Layout = MF.getDataLayout();
9490b57cec5SDimitry Andric 
9500b57cec5SDimitry Andric   CallingConv::ID CallConv = CLI.CallConv;
9510b57cec5SDimitry Andric   if (!callingConvSupported(CallConv))
9520b57cec5SDimitry Andric     fail(DL, DAG,
9530b57cec5SDimitry Andric          "WebAssembly doesn't support language-specific or target-specific "
9540b57cec5SDimitry Andric          "calling conventions yet");
9550b57cec5SDimitry Andric   if (CLI.IsPatchPoint)
9560b57cec5SDimitry Andric     fail(DL, DAG, "WebAssembly doesn't support patch point yet");
9570b57cec5SDimitry Andric 
9588bcb0991SDimitry Andric   if (CLI.IsTailCall) {
9595ffd83dbSDimitry Andric     auto NoTail = [&](const char *Msg) {
9605ffd83dbSDimitry Andric       if (CLI.CB && CLI.CB->isMustTailCall())
9615ffd83dbSDimitry Andric         fail(DL, DAG, Msg);
9625ffd83dbSDimitry Andric       CLI.IsTailCall = false;
9635ffd83dbSDimitry Andric     };
9645ffd83dbSDimitry Andric 
9655ffd83dbSDimitry Andric     if (!Subtarget->hasTailCall())
9665ffd83dbSDimitry Andric       NoTail("WebAssembly 'tail-call' feature not enabled");
9675ffd83dbSDimitry Andric 
9685ffd83dbSDimitry Andric     // Varargs calls cannot be tail calls because the buffer is on the stack
9695ffd83dbSDimitry Andric     if (CLI.IsVarArg)
9705ffd83dbSDimitry Andric       NoTail("WebAssembly does not support varargs tail calls");
9715ffd83dbSDimitry Andric 
9728bcb0991SDimitry Andric     // Do not tail call unless caller and callee return types match
9738bcb0991SDimitry Andric     const Function &F = MF.getFunction();
9748bcb0991SDimitry Andric     const TargetMachine &TM = getTargetMachine();
9758bcb0991SDimitry Andric     Type *RetTy = F.getReturnType();
9768bcb0991SDimitry Andric     SmallVector<MVT, 4> CallerRetTys;
9778bcb0991SDimitry Andric     SmallVector<MVT, 4> CalleeRetTys;
9788bcb0991SDimitry Andric     computeLegalValueVTs(F, TM, RetTy, CallerRetTys);
9798bcb0991SDimitry Andric     computeLegalValueVTs(F, TM, CLI.RetTy, CalleeRetTys);
9808bcb0991SDimitry Andric     bool TypesMatch = CallerRetTys.size() == CalleeRetTys.size() &&
9818bcb0991SDimitry Andric                       std::equal(CallerRetTys.begin(), CallerRetTys.end(),
9828bcb0991SDimitry Andric                                  CalleeRetTys.begin());
9835ffd83dbSDimitry Andric     if (!TypesMatch)
9845ffd83dbSDimitry Andric       NoTail("WebAssembly tail call requires caller and callee return types to "
9855ffd83dbSDimitry Andric              "match");
9865ffd83dbSDimitry Andric 
9875ffd83dbSDimitry Andric     // If pointers to local stack values are passed, we cannot tail call
9885ffd83dbSDimitry Andric     if (CLI.CB) {
9895ffd83dbSDimitry Andric       for (auto &Arg : CLI.CB->args()) {
9905ffd83dbSDimitry Andric         Value *Val = Arg.get();
9915ffd83dbSDimitry Andric         // Trace the value back through pointer operations
9925ffd83dbSDimitry Andric         while (true) {
9935ffd83dbSDimitry Andric           Value *Src = Val->stripPointerCastsAndAliases();
9945ffd83dbSDimitry Andric           if (auto *GEP = dyn_cast<GetElementPtrInst>(Src))
9955ffd83dbSDimitry Andric             Src = GEP->getPointerOperand();
9965ffd83dbSDimitry Andric           if (Val == Src)
9975ffd83dbSDimitry Andric             break;
9985ffd83dbSDimitry Andric           Val = Src;
9990b57cec5SDimitry Andric         }
10005ffd83dbSDimitry Andric         if (isa<AllocaInst>(Val)) {
10015ffd83dbSDimitry Andric           NoTail(
10025ffd83dbSDimitry Andric               "WebAssembly does not support tail calling with stack arguments");
10035ffd83dbSDimitry Andric           break;
10048bcb0991SDimitry Andric         }
10058bcb0991SDimitry Andric       }
10068bcb0991SDimitry Andric     }
10078bcb0991SDimitry Andric   }
10080b57cec5SDimitry Andric 
10090b57cec5SDimitry Andric   SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
10100b57cec5SDimitry Andric   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
10110b57cec5SDimitry Andric   SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
10128bcb0991SDimitry Andric 
10138bcb0991SDimitry Andric   // The generic code may have added an sret argument. If we're lowering an
10148bcb0991SDimitry Andric   // invoke function, the ABI requires that the function pointer be the first
10158bcb0991SDimitry Andric   // argument, so we may have to swap the arguments.
10168bcb0991SDimitry Andric   if (CallConv == CallingConv::WASM_EmscriptenInvoke && Outs.size() >= 2 &&
10178bcb0991SDimitry Andric       Outs[0].Flags.isSRet()) {
10188bcb0991SDimitry Andric     std::swap(Outs[0], Outs[1]);
10198bcb0991SDimitry Andric     std::swap(OutVals[0], OutVals[1]);
10208bcb0991SDimitry Andric   }
10218bcb0991SDimitry Andric 
10225ffd83dbSDimitry Andric   bool HasSwiftSelfArg = false;
10235ffd83dbSDimitry Andric   bool HasSwiftErrorArg = false;
10240b57cec5SDimitry Andric   unsigned NumFixedArgs = 0;
10250b57cec5SDimitry Andric   for (unsigned I = 0; I < Outs.size(); ++I) {
10260b57cec5SDimitry Andric     const ISD::OutputArg &Out = Outs[I];
10270b57cec5SDimitry Andric     SDValue &OutVal = OutVals[I];
10285ffd83dbSDimitry Andric     HasSwiftSelfArg |= Out.Flags.isSwiftSelf();
10295ffd83dbSDimitry Andric     HasSwiftErrorArg |= Out.Flags.isSwiftError();
10300b57cec5SDimitry Andric     if (Out.Flags.isNest())
10310b57cec5SDimitry Andric       fail(DL, DAG, "WebAssembly hasn't implemented nest arguments");
10320b57cec5SDimitry Andric     if (Out.Flags.isInAlloca())
10330b57cec5SDimitry Andric       fail(DL, DAG, "WebAssembly hasn't implemented inalloca arguments");
10340b57cec5SDimitry Andric     if (Out.Flags.isInConsecutiveRegs())
10350b57cec5SDimitry Andric       fail(DL, DAG, "WebAssembly hasn't implemented cons regs arguments");
10360b57cec5SDimitry Andric     if (Out.Flags.isInConsecutiveRegsLast())
10370b57cec5SDimitry Andric       fail(DL, DAG, "WebAssembly hasn't implemented cons regs last arguments");
10380b57cec5SDimitry Andric     if (Out.Flags.isByVal() && Out.Flags.getByValSize() != 0) {
10390b57cec5SDimitry Andric       auto &MFI = MF.getFrameInfo();
10400b57cec5SDimitry Andric       int FI = MFI.CreateStackObject(Out.Flags.getByValSize(),
10415ffd83dbSDimitry Andric                                      Out.Flags.getNonZeroByValAlign(),
10420b57cec5SDimitry Andric                                      /*isSS=*/false);
10430b57cec5SDimitry Andric       SDValue SizeNode =
10440b57cec5SDimitry Andric           DAG.getConstant(Out.Flags.getByValSize(), DL, MVT::i32);
10450b57cec5SDimitry Andric       SDValue FINode = DAG.getFrameIndex(FI, getPointerTy(Layout));
10460b57cec5SDimitry Andric       Chain = DAG.getMemcpy(
10475ffd83dbSDimitry Andric           Chain, DL, FINode, OutVal, SizeNode, Out.Flags.getNonZeroByValAlign(),
10480b57cec5SDimitry Andric           /*isVolatile*/ false, /*AlwaysInline=*/false,
10490b57cec5SDimitry Andric           /*isTailCall*/ false, MachinePointerInfo(), MachinePointerInfo());
10500b57cec5SDimitry Andric       OutVal = FINode;
10510b57cec5SDimitry Andric     }
10520b57cec5SDimitry Andric     // Count the number of fixed args *after* legalization.
10530b57cec5SDimitry Andric     NumFixedArgs += Out.IsFixed;
10540b57cec5SDimitry Andric   }
10550b57cec5SDimitry Andric 
10560b57cec5SDimitry Andric   bool IsVarArg = CLI.IsVarArg;
10570b57cec5SDimitry Andric   auto PtrVT = getPointerTy(Layout);
10580b57cec5SDimitry Andric 
10595ffd83dbSDimitry Andric   // For swiftcc, emit additional swiftself and swifterror arguments
10605ffd83dbSDimitry Andric   // if there aren't. These additional arguments are also added for callee
10615ffd83dbSDimitry Andric   // signature They are necessary to match callee and caller signature for
10625ffd83dbSDimitry Andric   // indirect call.
10635ffd83dbSDimitry Andric   if (CallConv == CallingConv::Swift) {
10645ffd83dbSDimitry Andric     if (!HasSwiftSelfArg) {
10655ffd83dbSDimitry Andric       NumFixedArgs++;
10665ffd83dbSDimitry Andric       ISD::OutputArg Arg;
10675ffd83dbSDimitry Andric       Arg.Flags.setSwiftSelf();
10685ffd83dbSDimitry Andric       CLI.Outs.push_back(Arg);
10695ffd83dbSDimitry Andric       SDValue ArgVal = DAG.getUNDEF(PtrVT);
10705ffd83dbSDimitry Andric       CLI.OutVals.push_back(ArgVal);
10715ffd83dbSDimitry Andric     }
10725ffd83dbSDimitry Andric     if (!HasSwiftErrorArg) {
10735ffd83dbSDimitry Andric       NumFixedArgs++;
10745ffd83dbSDimitry Andric       ISD::OutputArg Arg;
10755ffd83dbSDimitry Andric       Arg.Flags.setSwiftError();
10765ffd83dbSDimitry Andric       CLI.Outs.push_back(Arg);
10775ffd83dbSDimitry Andric       SDValue ArgVal = DAG.getUNDEF(PtrVT);
10785ffd83dbSDimitry Andric       CLI.OutVals.push_back(ArgVal);
10795ffd83dbSDimitry Andric     }
10805ffd83dbSDimitry Andric   }
10815ffd83dbSDimitry Andric 
10820b57cec5SDimitry Andric   // Analyze operands of the call, assigning locations to each operand.
10830b57cec5SDimitry Andric   SmallVector<CCValAssign, 16> ArgLocs;
10840b57cec5SDimitry Andric   CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
10850b57cec5SDimitry Andric 
10860b57cec5SDimitry Andric   if (IsVarArg) {
10870b57cec5SDimitry Andric     // Outgoing non-fixed arguments are placed in a buffer. First
10880b57cec5SDimitry Andric     // compute their offsets and the total amount of buffer space needed.
10890b57cec5SDimitry Andric     for (unsigned I = NumFixedArgs; I < Outs.size(); ++I) {
10900b57cec5SDimitry Andric       const ISD::OutputArg &Out = Outs[I];
10910b57cec5SDimitry Andric       SDValue &Arg = OutVals[I];
10920b57cec5SDimitry Andric       EVT VT = Arg.getValueType();
10930b57cec5SDimitry Andric       assert(VT != MVT::iPTR && "Legalized args should be concrete");
10940b57cec5SDimitry Andric       Type *Ty = VT.getTypeForEVT(*DAG.getContext());
10955ffd83dbSDimitry Andric       Align Alignment =
10965ffd83dbSDimitry Andric           std::max(Out.Flags.getNonZeroOrigAlign(), Layout.getABITypeAlign(Ty));
10975ffd83dbSDimitry Andric       unsigned Offset =
10985ffd83dbSDimitry Andric           CCInfo.AllocateStack(Layout.getTypeAllocSize(Ty), Alignment);
10990b57cec5SDimitry Andric       CCInfo.addLoc(CCValAssign::getMem(ArgLocs.size(), VT.getSimpleVT(),
11000b57cec5SDimitry Andric                                         Offset, VT.getSimpleVT(),
11010b57cec5SDimitry Andric                                         CCValAssign::Full));
11020b57cec5SDimitry Andric     }
11030b57cec5SDimitry Andric   }
11040b57cec5SDimitry Andric 
11050b57cec5SDimitry Andric   unsigned NumBytes = CCInfo.getAlignedCallFrameSize();
11060b57cec5SDimitry Andric 
11070b57cec5SDimitry Andric   SDValue FINode;
11080b57cec5SDimitry Andric   if (IsVarArg && NumBytes) {
11090b57cec5SDimitry Andric     // For non-fixed arguments, next emit stores to store the argument values
11100b57cec5SDimitry Andric     // to the stack buffer at the offsets computed above.
11110b57cec5SDimitry Andric     int FI = MF.getFrameInfo().CreateStackObject(NumBytes,
11120b57cec5SDimitry Andric                                                  Layout.getStackAlignment(),
11130b57cec5SDimitry Andric                                                  /*isSS=*/false);
11140b57cec5SDimitry Andric     unsigned ValNo = 0;
11150b57cec5SDimitry Andric     SmallVector<SDValue, 8> Chains;
1116e8d8bef9SDimitry Andric     for (SDValue Arg : drop_begin(OutVals, NumFixedArgs)) {
11170b57cec5SDimitry Andric       assert(ArgLocs[ValNo].getValNo() == ValNo &&
11180b57cec5SDimitry Andric              "ArgLocs should remain in order and only hold varargs args");
11190b57cec5SDimitry Andric       unsigned Offset = ArgLocs[ValNo++].getLocMemOffset();
11200b57cec5SDimitry Andric       FINode = DAG.getFrameIndex(FI, getPointerTy(Layout));
11210b57cec5SDimitry Andric       SDValue Add = DAG.getNode(ISD::ADD, DL, PtrVT, FINode,
11220b57cec5SDimitry Andric                                 DAG.getConstant(Offset, DL, PtrVT));
11230b57cec5SDimitry Andric       Chains.push_back(
11240b57cec5SDimitry Andric           DAG.getStore(Chain, DL, Arg, Add,
1125e8d8bef9SDimitry Andric                        MachinePointerInfo::getFixedStack(MF, FI, Offset)));
11260b57cec5SDimitry Andric     }
11270b57cec5SDimitry Andric     if (!Chains.empty())
11280b57cec5SDimitry Andric       Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
11290b57cec5SDimitry Andric   } else if (IsVarArg) {
11300b57cec5SDimitry Andric     FINode = DAG.getIntPtrConstant(0, DL);
11310b57cec5SDimitry Andric   }
11320b57cec5SDimitry Andric 
11330b57cec5SDimitry Andric   if (Callee->getOpcode() == ISD::GlobalAddress) {
11340b57cec5SDimitry Andric     // If the callee is a GlobalAddress node (quite common, every direct call
11350b57cec5SDimitry Andric     // is) turn it into a TargetGlobalAddress node so that LowerGlobalAddress
11360b57cec5SDimitry Andric     // doesn't at MO_GOT which is not needed for direct calls.
11370b57cec5SDimitry Andric     GlobalAddressSDNode* GA = cast<GlobalAddressSDNode>(Callee);
11380b57cec5SDimitry Andric     Callee = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
11390b57cec5SDimitry Andric                                         getPointerTy(DAG.getDataLayout()),
11400b57cec5SDimitry Andric                                         GA->getOffset());
11410b57cec5SDimitry Andric     Callee = DAG.getNode(WebAssemblyISD::Wrapper, DL,
11420b57cec5SDimitry Andric                          getPointerTy(DAG.getDataLayout()), Callee);
11430b57cec5SDimitry Andric   }
11440b57cec5SDimitry Andric 
11450b57cec5SDimitry Andric   // Compute the operands for the CALLn node.
11460b57cec5SDimitry Andric   SmallVector<SDValue, 16> Ops;
11470b57cec5SDimitry Andric   Ops.push_back(Chain);
11480b57cec5SDimitry Andric   Ops.push_back(Callee);
11490b57cec5SDimitry Andric 
11500b57cec5SDimitry Andric   // Add all fixed arguments. Note that for non-varargs calls, NumFixedArgs
11510b57cec5SDimitry Andric   // isn't reliable.
11520b57cec5SDimitry Andric   Ops.append(OutVals.begin(),
11530b57cec5SDimitry Andric              IsVarArg ? OutVals.begin() + NumFixedArgs : OutVals.end());
11540b57cec5SDimitry Andric   // Add a pointer to the vararg buffer.
11550b57cec5SDimitry Andric   if (IsVarArg)
11560b57cec5SDimitry Andric     Ops.push_back(FINode);
11570b57cec5SDimitry Andric 
11580b57cec5SDimitry Andric   SmallVector<EVT, 8> InTys;
11590b57cec5SDimitry Andric   for (const auto &In : Ins) {
11600b57cec5SDimitry Andric     assert(!In.Flags.isByVal() && "byval is not valid for return values");
11610b57cec5SDimitry Andric     assert(!In.Flags.isNest() && "nest is not valid for return values");
11620b57cec5SDimitry Andric     if (In.Flags.isInAlloca())
11630b57cec5SDimitry Andric       fail(DL, DAG, "WebAssembly hasn't implemented inalloca return values");
11640b57cec5SDimitry Andric     if (In.Flags.isInConsecutiveRegs())
11650b57cec5SDimitry Andric       fail(DL, DAG, "WebAssembly hasn't implemented cons regs return values");
11660b57cec5SDimitry Andric     if (In.Flags.isInConsecutiveRegsLast())
11670b57cec5SDimitry Andric       fail(DL, DAG,
11680b57cec5SDimitry Andric            "WebAssembly hasn't implemented cons regs last return values");
11695ffd83dbSDimitry Andric     // Ignore In.getNonZeroOrigAlign() because all our arguments are passed in
11700b57cec5SDimitry Andric     // registers.
11710b57cec5SDimitry Andric     InTys.push_back(In.VT);
11720b57cec5SDimitry Andric   }
11730b57cec5SDimitry Andric 
1174fe6060f1SDimitry Andric   // Lastly, if this is a call to a funcref we need to add an instruction
1175fe6060f1SDimitry Andric   // table.set to the chain and transform the call.
1176*349cc55cSDimitry Andric   if (CLI.CB &&
1177*349cc55cSDimitry Andric       WebAssembly::isFuncrefType(CLI.CB->getCalledOperand()->getType())) {
1178fe6060f1SDimitry Andric     // In the absence of function references proposal where a funcref call is
1179fe6060f1SDimitry Andric     // lowered to call_ref, using reference types we generate a table.set to set
1180fe6060f1SDimitry Andric     // the funcref to a special table used solely for this purpose, followed by
1181fe6060f1SDimitry Andric     // a call_indirect. Here we just generate the table set, and return the
1182fe6060f1SDimitry Andric     // SDValue of the table.set so that LowerCall can finalize the lowering by
1183fe6060f1SDimitry Andric     // generating the call_indirect.
1184fe6060f1SDimitry Andric     SDValue Chain = Ops[0];
1185fe6060f1SDimitry Andric 
1186fe6060f1SDimitry Andric     MCSymbolWasm *Table = WebAssembly::getOrCreateFuncrefCallTableSymbol(
1187fe6060f1SDimitry Andric         MF.getContext(), Subtarget);
1188fe6060f1SDimitry Andric     SDValue Sym = DAG.getMCSymbol(Table, PtrVT);
1189fe6060f1SDimitry Andric     SDValue TableSlot = DAG.getConstant(0, DL, MVT::i32);
1190fe6060f1SDimitry Andric     SDValue TableSetOps[] = {Chain, Sym, TableSlot, Callee};
1191fe6060f1SDimitry Andric     SDValue TableSet = DAG.getMemIntrinsicNode(
1192fe6060f1SDimitry Andric         WebAssemblyISD::TABLE_SET, DL, DAG.getVTList(MVT::Other), TableSetOps,
1193fe6060f1SDimitry Andric         MVT::funcref,
1194fe6060f1SDimitry Andric         // Machine Mem Operand args
1195*349cc55cSDimitry Andric         MachinePointerInfo(
1196*349cc55cSDimitry Andric             WebAssembly::WasmAddressSpace::WASM_ADDRESS_SPACE_FUNCREF),
1197fe6060f1SDimitry Andric         CLI.CB->getCalledOperand()->getPointerAlignment(DAG.getDataLayout()),
1198fe6060f1SDimitry Andric         MachineMemOperand::MOStore);
1199fe6060f1SDimitry Andric 
1200fe6060f1SDimitry Andric     Ops[0] = TableSet; // The new chain is the TableSet itself
1201fe6060f1SDimitry Andric   }
1202fe6060f1SDimitry Andric 
12030b57cec5SDimitry Andric   if (CLI.IsTailCall) {
12040b57cec5SDimitry Andric     // ret_calls do not return values to the current frame
12050b57cec5SDimitry Andric     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
12060b57cec5SDimitry Andric     return DAG.getNode(WebAssemblyISD::RET_CALL, DL, NodeTys, Ops);
12070b57cec5SDimitry Andric   }
12080b57cec5SDimitry Andric 
12090b57cec5SDimitry Andric   InTys.push_back(MVT::Other);
12100b57cec5SDimitry Andric   SDVTList InTyList = DAG.getVTList(InTys);
12115ffd83dbSDimitry Andric   SDValue Res = DAG.getNode(WebAssemblyISD::CALL, DL, InTyList, Ops);
12120b57cec5SDimitry Andric 
12135ffd83dbSDimitry Andric   for (size_t I = 0; I < Ins.size(); ++I)
12145ffd83dbSDimitry Andric     InVals.push_back(Res.getValue(I));
12155ffd83dbSDimitry Andric 
12165ffd83dbSDimitry Andric   // Return the chain
12175ffd83dbSDimitry Andric   return Res.getValue(Ins.size());
12180b57cec5SDimitry Andric }
12190b57cec5SDimitry Andric 
12200b57cec5SDimitry Andric bool WebAssemblyTargetLowering::CanLowerReturn(
12210b57cec5SDimitry Andric     CallingConv::ID /*CallConv*/, MachineFunction & /*MF*/, bool /*IsVarArg*/,
12220b57cec5SDimitry Andric     const SmallVectorImpl<ISD::OutputArg> &Outs,
12230b57cec5SDimitry Andric     LLVMContext & /*Context*/) const {
12248bcb0991SDimitry Andric   // WebAssembly can only handle returning tuples with multivalue enabled
12258bcb0991SDimitry Andric   return Subtarget->hasMultivalue() || Outs.size() <= 1;
12260b57cec5SDimitry Andric }
12270b57cec5SDimitry Andric 
12280b57cec5SDimitry Andric SDValue WebAssemblyTargetLowering::LowerReturn(
12290b57cec5SDimitry Andric     SDValue Chain, CallingConv::ID CallConv, bool /*IsVarArg*/,
12300b57cec5SDimitry Andric     const SmallVectorImpl<ISD::OutputArg> &Outs,
12310b57cec5SDimitry Andric     const SmallVectorImpl<SDValue> &OutVals, const SDLoc &DL,
12320b57cec5SDimitry Andric     SelectionDAG &DAG) const {
12338bcb0991SDimitry Andric   assert((Subtarget->hasMultivalue() || Outs.size() <= 1) &&
12348bcb0991SDimitry Andric          "MVP WebAssembly can only return up to one value");
12350b57cec5SDimitry Andric   if (!callingConvSupported(CallConv))
12360b57cec5SDimitry Andric     fail(DL, DAG, "WebAssembly doesn't support non-C calling conventions");
12370b57cec5SDimitry Andric 
12380b57cec5SDimitry Andric   SmallVector<SDValue, 4> RetOps(1, Chain);
12390b57cec5SDimitry Andric   RetOps.append(OutVals.begin(), OutVals.end());
12400b57cec5SDimitry Andric   Chain = DAG.getNode(WebAssemblyISD::RETURN, DL, MVT::Other, RetOps);
12410b57cec5SDimitry Andric 
12420b57cec5SDimitry Andric   // Record the number and types of the return values.
12430b57cec5SDimitry Andric   for (const ISD::OutputArg &Out : Outs) {
12440b57cec5SDimitry Andric     assert(!Out.Flags.isByVal() && "byval is not valid for return values");
12450b57cec5SDimitry Andric     assert(!Out.Flags.isNest() && "nest is not valid for return values");
12460b57cec5SDimitry Andric     assert(Out.IsFixed && "non-fixed return value is not valid");
12470b57cec5SDimitry Andric     if (Out.Flags.isInAlloca())
12480b57cec5SDimitry Andric       fail(DL, DAG, "WebAssembly hasn't implemented inalloca results");
12490b57cec5SDimitry Andric     if (Out.Flags.isInConsecutiveRegs())
12500b57cec5SDimitry Andric       fail(DL, DAG, "WebAssembly hasn't implemented cons regs results");
12510b57cec5SDimitry Andric     if (Out.Flags.isInConsecutiveRegsLast())
12520b57cec5SDimitry Andric       fail(DL, DAG, "WebAssembly hasn't implemented cons regs last results");
12530b57cec5SDimitry Andric   }
12540b57cec5SDimitry Andric 
12550b57cec5SDimitry Andric   return Chain;
12560b57cec5SDimitry Andric }
12570b57cec5SDimitry Andric 
12580b57cec5SDimitry Andric SDValue WebAssemblyTargetLowering::LowerFormalArguments(
12590b57cec5SDimitry Andric     SDValue Chain, CallingConv::ID CallConv, bool IsVarArg,
12600b57cec5SDimitry Andric     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
12610b57cec5SDimitry Andric     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
12620b57cec5SDimitry Andric   if (!callingConvSupported(CallConv))
12630b57cec5SDimitry Andric     fail(DL, DAG, "WebAssembly doesn't support non-C calling conventions");
12640b57cec5SDimitry Andric 
12650b57cec5SDimitry Andric   MachineFunction &MF = DAG.getMachineFunction();
12660b57cec5SDimitry Andric   auto *MFI = MF.getInfo<WebAssemblyFunctionInfo>();
12670b57cec5SDimitry Andric 
12680b57cec5SDimitry Andric   // Set up the incoming ARGUMENTS value, which serves to represent the liveness
12690b57cec5SDimitry Andric   // of the incoming values before they're represented by virtual registers.
12700b57cec5SDimitry Andric   MF.getRegInfo().addLiveIn(WebAssembly::ARGUMENTS);
12710b57cec5SDimitry Andric 
12725ffd83dbSDimitry Andric   bool HasSwiftErrorArg = false;
12735ffd83dbSDimitry Andric   bool HasSwiftSelfArg = false;
12740b57cec5SDimitry Andric   for (const ISD::InputArg &In : Ins) {
12755ffd83dbSDimitry Andric     HasSwiftSelfArg |= In.Flags.isSwiftSelf();
12765ffd83dbSDimitry Andric     HasSwiftErrorArg |= In.Flags.isSwiftError();
12770b57cec5SDimitry Andric     if (In.Flags.isInAlloca())
12780b57cec5SDimitry Andric       fail(DL, DAG, "WebAssembly hasn't implemented inalloca arguments");
12790b57cec5SDimitry Andric     if (In.Flags.isNest())
12800b57cec5SDimitry Andric       fail(DL, DAG, "WebAssembly hasn't implemented nest arguments");
12810b57cec5SDimitry Andric     if (In.Flags.isInConsecutiveRegs())
12820b57cec5SDimitry Andric       fail(DL, DAG, "WebAssembly hasn't implemented cons regs arguments");
12830b57cec5SDimitry Andric     if (In.Flags.isInConsecutiveRegsLast())
12840b57cec5SDimitry Andric       fail(DL, DAG, "WebAssembly hasn't implemented cons regs last arguments");
12855ffd83dbSDimitry Andric     // Ignore In.getNonZeroOrigAlign() because all our arguments are passed in
12860b57cec5SDimitry Andric     // registers.
12870b57cec5SDimitry Andric     InVals.push_back(In.Used ? DAG.getNode(WebAssemblyISD::ARGUMENT, DL, In.VT,
12880b57cec5SDimitry Andric                                            DAG.getTargetConstant(InVals.size(),
12890b57cec5SDimitry Andric                                                                  DL, MVT::i32))
12900b57cec5SDimitry Andric                              : DAG.getUNDEF(In.VT));
12910b57cec5SDimitry Andric 
12920b57cec5SDimitry Andric     // Record the number and types of arguments.
12930b57cec5SDimitry Andric     MFI->addParam(In.VT);
12940b57cec5SDimitry Andric   }
12950b57cec5SDimitry Andric 
12965ffd83dbSDimitry Andric   // For swiftcc, emit additional swiftself and swifterror arguments
12975ffd83dbSDimitry Andric   // if there aren't. These additional arguments are also added for callee
12985ffd83dbSDimitry Andric   // signature They are necessary to match callee and caller signature for
12995ffd83dbSDimitry Andric   // indirect call.
13005ffd83dbSDimitry Andric   auto PtrVT = getPointerTy(MF.getDataLayout());
13015ffd83dbSDimitry Andric   if (CallConv == CallingConv::Swift) {
13025ffd83dbSDimitry Andric     if (!HasSwiftSelfArg) {
13035ffd83dbSDimitry Andric       MFI->addParam(PtrVT);
13045ffd83dbSDimitry Andric     }
13055ffd83dbSDimitry Andric     if (!HasSwiftErrorArg) {
13065ffd83dbSDimitry Andric       MFI->addParam(PtrVT);
13075ffd83dbSDimitry Andric     }
13085ffd83dbSDimitry Andric   }
13090b57cec5SDimitry Andric   // Varargs are copied into a buffer allocated by the caller, and a pointer to
13100b57cec5SDimitry Andric   // the buffer is passed as an argument.
13110b57cec5SDimitry Andric   if (IsVarArg) {
13120b57cec5SDimitry Andric     MVT PtrVT = getPointerTy(MF.getDataLayout());
13138bcb0991SDimitry Andric     Register VarargVreg =
13140b57cec5SDimitry Andric         MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrVT));
13150b57cec5SDimitry Andric     MFI->setVarargBufferVreg(VarargVreg);
13160b57cec5SDimitry Andric     Chain = DAG.getCopyToReg(
13170b57cec5SDimitry Andric         Chain, DL, VarargVreg,
13180b57cec5SDimitry Andric         DAG.getNode(WebAssemblyISD::ARGUMENT, DL, PtrVT,
13190b57cec5SDimitry Andric                     DAG.getTargetConstant(Ins.size(), DL, MVT::i32)));
13200b57cec5SDimitry Andric     MFI->addParam(PtrVT);
13210b57cec5SDimitry Andric   }
13220b57cec5SDimitry Andric 
13230b57cec5SDimitry Andric   // Record the number and types of arguments and results.
13240b57cec5SDimitry Andric   SmallVector<MVT, 4> Params;
13250b57cec5SDimitry Andric   SmallVector<MVT, 4> Results;
13265ffd83dbSDimitry Andric   computeSignatureVTs(MF.getFunction().getFunctionType(), &MF.getFunction(),
13275ffd83dbSDimitry Andric                       MF.getFunction(), DAG.getTarget(), Params, Results);
13280b57cec5SDimitry Andric   for (MVT VT : Results)
13290b57cec5SDimitry Andric     MFI->addResult(VT);
13300b57cec5SDimitry Andric   // TODO: Use signatures in WebAssemblyMachineFunctionInfo too and unify
13310b57cec5SDimitry Andric   // the param logic here with ComputeSignatureVTs
13320b57cec5SDimitry Andric   assert(MFI->getParams().size() == Params.size() &&
13330b57cec5SDimitry Andric          std::equal(MFI->getParams().begin(), MFI->getParams().end(),
13340b57cec5SDimitry Andric                     Params.begin()));
13350b57cec5SDimitry Andric 
13360b57cec5SDimitry Andric   return Chain;
13370b57cec5SDimitry Andric }
13380b57cec5SDimitry Andric 
13390b57cec5SDimitry Andric void WebAssemblyTargetLowering::ReplaceNodeResults(
13400b57cec5SDimitry Andric     SDNode *N, SmallVectorImpl<SDValue> &Results, SelectionDAG &DAG) const {
13410b57cec5SDimitry Andric   switch (N->getOpcode()) {
13420b57cec5SDimitry Andric   case ISD::SIGN_EXTEND_INREG:
13430b57cec5SDimitry Andric     // Do not add any results, signifying that N should not be custom lowered
13440b57cec5SDimitry Andric     // after all. This happens because simd128 turns on custom lowering for
13450b57cec5SDimitry Andric     // SIGN_EXTEND_INREG, but for non-vector sign extends the result might be an
13460b57cec5SDimitry Andric     // illegal type.
13470b57cec5SDimitry Andric     break;
13480b57cec5SDimitry Andric   default:
13490b57cec5SDimitry Andric     llvm_unreachable(
13500b57cec5SDimitry Andric         "ReplaceNodeResults not implemented for this op for WebAssembly!");
13510b57cec5SDimitry Andric   }
13520b57cec5SDimitry Andric }
13530b57cec5SDimitry Andric 
13540b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
13550b57cec5SDimitry Andric //  Custom lowering hooks.
13560b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
13570b57cec5SDimitry Andric 
13580b57cec5SDimitry Andric SDValue WebAssemblyTargetLowering::LowerOperation(SDValue Op,
13590b57cec5SDimitry Andric                                                   SelectionDAG &DAG) const {
13600b57cec5SDimitry Andric   SDLoc DL(Op);
13610b57cec5SDimitry Andric   switch (Op.getOpcode()) {
13620b57cec5SDimitry Andric   default:
13630b57cec5SDimitry Andric     llvm_unreachable("unimplemented operation lowering");
13640b57cec5SDimitry Andric     return SDValue();
13650b57cec5SDimitry Andric   case ISD::FrameIndex:
13660b57cec5SDimitry Andric     return LowerFrameIndex(Op, DAG);
13670b57cec5SDimitry Andric   case ISD::GlobalAddress:
13680b57cec5SDimitry Andric     return LowerGlobalAddress(Op, DAG);
1369e8d8bef9SDimitry Andric   case ISD::GlobalTLSAddress:
1370e8d8bef9SDimitry Andric     return LowerGlobalTLSAddress(Op, DAG);
13710b57cec5SDimitry Andric   case ISD::ExternalSymbol:
13720b57cec5SDimitry Andric     return LowerExternalSymbol(Op, DAG);
13730b57cec5SDimitry Andric   case ISD::JumpTable:
13740b57cec5SDimitry Andric     return LowerJumpTable(Op, DAG);
13750b57cec5SDimitry Andric   case ISD::BR_JT:
13760b57cec5SDimitry Andric     return LowerBR_JT(Op, DAG);
13770b57cec5SDimitry Andric   case ISD::VASTART:
13780b57cec5SDimitry Andric     return LowerVASTART(Op, DAG);
13790b57cec5SDimitry Andric   case ISD::BlockAddress:
13800b57cec5SDimitry Andric   case ISD::BRIND:
13810b57cec5SDimitry Andric     fail(DL, DAG, "WebAssembly hasn't implemented computed gotos");
13820b57cec5SDimitry Andric     return SDValue();
13830b57cec5SDimitry Andric   case ISD::RETURNADDR:
13840b57cec5SDimitry Andric     return LowerRETURNADDR(Op, DAG);
13850b57cec5SDimitry Andric   case ISD::FRAMEADDR:
13860b57cec5SDimitry Andric     return LowerFRAMEADDR(Op, DAG);
13870b57cec5SDimitry Andric   case ISD::CopyToReg:
13880b57cec5SDimitry Andric     return LowerCopyToReg(Op, DAG);
13890b57cec5SDimitry Andric   case ISD::EXTRACT_VECTOR_ELT:
13900b57cec5SDimitry Andric   case ISD::INSERT_VECTOR_ELT:
13910b57cec5SDimitry Andric     return LowerAccessVectorElement(Op, DAG);
13920b57cec5SDimitry Andric   case ISD::INTRINSIC_VOID:
13930b57cec5SDimitry Andric   case ISD::INTRINSIC_WO_CHAIN:
13940b57cec5SDimitry Andric   case ISD::INTRINSIC_W_CHAIN:
13950b57cec5SDimitry Andric     return LowerIntrinsic(Op, DAG);
13960b57cec5SDimitry Andric   case ISD::SIGN_EXTEND_INREG:
13970b57cec5SDimitry Andric     return LowerSIGN_EXTEND_INREG(Op, DAG);
13980b57cec5SDimitry Andric   case ISD::BUILD_VECTOR:
13990b57cec5SDimitry Andric     return LowerBUILD_VECTOR(Op, DAG);
14000b57cec5SDimitry Andric   case ISD::VECTOR_SHUFFLE:
14010b57cec5SDimitry Andric     return LowerVECTOR_SHUFFLE(Op, DAG);
1402480093f4SDimitry Andric   case ISD::SETCC:
1403480093f4SDimitry Andric     return LowerSETCC(Op, DAG);
14040b57cec5SDimitry Andric   case ISD::SHL:
14050b57cec5SDimitry Andric   case ISD::SRA:
14060b57cec5SDimitry Andric   case ISD::SRL:
14070b57cec5SDimitry Andric     return LowerShift(Op, DAG);
1408fe6060f1SDimitry Andric   case ISD::FP_TO_SINT_SAT:
1409fe6060f1SDimitry Andric   case ISD::FP_TO_UINT_SAT:
1410fe6060f1SDimitry Andric     return LowerFP_TO_INT_SAT(Op, DAG);
1411fe6060f1SDimitry Andric   case ISD::LOAD:
1412fe6060f1SDimitry Andric     return LowerLoad(Op, DAG);
1413fe6060f1SDimitry Andric   case ISD::STORE:
1414fe6060f1SDimitry Andric     return LowerStore(Op, DAG);
1415*349cc55cSDimitry Andric   case ISD::CTPOP:
1416*349cc55cSDimitry Andric   case ISD::CTLZ:
1417*349cc55cSDimitry Andric   case ISD::CTTZ:
1418*349cc55cSDimitry Andric     return DAG.UnrollVectorOp(Op.getNode());
14190b57cec5SDimitry Andric   }
14200b57cec5SDimitry Andric }
14210b57cec5SDimitry Andric 
1422fe6060f1SDimitry Andric static bool IsWebAssemblyGlobal(SDValue Op) {
1423fe6060f1SDimitry Andric   if (const GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op))
1424fe6060f1SDimitry Andric     return WebAssembly::isWasmVarAddressSpace(GA->getAddressSpace());
1425fe6060f1SDimitry Andric 
1426fe6060f1SDimitry Andric   return false;
1427fe6060f1SDimitry Andric }
1428fe6060f1SDimitry Andric 
1429fe6060f1SDimitry Andric static Optional<unsigned> IsWebAssemblyLocal(SDValue Op, SelectionDAG &DAG) {
1430fe6060f1SDimitry Andric   const FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Op);
1431fe6060f1SDimitry Andric   if (!FI)
1432fe6060f1SDimitry Andric     return None;
1433fe6060f1SDimitry Andric 
1434fe6060f1SDimitry Andric   auto &MF = DAG.getMachineFunction();
1435fe6060f1SDimitry Andric   return WebAssemblyFrameLowering::getLocalForStackObject(MF, FI->getIndex());
1436fe6060f1SDimitry Andric }
1437fe6060f1SDimitry Andric 
1438*349cc55cSDimitry Andric static bool IsWebAssemblyTable(SDValue Op) {
1439*349cc55cSDimitry Andric   const GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op);
1440*349cc55cSDimitry Andric   if (GA && WebAssembly::isWasmVarAddressSpace(GA->getAddressSpace())) {
1441*349cc55cSDimitry Andric     const GlobalValue *Value = GA->getGlobal();
1442*349cc55cSDimitry Andric     const Type *Ty = Value->getValueType();
1443*349cc55cSDimitry Andric 
1444*349cc55cSDimitry Andric     if (Ty->isArrayTy() && WebAssembly::isRefType(Ty->getArrayElementType()))
1445*349cc55cSDimitry Andric       return true;
1446*349cc55cSDimitry Andric   }
1447*349cc55cSDimitry Andric   return false;
1448fe6060f1SDimitry Andric }
1449fe6060f1SDimitry Andric 
1450*349cc55cSDimitry Andric // This function will accept as Op any access to a table, so Op can
1451*349cc55cSDimitry Andric // be the actual table or an offset into the table.
1452*349cc55cSDimitry Andric static bool IsWebAssemblyTableWithOffset(SDValue Op) {
1453*349cc55cSDimitry Andric   if (Op->getOpcode() == ISD::ADD && Op->getNumOperands() == 2)
1454*349cc55cSDimitry Andric     return (Op->getOperand(1).getSimpleValueType() == MVT::i32 &&
1455*349cc55cSDimitry Andric             IsWebAssemblyTableWithOffset(Op->getOperand(0))) ||
1456*349cc55cSDimitry Andric            (Op->getOperand(0).getSimpleValueType() == MVT::i32 &&
1457*349cc55cSDimitry Andric             IsWebAssemblyTableWithOffset(Op->getOperand(1)));
1458*349cc55cSDimitry Andric 
1459*349cc55cSDimitry Andric   return IsWebAssemblyTable(Op);
1460*349cc55cSDimitry Andric }
1461*349cc55cSDimitry Andric 
1462*349cc55cSDimitry Andric // Helper for table pattern matching used in LowerStore and LowerLoad
1463*349cc55cSDimitry Andric bool WebAssemblyTargetLowering::MatchTableForLowering(SelectionDAG &DAG,
1464*349cc55cSDimitry Andric                                                       const SDLoc &DL,
1465*349cc55cSDimitry Andric                                                       const SDValue &Base,
1466*349cc55cSDimitry Andric                                                       GlobalAddressSDNode *&GA,
1467*349cc55cSDimitry Andric                                                       SDValue &Idx) const {
1468*349cc55cSDimitry Andric   // We expect the following graph for a load of the form:
1469*349cc55cSDimitry Andric   // table[<var> + <constant offset>]
1470*349cc55cSDimitry Andric   //
1471*349cc55cSDimitry Andric   // Case 1:
1472*349cc55cSDimitry Andric   // externref = load t1
1473*349cc55cSDimitry Andric   // t1: i32 = add t2, i32:<constant offset>
1474*349cc55cSDimitry Andric   // t2: i32 = add tX, table
1475*349cc55cSDimitry Andric   //
1476*349cc55cSDimitry Andric   // This is in some cases simplified to just:
1477*349cc55cSDimitry Andric   // Case 2:
1478*349cc55cSDimitry Andric   // externref = load t1
1479*349cc55cSDimitry Andric   // t1: i32 = add t2, i32:tX
1480*349cc55cSDimitry Andric   //
1481*349cc55cSDimitry Andric   // So, unfortunately we need to check for both cases and if we are in the
1482*349cc55cSDimitry Andric   // first case extract the table GlobalAddressNode and build a new node tY
1483*349cc55cSDimitry Andric   // that's tY: i32 = add i32:<constant offset>, i32:tX
1484*349cc55cSDimitry Andric   //
1485*349cc55cSDimitry Andric   if (IsWebAssemblyTable(Base)) {
1486*349cc55cSDimitry Andric     GA = cast<GlobalAddressSDNode>(Base);
1487*349cc55cSDimitry Andric     Idx = DAG.getConstant(0, DL, MVT::i32);
1488*349cc55cSDimitry Andric   } else {
1489*349cc55cSDimitry Andric     GA = dyn_cast<GlobalAddressSDNode>(Base->getOperand(0));
1490*349cc55cSDimitry Andric     if (GA) {
1491*349cc55cSDimitry Andric       // We are in Case 2 above.
1492*349cc55cSDimitry Andric       Idx = Base->getOperand(1);
1493*349cc55cSDimitry Andric       if (!Idx || GA->getNumValues() != 1 || Idx->getNumValues() != 1)
1494*349cc55cSDimitry Andric         return false;
1495*349cc55cSDimitry Andric     } else {
1496*349cc55cSDimitry Andric       // This might be Case 1 above (or an error)
1497*349cc55cSDimitry Andric       SDValue V = Base->getOperand(0);
1498*349cc55cSDimitry Andric       GA = dyn_cast<GlobalAddressSDNode>(V->getOperand(1));
1499*349cc55cSDimitry Andric 
1500*349cc55cSDimitry Andric       if (V->getOpcode() != ISD::ADD || V->getNumOperands() != 2 || !GA)
1501*349cc55cSDimitry Andric         return false;
1502*349cc55cSDimitry Andric 
1503*349cc55cSDimitry Andric       SDValue IdxV = DAG.getNode(ISD::ADD, DL, MVT::i32, Base->getOperand(1),
1504*349cc55cSDimitry Andric                                  V->getOperand(0));
1505*349cc55cSDimitry Andric       Idx = IdxV;
1506*349cc55cSDimitry Andric     }
1507*349cc55cSDimitry Andric   }
1508*349cc55cSDimitry Andric 
1509*349cc55cSDimitry Andric   return true;
1510fe6060f1SDimitry Andric }
1511fe6060f1SDimitry Andric 
1512fe6060f1SDimitry Andric SDValue WebAssemblyTargetLowering::LowerStore(SDValue Op,
1513fe6060f1SDimitry Andric                                               SelectionDAG &DAG) const {
1514fe6060f1SDimitry Andric   SDLoc DL(Op);
1515fe6060f1SDimitry Andric   StoreSDNode *SN = cast<StoreSDNode>(Op.getNode());
1516fe6060f1SDimitry Andric   const SDValue &Value = SN->getValue();
1517fe6060f1SDimitry Andric   const SDValue &Base = SN->getBasePtr();
1518fe6060f1SDimitry Andric   const SDValue &Offset = SN->getOffset();
1519fe6060f1SDimitry Andric 
1520*349cc55cSDimitry Andric   if (IsWebAssemblyTableWithOffset(Base)) {
1521*349cc55cSDimitry Andric     if (!Offset->isUndef())
1522*349cc55cSDimitry Andric       report_fatal_error(
1523*349cc55cSDimitry Andric           "unexpected offset when loading from webassembly table", false);
1524*349cc55cSDimitry Andric 
1525*349cc55cSDimitry Andric     SDValue Idx;
1526*349cc55cSDimitry Andric     GlobalAddressSDNode *GA;
1527*349cc55cSDimitry Andric 
1528*349cc55cSDimitry Andric     if (!MatchTableForLowering(DAG, DL, Base, GA, Idx))
1529*349cc55cSDimitry Andric       report_fatal_error("failed pattern matching for lowering table store",
1530*349cc55cSDimitry Andric                          false);
1531*349cc55cSDimitry Andric 
1532*349cc55cSDimitry Andric     SDVTList Tys = DAG.getVTList(MVT::Other);
1533*349cc55cSDimitry Andric     SDValue TableSetOps[] = {SN->getChain(), SDValue(GA, 0), Idx, Value};
1534*349cc55cSDimitry Andric     SDValue TableSet =
1535*349cc55cSDimitry Andric         DAG.getMemIntrinsicNode(WebAssemblyISD::TABLE_SET, DL, Tys, TableSetOps,
1536*349cc55cSDimitry Andric                                 SN->getMemoryVT(), SN->getMemOperand());
1537*349cc55cSDimitry Andric     return TableSet;
1538*349cc55cSDimitry Andric   }
1539*349cc55cSDimitry Andric 
1540fe6060f1SDimitry Andric   if (IsWebAssemblyGlobal(Base)) {
1541fe6060f1SDimitry Andric     if (!Offset->isUndef())
1542fe6060f1SDimitry Andric       report_fatal_error("unexpected offset when storing to webassembly global",
1543fe6060f1SDimitry Andric                          false);
1544fe6060f1SDimitry Andric 
1545fe6060f1SDimitry Andric     SDVTList Tys = DAG.getVTList(MVT::Other);
1546fe6060f1SDimitry Andric     SDValue Ops[] = {SN->getChain(), Value, Base};
1547fe6060f1SDimitry Andric     return DAG.getMemIntrinsicNode(WebAssemblyISD::GLOBAL_SET, DL, Tys, Ops,
1548fe6060f1SDimitry Andric                                    SN->getMemoryVT(), SN->getMemOperand());
1549fe6060f1SDimitry Andric   }
1550fe6060f1SDimitry Andric 
1551fe6060f1SDimitry Andric   if (Optional<unsigned> Local = IsWebAssemblyLocal(Base, DAG)) {
1552fe6060f1SDimitry Andric     if (!Offset->isUndef())
1553fe6060f1SDimitry Andric       report_fatal_error("unexpected offset when storing to webassembly local",
1554fe6060f1SDimitry Andric                          false);
1555fe6060f1SDimitry Andric 
1556fe6060f1SDimitry Andric     SDValue Idx = DAG.getTargetConstant(*Local, Base, MVT::i32);
1557fe6060f1SDimitry Andric     SDVTList Tys = DAG.getVTList(MVT::Other); // The chain.
1558fe6060f1SDimitry Andric     SDValue Ops[] = {SN->getChain(), Idx, Value};
1559fe6060f1SDimitry Andric     return DAG.getNode(WebAssemblyISD::LOCAL_SET, DL, Tys, Ops);
1560fe6060f1SDimitry Andric   }
1561fe6060f1SDimitry Andric 
1562fe6060f1SDimitry Andric   return Op;
1563fe6060f1SDimitry Andric }
1564fe6060f1SDimitry Andric 
1565fe6060f1SDimitry Andric SDValue WebAssemblyTargetLowering::LowerLoad(SDValue Op,
1566fe6060f1SDimitry Andric                                              SelectionDAG &DAG) const {
1567fe6060f1SDimitry Andric   SDLoc DL(Op);
1568fe6060f1SDimitry Andric   LoadSDNode *LN = cast<LoadSDNode>(Op.getNode());
1569fe6060f1SDimitry Andric   const SDValue &Base = LN->getBasePtr();
1570fe6060f1SDimitry Andric   const SDValue &Offset = LN->getOffset();
1571fe6060f1SDimitry Andric 
1572*349cc55cSDimitry Andric   if (IsWebAssemblyTableWithOffset(Base)) {
1573*349cc55cSDimitry Andric     if (!Offset->isUndef())
1574*349cc55cSDimitry Andric       report_fatal_error(
1575*349cc55cSDimitry Andric           "unexpected offset when loading from webassembly table", false);
1576*349cc55cSDimitry Andric 
1577*349cc55cSDimitry Andric     GlobalAddressSDNode *GA;
1578*349cc55cSDimitry Andric     SDValue Idx;
1579*349cc55cSDimitry Andric 
1580*349cc55cSDimitry Andric     if (!MatchTableForLowering(DAG, DL, Base, GA, Idx))
1581*349cc55cSDimitry Andric       report_fatal_error("failed pattern matching for lowering table load",
1582*349cc55cSDimitry Andric                          false);
1583*349cc55cSDimitry Andric 
1584*349cc55cSDimitry Andric     SDVTList Tys = DAG.getVTList(LN->getValueType(0), MVT::Other);
1585*349cc55cSDimitry Andric     SDValue TableGetOps[] = {LN->getChain(), SDValue(GA, 0), Idx};
1586*349cc55cSDimitry Andric     SDValue TableGet =
1587*349cc55cSDimitry Andric         DAG.getMemIntrinsicNode(WebAssemblyISD::TABLE_GET, DL, Tys, TableGetOps,
1588*349cc55cSDimitry Andric                                 LN->getMemoryVT(), LN->getMemOperand());
1589*349cc55cSDimitry Andric     return TableGet;
1590*349cc55cSDimitry Andric   }
1591*349cc55cSDimitry Andric 
1592fe6060f1SDimitry Andric   if (IsWebAssemblyGlobal(Base)) {
1593fe6060f1SDimitry Andric     if (!Offset->isUndef())
1594fe6060f1SDimitry Andric       report_fatal_error(
1595fe6060f1SDimitry Andric           "unexpected offset when loading from webassembly global", false);
1596fe6060f1SDimitry Andric 
1597fe6060f1SDimitry Andric     SDVTList Tys = DAG.getVTList(LN->getValueType(0), MVT::Other);
1598fe6060f1SDimitry Andric     SDValue Ops[] = {LN->getChain(), Base};
1599fe6060f1SDimitry Andric     return DAG.getMemIntrinsicNode(WebAssemblyISD::GLOBAL_GET, DL, Tys, Ops,
1600fe6060f1SDimitry Andric                                    LN->getMemoryVT(), LN->getMemOperand());
1601fe6060f1SDimitry Andric   }
1602fe6060f1SDimitry Andric 
1603fe6060f1SDimitry Andric   if (Optional<unsigned> Local = IsWebAssemblyLocal(Base, DAG)) {
1604fe6060f1SDimitry Andric     if (!Offset->isUndef())
1605fe6060f1SDimitry Andric       report_fatal_error(
1606fe6060f1SDimitry Andric           "unexpected offset when loading from webassembly local", false);
1607fe6060f1SDimitry Andric 
1608fe6060f1SDimitry Andric     SDValue Idx = DAG.getTargetConstant(*Local, Base, MVT::i32);
1609fe6060f1SDimitry Andric     EVT LocalVT = LN->getValueType(0);
1610fe6060f1SDimitry Andric     SDValue LocalGet = DAG.getNode(WebAssemblyISD::LOCAL_GET, DL, LocalVT,
1611fe6060f1SDimitry Andric                                    {LN->getChain(), Idx});
1612fe6060f1SDimitry Andric     SDValue Result = DAG.getMergeValues({LocalGet, LN->getChain()}, DL);
1613fe6060f1SDimitry Andric     assert(Result->getNumValues() == 2 && "Loads must carry a chain!");
1614fe6060f1SDimitry Andric     return Result;
1615fe6060f1SDimitry Andric   }
1616fe6060f1SDimitry Andric 
1617fe6060f1SDimitry Andric   return Op;
1618fe6060f1SDimitry Andric }
1619fe6060f1SDimitry Andric 
16200b57cec5SDimitry Andric SDValue WebAssemblyTargetLowering::LowerCopyToReg(SDValue Op,
16210b57cec5SDimitry Andric                                                   SelectionDAG &DAG) const {
16220b57cec5SDimitry Andric   SDValue Src = Op.getOperand(2);
16230b57cec5SDimitry Andric   if (isa<FrameIndexSDNode>(Src.getNode())) {
16240b57cec5SDimitry Andric     // CopyToReg nodes don't support FrameIndex operands. Other targets select
16250b57cec5SDimitry Andric     // the FI to some LEA-like instruction, but since we don't have that, we
16260b57cec5SDimitry Andric     // need to insert some kind of instruction that can take an FI operand and
16270b57cec5SDimitry Andric     // produces a value usable by CopyToReg (i.e. in a vreg). So insert a dummy
16280b57cec5SDimitry Andric     // local.copy between Op and its FI operand.
16290b57cec5SDimitry Andric     SDValue Chain = Op.getOperand(0);
16300b57cec5SDimitry Andric     SDLoc DL(Op);
16310b57cec5SDimitry Andric     unsigned Reg = cast<RegisterSDNode>(Op.getOperand(1))->getReg();
16320b57cec5SDimitry Andric     EVT VT = Src.getValueType();
16330b57cec5SDimitry Andric     SDValue Copy(DAG.getMachineNode(VT == MVT::i32 ? WebAssembly::COPY_I32
16340b57cec5SDimitry Andric                                                    : WebAssembly::COPY_I64,
16350b57cec5SDimitry Andric                                     DL, VT, Src),
16360b57cec5SDimitry Andric                  0);
16370b57cec5SDimitry Andric     return Op.getNode()->getNumValues() == 1
16380b57cec5SDimitry Andric                ? DAG.getCopyToReg(Chain, DL, Reg, Copy)
16390b57cec5SDimitry Andric                : DAG.getCopyToReg(Chain, DL, Reg, Copy,
16400b57cec5SDimitry Andric                                   Op.getNumOperands() == 4 ? Op.getOperand(3)
16410b57cec5SDimitry Andric                                                            : SDValue());
16420b57cec5SDimitry Andric   }
16430b57cec5SDimitry Andric   return SDValue();
16440b57cec5SDimitry Andric }
16450b57cec5SDimitry Andric 
16460b57cec5SDimitry Andric SDValue WebAssemblyTargetLowering::LowerFrameIndex(SDValue Op,
16470b57cec5SDimitry Andric                                                    SelectionDAG &DAG) const {
16480b57cec5SDimitry Andric   int FI = cast<FrameIndexSDNode>(Op)->getIndex();
16490b57cec5SDimitry Andric   return DAG.getTargetFrameIndex(FI, Op.getValueType());
16500b57cec5SDimitry Andric }
16510b57cec5SDimitry Andric 
16520b57cec5SDimitry Andric SDValue WebAssemblyTargetLowering::LowerRETURNADDR(SDValue Op,
16530b57cec5SDimitry Andric                                                    SelectionDAG &DAG) const {
16540b57cec5SDimitry Andric   SDLoc DL(Op);
16550b57cec5SDimitry Andric 
16560b57cec5SDimitry Andric   if (!Subtarget->getTargetTriple().isOSEmscripten()) {
16570b57cec5SDimitry Andric     fail(DL, DAG,
16580b57cec5SDimitry Andric          "Non-Emscripten WebAssembly hasn't implemented "
16590b57cec5SDimitry Andric          "__builtin_return_address");
16600b57cec5SDimitry Andric     return SDValue();
16610b57cec5SDimitry Andric   }
16620b57cec5SDimitry Andric 
16630b57cec5SDimitry Andric   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
16640b57cec5SDimitry Andric     return SDValue();
16650b57cec5SDimitry Andric 
1666*349cc55cSDimitry Andric   unsigned Depth = Op.getConstantOperandVal(0);
16678bcb0991SDimitry Andric   MakeLibCallOptions CallOptions;
16680b57cec5SDimitry Andric   return makeLibCall(DAG, RTLIB::RETURN_ADDRESS, Op.getValueType(),
16698bcb0991SDimitry Andric                      {DAG.getConstant(Depth, DL, MVT::i32)}, CallOptions, DL)
16700b57cec5SDimitry Andric       .first;
16710b57cec5SDimitry Andric }
16720b57cec5SDimitry Andric 
16730b57cec5SDimitry Andric SDValue WebAssemblyTargetLowering::LowerFRAMEADDR(SDValue Op,
16740b57cec5SDimitry Andric                                                   SelectionDAG &DAG) const {
16750b57cec5SDimitry Andric   // Non-zero depths are not supported by WebAssembly currently. Use the
16760b57cec5SDimitry Andric   // legalizer's default expansion, which is to return 0 (what this function is
16770b57cec5SDimitry Andric   // documented to do).
16780b57cec5SDimitry Andric   if (Op.getConstantOperandVal(0) > 0)
16790b57cec5SDimitry Andric     return SDValue();
16800b57cec5SDimitry Andric 
16810b57cec5SDimitry Andric   DAG.getMachineFunction().getFrameInfo().setFrameAddressIsTaken(true);
16820b57cec5SDimitry Andric   EVT VT = Op.getValueType();
16838bcb0991SDimitry Andric   Register FP =
16840b57cec5SDimitry Andric       Subtarget->getRegisterInfo()->getFrameRegister(DAG.getMachineFunction());
16850b57cec5SDimitry Andric   return DAG.getCopyFromReg(DAG.getEntryNode(), SDLoc(Op), FP, VT);
16860b57cec5SDimitry Andric }
16870b57cec5SDimitry Andric 
1688e8d8bef9SDimitry Andric SDValue
1689e8d8bef9SDimitry Andric WebAssemblyTargetLowering::LowerGlobalTLSAddress(SDValue Op,
1690e8d8bef9SDimitry Andric                                                  SelectionDAG &DAG) const {
1691e8d8bef9SDimitry Andric   SDLoc DL(Op);
1692e8d8bef9SDimitry Andric   const auto *GA = cast<GlobalAddressSDNode>(Op);
1693e8d8bef9SDimitry Andric 
1694e8d8bef9SDimitry Andric   MachineFunction &MF = DAG.getMachineFunction();
1695e8d8bef9SDimitry Andric   if (!MF.getSubtarget<WebAssemblySubtarget>().hasBulkMemory())
1696e8d8bef9SDimitry Andric     report_fatal_error("cannot use thread-local storage without bulk memory",
1697e8d8bef9SDimitry Andric                        false);
1698e8d8bef9SDimitry Andric 
1699e8d8bef9SDimitry Andric   const GlobalValue *GV = GA->getGlobal();
1700e8d8bef9SDimitry Andric 
1701e8d8bef9SDimitry Andric   // Currently Emscripten does not support dynamic linking with threads.
1702e8d8bef9SDimitry Andric   // Therefore, if we have thread-local storage, only the local-exec model
1703e8d8bef9SDimitry Andric   // is possible.
1704e8d8bef9SDimitry Andric   // TODO: remove this and implement proper TLS models once Emscripten
1705e8d8bef9SDimitry Andric   // supports dynamic linking with threads.
1706e8d8bef9SDimitry Andric   if (GV->getThreadLocalMode() != GlobalValue::LocalExecTLSModel &&
1707e8d8bef9SDimitry Andric       !Subtarget->getTargetTriple().isOSEmscripten()) {
1708e8d8bef9SDimitry Andric     report_fatal_error("only -ftls-model=local-exec is supported for now on "
1709e8d8bef9SDimitry Andric                        "non-Emscripten OSes: variable " +
1710e8d8bef9SDimitry Andric                            GV->getName(),
1711e8d8bef9SDimitry Andric                        false);
1712e8d8bef9SDimitry Andric   }
1713e8d8bef9SDimitry Andric 
1714*349cc55cSDimitry Andric   auto model = GV->getThreadLocalMode();
1715*349cc55cSDimitry Andric 
1716*349cc55cSDimitry Andric   // Unsupported TLS modes
1717*349cc55cSDimitry Andric   assert(model != GlobalValue::NotThreadLocal);
1718*349cc55cSDimitry Andric   assert(model != GlobalValue::InitialExecTLSModel);
1719*349cc55cSDimitry Andric 
1720*349cc55cSDimitry Andric   if (model == GlobalValue::LocalExecTLSModel ||
1721*349cc55cSDimitry Andric       model == GlobalValue::LocalDynamicTLSModel ||
1722*349cc55cSDimitry Andric       (model == GlobalValue::GeneralDynamicTLSModel &&
1723*349cc55cSDimitry Andric        getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV))) {
1724*349cc55cSDimitry Andric     // For DSO-local TLS variables we use offset from __tls_base
1725*349cc55cSDimitry Andric 
1726*349cc55cSDimitry Andric     MVT PtrVT = getPointerTy(DAG.getDataLayout());
1727e8d8bef9SDimitry Andric     auto GlobalGet = PtrVT == MVT::i64 ? WebAssembly::GLOBAL_GET_I64
1728e8d8bef9SDimitry Andric                                        : WebAssembly::GLOBAL_GET_I32;
1729e8d8bef9SDimitry Andric     const char *BaseName = MF.createExternalSymbolName("__tls_base");
1730e8d8bef9SDimitry Andric 
1731e8d8bef9SDimitry Andric     SDValue BaseAddr(
1732e8d8bef9SDimitry Andric         DAG.getMachineNode(GlobalGet, DL, PtrVT,
1733e8d8bef9SDimitry Andric                            DAG.getTargetExternalSymbol(BaseName, PtrVT)),
1734e8d8bef9SDimitry Andric         0);
1735e8d8bef9SDimitry Andric 
1736e8d8bef9SDimitry Andric     SDValue TLSOffset = DAG.getTargetGlobalAddress(
1737e8d8bef9SDimitry Andric         GV, DL, PtrVT, GA->getOffset(), WebAssemblyII::MO_TLS_BASE_REL);
1738*349cc55cSDimitry Andric     SDValue SymOffset =
1739*349cc55cSDimitry Andric         DAG.getNode(WebAssemblyISD::WrapperREL, DL, PtrVT, TLSOffset);
1740e8d8bef9SDimitry Andric 
1741*349cc55cSDimitry Andric     return DAG.getNode(ISD::ADD, DL, PtrVT, BaseAddr, SymOffset);
1742*349cc55cSDimitry Andric   }
1743*349cc55cSDimitry Andric 
1744*349cc55cSDimitry Andric   assert(model == GlobalValue::GeneralDynamicTLSModel);
1745*349cc55cSDimitry Andric 
1746*349cc55cSDimitry Andric   EVT VT = Op.getValueType();
1747*349cc55cSDimitry Andric   return DAG.getNode(WebAssemblyISD::Wrapper, DL, VT,
1748*349cc55cSDimitry Andric                      DAG.getTargetGlobalAddress(GA->getGlobal(), DL, VT,
1749*349cc55cSDimitry Andric                                                 GA->getOffset(),
1750*349cc55cSDimitry Andric                                                 WebAssemblyII::MO_GOT_TLS));
1751e8d8bef9SDimitry Andric }
1752e8d8bef9SDimitry Andric 
17530b57cec5SDimitry Andric SDValue WebAssemblyTargetLowering::LowerGlobalAddress(SDValue Op,
17540b57cec5SDimitry Andric                                                       SelectionDAG &DAG) const {
17550b57cec5SDimitry Andric   SDLoc DL(Op);
17560b57cec5SDimitry Andric   const auto *GA = cast<GlobalAddressSDNode>(Op);
17570b57cec5SDimitry Andric   EVT VT = Op.getValueType();
17580b57cec5SDimitry Andric   assert(GA->getTargetFlags() == 0 &&
17590b57cec5SDimitry Andric          "Unexpected target flags on generic GlobalAddressSDNode");
1760fe6060f1SDimitry Andric   if (!WebAssembly::isValidAddressSpace(GA->getAddressSpace()))
1761fe6060f1SDimitry Andric     fail(DL, DAG, "Invalid address space for WebAssembly target");
17620b57cec5SDimitry Andric 
17630b57cec5SDimitry Andric   unsigned OperandFlags = 0;
17640b57cec5SDimitry Andric   if (isPositionIndependent()) {
17650b57cec5SDimitry Andric     const GlobalValue *GV = GA->getGlobal();
17660b57cec5SDimitry Andric     if (getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV)) {
17670b57cec5SDimitry Andric       MachineFunction &MF = DAG.getMachineFunction();
17680b57cec5SDimitry Andric       MVT PtrVT = getPointerTy(MF.getDataLayout());
17690b57cec5SDimitry Andric       const char *BaseName;
17700b57cec5SDimitry Andric       if (GV->getValueType()->isFunctionTy()) {
17710b57cec5SDimitry Andric         BaseName = MF.createExternalSymbolName("__table_base");
17720b57cec5SDimitry Andric         OperandFlags = WebAssemblyII::MO_TABLE_BASE_REL;
17730b57cec5SDimitry Andric       }
17740b57cec5SDimitry Andric       else {
17750b57cec5SDimitry Andric         BaseName = MF.createExternalSymbolName("__memory_base");
17760b57cec5SDimitry Andric         OperandFlags = WebAssemblyII::MO_MEMORY_BASE_REL;
17770b57cec5SDimitry Andric       }
17780b57cec5SDimitry Andric       SDValue BaseAddr =
17790b57cec5SDimitry Andric           DAG.getNode(WebAssemblyISD::Wrapper, DL, PtrVT,
17800b57cec5SDimitry Andric                       DAG.getTargetExternalSymbol(BaseName, PtrVT));
17810b57cec5SDimitry Andric 
17820b57cec5SDimitry Andric       SDValue SymAddr = DAG.getNode(
1783*349cc55cSDimitry Andric           WebAssemblyISD::WrapperREL, DL, VT,
17840b57cec5SDimitry Andric           DAG.getTargetGlobalAddress(GA->getGlobal(), DL, VT, GA->getOffset(),
17850b57cec5SDimitry Andric                                      OperandFlags));
17860b57cec5SDimitry Andric 
17870b57cec5SDimitry Andric       return DAG.getNode(ISD::ADD, DL, VT, BaseAddr, SymAddr);
17880b57cec5SDimitry Andric     }
1789*349cc55cSDimitry Andric     OperandFlags = WebAssemblyII::MO_GOT;
17900b57cec5SDimitry Andric   }
17910b57cec5SDimitry Andric 
17920b57cec5SDimitry Andric   return DAG.getNode(WebAssemblyISD::Wrapper, DL, VT,
17930b57cec5SDimitry Andric                      DAG.getTargetGlobalAddress(GA->getGlobal(), DL, VT,
17940b57cec5SDimitry Andric                                                 GA->getOffset(), OperandFlags));
17950b57cec5SDimitry Andric }
17960b57cec5SDimitry Andric 
17970b57cec5SDimitry Andric SDValue
17980b57cec5SDimitry Andric WebAssemblyTargetLowering::LowerExternalSymbol(SDValue Op,
17990b57cec5SDimitry Andric                                                SelectionDAG &DAG) const {
18000b57cec5SDimitry Andric   SDLoc DL(Op);
18010b57cec5SDimitry Andric   const auto *ES = cast<ExternalSymbolSDNode>(Op);
18020b57cec5SDimitry Andric   EVT VT = Op.getValueType();
18030b57cec5SDimitry Andric   assert(ES->getTargetFlags() == 0 &&
18040b57cec5SDimitry Andric          "Unexpected target flags on generic ExternalSymbolSDNode");
18050b57cec5SDimitry Andric   return DAG.getNode(WebAssemblyISD::Wrapper, DL, VT,
18060b57cec5SDimitry Andric                      DAG.getTargetExternalSymbol(ES->getSymbol(), VT));
18070b57cec5SDimitry Andric }
18080b57cec5SDimitry Andric 
18090b57cec5SDimitry Andric SDValue WebAssemblyTargetLowering::LowerJumpTable(SDValue Op,
18100b57cec5SDimitry Andric                                                   SelectionDAG &DAG) const {
18110b57cec5SDimitry Andric   // There's no need for a Wrapper node because we always incorporate a jump
18120b57cec5SDimitry Andric   // table operand into a BR_TABLE instruction, rather than ever
18130b57cec5SDimitry Andric   // materializing it in a register.
18140b57cec5SDimitry Andric   const JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
18150b57cec5SDimitry Andric   return DAG.getTargetJumpTable(JT->getIndex(), Op.getValueType(),
18160b57cec5SDimitry Andric                                 JT->getTargetFlags());
18170b57cec5SDimitry Andric }
18180b57cec5SDimitry Andric 
18190b57cec5SDimitry Andric SDValue WebAssemblyTargetLowering::LowerBR_JT(SDValue Op,
18200b57cec5SDimitry Andric                                               SelectionDAG &DAG) const {
18210b57cec5SDimitry Andric   SDLoc DL(Op);
18220b57cec5SDimitry Andric   SDValue Chain = Op.getOperand(0);
18230b57cec5SDimitry Andric   const auto *JT = cast<JumpTableSDNode>(Op.getOperand(1));
18240b57cec5SDimitry Andric   SDValue Index = Op.getOperand(2);
18250b57cec5SDimitry Andric   assert(JT->getTargetFlags() == 0 && "WebAssembly doesn't set target flags");
18260b57cec5SDimitry Andric 
18270b57cec5SDimitry Andric   SmallVector<SDValue, 8> Ops;
18280b57cec5SDimitry Andric   Ops.push_back(Chain);
18290b57cec5SDimitry Andric   Ops.push_back(Index);
18300b57cec5SDimitry Andric 
18310b57cec5SDimitry Andric   MachineJumpTableInfo *MJTI = DAG.getMachineFunction().getJumpTableInfo();
18320b57cec5SDimitry Andric   const auto &MBBs = MJTI->getJumpTables()[JT->getIndex()].MBBs;
18330b57cec5SDimitry Andric 
18340b57cec5SDimitry Andric   // Add an operand for each case.
18350b57cec5SDimitry Andric   for (auto MBB : MBBs)
18360b57cec5SDimitry Andric     Ops.push_back(DAG.getBasicBlock(MBB));
18370b57cec5SDimitry Andric 
18385ffd83dbSDimitry Andric   // Add the first MBB as a dummy default target for now. This will be replaced
18395ffd83dbSDimitry Andric   // with the proper default target (and the preceding range check eliminated)
18405ffd83dbSDimitry Andric   // if possible by WebAssemblyFixBrTableDefaults.
18415ffd83dbSDimitry Andric   Ops.push_back(DAG.getBasicBlock(*MBBs.begin()));
18420b57cec5SDimitry Andric   return DAG.getNode(WebAssemblyISD::BR_TABLE, DL, MVT::Other, Ops);
18430b57cec5SDimitry Andric }
18440b57cec5SDimitry Andric 
18450b57cec5SDimitry Andric SDValue WebAssemblyTargetLowering::LowerVASTART(SDValue Op,
18460b57cec5SDimitry Andric                                                 SelectionDAG &DAG) const {
18470b57cec5SDimitry Andric   SDLoc DL(Op);
18480b57cec5SDimitry Andric   EVT PtrVT = getPointerTy(DAG.getMachineFunction().getDataLayout());
18490b57cec5SDimitry Andric 
18500b57cec5SDimitry Andric   auto *MFI = DAG.getMachineFunction().getInfo<WebAssemblyFunctionInfo>();
18510b57cec5SDimitry Andric   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
18520b57cec5SDimitry Andric 
18530b57cec5SDimitry Andric   SDValue ArgN = DAG.getCopyFromReg(DAG.getEntryNode(), DL,
18540b57cec5SDimitry Andric                                     MFI->getVarargBufferVreg(), PtrVT);
18550b57cec5SDimitry Andric   return DAG.getStore(Op.getOperand(0), DL, ArgN, Op.getOperand(1),
1856e8d8bef9SDimitry Andric                       MachinePointerInfo(SV));
1857e8d8bef9SDimitry Andric }
1858e8d8bef9SDimitry Andric 
18590b57cec5SDimitry Andric SDValue WebAssemblyTargetLowering::LowerIntrinsic(SDValue Op,
18600b57cec5SDimitry Andric                                                   SelectionDAG &DAG) const {
18610b57cec5SDimitry Andric   MachineFunction &MF = DAG.getMachineFunction();
18620b57cec5SDimitry Andric   unsigned IntNo;
18630b57cec5SDimitry Andric   switch (Op.getOpcode()) {
18640b57cec5SDimitry Andric   case ISD::INTRINSIC_VOID:
18650b57cec5SDimitry Andric   case ISD::INTRINSIC_W_CHAIN:
1866*349cc55cSDimitry Andric     IntNo = Op.getConstantOperandVal(1);
18670b57cec5SDimitry Andric     break;
18680b57cec5SDimitry Andric   case ISD::INTRINSIC_WO_CHAIN:
1869*349cc55cSDimitry Andric     IntNo = Op.getConstantOperandVal(0);
18700b57cec5SDimitry Andric     break;
18710b57cec5SDimitry Andric   default:
18720b57cec5SDimitry Andric     llvm_unreachable("Invalid intrinsic");
18730b57cec5SDimitry Andric   }
18740b57cec5SDimitry Andric   SDLoc DL(Op);
18750b57cec5SDimitry Andric 
18760b57cec5SDimitry Andric   switch (IntNo) {
18770b57cec5SDimitry Andric   default:
18780b57cec5SDimitry Andric     return SDValue(); // Don't custom lower most intrinsics.
18790b57cec5SDimitry Andric 
18800b57cec5SDimitry Andric   case Intrinsic::wasm_lsda: {
1881*349cc55cSDimitry Andric     auto PtrVT = getPointerTy(MF.getDataLayout());
1882*349cc55cSDimitry Andric     const char *SymName = MF.createExternalSymbolName(
1883*349cc55cSDimitry Andric         "GCC_except_table" + std::to_string(MF.getFunctionNumber()));
1884*349cc55cSDimitry Andric     if (isPositionIndependent()) {
1885*349cc55cSDimitry Andric       SDValue Node = DAG.getTargetExternalSymbol(
1886*349cc55cSDimitry Andric           SymName, PtrVT, WebAssemblyII::MO_MEMORY_BASE_REL);
1887*349cc55cSDimitry Andric       const char *BaseName = MF.createExternalSymbolName("__memory_base");
1888*349cc55cSDimitry Andric       SDValue BaseAddr =
1889*349cc55cSDimitry Andric           DAG.getNode(WebAssemblyISD::Wrapper, DL, PtrVT,
1890*349cc55cSDimitry Andric                       DAG.getTargetExternalSymbol(BaseName, PtrVT));
1891*349cc55cSDimitry Andric       SDValue SymAddr =
1892*349cc55cSDimitry Andric           DAG.getNode(WebAssemblyISD::WrapperREL, DL, PtrVT, Node);
1893*349cc55cSDimitry Andric       return DAG.getNode(ISD::ADD, DL, PtrVT, BaseAddr, SymAddr);
18940b57cec5SDimitry Andric     }
1895*349cc55cSDimitry Andric     SDValue Node = DAG.getTargetExternalSymbol(SymName, PtrVT);
1896*349cc55cSDimitry Andric     return DAG.getNode(WebAssemblyISD::Wrapper, DL, PtrVT, Node);
1897e8d8bef9SDimitry Andric   }
1898e8d8bef9SDimitry Andric 
18995ffd83dbSDimitry Andric   case Intrinsic::wasm_shuffle: {
19005ffd83dbSDimitry Andric     // Drop in-chain and replace undefs, but otherwise pass through unchanged
19015ffd83dbSDimitry Andric     SDValue Ops[18];
19025ffd83dbSDimitry Andric     size_t OpIdx = 0;
19035ffd83dbSDimitry Andric     Ops[OpIdx++] = Op.getOperand(1);
19045ffd83dbSDimitry Andric     Ops[OpIdx++] = Op.getOperand(2);
19055ffd83dbSDimitry Andric     while (OpIdx < 18) {
19065ffd83dbSDimitry Andric       const SDValue &MaskIdx = Op.getOperand(OpIdx + 1);
19075ffd83dbSDimitry Andric       if (MaskIdx.isUndef() ||
19085ffd83dbSDimitry Andric           cast<ConstantSDNode>(MaskIdx.getNode())->getZExtValue() >= 32) {
19095ffd83dbSDimitry Andric         Ops[OpIdx++] = DAG.getConstant(0, DL, MVT::i32);
19105ffd83dbSDimitry Andric       } else {
19115ffd83dbSDimitry Andric         Ops[OpIdx++] = MaskIdx;
19125ffd83dbSDimitry Andric       }
19135ffd83dbSDimitry Andric     }
19145ffd83dbSDimitry Andric     return DAG.getNode(WebAssemblyISD::SHUFFLE, DL, Op.getValueType(), Ops);
19155ffd83dbSDimitry Andric   }
19160b57cec5SDimitry Andric   }
19170b57cec5SDimitry Andric }
19180b57cec5SDimitry Andric 
19190b57cec5SDimitry Andric SDValue
19200b57cec5SDimitry Andric WebAssemblyTargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
19210b57cec5SDimitry Andric                                                   SelectionDAG &DAG) const {
19220b57cec5SDimitry Andric   SDLoc DL(Op);
19230b57cec5SDimitry Andric   // If sign extension operations are disabled, allow sext_inreg only if operand
19245ffd83dbSDimitry Andric   // is a vector extract of an i8 or i16 lane. SIMD does not depend on sign
19255ffd83dbSDimitry Andric   // extension operations, but allowing sext_inreg in this context lets us have
19265ffd83dbSDimitry Andric   // simple patterns to select extract_lane_s instructions. Expanding sext_inreg
19275ffd83dbSDimitry Andric   // everywhere would be simpler in this file, but would necessitate large and
19285ffd83dbSDimitry Andric   // brittle patterns to undo the expansion and select extract_lane_s
19295ffd83dbSDimitry Andric   // instructions.
19300b57cec5SDimitry Andric   assert(!Subtarget->hasSignExt() && Subtarget->hasSIMD128());
19315ffd83dbSDimitry Andric   if (Op.getOperand(0).getOpcode() != ISD::EXTRACT_VECTOR_ELT)
19325ffd83dbSDimitry Andric     return SDValue();
19335ffd83dbSDimitry Andric 
19340b57cec5SDimitry Andric   const SDValue &Extract = Op.getOperand(0);
19350b57cec5SDimitry Andric   MVT VecT = Extract.getOperand(0).getSimpleValueType();
19365ffd83dbSDimitry Andric   if (VecT.getVectorElementType().getSizeInBits() > 32)
19375ffd83dbSDimitry Andric     return SDValue();
19385ffd83dbSDimitry Andric   MVT ExtractedLaneT =
19395ffd83dbSDimitry Andric       cast<VTSDNode>(Op.getOperand(1).getNode())->getVT().getSimpleVT();
19400b57cec5SDimitry Andric   MVT ExtractedVecT =
19410b57cec5SDimitry Andric       MVT::getVectorVT(ExtractedLaneT, 128 / ExtractedLaneT.getSizeInBits());
19420b57cec5SDimitry Andric   if (ExtractedVecT == VecT)
19430b57cec5SDimitry Andric     return Op;
19445ffd83dbSDimitry Andric 
19450b57cec5SDimitry Andric   // Bitcast vector to appropriate type to ensure ISel pattern coverage
19465ffd83dbSDimitry Andric   const SDNode *Index = Extract.getOperand(1).getNode();
19475ffd83dbSDimitry Andric   if (!isa<ConstantSDNode>(Index))
19485ffd83dbSDimitry Andric     return SDValue();
19495ffd83dbSDimitry Andric   unsigned IndexVal = cast<ConstantSDNode>(Index)->getZExtValue();
19500b57cec5SDimitry Andric   unsigned Scale =
19510b57cec5SDimitry Andric       ExtractedVecT.getVectorNumElements() / VecT.getVectorNumElements();
19520b57cec5SDimitry Andric   assert(Scale > 1);
19530b57cec5SDimitry Andric   SDValue NewIndex =
19545ffd83dbSDimitry Andric       DAG.getConstant(IndexVal * Scale, DL, Index->getValueType(0));
19550b57cec5SDimitry Andric   SDValue NewExtract = DAG.getNode(
19560b57cec5SDimitry Andric       ISD::EXTRACT_VECTOR_ELT, DL, Extract.getValueType(),
19570b57cec5SDimitry Andric       DAG.getBitcast(ExtractedVecT, Extract.getOperand(0)), NewIndex);
19585ffd83dbSDimitry Andric   return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, Op.getValueType(), NewExtract,
19595ffd83dbSDimitry Andric                      Op.getOperand(1));
19600b57cec5SDimitry Andric }
19610b57cec5SDimitry Andric 
1962*349cc55cSDimitry Andric static SDValue LowerConvertLow(SDValue Op, SelectionDAG &DAG) {
1963*349cc55cSDimitry Andric   SDLoc DL(Op);
1964*349cc55cSDimitry Andric   if (Op.getValueType() != MVT::v2f64)
1965*349cc55cSDimitry Andric     return SDValue();
1966*349cc55cSDimitry Andric 
1967*349cc55cSDimitry Andric   auto GetConvertedLane = [](SDValue Op, unsigned &Opcode, SDValue &SrcVec,
1968*349cc55cSDimitry Andric                              unsigned &Index) -> bool {
1969*349cc55cSDimitry Andric     switch (Op.getOpcode()) {
1970*349cc55cSDimitry Andric     case ISD::SINT_TO_FP:
1971*349cc55cSDimitry Andric       Opcode = WebAssemblyISD::CONVERT_LOW_S;
1972*349cc55cSDimitry Andric       break;
1973*349cc55cSDimitry Andric     case ISD::UINT_TO_FP:
1974*349cc55cSDimitry Andric       Opcode = WebAssemblyISD::CONVERT_LOW_U;
1975*349cc55cSDimitry Andric       break;
1976*349cc55cSDimitry Andric     case ISD::FP_EXTEND:
1977*349cc55cSDimitry Andric       Opcode = WebAssemblyISD::PROMOTE_LOW;
1978*349cc55cSDimitry Andric       break;
1979*349cc55cSDimitry Andric     default:
1980*349cc55cSDimitry Andric       return false;
1981*349cc55cSDimitry Andric     }
1982*349cc55cSDimitry Andric 
1983*349cc55cSDimitry Andric     auto ExtractVector = Op.getOperand(0);
1984*349cc55cSDimitry Andric     if (ExtractVector.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
1985*349cc55cSDimitry Andric       return false;
1986*349cc55cSDimitry Andric 
1987*349cc55cSDimitry Andric     if (!isa<ConstantSDNode>(ExtractVector.getOperand(1).getNode()))
1988*349cc55cSDimitry Andric       return false;
1989*349cc55cSDimitry Andric 
1990*349cc55cSDimitry Andric     SrcVec = ExtractVector.getOperand(0);
1991*349cc55cSDimitry Andric     Index = ExtractVector.getConstantOperandVal(1);
1992*349cc55cSDimitry Andric     return true;
1993*349cc55cSDimitry Andric   };
1994*349cc55cSDimitry Andric 
1995*349cc55cSDimitry Andric   unsigned LHSOpcode, RHSOpcode, LHSIndex, RHSIndex;
1996*349cc55cSDimitry Andric   SDValue LHSSrcVec, RHSSrcVec;
1997*349cc55cSDimitry Andric   if (!GetConvertedLane(Op.getOperand(0), LHSOpcode, LHSSrcVec, LHSIndex) ||
1998*349cc55cSDimitry Andric       !GetConvertedLane(Op.getOperand(1), RHSOpcode, RHSSrcVec, RHSIndex))
1999*349cc55cSDimitry Andric     return SDValue();
2000*349cc55cSDimitry Andric 
2001*349cc55cSDimitry Andric   if (LHSOpcode != RHSOpcode)
2002*349cc55cSDimitry Andric     return SDValue();
2003*349cc55cSDimitry Andric 
2004*349cc55cSDimitry Andric   MVT ExpectedSrcVT;
2005*349cc55cSDimitry Andric   switch (LHSOpcode) {
2006*349cc55cSDimitry Andric   case WebAssemblyISD::CONVERT_LOW_S:
2007*349cc55cSDimitry Andric   case WebAssemblyISD::CONVERT_LOW_U:
2008*349cc55cSDimitry Andric     ExpectedSrcVT = MVT::v4i32;
2009*349cc55cSDimitry Andric     break;
2010*349cc55cSDimitry Andric   case WebAssemblyISD::PROMOTE_LOW:
2011*349cc55cSDimitry Andric     ExpectedSrcVT = MVT::v4f32;
2012*349cc55cSDimitry Andric     break;
2013*349cc55cSDimitry Andric   }
2014*349cc55cSDimitry Andric   if (LHSSrcVec.getValueType() != ExpectedSrcVT)
2015*349cc55cSDimitry Andric     return SDValue();
2016*349cc55cSDimitry Andric 
2017*349cc55cSDimitry Andric   auto Src = LHSSrcVec;
2018*349cc55cSDimitry Andric   if (LHSIndex != 0 || RHSIndex != 1 || LHSSrcVec != RHSSrcVec) {
2019*349cc55cSDimitry Andric     // Shuffle the source vector so that the converted lanes are the low lanes.
2020*349cc55cSDimitry Andric     Src = DAG.getVectorShuffle(
2021*349cc55cSDimitry Andric         ExpectedSrcVT, DL, LHSSrcVec, RHSSrcVec,
2022*349cc55cSDimitry Andric         {static_cast<int>(LHSIndex), static_cast<int>(RHSIndex) + 4, -1, -1});
2023*349cc55cSDimitry Andric   }
2024*349cc55cSDimitry Andric   return DAG.getNode(LHSOpcode, DL, MVT::v2f64, Src);
2025*349cc55cSDimitry Andric }
2026*349cc55cSDimitry Andric 
20270b57cec5SDimitry Andric SDValue WebAssemblyTargetLowering::LowerBUILD_VECTOR(SDValue Op,
20280b57cec5SDimitry Andric                                                      SelectionDAG &DAG) const {
2029*349cc55cSDimitry Andric   if (auto ConvertLow = LowerConvertLow(Op, DAG))
2030*349cc55cSDimitry Andric     return ConvertLow;
2031*349cc55cSDimitry Andric 
20320b57cec5SDimitry Andric   SDLoc DL(Op);
20330b57cec5SDimitry Andric   const EVT VecT = Op.getValueType();
20340b57cec5SDimitry Andric   const EVT LaneT = Op.getOperand(0).getValueType();
20350b57cec5SDimitry Andric   const size_t Lanes = Op.getNumOperands();
20365ffd83dbSDimitry Andric   bool CanSwizzle = VecT == MVT::v16i8;
20378bcb0991SDimitry Andric 
20388bcb0991SDimitry Andric   // BUILD_VECTORs are lowered to the instruction that initializes the highest
20398bcb0991SDimitry Andric   // possible number of lanes at once followed by a sequence of replace_lane
20408bcb0991SDimitry Andric   // instructions to individually initialize any remaining lanes.
20418bcb0991SDimitry Andric 
20428bcb0991SDimitry Andric   // TODO: Tune this. For example, lanewise swizzling is very expensive, so
20438bcb0991SDimitry Andric   // swizzled lanes should be given greater weight.
20448bcb0991SDimitry Andric 
2045fe6060f1SDimitry Andric   // TODO: Investigate looping rather than always extracting/replacing specific
2046fe6060f1SDimitry Andric   // lanes to fill gaps.
20478bcb0991SDimitry Andric 
20480b57cec5SDimitry Andric   auto IsConstant = [](const SDValue &V) {
20490b57cec5SDimitry Andric     return V.getOpcode() == ISD::Constant || V.getOpcode() == ISD::ConstantFP;
20500b57cec5SDimitry Andric   };
20510b57cec5SDimitry Andric 
20528bcb0991SDimitry Andric   // Returns the source vector and index vector pair if they exist. Checks for:
20538bcb0991SDimitry Andric   //   (extract_vector_elt
20548bcb0991SDimitry Andric   //     $src,
20558bcb0991SDimitry Andric   //     (sign_extend_inreg (extract_vector_elt $indices, $i))
20568bcb0991SDimitry Andric   //   )
20578bcb0991SDimitry Andric   auto GetSwizzleSrcs = [](size_t I, const SDValue &Lane) {
20588bcb0991SDimitry Andric     auto Bail = std::make_pair(SDValue(), SDValue());
20598bcb0991SDimitry Andric     if (Lane->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
20608bcb0991SDimitry Andric       return Bail;
20618bcb0991SDimitry Andric     const SDValue &SwizzleSrc = Lane->getOperand(0);
20628bcb0991SDimitry Andric     const SDValue &IndexExt = Lane->getOperand(1);
20638bcb0991SDimitry Andric     if (IndexExt->getOpcode() != ISD::SIGN_EXTEND_INREG)
20648bcb0991SDimitry Andric       return Bail;
20658bcb0991SDimitry Andric     const SDValue &Index = IndexExt->getOperand(0);
20668bcb0991SDimitry Andric     if (Index->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
20678bcb0991SDimitry Andric       return Bail;
20688bcb0991SDimitry Andric     const SDValue &SwizzleIndices = Index->getOperand(0);
20698bcb0991SDimitry Andric     if (SwizzleSrc.getValueType() != MVT::v16i8 ||
20708bcb0991SDimitry Andric         SwizzleIndices.getValueType() != MVT::v16i8 ||
20718bcb0991SDimitry Andric         Index->getOperand(1)->getOpcode() != ISD::Constant ||
20728bcb0991SDimitry Andric         Index->getConstantOperandVal(1) != I)
20738bcb0991SDimitry Andric       return Bail;
20748bcb0991SDimitry Andric     return std::make_pair(SwizzleSrc, SwizzleIndices);
20758bcb0991SDimitry Andric   };
20768bcb0991SDimitry Andric 
2077fe6060f1SDimitry Andric   // If the lane is extracted from another vector at a constant index, return
2078fe6060f1SDimitry Andric   // that vector. The source vector must not have more lanes than the dest
2079fe6060f1SDimitry Andric   // because the shufflevector indices are in terms of the destination lanes and
2080fe6060f1SDimitry Andric   // would not be able to address the smaller individual source lanes.
2081fe6060f1SDimitry Andric   auto GetShuffleSrc = [&](const SDValue &Lane) {
2082fe6060f1SDimitry Andric     if (Lane->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
2083fe6060f1SDimitry Andric       return SDValue();
2084fe6060f1SDimitry Andric     if (!isa<ConstantSDNode>(Lane->getOperand(1).getNode()))
2085fe6060f1SDimitry Andric       return SDValue();
2086fe6060f1SDimitry Andric     if (Lane->getOperand(0).getValueType().getVectorNumElements() >
2087fe6060f1SDimitry Andric         VecT.getVectorNumElements())
2088fe6060f1SDimitry Andric       return SDValue();
2089fe6060f1SDimitry Andric     return Lane->getOperand(0);
2090fe6060f1SDimitry Andric   };
2091fe6060f1SDimitry Andric 
20928bcb0991SDimitry Andric   using ValueEntry = std::pair<SDValue, size_t>;
20938bcb0991SDimitry Andric   SmallVector<ValueEntry, 16> SplatValueCounts;
20948bcb0991SDimitry Andric 
20958bcb0991SDimitry Andric   using SwizzleEntry = std::pair<std::pair<SDValue, SDValue>, size_t>;
20968bcb0991SDimitry Andric   SmallVector<SwizzleEntry, 16> SwizzleCounts;
20978bcb0991SDimitry Andric 
2098fe6060f1SDimitry Andric   using ShuffleEntry = std::pair<SDValue, size_t>;
2099fe6060f1SDimitry Andric   SmallVector<ShuffleEntry, 16> ShuffleCounts;
2100fe6060f1SDimitry Andric 
21018bcb0991SDimitry Andric   auto AddCount = [](auto &Counts, const auto &Val) {
2102e8d8bef9SDimitry Andric     auto CountIt =
2103e8d8bef9SDimitry Andric         llvm::find_if(Counts, [&Val](auto E) { return E.first == Val; });
21048bcb0991SDimitry Andric     if (CountIt == Counts.end()) {
21058bcb0991SDimitry Andric       Counts.emplace_back(Val, 1);
21060b57cec5SDimitry Andric     } else {
21070b57cec5SDimitry Andric       CountIt->second++;
21080b57cec5SDimitry Andric     }
21098bcb0991SDimitry Andric   };
21100b57cec5SDimitry Andric 
21118bcb0991SDimitry Andric   auto GetMostCommon = [](auto &Counts) {
21128bcb0991SDimitry Andric     auto CommonIt =
21138bcb0991SDimitry Andric         std::max_element(Counts.begin(), Counts.end(),
21148bcb0991SDimitry Andric                          [](auto A, auto B) { return A.second < B.second; });
21158bcb0991SDimitry Andric     assert(CommonIt != Counts.end() && "Unexpected all-undef build_vector");
21168bcb0991SDimitry Andric     return *CommonIt;
21178bcb0991SDimitry Andric   };
21188bcb0991SDimitry Andric 
21198bcb0991SDimitry Andric   size_t NumConstantLanes = 0;
21208bcb0991SDimitry Andric 
21218bcb0991SDimitry Andric   // Count eligible lanes for each type of vector creation op
21228bcb0991SDimitry Andric   for (size_t I = 0; I < Lanes; ++I) {
21238bcb0991SDimitry Andric     const SDValue &Lane = Op->getOperand(I);
21248bcb0991SDimitry Andric     if (Lane.isUndef())
21258bcb0991SDimitry Andric       continue;
21268bcb0991SDimitry Andric 
21278bcb0991SDimitry Andric     AddCount(SplatValueCounts, Lane);
21288bcb0991SDimitry Andric 
2129fe6060f1SDimitry Andric     if (IsConstant(Lane))
21308bcb0991SDimitry Andric       NumConstantLanes++;
2131fe6060f1SDimitry Andric     if (auto ShuffleSrc = GetShuffleSrc(Lane))
2132fe6060f1SDimitry Andric       AddCount(ShuffleCounts, ShuffleSrc);
2133fe6060f1SDimitry Andric     if (CanSwizzle) {
21348bcb0991SDimitry Andric       auto SwizzleSrcs = GetSwizzleSrcs(I, Lane);
21358bcb0991SDimitry Andric       if (SwizzleSrcs.first)
21368bcb0991SDimitry Andric         AddCount(SwizzleCounts, SwizzleSrcs);
21378bcb0991SDimitry Andric     }
21388bcb0991SDimitry Andric   }
21398bcb0991SDimitry Andric 
21408bcb0991SDimitry Andric   SDValue SplatValue;
21418bcb0991SDimitry Andric   size_t NumSplatLanes;
21428bcb0991SDimitry Andric   std::tie(SplatValue, NumSplatLanes) = GetMostCommon(SplatValueCounts);
21438bcb0991SDimitry Andric 
21448bcb0991SDimitry Andric   SDValue SwizzleSrc;
21458bcb0991SDimitry Andric   SDValue SwizzleIndices;
21468bcb0991SDimitry Andric   size_t NumSwizzleLanes = 0;
21478bcb0991SDimitry Andric   if (SwizzleCounts.size())
21488bcb0991SDimitry Andric     std::forward_as_tuple(std::tie(SwizzleSrc, SwizzleIndices),
21498bcb0991SDimitry Andric                           NumSwizzleLanes) = GetMostCommon(SwizzleCounts);
21508bcb0991SDimitry Andric 
2151fe6060f1SDimitry Andric   // Shuffles can draw from up to two vectors, so find the two most common
2152fe6060f1SDimitry Andric   // sources.
2153fe6060f1SDimitry Andric   SDValue ShuffleSrc1, ShuffleSrc2;
2154fe6060f1SDimitry Andric   size_t NumShuffleLanes = 0;
2155fe6060f1SDimitry Andric   if (ShuffleCounts.size()) {
2156fe6060f1SDimitry Andric     std::tie(ShuffleSrc1, NumShuffleLanes) = GetMostCommon(ShuffleCounts);
2157*349cc55cSDimitry Andric     llvm::erase_if(ShuffleCounts,
2158*349cc55cSDimitry Andric                    [&](const auto &Pair) { return Pair.first == ShuffleSrc1; });
2159fe6060f1SDimitry Andric   }
2160fe6060f1SDimitry Andric   if (ShuffleCounts.size()) {
2161fe6060f1SDimitry Andric     size_t AdditionalShuffleLanes;
2162fe6060f1SDimitry Andric     std::tie(ShuffleSrc2, AdditionalShuffleLanes) =
2163fe6060f1SDimitry Andric         GetMostCommon(ShuffleCounts);
2164fe6060f1SDimitry Andric     NumShuffleLanes += AdditionalShuffleLanes;
2165fe6060f1SDimitry Andric   }
2166fe6060f1SDimitry Andric 
21678bcb0991SDimitry Andric   // Predicate returning true if the lane is properly initialized by the
21688bcb0991SDimitry Andric   // original instruction
21698bcb0991SDimitry Andric   std::function<bool(size_t, const SDValue &)> IsLaneConstructed;
21708bcb0991SDimitry Andric   SDValue Result;
2171fe6060f1SDimitry Andric   // Prefer swizzles over shuffles over vector consts over splats
2172fe6060f1SDimitry Andric   if (NumSwizzleLanes >= NumShuffleLanes &&
2173fe6060f1SDimitry Andric       NumSwizzleLanes >= NumConstantLanes && NumSwizzleLanes >= NumSplatLanes) {
21748bcb0991SDimitry Andric     Result = DAG.getNode(WebAssemblyISD::SWIZZLE, DL, VecT, SwizzleSrc,
21758bcb0991SDimitry Andric                          SwizzleIndices);
21768bcb0991SDimitry Andric     auto Swizzled = std::make_pair(SwizzleSrc, SwizzleIndices);
21778bcb0991SDimitry Andric     IsLaneConstructed = [&, Swizzled](size_t I, const SDValue &Lane) {
21788bcb0991SDimitry Andric       return Swizzled == GetSwizzleSrcs(I, Lane);
21798bcb0991SDimitry Andric     };
2180fe6060f1SDimitry Andric   } else if (NumShuffleLanes >= NumConstantLanes &&
2181fe6060f1SDimitry Andric              NumShuffleLanes >= NumSplatLanes) {
2182fe6060f1SDimitry Andric     size_t DestLaneSize = VecT.getVectorElementType().getFixedSizeInBits() / 8;
2183fe6060f1SDimitry Andric     size_t DestLaneCount = VecT.getVectorNumElements();
2184fe6060f1SDimitry Andric     size_t Scale1 = 1;
2185fe6060f1SDimitry Andric     size_t Scale2 = 1;
2186fe6060f1SDimitry Andric     SDValue Src1 = ShuffleSrc1;
2187fe6060f1SDimitry Andric     SDValue Src2 = ShuffleSrc2 ? ShuffleSrc2 : DAG.getUNDEF(VecT);
2188fe6060f1SDimitry Andric     if (Src1.getValueType() != VecT) {
2189fe6060f1SDimitry Andric       size_t LaneSize =
2190fe6060f1SDimitry Andric           Src1.getValueType().getVectorElementType().getFixedSizeInBits() / 8;
2191fe6060f1SDimitry Andric       assert(LaneSize > DestLaneSize);
2192fe6060f1SDimitry Andric       Scale1 = LaneSize / DestLaneSize;
2193fe6060f1SDimitry Andric       Src1 = DAG.getBitcast(VecT, Src1);
2194fe6060f1SDimitry Andric     }
2195fe6060f1SDimitry Andric     if (Src2.getValueType() != VecT) {
2196fe6060f1SDimitry Andric       size_t LaneSize =
2197fe6060f1SDimitry Andric           Src2.getValueType().getVectorElementType().getFixedSizeInBits() / 8;
2198fe6060f1SDimitry Andric       assert(LaneSize > DestLaneSize);
2199fe6060f1SDimitry Andric       Scale2 = LaneSize / DestLaneSize;
2200fe6060f1SDimitry Andric       Src2 = DAG.getBitcast(VecT, Src2);
2201fe6060f1SDimitry Andric     }
2202fe6060f1SDimitry Andric 
2203fe6060f1SDimitry Andric     int Mask[16];
2204fe6060f1SDimitry Andric     assert(DestLaneCount <= 16);
2205fe6060f1SDimitry Andric     for (size_t I = 0; I < DestLaneCount; ++I) {
2206fe6060f1SDimitry Andric       const SDValue &Lane = Op->getOperand(I);
2207fe6060f1SDimitry Andric       SDValue Src = GetShuffleSrc(Lane);
2208fe6060f1SDimitry Andric       if (Src == ShuffleSrc1) {
2209fe6060f1SDimitry Andric         Mask[I] = Lane->getConstantOperandVal(1) * Scale1;
2210fe6060f1SDimitry Andric       } else if (Src && Src == ShuffleSrc2) {
2211fe6060f1SDimitry Andric         Mask[I] = DestLaneCount + Lane->getConstantOperandVal(1) * Scale2;
2212fe6060f1SDimitry Andric       } else {
2213fe6060f1SDimitry Andric         Mask[I] = -1;
2214fe6060f1SDimitry Andric       }
2215fe6060f1SDimitry Andric     }
2216fe6060f1SDimitry Andric     ArrayRef<int> MaskRef(Mask, DestLaneCount);
2217fe6060f1SDimitry Andric     Result = DAG.getVectorShuffle(VecT, DL, Src1, Src2, MaskRef);
2218fe6060f1SDimitry Andric     IsLaneConstructed = [&](size_t, const SDValue &Lane) {
2219fe6060f1SDimitry Andric       auto Src = GetShuffleSrc(Lane);
2220fe6060f1SDimitry Andric       return Src == ShuffleSrc1 || (Src && Src == ShuffleSrc2);
2221fe6060f1SDimitry Andric     };
2222fe6060f1SDimitry Andric   } else if (NumConstantLanes >= NumSplatLanes) {
22230b57cec5SDimitry Andric     SmallVector<SDValue, 16> ConstLanes;
22240b57cec5SDimitry Andric     for (const SDValue &Lane : Op->op_values()) {
22250b57cec5SDimitry Andric       if (IsConstant(Lane)) {
2226*349cc55cSDimitry Andric         // Values may need to be fixed so that they will sign extend to be
2227*349cc55cSDimitry Andric         // within the expected range during ISel. Check whether the value is in
2228*349cc55cSDimitry Andric         // bounds based on the lane bit width and if it is out of bounds, lop
2229*349cc55cSDimitry Andric         // off the extra bits and subtract 2^n to reflect giving the high bit
2230*349cc55cSDimitry Andric         // value -2^(n-1) rather than +2^(n-1). Skip the i64 case because it
2231*349cc55cSDimitry Andric         // cannot possibly be out of range.
2232*349cc55cSDimitry Andric         auto *Const = dyn_cast<ConstantSDNode>(Lane.getNode());
2233*349cc55cSDimitry Andric         int64_t Val = Const ? Const->getSExtValue() : 0;
2234*349cc55cSDimitry Andric         uint64_t LaneBits = 128 / Lanes;
2235*349cc55cSDimitry Andric         assert((LaneBits == 64 || Val >= -(1ll << (LaneBits - 1))) &&
2236*349cc55cSDimitry Andric                "Unexpected out of bounds negative value");
2237*349cc55cSDimitry Andric         if (Const && LaneBits != 64 && Val > (1ll << (LaneBits - 1)) - 1) {
2238*349cc55cSDimitry Andric           auto NewVal = ((uint64_t)Val % (1ll << LaneBits)) - (1ll << LaneBits);
2239*349cc55cSDimitry Andric           ConstLanes.push_back(DAG.getConstant(NewVal, SDLoc(Lane), LaneT));
2240*349cc55cSDimitry Andric         } else {
22410b57cec5SDimitry Andric           ConstLanes.push_back(Lane);
2242*349cc55cSDimitry Andric         }
22430b57cec5SDimitry Andric       } else if (LaneT.isFloatingPoint()) {
22440b57cec5SDimitry Andric         ConstLanes.push_back(DAG.getConstantFP(0, DL, LaneT));
22450b57cec5SDimitry Andric       } else {
22460b57cec5SDimitry Andric         ConstLanes.push_back(DAG.getConstant(0, DL, LaneT));
22470b57cec5SDimitry Andric       }
22480b57cec5SDimitry Andric     }
22498bcb0991SDimitry Andric     Result = DAG.getBuildVector(VecT, DL, ConstLanes);
2250e8d8bef9SDimitry Andric     IsLaneConstructed = [&IsConstant](size_t _, const SDValue &Lane) {
22518bcb0991SDimitry Andric       return IsConstant(Lane);
22528bcb0991SDimitry Andric     };
2253e8d8bef9SDimitry Andric   } else {
22548bcb0991SDimitry Andric     // Use a splat, but possibly a load_splat
22558bcb0991SDimitry Andric     LoadSDNode *SplattedLoad;
22565ffd83dbSDimitry Andric     if ((SplattedLoad = dyn_cast<LoadSDNode>(SplatValue)) &&
22578bcb0991SDimitry Andric         SplattedLoad->getMemoryVT() == VecT.getVectorElementType()) {
2258480093f4SDimitry Andric       Result = DAG.getMemIntrinsicNode(
2259480093f4SDimitry Andric           WebAssemblyISD::LOAD_SPLAT, DL, DAG.getVTList(VecT),
2260480093f4SDimitry Andric           {SplattedLoad->getChain(), SplattedLoad->getBasePtr(),
2261480093f4SDimitry Andric            SplattedLoad->getOffset()},
2262480093f4SDimitry Andric           SplattedLoad->getMemoryVT(), SplattedLoad->getMemOperand());
22638bcb0991SDimitry Andric     } else {
22648bcb0991SDimitry Andric       Result = DAG.getSplatBuildVector(VecT, DL, SplatValue);
22658bcb0991SDimitry Andric     }
2266e8d8bef9SDimitry Andric     IsLaneConstructed = [&SplatValue](size_t _, const SDValue &Lane) {
22678bcb0991SDimitry Andric       return Lane == SplatValue;
22688bcb0991SDimitry Andric     };
22698bcb0991SDimitry Andric   }
22708bcb0991SDimitry Andric 
2271e8d8bef9SDimitry Andric   assert(Result);
2272e8d8bef9SDimitry Andric   assert(IsLaneConstructed);
2273e8d8bef9SDimitry Andric 
22748bcb0991SDimitry Andric   // Add replace_lane instructions for any unhandled values
22750b57cec5SDimitry Andric   for (size_t I = 0; I < Lanes; ++I) {
22760b57cec5SDimitry Andric     const SDValue &Lane = Op->getOperand(I);
22778bcb0991SDimitry Andric     if (!Lane.isUndef() && !IsLaneConstructed(I, Lane))
22780b57cec5SDimitry Andric       Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VecT, Result, Lane,
22790b57cec5SDimitry Andric                            DAG.getConstant(I, DL, MVT::i32));
22800b57cec5SDimitry Andric   }
22818bcb0991SDimitry Andric 
22820b57cec5SDimitry Andric   return Result;
22830b57cec5SDimitry Andric }
22840b57cec5SDimitry Andric 
22850b57cec5SDimitry Andric SDValue
22860b57cec5SDimitry Andric WebAssemblyTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
22870b57cec5SDimitry Andric                                                SelectionDAG &DAG) const {
22880b57cec5SDimitry Andric   SDLoc DL(Op);
22890b57cec5SDimitry Andric   ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Op.getNode())->getMask();
22900b57cec5SDimitry Andric   MVT VecType = Op.getOperand(0).getSimpleValueType();
22910b57cec5SDimitry Andric   assert(VecType.is128BitVector() && "Unexpected shuffle vector type");
22920b57cec5SDimitry Andric   size_t LaneBytes = VecType.getVectorElementType().getSizeInBits() / 8;
22930b57cec5SDimitry Andric 
22940b57cec5SDimitry Andric   // Space for two vector args and sixteen mask indices
22950b57cec5SDimitry Andric   SDValue Ops[18];
22960b57cec5SDimitry Andric   size_t OpIdx = 0;
22970b57cec5SDimitry Andric   Ops[OpIdx++] = Op.getOperand(0);
22980b57cec5SDimitry Andric   Ops[OpIdx++] = Op.getOperand(1);
22990b57cec5SDimitry Andric 
23000b57cec5SDimitry Andric   // Expand mask indices to byte indices and materialize them as operands
23010b57cec5SDimitry Andric   for (int M : Mask) {
23020b57cec5SDimitry Andric     for (size_t J = 0; J < LaneBytes; ++J) {
23030b57cec5SDimitry Andric       // Lower undefs (represented by -1 in mask) to zero
23040b57cec5SDimitry Andric       uint64_t ByteIndex = M == -1 ? 0 : (uint64_t)M * LaneBytes + J;
23050b57cec5SDimitry Andric       Ops[OpIdx++] = DAG.getConstant(ByteIndex, DL, MVT::i32);
23060b57cec5SDimitry Andric     }
23070b57cec5SDimitry Andric   }
23080b57cec5SDimitry Andric 
23090b57cec5SDimitry Andric   return DAG.getNode(WebAssemblyISD::SHUFFLE, DL, Op.getValueType(), Ops);
23100b57cec5SDimitry Andric }
23110b57cec5SDimitry Andric 
2312480093f4SDimitry Andric SDValue WebAssemblyTargetLowering::LowerSETCC(SDValue Op,
2313480093f4SDimitry Andric                                               SelectionDAG &DAG) const {
2314480093f4SDimitry Andric   SDLoc DL(Op);
2315fe6060f1SDimitry Andric   // The legalizer does not know how to expand the unsupported comparison modes
2316fe6060f1SDimitry Andric   // of i64x2 vectors, so we manually unroll them here.
2317480093f4SDimitry Andric   assert(Op->getOperand(0)->getSimpleValueType(0) == MVT::v2i64);
2318480093f4SDimitry Andric   SmallVector<SDValue, 2> LHS, RHS;
2319480093f4SDimitry Andric   DAG.ExtractVectorElements(Op->getOperand(0), LHS);
2320480093f4SDimitry Andric   DAG.ExtractVectorElements(Op->getOperand(1), RHS);
2321480093f4SDimitry Andric   const SDValue &CC = Op->getOperand(2);
2322480093f4SDimitry Andric   auto MakeLane = [&](unsigned I) {
2323480093f4SDimitry Andric     return DAG.getNode(ISD::SELECT_CC, DL, MVT::i64, LHS[I], RHS[I],
2324480093f4SDimitry Andric                        DAG.getConstant(uint64_t(-1), DL, MVT::i64),
2325480093f4SDimitry Andric                        DAG.getConstant(uint64_t(0), DL, MVT::i64), CC);
2326480093f4SDimitry Andric   };
2327480093f4SDimitry Andric   return DAG.getBuildVector(Op->getValueType(0), DL,
2328480093f4SDimitry Andric                             {MakeLane(0), MakeLane(1)});
2329480093f4SDimitry Andric }
2330480093f4SDimitry Andric 
23310b57cec5SDimitry Andric SDValue
23320b57cec5SDimitry Andric WebAssemblyTargetLowering::LowerAccessVectorElement(SDValue Op,
23330b57cec5SDimitry Andric                                                     SelectionDAG &DAG) const {
23340b57cec5SDimitry Andric   // Allow constant lane indices, expand variable lane indices
23350b57cec5SDimitry Andric   SDNode *IdxNode = Op.getOperand(Op.getNumOperands() - 1).getNode();
23360b57cec5SDimitry Andric   if (isa<ConstantSDNode>(IdxNode) || IdxNode->isUndef())
23370b57cec5SDimitry Andric     return Op;
23380b57cec5SDimitry Andric   else
23390b57cec5SDimitry Andric     // Perform default expansion
23400b57cec5SDimitry Andric     return SDValue();
23410b57cec5SDimitry Andric }
23420b57cec5SDimitry Andric 
23430b57cec5SDimitry Andric static SDValue unrollVectorShift(SDValue Op, SelectionDAG &DAG) {
23440b57cec5SDimitry Andric   EVT LaneT = Op.getSimpleValueType().getVectorElementType();
23450b57cec5SDimitry Andric   // 32-bit and 64-bit unrolled shifts will have proper semantics
23460b57cec5SDimitry Andric   if (LaneT.bitsGE(MVT::i32))
23470b57cec5SDimitry Andric     return DAG.UnrollVectorOp(Op.getNode());
23480b57cec5SDimitry Andric   // Otherwise mask the shift value to get proper semantics from 32-bit shift
23490b57cec5SDimitry Andric   SDLoc DL(Op);
23505ffd83dbSDimitry Andric   size_t NumLanes = Op.getSimpleValueType().getVectorNumElements();
23515ffd83dbSDimitry Andric   SDValue Mask = DAG.getConstant(LaneT.getSizeInBits() - 1, DL, MVT::i32);
23525ffd83dbSDimitry Andric   unsigned ShiftOpcode = Op.getOpcode();
23535ffd83dbSDimitry Andric   SmallVector<SDValue, 16> ShiftedElements;
23545ffd83dbSDimitry Andric   DAG.ExtractVectorElements(Op.getOperand(0), ShiftedElements, 0, 0, MVT::i32);
23555ffd83dbSDimitry Andric   SmallVector<SDValue, 16> ShiftElements;
23565ffd83dbSDimitry Andric   DAG.ExtractVectorElements(Op.getOperand(1), ShiftElements, 0, 0, MVT::i32);
23575ffd83dbSDimitry Andric   SmallVector<SDValue, 16> UnrolledOps;
23585ffd83dbSDimitry Andric   for (size_t i = 0; i < NumLanes; ++i) {
23595ffd83dbSDimitry Andric     SDValue MaskedShiftValue =
23605ffd83dbSDimitry Andric         DAG.getNode(ISD::AND, DL, MVT::i32, ShiftElements[i], Mask);
23615ffd83dbSDimitry Andric     SDValue ShiftedValue = ShiftedElements[i];
23625ffd83dbSDimitry Andric     if (ShiftOpcode == ISD::SRA)
23635ffd83dbSDimitry Andric       ShiftedValue = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i32,
23645ffd83dbSDimitry Andric                                  ShiftedValue, DAG.getValueType(LaneT));
23655ffd83dbSDimitry Andric     UnrolledOps.push_back(
23665ffd83dbSDimitry Andric         DAG.getNode(ShiftOpcode, DL, MVT::i32, ShiftedValue, MaskedShiftValue));
23675ffd83dbSDimitry Andric   }
23685ffd83dbSDimitry Andric   return DAG.getBuildVector(Op.getValueType(), DL, UnrolledOps);
23690b57cec5SDimitry Andric }
23700b57cec5SDimitry Andric 
23710b57cec5SDimitry Andric SDValue WebAssemblyTargetLowering::LowerShift(SDValue Op,
23720b57cec5SDimitry Andric                                               SelectionDAG &DAG) const {
23730b57cec5SDimitry Andric   SDLoc DL(Op);
23740b57cec5SDimitry Andric 
23750b57cec5SDimitry Andric   // Only manually lower vector shifts
23760b57cec5SDimitry Andric   assert(Op.getSimpleValueType().isVector());
23770b57cec5SDimitry Andric 
23785ffd83dbSDimitry Andric   auto ShiftVal = DAG.getSplatValue(Op.getOperand(1));
23795ffd83dbSDimitry Andric   if (!ShiftVal)
23800b57cec5SDimitry Andric     return unrollVectorShift(Op, DAG);
23810b57cec5SDimitry Andric 
23825ffd83dbSDimitry Andric   // Use anyext because none of the high bits can affect the shift
23835ffd83dbSDimitry Andric   ShiftVal = DAG.getAnyExtOrTrunc(ShiftVal, DL, MVT::i32);
23840b57cec5SDimitry Andric 
23850b57cec5SDimitry Andric   unsigned Opcode;
23860b57cec5SDimitry Andric   switch (Op.getOpcode()) {
23870b57cec5SDimitry Andric   case ISD::SHL:
23880b57cec5SDimitry Andric     Opcode = WebAssemblyISD::VEC_SHL;
23890b57cec5SDimitry Andric     break;
23900b57cec5SDimitry Andric   case ISD::SRA:
23910b57cec5SDimitry Andric     Opcode = WebAssemblyISD::VEC_SHR_S;
23920b57cec5SDimitry Andric     break;
23930b57cec5SDimitry Andric   case ISD::SRL:
23940b57cec5SDimitry Andric     Opcode = WebAssemblyISD::VEC_SHR_U;
23950b57cec5SDimitry Andric     break;
23960b57cec5SDimitry Andric   default:
23970b57cec5SDimitry Andric     llvm_unreachable("unexpected opcode");
23980b57cec5SDimitry Andric   }
23995ffd83dbSDimitry Andric 
24005ffd83dbSDimitry Andric   return DAG.getNode(Opcode, DL, Op.getValueType(), Op.getOperand(0), ShiftVal);
24010b57cec5SDimitry Andric }
24020b57cec5SDimitry Andric 
2403fe6060f1SDimitry Andric SDValue WebAssemblyTargetLowering::LowerFP_TO_INT_SAT(SDValue Op,
2404fe6060f1SDimitry Andric                                                       SelectionDAG &DAG) const {
2405fe6060f1SDimitry Andric   SDLoc DL(Op);
2406fe6060f1SDimitry Andric   EVT ResT = Op.getValueType();
2407fe6060f1SDimitry Andric   EVT SatVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
2408fe6060f1SDimitry Andric 
2409fe6060f1SDimitry Andric   if ((ResT == MVT::i32 || ResT == MVT::i64) &&
2410fe6060f1SDimitry Andric       (SatVT == MVT::i32 || SatVT == MVT::i64))
2411fe6060f1SDimitry Andric     return Op;
2412fe6060f1SDimitry Andric 
2413fe6060f1SDimitry Andric   if (ResT == MVT::v4i32 && SatVT == MVT::i32)
2414fe6060f1SDimitry Andric     return Op;
2415fe6060f1SDimitry Andric 
2416fe6060f1SDimitry Andric   return SDValue();
2417fe6060f1SDimitry Andric }
2418fe6060f1SDimitry Andric 
24190b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
24205ffd83dbSDimitry Andric //   Custom DAG combine hooks
24210b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
24225ffd83dbSDimitry Andric static SDValue
24235ffd83dbSDimitry Andric performVECTOR_SHUFFLECombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
24245ffd83dbSDimitry Andric   auto &DAG = DCI.DAG;
24255ffd83dbSDimitry Andric   auto Shuffle = cast<ShuffleVectorSDNode>(N);
24265ffd83dbSDimitry Andric 
24275ffd83dbSDimitry Andric   // Hoist vector bitcasts that don't change the number of lanes out of unary
24285ffd83dbSDimitry Andric   // shuffles, where they are less likely to get in the way of other combines.
24295ffd83dbSDimitry Andric   // (shuffle (vNxT1 (bitcast (vNxT0 x))), undef, mask) ->
24305ffd83dbSDimitry Andric   //  (vNxT1 (bitcast (vNxT0 (shuffle x, undef, mask))))
24315ffd83dbSDimitry Andric   SDValue Bitcast = N->getOperand(0);
24325ffd83dbSDimitry Andric   if (Bitcast.getOpcode() != ISD::BITCAST)
24335ffd83dbSDimitry Andric     return SDValue();
24345ffd83dbSDimitry Andric   if (!N->getOperand(1).isUndef())
24355ffd83dbSDimitry Andric     return SDValue();
24365ffd83dbSDimitry Andric   SDValue CastOp = Bitcast.getOperand(0);
24375ffd83dbSDimitry Andric   MVT SrcType = CastOp.getSimpleValueType();
24385ffd83dbSDimitry Andric   MVT DstType = Bitcast.getSimpleValueType();
24395ffd83dbSDimitry Andric   if (!SrcType.is128BitVector() ||
24405ffd83dbSDimitry Andric       SrcType.getVectorNumElements() != DstType.getVectorNumElements())
24415ffd83dbSDimitry Andric     return SDValue();
24425ffd83dbSDimitry Andric   SDValue NewShuffle = DAG.getVectorShuffle(
24435ffd83dbSDimitry Andric       SrcType, SDLoc(N), CastOp, DAG.getUNDEF(SrcType), Shuffle->getMask());
24445ffd83dbSDimitry Andric   return DAG.getBitcast(DstType, NewShuffle);
24455ffd83dbSDimitry Andric }
24465ffd83dbSDimitry Andric 
2447fe6060f1SDimitry Andric static SDValue
2448fe6060f1SDimitry Andric performVectorExtendCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
2449e8d8bef9SDimitry Andric   auto &DAG = DCI.DAG;
2450e8d8bef9SDimitry Andric   assert(N->getOpcode() == ISD::SIGN_EXTEND ||
2451e8d8bef9SDimitry Andric          N->getOpcode() == ISD::ZERO_EXTEND);
2452e8d8bef9SDimitry Andric 
2453e8d8bef9SDimitry Andric   // Combine ({s,z}ext (extract_subvector src, i)) into a widening operation if
2454e8d8bef9SDimitry Andric   // possible before the extract_subvector can be expanded.
2455e8d8bef9SDimitry Andric   auto Extract = N->getOperand(0);
2456e8d8bef9SDimitry Andric   if (Extract.getOpcode() != ISD::EXTRACT_SUBVECTOR)
2457e8d8bef9SDimitry Andric     return SDValue();
2458e8d8bef9SDimitry Andric   auto Source = Extract.getOperand(0);
2459e8d8bef9SDimitry Andric   auto *IndexNode = dyn_cast<ConstantSDNode>(Extract.getOperand(1));
2460e8d8bef9SDimitry Andric   if (IndexNode == nullptr)
2461e8d8bef9SDimitry Andric     return SDValue();
2462e8d8bef9SDimitry Andric   auto Index = IndexNode->getZExtValue();
2463e8d8bef9SDimitry Andric 
2464fe6060f1SDimitry Andric   // Only v8i8, v4i16, and v2i32 extracts can be widened, and only if the
2465fe6060f1SDimitry Andric   // extracted subvector is the low or high half of its source.
2466e8d8bef9SDimitry Andric   EVT ResVT = N->getValueType(0);
2467e8d8bef9SDimitry Andric   if (ResVT == MVT::v8i16) {
2468e8d8bef9SDimitry Andric     if (Extract.getValueType() != MVT::v8i8 ||
2469e8d8bef9SDimitry Andric         Source.getValueType() != MVT::v16i8 || (Index != 0 && Index != 8))
2470e8d8bef9SDimitry Andric       return SDValue();
2471e8d8bef9SDimitry Andric   } else if (ResVT == MVT::v4i32) {
2472e8d8bef9SDimitry Andric     if (Extract.getValueType() != MVT::v4i16 ||
2473e8d8bef9SDimitry Andric         Source.getValueType() != MVT::v8i16 || (Index != 0 && Index != 4))
2474e8d8bef9SDimitry Andric       return SDValue();
2475fe6060f1SDimitry Andric   } else if (ResVT == MVT::v2i64) {
2476fe6060f1SDimitry Andric     if (Extract.getValueType() != MVT::v2i32 ||
2477fe6060f1SDimitry Andric         Source.getValueType() != MVT::v4i32 || (Index != 0 && Index != 2))
2478fe6060f1SDimitry Andric       return SDValue();
2479e8d8bef9SDimitry Andric   } else {
2480e8d8bef9SDimitry Andric     return SDValue();
2481e8d8bef9SDimitry Andric   }
2482e8d8bef9SDimitry Andric 
2483e8d8bef9SDimitry Andric   bool IsSext = N->getOpcode() == ISD::SIGN_EXTEND;
2484e8d8bef9SDimitry Andric   bool IsLow = Index == 0;
2485e8d8bef9SDimitry Andric 
2486fe6060f1SDimitry Andric   unsigned Op = IsSext ? (IsLow ? WebAssemblyISD::EXTEND_LOW_S
2487fe6060f1SDimitry Andric                                 : WebAssemblyISD::EXTEND_HIGH_S)
2488fe6060f1SDimitry Andric                        : (IsLow ? WebAssemblyISD::EXTEND_LOW_U
2489fe6060f1SDimitry Andric                                 : WebAssemblyISD::EXTEND_HIGH_U);
2490e8d8bef9SDimitry Andric 
2491e8d8bef9SDimitry Andric   return DAG.getNode(Op, SDLoc(N), ResVT, Source);
2492e8d8bef9SDimitry Andric }
2493e8d8bef9SDimitry Andric 
2494fe6060f1SDimitry Andric static SDValue
2495fe6060f1SDimitry Andric performVectorTruncZeroCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
2496fe6060f1SDimitry Andric   auto &DAG = DCI.DAG;
2497fe6060f1SDimitry Andric 
2498fe6060f1SDimitry Andric   auto GetWasmConversionOp = [](unsigned Op) {
2499fe6060f1SDimitry Andric     switch (Op) {
2500fe6060f1SDimitry Andric     case ISD::FP_TO_SINT_SAT:
2501fe6060f1SDimitry Andric       return WebAssemblyISD::TRUNC_SAT_ZERO_S;
2502fe6060f1SDimitry Andric     case ISD::FP_TO_UINT_SAT:
2503fe6060f1SDimitry Andric       return WebAssemblyISD::TRUNC_SAT_ZERO_U;
2504fe6060f1SDimitry Andric     case ISD::FP_ROUND:
2505fe6060f1SDimitry Andric       return WebAssemblyISD::DEMOTE_ZERO;
2506fe6060f1SDimitry Andric     }
2507fe6060f1SDimitry Andric     llvm_unreachable("unexpected op");
2508fe6060f1SDimitry Andric   };
2509fe6060f1SDimitry Andric 
2510fe6060f1SDimitry Andric   auto IsZeroSplat = [](SDValue SplatVal) {
2511fe6060f1SDimitry Andric     auto *Splat = dyn_cast<BuildVectorSDNode>(SplatVal.getNode());
2512fe6060f1SDimitry Andric     APInt SplatValue, SplatUndef;
2513fe6060f1SDimitry Andric     unsigned SplatBitSize;
2514fe6060f1SDimitry Andric     bool HasAnyUndefs;
2515fe6060f1SDimitry Andric     return Splat &&
2516fe6060f1SDimitry Andric            Splat->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
2517fe6060f1SDimitry Andric                                   HasAnyUndefs) &&
2518fe6060f1SDimitry Andric            SplatValue == 0;
2519fe6060f1SDimitry Andric   };
2520fe6060f1SDimitry Andric 
2521fe6060f1SDimitry Andric   if (N->getOpcode() == ISD::CONCAT_VECTORS) {
2522fe6060f1SDimitry Andric     // Combine this:
2523fe6060f1SDimitry Andric     //
2524fe6060f1SDimitry Andric     //   (concat_vectors (v2i32 (fp_to_{s,u}int_sat $x, 32)), (v2i32 (splat 0)))
2525fe6060f1SDimitry Andric     //
2526fe6060f1SDimitry Andric     // into (i32x4.trunc_sat_f64x2_zero_{s,u} $x).
2527fe6060f1SDimitry Andric     //
2528fe6060f1SDimitry Andric     // Or this:
2529fe6060f1SDimitry Andric     //
2530fe6060f1SDimitry Andric     //   (concat_vectors (v2f32 (fp_round (v2f64 $x))), (v2f32 (splat 0)))
2531fe6060f1SDimitry Andric     //
2532fe6060f1SDimitry Andric     // into (f32x4.demote_zero_f64x2 $x).
2533fe6060f1SDimitry Andric     EVT ResVT;
2534fe6060f1SDimitry Andric     EVT ExpectedConversionType;
2535fe6060f1SDimitry Andric     auto Conversion = N->getOperand(0);
2536fe6060f1SDimitry Andric     auto ConversionOp = Conversion.getOpcode();
2537fe6060f1SDimitry Andric     switch (ConversionOp) {
2538fe6060f1SDimitry Andric     case ISD::FP_TO_SINT_SAT:
2539fe6060f1SDimitry Andric     case ISD::FP_TO_UINT_SAT:
2540fe6060f1SDimitry Andric       ResVT = MVT::v4i32;
2541fe6060f1SDimitry Andric       ExpectedConversionType = MVT::v2i32;
2542fe6060f1SDimitry Andric       break;
2543fe6060f1SDimitry Andric     case ISD::FP_ROUND:
2544fe6060f1SDimitry Andric       ResVT = MVT::v4f32;
2545fe6060f1SDimitry Andric       ExpectedConversionType = MVT::v2f32;
2546fe6060f1SDimitry Andric       break;
2547fe6060f1SDimitry Andric     default:
2548fe6060f1SDimitry Andric       return SDValue();
2549fe6060f1SDimitry Andric     }
2550fe6060f1SDimitry Andric 
2551fe6060f1SDimitry Andric     if (N->getValueType(0) != ResVT)
2552fe6060f1SDimitry Andric       return SDValue();
2553fe6060f1SDimitry Andric 
2554fe6060f1SDimitry Andric     if (Conversion.getValueType() != ExpectedConversionType)
2555fe6060f1SDimitry Andric       return SDValue();
2556fe6060f1SDimitry Andric 
2557fe6060f1SDimitry Andric     auto Source = Conversion.getOperand(0);
2558fe6060f1SDimitry Andric     if (Source.getValueType() != MVT::v2f64)
2559fe6060f1SDimitry Andric       return SDValue();
2560fe6060f1SDimitry Andric 
2561fe6060f1SDimitry Andric     if (!IsZeroSplat(N->getOperand(1)) ||
2562fe6060f1SDimitry Andric         N->getOperand(1).getValueType() != ExpectedConversionType)
2563fe6060f1SDimitry Andric       return SDValue();
2564fe6060f1SDimitry Andric 
2565fe6060f1SDimitry Andric     unsigned Op = GetWasmConversionOp(ConversionOp);
2566fe6060f1SDimitry Andric     return DAG.getNode(Op, SDLoc(N), ResVT, Source);
2567fe6060f1SDimitry Andric   }
2568fe6060f1SDimitry Andric 
2569fe6060f1SDimitry Andric   // Combine this:
2570fe6060f1SDimitry Andric   //
2571fe6060f1SDimitry Andric   //   (fp_to_{s,u}int_sat (concat_vectors $x, (v2f64 (splat 0))), 32)
2572fe6060f1SDimitry Andric   //
2573fe6060f1SDimitry Andric   // into (i32x4.trunc_sat_f64x2_zero_{s,u} $x).
2574fe6060f1SDimitry Andric   //
2575fe6060f1SDimitry Andric   // Or this:
2576fe6060f1SDimitry Andric   //
2577fe6060f1SDimitry Andric   //   (v4f32 (fp_round (concat_vectors $x, (v2f64 (splat 0)))))
2578fe6060f1SDimitry Andric   //
2579fe6060f1SDimitry Andric   // into (f32x4.demote_zero_f64x2 $x).
2580fe6060f1SDimitry Andric   EVT ResVT;
2581fe6060f1SDimitry Andric   auto ConversionOp = N->getOpcode();
2582fe6060f1SDimitry Andric   switch (ConversionOp) {
2583fe6060f1SDimitry Andric   case ISD::FP_TO_SINT_SAT:
2584fe6060f1SDimitry Andric   case ISD::FP_TO_UINT_SAT:
2585fe6060f1SDimitry Andric     ResVT = MVT::v4i32;
2586fe6060f1SDimitry Andric     break;
2587fe6060f1SDimitry Andric   case ISD::FP_ROUND:
2588fe6060f1SDimitry Andric     ResVT = MVT::v4f32;
2589fe6060f1SDimitry Andric     break;
2590fe6060f1SDimitry Andric   default:
2591fe6060f1SDimitry Andric     llvm_unreachable("unexpected op");
2592fe6060f1SDimitry Andric   }
2593fe6060f1SDimitry Andric 
2594fe6060f1SDimitry Andric   if (N->getValueType(0) != ResVT)
2595fe6060f1SDimitry Andric     return SDValue();
2596fe6060f1SDimitry Andric 
2597fe6060f1SDimitry Andric   auto Concat = N->getOperand(0);
2598fe6060f1SDimitry Andric   if (Concat.getValueType() != MVT::v4f64)
2599fe6060f1SDimitry Andric     return SDValue();
2600fe6060f1SDimitry Andric 
2601fe6060f1SDimitry Andric   auto Source = Concat.getOperand(0);
2602fe6060f1SDimitry Andric   if (Source.getValueType() != MVT::v2f64)
2603fe6060f1SDimitry Andric     return SDValue();
2604fe6060f1SDimitry Andric 
2605fe6060f1SDimitry Andric   if (!IsZeroSplat(Concat.getOperand(1)) ||
2606fe6060f1SDimitry Andric       Concat.getOperand(1).getValueType() != MVT::v2f64)
2607fe6060f1SDimitry Andric     return SDValue();
2608fe6060f1SDimitry Andric 
2609fe6060f1SDimitry Andric   unsigned Op = GetWasmConversionOp(ConversionOp);
2610fe6060f1SDimitry Andric   return DAG.getNode(Op, SDLoc(N), ResVT, Source);
2611fe6060f1SDimitry Andric }
2612fe6060f1SDimitry Andric 
26135ffd83dbSDimitry Andric SDValue
26145ffd83dbSDimitry Andric WebAssemblyTargetLowering::PerformDAGCombine(SDNode *N,
26155ffd83dbSDimitry Andric                                              DAGCombinerInfo &DCI) const {
26165ffd83dbSDimitry Andric   switch (N->getOpcode()) {
26175ffd83dbSDimitry Andric   default:
26185ffd83dbSDimitry Andric     return SDValue();
26195ffd83dbSDimitry Andric   case ISD::VECTOR_SHUFFLE:
26205ffd83dbSDimitry Andric     return performVECTOR_SHUFFLECombine(N, DCI);
2621e8d8bef9SDimitry Andric   case ISD::SIGN_EXTEND:
2622e8d8bef9SDimitry Andric   case ISD::ZERO_EXTEND:
2623fe6060f1SDimitry Andric     return performVectorExtendCombine(N, DCI);
2624fe6060f1SDimitry Andric   case ISD::FP_TO_SINT_SAT:
2625fe6060f1SDimitry Andric   case ISD::FP_TO_UINT_SAT:
2626fe6060f1SDimitry Andric   case ISD::FP_ROUND:
2627fe6060f1SDimitry Andric   case ISD::CONCAT_VECTORS:
2628fe6060f1SDimitry Andric     return performVectorTruncZeroCombine(N, DCI);
26295ffd83dbSDimitry Andric   }
26305ffd83dbSDimitry Andric }
2631