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