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