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