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     // Expand operations not supported for i64x2 vectors
190     for (unsigned CC = 0; CC < ISD::SETCC_INVALID; ++CC)
191       setCondCodeAction(static_cast<ISD::CondCode>(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 *LowerCallResults(MachineInstr &CallResults,
430                                            DebugLoc DL, MachineBasicBlock *BB,
431                                            const TargetInstrInfo &TII) {
432   MachineInstr &CallParams = *CallResults.getPrevNode();
433   assert(CallParams.getOpcode() == WebAssembly::CALL_PARAMS);
434   assert(CallResults.getOpcode() == WebAssembly::CALL_RESULTS ||
435          CallResults.getOpcode() == WebAssembly::RET_CALL_RESULTS);
436 
437   bool IsIndirect = CallParams.getOperand(0).isReg();
438   bool IsRetCall = CallResults.getOpcode() == WebAssembly::RET_CALL_RESULTS;
439 
440   unsigned CallOp;
441   if (IsIndirect && IsRetCall) {
442     CallOp = WebAssembly::RET_CALL_INDIRECT;
443   } else if (IsIndirect) {
444     CallOp = WebAssembly::CALL_INDIRECT;
445   } else if (IsRetCall) {
446     CallOp = WebAssembly::RET_CALL;
447   } else {
448     CallOp = WebAssembly::CALL;
449   }
450 
451   MachineFunction &MF = *BB->getParent();
452   const MCInstrDesc &MCID = TII.get(CallOp);
453   MachineInstrBuilder MIB(MF, MF.CreateMachineInstr(MCID, DL));
454 
455   // See if we must truncate the function pointer.
456   // CALL_INDIRECT takes an i32, but in wasm64 we represent function pointers
457   // as 64-bit for uniformity with other pointer types.
458   // See also: WebAssemblyFastISel::selectCall
459   if (IsIndirect && MF.getSubtarget<WebAssemblySubtarget>().hasAddr64()) {
460     Register Reg32 =
461         MF.getRegInfo().createVirtualRegister(&WebAssembly::I32RegClass);
462     auto &FnPtr = CallParams.getOperand(0);
463     BuildMI(*BB, CallResults.getIterator(), DL,
464             TII.get(WebAssembly::I32_WRAP_I64), Reg32)
465         .addReg(FnPtr.getReg());
466     FnPtr.setReg(Reg32);
467   }
468 
469   // Move the function pointer to the end of the arguments for indirect calls
470   if (IsIndirect) {
471     auto FnPtr = CallParams.getOperand(0);
472     CallParams.RemoveOperand(0);
473     CallParams.addOperand(FnPtr);
474   }
475 
476   for (auto Def : CallResults.defs())
477     MIB.add(Def);
478 
479   // Add placeholders for the type index and immediate flags
480   if (IsIndirect) {
481     MIB.addImm(0);
482     MIB.addImm(0);
483 
484     // Ensure that the object file has a __indirect_function_table import, as we
485     // call_indirect against it.
486     MCSymbolWasm *Sym = WebAssembly::getOrCreateFunctionTableSymbol(
487         MF.getContext(), "__indirect_function_table");
488     // Until call_indirect emits TABLE_NUMBER relocs against this symbol, mark
489     // it as NO_STRIP so as to ensure that the indirect function table makes it
490     // to linked output.
491     Sym->setNoStrip();
492   }
493 
494   for (auto Use : CallParams.uses())
495     MIB.add(Use);
496 
497   BB->insert(CallResults.getIterator(), MIB);
498   CallParams.eraseFromParent();
499   CallResults.eraseFromParent();
500 
501   return BB;
502 }
503 
504 MachineBasicBlock *WebAssemblyTargetLowering::EmitInstrWithCustomInserter(
505     MachineInstr &MI, MachineBasicBlock *BB) const {
506   const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
507   DebugLoc DL = MI.getDebugLoc();
508 
509   switch (MI.getOpcode()) {
510   default:
511     llvm_unreachable("Unexpected instr type to insert");
512   case WebAssembly::FP_TO_SINT_I32_F32:
513     return LowerFPToInt(MI, DL, BB, TII, false, false, false,
514                         WebAssembly::I32_TRUNC_S_F32);
515   case WebAssembly::FP_TO_UINT_I32_F32:
516     return LowerFPToInt(MI, DL, BB, TII, true, false, false,
517                         WebAssembly::I32_TRUNC_U_F32);
518   case WebAssembly::FP_TO_SINT_I64_F32:
519     return LowerFPToInt(MI, DL, BB, TII, false, true, false,
520                         WebAssembly::I64_TRUNC_S_F32);
521   case WebAssembly::FP_TO_UINT_I64_F32:
522     return LowerFPToInt(MI, DL, BB, TII, true, true, false,
523                         WebAssembly::I64_TRUNC_U_F32);
524   case WebAssembly::FP_TO_SINT_I32_F64:
525     return LowerFPToInt(MI, DL, BB, TII, false, false, true,
526                         WebAssembly::I32_TRUNC_S_F64);
527   case WebAssembly::FP_TO_UINT_I32_F64:
528     return LowerFPToInt(MI, DL, BB, TII, true, false, true,
529                         WebAssembly::I32_TRUNC_U_F64);
530   case WebAssembly::FP_TO_SINT_I64_F64:
531     return LowerFPToInt(MI, DL, BB, TII, false, true, true,
532                         WebAssembly::I64_TRUNC_S_F64);
533   case WebAssembly::FP_TO_UINT_I64_F64:
534     return LowerFPToInt(MI, DL, BB, TII, true, true, true,
535                         WebAssembly::I64_TRUNC_U_F64);
536   case WebAssembly::CALL_RESULTS:
537   case WebAssembly::RET_CALL_RESULTS:
538     return LowerCallResults(MI, DL, BB, TII);
539   }
540 }
541 
542 const char *
543 WebAssemblyTargetLowering::getTargetNodeName(unsigned Opcode) const {
544   switch (static_cast<WebAssemblyISD::NodeType>(Opcode)) {
545   case WebAssemblyISD::FIRST_NUMBER:
546   case WebAssemblyISD::FIRST_MEM_OPCODE:
547     break;
548 #define HANDLE_NODETYPE(NODE)                                                  \
549   case WebAssemblyISD::NODE:                                                   \
550     return "WebAssemblyISD::" #NODE;
551 #define HANDLE_MEM_NODETYPE(NODE) HANDLE_NODETYPE(NODE)
552 #include "WebAssemblyISD.def"
553 #undef HANDLE_MEM_NODETYPE
554 #undef HANDLE_NODETYPE
555   }
556   return nullptr;
557 }
558 
559 std::pair<unsigned, const TargetRegisterClass *>
560 WebAssemblyTargetLowering::getRegForInlineAsmConstraint(
561     const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
562   // First, see if this is a constraint that directly corresponds to a
563   // WebAssembly register class.
564   if (Constraint.size() == 1) {
565     switch (Constraint[0]) {
566     case 'r':
567       assert(VT != MVT::iPTR && "Pointer MVT not expected here");
568       if (Subtarget->hasSIMD128() && VT.isVector()) {
569         if (VT.getSizeInBits() == 128)
570           return std::make_pair(0U, &WebAssembly::V128RegClass);
571       }
572       if (VT.isInteger() && !VT.isVector()) {
573         if (VT.getSizeInBits() <= 32)
574           return std::make_pair(0U, &WebAssembly::I32RegClass);
575         if (VT.getSizeInBits() <= 64)
576           return std::make_pair(0U, &WebAssembly::I64RegClass);
577       }
578       if (VT.isFloatingPoint() && !VT.isVector()) {
579         switch (VT.getSizeInBits()) {
580         case 32:
581           return std::make_pair(0U, &WebAssembly::F32RegClass);
582         case 64:
583           return std::make_pair(0U, &WebAssembly::F64RegClass);
584         default:
585           break;
586         }
587       }
588       break;
589     default:
590       break;
591     }
592   }
593 
594   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
595 }
596 
597 bool WebAssemblyTargetLowering::isCheapToSpeculateCttz() const {
598   // Assume ctz is a relatively cheap operation.
599   return true;
600 }
601 
602 bool WebAssemblyTargetLowering::isCheapToSpeculateCtlz() const {
603   // Assume clz is a relatively cheap operation.
604   return true;
605 }
606 
607 bool WebAssemblyTargetLowering::isLegalAddressingMode(const DataLayout &DL,
608                                                       const AddrMode &AM,
609                                                       Type *Ty, unsigned AS,
610                                                       Instruction *I) const {
611   // WebAssembly offsets are added as unsigned without wrapping. The
612   // isLegalAddressingMode gives us no way to determine if wrapping could be
613   // happening, so we approximate this by accepting only non-negative offsets.
614   if (AM.BaseOffs < 0)
615     return false;
616 
617   // WebAssembly has no scale register operands.
618   if (AM.Scale != 0)
619     return false;
620 
621   // Everything else is legal.
622   return true;
623 }
624 
625 bool WebAssemblyTargetLowering::allowsMisalignedMemoryAccesses(
626     EVT /*VT*/, unsigned /*AddrSpace*/, Align /*Align*/,
627     MachineMemOperand::Flags /*Flags*/, bool *Fast) const {
628   // WebAssembly supports unaligned accesses, though it should be declared
629   // with the p2align attribute on loads and stores which do so, and there
630   // may be a performance impact. We tell LLVM they're "fast" because
631   // for the kinds of things that LLVM uses this for (merging adjacent stores
632   // of constants, etc.), WebAssembly implementations will either want the
633   // unaligned access or they'll split anyway.
634   if (Fast)
635     *Fast = true;
636   return true;
637 }
638 
639 bool WebAssemblyTargetLowering::isIntDivCheap(EVT VT,
640                                               AttributeList Attr) const {
641   // The current thinking is that wasm engines will perform this optimization,
642   // so we can save on code size.
643   return true;
644 }
645 
646 bool WebAssemblyTargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const {
647   EVT ExtT = ExtVal.getValueType();
648   EVT MemT = cast<LoadSDNode>(ExtVal->getOperand(0))->getValueType(0);
649   return (ExtT == MVT::v8i16 && MemT == MVT::v8i8) ||
650          (ExtT == MVT::v4i32 && MemT == MVT::v4i16) ||
651          (ExtT == MVT::v2i64 && MemT == MVT::v2i32);
652 }
653 
654 EVT WebAssemblyTargetLowering::getSetCCResultType(const DataLayout &DL,
655                                                   LLVMContext &C,
656                                                   EVT VT) const {
657   if (VT.isVector())
658     return VT.changeVectorElementTypeToInteger();
659 
660   // So far, all branch instructions in Wasm take an I32 condition.
661   // The default TargetLowering::getSetCCResultType returns the pointer size,
662   // which would be useful to reduce instruction counts when testing
663   // against 64-bit pointers/values if at some point Wasm supports that.
664   return EVT::getIntegerVT(C, 32);
665 }
666 
667 bool WebAssemblyTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
668                                                    const CallInst &I,
669                                                    MachineFunction &MF,
670                                                    unsigned Intrinsic) const {
671   switch (Intrinsic) {
672   case Intrinsic::wasm_memory_atomic_notify:
673     Info.opc = ISD::INTRINSIC_W_CHAIN;
674     Info.memVT = MVT::i32;
675     Info.ptrVal = I.getArgOperand(0);
676     Info.offset = 0;
677     Info.align = Align(4);
678     // atomic.notify instruction does not really load the memory specified with
679     // this argument, but MachineMemOperand should either be load or store, so
680     // we set this to a load.
681     // FIXME Volatile isn't really correct, but currently all LLVM atomic
682     // instructions are treated as volatiles in the backend, so we should be
683     // consistent. The same applies for wasm_atomic_wait intrinsics too.
684     Info.flags = MachineMemOperand::MOVolatile | MachineMemOperand::MOLoad;
685     return true;
686   case Intrinsic::wasm_memory_atomic_wait32:
687     Info.opc = ISD::INTRINSIC_W_CHAIN;
688     Info.memVT = MVT::i32;
689     Info.ptrVal = I.getArgOperand(0);
690     Info.offset = 0;
691     Info.align = Align(4);
692     Info.flags = MachineMemOperand::MOVolatile | MachineMemOperand::MOLoad;
693     return true;
694   case Intrinsic::wasm_memory_atomic_wait64:
695     Info.opc = ISD::INTRINSIC_W_CHAIN;
696     Info.memVT = MVT::i64;
697     Info.ptrVal = I.getArgOperand(0);
698     Info.offset = 0;
699     Info.align = Align(8);
700     Info.flags = MachineMemOperand::MOVolatile | MachineMemOperand::MOLoad;
701     return true;
702   case Intrinsic::wasm_load32_zero:
703   case Intrinsic::wasm_load64_zero:
704     Info.opc = ISD::INTRINSIC_W_CHAIN;
705     Info.memVT = Intrinsic == Intrinsic::wasm_load32_zero ? MVT::i32 : MVT::i64;
706     Info.ptrVal = I.getArgOperand(0);
707     Info.offset = 0;
708     Info.align = Info.memVT == MVT::i32 ? Align(4) : Align(8);
709     Info.flags = MachineMemOperand::MOLoad;
710     return true;
711   case Intrinsic::wasm_load8_lane:
712   case Intrinsic::wasm_load16_lane:
713   case Intrinsic::wasm_load32_lane:
714   case Intrinsic::wasm_load64_lane:
715   case Intrinsic::wasm_store8_lane:
716   case Intrinsic::wasm_store16_lane:
717   case Intrinsic::wasm_store32_lane:
718   case Intrinsic::wasm_store64_lane: {
719     MVT MemVT;
720     Align MemAlign;
721     switch (Intrinsic) {
722     case Intrinsic::wasm_load8_lane:
723     case Intrinsic::wasm_store8_lane:
724       MemVT = MVT::i8;
725       MemAlign = Align(1);
726       break;
727     case Intrinsic::wasm_load16_lane:
728     case Intrinsic::wasm_store16_lane:
729       MemVT = MVT::i16;
730       MemAlign = Align(2);
731       break;
732     case Intrinsic::wasm_load32_lane:
733     case Intrinsic::wasm_store32_lane:
734       MemVT = MVT::i32;
735       MemAlign = Align(4);
736       break;
737     case Intrinsic::wasm_load64_lane:
738     case Intrinsic::wasm_store64_lane:
739       MemVT = MVT::i64;
740       MemAlign = Align(8);
741       break;
742     default:
743       llvm_unreachable("unexpected intrinsic");
744     }
745     if (Intrinsic == Intrinsic::wasm_load8_lane ||
746         Intrinsic == Intrinsic::wasm_load16_lane ||
747         Intrinsic == Intrinsic::wasm_load32_lane ||
748         Intrinsic == Intrinsic::wasm_load64_lane) {
749       Info.opc = ISD::INTRINSIC_W_CHAIN;
750       Info.flags = MachineMemOperand::MOLoad;
751     } else {
752       Info.opc = ISD::INTRINSIC_VOID;
753       Info.flags = MachineMemOperand::MOStore;
754     }
755     Info.ptrVal = I.getArgOperand(0);
756     Info.memVT = MemVT;
757     Info.offset = 0;
758     Info.align = MemAlign;
759     return true;
760   }
761   case Intrinsic::wasm_prefetch_t:
762   case Intrinsic::wasm_prefetch_nt: {
763     Info.opc = ISD::INTRINSIC_VOID;
764     Info.memVT = MVT::i8;
765     Info.ptrVal = I.getArgOperand(0);
766     Info.offset = 0;
767     Info.align = Align(1);
768     Info.flags = MachineMemOperand::MOLoad;
769     return true;
770   }
771   default:
772     return false;
773   }
774 }
775 
776 //===----------------------------------------------------------------------===//
777 // WebAssembly Lowering private implementation.
778 //===----------------------------------------------------------------------===//
779 
780 //===----------------------------------------------------------------------===//
781 // Lowering Code
782 //===----------------------------------------------------------------------===//
783 
784 static void fail(const SDLoc &DL, SelectionDAG &DAG, const char *Msg) {
785   MachineFunction &MF = DAG.getMachineFunction();
786   DAG.getContext()->diagnose(
787       DiagnosticInfoUnsupported(MF.getFunction(), Msg, DL.getDebugLoc()));
788 }
789 
790 // Test whether the given calling convention is supported.
791 static bool callingConvSupported(CallingConv::ID CallConv) {
792   // We currently support the language-independent target-independent
793   // conventions. We don't yet have a way to annotate calls with properties like
794   // "cold", and we don't have any call-clobbered registers, so these are mostly
795   // all handled the same.
796   return CallConv == CallingConv::C || CallConv == CallingConv::Fast ||
797          CallConv == CallingConv::Cold ||
798          CallConv == CallingConv::PreserveMost ||
799          CallConv == CallingConv::PreserveAll ||
800          CallConv == CallingConv::CXX_FAST_TLS ||
801          CallConv == CallingConv::WASM_EmscriptenInvoke ||
802          CallConv == CallingConv::Swift;
803 }
804 
805 SDValue
806 WebAssemblyTargetLowering::LowerCall(CallLoweringInfo &CLI,
807                                      SmallVectorImpl<SDValue> &InVals) const {
808   SelectionDAG &DAG = CLI.DAG;
809   SDLoc DL = CLI.DL;
810   SDValue Chain = CLI.Chain;
811   SDValue Callee = CLI.Callee;
812   MachineFunction &MF = DAG.getMachineFunction();
813   auto Layout = MF.getDataLayout();
814 
815   CallingConv::ID CallConv = CLI.CallConv;
816   if (!callingConvSupported(CallConv))
817     fail(DL, DAG,
818          "WebAssembly doesn't support language-specific or target-specific "
819          "calling conventions yet");
820   if (CLI.IsPatchPoint)
821     fail(DL, DAG, "WebAssembly doesn't support patch point yet");
822 
823   if (CLI.IsTailCall) {
824     auto NoTail = [&](const char *Msg) {
825       if (CLI.CB && CLI.CB->isMustTailCall())
826         fail(DL, DAG, Msg);
827       CLI.IsTailCall = false;
828     };
829 
830     if (!Subtarget->hasTailCall())
831       NoTail("WebAssembly 'tail-call' feature not enabled");
832 
833     // Varargs calls cannot be tail calls because the buffer is on the stack
834     if (CLI.IsVarArg)
835       NoTail("WebAssembly does not support varargs tail calls");
836 
837     // Do not tail call unless caller and callee return types match
838     const Function &F = MF.getFunction();
839     const TargetMachine &TM = getTargetMachine();
840     Type *RetTy = F.getReturnType();
841     SmallVector<MVT, 4> CallerRetTys;
842     SmallVector<MVT, 4> CalleeRetTys;
843     computeLegalValueVTs(F, TM, RetTy, CallerRetTys);
844     computeLegalValueVTs(F, TM, CLI.RetTy, CalleeRetTys);
845     bool TypesMatch = CallerRetTys.size() == CalleeRetTys.size() &&
846                       std::equal(CallerRetTys.begin(), CallerRetTys.end(),
847                                  CalleeRetTys.begin());
848     if (!TypesMatch)
849       NoTail("WebAssembly tail call requires caller and callee return types to "
850              "match");
851 
852     // If pointers to local stack values are passed, we cannot tail call
853     if (CLI.CB) {
854       for (auto &Arg : CLI.CB->args()) {
855         Value *Val = Arg.get();
856         // Trace the value back through pointer operations
857         while (true) {
858           Value *Src = Val->stripPointerCastsAndAliases();
859           if (auto *GEP = dyn_cast<GetElementPtrInst>(Src))
860             Src = GEP->getPointerOperand();
861           if (Val == Src)
862             break;
863           Val = Src;
864         }
865         if (isa<AllocaInst>(Val)) {
866           NoTail(
867               "WebAssembly does not support tail calling with stack arguments");
868           break;
869         }
870       }
871     }
872   }
873 
874   SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
875   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
876   SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
877 
878   // The generic code may have added an sret argument. If we're lowering an
879   // invoke function, the ABI requires that the function pointer be the first
880   // argument, so we may have to swap the arguments.
881   if (CallConv == CallingConv::WASM_EmscriptenInvoke && Outs.size() >= 2 &&
882       Outs[0].Flags.isSRet()) {
883     std::swap(Outs[0], Outs[1]);
884     std::swap(OutVals[0], OutVals[1]);
885   }
886 
887   bool HasSwiftSelfArg = false;
888   bool HasSwiftErrorArg = false;
889   unsigned NumFixedArgs = 0;
890   for (unsigned I = 0; I < Outs.size(); ++I) {
891     const ISD::OutputArg &Out = Outs[I];
892     SDValue &OutVal = OutVals[I];
893     HasSwiftSelfArg |= Out.Flags.isSwiftSelf();
894     HasSwiftErrorArg |= Out.Flags.isSwiftError();
895     if (Out.Flags.isNest())
896       fail(DL, DAG, "WebAssembly hasn't implemented nest arguments");
897     if (Out.Flags.isInAlloca())
898       fail(DL, DAG, "WebAssembly hasn't implemented inalloca arguments");
899     if (Out.Flags.isInConsecutiveRegs())
900       fail(DL, DAG, "WebAssembly hasn't implemented cons regs arguments");
901     if (Out.Flags.isInConsecutiveRegsLast())
902       fail(DL, DAG, "WebAssembly hasn't implemented cons regs last arguments");
903     if (Out.Flags.isByVal() && Out.Flags.getByValSize() != 0) {
904       auto &MFI = MF.getFrameInfo();
905       int FI = MFI.CreateStackObject(Out.Flags.getByValSize(),
906                                      Out.Flags.getNonZeroByValAlign(),
907                                      /*isSS=*/false);
908       SDValue SizeNode =
909           DAG.getConstant(Out.Flags.getByValSize(), DL, MVT::i32);
910       SDValue FINode = DAG.getFrameIndex(FI, getPointerTy(Layout));
911       Chain = DAG.getMemcpy(
912           Chain, DL, FINode, OutVal, SizeNode, Out.Flags.getNonZeroByValAlign(),
913           /*isVolatile*/ false, /*AlwaysInline=*/false,
914           /*isTailCall*/ false, MachinePointerInfo(), MachinePointerInfo());
915       OutVal = FINode;
916     }
917     // Count the number of fixed args *after* legalization.
918     NumFixedArgs += Out.IsFixed;
919   }
920 
921   bool IsVarArg = CLI.IsVarArg;
922   auto PtrVT = getPointerTy(Layout);
923 
924   // For swiftcc, emit additional swiftself and swifterror arguments
925   // if there aren't. These additional arguments are also added for callee
926   // signature They are necessary to match callee and caller signature for
927   // indirect call.
928   if (CallConv == CallingConv::Swift) {
929     if (!HasSwiftSelfArg) {
930       NumFixedArgs++;
931       ISD::OutputArg Arg;
932       Arg.Flags.setSwiftSelf();
933       CLI.Outs.push_back(Arg);
934       SDValue ArgVal = DAG.getUNDEF(PtrVT);
935       CLI.OutVals.push_back(ArgVal);
936     }
937     if (!HasSwiftErrorArg) {
938       NumFixedArgs++;
939       ISD::OutputArg Arg;
940       Arg.Flags.setSwiftError();
941       CLI.Outs.push_back(Arg);
942       SDValue ArgVal = DAG.getUNDEF(PtrVT);
943       CLI.OutVals.push_back(ArgVal);
944     }
945   }
946 
947   // Analyze operands of the call, assigning locations to each operand.
948   SmallVector<CCValAssign, 16> ArgLocs;
949   CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
950 
951   if (IsVarArg) {
952     // Outgoing non-fixed arguments are placed in a buffer. First
953     // compute their offsets and the total amount of buffer space needed.
954     for (unsigned I = NumFixedArgs; I < Outs.size(); ++I) {
955       const ISD::OutputArg &Out = Outs[I];
956       SDValue &Arg = OutVals[I];
957       EVT VT = Arg.getValueType();
958       assert(VT != MVT::iPTR && "Legalized args should be concrete");
959       Type *Ty = VT.getTypeForEVT(*DAG.getContext());
960       Align Alignment =
961           std::max(Out.Flags.getNonZeroOrigAlign(), Layout.getABITypeAlign(Ty));
962       unsigned Offset =
963           CCInfo.AllocateStack(Layout.getTypeAllocSize(Ty), Alignment);
964       CCInfo.addLoc(CCValAssign::getMem(ArgLocs.size(), VT.getSimpleVT(),
965                                         Offset, VT.getSimpleVT(),
966                                         CCValAssign::Full));
967     }
968   }
969 
970   unsigned NumBytes = CCInfo.getAlignedCallFrameSize();
971 
972   SDValue FINode;
973   if (IsVarArg && NumBytes) {
974     // For non-fixed arguments, next emit stores to store the argument values
975     // to the stack buffer at the offsets computed above.
976     int FI = MF.getFrameInfo().CreateStackObject(NumBytes,
977                                                  Layout.getStackAlignment(),
978                                                  /*isSS=*/false);
979     unsigned ValNo = 0;
980     SmallVector<SDValue, 8> Chains;
981     for (SDValue Arg : drop_begin(OutVals, NumFixedArgs)) {
982       assert(ArgLocs[ValNo].getValNo() == ValNo &&
983              "ArgLocs should remain in order and only hold varargs args");
984       unsigned Offset = ArgLocs[ValNo++].getLocMemOffset();
985       FINode = DAG.getFrameIndex(FI, getPointerTy(Layout));
986       SDValue Add = DAG.getNode(ISD::ADD, DL, PtrVT, FINode,
987                                 DAG.getConstant(Offset, DL, PtrVT));
988       Chains.push_back(
989           DAG.getStore(Chain, DL, Arg, Add,
990                        MachinePointerInfo::getFixedStack(MF, FI, Offset)));
991     }
992     if (!Chains.empty())
993       Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
994   } else if (IsVarArg) {
995     FINode = DAG.getIntPtrConstant(0, DL);
996   }
997 
998   if (Callee->getOpcode() == ISD::GlobalAddress) {
999     // If the callee is a GlobalAddress node (quite common, every direct call
1000     // is) turn it into a TargetGlobalAddress node so that LowerGlobalAddress
1001     // doesn't at MO_GOT which is not needed for direct calls.
1002     GlobalAddressSDNode* GA = cast<GlobalAddressSDNode>(Callee);
1003     Callee = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
1004                                         getPointerTy(DAG.getDataLayout()),
1005                                         GA->getOffset());
1006     Callee = DAG.getNode(WebAssemblyISD::Wrapper, DL,
1007                          getPointerTy(DAG.getDataLayout()), Callee);
1008   }
1009 
1010   // Compute the operands for the CALLn node.
1011   SmallVector<SDValue, 16> Ops;
1012   Ops.push_back(Chain);
1013   Ops.push_back(Callee);
1014 
1015   // Add all fixed arguments. Note that for non-varargs calls, NumFixedArgs
1016   // isn't reliable.
1017   Ops.append(OutVals.begin(),
1018              IsVarArg ? OutVals.begin() + NumFixedArgs : OutVals.end());
1019   // Add a pointer to the vararg buffer.
1020   if (IsVarArg)
1021     Ops.push_back(FINode);
1022 
1023   SmallVector<EVT, 8> InTys;
1024   for (const auto &In : Ins) {
1025     assert(!In.Flags.isByVal() && "byval is not valid for return values");
1026     assert(!In.Flags.isNest() && "nest is not valid for return values");
1027     if (In.Flags.isInAlloca())
1028       fail(DL, DAG, "WebAssembly hasn't implemented inalloca return values");
1029     if (In.Flags.isInConsecutiveRegs())
1030       fail(DL, DAG, "WebAssembly hasn't implemented cons regs return values");
1031     if (In.Flags.isInConsecutiveRegsLast())
1032       fail(DL, DAG,
1033            "WebAssembly hasn't implemented cons regs last return values");
1034     // Ignore In.getNonZeroOrigAlign() because all our arguments are passed in
1035     // registers.
1036     InTys.push_back(In.VT);
1037   }
1038 
1039   if (CLI.IsTailCall) {
1040     // ret_calls do not return values to the current frame
1041     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1042     return DAG.getNode(WebAssemblyISD::RET_CALL, DL, NodeTys, Ops);
1043   }
1044 
1045   InTys.push_back(MVT::Other);
1046   SDVTList InTyList = DAG.getVTList(InTys);
1047   SDValue Res = DAG.getNode(WebAssemblyISD::CALL, DL, InTyList, Ops);
1048 
1049   for (size_t I = 0; I < Ins.size(); ++I)
1050     InVals.push_back(Res.getValue(I));
1051 
1052   // Return the chain
1053   return Res.getValue(Ins.size());
1054 }
1055 
1056 bool WebAssemblyTargetLowering::CanLowerReturn(
1057     CallingConv::ID /*CallConv*/, MachineFunction & /*MF*/, bool /*IsVarArg*/,
1058     const SmallVectorImpl<ISD::OutputArg> &Outs,
1059     LLVMContext & /*Context*/) const {
1060   // WebAssembly can only handle returning tuples with multivalue enabled
1061   return Subtarget->hasMultivalue() || Outs.size() <= 1;
1062 }
1063 
1064 SDValue WebAssemblyTargetLowering::LowerReturn(
1065     SDValue Chain, CallingConv::ID CallConv, bool /*IsVarArg*/,
1066     const SmallVectorImpl<ISD::OutputArg> &Outs,
1067     const SmallVectorImpl<SDValue> &OutVals, const SDLoc &DL,
1068     SelectionDAG &DAG) const {
1069   assert((Subtarget->hasMultivalue() || Outs.size() <= 1) &&
1070          "MVP WebAssembly can only return up to one value");
1071   if (!callingConvSupported(CallConv))
1072     fail(DL, DAG, "WebAssembly doesn't support non-C calling conventions");
1073 
1074   SmallVector<SDValue, 4> RetOps(1, Chain);
1075   RetOps.append(OutVals.begin(), OutVals.end());
1076   Chain = DAG.getNode(WebAssemblyISD::RETURN, DL, MVT::Other, RetOps);
1077 
1078   // Record the number and types of the return values.
1079   for (const ISD::OutputArg &Out : Outs) {
1080     assert(!Out.Flags.isByVal() && "byval is not valid for return values");
1081     assert(!Out.Flags.isNest() && "nest is not valid for return values");
1082     assert(Out.IsFixed && "non-fixed return value is not valid");
1083     if (Out.Flags.isInAlloca())
1084       fail(DL, DAG, "WebAssembly hasn't implemented inalloca results");
1085     if (Out.Flags.isInConsecutiveRegs())
1086       fail(DL, DAG, "WebAssembly hasn't implemented cons regs results");
1087     if (Out.Flags.isInConsecutiveRegsLast())
1088       fail(DL, DAG, "WebAssembly hasn't implemented cons regs last results");
1089   }
1090 
1091   return Chain;
1092 }
1093 
1094 SDValue WebAssemblyTargetLowering::LowerFormalArguments(
1095     SDValue Chain, CallingConv::ID CallConv, bool IsVarArg,
1096     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
1097     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
1098   if (!callingConvSupported(CallConv))
1099     fail(DL, DAG, "WebAssembly doesn't support non-C calling conventions");
1100 
1101   MachineFunction &MF = DAG.getMachineFunction();
1102   auto *MFI = MF.getInfo<WebAssemblyFunctionInfo>();
1103 
1104   // Set up the incoming ARGUMENTS value, which serves to represent the liveness
1105   // of the incoming values before they're represented by virtual registers.
1106   MF.getRegInfo().addLiveIn(WebAssembly::ARGUMENTS);
1107 
1108   bool HasSwiftErrorArg = false;
1109   bool HasSwiftSelfArg = false;
1110   for (const ISD::InputArg &In : Ins) {
1111     HasSwiftSelfArg |= In.Flags.isSwiftSelf();
1112     HasSwiftErrorArg |= In.Flags.isSwiftError();
1113     if (In.Flags.isInAlloca())
1114       fail(DL, DAG, "WebAssembly hasn't implemented inalloca arguments");
1115     if (In.Flags.isNest())
1116       fail(DL, DAG, "WebAssembly hasn't implemented nest arguments");
1117     if (In.Flags.isInConsecutiveRegs())
1118       fail(DL, DAG, "WebAssembly hasn't implemented cons regs arguments");
1119     if (In.Flags.isInConsecutiveRegsLast())
1120       fail(DL, DAG, "WebAssembly hasn't implemented cons regs last arguments");
1121     // Ignore In.getNonZeroOrigAlign() because all our arguments are passed in
1122     // registers.
1123     InVals.push_back(In.Used ? DAG.getNode(WebAssemblyISD::ARGUMENT, DL, In.VT,
1124                                            DAG.getTargetConstant(InVals.size(),
1125                                                                  DL, MVT::i32))
1126                              : DAG.getUNDEF(In.VT));
1127 
1128     // Record the number and types of arguments.
1129     MFI->addParam(In.VT);
1130   }
1131 
1132   // For swiftcc, emit additional swiftself and swifterror arguments
1133   // if there aren't. These additional arguments are also added for callee
1134   // signature They are necessary to match callee and caller signature for
1135   // indirect call.
1136   auto PtrVT = getPointerTy(MF.getDataLayout());
1137   if (CallConv == CallingConv::Swift) {
1138     if (!HasSwiftSelfArg) {
1139       MFI->addParam(PtrVT);
1140     }
1141     if (!HasSwiftErrorArg) {
1142       MFI->addParam(PtrVT);
1143     }
1144   }
1145   // Varargs are copied into a buffer allocated by the caller, and a pointer to
1146   // the buffer is passed as an argument.
1147   if (IsVarArg) {
1148     MVT PtrVT = getPointerTy(MF.getDataLayout());
1149     Register VarargVreg =
1150         MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrVT));
1151     MFI->setVarargBufferVreg(VarargVreg);
1152     Chain = DAG.getCopyToReg(
1153         Chain, DL, VarargVreg,
1154         DAG.getNode(WebAssemblyISD::ARGUMENT, DL, PtrVT,
1155                     DAG.getTargetConstant(Ins.size(), DL, MVT::i32)));
1156     MFI->addParam(PtrVT);
1157   }
1158 
1159   // Record the number and types of arguments and results.
1160   SmallVector<MVT, 4> Params;
1161   SmallVector<MVT, 4> Results;
1162   computeSignatureVTs(MF.getFunction().getFunctionType(), &MF.getFunction(),
1163                       MF.getFunction(), DAG.getTarget(), Params, Results);
1164   for (MVT VT : Results)
1165     MFI->addResult(VT);
1166   // TODO: Use signatures in WebAssemblyMachineFunctionInfo too and unify
1167   // the param logic here with ComputeSignatureVTs
1168   assert(MFI->getParams().size() == Params.size() &&
1169          std::equal(MFI->getParams().begin(), MFI->getParams().end(),
1170                     Params.begin()));
1171 
1172   return Chain;
1173 }
1174 
1175 void WebAssemblyTargetLowering::ReplaceNodeResults(
1176     SDNode *N, SmallVectorImpl<SDValue> &Results, SelectionDAG &DAG) const {
1177   switch (N->getOpcode()) {
1178   case ISD::SIGN_EXTEND_INREG:
1179     // Do not add any results, signifying that N should not be custom lowered
1180     // after all. This happens because simd128 turns on custom lowering for
1181     // SIGN_EXTEND_INREG, but for non-vector sign extends the result might be an
1182     // illegal type.
1183     break;
1184   default:
1185     llvm_unreachable(
1186         "ReplaceNodeResults not implemented for this op for WebAssembly!");
1187   }
1188 }
1189 
1190 //===----------------------------------------------------------------------===//
1191 //  Custom lowering hooks.
1192 //===----------------------------------------------------------------------===//
1193 
1194 SDValue WebAssemblyTargetLowering::LowerOperation(SDValue Op,
1195                                                   SelectionDAG &DAG) const {
1196   SDLoc DL(Op);
1197   switch (Op.getOpcode()) {
1198   default:
1199     llvm_unreachable("unimplemented operation lowering");
1200     return SDValue();
1201   case ISD::FrameIndex:
1202     return LowerFrameIndex(Op, DAG);
1203   case ISD::GlobalAddress:
1204     return LowerGlobalAddress(Op, DAG);
1205   case ISD::GlobalTLSAddress:
1206     return LowerGlobalTLSAddress(Op, DAG);
1207   case ISD::ExternalSymbol:
1208     return LowerExternalSymbol(Op, DAG);
1209   case ISD::JumpTable:
1210     return LowerJumpTable(Op, DAG);
1211   case ISD::BR_JT:
1212     return LowerBR_JT(Op, DAG);
1213   case ISD::VASTART:
1214     return LowerVASTART(Op, DAG);
1215   case ISD::BlockAddress:
1216   case ISD::BRIND:
1217     fail(DL, DAG, "WebAssembly hasn't implemented computed gotos");
1218     return SDValue();
1219   case ISD::RETURNADDR:
1220     return LowerRETURNADDR(Op, DAG);
1221   case ISD::FRAMEADDR:
1222     return LowerFRAMEADDR(Op, DAG);
1223   case ISD::CopyToReg:
1224     return LowerCopyToReg(Op, DAG);
1225   case ISD::EXTRACT_VECTOR_ELT:
1226   case ISD::INSERT_VECTOR_ELT:
1227     return LowerAccessVectorElement(Op, DAG);
1228   case ISD::INTRINSIC_VOID:
1229   case ISD::INTRINSIC_WO_CHAIN:
1230   case ISD::INTRINSIC_W_CHAIN:
1231     return LowerIntrinsic(Op, DAG);
1232   case ISD::SIGN_EXTEND_INREG:
1233     return LowerSIGN_EXTEND_INREG(Op, DAG);
1234   case ISD::BUILD_VECTOR:
1235     return LowerBUILD_VECTOR(Op, DAG);
1236   case ISD::VECTOR_SHUFFLE:
1237     return LowerVECTOR_SHUFFLE(Op, DAG);
1238   case ISD::SETCC:
1239     return LowerSETCC(Op, DAG);
1240   case ISD::SHL:
1241   case ISD::SRA:
1242   case ISD::SRL:
1243     return LowerShift(Op, DAG);
1244   }
1245 }
1246 
1247 SDValue WebAssemblyTargetLowering::LowerCopyToReg(SDValue Op,
1248                                                   SelectionDAG &DAG) const {
1249   SDValue Src = Op.getOperand(2);
1250   if (isa<FrameIndexSDNode>(Src.getNode())) {
1251     // CopyToReg nodes don't support FrameIndex operands. Other targets select
1252     // the FI to some LEA-like instruction, but since we don't have that, we
1253     // need to insert some kind of instruction that can take an FI operand and
1254     // produces a value usable by CopyToReg (i.e. in a vreg). So insert a dummy
1255     // local.copy between Op and its FI operand.
1256     SDValue Chain = Op.getOperand(0);
1257     SDLoc DL(Op);
1258     unsigned Reg = cast<RegisterSDNode>(Op.getOperand(1))->getReg();
1259     EVT VT = Src.getValueType();
1260     SDValue Copy(DAG.getMachineNode(VT == MVT::i32 ? WebAssembly::COPY_I32
1261                                                    : WebAssembly::COPY_I64,
1262                                     DL, VT, Src),
1263                  0);
1264     return Op.getNode()->getNumValues() == 1
1265                ? DAG.getCopyToReg(Chain, DL, Reg, Copy)
1266                : DAG.getCopyToReg(Chain, DL, Reg, Copy,
1267                                   Op.getNumOperands() == 4 ? Op.getOperand(3)
1268                                                            : SDValue());
1269   }
1270   return SDValue();
1271 }
1272 
1273 SDValue WebAssemblyTargetLowering::LowerFrameIndex(SDValue Op,
1274                                                    SelectionDAG &DAG) const {
1275   int FI = cast<FrameIndexSDNode>(Op)->getIndex();
1276   return DAG.getTargetFrameIndex(FI, Op.getValueType());
1277 }
1278 
1279 SDValue WebAssemblyTargetLowering::LowerRETURNADDR(SDValue Op,
1280                                                    SelectionDAG &DAG) const {
1281   SDLoc DL(Op);
1282 
1283   if (!Subtarget->getTargetTriple().isOSEmscripten()) {
1284     fail(DL, DAG,
1285          "Non-Emscripten WebAssembly hasn't implemented "
1286          "__builtin_return_address");
1287     return SDValue();
1288   }
1289 
1290   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
1291     return SDValue();
1292 
1293   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
1294   MakeLibCallOptions CallOptions;
1295   return makeLibCall(DAG, RTLIB::RETURN_ADDRESS, Op.getValueType(),
1296                      {DAG.getConstant(Depth, DL, MVT::i32)}, CallOptions, DL)
1297       .first;
1298 }
1299 
1300 SDValue WebAssemblyTargetLowering::LowerFRAMEADDR(SDValue Op,
1301                                                   SelectionDAG &DAG) const {
1302   // Non-zero depths are not supported by WebAssembly currently. Use the
1303   // legalizer's default expansion, which is to return 0 (what this function is
1304   // documented to do).
1305   if (Op.getConstantOperandVal(0) > 0)
1306     return SDValue();
1307 
1308   DAG.getMachineFunction().getFrameInfo().setFrameAddressIsTaken(true);
1309   EVT VT = Op.getValueType();
1310   Register FP =
1311       Subtarget->getRegisterInfo()->getFrameRegister(DAG.getMachineFunction());
1312   return DAG.getCopyFromReg(DAG.getEntryNode(), SDLoc(Op), FP, VT);
1313 }
1314 
1315 SDValue
1316 WebAssemblyTargetLowering::LowerGlobalTLSAddress(SDValue Op,
1317                                                  SelectionDAG &DAG) const {
1318   SDLoc DL(Op);
1319   const auto *GA = cast<GlobalAddressSDNode>(Op);
1320   MVT PtrVT = getPointerTy(DAG.getDataLayout());
1321 
1322   MachineFunction &MF = DAG.getMachineFunction();
1323   if (!MF.getSubtarget<WebAssemblySubtarget>().hasBulkMemory())
1324     report_fatal_error("cannot use thread-local storage without bulk memory",
1325                        false);
1326 
1327   const GlobalValue *GV = GA->getGlobal();
1328 
1329   // Currently Emscripten does not support dynamic linking with threads.
1330   // Therefore, if we have thread-local storage, only the local-exec model
1331   // is possible.
1332   // TODO: remove this and implement proper TLS models once Emscripten
1333   // supports dynamic linking with threads.
1334   if (GV->getThreadLocalMode() != GlobalValue::LocalExecTLSModel &&
1335       !Subtarget->getTargetTriple().isOSEmscripten()) {
1336     report_fatal_error("only -ftls-model=local-exec is supported for now on "
1337                        "non-Emscripten OSes: variable " +
1338                            GV->getName(),
1339                        false);
1340   }
1341 
1342   auto GlobalGet = PtrVT == MVT::i64 ? WebAssembly::GLOBAL_GET_I64
1343                                      : WebAssembly::GLOBAL_GET_I32;
1344   const char *BaseName = MF.createExternalSymbolName("__tls_base");
1345 
1346   SDValue BaseAddr(
1347       DAG.getMachineNode(GlobalGet, DL, PtrVT,
1348                          DAG.getTargetExternalSymbol(BaseName, PtrVT)),
1349       0);
1350 
1351   SDValue TLSOffset = DAG.getTargetGlobalAddress(
1352       GV, DL, PtrVT, GA->getOffset(), WebAssemblyII::MO_TLS_BASE_REL);
1353   SDValue SymAddr = DAG.getNode(WebAssemblyISD::Wrapper, DL, PtrVT, TLSOffset);
1354 
1355   return DAG.getNode(ISD::ADD, DL, PtrVT, BaseAddr, SymAddr);
1356 }
1357 
1358 SDValue WebAssemblyTargetLowering::LowerGlobalAddress(SDValue Op,
1359                                                       SelectionDAG &DAG) const {
1360   SDLoc DL(Op);
1361   const auto *GA = cast<GlobalAddressSDNode>(Op);
1362   EVT VT = Op.getValueType();
1363   assert(GA->getTargetFlags() == 0 &&
1364          "Unexpected target flags on generic GlobalAddressSDNode");
1365   if (GA->getAddressSpace() != 0)
1366     fail(DL, DAG, "WebAssembly only expects the 0 address space");
1367 
1368   unsigned OperandFlags = 0;
1369   if (isPositionIndependent()) {
1370     const GlobalValue *GV = GA->getGlobal();
1371     if (getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV)) {
1372       MachineFunction &MF = DAG.getMachineFunction();
1373       MVT PtrVT = getPointerTy(MF.getDataLayout());
1374       const char *BaseName;
1375       if (GV->getValueType()->isFunctionTy()) {
1376         BaseName = MF.createExternalSymbolName("__table_base");
1377         OperandFlags = WebAssemblyII::MO_TABLE_BASE_REL;
1378       }
1379       else {
1380         BaseName = MF.createExternalSymbolName("__memory_base");
1381         OperandFlags = WebAssemblyII::MO_MEMORY_BASE_REL;
1382       }
1383       SDValue BaseAddr =
1384           DAG.getNode(WebAssemblyISD::Wrapper, DL, PtrVT,
1385                       DAG.getTargetExternalSymbol(BaseName, PtrVT));
1386 
1387       SDValue SymAddr = DAG.getNode(
1388           WebAssemblyISD::WrapperPIC, DL, VT,
1389           DAG.getTargetGlobalAddress(GA->getGlobal(), DL, VT, GA->getOffset(),
1390                                      OperandFlags));
1391 
1392       return DAG.getNode(ISD::ADD, DL, VT, BaseAddr, SymAddr);
1393     } else {
1394       OperandFlags = WebAssemblyII::MO_GOT;
1395     }
1396   }
1397 
1398   return DAG.getNode(WebAssemblyISD::Wrapper, DL, VT,
1399                      DAG.getTargetGlobalAddress(GA->getGlobal(), DL, VT,
1400                                                 GA->getOffset(), OperandFlags));
1401 }
1402 
1403 SDValue
1404 WebAssemblyTargetLowering::LowerExternalSymbol(SDValue Op,
1405                                                SelectionDAG &DAG) const {
1406   SDLoc DL(Op);
1407   const auto *ES = cast<ExternalSymbolSDNode>(Op);
1408   EVT VT = Op.getValueType();
1409   assert(ES->getTargetFlags() == 0 &&
1410          "Unexpected target flags on generic ExternalSymbolSDNode");
1411   return DAG.getNode(WebAssemblyISD::Wrapper, DL, VT,
1412                      DAG.getTargetExternalSymbol(ES->getSymbol(), VT));
1413 }
1414 
1415 SDValue WebAssemblyTargetLowering::LowerJumpTable(SDValue Op,
1416                                                   SelectionDAG &DAG) const {
1417   // There's no need for a Wrapper node because we always incorporate a jump
1418   // table operand into a BR_TABLE instruction, rather than ever
1419   // materializing it in a register.
1420   const JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
1421   return DAG.getTargetJumpTable(JT->getIndex(), Op.getValueType(),
1422                                 JT->getTargetFlags());
1423 }
1424 
1425 SDValue WebAssemblyTargetLowering::LowerBR_JT(SDValue Op,
1426                                               SelectionDAG &DAG) const {
1427   SDLoc DL(Op);
1428   SDValue Chain = Op.getOperand(0);
1429   const auto *JT = cast<JumpTableSDNode>(Op.getOperand(1));
1430   SDValue Index = Op.getOperand(2);
1431   assert(JT->getTargetFlags() == 0 && "WebAssembly doesn't set target flags");
1432 
1433   SmallVector<SDValue, 8> Ops;
1434   Ops.push_back(Chain);
1435   Ops.push_back(Index);
1436 
1437   MachineJumpTableInfo *MJTI = DAG.getMachineFunction().getJumpTableInfo();
1438   const auto &MBBs = MJTI->getJumpTables()[JT->getIndex()].MBBs;
1439 
1440   // Add an operand for each case.
1441   for (auto MBB : MBBs)
1442     Ops.push_back(DAG.getBasicBlock(MBB));
1443 
1444   // Add the first MBB as a dummy default target for now. This will be replaced
1445   // with the proper default target (and the preceding range check eliminated)
1446   // if possible by WebAssemblyFixBrTableDefaults.
1447   Ops.push_back(DAG.getBasicBlock(*MBBs.begin()));
1448   return DAG.getNode(WebAssemblyISD::BR_TABLE, DL, MVT::Other, Ops);
1449 }
1450 
1451 SDValue WebAssemblyTargetLowering::LowerVASTART(SDValue Op,
1452                                                 SelectionDAG &DAG) const {
1453   SDLoc DL(Op);
1454   EVT PtrVT = getPointerTy(DAG.getMachineFunction().getDataLayout());
1455 
1456   auto *MFI = DAG.getMachineFunction().getInfo<WebAssemblyFunctionInfo>();
1457   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
1458 
1459   SDValue ArgN = DAG.getCopyFromReg(DAG.getEntryNode(), DL,
1460                                     MFI->getVarargBufferVreg(), PtrVT);
1461   return DAG.getStore(Op.getOperand(0), DL, ArgN, Op.getOperand(1),
1462                       MachinePointerInfo(SV));
1463 }
1464 
1465 static SDValue getCppExceptionSymNode(SDValue Op, unsigned TagIndex,
1466                                       SelectionDAG &DAG) {
1467   // We only support C++ exceptions for now
1468   int Tag =
1469       cast<ConstantSDNode>(Op.getOperand(TagIndex).getNode())->getZExtValue();
1470   if (Tag != WebAssembly::CPP_EXCEPTION)
1471     llvm_unreachable("Invalid tag: We only support C++ exceptions for now");
1472   auto &MF = DAG.getMachineFunction();
1473   const auto &TLI = DAG.getTargetLoweringInfo();
1474   MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
1475   const char *SymName = MF.createExternalSymbolName("__cpp_exception");
1476   return DAG.getNode(WebAssemblyISD::Wrapper, SDLoc(Op), PtrVT,
1477                      DAG.getTargetExternalSymbol(SymName, PtrVT));
1478 }
1479 
1480 SDValue WebAssemblyTargetLowering::LowerIntrinsic(SDValue Op,
1481                                                   SelectionDAG &DAG) const {
1482   MachineFunction &MF = DAG.getMachineFunction();
1483   unsigned IntNo;
1484   switch (Op.getOpcode()) {
1485   case ISD::INTRINSIC_VOID:
1486   case ISD::INTRINSIC_W_CHAIN:
1487     IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
1488     break;
1489   case ISD::INTRINSIC_WO_CHAIN:
1490     IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
1491     break;
1492   default:
1493     llvm_unreachable("Invalid intrinsic");
1494   }
1495   SDLoc DL(Op);
1496 
1497   switch (IntNo) {
1498   default:
1499     return SDValue(); // Don't custom lower most intrinsics.
1500 
1501   case Intrinsic::wasm_lsda: {
1502     EVT VT = Op.getValueType();
1503     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1504     MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
1505     auto &Context = MF.getMMI().getContext();
1506     MCSymbol *S = Context.getOrCreateSymbol(Twine("GCC_except_table") +
1507                                             Twine(MF.getFunctionNumber()));
1508     return DAG.getNode(WebAssemblyISD::Wrapper, DL, VT,
1509                        DAG.getMCSymbol(S, PtrVT));
1510   }
1511 
1512   case Intrinsic::wasm_throw: {
1513     SDValue SymNode = getCppExceptionSymNode(Op, 2, DAG);
1514     return DAG.getNode(WebAssemblyISD::THROW, DL,
1515                        MVT::Other, // outchain type
1516                        {
1517                            Op.getOperand(0), // inchain
1518                            SymNode,          // exception symbol
1519                            Op.getOperand(3)  // thrown value
1520                        });
1521   }
1522 
1523   case Intrinsic::wasm_catch: {
1524     SDValue SymNode = getCppExceptionSymNode(Op, 2, DAG);
1525     return DAG.getNode(WebAssemblyISD::CATCH, DL,
1526                        {
1527                            MVT::i32,  // outchain type
1528                            MVT::Other // return value
1529                        },
1530                        {
1531                            Op.getOperand(0), // inchain
1532                            SymNode           // exception symbol
1533                        });
1534   }
1535 
1536   case Intrinsic::wasm_shuffle: {
1537     // Drop in-chain and replace undefs, but otherwise pass through unchanged
1538     SDValue Ops[18];
1539     size_t OpIdx = 0;
1540     Ops[OpIdx++] = Op.getOperand(1);
1541     Ops[OpIdx++] = Op.getOperand(2);
1542     while (OpIdx < 18) {
1543       const SDValue &MaskIdx = Op.getOperand(OpIdx + 1);
1544       if (MaskIdx.isUndef() ||
1545           cast<ConstantSDNode>(MaskIdx.getNode())->getZExtValue() >= 32) {
1546         Ops[OpIdx++] = DAG.getConstant(0, DL, MVT::i32);
1547       } else {
1548         Ops[OpIdx++] = MaskIdx;
1549       }
1550     }
1551     return DAG.getNode(WebAssemblyISD::SHUFFLE, DL, Op.getValueType(), Ops);
1552   }
1553   }
1554 }
1555 
1556 SDValue
1557 WebAssemblyTargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
1558                                                   SelectionDAG &DAG) const {
1559   SDLoc DL(Op);
1560   // If sign extension operations are disabled, allow sext_inreg only if operand
1561   // is a vector extract of an i8 or i16 lane. SIMD does not depend on sign
1562   // extension operations, but allowing sext_inreg in this context lets us have
1563   // simple patterns to select extract_lane_s instructions. Expanding sext_inreg
1564   // everywhere would be simpler in this file, but would necessitate large and
1565   // brittle patterns to undo the expansion and select extract_lane_s
1566   // instructions.
1567   assert(!Subtarget->hasSignExt() && Subtarget->hasSIMD128());
1568   if (Op.getOperand(0).getOpcode() != ISD::EXTRACT_VECTOR_ELT)
1569     return SDValue();
1570 
1571   const SDValue &Extract = Op.getOperand(0);
1572   MVT VecT = Extract.getOperand(0).getSimpleValueType();
1573   if (VecT.getVectorElementType().getSizeInBits() > 32)
1574     return SDValue();
1575   MVT ExtractedLaneT =
1576       cast<VTSDNode>(Op.getOperand(1).getNode())->getVT().getSimpleVT();
1577   MVT ExtractedVecT =
1578       MVT::getVectorVT(ExtractedLaneT, 128 / ExtractedLaneT.getSizeInBits());
1579   if (ExtractedVecT == VecT)
1580     return Op;
1581 
1582   // Bitcast vector to appropriate type to ensure ISel pattern coverage
1583   const SDNode *Index = Extract.getOperand(1).getNode();
1584   if (!isa<ConstantSDNode>(Index))
1585     return SDValue();
1586   unsigned IndexVal = cast<ConstantSDNode>(Index)->getZExtValue();
1587   unsigned Scale =
1588       ExtractedVecT.getVectorNumElements() / VecT.getVectorNumElements();
1589   assert(Scale > 1);
1590   SDValue NewIndex =
1591       DAG.getConstant(IndexVal * Scale, DL, Index->getValueType(0));
1592   SDValue NewExtract = DAG.getNode(
1593       ISD::EXTRACT_VECTOR_ELT, DL, Extract.getValueType(),
1594       DAG.getBitcast(ExtractedVecT, Extract.getOperand(0)), NewIndex);
1595   return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, Op.getValueType(), NewExtract,
1596                      Op.getOperand(1));
1597 }
1598 
1599 SDValue WebAssemblyTargetLowering::LowerBUILD_VECTOR(SDValue Op,
1600                                                      SelectionDAG &DAG) const {
1601   SDLoc DL(Op);
1602   const EVT VecT = Op.getValueType();
1603   const EVT LaneT = Op.getOperand(0).getValueType();
1604   const size_t Lanes = Op.getNumOperands();
1605   bool CanSwizzle = VecT == MVT::v16i8;
1606 
1607   // BUILD_VECTORs are lowered to the instruction that initializes the highest
1608   // possible number of lanes at once followed by a sequence of replace_lane
1609   // instructions to individually initialize any remaining lanes.
1610 
1611   // TODO: Tune this. For example, lanewise swizzling is very expensive, so
1612   // swizzled lanes should be given greater weight.
1613 
1614   // TODO: Investigate building vectors by shuffling together vectors built by
1615   // separately specialized means.
1616 
1617   auto IsConstant = [](const SDValue &V) {
1618     return V.getOpcode() == ISD::Constant || V.getOpcode() == ISD::ConstantFP;
1619   };
1620 
1621   // Returns the source vector and index vector pair if they exist. Checks for:
1622   //   (extract_vector_elt
1623   //     $src,
1624   //     (sign_extend_inreg (extract_vector_elt $indices, $i))
1625   //   )
1626   auto GetSwizzleSrcs = [](size_t I, const SDValue &Lane) {
1627     auto Bail = std::make_pair(SDValue(), SDValue());
1628     if (Lane->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
1629       return Bail;
1630     const SDValue &SwizzleSrc = Lane->getOperand(0);
1631     const SDValue &IndexExt = Lane->getOperand(1);
1632     if (IndexExt->getOpcode() != ISD::SIGN_EXTEND_INREG)
1633       return Bail;
1634     const SDValue &Index = IndexExt->getOperand(0);
1635     if (Index->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
1636       return Bail;
1637     const SDValue &SwizzleIndices = Index->getOperand(0);
1638     if (SwizzleSrc.getValueType() != MVT::v16i8 ||
1639         SwizzleIndices.getValueType() != MVT::v16i8 ||
1640         Index->getOperand(1)->getOpcode() != ISD::Constant ||
1641         Index->getConstantOperandVal(1) != I)
1642       return Bail;
1643     return std::make_pair(SwizzleSrc, SwizzleIndices);
1644   };
1645 
1646   using ValueEntry = std::pair<SDValue, size_t>;
1647   SmallVector<ValueEntry, 16> SplatValueCounts;
1648 
1649   using SwizzleEntry = std::pair<std::pair<SDValue, SDValue>, size_t>;
1650   SmallVector<SwizzleEntry, 16> SwizzleCounts;
1651 
1652   auto AddCount = [](auto &Counts, const auto &Val) {
1653     auto CountIt =
1654         llvm::find_if(Counts, [&Val](auto E) { return E.first == Val; });
1655     if (CountIt == Counts.end()) {
1656       Counts.emplace_back(Val, 1);
1657     } else {
1658       CountIt->second++;
1659     }
1660   };
1661 
1662   auto GetMostCommon = [](auto &Counts) {
1663     auto CommonIt =
1664         std::max_element(Counts.begin(), Counts.end(),
1665                          [](auto A, auto B) { return A.second < B.second; });
1666     assert(CommonIt != Counts.end() && "Unexpected all-undef build_vector");
1667     return *CommonIt;
1668   };
1669 
1670   size_t NumConstantLanes = 0;
1671 
1672   // Count eligible lanes for each type of vector creation op
1673   for (size_t I = 0; I < Lanes; ++I) {
1674     const SDValue &Lane = Op->getOperand(I);
1675     if (Lane.isUndef())
1676       continue;
1677 
1678     AddCount(SplatValueCounts, Lane);
1679 
1680     if (IsConstant(Lane)) {
1681       NumConstantLanes++;
1682     } else if (CanSwizzle) {
1683       auto SwizzleSrcs = GetSwizzleSrcs(I, Lane);
1684       if (SwizzleSrcs.first)
1685         AddCount(SwizzleCounts, SwizzleSrcs);
1686     }
1687   }
1688 
1689   SDValue SplatValue;
1690   size_t NumSplatLanes;
1691   std::tie(SplatValue, NumSplatLanes) = GetMostCommon(SplatValueCounts);
1692 
1693   SDValue SwizzleSrc;
1694   SDValue SwizzleIndices;
1695   size_t NumSwizzleLanes = 0;
1696   if (SwizzleCounts.size())
1697     std::forward_as_tuple(std::tie(SwizzleSrc, SwizzleIndices),
1698                           NumSwizzleLanes) = GetMostCommon(SwizzleCounts);
1699 
1700   // Predicate returning true if the lane is properly initialized by the
1701   // original instruction
1702   std::function<bool(size_t, const SDValue &)> IsLaneConstructed;
1703   SDValue Result;
1704   // Prefer swizzles over vector consts over splats
1705   if (NumSwizzleLanes >= NumSplatLanes &&
1706       (!Subtarget->hasUnimplementedSIMD128() ||
1707        NumSwizzleLanes >= NumConstantLanes)) {
1708     Result = DAG.getNode(WebAssemblyISD::SWIZZLE, DL, VecT, SwizzleSrc,
1709                          SwizzleIndices);
1710     auto Swizzled = std::make_pair(SwizzleSrc, SwizzleIndices);
1711     IsLaneConstructed = [&, Swizzled](size_t I, const SDValue &Lane) {
1712       return Swizzled == GetSwizzleSrcs(I, Lane);
1713     };
1714   } else if (NumConstantLanes >= NumSplatLanes &&
1715              Subtarget->hasUnimplementedSIMD128()) {
1716     // If we support v128.const, emit it directly
1717     SmallVector<SDValue, 16> ConstLanes;
1718     for (const SDValue &Lane : Op->op_values()) {
1719       if (IsConstant(Lane)) {
1720         ConstLanes.push_back(Lane);
1721       } else if (LaneT.isFloatingPoint()) {
1722         ConstLanes.push_back(DAG.getConstantFP(0, DL, LaneT));
1723       } else {
1724         ConstLanes.push_back(DAG.getConstant(0, DL, LaneT));
1725       }
1726     }
1727     Result = DAG.getBuildVector(VecT, DL, ConstLanes);
1728     IsLaneConstructed = [&IsConstant](size_t _, const SDValue &Lane) {
1729       return IsConstant(Lane);
1730     };
1731   } else if (NumConstantLanes >= NumSplatLanes && VecT.isInteger()) {
1732     // Otherwise, if this is an integer vector, pack the lane values together so
1733     // we can construct the 128-bit constant from a pair of i64s using a splat
1734     // followed by at most one i64x2.replace_lane. Also keep track of the lanes
1735     // that actually matter so we can avoid the replace_lane in more cases.
1736     std::array<uint64_t, 2> I64s{{0, 0}};
1737     std::array<uint64_t, 2> ConstLaneMasks{{0, 0}};
1738     size_t LaneBits = 128 / Lanes;
1739     size_t HalfLanes = Lanes / 2;
1740     for (size_t I = 0; I < Lanes; ++I) {
1741       const SDValue &Lane = Op.getOperand(I);
1742       if (IsConstant(Lane)) {
1743         // How much we need to shift Val to position it in an i64
1744         auto Shift = LaneBits * (I % HalfLanes);
1745         auto Mask = maskTrailingOnes<uint64_t>(LaneBits);
1746         auto Val = cast<ConstantSDNode>(Lane.getNode())->getZExtValue() & Mask;
1747         I64s[I / HalfLanes] |= Val << Shift;
1748         ConstLaneMasks[I / HalfLanes] |= Mask << Shift;
1749       }
1750     }
1751     // Check whether all constant lanes in the second half of the vector are
1752     // equivalent in the first half or vice versa to determine whether splatting
1753     // either side will be sufficient to materialize the constant. As a special
1754     // case, if the first and second halves have no constant lanes in common, we
1755     // can just combine them.
1756     bool FirstHalfSufficient = (I64s[0] & ConstLaneMasks[1]) == I64s[1];
1757     bool SecondHalfSufficient = (I64s[1] & ConstLaneMasks[0]) == I64s[0];
1758     bool CombinedSufficient = (ConstLaneMasks[0] & ConstLaneMasks[1]) == 0;
1759 
1760     uint64_t Splatted;
1761     if (SecondHalfSufficient) {
1762       Splatted = I64s[1];
1763     } else if (CombinedSufficient) {
1764       Splatted = I64s[0] | I64s[1];
1765     } else {
1766       Splatted = I64s[0];
1767     }
1768 
1769     Result = DAG.getSplatBuildVector(MVT::v2i64, DL,
1770                                      DAG.getConstant(Splatted, DL, MVT::i64));
1771     if (!FirstHalfSufficient && !SecondHalfSufficient && !CombinedSufficient) {
1772       Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, MVT::v2i64, Result,
1773                            DAG.getConstant(I64s[1], DL, MVT::i64),
1774                            DAG.getConstant(1, DL, MVT::i32));
1775     }
1776     Result = DAG.getBitcast(VecT, Result);
1777     IsLaneConstructed = [&IsConstant](size_t _, const SDValue &Lane) {
1778       return IsConstant(Lane);
1779     };
1780   } else {
1781     // Use a splat, but possibly a load_splat
1782     LoadSDNode *SplattedLoad;
1783     if ((SplattedLoad = dyn_cast<LoadSDNode>(SplatValue)) &&
1784         SplattedLoad->getMemoryVT() == VecT.getVectorElementType()) {
1785       Result = DAG.getMemIntrinsicNode(
1786           WebAssemblyISD::LOAD_SPLAT, DL, DAG.getVTList(VecT),
1787           {SplattedLoad->getChain(), SplattedLoad->getBasePtr(),
1788            SplattedLoad->getOffset()},
1789           SplattedLoad->getMemoryVT(), SplattedLoad->getMemOperand());
1790     } else {
1791       Result = DAG.getSplatBuildVector(VecT, DL, SplatValue);
1792     }
1793     IsLaneConstructed = [&SplatValue](size_t _, const SDValue &Lane) {
1794       return Lane == SplatValue;
1795     };
1796   }
1797 
1798   assert(Result);
1799   assert(IsLaneConstructed);
1800 
1801   // Add replace_lane instructions for any unhandled values
1802   for (size_t I = 0; I < Lanes; ++I) {
1803     const SDValue &Lane = Op->getOperand(I);
1804     if (!Lane.isUndef() && !IsLaneConstructed(I, Lane))
1805       Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VecT, Result, Lane,
1806                            DAG.getConstant(I, DL, MVT::i32));
1807   }
1808 
1809   return Result;
1810 }
1811 
1812 SDValue
1813 WebAssemblyTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
1814                                                SelectionDAG &DAG) const {
1815   SDLoc DL(Op);
1816   ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Op.getNode())->getMask();
1817   MVT VecType = Op.getOperand(0).getSimpleValueType();
1818   assert(VecType.is128BitVector() && "Unexpected shuffle vector type");
1819   size_t LaneBytes = VecType.getVectorElementType().getSizeInBits() / 8;
1820 
1821   // Space for two vector args and sixteen mask indices
1822   SDValue Ops[18];
1823   size_t OpIdx = 0;
1824   Ops[OpIdx++] = Op.getOperand(0);
1825   Ops[OpIdx++] = Op.getOperand(1);
1826 
1827   // Expand mask indices to byte indices and materialize them as operands
1828   for (int M : Mask) {
1829     for (size_t J = 0; J < LaneBytes; ++J) {
1830       // Lower undefs (represented by -1 in mask) to zero
1831       uint64_t ByteIndex = M == -1 ? 0 : (uint64_t)M * LaneBytes + J;
1832       Ops[OpIdx++] = DAG.getConstant(ByteIndex, DL, MVT::i32);
1833     }
1834   }
1835 
1836   return DAG.getNode(WebAssemblyISD::SHUFFLE, DL, Op.getValueType(), Ops);
1837 }
1838 
1839 SDValue WebAssemblyTargetLowering::LowerSETCC(SDValue Op,
1840                                               SelectionDAG &DAG) const {
1841   SDLoc DL(Op);
1842   // The legalizer does not know how to expand the comparison modes of i64x2
1843   // vectors because no comparison modes are supported. We could solve this by
1844   // expanding all i64x2 SETCC nodes, but that seems to expand f64x2 SETCC nodes
1845   // (which return i64x2 results) as well. So instead we manually unroll i64x2
1846   // comparisons here.
1847   assert(Op->getOperand(0)->getSimpleValueType(0) == MVT::v2i64);
1848   SmallVector<SDValue, 2> LHS, RHS;
1849   DAG.ExtractVectorElements(Op->getOperand(0), LHS);
1850   DAG.ExtractVectorElements(Op->getOperand(1), RHS);
1851   const SDValue &CC = Op->getOperand(2);
1852   auto MakeLane = [&](unsigned I) {
1853     return DAG.getNode(ISD::SELECT_CC, DL, MVT::i64, LHS[I], RHS[I],
1854                        DAG.getConstant(uint64_t(-1), DL, MVT::i64),
1855                        DAG.getConstant(uint64_t(0), DL, MVT::i64), CC);
1856   };
1857   return DAG.getBuildVector(Op->getValueType(0), DL,
1858                             {MakeLane(0), MakeLane(1)});
1859 }
1860 
1861 SDValue
1862 WebAssemblyTargetLowering::LowerAccessVectorElement(SDValue Op,
1863                                                     SelectionDAG &DAG) const {
1864   // Allow constant lane indices, expand variable lane indices
1865   SDNode *IdxNode = Op.getOperand(Op.getNumOperands() - 1).getNode();
1866   if (isa<ConstantSDNode>(IdxNode) || IdxNode->isUndef())
1867     return Op;
1868   else
1869     // Perform default expansion
1870     return SDValue();
1871 }
1872 
1873 static SDValue unrollVectorShift(SDValue Op, SelectionDAG &DAG) {
1874   EVT LaneT = Op.getSimpleValueType().getVectorElementType();
1875   // 32-bit and 64-bit unrolled shifts will have proper semantics
1876   if (LaneT.bitsGE(MVT::i32))
1877     return DAG.UnrollVectorOp(Op.getNode());
1878   // Otherwise mask the shift value to get proper semantics from 32-bit shift
1879   SDLoc DL(Op);
1880   size_t NumLanes = Op.getSimpleValueType().getVectorNumElements();
1881   SDValue Mask = DAG.getConstant(LaneT.getSizeInBits() - 1, DL, MVT::i32);
1882   unsigned ShiftOpcode = Op.getOpcode();
1883   SmallVector<SDValue, 16> ShiftedElements;
1884   DAG.ExtractVectorElements(Op.getOperand(0), ShiftedElements, 0, 0, MVT::i32);
1885   SmallVector<SDValue, 16> ShiftElements;
1886   DAG.ExtractVectorElements(Op.getOperand(1), ShiftElements, 0, 0, MVT::i32);
1887   SmallVector<SDValue, 16> UnrolledOps;
1888   for (size_t i = 0; i < NumLanes; ++i) {
1889     SDValue MaskedShiftValue =
1890         DAG.getNode(ISD::AND, DL, MVT::i32, ShiftElements[i], Mask);
1891     SDValue ShiftedValue = ShiftedElements[i];
1892     if (ShiftOpcode == ISD::SRA)
1893       ShiftedValue = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i32,
1894                                  ShiftedValue, DAG.getValueType(LaneT));
1895     UnrolledOps.push_back(
1896         DAG.getNode(ShiftOpcode, DL, MVT::i32, ShiftedValue, MaskedShiftValue));
1897   }
1898   return DAG.getBuildVector(Op.getValueType(), DL, UnrolledOps);
1899 }
1900 
1901 SDValue WebAssemblyTargetLowering::LowerShift(SDValue Op,
1902                                               SelectionDAG &DAG) const {
1903   SDLoc DL(Op);
1904 
1905   // Only manually lower vector shifts
1906   assert(Op.getSimpleValueType().isVector());
1907 
1908   auto ShiftVal = DAG.getSplatValue(Op.getOperand(1));
1909   if (!ShiftVal)
1910     return unrollVectorShift(Op, DAG);
1911 
1912   // Use anyext because none of the high bits can affect the shift
1913   ShiftVal = DAG.getAnyExtOrTrunc(ShiftVal, DL, MVT::i32);
1914 
1915   unsigned Opcode;
1916   switch (Op.getOpcode()) {
1917   case ISD::SHL:
1918     Opcode = WebAssemblyISD::VEC_SHL;
1919     break;
1920   case ISD::SRA:
1921     Opcode = WebAssemblyISD::VEC_SHR_S;
1922     break;
1923   case ISD::SRL:
1924     Opcode = WebAssemblyISD::VEC_SHR_U;
1925     break;
1926   default:
1927     llvm_unreachable("unexpected opcode");
1928   }
1929 
1930   return DAG.getNode(Opcode, DL, Op.getValueType(), Op.getOperand(0), ShiftVal);
1931 }
1932 
1933 //===----------------------------------------------------------------------===//
1934 //   Custom DAG combine hooks
1935 //===----------------------------------------------------------------------===//
1936 static SDValue
1937 performVECTOR_SHUFFLECombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
1938   auto &DAG = DCI.DAG;
1939   auto Shuffle = cast<ShuffleVectorSDNode>(N);
1940 
1941   // Hoist vector bitcasts that don't change the number of lanes out of unary
1942   // shuffles, where they are less likely to get in the way of other combines.
1943   // (shuffle (vNxT1 (bitcast (vNxT0 x))), undef, mask) ->
1944   //  (vNxT1 (bitcast (vNxT0 (shuffle x, undef, mask))))
1945   SDValue Bitcast = N->getOperand(0);
1946   if (Bitcast.getOpcode() != ISD::BITCAST)
1947     return SDValue();
1948   if (!N->getOperand(1).isUndef())
1949     return SDValue();
1950   SDValue CastOp = Bitcast.getOperand(0);
1951   MVT SrcType = CastOp.getSimpleValueType();
1952   MVT DstType = Bitcast.getSimpleValueType();
1953   if (!SrcType.is128BitVector() ||
1954       SrcType.getVectorNumElements() != DstType.getVectorNumElements())
1955     return SDValue();
1956   SDValue NewShuffle = DAG.getVectorShuffle(
1957       SrcType, SDLoc(N), CastOp, DAG.getUNDEF(SrcType), Shuffle->getMask());
1958   return DAG.getBitcast(DstType, NewShuffle);
1959 }
1960 
1961 static SDValue performVectorWidenCombine(SDNode *N,
1962                                          TargetLowering::DAGCombinerInfo &DCI) {
1963   auto &DAG = DCI.DAG;
1964   assert(N->getOpcode() == ISD::SIGN_EXTEND ||
1965          N->getOpcode() == ISD::ZERO_EXTEND);
1966 
1967   // Combine ({s,z}ext (extract_subvector src, i)) into a widening operation if
1968   // possible before the extract_subvector can be expanded.
1969   auto Extract = N->getOperand(0);
1970   if (Extract.getOpcode() != ISD::EXTRACT_SUBVECTOR)
1971     return SDValue();
1972   auto Source = Extract.getOperand(0);
1973   auto *IndexNode = dyn_cast<ConstantSDNode>(Extract.getOperand(1));
1974   if (IndexNode == nullptr)
1975     return SDValue();
1976   auto Index = IndexNode->getZExtValue();
1977 
1978   // Only v8i8 and v4i16 extracts can be widened, and only if the extracted
1979   // subvector is the low or high half of its source.
1980   EVT ResVT = N->getValueType(0);
1981   if (ResVT == MVT::v8i16) {
1982     if (Extract.getValueType() != MVT::v8i8 ||
1983         Source.getValueType() != MVT::v16i8 || (Index != 0 && Index != 8))
1984       return SDValue();
1985   } else if (ResVT == MVT::v4i32) {
1986     if (Extract.getValueType() != MVT::v4i16 ||
1987         Source.getValueType() != MVT::v8i16 || (Index != 0 && Index != 4))
1988       return SDValue();
1989   } else {
1990     return SDValue();
1991   }
1992 
1993   bool IsSext = N->getOpcode() == ISD::SIGN_EXTEND;
1994   bool IsLow = Index == 0;
1995 
1996   unsigned Op = IsSext ? (IsLow ? WebAssemblyISD::WIDEN_LOW_S
1997                                 : WebAssemblyISD::WIDEN_HIGH_S)
1998                        : (IsLow ? WebAssemblyISD::WIDEN_LOW_U
1999                                 : WebAssemblyISD::WIDEN_HIGH_U);
2000 
2001   return DAG.getNode(Op, SDLoc(N), ResVT, Source);
2002 }
2003 
2004 SDValue
2005 WebAssemblyTargetLowering::PerformDAGCombine(SDNode *N,
2006                                              DAGCombinerInfo &DCI) const {
2007   switch (N->getOpcode()) {
2008   default:
2009     return SDValue();
2010   case ISD::VECTOR_SHUFFLE:
2011     return performVECTOR_SHUFFLECombine(N, DCI);
2012   case ISD::SIGN_EXTEND:
2013   case ISD::ZERO_EXTEND:
2014     return performVectorWidenCombine(N, DCI);
2015   }
2016 }
2017