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