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