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 "WebAssemblyMachineFunctionInfo.h"
17 #include "WebAssemblySubtarget.h"
18 #include "WebAssemblyTargetMachine.h"
19 #include "llvm/CodeGen/Analysis.h"
20 #include "llvm/CodeGen/CallingConvLower.h"
21 #include "llvm/CodeGen/MachineInstrBuilder.h"
22 #include "llvm/CodeGen/MachineJumpTableInfo.h"
23 #include "llvm/CodeGen/MachineModuleInfo.h"
24 #include "llvm/CodeGen/MachineRegisterInfo.h"
25 #include "llvm/CodeGen/SelectionDAG.h"
26 #include "llvm/CodeGen/WasmEHFuncInfo.h"
27 #include "llvm/IR/DiagnosticInfo.h"
28 #include "llvm/IR/DiagnosticPrinter.h"
29 #include "llvm/IR/Function.h"
30 #include "llvm/IR/Intrinsics.h"
31 #include "llvm/Support/Debug.h"
32 #include "llvm/Support/ErrorHandling.h"
33 #include "llvm/Support/raw_ostream.h"
34 #include "llvm/Target/TargetOptions.h"
35 using namespace llvm;
36 
37 #define DEBUG_TYPE "wasm-lower"
38 
39 WebAssemblyTargetLowering::WebAssemblyTargetLowering(
40     const TargetMachine &TM, const WebAssemblySubtarget &STI)
41     : TargetLowering(TM), Subtarget(&STI) {
42   auto MVTPtr = Subtarget->hasAddr64() ? MVT::i64 : MVT::i32;
43 
44   // Booleans always contain 0 or 1.
45   setBooleanContents(ZeroOrOneBooleanContent);
46   // Except in SIMD vectors
47   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
48   // We don't know the microarchitecture here, so just reduce register pressure.
49   setSchedulingPreference(Sched::RegPressure);
50   // Tell ISel that we have a stack pointer.
51   setStackPointerRegisterToSaveRestore(
52       Subtarget->hasAddr64() ? WebAssembly::SP64 : WebAssembly::SP32);
53   // Set up the register classes.
54   addRegisterClass(MVT::i32, &WebAssembly::I32RegClass);
55   addRegisterClass(MVT::i64, &WebAssembly::I64RegClass);
56   addRegisterClass(MVT::f32, &WebAssembly::F32RegClass);
57   addRegisterClass(MVT::f64, &WebAssembly::F64RegClass);
58   if (Subtarget->hasSIMD128()) {
59     addRegisterClass(MVT::v16i8, &WebAssembly::V128RegClass);
60     addRegisterClass(MVT::v8i16, &WebAssembly::V128RegClass);
61     addRegisterClass(MVT::v4i32, &WebAssembly::V128RegClass);
62     addRegisterClass(MVT::v4f32, &WebAssembly::V128RegClass);
63   }
64   if (Subtarget->hasUnimplementedSIMD128()) {
65     addRegisterClass(MVT::v2i64, &WebAssembly::V128RegClass);
66     addRegisterClass(MVT::v2f64, &WebAssembly::V128RegClass);
67   }
68   // Compute derived properties from the register classes.
69   computeRegisterProperties(Subtarget->getRegisterInfo());
70 
71   setOperationAction(ISD::GlobalAddress, MVTPtr, Custom);
72   setOperationAction(ISD::ExternalSymbol, MVTPtr, Custom);
73   setOperationAction(ISD::JumpTable, MVTPtr, Custom);
74   setOperationAction(ISD::BlockAddress, MVTPtr, Custom);
75   setOperationAction(ISD::BRIND, MVT::Other, Custom);
76 
77   // Take the default expansion for va_arg, va_copy, and va_end. There is no
78   // default action for va_start, so we do that custom.
79   setOperationAction(ISD::VASTART, MVT::Other, Custom);
80   setOperationAction(ISD::VAARG, MVT::Other, Expand);
81   setOperationAction(ISD::VACOPY, MVT::Other, Expand);
82   setOperationAction(ISD::VAEND, MVT::Other, Expand);
83 
84   for (auto T : {MVT::f32, MVT::f64, MVT::v4f32, MVT::v2f64}) {
85     // Don't expand the floating-point types to constant pools.
86     setOperationAction(ISD::ConstantFP, T, Legal);
87     // Expand floating-point comparisons.
88     for (auto CC : {ISD::SETO, ISD::SETUO, ISD::SETUEQ, ISD::SETONE,
89                     ISD::SETULT, ISD::SETULE, ISD::SETUGT, ISD::SETUGE})
90       setCondCodeAction(CC, T, Expand);
91     // Expand floating-point library function operators.
92     for (auto Op :
93          {ISD::FSIN, ISD::FCOS, ISD::FSINCOS, ISD::FPOW, ISD::FREM, ISD::FMA})
94       setOperationAction(Op, T, Expand);
95     // Note supported floating-point library function operators that otherwise
96     // default to expand.
97     for (auto Op :
98          {ISD::FCEIL, ISD::FFLOOR, ISD::FTRUNC, ISD::FNEARBYINT, ISD::FRINT})
99       setOperationAction(Op, T, Legal);
100     // Support minimum and maximum, which otherwise default to expand.
101     setOperationAction(ISD::FMINIMUM, T, Legal);
102     setOperationAction(ISD::FMAXIMUM, T, Legal);
103     // WebAssembly currently has no builtin f16 support.
104     setOperationAction(ISD::FP16_TO_FP, T, Expand);
105     setOperationAction(ISD::FP_TO_FP16, T, Expand);
106     setLoadExtAction(ISD::EXTLOAD, T, MVT::f16, Expand);
107     setTruncStoreAction(T, MVT::f16, Expand);
108   }
109 
110   // Expand unavailable integer operations.
111   for (auto Op :
112        {ISD::BSWAP, ISD::SMUL_LOHI, ISD::UMUL_LOHI, ISD::MULHS, ISD::MULHU,
113         ISD::SDIVREM, ISD::UDIVREM, ISD::SHL_PARTS, ISD::SRA_PARTS,
114         ISD::SRL_PARTS, ISD::ADDC, ISD::ADDE, ISD::SUBC, ISD::SUBE}) {
115     for (auto T : {MVT::i32, MVT::i64})
116       setOperationAction(Op, T, Expand);
117     if (Subtarget->hasSIMD128())
118       for (auto T : {MVT::v16i8, MVT::v8i16, MVT::v4i32})
119         setOperationAction(Op, T, Expand);
120     if (Subtarget->hasUnimplementedSIMD128())
121       setOperationAction(Op, MVT::v2i64, Expand);
122   }
123 
124   // SIMD-specific configuration
125   if (Subtarget->hasSIMD128()) {
126     // Support saturating add for i8x16 and i16x8
127     for (auto Op : {ISD::SADDSAT, ISD::UADDSAT})
128       for (auto T : {MVT::v16i8, MVT::v8i16})
129         setOperationAction(Op, T, Legal);
130 
131     // Custom lower BUILD_VECTORs to minimize number of replace_lanes
132     for (auto T : {MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v4f32})
133       setOperationAction(ISD::BUILD_VECTOR, T, Custom);
134     if (Subtarget->hasUnimplementedSIMD128())
135       for (auto T : {MVT::v2i64, MVT::v2f64})
136         setOperationAction(ISD::BUILD_VECTOR, T, Custom);
137 
138     // We have custom shuffle lowering to expose the shuffle mask
139     for (auto T : {MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v4f32})
140       setOperationAction(ISD::VECTOR_SHUFFLE, T, Custom);
141     if (Subtarget->hasUnimplementedSIMD128())
142       for (auto T: {MVT::v2i64, MVT::v2f64})
143         setOperationAction(ISD::VECTOR_SHUFFLE, T, Custom);
144 
145     // Custom lowering since wasm shifts must have a scalar shift amount
146     for (auto Op : {ISD::SHL, ISD::SRA, ISD::SRL}) {
147       for (auto T : {MVT::v16i8, MVT::v8i16, MVT::v4i32})
148         setOperationAction(Op, T, Custom);
149       if (Subtarget->hasUnimplementedSIMD128())
150         setOperationAction(Op, MVT::v2i64, Custom);
151     }
152 
153     // Custom lower lane accesses to expand out variable indices
154     for (auto Op : {ISD::EXTRACT_VECTOR_ELT, ISD::INSERT_VECTOR_ELT}) {
155       for (auto T : {MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v4f32})
156         setOperationAction(Op, T, Custom);
157       if (Subtarget->hasUnimplementedSIMD128())
158         for (auto T : {MVT::v2i64, MVT::v2f64})
159           setOperationAction(Op, T, Custom);
160     }
161 
162     // There is no i64x2.mul instruction
163     setOperationAction(ISD::MUL, MVT::v2i64, Expand);
164 
165     // There are no vector select instructions
166     for (auto Op : {ISD::VSELECT, ISD::SELECT_CC, ISD::SELECT}) {
167       for (auto T : {MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v4f32})
168         setOperationAction(Op, T, Expand);
169       if (Subtarget->hasUnimplementedSIMD128())
170         for (auto T : {MVT::v2i64, MVT::v2f64})
171           setOperationAction(Op, T, Expand);
172     }
173 
174     // Expand integer operations supported for scalars but not SIMD
175     for (auto Op : {ISD::CTLZ, ISD::CTTZ, ISD::CTPOP, ISD::SDIV, ISD::UDIV,
176                     ISD::SREM, ISD::UREM, ISD::ROTL, ISD::ROTR}) {
177       for (auto T : {MVT::v16i8, MVT::v8i16, MVT::v4i32})
178         setOperationAction(Op, T, Expand);
179       if (Subtarget->hasUnimplementedSIMD128())
180         setOperationAction(Op, MVT::v2i64, Expand);
181     }
182 
183     // Expand float operations supported for scalars but not SIMD
184     for (auto Op : {ISD::FCEIL, ISD::FFLOOR, ISD::FTRUNC, ISD::FNEARBYINT,
185                     ISD::FCOPYSIGN, ISD::FLOG, ISD::FLOG2, ISD::FLOG10,
186                     ISD::FEXP, ISD::FEXP2, ISD::FRINT}) {
187       setOperationAction(Op, MVT::v4f32, Expand);
188       if (Subtarget->hasUnimplementedSIMD128())
189         setOperationAction(Op, MVT::v2f64, Expand);
190     }
191 
192     // Expand additional SIMD ops that V8 hasn't implemented yet
193     if (!Subtarget->hasUnimplementedSIMD128()) {
194       setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
195       setOperationAction(ISD::FDIV, MVT::v4f32, Expand);
196     }
197   }
198 
199   // As a special case, these operators use the type to mean the type to
200   // sign-extend from.
201   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
202   if (!Subtarget->hasSignExt()) {
203     // Sign extends are legal only when extending a vector extract
204     auto Action = Subtarget->hasSIMD128() ? Custom : Expand;
205     for (auto T : {MVT::i8, MVT::i16, MVT::i32})
206       setOperationAction(ISD::SIGN_EXTEND_INREG, T, Action);
207   }
208   for (auto T : MVT::integer_fixedlen_vector_valuetypes())
209     setOperationAction(ISD::SIGN_EXTEND_INREG, T, Expand);
210 
211   // Dynamic stack allocation: use the default expansion.
212   setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
213   setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
214   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVTPtr, Expand);
215 
216   setOperationAction(ISD::FrameIndex, MVT::i32, Custom);
217   setOperationAction(ISD::CopyToReg, MVT::Other, Custom);
218 
219   // Expand these forms; we pattern-match the forms that we can handle in isel.
220   for (auto T : {MVT::i32, MVT::i64, MVT::f32, MVT::f64})
221     for (auto Op : {ISD::BR_CC, ISD::SELECT_CC})
222       setOperationAction(Op, T, Expand);
223 
224   // We have custom switch handling.
225   setOperationAction(ISD::BR_JT, MVT::Other, Custom);
226 
227   // WebAssembly doesn't have:
228   //  - Floating-point extending loads.
229   //  - Floating-point truncating stores.
230   //  - i1 extending loads.
231   //  - extending/truncating SIMD loads/stores
232   setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f32, Expand);
233   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
234   for (auto T : MVT::integer_valuetypes())
235     for (auto Ext : {ISD::EXTLOAD, ISD::ZEXTLOAD, ISD::SEXTLOAD})
236       setLoadExtAction(Ext, T, MVT::i1, Promote);
237   if (Subtarget->hasSIMD128()) {
238     for (auto T : {MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64, MVT::v4f32,
239                    MVT::v2f64}) {
240       for (auto MemT : MVT::fixedlen_vector_valuetypes()) {
241         if (MVT(T) != MemT) {
242           setTruncStoreAction(T, MemT, Expand);
243           for (auto Ext : {ISD::EXTLOAD, ISD::ZEXTLOAD, ISD::SEXTLOAD})
244             setLoadExtAction(Ext, T, MemT, Expand);
245         }
246       }
247     }
248   }
249 
250   // Don't do anything clever with build_pairs
251   setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand);
252 
253   // Trap lowers to wasm unreachable
254   setOperationAction(ISD::TRAP, MVT::Other, Legal);
255 
256   // Exception handling intrinsics
257   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
258   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
259 
260   setMaxAtomicSizeInBitsSupported(64);
261 
262   // Override the __gnu_f2h_ieee/__gnu_h2f_ieee names so that the f32 name is
263   // consistent with the f64 and f128 names.
264   setLibcallName(RTLIB::FPEXT_F16_F32, "__extendhfsf2");
265   setLibcallName(RTLIB::FPROUND_F32_F16, "__truncsfhf2");
266 
267   // Define the emscripten name for return address helper.
268   // TODO: when implementing other WASM backends, make this generic or only do
269   // this on emscripten depending on what they end up doing.
270   setLibcallName(RTLIB::RETURN_ADDRESS, "emscripten_return_address");
271 
272   // Always convert switches to br_tables unless there is only one case, which
273   // is equivalent to a simple branch. This reduces code size for wasm, and we
274   // defer possible jump table optimizations to the VM.
275   setMinimumJumpTableEntries(2);
276 }
277 
278 TargetLowering::AtomicExpansionKind
279 WebAssemblyTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
280   // We have wasm instructions for these
281   switch (AI->getOperation()) {
282   case AtomicRMWInst::Add:
283   case AtomicRMWInst::Sub:
284   case AtomicRMWInst::And:
285   case AtomicRMWInst::Or:
286   case AtomicRMWInst::Xor:
287   case AtomicRMWInst::Xchg:
288     return AtomicExpansionKind::None;
289   default:
290     break;
291   }
292   return AtomicExpansionKind::CmpXChg;
293 }
294 
295 FastISel *WebAssemblyTargetLowering::createFastISel(
296     FunctionLoweringInfo &FuncInfo, const TargetLibraryInfo *LibInfo) const {
297   return WebAssembly::createFastISel(FuncInfo, LibInfo);
298 }
299 
300 MVT WebAssemblyTargetLowering::getScalarShiftAmountTy(const DataLayout & /*DL*/,
301                                                       EVT VT) const {
302   unsigned BitWidth = NextPowerOf2(VT.getSizeInBits() - 1);
303   if (BitWidth > 1 && BitWidth < 8)
304     BitWidth = 8;
305 
306   if (BitWidth > 64) {
307     // The shift will be lowered to a libcall, and compiler-rt libcalls expect
308     // the count to be an i32.
309     BitWidth = 32;
310     assert(BitWidth >= Log2_32_Ceil(VT.getSizeInBits()) &&
311            "32-bit shift counts ought to be enough for anyone");
312   }
313 
314   MVT Result = MVT::getIntegerVT(BitWidth);
315   assert(Result != MVT::INVALID_SIMPLE_VALUE_TYPE &&
316          "Unable to represent scalar shift amount type");
317   return Result;
318 }
319 
320 // Lower an fp-to-int conversion operator from the LLVM opcode, which has an
321 // undefined result on invalid/overflow, to the WebAssembly opcode, which
322 // traps on invalid/overflow.
323 static MachineBasicBlock *LowerFPToInt(MachineInstr &MI, DebugLoc DL,
324                                        MachineBasicBlock *BB,
325                                        const TargetInstrInfo &TII,
326                                        bool IsUnsigned, bool Int64,
327                                        bool Float64, unsigned LoweredOpcode) {
328   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
329 
330   Register OutReg = MI.getOperand(0).getReg();
331   Register InReg = MI.getOperand(1).getReg();
332 
333   unsigned Abs = Float64 ? WebAssembly::ABS_F64 : WebAssembly::ABS_F32;
334   unsigned FConst = Float64 ? WebAssembly::CONST_F64 : WebAssembly::CONST_F32;
335   unsigned LT = Float64 ? WebAssembly::LT_F64 : WebAssembly::LT_F32;
336   unsigned GE = Float64 ? WebAssembly::GE_F64 : WebAssembly::GE_F32;
337   unsigned IConst = Int64 ? WebAssembly::CONST_I64 : WebAssembly::CONST_I32;
338   unsigned Eqz = WebAssembly::EQZ_I32;
339   unsigned And = WebAssembly::AND_I32;
340   int64_t Limit = Int64 ? INT64_MIN : INT32_MIN;
341   int64_t Substitute = IsUnsigned ? 0 : Limit;
342   double CmpVal = IsUnsigned ? -(double)Limit * 2.0 : -(double)Limit;
343   auto &Context = BB->getParent()->getFunction().getContext();
344   Type *Ty = Float64 ? Type::getDoubleTy(Context) : Type::getFloatTy(Context);
345 
346   const BasicBlock *LLVMBB = BB->getBasicBlock();
347   MachineFunction *F = BB->getParent();
348   MachineBasicBlock *TrueMBB = F->CreateMachineBasicBlock(LLVMBB);
349   MachineBasicBlock *FalseMBB = F->CreateMachineBasicBlock(LLVMBB);
350   MachineBasicBlock *DoneMBB = F->CreateMachineBasicBlock(LLVMBB);
351 
352   MachineFunction::iterator It = ++BB->getIterator();
353   F->insert(It, FalseMBB);
354   F->insert(It, TrueMBB);
355   F->insert(It, DoneMBB);
356 
357   // Transfer the remainder of BB and its successor edges to DoneMBB.
358   DoneMBB->splice(DoneMBB->begin(), BB, std::next(MI.getIterator()), BB->end());
359   DoneMBB->transferSuccessorsAndUpdatePHIs(BB);
360 
361   BB->addSuccessor(TrueMBB);
362   BB->addSuccessor(FalseMBB);
363   TrueMBB->addSuccessor(DoneMBB);
364   FalseMBB->addSuccessor(DoneMBB);
365 
366   unsigned Tmp0, Tmp1, CmpReg, EqzReg, FalseReg, TrueReg;
367   Tmp0 = MRI.createVirtualRegister(MRI.getRegClass(InReg));
368   Tmp1 = MRI.createVirtualRegister(MRI.getRegClass(InReg));
369   CmpReg = MRI.createVirtualRegister(&WebAssembly::I32RegClass);
370   EqzReg = MRI.createVirtualRegister(&WebAssembly::I32RegClass);
371   FalseReg = MRI.createVirtualRegister(MRI.getRegClass(OutReg));
372   TrueReg = MRI.createVirtualRegister(MRI.getRegClass(OutReg));
373 
374   MI.eraseFromParent();
375   // For signed numbers, we can do a single comparison to determine whether
376   // fabs(x) is within range.
377   if (IsUnsigned) {
378     Tmp0 = InReg;
379   } else {
380     BuildMI(BB, DL, TII.get(Abs), Tmp0).addReg(InReg);
381   }
382   BuildMI(BB, DL, TII.get(FConst), Tmp1)
383       .addFPImm(cast<ConstantFP>(ConstantFP::get(Ty, CmpVal)));
384   BuildMI(BB, DL, TII.get(LT), CmpReg).addReg(Tmp0).addReg(Tmp1);
385 
386   // For unsigned numbers, we have to do a separate comparison with zero.
387   if (IsUnsigned) {
388     Tmp1 = MRI.createVirtualRegister(MRI.getRegClass(InReg));
389     Register SecondCmpReg =
390         MRI.createVirtualRegister(&WebAssembly::I32RegClass);
391     Register AndReg = MRI.createVirtualRegister(&WebAssembly::I32RegClass);
392     BuildMI(BB, DL, TII.get(FConst), Tmp1)
393         .addFPImm(cast<ConstantFP>(ConstantFP::get(Ty, 0.0)));
394     BuildMI(BB, DL, TII.get(GE), SecondCmpReg).addReg(Tmp0).addReg(Tmp1);
395     BuildMI(BB, DL, TII.get(And), AndReg).addReg(CmpReg).addReg(SecondCmpReg);
396     CmpReg = AndReg;
397   }
398 
399   BuildMI(BB, DL, TII.get(Eqz), EqzReg).addReg(CmpReg);
400 
401   // Create the CFG diamond to select between doing the conversion or using
402   // the substitute value.
403   BuildMI(BB, DL, TII.get(WebAssembly::BR_IF)).addMBB(TrueMBB).addReg(EqzReg);
404   BuildMI(FalseMBB, DL, TII.get(LoweredOpcode), FalseReg).addReg(InReg);
405   BuildMI(FalseMBB, DL, TII.get(WebAssembly::BR)).addMBB(DoneMBB);
406   BuildMI(TrueMBB, DL, TII.get(IConst), TrueReg).addImm(Substitute);
407   BuildMI(*DoneMBB, DoneMBB->begin(), DL, TII.get(TargetOpcode::PHI), OutReg)
408       .addReg(FalseReg)
409       .addMBB(FalseMBB)
410       .addReg(TrueReg)
411       .addMBB(TrueMBB);
412 
413   return DoneMBB;
414 }
415 
416 MachineBasicBlock *WebAssemblyTargetLowering::EmitInstrWithCustomInserter(
417     MachineInstr &MI, MachineBasicBlock *BB) const {
418   const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
419   DebugLoc DL = MI.getDebugLoc();
420 
421   switch (MI.getOpcode()) {
422   default:
423     llvm_unreachable("Unexpected instr type to insert");
424   case WebAssembly::FP_TO_SINT_I32_F32:
425     return LowerFPToInt(MI, DL, BB, TII, false, false, false,
426                         WebAssembly::I32_TRUNC_S_F32);
427   case WebAssembly::FP_TO_UINT_I32_F32:
428     return LowerFPToInt(MI, DL, BB, TII, true, false, false,
429                         WebAssembly::I32_TRUNC_U_F32);
430   case WebAssembly::FP_TO_SINT_I64_F32:
431     return LowerFPToInt(MI, DL, BB, TII, false, true, false,
432                         WebAssembly::I64_TRUNC_S_F32);
433   case WebAssembly::FP_TO_UINT_I64_F32:
434     return LowerFPToInt(MI, DL, BB, TII, true, true, false,
435                         WebAssembly::I64_TRUNC_U_F32);
436   case WebAssembly::FP_TO_SINT_I32_F64:
437     return LowerFPToInt(MI, DL, BB, TII, false, false, true,
438                         WebAssembly::I32_TRUNC_S_F64);
439   case WebAssembly::FP_TO_UINT_I32_F64:
440     return LowerFPToInt(MI, DL, BB, TII, true, false, true,
441                         WebAssembly::I32_TRUNC_U_F64);
442   case WebAssembly::FP_TO_SINT_I64_F64:
443     return LowerFPToInt(MI, DL, BB, TII, false, true, true,
444                         WebAssembly::I64_TRUNC_S_F64);
445   case WebAssembly::FP_TO_UINT_I64_F64:
446     return LowerFPToInt(MI, DL, BB, TII, true, true, true,
447                         WebAssembly::I64_TRUNC_U_F64);
448     llvm_unreachable("Unexpected instruction to emit with custom inserter");
449   }
450 }
451 
452 const char *
453 WebAssemblyTargetLowering::getTargetNodeName(unsigned Opcode) const {
454   switch (static_cast<WebAssemblyISD::NodeType>(Opcode)) {
455   case WebAssemblyISD::FIRST_NUMBER:
456     break;
457 #define HANDLE_NODETYPE(NODE)                                                  \
458   case WebAssemblyISD::NODE:                                                   \
459     return "WebAssemblyISD::" #NODE;
460 #include "WebAssemblyISD.def"
461 #undef HANDLE_NODETYPE
462   }
463   return nullptr;
464 }
465 
466 std::pair<unsigned, const TargetRegisterClass *>
467 WebAssemblyTargetLowering::getRegForInlineAsmConstraint(
468     const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
469   // First, see if this is a constraint that directly corresponds to a
470   // WebAssembly register class.
471   if (Constraint.size() == 1) {
472     switch (Constraint[0]) {
473     case 'r':
474       assert(VT != MVT::iPTR && "Pointer MVT not expected here");
475       if (Subtarget->hasSIMD128() && VT.isVector()) {
476         if (VT.getSizeInBits() == 128)
477           return std::make_pair(0U, &WebAssembly::V128RegClass);
478       }
479       if (VT.isInteger() && !VT.isVector()) {
480         if (VT.getSizeInBits() <= 32)
481           return std::make_pair(0U, &WebAssembly::I32RegClass);
482         if (VT.getSizeInBits() <= 64)
483           return std::make_pair(0U, &WebAssembly::I64RegClass);
484       }
485       break;
486     default:
487       break;
488     }
489   }
490 
491   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
492 }
493 
494 bool WebAssemblyTargetLowering::isCheapToSpeculateCttz() const {
495   // Assume ctz is a relatively cheap operation.
496   return true;
497 }
498 
499 bool WebAssemblyTargetLowering::isCheapToSpeculateCtlz() const {
500   // Assume clz is a relatively cheap operation.
501   return true;
502 }
503 
504 bool WebAssemblyTargetLowering::isLegalAddressingMode(const DataLayout &DL,
505                                                       const AddrMode &AM,
506                                                       Type *Ty, unsigned AS,
507                                                       Instruction *I) const {
508   // WebAssembly offsets are added as unsigned without wrapping. The
509   // isLegalAddressingMode gives us no way to determine if wrapping could be
510   // happening, so we approximate this by accepting only non-negative offsets.
511   if (AM.BaseOffs < 0)
512     return false;
513 
514   // WebAssembly has no scale register operands.
515   if (AM.Scale != 0)
516     return false;
517 
518   // Everything else is legal.
519   return true;
520 }
521 
522 bool WebAssemblyTargetLowering::allowsMisalignedMemoryAccesses(
523     EVT /*VT*/, unsigned /*AddrSpace*/, unsigned /*Align*/,
524     MachineMemOperand::Flags /*Flags*/, bool *Fast) const {
525   // WebAssembly supports unaligned accesses, though it should be declared
526   // with the p2align attribute on loads and stores which do so, and there
527   // may be a performance impact. We tell LLVM they're "fast" because
528   // for the kinds of things that LLVM uses this for (merging adjacent stores
529   // of constants, etc.), WebAssembly implementations will either want the
530   // unaligned access or they'll split anyway.
531   if (Fast)
532     *Fast = true;
533   return true;
534 }
535 
536 bool WebAssemblyTargetLowering::isIntDivCheap(EVT VT,
537                                               AttributeList Attr) const {
538   // The current thinking is that wasm engines will perform this optimization,
539   // so we can save on code size.
540   return true;
541 }
542 
543 EVT WebAssemblyTargetLowering::getSetCCResultType(const DataLayout &DL,
544                                                   LLVMContext &C,
545                                                   EVT VT) const {
546   if (VT.isVector())
547     return VT.changeVectorElementTypeToInteger();
548 
549   return TargetLowering::getSetCCResultType(DL, C, VT);
550 }
551 
552 bool WebAssemblyTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
553                                                    const CallInst &I,
554                                                    MachineFunction &MF,
555                                                    unsigned Intrinsic) const {
556   switch (Intrinsic) {
557   case Intrinsic::wasm_atomic_notify:
558     Info.opc = ISD::INTRINSIC_W_CHAIN;
559     Info.memVT = MVT::i32;
560     Info.ptrVal = I.getArgOperand(0);
561     Info.offset = 0;
562     Info.align = Align(4);
563     // atomic.notify instruction does not really load the memory specified with
564     // this argument, but MachineMemOperand should either be load or store, so
565     // we set this to a load.
566     // FIXME Volatile isn't really correct, but currently all LLVM atomic
567     // instructions are treated as volatiles in the backend, so we should be
568     // consistent. The same applies for wasm_atomic_wait intrinsics too.
569     Info.flags = MachineMemOperand::MOVolatile | MachineMemOperand::MOLoad;
570     return true;
571   case Intrinsic::wasm_atomic_wait_i32:
572     Info.opc = ISD::INTRINSIC_W_CHAIN;
573     Info.memVT = MVT::i32;
574     Info.ptrVal = I.getArgOperand(0);
575     Info.offset = 0;
576     Info.align = Align(4);
577     Info.flags = MachineMemOperand::MOVolatile | MachineMemOperand::MOLoad;
578     return true;
579   case Intrinsic::wasm_atomic_wait_i64:
580     Info.opc = ISD::INTRINSIC_W_CHAIN;
581     Info.memVT = MVT::i64;
582     Info.ptrVal = I.getArgOperand(0);
583     Info.offset = 0;
584     Info.align = Align(8);
585     Info.flags = MachineMemOperand::MOVolatile | MachineMemOperand::MOLoad;
586     return true;
587   default:
588     return false;
589   }
590 }
591 
592 //===----------------------------------------------------------------------===//
593 // WebAssembly Lowering private implementation.
594 //===----------------------------------------------------------------------===//
595 
596 //===----------------------------------------------------------------------===//
597 // Lowering Code
598 //===----------------------------------------------------------------------===//
599 
600 static void fail(const SDLoc &DL, SelectionDAG &DAG, const char *Msg) {
601   MachineFunction &MF = DAG.getMachineFunction();
602   DAG.getContext()->diagnose(
603       DiagnosticInfoUnsupported(MF.getFunction(), Msg, DL.getDebugLoc()));
604 }
605 
606 // Test whether the given calling convention is supported.
607 static bool callingConvSupported(CallingConv::ID CallConv) {
608   // We currently support the language-independent target-independent
609   // conventions. We don't yet have a way to annotate calls with properties like
610   // "cold", and we don't have any call-clobbered registers, so these are mostly
611   // all handled the same.
612   return CallConv == CallingConv::C || CallConv == CallingConv::Fast ||
613          CallConv == CallingConv::Cold ||
614          CallConv == CallingConv::PreserveMost ||
615          CallConv == CallingConv::PreserveAll ||
616          CallConv == CallingConv::CXX_FAST_TLS ||
617          CallConv == CallingConv::WASM_EmscriptenInvoke;
618 }
619 
620 SDValue
621 WebAssemblyTargetLowering::LowerCall(CallLoweringInfo &CLI,
622                                      SmallVectorImpl<SDValue> &InVals) const {
623   SelectionDAG &DAG = CLI.DAG;
624   SDLoc DL = CLI.DL;
625   SDValue Chain = CLI.Chain;
626   SDValue Callee = CLI.Callee;
627   MachineFunction &MF = DAG.getMachineFunction();
628   auto Layout = MF.getDataLayout();
629 
630   CallingConv::ID CallConv = CLI.CallConv;
631   if (!callingConvSupported(CallConv))
632     fail(DL, DAG,
633          "WebAssembly doesn't support language-specific or target-specific "
634          "calling conventions yet");
635   if (CLI.IsPatchPoint)
636     fail(DL, DAG, "WebAssembly doesn't support patch point yet");
637 
638   if (CLI.IsTailCall) {
639     bool MustTail = CLI.CS && CLI.CS.isMustTailCall();
640     if (Subtarget->hasTailCall() && !CLI.IsVarArg) {
641       // Do not tail call unless caller and callee return types match
642       const Function &F = MF.getFunction();
643       const TargetMachine &TM = getTargetMachine();
644       Type *RetTy = F.getReturnType();
645       SmallVector<MVT, 4> CallerRetTys;
646       SmallVector<MVT, 4> CalleeRetTys;
647       computeLegalValueVTs(F, TM, RetTy, CallerRetTys);
648       computeLegalValueVTs(F, TM, CLI.RetTy, CalleeRetTys);
649       bool TypesMatch = CallerRetTys.size() == CalleeRetTys.size() &&
650                         std::equal(CallerRetTys.begin(), CallerRetTys.end(),
651                                    CalleeRetTys.begin());
652       if (!TypesMatch) {
653         // musttail in this case would be an LLVM IR validation failure
654         assert(!MustTail);
655         CLI.IsTailCall = false;
656       }
657     } else {
658       CLI.IsTailCall = false;
659       if (MustTail) {
660         if (CLI.IsVarArg) {
661           // The return would pop the argument buffer
662           fail(DL, DAG, "WebAssembly does not support varargs tail calls");
663         } else {
664           fail(DL, DAG, "WebAssembly 'tail-call' feature not enabled");
665         }
666       }
667     }
668   }
669 
670   SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
671   if (Ins.size() > 1)
672     fail(DL, DAG, "WebAssembly doesn't support more than 1 returned value yet");
673 
674   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
675   SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
676 
677   // The generic code may have added an sret argument. If we're lowering an
678   // invoke function, the ABI requires that the function pointer be the first
679   // argument, so we may have to swap the arguments.
680   if (CallConv == CallingConv::WASM_EmscriptenInvoke && Outs.size() >= 2 &&
681       Outs[0].Flags.isSRet()) {
682     std::swap(Outs[0], Outs[1]);
683     std::swap(OutVals[0], OutVals[1]);
684   }
685 
686   unsigned NumFixedArgs = 0;
687   for (unsigned I = 0; I < Outs.size(); ++I) {
688     const ISD::OutputArg &Out = Outs[I];
689     SDValue &OutVal = OutVals[I];
690     if (Out.Flags.isNest())
691       fail(DL, DAG, "WebAssembly hasn't implemented nest arguments");
692     if (Out.Flags.isInAlloca())
693       fail(DL, DAG, "WebAssembly hasn't implemented inalloca arguments");
694     if (Out.Flags.isInConsecutiveRegs())
695       fail(DL, DAG, "WebAssembly hasn't implemented cons regs arguments");
696     if (Out.Flags.isInConsecutiveRegsLast())
697       fail(DL, DAG, "WebAssembly hasn't implemented cons regs last arguments");
698     if (Out.Flags.isByVal() && Out.Flags.getByValSize() != 0) {
699       auto &MFI = MF.getFrameInfo();
700       int FI = MFI.CreateStackObject(Out.Flags.getByValSize(),
701                                      Out.Flags.getByValAlign(),
702                                      /*isSS=*/false);
703       SDValue SizeNode =
704           DAG.getConstant(Out.Flags.getByValSize(), DL, MVT::i32);
705       SDValue FINode = DAG.getFrameIndex(FI, getPointerTy(Layout));
706       Chain = DAG.getMemcpy(
707           Chain, DL, FINode, OutVal, SizeNode, Out.Flags.getByValAlign(),
708           /*isVolatile*/ false, /*AlwaysInline=*/false,
709           /*isTailCall*/ false, MachinePointerInfo(), MachinePointerInfo());
710       OutVal = FINode;
711     }
712     // Count the number of fixed args *after* legalization.
713     NumFixedArgs += Out.IsFixed;
714   }
715 
716   bool IsVarArg = CLI.IsVarArg;
717   auto PtrVT = getPointerTy(Layout);
718 
719   // Analyze operands of the call, assigning locations to each operand.
720   SmallVector<CCValAssign, 16> ArgLocs;
721   CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
722 
723   if (IsVarArg) {
724     // Outgoing non-fixed arguments are placed in a buffer. First
725     // compute their offsets and the total amount of buffer space needed.
726     for (unsigned I = NumFixedArgs; I < Outs.size(); ++I) {
727       const ISD::OutputArg &Out = Outs[I];
728       SDValue &Arg = OutVals[I];
729       EVT VT = Arg.getValueType();
730       assert(VT != MVT::iPTR && "Legalized args should be concrete");
731       Type *Ty = VT.getTypeForEVT(*DAG.getContext());
732       unsigned Align = std::max(Out.Flags.getOrigAlign(),
733                                 Layout.getABITypeAlignment(Ty));
734       unsigned Offset = CCInfo.AllocateStack(Layout.getTypeAllocSize(Ty),
735                                              Align);
736       CCInfo.addLoc(CCValAssign::getMem(ArgLocs.size(), VT.getSimpleVT(),
737                                         Offset, VT.getSimpleVT(),
738                                         CCValAssign::Full));
739     }
740   }
741 
742   unsigned NumBytes = CCInfo.getAlignedCallFrameSize();
743 
744   SDValue FINode;
745   if (IsVarArg && NumBytes) {
746     // For non-fixed arguments, next emit stores to store the argument values
747     // to the stack buffer at the offsets computed above.
748     int FI = MF.getFrameInfo().CreateStackObject(NumBytes,
749                                                  Layout.getStackAlignment(),
750                                                  /*isSS=*/false);
751     unsigned ValNo = 0;
752     SmallVector<SDValue, 8> Chains;
753     for (SDValue Arg :
754          make_range(OutVals.begin() + NumFixedArgs, OutVals.end())) {
755       assert(ArgLocs[ValNo].getValNo() == ValNo &&
756              "ArgLocs should remain in order and only hold varargs args");
757       unsigned Offset = ArgLocs[ValNo++].getLocMemOffset();
758       FINode = DAG.getFrameIndex(FI, getPointerTy(Layout));
759       SDValue Add = DAG.getNode(ISD::ADD, DL, PtrVT, FINode,
760                                 DAG.getConstant(Offset, DL, PtrVT));
761       Chains.push_back(
762           DAG.getStore(Chain, DL, Arg, Add,
763                        MachinePointerInfo::getFixedStack(MF, FI, Offset), 0));
764     }
765     if (!Chains.empty())
766       Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
767   } else if (IsVarArg) {
768     FINode = DAG.getIntPtrConstant(0, DL);
769   }
770 
771   if (Callee->getOpcode() == ISD::GlobalAddress) {
772     // If the callee is a GlobalAddress node (quite common, every direct call
773     // is) turn it into a TargetGlobalAddress node so that LowerGlobalAddress
774     // doesn't at MO_GOT which is not needed for direct calls.
775     GlobalAddressSDNode* GA = cast<GlobalAddressSDNode>(Callee);
776     Callee = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
777                                         getPointerTy(DAG.getDataLayout()),
778                                         GA->getOffset());
779     Callee = DAG.getNode(WebAssemblyISD::Wrapper, DL,
780                          getPointerTy(DAG.getDataLayout()), Callee);
781   }
782 
783   // Compute the operands for the CALLn node.
784   SmallVector<SDValue, 16> Ops;
785   Ops.push_back(Chain);
786   Ops.push_back(Callee);
787 
788   // Add all fixed arguments. Note that for non-varargs calls, NumFixedArgs
789   // isn't reliable.
790   Ops.append(OutVals.begin(),
791              IsVarArg ? OutVals.begin() + NumFixedArgs : OutVals.end());
792   // Add a pointer to the vararg buffer.
793   if (IsVarArg)
794     Ops.push_back(FINode);
795 
796   SmallVector<EVT, 8> InTys;
797   for (const auto &In : Ins) {
798     assert(!In.Flags.isByVal() && "byval is not valid for return values");
799     assert(!In.Flags.isNest() && "nest is not valid for return values");
800     if (In.Flags.isInAlloca())
801       fail(DL, DAG, "WebAssembly hasn't implemented inalloca return values");
802     if (In.Flags.isInConsecutiveRegs())
803       fail(DL, DAG, "WebAssembly hasn't implemented cons regs return values");
804     if (In.Flags.isInConsecutiveRegsLast())
805       fail(DL, DAG,
806            "WebAssembly hasn't implemented cons regs last return values");
807     // Ignore In.getOrigAlign() because all our arguments are passed in
808     // registers.
809     InTys.push_back(In.VT);
810   }
811 
812   if (CLI.IsTailCall) {
813     // ret_calls do not return values to the current frame
814     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
815     return DAG.getNode(WebAssemblyISD::RET_CALL, DL, NodeTys, Ops);
816   }
817 
818   InTys.push_back(MVT::Other);
819   SDVTList InTyList = DAG.getVTList(InTys);
820   SDValue Res =
821       DAG.getNode(Ins.empty() ? WebAssemblyISD::CALL0 : WebAssemblyISD::CALL1,
822                   DL, InTyList, Ops);
823   if (Ins.empty()) {
824     Chain = Res;
825   } else {
826     InVals.push_back(Res);
827     Chain = Res.getValue(1);
828   }
829 
830   return Chain;
831 }
832 
833 bool WebAssemblyTargetLowering::CanLowerReturn(
834     CallingConv::ID /*CallConv*/, MachineFunction & /*MF*/, bool /*IsVarArg*/,
835     const SmallVectorImpl<ISD::OutputArg> &Outs,
836     LLVMContext & /*Context*/) const {
837   // WebAssembly can't currently handle returning tuples.
838   return Outs.size() <= 1;
839 }
840 
841 SDValue WebAssemblyTargetLowering::LowerReturn(
842     SDValue Chain, CallingConv::ID CallConv, bool /*IsVarArg*/,
843     const SmallVectorImpl<ISD::OutputArg> &Outs,
844     const SmallVectorImpl<SDValue> &OutVals, const SDLoc &DL,
845     SelectionDAG &DAG) const {
846   assert(Outs.size() <= 1 && "WebAssembly can only return up to one value");
847   if (!callingConvSupported(CallConv))
848     fail(DL, DAG, "WebAssembly doesn't support non-C calling conventions");
849 
850   SmallVector<SDValue, 4> RetOps(1, Chain);
851   RetOps.append(OutVals.begin(), OutVals.end());
852   Chain = DAG.getNode(WebAssemblyISD::RETURN, DL, MVT::Other, RetOps);
853 
854   // Record the number and types of the return values.
855   for (const ISD::OutputArg &Out : Outs) {
856     assert(!Out.Flags.isByVal() && "byval is not valid for return values");
857     assert(!Out.Flags.isNest() && "nest is not valid for return values");
858     assert(Out.IsFixed && "non-fixed return value is not valid");
859     if (Out.Flags.isInAlloca())
860       fail(DL, DAG, "WebAssembly hasn't implemented inalloca results");
861     if (Out.Flags.isInConsecutiveRegs())
862       fail(DL, DAG, "WebAssembly hasn't implemented cons regs results");
863     if (Out.Flags.isInConsecutiveRegsLast())
864       fail(DL, DAG, "WebAssembly hasn't implemented cons regs last results");
865   }
866 
867   return Chain;
868 }
869 
870 SDValue WebAssemblyTargetLowering::LowerFormalArguments(
871     SDValue Chain, CallingConv::ID CallConv, bool IsVarArg,
872     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
873     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
874   if (!callingConvSupported(CallConv))
875     fail(DL, DAG, "WebAssembly doesn't support non-C calling conventions");
876 
877   MachineFunction &MF = DAG.getMachineFunction();
878   auto *MFI = MF.getInfo<WebAssemblyFunctionInfo>();
879 
880   // Set up the incoming ARGUMENTS value, which serves to represent the liveness
881   // of the incoming values before they're represented by virtual registers.
882   MF.getRegInfo().addLiveIn(WebAssembly::ARGUMENTS);
883 
884   for (const ISD::InputArg &In : Ins) {
885     if (In.Flags.isInAlloca())
886       fail(DL, DAG, "WebAssembly hasn't implemented inalloca arguments");
887     if (In.Flags.isNest())
888       fail(DL, DAG, "WebAssembly hasn't implemented nest arguments");
889     if (In.Flags.isInConsecutiveRegs())
890       fail(DL, DAG, "WebAssembly hasn't implemented cons regs arguments");
891     if (In.Flags.isInConsecutiveRegsLast())
892       fail(DL, DAG, "WebAssembly hasn't implemented cons regs last arguments");
893     // Ignore In.getOrigAlign() because all our arguments are passed in
894     // registers.
895     InVals.push_back(In.Used ? DAG.getNode(WebAssemblyISD::ARGUMENT, DL, In.VT,
896                                            DAG.getTargetConstant(InVals.size(),
897                                                                  DL, MVT::i32))
898                              : DAG.getUNDEF(In.VT));
899 
900     // Record the number and types of arguments.
901     MFI->addParam(In.VT);
902   }
903 
904   // Varargs are copied into a buffer allocated by the caller, and a pointer to
905   // the buffer is passed as an argument.
906   if (IsVarArg) {
907     MVT PtrVT = getPointerTy(MF.getDataLayout());
908     Register VarargVreg =
909         MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrVT));
910     MFI->setVarargBufferVreg(VarargVreg);
911     Chain = DAG.getCopyToReg(
912         Chain, DL, VarargVreg,
913         DAG.getNode(WebAssemblyISD::ARGUMENT, DL, PtrVT,
914                     DAG.getTargetConstant(Ins.size(), DL, MVT::i32)));
915     MFI->addParam(PtrVT);
916   }
917 
918   // Record the number and types of arguments and results.
919   SmallVector<MVT, 4> Params;
920   SmallVector<MVT, 4> Results;
921   computeSignatureVTs(MF.getFunction().getFunctionType(), MF.getFunction(),
922                       DAG.getTarget(), Params, Results);
923   for (MVT VT : Results)
924     MFI->addResult(VT);
925   // TODO: Use signatures in WebAssemblyMachineFunctionInfo too and unify
926   // the param logic here with ComputeSignatureVTs
927   assert(MFI->getParams().size() == Params.size() &&
928          std::equal(MFI->getParams().begin(), MFI->getParams().end(),
929                     Params.begin()));
930 
931   return Chain;
932 }
933 
934 void WebAssemblyTargetLowering::ReplaceNodeResults(
935     SDNode *N, SmallVectorImpl<SDValue> &Results, SelectionDAG &DAG) const {
936   switch (N->getOpcode()) {
937   case ISD::SIGN_EXTEND_INREG:
938     // Do not add any results, signifying that N should not be custom lowered
939     // after all. This happens because simd128 turns on custom lowering for
940     // SIGN_EXTEND_INREG, but for non-vector sign extends the result might be an
941     // illegal type.
942     break;
943   default:
944     llvm_unreachable(
945         "ReplaceNodeResults not implemented for this op for WebAssembly!");
946   }
947 }
948 
949 //===----------------------------------------------------------------------===//
950 //  Custom lowering hooks.
951 //===----------------------------------------------------------------------===//
952 
953 SDValue WebAssemblyTargetLowering::LowerOperation(SDValue Op,
954                                                   SelectionDAG &DAG) const {
955   SDLoc DL(Op);
956   switch (Op.getOpcode()) {
957   default:
958     llvm_unreachable("unimplemented operation lowering");
959     return SDValue();
960   case ISD::FrameIndex:
961     return LowerFrameIndex(Op, DAG);
962   case ISD::GlobalAddress:
963     return LowerGlobalAddress(Op, DAG);
964   case ISD::ExternalSymbol:
965     return LowerExternalSymbol(Op, DAG);
966   case ISD::JumpTable:
967     return LowerJumpTable(Op, DAG);
968   case ISD::BR_JT:
969     return LowerBR_JT(Op, DAG);
970   case ISD::VASTART:
971     return LowerVASTART(Op, DAG);
972   case ISD::BlockAddress:
973   case ISD::BRIND:
974     fail(DL, DAG, "WebAssembly hasn't implemented computed gotos");
975     return SDValue();
976   case ISD::RETURNADDR:
977     return LowerRETURNADDR(Op, DAG);
978   case ISD::FRAMEADDR:
979     return LowerFRAMEADDR(Op, DAG);
980   case ISD::CopyToReg:
981     return LowerCopyToReg(Op, DAG);
982   case ISD::EXTRACT_VECTOR_ELT:
983   case ISD::INSERT_VECTOR_ELT:
984     return LowerAccessVectorElement(Op, DAG);
985   case ISD::INTRINSIC_VOID:
986   case ISD::INTRINSIC_WO_CHAIN:
987   case ISD::INTRINSIC_W_CHAIN:
988     return LowerIntrinsic(Op, DAG);
989   case ISD::SIGN_EXTEND_INREG:
990     return LowerSIGN_EXTEND_INREG(Op, DAG);
991   case ISD::BUILD_VECTOR:
992     return LowerBUILD_VECTOR(Op, DAG);
993   case ISD::VECTOR_SHUFFLE:
994     return LowerVECTOR_SHUFFLE(Op, DAG);
995   case ISD::SHL:
996   case ISD::SRA:
997   case ISD::SRL:
998     return LowerShift(Op, DAG);
999   }
1000 }
1001 
1002 SDValue WebAssemblyTargetLowering::LowerCopyToReg(SDValue Op,
1003                                                   SelectionDAG &DAG) const {
1004   SDValue Src = Op.getOperand(2);
1005   if (isa<FrameIndexSDNode>(Src.getNode())) {
1006     // CopyToReg nodes don't support FrameIndex operands. Other targets select
1007     // the FI to some LEA-like instruction, but since we don't have that, we
1008     // need to insert some kind of instruction that can take an FI operand and
1009     // produces a value usable by CopyToReg (i.e. in a vreg). So insert a dummy
1010     // local.copy between Op and its FI operand.
1011     SDValue Chain = Op.getOperand(0);
1012     SDLoc DL(Op);
1013     unsigned Reg = cast<RegisterSDNode>(Op.getOperand(1))->getReg();
1014     EVT VT = Src.getValueType();
1015     SDValue Copy(DAG.getMachineNode(VT == MVT::i32 ? WebAssembly::COPY_I32
1016                                                    : WebAssembly::COPY_I64,
1017                                     DL, VT, Src),
1018                  0);
1019     return Op.getNode()->getNumValues() == 1
1020                ? DAG.getCopyToReg(Chain, DL, Reg, Copy)
1021                : DAG.getCopyToReg(Chain, DL, Reg, Copy,
1022                                   Op.getNumOperands() == 4 ? Op.getOperand(3)
1023                                                            : SDValue());
1024   }
1025   return SDValue();
1026 }
1027 
1028 SDValue WebAssemblyTargetLowering::LowerFrameIndex(SDValue Op,
1029                                                    SelectionDAG &DAG) const {
1030   int FI = cast<FrameIndexSDNode>(Op)->getIndex();
1031   return DAG.getTargetFrameIndex(FI, Op.getValueType());
1032 }
1033 
1034 SDValue WebAssemblyTargetLowering::LowerRETURNADDR(SDValue Op,
1035                                                    SelectionDAG &DAG) const {
1036   SDLoc DL(Op);
1037 
1038   if (!Subtarget->getTargetTriple().isOSEmscripten()) {
1039     fail(DL, DAG,
1040          "Non-Emscripten WebAssembly hasn't implemented "
1041          "__builtin_return_address");
1042     return SDValue();
1043   }
1044 
1045   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
1046     return SDValue();
1047 
1048   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
1049   MakeLibCallOptions CallOptions;
1050   return makeLibCall(DAG, RTLIB::RETURN_ADDRESS, Op.getValueType(),
1051                      {DAG.getConstant(Depth, DL, MVT::i32)}, CallOptions, DL)
1052       .first;
1053 }
1054 
1055 SDValue WebAssemblyTargetLowering::LowerFRAMEADDR(SDValue Op,
1056                                                   SelectionDAG &DAG) const {
1057   // Non-zero depths are not supported by WebAssembly currently. Use the
1058   // legalizer's default expansion, which is to return 0 (what this function is
1059   // documented to do).
1060   if (Op.getConstantOperandVal(0) > 0)
1061     return SDValue();
1062 
1063   DAG.getMachineFunction().getFrameInfo().setFrameAddressIsTaken(true);
1064   EVT VT = Op.getValueType();
1065   Register FP =
1066       Subtarget->getRegisterInfo()->getFrameRegister(DAG.getMachineFunction());
1067   return DAG.getCopyFromReg(DAG.getEntryNode(), SDLoc(Op), FP, VT);
1068 }
1069 
1070 SDValue WebAssemblyTargetLowering::LowerGlobalAddress(SDValue Op,
1071                                                       SelectionDAG &DAG) const {
1072   SDLoc DL(Op);
1073   const auto *GA = cast<GlobalAddressSDNode>(Op);
1074   EVT VT = Op.getValueType();
1075   assert(GA->getTargetFlags() == 0 &&
1076          "Unexpected target flags on generic GlobalAddressSDNode");
1077   if (GA->getAddressSpace() != 0)
1078     fail(DL, DAG, "WebAssembly only expects the 0 address space");
1079 
1080   unsigned OperandFlags = 0;
1081   if (isPositionIndependent()) {
1082     const GlobalValue *GV = GA->getGlobal();
1083     if (getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV)) {
1084       MachineFunction &MF = DAG.getMachineFunction();
1085       MVT PtrVT = getPointerTy(MF.getDataLayout());
1086       const char *BaseName;
1087       if (GV->getValueType()->isFunctionTy()) {
1088         BaseName = MF.createExternalSymbolName("__table_base");
1089         OperandFlags = WebAssemblyII::MO_TABLE_BASE_REL;
1090       }
1091       else {
1092         BaseName = MF.createExternalSymbolName("__memory_base");
1093         OperandFlags = WebAssemblyII::MO_MEMORY_BASE_REL;
1094       }
1095       SDValue BaseAddr =
1096           DAG.getNode(WebAssemblyISD::Wrapper, DL, PtrVT,
1097                       DAG.getTargetExternalSymbol(BaseName, PtrVT));
1098 
1099       SDValue SymAddr = DAG.getNode(
1100           WebAssemblyISD::WrapperPIC, DL, VT,
1101           DAG.getTargetGlobalAddress(GA->getGlobal(), DL, VT, GA->getOffset(),
1102                                      OperandFlags));
1103 
1104       return DAG.getNode(ISD::ADD, DL, VT, BaseAddr, SymAddr);
1105     } else {
1106       OperandFlags = WebAssemblyII::MO_GOT;
1107     }
1108   }
1109 
1110   return DAG.getNode(WebAssemblyISD::Wrapper, DL, VT,
1111                      DAG.getTargetGlobalAddress(GA->getGlobal(), DL, VT,
1112                                                 GA->getOffset(), OperandFlags));
1113 }
1114 
1115 SDValue
1116 WebAssemblyTargetLowering::LowerExternalSymbol(SDValue Op,
1117                                                SelectionDAG &DAG) const {
1118   SDLoc DL(Op);
1119   const auto *ES = cast<ExternalSymbolSDNode>(Op);
1120   EVT VT = Op.getValueType();
1121   assert(ES->getTargetFlags() == 0 &&
1122          "Unexpected target flags on generic ExternalSymbolSDNode");
1123   return DAG.getNode(WebAssemblyISD::Wrapper, DL, VT,
1124                      DAG.getTargetExternalSymbol(ES->getSymbol(), VT));
1125 }
1126 
1127 SDValue WebAssemblyTargetLowering::LowerJumpTable(SDValue Op,
1128                                                   SelectionDAG &DAG) const {
1129   // There's no need for a Wrapper node because we always incorporate a jump
1130   // table operand into a BR_TABLE instruction, rather than ever
1131   // materializing it in a register.
1132   const JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
1133   return DAG.getTargetJumpTable(JT->getIndex(), Op.getValueType(),
1134                                 JT->getTargetFlags());
1135 }
1136 
1137 SDValue WebAssemblyTargetLowering::LowerBR_JT(SDValue Op,
1138                                               SelectionDAG &DAG) const {
1139   SDLoc DL(Op);
1140   SDValue Chain = Op.getOperand(0);
1141   const auto *JT = cast<JumpTableSDNode>(Op.getOperand(1));
1142   SDValue Index = Op.getOperand(2);
1143   assert(JT->getTargetFlags() == 0 && "WebAssembly doesn't set target flags");
1144 
1145   SmallVector<SDValue, 8> Ops;
1146   Ops.push_back(Chain);
1147   Ops.push_back(Index);
1148 
1149   MachineJumpTableInfo *MJTI = DAG.getMachineFunction().getJumpTableInfo();
1150   const auto &MBBs = MJTI->getJumpTables()[JT->getIndex()].MBBs;
1151 
1152   // Add an operand for each case.
1153   for (auto MBB : MBBs)
1154     Ops.push_back(DAG.getBasicBlock(MBB));
1155 
1156   // TODO: For now, we just pick something arbitrary for a default case for now.
1157   // We really want to sniff out the guard and put in the real default case (and
1158   // delete the guard).
1159   Ops.push_back(DAG.getBasicBlock(MBBs[0]));
1160 
1161   return DAG.getNode(WebAssemblyISD::BR_TABLE, DL, MVT::Other, Ops);
1162 }
1163 
1164 SDValue WebAssemblyTargetLowering::LowerVASTART(SDValue Op,
1165                                                 SelectionDAG &DAG) const {
1166   SDLoc DL(Op);
1167   EVT PtrVT = getPointerTy(DAG.getMachineFunction().getDataLayout());
1168 
1169   auto *MFI = DAG.getMachineFunction().getInfo<WebAssemblyFunctionInfo>();
1170   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
1171 
1172   SDValue ArgN = DAG.getCopyFromReg(DAG.getEntryNode(), DL,
1173                                     MFI->getVarargBufferVreg(), PtrVT);
1174   return DAG.getStore(Op.getOperand(0), DL, ArgN, Op.getOperand(1),
1175                       MachinePointerInfo(SV), 0);
1176 }
1177 
1178 SDValue WebAssemblyTargetLowering::LowerIntrinsic(SDValue Op,
1179                                                   SelectionDAG &DAG) const {
1180   MachineFunction &MF = DAG.getMachineFunction();
1181   unsigned IntNo;
1182   switch (Op.getOpcode()) {
1183   case ISD::INTRINSIC_VOID:
1184   case ISD::INTRINSIC_W_CHAIN:
1185     IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
1186     break;
1187   case ISD::INTRINSIC_WO_CHAIN:
1188     IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
1189     break;
1190   default:
1191     llvm_unreachable("Invalid intrinsic");
1192   }
1193   SDLoc DL(Op);
1194 
1195   switch (IntNo) {
1196   default:
1197     return SDValue(); // Don't custom lower most intrinsics.
1198 
1199   case Intrinsic::wasm_lsda: {
1200     EVT VT = Op.getValueType();
1201     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1202     MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
1203     auto &Context = MF.getMMI().getContext();
1204     MCSymbol *S = Context.getOrCreateSymbol(Twine("GCC_except_table") +
1205                                             Twine(MF.getFunctionNumber()));
1206     return DAG.getNode(WebAssemblyISD::Wrapper, DL, VT,
1207                        DAG.getMCSymbol(S, PtrVT));
1208   }
1209 
1210   case Intrinsic::wasm_throw: {
1211     // We only support C++ exceptions for now
1212     int Tag = cast<ConstantSDNode>(Op.getOperand(2).getNode())->getZExtValue();
1213     if (Tag != CPP_EXCEPTION)
1214       llvm_unreachable("Invalid tag!");
1215     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1216     MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
1217     const char *SymName = MF.createExternalSymbolName("__cpp_exception");
1218     SDValue SymNode = DAG.getNode(WebAssemblyISD::Wrapper, DL, PtrVT,
1219                                   DAG.getTargetExternalSymbol(SymName, PtrVT));
1220     return DAG.getNode(WebAssemblyISD::THROW, DL,
1221                        MVT::Other, // outchain type
1222                        {
1223                            Op.getOperand(0), // inchain
1224                            SymNode,          // exception symbol
1225                            Op.getOperand(3)  // thrown value
1226                        });
1227   }
1228   }
1229 }
1230 
1231 SDValue
1232 WebAssemblyTargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
1233                                                   SelectionDAG &DAG) const {
1234   SDLoc DL(Op);
1235   // If sign extension operations are disabled, allow sext_inreg only if operand
1236   // is a vector extract. SIMD does not depend on sign extension operations, but
1237   // allowing sext_inreg in this context lets us have simple patterns to select
1238   // extract_lane_s instructions. Expanding sext_inreg everywhere would be
1239   // simpler in this file, but would necessitate large and brittle patterns to
1240   // undo the expansion and select extract_lane_s instructions.
1241   assert(!Subtarget->hasSignExt() && Subtarget->hasSIMD128());
1242   if (Op.getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
1243     const SDValue &Extract = Op.getOperand(0);
1244     MVT VecT = Extract.getOperand(0).getSimpleValueType();
1245     MVT ExtractedLaneT = static_cast<VTSDNode *>(Op.getOperand(1).getNode())
1246                              ->getVT()
1247                              .getSimpleVT();
1248     MVT ExtractedVecT =
1249         MVT::getVectorVT(ExtractedLaneT, 128 / ExtractedLaneT.getSizeInBits());
1250     if (ExtractedVecT == VecT)
1251       return Op;
1252     // Bitcast vector to appropriate type to ensure ISel pattern coverage
1253     const SDValue &Index = Extract.getOperand(1);
1254     unsigned IndexVal =
1255         static_cast<ConstantSDNode *>(Index.getNode())->getZExtValue();
1256     unsigned Scale =
1257         ExtractedVecT.getVectorNumElements() / VecT.getVectorNumElements();
1258     assert(Scale > 1);
1259     SDValue NewIndex =
1260         DAG.getConstant(IndexVal * Scale, DL, Index.getValueType());
1261     SDValue NewExtract = DAG.getNode(
1262         ISD::EXTRACT_VECTOR_ELT, DL, Extract.getValueType(),
1263         DAG.getBitcast(ExtractedVecT, Extract.getOperand(0)), NewIndex);
1264     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, Op.getValueType(),
1265                        NewExtract, Op.getOperand(1));
1266   }
1267   // Otherwise expand
1268   return SDValue();
1269 }
1270 
1271 SDValue WebAssemblyTargetLowering::LowerBUILD_VECTOR(SDValue Op,
1272                                                      SelectionDAG &DAG) const {
1273   SDLoc DL(Op);
1274   const EVT VecT = Op.getValueType();
1275   const EVT LaneT = Op.getOperand(0).getValueType();
1276   const size_t Lanes = Op.getNumOperands();
1277   auto IsConstant = [](const SDValue &V) {
1278     return V.getOpcode() == ISD::Constant || V.getOpcode() == ISD::ConstantFP;
1279   };
1280 
1281   // Find the most common operand, which is approximately the best to splat
1282   using Entry = std::pair<SDValue, size_t>;
1283   SmallVector<Entry, 16> ValueCounts;
1284   size_t NumConst = 0, NumDynamic = 0;
1285   for (const SDValue &Lane : Op->op_values()) {
1286     if (Lane.isUndef()) {
1287       continue;
1288     } else if (IsConstant(Lane)) {
1289       NumConst++;
1290     } else {
1291       NumDynamic++;
1292     }
1293     auto CountIt = std::find_if(ValueCounts.begin(), ValueCounts.end(),
1294                                 [&Lane](Entry A) { return A.first == Lane; });
1295     if (CountIt == ValueCounts.end()) {
1296       ValueCounts.emplace_back(Lane, 1);
1297     } else {
1298       CountIt->second++;
1299     }
1300   }
1301   auto CommonIt =
1302       std::max_element(ValueCounts.begin(), ValueCounts.end(),
1303                        [](Entry A, Entry B) { return A.second < B.second; });
1304   assert(CommonIt != ValueCounts.end() && "Unexpected all-undef build_vector");
1305   SDValue SplatValue = CommonIt->first;
1306   size_t NumCommon = CommonIt->second;
1307 
1308   // If v128.const is available, consider using it instead of a splat
1309   if (Subtarget->hasUnimplementedSIMD128()) {
1310     // {i32,i64,f32,f64}.const opcode, and value
1311     const size_t ConstBytes = 1 + std::max(size_t(4), 16 / Lanes);
1312     // SIMD prefix and opcode
1313     const size_t SplatBytes = 2;
1314     const size_t SplatConstBytes = SplatBytes + ConstBytes;
1315     // SIMD prefix, opcode, and lane index
1316     const size_t ReplaceBytes = 3;
1317     const size_t ReplaceConstBytes = ReplaceBytes + ConstBytes;
1318     // SIMD prefix, v128.const opcode, and 128-bit value
1319     const size_t VecConstBytes = 18;
1320     // Initial v128.const and a replace_lane for each non-const operand
1321     const size_t ConstInitBytes = VecConstBytes + NumDynamic * ReplaceBytes;
1322     // Initial splat and all necessary replace_lanes
1323     const size_t SplatInitBytes =
1324         IsConstant(SplatValue)
1325             // Initial constant splat
1326             ? (SplatConstBytes +
1327                // Constant replace_lanes
1328                (NumConst - NumCommon) * ReplaceConstBytes +
1329                // Dynamic replace_lanes
1330                (NumDynamic * ReplaceBytes))
1331             // Initial dynamic splat
1332             : (SplatBytes +
1333                // Constant replace_lanes
1334                (NumConst * ReplaceConstBytes) +
1335                // Dynamic replace_lanes
1336                (NumDynamic - NumCommon) * ReplaceBytes);
1337     if (ConstInitBytes < SplatInitBytes) {
1338       // Create build_vector that will lower to initial v128.const
1339       SmallVector<SDValue, 16> ConstLanes;
1340       for (const SDValue &Lane : Op->op_values()) {
1341         if (IsConstant(Lane)) {
1342           ConstLanes.push_back(Lane);
1343         } else if (LaneT.isFloatingPoint()) {
1344           ConstLanes.push_back(DAG.getConstantFP(0, DL, LaneT));
1345         } else {
1346           ConstLanes.push_back(DAG.getConstant(0, DL, LaneT));
1347         }
1348       }
1349       SDValue Result = DAG.getBuildVector(VecT, DL, ConstLanes);
1350       // Add replace_lane instructions for non-const lanes
1351       for (size_t I = 0; I < Lanes; ++I) {
1352         const SDValue &Lane = Op->getOperand(I);
1353         if (!Lane.isUndef() && !IsConstant(Lane))
1354           Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VecT, Result, Lane,
1355                                DAG.getConstant(I, DL, MVT::i32));
1356       }
1357       return Result;
1358     }
1359   }
1360   // Use a splat for the initial vector
1361   SDValue Result;
1362   // Possibly a load_splat
1363   LoadSDNode *SplattedLoad;
1364   if (Subtarget->hasUnimplementedSIMD128() &&
1365       (SplattedLoad = dyn_cast<LoadSDNode>(SplatValue)) &&
1366       SplattedLoad->getMemoryVT() == VecT.getVectorElementType()) {
1367     Result = DAG.getNode(WebAssemblyISD::LOAD_SPLAT, DL, VecT, SplatValue);
1368   } else {
1369     Result = DAG.getSplatBuildVector(VecT, DL, SplatValue);
1370   }
1371   // Add replace_lane instructions for other values
1372   for (size_t I = 0; I < Lanes; ++I) {
1373     const SDValue &Lane = Op->getOperand(I);
1374     if (Lane != SplatValue)
1375       Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VecT, Result, Lane,
1376                            DAG.getConstant(I, DL, MVT::i32));
1377   }
1378   return Result;
1379 }
1380 
1381 SDValue
1382 WebAssemblyTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
1383                                                SelectionDAG &DAG) const {
1384   SDLoc DL(Op);
1385   ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Op.getNode())->getMask();
1386   MVT VecType = Op.getOperand(0).getSimpleValueType();
1387   assert(VecType.is128BitVector() && "Unexpected shuffle vector type");
1388   size_t LaneBytes = VecType.getVectorElementType().getSizeInBits() / 8;
1389 
1390   // Space for two vector args and sixteen mask indices
1391   SDValue Ops[18];
1392   size_t OpIdx = 0;
1393   Ops[OpIdx++] = Op.getOperand(0);
1394   Ops[OpIdx++] = Op.getOperand(1);
1395 
1396   // Expand mask indices to byte indices and materialize them as operands
1397   for (int M : Mask) {
1398     for (size_t J = 0; J < LaneBytes; ++J) {
1399       // Lower undefs (represented by -1 in mask) to zero
1400       uint64_t ByteIndex = M == -1 ? 0 : (uint64_t)M * LaneBytes + J;
1401       Ops[OpIdx++] = DAG.getConstant(ByteIndex, DL, MVT::i32);
1402     }
1403   }
1404 
1405   return DAG.getNode(WebAssemblyISD::SHUFFLE, DL, Op.getValueType(), Ops);
1406 }
1407 
1408 SDValue
1409 WebAssemblyTargetLowering::LowerAccessVectorElement(SDValue Op,
1410                                                     SelectionDAG &DAG) const {
1411   // Allow constant lane indices, expand variable lane indices
1412   SDNode *IdxNode = Op.getOperand(Op.getNumOperands() - 1).getNode();
1413   if (isa<ConstantSDNode>(IdxNode) || IdxNode->isUndef())
1414     return Op;
1415   else
1416     // Perform default expansion
1417     return SDValue();
1418 }
1419 
1420 static SDValue unrollVectorShift(SDValue Op, SelectionDAG &DAG) {
1421   EVT LaneT = Op.getSimpleValueType().getVectorElementType();
1422   // 32-bit and 64-bit unrolled shifts will have proper semantics
1423   if (LaneT.bitsGE(MVT::i32))
1424     return DAG.UnrollVectorOp(Op.getNode());
1425   // Otherwise mask the shift value to get proper semantics from 32-bit shift
1426   SDLoc DL(Op);
1427   SDValue ShiftVal = Op.getOperand(1);
1428   uint64_t MaskVal = LaneT.getSizeInBits() - 1;
1429   SDValue MaskedShiftVal = DAG.getNode(
1430       ISD::AND,                    // mask opcode
1431       DL, ShiftVal.getValueType(), // masked value type
1432       ShiftVal,                    // original shift value operand
1433       DAG.getConstant(MaskVal, DL, ShiftVal.getValueType()) // mask operand
1434   );
1435 
1436   return DAG.UnrollVectorOp(
1437       DAG.getNode(Op.getOpcode(),        // original shift opcode
1438                   DL, Op.getValueType(), // original return type
1439                   Op.getOperand(0),      // original vector operand,
1440                   MaskedShiftVal         // new masked shift value operand
1441                   )
1442           .getNode());
1443 }
1444 
1445 SDValue WebAssemblyTargetLowering::LowerShift(SDValue Op,
1446                                               SelectionDAG &DAG) const {
1447   SDLoc DL(Op);
1448 
1449   // Only manually lower vector shifts
1450   assert(Op.getSimpleValueType().isVector());
1451 
1452   // Unroll non-splat vector shifts
1453   BuildVectorSDNode *ShiftVec;
1454   SDValue SplatVal;
1455   if (!(ShiftVec = dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode())) ||
1456       !(SplatVal = ShiftVec->getSplatValue()))
1457     return unrollVectorShift(Op, DAG);
1458 
1459   // All splats except i64x2 const splats are handled by patterns
1460   auto *SplatConst = dyn_cast<ConstantSDNode>(SplatVal);
1461   if (!SplatConst || Op.getSimpleValueType() != MVT::v2i64)
1462     return Op;
1463 
1464   // i64x2 const splats are custom lowered to avoid unnecessary wraps
1465   unsigned Opcode;
1466   switch (Op.getOpcode()) {
1467   case ISD::SHL:
1468     Opcode = WebAssemblyISD::VEC_SHL;
1469     break;
1470   case ISD::SRA:
1471     Opcode = WebAssemblyISD::VEC_SHR_S;
1472     break;
1473   case ISD::SRL:
1474     Opcode = WebAssemblyISD::VEC_SHR_U;
1475     break;
1476   default:
1477     llvm_unreachable("unexpected opcode");
1478   }
1479   APInt Shift = SplatConst->getAPIntValue().zextOrTrunc(32);
1480   return DAG.getNode(Opcode, DL, Op.getValueType(), Op.getOperand(0),
1481                      DAG.getConstant(Shift, DL, MVT::i32));
1482 }
1483 
1484 //===----------------------------------------------------------------------===//
1485 //                          WebAssembly Optimization Hooks
1486 //===----------------------------------------------------------------------===//
1487