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