blob: 04a9089ff5fe79fbc027504f533f9f1475abc3eb [file] [log] [blame]
Dan Gohman10e730a2015-06-29 23:51:55 +00001//=- WebAssemblyISelLowering.cpp - WebAssembly DAG Lowering Implementation -==//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// 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
Dan Gohman10e730a2015-06-29 23:51:55 +00006//
7//===----------------------------------------------------------------------===//
8///
9/// \file
Adrian Prantl5f8f34e42018-05-01 15:54:18 +000010/// This file implements the WebAssemblyTargetLowering class.
Dan Gohman10e730a2015-06-29 23:51:55 +000011///
12//===----------------------------------------------------------------------===//
13
14#include "WebAssemblyISelLowering.h"
15#include "MCTargetDesc/WebAssemblyMCTargetDesc.h"
16#include "WebAssemblyMachineFunctionInfo.h"
17#include "WebAssemblySubtarget.h"
18#include "WebAssemblyTargetMachine.h"
Dan Gohman10e730a2015-06-29 23:51:55 +000019#include "llvm/CodeGen/Analysis.h"
JF Bastienaf111db2015-08-24 22:16:48 +000020#include "llvm/CodeGen/CallingConvLower.h"
Dan Gohmancdd48b82017-11-28 01:13:40 +000021#include "llvm/CodeGen/MachineInstrBuilder.h"
Dan Gohman950a13c2015-09-16 16:51:30 +000022#include "llvm/CodeGen/MachineJumpTableInfo.h"
Heejin Ahn24faf852018-10-25 23:55:10 +000023#include "llvm/CodeGen/MachineModuleInfo.h"
Dan Gohman10e730a2015-06-29 23:51:55 +000024#include "llvm/CodeGen/MachineRegisterInfo.h"
25#include "llvm/CodeGen/SelectionDAG.h"
Heejin Ahnda419bd2018-11-14 02:46:21 +000026#include "llvm/CodeGen/WasmEHFuncInfo.h"
Oliver Stannard02fa1c82016-01-28 13:19:47 +000027#include "llvm/IR/DiagnosticInfo.h"
JF Bastienb9073fb2015-07-22 21:28:15 +000028#include "llvm/IR/DiagnosticPrinter.h"
Dan Gohman10e730a2015-06-29 23:51:55 +000029#include "llvm/IR/Function.h"
30#include "llvm/IR/Intrinsics.h"
Reid Kleckner5d986952019-12-11 07:55:26 -080031#include "llvm/IR/IntrinsicsWebAssembly.h"
Dan Gohman10e730a2015-06-29 23:51:55 +000032#include "llvm/Support/Debug.h"
33#include "llvm/Support/ErrorHandling.h"
34#include "llvm/Support/raw_ostream.h"
35#include "llvm/Target/TargetOptions.h"
36using namespace llvm;
37
38#define DEBUG_TYPE "wasm-lower"
39
40WebAssemblyTargetLowering::WebAssemblyTargetLowering(
41 const TargetMachine &TM, const WebAssemblySubtarget &STI)
Dan Gohmanbfaf7e12015-07-02 21:36:25 +000042 : TargetLowering(TM), Subtarget(&STI) {
JF Bastienaf111db2015-08-24 22:16:48 +000043 auto MVTPtr = Subtarget->hasAddr64() ? MVT::i64 : MVT::i32;
44
JF Bastien71d29ac2015-08-12 17:53:29 +000045 // Booleans always contain 0 or 1.
46 setBooleanContents(ZeroOrOneBooleanContent);
Thomas Lively5ea17d42018-10-20 01:35:23 +000047 // Except in SIMD vectors
48 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
Dan Gohman489abd72015-07-07 22:38:06 +000049 // We don't know the microarchitecture here, so just reduce register pressure.
50 setSchedulingPreference(Sched::RegPressure);
JF Bastienb9073fb2015-07-22 21:28:15 +000051 // Tell ISel that we have a stack pointer.
52 setStackPointerRegisterToSaveRestore(
53 Subtarget->hasAddr64() ? WebAssembly::SP64 : WebAssembly::SP32);
54 // Set up the register classes.
Dan Gohmand0bf9812015-09-26 01:09:44 +000055 addRegisterClass(MVT::i32, &WebAssembly::I32RegClass);
56 addRegisterClass(MVT::i64, &WebAssembly::I64RegClass);
57 addRegisterClass(MVT::f32, &WebAssembly::F32RegClass);
58 addRegisterClass(MVT::f64, &WebAssembly::F64RegClass);
Derek Schuff39bf39f2016-08-02 23:16:09 +000059 if (Subtarget->hasSIMD128()) {
60 addRegisterClass(MVT::v16i8, &WebAssembly::V128RegClass);
61 addRegisterClass(MVT::v8i16, &WebAssembly::V128RegClass);
62 addRegisterClass(MVT::v4i32, &WebAssembly::V128RegClass);
63 addRegisterClass(MVT::v4f32, &WebAssembly::V128RegClass);
Thomas Lively2b8b2972019-01-26 01:25:37 +000064 addRegisterClass(MVT::v2i64, &WebAssembly::V128RegClass);
65 addRegisterClass(MVT::v2f64, &WebAssembly::V128RegClass);
Derek Schuff39bf39f2016-08-02 23:16:09 +000066 }
JF Bastienb9073fb2015-07-22 21:28:15 +000067 // Compute derived properties from the register classes.
68 computeRegisterProperties(Subtarget->getRegisterInfo());
69
JF Bastienaf111db2015-08-24 22:16:48 +000070 setOperationAction(ISD::GlobalAddress, MVTPtr, Custom);
Dan Gohman2c8fe6a2015-11-25 16:44:29 +000071 setOperationAction(ISD::ExternalSymbol, MVTPtr, Custom);
Dan Gohman950a13c2015-09-16 16:51:30 +000072 setOperationAction(ISD::JumpTable, MVTPtr, Custom);
Derek Schuff51699a82016-02-12 22:56:03 +000073 setOperationAction(ISD::BlockAddress, MVTPtr, Custom);
74 setOperationAction(ISD::BRIND, MVT::Other, Custom);
JF Bastienaf111db2015-08-24 22:16:48 +000075
Dan Gohman35bfb242015-12-04 23:22:35 +000076 // Take the default expansion for va_arg, va_copy, and va_end. There is no
77 // default action for va_start, so we do that custom.
78 setOperationAction(ISD::VASTART, MVT::Other, Custom);
79 setOperationAction(ISD::VAARG, MVT::Other, Expand);
80 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
81 setOperationAction(ISD::VAEND, MVT::Other, Expand);
82
Thomas Livelyebd4c902018-09-12 17:56:00 +000083 for (auto T : {MVT::f32, MVT::f64, MVT::v4f32, MVT::v2f64}) {
JF Bastienda06bce2015-08-11 21:02:46 +000084 // Don't expand the floating-point types to constant pools.
85 setOperationAction(ISD::ConstantFP, T, Legal);
86 // Expand floating-point comparisons.
87 for (auto CC : {ISD::SETO, ISD::SETUO, ISD::SETUEQ, ISD::SETONE,
88 ISD::SETULT, ISD::SETULE, ISD::SETUGT, ISD::SETUGE})
89 setCondCodeAction(CC, T, Expand);
Dan Gohman32907a62015-08-20 22:57:13 +000090 // Expand floating-point library function operators.
Heejin Ahnf208f632018-09-05 01:27:38 +000091 for (auto Op :
92 {ISD::FSIN, ISD::FCOS, ISD::FSINCOS, ISD::FPOW, ISD::FREM, ISD::FMA})
Dan Gohman32907a62015-08-20 22:57:13 +000093 setOperationAction(Op, T, Expand);
Dan Gohman896e53f2015-08-24 18:23:13 +000094 // Note supported floating-point library function operators that otherwise
95 // default to expand.
Dan Gohman7a6b9822015-11-29 22:32:02 +000096 for (auto Op :
97 {ISD::FCEIL, ISD::FFLOOR, ISD::FTRUNC, ISD::FNEARBYINT, ISD::FRINT})
Dan Gohman896e53f2015-08-24 18:23:13 +000098 setOperationAction(Op, T, Legal);
Thomas Lively30f1d692018-10-24 22:49:55 +000099 // Support minimum and maximum, which otherwise default to expand.
100 setOperationAction(ISD::FMINIMUM, T, Legal);
101 setOperationAction(ISD::FMAXIMUM, T, Legal);
Dan Gohmana63e8eb2017-02-22 16:28:00 +0000102 // WebAssembly currently has no builtin f16 support.
103 setOperationAction(ISD::FP16_TO_FP, T, Expand);
104 setOperationAction(ISD::FP_TO_FP16, T, Expand);
105 setLoadExtAction(ISD::EXTLOAD, T, MVT::f16, Expand);
106 setTruncStoreAction(T, MVT::f16, Expand);
JF Bastienda06bce2015-08-11 21:02:46 +0000107 }
Dan Gohman32907a62015-08-20 22:57:13 +0000108
Thomas Lively66ea30c2018-11-29 22:01:01 +0000109 // Expand unavailable integer operations.
110 for (auto Op :
111 {ISD::BSWAP, ISD::SMUL_LOHI, ISD::UMUL_LOHI, ISD::MULHS, ISD::MULHU,
112 ISD::SDIVREM, ISD::UDIVREM, ISD::SHL_PARTS, ISD::SRA_PARTS,
113 ISD::SRL_PARTS, ISD::ADDC, ISD::ADDE, ISD::SUBC, ISD::SUBE}) {
Thomas Lively2b8b2972019-01-26 01:25:37 +0000114 for (auto T : {MVT::i32, MVT::i64})
Dan Gohman32907a62015-08-20 22:57:13 +0000115 setOperationAction(Op, T, Expand);
Thomas Lively2b8b2972019-01-26 01:25:37 +0000116 if (Subtarget->hasSIMD128())
Thomas Lively27748362020-01-30 18:23:14 -0800117 for (auto T : {MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64})
Thomas Lively66ea30c2018-11-29 22:01:01 +0000118 setOperationAction(Op, T, Expand);
Thomas Livelyb2382c82018-11-02 00:39:57 +0000119 }
Thomas Lively55735d52018-10-20 01:31:18 +0000120
Thomas Lively2b8b2972019-01-26 01:25:37 +0000121 // SIMD-specific configuration
122 if (Subtarget->hasSIMD128()) {
123 // Support saturating add for i8x16 and i16x8
124 for (auto Op : {ISD::SADDSAT, ISD::UADDSAT})
125 for (auto T : {MVT::v16i8, MVT::v8i16})
126 setOperationAction(Op, T, Legal);
127
Thomas Lively079816e2019-01-30 02:23:29 +0000128 // Custom lower BUILD_VECTORs to minimize number of replace_lanes
Thomas Lively27748362020-01-30 18:23:14 -0800129 for (auto T : {MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v4f32, MVT::v2i64,
130 MVT::v2f64})
Thomas Lively079816e2019-01-30 02:23:29 +0000131 setOperationAction(ISD::BUILD_VECTOR, T, Custom);
Thomas Lively079816e2019-01-30 02:23:29 +0000132
Thomas Lively2b8b2972019-01-26 01:25:37 +0000133 // We have custom shuffle lowering to expose the shuffle mask
Thomas Lively27748362020-01-30 18:23:14 -0800134 for (auto T : {MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v4f32, MVT::v2i64,
135 MVT::v2f64})
Thomas Lively2b8b2972019-01-26 01:25:37 +0000136 setOperationAction(ISD::VECTOR_SHUFFLE, T, Custom);
Thomas Lively2b8b2972019-01-26 01:25:37 +0000137
138 // Custom lowering since wasm shifts must have a scalar shift amount
Thomas Lively27748362020-01-30 18:23:14 -0800139 for (auto Op : {ISD::SHL, ISD::SRA, ISD::SRL})
140 for (auto T : {MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64})
Thomas Lively2b8b2972019-01-26 01:25:37 +0000141 setOperationAction(Op, T, Custom);
Thomas Lively2b8b2972019-01-26 01:25:37 +0000142
143 // Custom lower lane accesses to expand out variable indices
Thomas Lively27748362020-01-30 18:23:14 -0800144 for (auto Op : {ISD::EXTRACT_VECTOR_ELT, ISD::INSERT_VECTOR_ELT})
145 for (auto T : {MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v4f32, MVT::v2i64,
146 MVT::v2f64})
Thomas Lively2b8b2972019-01-26 01:25:37 +0000147 setOperationAction(Op, T, Custom);
Thomas Lively2b8b2972019-01-26 01:25:37 +0000148
149 // There is no i64x2.mul instruction
Thomas Lively27748362020-01-30 18:23:14 -0800150 // TODO: Actually, there is now. Implement it.
Thomas Lively2b8b2972019-01-26 01:25:37 +0000151 setOperationAction(ISD::MUL, MVT::v2i64, Expand);
152
153 // There are no vector select instructions
Thomas Lively27748362020-01-30 18:23:14 -0800154 for (auto Op : {ISD::VSELECT, ISD::SELECT_CC, ISD::SELECT})
155 for (auto T : {MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v4f32, MVT::v2i64,
156 MVT::v2f64})
Thomas Lively38c902b2018-11-09 01:38:44 +0000157 setOperationAction(Op, T, Expand);
Thomas Livelyd4891a12018-11-01 00:01:02 +0000158
Thomas Lively43876ae72019-03-02 03:32:25 +0000159 // Expand integer operations supported for scalars but not SIMD
160 for (auto Op : {ISD::CTLZ, ISD::CTTZ, ISD::CTPOP, ISD::SDIV, ISD::UDIV,
Thomas Lively27748362020-01-30 18:23:14 -0800161 ISD::SREM, ISD::UREM, ISD::ROTL, ISD::ROTR})
162 for (auto T : {MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64})
Thomas Lively43876ae72019-03-02 03:32:25 +0000163 setOperationAction(Op, T, Expand);
Thomas Lively43876ae72019-03-02 03:32:25 +0000164
Thomas Lively3a937562019-12-13 17:08:04 -0800165 // But we do have integer min and max operations
Thomas Lively27748362020-01-30 18:23:14 -0800166 for (auto Op : {ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX})
167 for (auto T : {MVT::v16i8, MVT::v8i16, MVT::v4i32})
168 setOperationAction(Op, T, Legal);
Thomas Lively3a937562019-12-13 17:08:04 -0800169
Thomas Lively43876ae72019-03-02 03:32:25 +0000170 // Expand float operations supported for scalars but not SIMD
171 for (auto Op : {ISD::FCEIL, ISD::FFLOOR, ISD::FTRUNC, ISD::FNEARBYINT,
Thomas Lively55229f62019-05-24 00:15:04 +0000172 ISD::FCOPYSIGN, ISD::FLOG, ISD::FLOG2, ISD::FLOG10,
Thomas Lively27748362020-01-30 18:23:14 -0800173 ISD::FEXP, ISD::FEXP2, ISD::FRINT})
174 for (auto T : {MVT::v4f32, MVT::v2f64})
175 setOperationAction(Op, T, Expand);
Thomas Lively43876ae72019-03-02 03:32:25 +0000176
Thomas Livelyecb7daf2019-11-01 10:21:00 -0700177 // Expand operations not supported for i64x2 vectors
Thomas Lively27748362020-01-30 18:23:14 -0800178 for (unsigned CC = 0; CC < ISD::SETCC_INVALID; ++CC)
179 setCondCodeAction(static_cast<ISD::CondCode>(CC), MVT::v2i64, Custom);
Thomas Livelyecb7daf2019-11-01 10:21:00 -0700180
Thomas Lively27748362020-01-30 18:23:14 -0800181 // 64x2 conversions are not in the spec
182 if (!Subtarget->hasUnimplementedSIMD128())
183 for (auto Op :
184 {ISD::SINT_TO_FP, ISD::UINT_TO_FP, ISD::FP_TO_SINT, ISD::FP_TO_UINT})
185 for (auto T : {MVT::v2i64, MVT::v2f64})
186 setOperationAction(Op, T, Expand);
Thomas Lively2b8b2972019-01-26 01:25:37 +0000187 }
188
Dan Gohman32907a62015-08-20 22:57:13 +0000189 // As a special case, these operators use the type to mean the type to
190 // sign-extend from.
Derek Schuffa519fe52017-09-13 00:29:06 +0000191 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
Dan Gohman5d2b9352018-01-19 17:16:24 +0000192 if (!Subtarget->hasSignExt()) {
Thomas Lively64a39a12019-01-10 22:32:11 +0000193 // Sign extends are legal only when extending a vector extract
194 auto Action = Subtarget->hasSIMD128() ? Custom : Expand;
Derek Schuffa519fe52017-09-13 00:29:06 +0000195 for (auto T : {MVT::i8, MVT::i16, MVT::i32})
Thomas Lively64a39a12019-01-10 22:32:11 +0000196 setOperationAction(ISD::SIGN_EXTEND_INREG, T, Action);
Derek Schuffa519fe52017-09-13 00:29:06 +0000197 }
Graham Hunter1a9195d2019-09-17 10:19:23 +0000198 for (auto T : MVT::integer_fixedlen_vector_valuetypes())
Thomas Lively5ea17d42018-10-20 01:35:23 +0000199 setOperationAction(ISD::SIGN_EXTEND_INREG, T, Expand);
Dan Gohman32907a62015-08-20 22:57:13 +0000200
201 // Dynamic stack allocation: use the default expansion.
202 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
203 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
Dan Gohman2683a552015-08-24 22:31:52 +0000204 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVTPtr, Expand);
JF Bastien73ff6af2015-08-31 22:24:11 +0000205
Derek Schuff9769deb2015-12-11 23:49:46 +0000206 setOperationAction(ISD::FrameIndex, MVT::i32, Custom);
Derek Schuffaadc89c2016-02-16 18:18:36 +0000207 setOperationAction(ISD::CopyToReg, MVT::Other, Custom);
Derek Schuff9769deb2015-12-11 23:49:46 +0000208
Dan Gohman950a13c2015-09-16 16:51:30 +0000209 // Expand these forms; we pattern-match the forms that we can handle in isel.
210 for (auto T : {MVT::i32, MVT::i64, MVT::f32, MVT::f64})
211 for (auto Op : {ISD::BR_CC, ISD::SELECT_CC})
212 setOperationAction(Op, T, Expand);
213
214 // We have custom switch handling.
215 setOperationAction(ISD::BR_JT, MVT::Other, Custom);
216
JF Bastien73ff6af2015-08-31 22:24:11 +0000217 // WebAssembly doesn't have:
218 // - Floating-point extending loads.
219 // - Floating-point truncating stores.
220 // - i1 extending loads.
Thomas Lively81125f72019-09-27 02:06:50 +0000221 // - truncating SIMD stores and most extending loads
Dan Gohman60bddf12015-12-10 02:07:53 +0000222 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f32, Expand);
JF Bastien73ff6af2015-08-31 22:24:11 +0000223 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
224 for (auto T : MVT::integer_valuetypes())
225 for (auto Ext : {ISD::EXTLOAD, ISD::ZEXTLOAD, ISD::SEXTLOAD})
226 setLoadExtAction(Ext, T, MVT::i1, Promote);
Thomas Lively325c9c52018-10-25 01:46:07 +0000227 if (Subtarget->hasSIMD128()) {
228 for (auto T : {MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64, MVT::v4f32,
229 MVT::v2f64}) {
Graham Hunter1a9195d2019-09-17 10:19:23 +0000230 for (auto MemT : MVT::fixedlen_vector_valuetypes()) {
Thomas Lively325c9c52018-10-25 01:46:07 +0000231 if (MVT(T) != MemT) {
232 setTruncStoreAction(T, MemT, Expand);
233 for (auto Ext : {ISD::EXTLOAD, ISD::ZEXTLOAD, ISD::SEXTLOAD})
234 setLoadExtAction(Ext, T, MemT, Expand);
235 }
236 }
237 }
Thomas Lively81125f72019-09-27 02:06:50 +0000238 // But some vector extending loads are legal
239 if (Subtarget->hasUnimplementedSIMD128()) {
240 for (auto Ext : {ISD::EXTLOAD, ISD::SEXTLOAD, ISD::ZEXTLOAD}) {
241 setLoadExtAction(Ext, MVT::v8i16, MVT::v8i8, Legal);
242 setLoadExtAction(Ext, MVT::v4i32, MVT::v4i16, Legal);
243 setLoadExtAction(Ext, MVT::v2i64, MVT::v2i32, Legal);
244 }
245 }
Thomas Lively325c9c52018-10-25 01:46:07 +0000246 }
Derek Schuffffa143c2015-11-10 00:30:57 +0000247
Thomas Lively33f87b82019-01-28 23:44:31 +0000248 // Don't do anything clever with build_pairs
249 setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand);
250
Derek Schuffffa143c2015-11-10 00:30:57 +0000251 // Trap lowers to wasm unreachable
252 setOperationAction(ISD::TRAP, MVT::Other, Legal);
Derek Schuff18ba1922017-08-30 18:07:45 +0000253
Heejin Ahn5ef4d5f2018-05-31 22:25:54 +0000254 // Exception handling intrinsics
255 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
Heejin Ahnda419bd2018-11-14 02:46:21 +0000256 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
Heejin Ahn5ef4d5f2018-05-31 22:25:54 +0000257
Derek Schuff18ba1922017-08-30 18:07:45 +0000258 setMaxAtomicSizeInBitsSupported(64);
Thomas Livelyd99af232019-02-05 00:49:55 +0000259
Dan Gohman3a7532e2019-04-30 19:17:59 +0000260 // Override the __gnu_f2h_ieee/__gnu_h2f_ieee names so that the f32 name is
261 // consistent with the f64 and f128 names.
262 setLibcallName(RTLIB::FPEXT_F16_F32, "__extendhfsf2");
263 setLibcallName(RTLIB::FPROUND_F32_F16, "__truncsfhf2");
264
Thomas Lively1a3cbe72019-05-23 01:24:01 +0000265 // Define the emscripten name for return address helper.
266 // TODO: when implementing other WASM backends, make this generic or only do
267 // this on emscripten depending on what they end up doing.
268 setLibcallName(RTLIB::RETURN_ADDRESS, "emscripten_return_address");
269
Heejin Ahnb9f282d2019-04-23 21:30:30 +0000270 // Always convert switches to br_tables unless there is only one case, which
271 // is equivalent to a simple branch. This reduces code size for wasm, and we
272 // defer possible jump table optimizations to the VM.
273 setMinimumJumpTableEntries(2);
Dan Gohmanbfaf7e12015-07-02 21:36:25 +0000274}
Dan Gohman10e730a2015-06-29 23:51:55 +0000275
Heejin Ahne8653bb2018-08-07 00:22:22 +0000276TargetLowering::AtomicExpansionKind
277WebAssemblyTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
278 // We have wasm instructions for these
279 switch (AI->getOperation()) {
280 case AtomicRMWInst::Add:
281 case AtomicRMWInst::Sub:
282 case AtomicRMWInst::And:
283 case AtomicRMWInst::Or:
284 case AtomicRMWInst::Xor:
285 case AtomicRMWInst::Xchg:
286 return AtomicExpansionKind::None;
287 default:
288 break;
289 }
290 return AtomicExpansionKind::CmpXChg;
291}
292
Dan Gohman7b634842015-08-24 18:44:37 +0000293FastISel *WebAssemblyTargetLowering::createFastISel(
294 FunctionLoweringInfo &FuncInfo, const TargetLibraryInfo *LibInfo) const {
295 return WebAssembly::createFastISel(FuncInfo, LibInfo);
296}
297
Dan Gohman7a6b9822015-11-29 22:32:02 +0000298MVT WebAssemblyTargetLowering::getScalarShiftAmountTy(const DataLayout & /*DL*/,
JF Bastienfda53372015-08-03 00:00:11 +0000299 EVT VT) const {
Dan Gohmana8483752015-12-10 00:26:26 +0000300 unsigned BitWidth = NextPowerOf2(VT.getSizeInBits() - 1);
Heejin Ahnf208f632018-09-05 01:27:38 +0000301 if (BitWidth > 1 && BitWidth < 8)
302 BitWidth = 8;
Dan Gohman41729532015-12-16 23:25:51 +0000303
304 if (BitWidth > 64) {
Dan Gohmana01e8bd2016-05-14 02:15:47 +0000305 // The shift will be lowered to a libcall, and compiler-rt libcalls expect
306 // the count to be an i32.
307 BitWidth = 32;
Dan Gohman41729532015-12-16 23:25:51 +0000308 assert(BitWidth >= Log2_32_Ceil(VT.getSizeInBits()) &&
Dan Gohmana01e8bd2016-05-14 02:15:47 +0000309 "32-bit shift counts ought to be enough for anyone");
Dan Gohman41729532015-12-16 23:25:51 +0000310 }
311
Dan Gohmana8483752015-12-10 00:26:26 +0000312 MVT Result = MVT::getIntegerVT(BitWidth);
313 assert(Result != MVT::INVALID_SIMPLE_VALUE_TYPE &&
314 "Unable to represent scalar shift amount type");
315 return Result;
JF Bastienfda53372015-08-03 00:00:11 +0000316}
317
Dan Gohmancdd48b82017-11-28 01:13:40 +0000318// Lower an fp-to-int conversion operator from the LLVM opcode, which has an
319// undefined result on invalid/overflow, to the WebAssembly opcode, which
320// traps on invalid/overflow.
Heejin Ahnf208f632018-09-05 01:27:38 +0000321static MachineBasicBlock *LowerFPToInt(MachineInstr &MI, DebugLoc DL,
322 MachineBasicBlock *BB,
323 const TargetInstrInfo &TII,
324 bool IsUnsigned, bool Int64,
325 bool Float64, unsigned LoweredOpcode) {
Dan Gohmancdd48b82017-11-28 01:13:40 +0000326 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
327
Daniel Sanders05c145d2019-08-12 22:40:45 +0000328 Register OutReg = MI.getOperand(0).getReg();
329 Register InReg = MI.getOperand(1).getReg();
Dan Gohmancdd48b82017-11-28 01:13:40 +0000330
331 unsigned Abs = Float64 ? WebAssembly::ABS_F64 : WebAssembly::ABS_F32;
332 unsigned FConst = Float64 ? WebAssembly::CONST_F64 : WebAssembly::CONST_F32;
333 unsigned LT = Float64 ? WebAssembly::LT_F64 : WebAssembly::LT_F32;
Dan Gohman580c1022017-11-29 20:20:11 +0000334 unsigned GE = Float64 ? WebAssembly::GE_F64 : WebAssembly::GE_F32;
Dan Gohmancdd48b82017-11-28 01:13:40 +0000335 unsigned IConst = Int64 ? WebAssembly::CONST_I64 : WebAssembly::CONST_I32;
Dan Gohman580c1022017-11-29 20:20:11 +0000336 unsigned Eqz = WebAssembly::EQZ_I32;
337 unsigned And = WebAssembly::AND_I32;
Dan Gohmancdd48b82017-11-28 01:13:40 +0000338 int64_t Limit = Int64 ? INT64_MIN : INT32_MIN;
339 int64_t Substitute = IsUnsigned ? 0 : Limit;
340 double CmpVal = IsUnsigned ? -(double)Limit * 2.0 : -(double)Limit;
David Blaikie21109242017-12-15 23:52:06 +0000341 auto &Context = BB->getParent()->getFunction().getContext();
Dan Gohmancdd48b82017-11-28 01:13:40 +0000342 Type *Ty = Float64 ? Type::getDoubleTy(Context) : Type::getFloatTy(Context);
343
Heejin Ahn18c56a02019-02-04 19:13:39 +0000344 const BasicBlock *LLVMBB = BB->getBasicBlock();
Dan Gohmancdd48b82017-11-28 01:13:40 +0000345 MachineFunction *F = BB->getParent();
Heejin Ahn18c56a02019-02-04 19:13:39 +0000346 MachineBasicBlock *TrueMBB = F->CreateMachineBasicBlock(LLVMBB);
347 MachineBasicBlock *FalseMBB = F->CreateMachineBasicBlock(LLVMBB);
348 MachineBasicBlock *DoneMBB = F->CreateMachineBasicBlock(LLVMBB);
Dan Gohmancdd48b82017-11-28 01:13:40 +0000349
350 MachineFunction::iterator It = ++BB->getIterator();
351 F->insert(It, FalseMBB);
352 F->insert(It, TrueMBB);
353 F->insert(It, DoneMBB);
354
355 // Transfer the remainder of BB and its successor edges to DoneMBB.
Heejin Ahn5c644c92019-03-05 21:05:09 +0000356 DoneMBB->splice(DoneMBB->begin(), BB, std::next(MI.getIterator()), BB->end());
Dan Gohmancdd48b82017-11-28 01:13:40 +0000357 DoneMBB->transferSuccessorsAndUpdatePHIs(BB);
358
359 BB->addSuccessor(TrueMBB);
360 BB->addSuccessor(FalseMBB);
361 TrueMBB->addSuccessor(DoneMBB);
362 FalseMBB->addSuccessor(DoneMBB);
363
Dan Gohman580c1022017-11-29 20:20:11 +0000364 unsigned Tmp0, Tmp1, CmpReg, EqzReg, FalseReg, TrueReg;
Dan Gohmancdd48b82017-11-28 01:13:40 +0000365 Tmp0 = MRI.createVirtualRegister(MRI.getRegClass(InReg));
366 Tmp1 = MRI.createVirtualRegister(MRI.getRegClass(InReg));
Dan Gohman580c1022017-11-29 20:20:11 +0000367 CmpReg = MRI.createVirtualRegister(&WebAssembly::I32RegClass);
368 EqzReg = MRI.createVirtualRegister(&WebAssembly::I32RegClass);
369 FalseReg = MRI.createVirtualRegister(MRI.getRegClass(OutReg));
370 TrueReg = MRI.createVirtualRegister(MRI.getRegClass(OutReg));
Dan Gohmancdd48b82017-11-28 01:13:40 +0000371
372 MI.eraseFromParent();
Dan Gohman580c1022017-11-29 20:20:11 +0000373 // For signed numbers, we can do a single comparison to determine whether
374 // fabs(x) is within range.
Dan Gohmancdd48b82017-11-28 01:13:40 +0000375 if (IsUnsigned) {
376 Tmp0 = InReg;
377 } else {
Heejin Ahnf208f632018-09-05 01:27:38 +0000378 BuildMI(BB, DL, TII.get(Abs), Tmp0).addReg(InReg);
Dan Gohmancdd48b82017-11-28 01:13:40 +0000379 }
380 BuildMI(BB, DL, TII.get(FConst), Tmp1)
381 .addFPImm(cast<ConstantFP>(ConstantFP::get(Ty, CmpVal)));
Heejin Ahnf208f632018-09-05 01:27:38 +0000382 BuildMI(BB, DL, TII.get(LT), CmpReg).addReg(Tmp0).addReg(Tmp1);
Dan Gohman580c1022017-11-29 20:20:11 +0000383
384 // For unsigned numbers, we have to do a separate comparison with zero.
385 if (IsUnsigned) {
386 Tmp1 = MRI.createVirtualRegister(MRI.getRegClass(InReg));
Daniel Sanders05c145d2019-08-12 22:40:45 +0000387 Register SecondCmpReg =
Heejin Ahnf208f632018-09-05 01:27:38 +0000388 MRI.createVirtualRegister(&WebAssembly::I32RegClass);
Daniel Sanders05c145d2019-08-12 22:40:45 +0000389 Register AndReg = MRI.createVirtualRegister(&WebAssembly::I32RegClass);
Dan Gohman580c1022017-11-29 20:20:11 +0000390 BuildMI(BB, DL, TII.get(FConst), Tmp1)
391 .addFPImm(cast<ConstantFP>(ConstantFP::get(Ty, 0.0)));
Heejin Ahnf208f632018-09-05 01:27:38 +0000392 BuildMI(BB, DL, TII.get(GE), SecondCmpReg).addReg(Tmp0).addReg(Tmp1);
393 BuildMI(BB, DL, TII.get(And), AndReg).addReg(CmpReg).addReg(SecondCmpReg);
Dan Gohman580c1022017-11-29 20:20:11 +0000394 CmpReg = AndReg;
395 }
396
Heejin Ahnf208f632018-09-05 01:27:38 +0000397 BuildMI(BB, DL, TII.get(Eqz), EqzReg).addReg(CmpReg);
Dan Gohman580c1022017-11-29 20:20:11 +0000398
399 // Create the CFG diamond to select between doing the conversion or using
400 // the substitute value.
Heejin Ahnf208f632018-09-05 01:27:38 +0000401 BuildMI(BB, DL, TII.get(WebAssembly::BR_IF)).addMBB(TrueMBB).addReg(EqzReg);
402 BuildMI(FalseMBB, DL, TII.get(LoweredOpcode), FalseReg).addReg(InReg);
403 BuildMI(FalseMBB, DL, TII.get(WebAssembly::BR)).addMBB(DoneMBB);
404 BuildMI(TrueMBB, DL, TII.get(IConst), TrueReg).addImm(Substitute);
Dan Gohmancdd48b82017-11-28 01:13:40 +0000405 BuildMI(*DoneMBB, DoneMBB->begin(), DL, TII.get(TargetOpcode::PHI), OutReg)
Dan Gohman580c1022017-11-29 20:20:11 +0000406 .addReg(FalseReg)
Dan Gohmancdd48b82017-11-28 01:13:40 +0000407 .addMBB(FalseMBB)
Dan Gohman580c1022017-11-29 20:20:11 +0000408 .addReg(TrueReg)
Dan Gohmancdd48b82017-11-28 01:13:40 +0000409 .addMBB(TrueMBB);
410
411 return DoneMBB;
412}
413
Thomas Lively28857d12019-12-13 15:15:22 -0800414static MachineBasicBlock *LowerCallResults(MachineInstr &CallResults,
415 DebugLoc DL, MachineBasicBlock *BB,
416 const TargetInstrInfo &TII) {
417 MachineInstr &CallParams = *CallResults.getPrevNode();
418 assert(CallParams.getOpcode() == WebAssembly::CALL_PARAMS);
419 assert(CallResults.getOpcode() == WebAssembly::CALL_RESULTS);
420
421 MachineFunction &MF = *BB->getParent();
422 const MCInstrDesc &MCID = TII.get(WebAssembly::CALL);
423 MachineInstrBuilder MIB(MF, MF.CreateMachineInstr(MCID, DL));
424
425 for (auto Def : CallResults.defs())
426 MIB.add(Def);
427 for (auto Use : CallParams.uses())
428 MIB.add(Use);
429
430 BB->insert(CallResults.getIterator(), MIB);
431 CallParams.eraseFromParent();
432 CallResults.eraseFromParent();
433
434 return BB;
435}
436
Heejin Ahnf208f632018-09-05 01:27:38 +0000437MachineBasicBlock *WebAssemblyTargetLowering::EmitInstrWithCustomInserter(
438 MachineInstr &MI, MachineBasicBlock *BB) const {
Dan Gohmancdd48b82017-11-28 01:13:40 +0000439 const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
440 DebugLoc DL = MI.getDebugLoc();
441
442 switch (MI.getOpcode()) {
Heejin Ahnf208f632018-09-05 01:27:38 +0000443 default:
444 llvm_unreachable("Unexpected instr type to insert");
Dan Gohmancdd48b82017-11-28 01:13:40 +0000445 case WebAssembly::FP_TO_SINT_I32_F32:
446 return LowerFPToInt(MI, DL, BB, TII, false, false, false,
447 WebAssembly::I32_TRUNC_S_F32);
448 case WebAssembly::FP_TO_UINT_I32_F32:
449 return LowerFPToInt(MI, DL, BB, TII, true, false, false,
450 WebAssembly::I32_TRUNC_U_F32);
451 case WebAssembly::FP_TO_SINT_I64_F32:
452 return LowerFPToInt(MI, DL, BB, TII, false, true, false,
453 WebAssembly::I64_TRUNC_S_F32);
454 case WebAssembly::FP_TO_UINT_I64_F32:
455 return LowerFPToInt(MI, DL, BB, TII, true, true, false,
456 WebAssembly::I64_TRUNC_U_F32);
457 case WebAssembly::FP_TO_SINT_I32_F64:
458 return LowerFPToInt(MI, DL, BB, TII, false, false, true,
459 WebAssembly::I32_TRUNC_S_F64);
460 case WebAssembly::FP_TO_UINT_I32_F64:
461 return LowerFPToInt(MI, DL, BB, TII, true, false, true,
462 WebAssembly::I32_TRUNC_U_F64);
463 case WebAssembly::FP_TO_SINT_I64_F64:
464 return LowerFPToInt(MI, DL, BB, TII, false, true, true,
465 WebAssembly::I64_TRUNC_S_F64);
466 case WebAssembly::FP_TO_UINT_I64_F64:
467 return LowerFPToInt(MI, DL, BB, TII, true, true, true,
468 WebAssembly::I64_TRUNC_U_F64);
Thomas Lively28857d12019-12-13 15:15:22 -0800469 case WebAssembly::CALL_RESULTS:
470 return LowerCallResults(MI, DL, BB, TII);
Dan Gohmancdd48b82017-11-28 01:13:40 +0000471 }
472}
473
Heejin Ahnf208f632018-09-05 01:27:38 +0000474const char *
475WebAssemblyTargetLowering::getTargetNodeName(unsigned Opcode) const {
JF Bastien480c8402015-08-11 20:13:18 +0000476 switch (static_cast<WebAssemblyISD::NodeType>(Opcode)) {
Heejin Ahnf208f632018-09-05 01:27:38 +0000477 case WebAssemblyISD::FIRST_NUMBER:
Thomas Lively3479fd22019-10-31 20:01:02 -0700478 case WebAssemblyISD::FIRST_MEM_OPCODE:
Heejin Ahnf208f632018-09-05 01:27:38 +0000479 break;
480#define HANDLE_NODETYPE(NODE) \
481 case WebAssemblyISD::NODE: \
JF Bastienaf111db2015-08-24 22:16:48 +0000482 return "WebAssemblyISD::" #NODE;
Thomas Lively3479fd22019-10-31 20:01:02 -0700483#define HANDLE_MEM_NODETYPE(NODE) HANDLE_NODETYPE(NODE)
JF Bastienaf111db2015-08-24 22:16:48 +0000484#include "WebAssemblyISD.def"
Thomas Lively3479fd22019-10-31 20:01:02 -0700485#undef HANDLE_MEM_NODETYPE
JF Bastienaf111db2015-08-24 22:16:48 +0000486#undef HANDLE_NODETYPE
JF Bastien480c8402015-08-11 20:13:18 +0000487 }
488 return nullptr;
489}
490
Dan Gohmanf19ed562015-11-13 01:42:29 +0000491std::pair<unsigned, const TargetRegisterClass *>
492WebAssemblyTargetLowering::getRegForInlineAsmConstraint(
493 const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
494 // First, see if this is a constraint that directly corresponds to a
495 // WebAssembly register class.
496 if (Constraint.size() == 1) {
497 switch (Constraint[0]) {
Heejin Ahnf208f632018-09-05 01:27:38 +0000498 case 'r':
499 assert(VT != MVT::iPTR && "Pointer MVT not expected here");
500 if (Subtarget->hasSIMD128() && VT.isVector()) {
501 if (VT.getSizeInBits() == 128)
502 return std::make_pair(0U, &WebAssembly::V128RegClass);
503 }
504 if (VT.isInteger() && !VT.isVector()) {
505 if (VT.getSizeInBits() <= 32)
506 return std::make_pair(0U, &WebAssembly::I32RegClass);
507 if (VT.getSizeInBits() <= 64)
508 return std::make_pair(0U, &WebAssembly::I64RegClass);
509 }
510 break;
511 default:
512 break;
Dan Gohmanf19ed562015-11-13 01:42:29 +0000513 }
514 }
515
516 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
517}
518
Dan Gohman3192ddf2015-11-19 23:04:59 +0000519bool WebAssemblyTargetLowering::isCheapToSpeculateCttz() const {
520 // Assume ctz is a relatively cheap operation.
521 return true;
522}
523
524bool WebAssemblyTargetLowering::isCheapToSpeculateCtlz() const {
525 // Assume clz is a relatively cheap operation.
526 return true;
527}
528
Dan Gohman4b9d7912015-12-15 22:01:29 +0000529bool WebAssemblyTargetLowering::isLegalAddressingMode(const DataLayout &DL,
530 const AddrMode &AM,
Heejin Ahnf208f632018-09-05 01:27:38 +0000531 Type *Ty, unsigned AS,
Jonas Paulsson024e3192017-07-21 11:59:37 +0000532 Instruction *I) const {
Dan Gohman4b9d7912015-12-15 22:01:29 +0000533 // WebAssembly offsets are added as unsigned without wrapping. The
534 // isLegalAddressingMode gives us no way to determine if wrapping could be
535 // happening, so we approximate this by accepting only non-negative offsets.
Heejin Ahnf208f632018-09-05 01:27:38 +0000536 if (AM.BaseOffs < 0)
537 return false;
Dan Gohman4b9d7912015-12-15 22:01:29 +0000538
539 // WebAssembly has no scale register operands.
Heejin Ahnf208f632018-09-05 01:27:38 +0000540 if (AM.Scale != 0)
541 return false;
Dan Gohman4b9d7912015-12-15 22:01:29 +0000542
543 // Everything else is legal.
544 return true;
545}
546
Dan Gohmanbb372242016-01-26 03:39:31 +0000547bool WebAssemblyTargetLowering::allowsMisalignedMemoryAccesses(
Simon Pilgrim4e0648a2019-06-12 17:14:03 +0000548 EVT /*VT*/, unsigned /*AddrSpace*/, unsigned /*Align*/,
549 MachineMemOperand::Flags /*Flags*/, bool *Fast) const {
Dan Gohmanbb372242016-01-26 03:39:31 +0000550 // WebAssembly supports unaligned accesses, though it should be declared
551 // with the p2align attribute on loads and stores which do so, and there
552 // may be a performance impact. We tell LLVM they're "fast" because
Dan Gohmanfb619e92016-01-26 14:55:17 +0000553 // for the kinds of things that LLVM uses this for (merging adjacent stores
Dan Gohmanbb372242016-01-26 03:39:31 +0000554 // of constants, etc.), WebAssembly implementations will either want the
555 // unaligned access or they'll split anyway.
Heejin Ahnf208f632018-09-05 01:27:38 +0000556 if (Fast)
557 *Fast = true;
Dan Gohmanbb372242016-01-26 03:39:31 +0000558 return true;
559}
560
Reid Klecknerb5180542017-03-21 16:57:19 +0000561bool WebAssemblyTargetLowering::isIntDivCheap(EVT VT,
562 AttributeList Attr) const {
Dan Gohmanb4c3c382016-05-18 14:29:42 +0000563 // The current thinking is that wasm engines will perform this optimization,
564 // so we can save on code size.
565 return true;
566}
567
Thomas Lively81125f72019-09-27 02:06:50 +0000568bool WebAssemblyTargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const {
569 if (!Subtarget->hasUnimplementedSIMD128())
570 return false;
571 MVT ExtT = ExtVal.getSimpleValueType();
572 MVT MemT = cast<LoadSDNode>(ExtVal->getOperand(0))->getSimpleValueType(0);
573 return (ExtT == MVT::v8i16 && MemT == MVT::v8i8) ||
574 (ExtT == MVT::v4i32 && MemT == MVT::v4i16) ||
575 (ExtT == MVT::v2i64 && MemT == MVT::v2i32);
576}
577
Simon Pilgrim99f70162018-06-28 17:27:09 +0000578EVT WebAssemblyTargetLowering::getSetCCResultType(const DataLayout &DL,
579 LLVMContext &C,
580 EVT VT) const {
581 if (VT.isVector())
582 return VT.changeVectorElementTypeToInteger();
583
584 return TargetLowering::getSetCCResultType(DL, C, VT);
585}
586
Heejin Ahn4128cb02018-08-02 21:44:24 +0000587bool WebAssemblyTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
588 const CallInst &I,
589 MachineFunction &MF,
590 unsigned Intrinsic) const {
591 switch (Intrinsic) {
592 case Intrinsic::wasm_atomic_notify:
593 Info.opc = ISD::INTRINSIC_W_CHAIN;
594 Info.memVT = MVT::i32;
595 Info.ptrVal = I.getArgOperand(0);
596 Info.offset = 0;
Guillaume Chateletc97a3d12019-08-05 11:02:05 +0000597 Info.align = Align(4);
Heejin Ahn4128cb02018-08-02 21:44:24 +0000598 // atomic.notify instruction does not really load the memory specified with
599 // this argument, but MachineMemOperand should either be load or store, so
600 // we set this to a load.
601 // FIXME Volatile isn't really correct, but currently all LLVM atomic
602 // instructions are treated as volatiles in the backend, so we should be
603 // consistent. The same applies for wasm_atomic_wait intrinsics too.
604 Info.flags = MachineMemOperand::MOVolatile | MachineMemOperand::MOLoad;
605 return true;
606 case Intrinsic::wasm_atomic_wait_i32:
607 Info.opc = ISD::INTRINSIC_W_CHAIN;
608 Info.memVT = MVT::i32;
609 Info.ptrVal = I.getArgOperand(0);
610 Info.offset = 0;
Guillaume Chateletc97a3d12019-08-05 11:02:05 +0000611 Info.align = Align(4);
Heejin Ahn4128cb02018-08-02 21:44:24 +0000612 Info.flags = MachineMemOperand::MOVolatile | MachineMemOperand::MOLoad;
613 return true;
614 case Intrinsic::wasm_atomic_wait_i64:
615 Info.opc = ISD::INTRINSIC_W_CHAIN;
616 Info.memVT = MVT::i64;
617 Info.ptrVal = I.getArgOperand(0);
618 Info.offset = 0;
Guillaume Chateletc97a3d12019-08-05 11:02:05 +0000619 Info.align = Align(8);
Heejin Ahn4128cb02018-08-02 21:44:24 +0000620 Info.flags = MachineMemOperand::MOVolatile | MachineMemOperand::MOLoad;
621 return true;
622 default:
623 return false;
624 }
625}
626
Dan Gohman10e730a2015-06-29 23:51:55 +0000627//===----------------------------------------------------------------------===//
628// WebAssembly Lowering private implementation.
629//===----------------------------------------------------------------------===//
630
631//===----------------------------------------------------------------------===//
632// Lowering Code
633//===----------------------------------------------------------------------===//
634
Heejin Ahn18c56a02019-02-04 19:13:39 +0000635static void fail(const SDLoc &DL, SelectionDAG &DAG, const char *Msg) {
JF Bastienb9073fb2015-07-22 21:28:15 +0000636 MachineFunction &MF = DAG.getMachineFunction();
637 DAG.getContext()->diagnose(
Heejin Ahn18c56a02019-02-04 19:13:39 +0000638 DiagnosticInfoUnsupported(MF.getFunction(), Msg, DL.getDebugLoc()));
JF Bastienb9073fb2015-07-22 21:28:15 +0000639}
640
Dan Gohman85dbdda2015-12-04 17:16:07 +0000641// Test whether the given calling convention is supported.
Heejin Ahn18c56a02019-02-04 19:13:39 +0000642static bool callingConvSupported(CallingConv::ID CallConv) {
Dan Gohman85dbdda2015-12-04 17:16:07 +0000643 // We currently support the language-independent target-independent
Dan Gohman1ce2b1a2015-12-04 18:27:03 +0000644 // conventions. We don't yet have a way to annotate calls with properties like
645 // "cold", and we don't have any call-clobbered registers, so these are mostly
646 // all handled the same.
Dan Gohmana3f5ce52015-12-04 17:18:32 +0000647 return CallConv == CallingConv::C || CallConv == CallingConv::Fast ||
Dan Gohman1ce2b1a2015-12-04 18:27:03 +0000648 CallConv == CallingConv::Cold ||
649 CallConv == CallingConv::PreserveMost ||
650 CallConv == CallingConv::PreserveAll ||
Keno Fischer5c3cdef2019-08-05 21:36:09 +0000651 CallConv == CallingConv::CXX_FAST_TLS ||
Yuta Saitoc5bd3d02020-01-24 10:20:07 -0800652 CallConv == CallingConv::WASM_EmscriptenInvoke ||
653 CallConv == CallingConv::Swift;
Dan Gohman85dbdda2015-12-04 17:16:07 +0000654}
655
Heejin Ahnf208f632018-09-05 01:27:38 +0000656SDValue
657WebAssemblyTargetLowering::LowerCall(CallLoweringInfo &CLI,
658 SmallVectorImpl<SDValue> &InVals) const {
JF Bastiend8a9d662015-08-24 21:59:51 +0000659 SelectionDAG &DAG = CLI.DAG;
660 SDLoc DL = CLI.DL;
661 SDValue Chain = CLI.Chain;
662 SDValue Callee = CLI.Callee;
663 MachineFunction &MF = DAG.getMachineFunction();
Derek Schuff992d83f2016-02-10 20:14:15 +0000664 auto Layout = MF.getDataLayout();
JF Bastiend8a9d662015-08-24 21:59:51 +0000665
666 CallingConv::ID CallConv = CLI.CallConv;
Heejin Ahn18c56a02019-02-04 19:13:39 +0000667 if (!callingConvSupported(CallConv))
Dan Gohman9cc692b2015-10-02 20:54:23 +0000668 fail(DL, DAG,
669 "WebAssembly doesn't support language-specific or target-specific "
670 "calling conventions yet");
JF Bastiend8a9d662015-08-24 21:59:51 +0000671 if (CLI.IsPatchPoint)
672 fail(DL, DAG, "WebAssembly doesn't support patch point yet");
673
Thomas Livelye0a9dce2019-07-30 18:08:39 +0000674 if (CLI.IsTailCall) {
675 bool MustTail = CLI.CS && CLI.CS.isMustTailCall();
676 if (Subtarget->hasTailCall() && !CLI.IsVarArg) {
677 // Do not tail call unless caller and callee return types match
678 const Function &F = MF.getFunction();
679 const TargetMachine &TM = getTargetMachine();
680 Type *RetTy = F.getReturnType();
681 SmallVector<MVT, 4> CallerRetTys;
682 SmallVector<MVT, 4> CalleeRetTys;
683 computeLegalValueVTs(F, TM, RetTy, CallerRetTys);
684 computeLegalValueVTs(F, TM, CLI.RetTy, CalleeRetTys);
685 bool TypesMatch = CallerRetTys.size() == CalleeRetTys.size() &&
686 std::equal(CallerRetTys.begin(), CallerRetTys.end(),
687 CalleeRetTys.begin());
688 if (!TypesMatch) {
689 // musttail in this case would be an LLVM IR validation failure
690 assert(!MustTail);
691 CLI.IsTailCall = false;
692 }
693 } else {
694 CLI.IsTailCall = false;
695 if (MustTail) {
696 if (CLI.IsVarArg) {
697 // The return would pop the argument buffer
698 fail(DL, DAG, "WebAssembly does not support varargs tail calls");
699 } else {
700 fail(DL, DAG, "WebAssembly 'tail-call' feature not enabled");
701 }
702 }
703 }
Thomas Livelya1d97a92019-06-26 16:17:15 +0000704 }
Dan Gohman9cc692b2015-10-02 20:54:23 +0000705
JF Bastiend8a9d662015-08-24 21:59:51 +0000706 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
Dan Gohman2d822e72015-12-04 17:12:52 +0000707 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
Derek Schuff4dd67782016-01-27 21:17:39 +0000708 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
Keno Fischer5c3cdef2019-08-05 21:36:09 +0000709
710 // The generic code may have added an sret argument. If we're lowering an
711 // invoke function, the ABI requires that the function pointer be the first
712 // argument, so we may have to swap the arguments.
713 if (CallConv == CallingConv::WASM_EmscriptenInvoke && Outs.size() >= 2 &&
714 Outs[0].Flags.isSRet()) {
715 std::swap(Outs[0], Outs[1]);
716 std::swap(OutVals[0], OutVals[1]);
717 }
718
Dan Gohman910ba332018-06-26 03:18:38 +0000719 unsigned NumFixedArgs = 0;
Heejin Ahn18c56a02019-02-04 19:13:39 +0000720 for (unsigned I = 0; I < Outs.size(); ++I) {
721 const ISD::OutputArg &Out = Outs[I];
722 SDValue &OutVal = OutVals[I];
Dan Gohman7935fa32015-12-10 00:22:40 +0000723 if (Out.Flags.isNest())
724 fail(DL, DAG, "WebAssembly hasn't implemented nest arguments");
Dan Gohman2d822e72015-12-04 17:12:52 +0000725 if (Out.Flags.isInAlloca())
Dan Gohman7935fa32015-12-10 00:22:40 +0000726 fail(DL, DAG, "WebAssembly hasn't implemented inalloca arguments");
Dan Gohman2d822e72015-12-04 17:12:52 +0000727 if (Out.Flags.isInConsecutiveRegs())
Dan Gohman7935fa32015-12-10 00:22:40 +0000728 fail(DL, DAG, "WebAssembly hasn't implemented cons regs arguments");
Dan Gohman2d822e72015-12-04 17:12:52 +0000729 if (Out.Flags.isInConsecutiveRegsLast())
Dan Gohman7935fa32015-12-10 00:22:40 +0000730 fail(DL, DAG, "WebAssembly hasn't implemented cons regs last arguments");
Dan Gohmana6771b32016-02-12 21:30:18 +0000731 if (Out.Flags.isByVal() && Out.Flags.getByValSize() != 0) {
Matthias Braun941a7052016-07-28 18:40:00 +0000732 auto &MFI = MF.getFrameInfo();
733 int FI = MFI.CreateStackObject(Out.Flags.getByValSize(),
Guillaume Chatelet333f2ad2020-02-03 14:49:01 +0100734 Out.Flags.getNonZeroByValAlign(),
Matthias Braun941a7052016-07-28 18:40:00 +0000735 /*isSS=*/false);
Derek Schuff4dd67782016-01-27 21:17:39 +0000736 SDValue SizeNode =
737 DAG.getConstant(Out.Flags.getByValSize(), DL, MVT::i32);
Derek Schuff992d83f2016-02-10 20:14:15 +0000738 SDValue FINode = DAG.getFrameIndex(FI, getPointerTy(Layout));
Derek Schuff4dd67782016-01-27 21:17:39 +0000739 Chain = DAG.getMemcpy(
Guillaume Chatelet333f2ad2020-02-03 14:49:01 +0100740 Chain, DL, FINode, OutVal, SizeNode, Out.Flags.getNonZeroByValAlign(),
Dan Gohman476ffce2016-02-17 01:43:37 +0000741 /*isVolatile*/ false, /*AlwaysInline=*/false,
Derek Schuff4dd67782016-01-27 21:17:39 +0000742 /*isTailCall*/ false, MachinePointerInfo(), MachinePointerInfo());
743 OutVal = FINode;
744 }
Dan Gohman910ba332018-06-26 03:18:38 +0000745 // Count the number of fixed args *after* legalization.
746 NumFixedArgs += Out.IsFixed;
Dan Gohman2d822e72015-12-04 17:12:52 +0000747 }
748
JF Bastiend8a9d662015-08-24 21:59:51 +0000749 bool IsVarArg = CLI.IsVarArg;
Derek Schuff992d83f2016-02-10 20:14:15 +0000750 auto PtrVT = getPointerTy(Layout);
Dan Gohmane590b332015-09-09 01:52:45 +0000751
JF Bastiend8a9d662015-08-24 21:59:51 +0000752 // Analyze operands of the call, assigning locations to each operand.
753 SmallVector<CCValAssign, 16> ArgLocs;
754 CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
JF Bastiend8a9d662015-08-24 21:59:51 +0000755
Dan Gohman35bfb242015-12-04 23:22:35 +0000756 if (IsVarArg) {
Derek Schuff27501e22016-02-10 19:51:04 +0000757 // Outgoing non-fixed arguments are placed in a buffer. First
758 // compute their offsets and the total amount of buffer space needed.
Dan Gohmanc71132c2019-02-26 05:20:19 +0000759 for (unsigned I = NumFixedArgs; I < Outs.size(); ++I) {
760 const ISD::OutputArg &Out = Outs[I];
761 SDValue &Arg = OutVals[I];
Dan Gohman35bfb242015-12-04 23:22:35 +0000762 EVT VT = Arg.getValueType();
763 assert(VT != MVT::iPTR && "Legalized args should be concrete");
764 Type *Ty = VT.getTypeForEVT(*DAG.getContext());
Dan Gohmanc71132c2019-02-26 05:20:19 +0000765 unsigned Align = std::max(Out.Flags.getOrigAlign(),
766 Layout.getABITypeAlignment(Ty));
Derek Schuff992d83f2016-02-10 20:14:15 +0000767 unsigned Offset = CCInfo.AllocateStack(Layout.getTypeAllocSize(Ty),
Dan Gohmanc71132c2019-02-26 05:20:19 +0000768 Align);
Dan Gohman35bfb242015-12-04 23:22:35 +0000769 CCInfo.addLoc(CCValAssign::getMem(ArgLocs.size(), VT.getSimpleVT(),
770 Offset, VT.getSimpleVT(),
771 CCValAssign::Full));
772 }
773 }
774
775 unsigned NumBytes = CCInfo.getAlignedCallFrameSize();
776
Derek Schuff27501e22016-02-10 19:51:04 +0000777 SDValue FINode;
778 if (IsVarArg && NumBytes) {
Dan Gohman35bfb242015-12-04 23:22:35 +0000779 // For non-fixed arguments, next emit stores to store the argument values
Derek Schuff27501e22016-02-10 19:51:04 +0000780 // to the stack buffer at the offsets computed above.
Matthias Braun941a7052016-07-28 18:40:00 +0000781 int FI = MF.getFrameInfo().CreateStackObject(NumBytes,
782 Layout.getStackAlignment(),
783 /*isSS=*/false);
Dan Gohman35bfb242015-12-04 23:22:35 +0000784 unsigned ValNo = 0;
785 SmallVector<SDValue, 8> Chains;
786 for (SDValue Arg :
787 make_range(OutVals.begin() + NumFixedArgs, OutVals.end())) {
788 assert(ArgLocs[ValNo].getValNo() == ValNo &&
789 "ArgLocs should remain in order and only hold varargs args");
790 unsigned Offset = ArgLocs[ValNo++].getLocMemOffset();
Derek Schuff992d83f2016-02-10 20:14:15 +0000791 FINode = DAG.getFrameIndex(FI, getPointerTy(Layout));
Derek Schuff27501e22016-02-10 19:51:04 +0000792 SDValue Add = DAG.getNode(ISD::ADD, DL, PtrVT, FINode,
Dan Gohman35bfb242015-12-04 23:22:35 +0000793 DAG.getConstant(Offset, DL, PtrVT));
Heejin Ahnf208f632018-09-05 01:27:38 +0000794 Chains.push_back(
795 DAG.getStore(Chain, DL, Arg, Add,
796 MachinePointerInfo::getFixedStack(MF, FI, Offset), 0));
Dan Gohman35bfb242015-12-04 23:22:35 +0000797 }
798 if (!Chains.empty())
799 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
Derek Schuff27501e22016-02-10 19:51:04 +0000800 } else if (IsVarArg) {
801 FINode = DAG.getIntPtrConstant(0, DL);
Dan Gohman35bfb242015-12-04 23:22:35 +0000802 }
803
Sam Clegg492f7522019-03-26 19:46:15 +0000804 if (Callee->getOpcode() == ISD::GlobalAddress) {
805 // If the callee is a GlobalAddress node (quite common, every direct call
806 // is) turn it into a TargetGlobalAddress node so that LowerGlobalAddress
807 // doesn't at MO_GOT which is not needed for direct calls.
808 GlobalAddressSDNode* GA = cast<GlobalAddressSDNode>(Callee);
809 Callee = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
810 getPointerTy(DAG.getDataLayout()),
811 GA->getOffset());
812 Callee = DAG.getNode(WebAssemblyISD::Wrapper, DL,
813 getPointerTy(DAG.getDataLayout()), Callee);
814 }
815
Dan Gohman35bfb242015-12-04 23:22:35 +0000816 // Compute the operands for the CALLn node.
JF Bastiend8a9d662015-08-24 21:59:51 +0000817 SmallVector<SDValue, 16> Ops;
818 Ops.push_back(Chain);
JF Bastienaf111db2015-08-24 22:16:48 +0000819 Ops.push_back(Callee);
Dan Gohman35bfb242015-12-04 23:22:35 +0000820
821 // Add all fixed arguments. Note that for non-varargs calls, NumFixedArgs
822 // isn't reliable.
823 Ops.append(OutVals.begin(),
824 IsVarArg ? OutVals.begin() + NumFixedArgs : OutVals.end());
Derek Schuff27501e22016-02-10 19:51:04 +0000825 // Add a pointer to the vararg buffer.
Heejin Ahnf208f632018-09-05 01:27:38 +0000826 if (IsVarArg)
827 Ops.push_back(FINode);
JF Bastiend8a9d662015-08-24 21:59:51 +0000828
Derek Schuff27501e22016-02-10 19:51:04 +0000829 SmallVector<EVT, 8> InTys;
Dan Gohman2d822e72015-12-04 17:12:52 +0000830 for (const auto &In : Ins) {
Dan Gohman7935fa32015-12-10 00:22:40 +0000831 assert(!In.Flags.isByVal() && "byval is not valid for return values");
832 assert(!In.Flags.isNest() && "nest is not valid for return values");
Dan Gohman2d822e72015-12-04 17:12:52 +0000833 if (In.Flags.isInAlloca())
Dan Gohman7935fa32015-12-10 00:22:40 +0000834 fail(DL, DAG, "WebAssembly hasn't implemented inalloca return values");
Dan Gohman2d822e72015-12-04 17:12:52 +0000835 if (In.Flags.isInConsecutiveRegs())
Dan Gohman7935fa32015-12-10 00:22:40 +0000836 fail(DL, DAG, "WebAssembly hasn't implemented cons regs return values");
Dan Gohman2d822e72015-12-04 17:12:52 +0000837 if (In.Flags.isInConsecutiveRegsLast())
Dan Gohman4b9d7912015-12-15 22:01:29 +0000838 fail(DL, DAG,
839 "WebAssembly hasn't implemented cons regs last return values");
Dan Gohman2d822e72015-12-04 17:12:52 +0000840 // Ignore In.getOrigAlign() because all our arguments are passed in
841 // registers.
Derek Schuff27501e22016-02-10 19:51:04 +0000842 InTys.push_back(In.VT);
Dan Gohman2d822e72015-12-04 17:12:52 +0000843 }
Thomas Livelya1d97a92019-06-26 16:17:15 +0000844
845 if (CLI.IsTailCall) {
846 // ret_calls do not return values to the current frame
847 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
848 return DAG.getNode(WebAssemblyISD::RET_CALL, DL, NodeTys, Ops);
849 }
850
Derek Schuff27501e22016-02-10 19:51:04 +0000851 InTys.push_back(MVT::Other);
Thomas Lively3ef169e2019-12-13 10:41:25 -0800852 unsigned Opc;
853 // TODO: Remove CALL0 and CALL1 in favor of CALL
854 switch (Ins.size()) {
855 case 0:
856 Opc = WebAssemblyISD::CALL0;
857 break;
858 case 1:
859 Opc = WebAssemblyISD::CALL1;
860 break;
861 default:
862 Opc = WebAssemblyISD::CALL;
863 break;
JF Bastienaf111db2015-08-24 22:16:48 +0000864 }
Thomas Lively3ef169e2019-12-13 10:41:25 -0800865 SDVTList InTyList = DAG.getVTList(InTys);
866 SDValue Res = DAG.getNode(Opc, DL, InTyList, Ops);
JF Bastiend8a9d662015-08-24 21:59:51 +0000867
Thomas Lively3ef169e2019-12-13 10:41:25 -0800868 for (size_t I = 0; I < Ins.size(); ++I)
869 InVals.push_back(Res.getValue(I));
870
871 // Return the chain
872 return Res.getValue(Ins.size());
JF Bastiend8a9d662015-08-24 21:59:51 +0000873}
874
JF Bastienb9073fb2015-07-22 21:28:15 +0000875bool WebAssemblyTargetLowering::CanLowerReturn(
Dan Gohman7a6b9822015-11-29 22:32:02 +0000876 CallingConv::ID /*CallConv*/, MachineFunction & /*MF*/, bool /*IsVarArg*/,
877 const SmallVectorImpl<ISD::OutputArg> &Outs,
878 LLVMContext & /*Context*/) const {
Thomas Lively00f9e5a2019-10-09 21:42:08 +0000879 // WebAssembly can only handle returning tuples with multivalue enabled
880 return Subtarget->hasMultivalue() || Outs.size() <= 1;
JF Bastienb9073fb2015-07-22 21:28:15 +0000881}
882
883SDValue WebAssemblyTargetLowering::LowerReturn(
Dan Gohman35bfb242015-12-04 23:22:35 +0000884 SDValue Chain, CallingConv::ID CallConv, bool /*IsVarArg*/,
JF Bastienb9073fb2015-07-22 21:28:15 +0000885 const SmallVectorImpl<ISD::OutputArg> &Outs,
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000886 const SmallVectorImpl<SDValue> &OutVals, const SDLoc &DL,
JF Bastienb9073fb2015-07-22 21:28:15 +0000887 SelectionDAG &DAG) const {
Simon Pilgrim788ba152019-10-10 12:21:52 +0000888 assert((Subtarget->hasMultivalue() || Outs.size() <= 1) &&
889 "MVP WebAssembly can only return up to one value");
Heejin Ahn18c56a02019-02-04 19:13:39 +0000890 if (!callingConvSupported(CallConv))
JF Bastienb9073fb2015-07-22 21:28:15 +0000891 fail(DL, DAG, "WebAssembly doesn't support non-C calling conventions");
892
JF Bastien600aee92015-07-31 17:53:38 +0000893 SmallVector<SDValue, 4> RetOps(1, Chain);
894 RetOps.append(OutVals.begin(), OutVals.end());
JF Bastien4a2d5602015-07-31 21:04:18 +0000895 Chain = DAG.getNode(WebAssemblyISD::RETURN, DL, MVT::Other, RetOps);
JF Bastienb9073fb2015-07-22 21:28:15 +0000896
Dan Gohman754cd112015-11-11 01:33:02 +0000897 // Record the number and types of the return values.
898 for (const ISD::OutputArg &Out : Outs) {
Dan Gohmanac132e92015-12-02 23:40:03 +0000899 assert(!Out.Flags.isByVal() && "byval is not valid for return values");
900 assert(!Out.Flags.isNest() && "nest is not valid for return values");
Dan Gohman35bfb242015-12-04 23:22:35 +0000901 assert(Out.IsFixed && "non-fixed return value is not valid");
Dan Gohman754cd112015-11-11 01:33:02 +0000902 if (Out.Flags.isInAlloca())
903 fail(DL, DAG, "WebAssembly hasn't implemented inalloca results");
Dan Gohman754cd112015-11-11 01:33:02 +0000904 if (Out.Flags.isInConsecutiveRegs())
905 fail(DL, DAG, "WebAssembly hasn't implemented cons regs results");
906 if (Out.Flags.isInConsecutiveRegsLast())
907 fail(DL, DAG, "WebAssembly hasn't implemented cons regs last results");
Dan Gohman754cd112015-11-11 01:33:02 +0000908 }
909
JF Bastienb9073fb2015-07-22 21:28:15 +0000910 return Chain;
911}
912
913SDValue WebAssemblyTargetLowering::LowerFormalArguments(
Derek Schuff27501e22016-02-10 19:51:04 +0000914 SDValue Chain, CallingConv::ID CallConv, bool IsVarArg,
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000915 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
916 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
Heejin Ahn18c56a02019-02-04 19:13:39 +0000917 if (!callingConvSupported(CallConv))
JF Bastienb9073fb2015-07-22 21:28:15 +0000918 fail(DL, DAG, "WebAssembly doesn't support non-C calling conventions");
JF Bastienb9073fb2015-07-22 21:28:15 +0000919
Dan Gohman2726b882016-10-06 22:29:32 +0000920 MachineFunction &MF = DAG.getMachineFunction();
921 auto *MFI = MF.getInfo<WebAssemblyFunctionInfo>();
922
Dan Gohmanfb3e0592015-11-25 19:36:19 +0000923 // Set up the incoming ARGUMENTS value, which serves to represent the liveness
924 // of the incoming values before they're represented by virtual registers.
925 MF.getRegInfo().addLiveIn(WebAssembly::ARGUMENTS);
926
JF Bastien600aee92015-07-31 17:53:38 +0000927 for (const ISD::InputArg &In : Ins) {
JF Bastien600aee92015-07-31 17:53:38 +0000928 if (In.Flags.isInAlloca())
929 fail(DL, DAG, "WebAssembly hasn't implemented inalloca arguments");
930 if (In.Flags.isNest())
931 fail(DL, DAG, "WebAssembly hasn't implemented nest arguments");
JF Bastien600aee92015-07-31 17:53:38 +0000932 if (In.Flags.isInConsecutiveRegs())
933 fail(DL, DAG, "WebAssembly hasn't implemented cons regs arguments");
934 if (In.Flags.isInConsecutiveRegsLast())
935 fail(DL, DAG, "WebAssembly hasn't implemented cons regs last arguments");
Dan Gohman9c54d3b2015-11-25 18:13:18 +0000936 // Ignore In.getOrigAlign() because all our arguments are passed in
937 // registers.
Heejin Ahnf208f632018-09-05 01:27:38 +0000938 InVals.push_back(In.Used ? DAG.getNode(WebAssemblyISD::ARGUMENT, DL, In.VT,
939 DAG.getTargetConstant(InVals.size(),
940 DL, MVT::i32))
941 : DAG.getUNDEF(In.VT));
Dan Gohman754cd112015-11-11 01:33:02 +0000942
943 // Record the number and types of arguments.
Derek Schuff27501e22016-02-10 19:51:04 +0000944 MFI->addParam(In.VT);
JF Bastien600aee92015-07-31 17:53:38 +0000945 }
JF Bastienb9073fb2015-07-22 21:28:15 +0000946
Derek Schuff27501e22016-02-10 19:51:04 +0000947 // Varargs are copied into a buffer allocated by the caller, and a pointer to
948 // the buffer is passed as an argument.
949 if (IsVarArg) {
950 MVT PtrVT = getPointerTy(MF.getDataLayout());
Daniel Sanders05c145d2019-08-12 22:40:45 +0000951 Register VarargVreg =
Derek Schuff27501e22016-02-10 19:51:04 +0000952 MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrVT));
953 MFI->setVarargBufferVreg(VarargVreg);
954 Chain = DAG.getCopyToReg(
955 Chain, DL, VarargVreg,
956 DAG.getNode(WebAssemblyISD::ARGUMENT, DL, PtrVT,
957 DAG.getTargetConstant(Ins.size(), DL, MVT::i32)));
958 MFI->addParam(PtrVT);
959 }
Dan Gohman35bfb242015-12-04 23:22:35 +0000960
Derek Schuff77a7a382018-10-03 22:22:48 +0000961 // Record the number and types of arguments and results.
Dan Gohman2726b882016-10-06 22:29:32 +0000962 SmallVector<MVT, 4> Params;
963 SmallVector<MVT, 4> Results;
Heejin Ahn18c56a02019-02-04 19:13:39 +0000964 computeSignatureVTs(MF.getFunction().getFunctionType(), MF.getFunction(),
Derek Schuff77a7a382018-10-03 22:22:48 +0000965 DAG.getTarget(), Params, Results);
Dan Gohman2726b882016-10-06 22:29:32 +0000966 for (MVT VT : Results)
967 MFI->addResult(VT);
Derek Schuff77a7a382018-10-03 22:22:48 +0000968 // TODO: Use signatures in WebAssemblyMachineFunctionInfo too and unify
969 // the param logic here with ComputeSignatureVTs
970 assert(MFI->getParams().size() == Params.size() &&
971 std::equal(MFI->getParams().begin(), MFI->getParams().end(),
972 Params.begin()));
Dan Gohman2726b882016-10-06 22:29:32 +0000973
JF Bastienb9073fb2015-07-22 21:28:15 +0000974 return Chain;
975}
976
Thomas Livelye18b5c62019-05-23 18:09:26 +0000977void WebAssemblyTargetLowering::ReplaceNodeResults(
978 SDNode *N, SmallVectorImpl<SDValue> &Results, SelectionDAG &DAG) const {
979 switch (N->getOpcode()) {
980 case ISD::SIGN_EXTEND_INREG:
981 // Do not add any results, signifying that N should not be custom lowered
982 // after all. This happens because simd128 turns on custom lowering for
983 // SIGN_EXTEND_INREG, but for non-vector sign extends the result might be an
984 // illegal type.
985 break;
986 default:
987 llvm_unreachable(
988 "ReplaceNodeResults not implemented for this op for WebAssembly!");
989 }
990}
991
Dan Gohman10e730a2015-06-29 23:51:55 +0000992//===----------------------------------------------------------------------===//
JF Bastienaf111db2015-08-24 22:16:48 +0000993// Custom lowering hooks.
Dan Gohman10e730a2015-06-29 23:51:55 +0000994//===----------------------------------------------------------------------===//
995
JF Bastienaf111db2015-08-24 22:16:48 +0000996SDValue WebAssemblyTargetLowering::LowerOperation(SDValue Op,
997 SelectionDAG &DAG) const {
Derek Schuff51699a82016-02-12 22:56:03 +0000998 SDLoc DL(Op);
JF Bastienaf111db2015-08-24 22:16:48 +0000999 switch (Op.getOpcode()) {
Heejin Ahnf208f632018-09-05 01:27:38 +00001000 default:
1001 llvm_unreachable("unimplemented operation lowering");
1002 return SDValue();
1003 case ISD::FrameIndex:
1004 return LowerFrameIndex(Op, DAG);
1005 case ISD::GlobalAddress:
1006 return LowerGlobalAddress(Op, DAG);
1007 case ISD::ExternalSymbol:
1008 return LowerExternalSymbol(Op, DAG);
1009 case ISD::JumpTable:
1010 return LowerJumpTable(Op, DAG);
1011 case ISD::BR_JT:
1012 return LowerBR_JT(Op, DAG);
1013 case ISD::VASTART:
1014 return LowerVASTART(Op, DAG);
1015 case ISD::BlockAddress:
1016 case ISD::BRIND:
1017 fail(DL, DAG, "WebAssembly hasn't implemented computed gotos");
1018 return SDValue();
Thomas Lively1a3cbe72019-05-23 01:24:01 +00001019 case ISD::RETURNADDR:
1020 return LowerRETURNADDR(Op, DAG);
Heejin Ahnf208f632018-09-05 01:27:38 +00001021 case ISD::FRAMEADDR:
1022 return LowerFRAMEADDR(Op, DAG);
1023 case ISD::CopyToReg:
1024 return LowerCopyToReg(Op, DAG);
Thomas Livelyfb84fd72018-11-02 00:06:56 +00001025 case ISD::EXTRACT_VECTOR_ELT:
1026 case ISD::INSERT_VECTOR_ELT:
1027 return LowerAccessVectorElement(Op, DAG);
Heejin Ahnda419bd2018-11-14 02:46:21 +00001028 case ISD::INTRINSIC_VOID:
Heejin Ahnd6f48782019-01-30 03:21:57 +00001029 case ISD::INTRINSIC_WO_CHAIN:
1030 case ISD::INTRINSIC_W_CHAIN:
1031 return LowerIntrinsic(Op, DAG);
Thomas Lively64a39a12019-01-10 22:32:11 +00001032 case ISD::SIGN_EXTEND_INREG:
1033 return LowerSIGN_EXTEND_INREG(Op, DAG);
Thomas Lively079816e2019-01-30 02:23:29 +00001034 case ISD::BUILD_VECTOR:
1035 return LowerBUILD_VECTOR(Op, DAG);
Thomas Livelya0d25812018-09-07 21:54:46 +00001036 case ISD::VECTOR_SHUFFLE:
1037 return LowerVECTOR_SHUFFLE(Op, DAG);
Thomas Livelyecb7daf2019-11-01 10:21:00 -07001038 case ISD::SETCC:
1039 return LowerSETCC(Op, DAG);
Thomas Lively55735d52018-10-20 01:31:18 +00001040 case ISD::SHL:
1041 case ISD::SRA:
1042 case ISD::SRL:
1043 return LowerShift(Op, DAG);
JF Bastienaf111db2015-08-24 22:16:48 +00001044 }
1045}
1046
Derek Schuffaadc89c2016-02-16 18:18:36 +00001047SDValue WebAssemblyTargetLowering::LowerCopyToReg(SDValue Op,
1048 SelectionDAG &DAG) const {
1049 SDValue Src = Op.getOperand(2);
1050 if (isa<FrameIndexSDNode>(Src.getNode())) {
1051 // CopyToReg nodes don't support FrameIndex operands. Other targets select
1052 // the FI to some LEA-like instruction, but since we don't have that, we
1053 // need to insert some kind of instruction that can take an FI operand and
1054 // produces a value usable by CopyToReg (i.e. in a vreg). So insert a dummy
Thomas Lively6a87dda2019-01-08 06:25:55 +00001055 // local.copy between Op and its FI operand.
Dan Gohman02c08712016-02-20 23:09:44 +00001056 SDValue Chain = Op.getOperand(0);
Derek Schuffaadc89c2016-02-16 18:18:36 +00001057 SDLoc DL(Op);
Dan Gohman02c08712016-02-20 23:09:44 +00001058 unsigned Reg = cast<RegisterSDNode>(Op.getOperand(1))->getReg();
Derek Schuffaadc89c2016-02-16 18:18:36 +00001059 EVT VT = Src.getValueType();
Heejin Ahnf208f632018-09-05 01:27:38 +00001060 SDValue Copy(DAG.getMachineNode(VT == MVT::i32 ? WebAssembly::COPY_I32
1061 : WebAssembly::COPY_I64,
1062 DL, VT, Src),
1063 0);
Dan Gohman02c08712016-02-20 23:09:44 +00001064 return Op.getNode()->getNumValues() == 1
1065 ? DAG.getCopyToReg(Chain, DL, Reg, Copy)
Heejin Ahnf208f632018-09-05 01:27:38 +00001066 : DAG.getCopyToReg(Chain, DL, Reg, Copy,
1067 Op.getNumOperands() == 4 ? Op.getOperand(3)
1068 : SDValue());
Derek Schuffaadc89c2016-02-16 18:18:36 +00001069 }
1070 return SDValue();
1071}
1072
Derek Schuff9769deb2015-12-11 23:49:46 +00001073SDValue WebAssemblyTargetLowering::LowerFrameIndex(SDValue Op,
1074 SelectionDAG &DAG) const {
1075 int FI = cast<FrameIndexSDNode>(Op)->getIndex();
1076 return DAG.getTargetFrameIndex(FI, Op.getValueType());
1077}
1078
Thomas Lively1a3cbe72019-05-23 01:24:01 +00001079SDValue WebAssemblyTargetLowering::LowerRETURNADDR(SDValue Op,
1080 SelectionDAG &DAG) const {
1081 SDLoc DL(Op);
1082
1083 if (!Subtarget->getTargetTriple().isOSEmscripten()) {
1084 fail(DL, DAG,
1085 "Non-Emscripten WebAssembly hasn't implemented "
1086 "__builtin_return_address");
1087 return SDValue();
1088 }
1089
1090 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
1091 return SDValue();
1092
1093 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
Shiva Chen72a41e72019-08-22 04:59:43 +00001094 MakeLibCallOptions CallOptions;
Thomas Lively1a3cbe72019-05-23 01:24:01 +00001095 return makeLibCall(DAG, RTLIB::RETURN_ADDRESS, Op.getValueType(),
Shiva Chen72a41e72019-08-22 04:59:43 +00001096 {DAG.getConstant(Depth, DL, MVT::i32)}, CallOptions, DL)
Thomas Lively1a3cbe72019-05-23 01:24:01 +00001097 .first;
1098}
1099
Dan Gohman94c65662016-02-16 23:48:04 +00001100SDValue WebAssemblyTargetLowering::LowerFRAMEADDR(SDValue Op,
1101 SelectionDAG &DAG) const {
1102 // Non-zero depths are not supported by WebAssembly currently. Use the
1103 // legalizer's default expansion, which is to return 0 (what this function is
1104 // documented to do).
Dan Gohman1d547bf2016-02-17 00:14:03 +00001105 if (Op.getConstantOperandVal(0) > 0)
Dan Gohman94c65662016-02-16 23:48:04 +00001106 return SDValue();
1107
Matthias Braun941a7052016-07-28 18:40:00 +00001108 DAG.getMachineFunction().getFrameInfo().setFrameAddressIsTaken(true);
Dan Gohman94c65662016-02-16 23:48:04 +00001109 EVT VT = Op.getValueType();
Daniel Sanders05c145d2019-08-12 22:40:45 +00001110 Register FP =
Dan Gohman94c65662016-02-16 23:48:04 +00001111 Subtarget->getRegisterInfo()->getFrameRegister(DAG.getMachineFunction());
1112 return DAG.getCopyFromReg(DAG.getEntryNode(), SDLoc(Op), FP, VT);
1113}
1114
JF Bastienaf111db2015-08-24 22:16:48 +00001115SDValue WebAssemblyTargetLowering::LowerGlobalAddress(SDValue Op,
1116 SelectionDAG &DAG) const {
1117 SDLoc DL(Op);
1118 const auto *GA = cast<GlobalAddressSDNode>(Op);
1119 EVT VT = Op.getValueType();
Dan Gohman26c67652016-01-11 23:38:05 +00001120 assert(GA->getTargetFlags() == 0 &&
1121 "Unexpected target flags on generic GlobalAddressSDNode");
JF Bastienaf111db2015-08-24 22:16:48 +00001122 if (GA->getAddressSpace() != 0)
1123 fail(DL, DAG, "WebAssembly only expects the 0 address space");
Sam Clegg492f7522019-03-26 19:46:15 +00001124
Sam Cleggef4c66c2019-04-03 00:17:29 +00001125 unsigned OperandFlags = 0;
Sam Clegg492f7522019-03-26 19:46:15 +00001126 if (isPositionIndependent()) {
1127 const GlobalValue *GV = GA->getGlobal();
1128 if (getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV)) {
1129 MachineFunction &MF = DAG.getMachineFunction();
1130 MVT PtrVT = getPointerTy(MF.getDataLayout());
1131 const char *BaseName;
Sam Clegg2a7cac92019-04-04 17:43:50 +00001132 if (GV->getValueType()->isFunctionTy()) {
Sam Clegg492f7522019-03-26 19:46:15 +00001133 BaseName = MF.createExternalSymbolName("__table_base");
Sam Clegg2a7cac92019-04-04 17:43:50 +00001134 OperandFlags = WebAssemblyII::MO_TABLE_BASE_REL;
1135 }
1136 else {
Sam Clegg492f7522019-03-26 19:46:15 +00001137 BaseName = MF.createExternalSymbolName("__memory_base");
Sam Clegg2a7cac92019-04-04 17:43:50 +00001138 OperandFlags = WebAssemblyII::MO_MEMORY_BASE_REL;
1139 }
Sam Clegg492f7522019-03-26 19:46:15 +00001140 SDValue BaseAddr =
1141 DAG.getNode(WebAssemblyISD::Wrapper, DL, PtrVT,
1142 DAG.getTargetExternalSymbol(BaseName, PtrVT));
1143
1144 SDValue SymAddr = DAG.getNode(
1145 WebAssemblyISD::WrapperPIC, DL, VT,
Sam Clegg2a7cac92019-04-04 17:43:50 +00001146 DAG.getTargetGlobalAddress(GA->getGlobal(), DL, VT, GA->getOffset(),
1147 OperandFlags));
Sam Clegg492f7522019-03-26 19:46:15 +00001148
1149 return DAG.getNode(ISD::ADD, DL, VT, BaseAddr, SymAddr);
1150 } else {
Sam Cleggef4c66c2019-04-03 00:17:29 +00001151 OperandFlags = WebAssemblyII::MO_GOT;
Sam Clegg492f7522019-03-26 19:46:15 +00001152 }
1153 }
1154
1155 return DAG.getNode(WebAssemblyISD::Wrapper, DL, VT,
1156 DAG.getTargetGlobalAddress(GA->getGlobal(), DL, VT,
Sam Cleggef4c66c2019-04-03 00:17:29 +00001157 GA->getOffset(), OperandFlags));
JF Bastienaf111db2015-08-24 22:16:48 +00001158}
1159
Heejin Ahnf208f632018-09-05 01:27:38 +00001160SDValue
1161WebAssemblyTargetLowering::LowerExternalSymbol(SDValue Op,
1162 SelectionDAG &DAG) const {
Dan Gohman2c8fe6a2015-11-25 16:44:29 +00001163 SDLoc DL(Op);
1164 const auto *ES = cast<ExternalSymbolSDNode>(Op);
1165 EVT VT = Op.getValueType();
Dan Gohman26c67652016-01-11 23:38:05 +00001166 assert(ES->getTargetFlags() == 0 &&
1167 "Unexpected target flags on generic ExternalSymbolSDNode");
Sam Cleggef4c66c2019-04-03 00:17:29 +00001168 return DAG.getNode(WebAssemblyISD::Wrapper, DL, VT,
1169 DAG.getTargetExternalSymbol(ES->getSymbol(), VT));
Dan Gohman2c8fe6a2015-11-25 16:44:29 +00001170}
1171
Dan Gohman950a13c2015-09-16 16:51:30 +00001172SDValue WebAssemblyTargetLowering::LowerJumpTable(SDValue Op,
1173 SelectionDAG &DAG) const {
1174 // There's no need for a Wrapper node because we always incorporate a jump
Dan Gohman14026062016-03-08 03:18:12 +00001175 // table operand into a BR_TABLE instruction, rather than ever
Dan Gohmanbb7ce8e2015-11-20 03:02:49 +00001176 // materializing it in a register.
Dan Gohman950a13c2015-09-16 16:51:30 +00001177 const JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
1178 return DAG.getTargetJumpTable(JT->getIndex(), Op.getValueType(),
1179 JT->getTargetFlags());
1180}
1181
1182SDValue WebAssemblyTargetLowering::LowerBR_JT(SDValue Op,
1183 SelectionDAG &DAG) const {
1184 SDLoc DL(Op);
1185 SDValue Chain = Op.getOperand(0);
1186 const auto *JT = cast<JumpTableSDNode>(Op.getOperand(1));
1187 SDValue Index = Op.getOperand(2);
1188 assert(JT->getTargetFlags() == 0 && "WebAssembly doesn't set target flags");
1189
1190 SmallVector<SDValue, 8> Ops;
1191 Ops.push_back(Chain);
1192 Ops.push_back(Index);
1193
1194 MachineJumpTableInfo *MJTI = DAG.getMachineFunction().getJumpTableInfo();
1195 const auto &MBBs = MJTI->getJumpTables()[JT->getIndex()].MBBs;
1196
Dan Gohman14026062016-03-08 03:18:12 +00001197 // Add an operand for each case.
Heejin Ahnf208f632018-09-05 01:27:38 +00001198 for (auto MBB : MBBs)
1199 Ops.push_back(DAG.getBasicBlock(MBB));
Dan Gohman14026062016-03-08 03:18:12 +00001200
Dan Gohman950a13c2015-09-16 16:51:30 +00001201 // TODO: For now, we just pick something arbitrary for a default case for now.
1202 // We really want to sniff out the guard and put in the real default case (and
1203 // delete the guard).
1204 Ops.push_back(DAG.getBasicBlock(MBBs[0]));
1205
Dan Gohman14026062016-03-08 03:18:12 +00001206 return DAG.getNode(WebAssemblyISD::BR_TABLE, DL, MVT::Other, Ops);
Dan Gohman950a13c2015-09-16 16:51:30 +00001207}
1208
Dan Gohman35bfb242015-12-04 23:22:35 +00001209SDValue WebAssemblyTargetLowering::LowerVASTART(SDValue Op,
1210 SelectionDAG &DAG) const {
1211 SDLoc DL(Op);
1212 EVT PtrVT = getPointerTy(DAG.getMachineFunction().getDataLayout());
1213
Derek Schuff27501e22016-02-10 19:51:04 +00001214 auto *MFI = DAG.getMachineFunction().getInfo<WebAssemblyFunctionInfo>();
Dan Gohman35bfb242015-12-04 23:22:35 +00001215 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
Derek Schuff27501e22016-02-10 19:51:04 +00001216
1217 SDValue ArgN = DAG.getCopyFromReg(DAG.getEntryNode(), DL,
1218 MFI->getVarargBufferVreg(), PtrVT);
1219 return DAG.getStore(Op.getOperand(0), DL, ArgN, Op.getOperand(1),
Derek Schuff1a946e42016-07-15 19:35:43 +00001220 MachinePointerInfo(SV), 0);
Dan Gohman35bfb242015-12-04 23:22:35 +00001221}
1222
Heejin Ahnd6f48782019-01-30 03:21:57 +00001223SDValue WebAssemblyTargetLowering::LowerIntrinsic(SDValue Op,
1224 SelectionDAG &DAG) const {
1225 MachineFunction &MF = DAG.getMachineFunction();
1226 unsigned IntNo;
1227 switch (Op.getOpcode()) {
1228 case ISD::INTRINSIC_VOID:
1229 case ISD::INTRINSIC_W_CHAIN:
1230 IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
1231 break;
1232 case ISD::INTRINSIC_WO_CHAIN:
1233 IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
1234 break;
1235 default:
1236 llvm_unreachable("Invalid intrinsic");
1237 }
Heejin Ahn5ef4d5f2018-05-31 22:25:54 +00001238 SDLoc DL(Op);
Heejin Ahnd6f48782019-01-30 03:21:57 +00001239
Heejin Ahn5ef4d5f2018-05-31 22:25:54 +00001240 switch (IntNo) {
1241 default:
Heejin Ahn18c56a02019-02-04 19:13:39 +00001242 return SDValue(); // Don't custom lower most intrinsics.
Thomas Lively5d461c92018-10-03 23:02:23 +00001243
Heejin Ahn24faf852018-10-25 23:55:10 +00001244 case Intrinsic::wasm_lsda: {
Heejin Ahn24faf852018-10-25 23:55:10 +00001245 EVT VT = Op.getValueType();
1246 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1247 MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
1248 auto &Context = MF.getMMI().getContext();
1249 MCSymbol *S = Context.getOrCreateSymbol(Twine("GCC_except_table") +
1250 Twine(MF.getFunctionNumber()));
1251 return DAG.getNode(WebAssemblyISD::Wrapper, DL, VT,
1252 DAG.getMCSymbol(S, PtrVT));
1253 }
Heejin Ahnda419bd2018-11-14 02:46:21 +00001254
1255 case Intrinsic::wasm_throw: {
Heejin Ahnd6f48782019-01-30 03:21:57 +00001256 // We only support C++ exceptions for now
Heejin Ahnda419bd2018-11-14 02:46:21 +00001257 int Tag = cast<ConstantSDNode>(Op.getOperand(2).getNode())->getZExtValue();
Heejin Ahnd6f48782019-01-30 03:21:57 +00001258 if (Tag != CPP_EXCEPTION)
Heejin Ahnda419bd2018-11-14 02:46:21 +00001259 llvm_unreachable("Invalid tag!");
Heejin Ahnd6f48782019-01-30 03:21:57 +00001260 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1261 MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
1262 const char *SymName = MF.createExternalSymbolName("__cpp_exception");
Sam Cleggef4c66c2019-04-03 00:17:29 +00001263 SDValue SymNode = DAG.getNode(WebAssemblyISD::Wrapper, DL, PtrVT,
1264 DAG.getTargetExternalSymbol(SymName, PtrVT));
Heejin Ahnd6f48782019-01-30 03:21:57 +00001265 return DAG.getNode(WebAssemblyISD::THROW, DL,
1266 MVT::Other, // outchain type
1267 {
1268 Op.getOperand(0), // inchain
1269 SymNode, // exception symbol
1270 Op.getOperand(3) // thrown value
1271 });
Heejin Ahnda419bd2018-11-14 02:46:21 +00001272 }
1273 }
1274}
1275
1276SDValue
Thomas Lively64a39a12019-01-10 22:32:11 +00001277WebAssemblyTargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
1278 SelectionDAG &DAG) const {
Thomas Lively3d9ca002019-06-04 21:08:20 +00001279 SDLoc DL(Op);
Thomas Lively64a39a12019-01-10 22:32:11 +00001280 // If sign extension operations are disabled, allow sext_inreg only if operand
1281 // is a vector extract. SIMD does not depend on sign extension operations, but
1282 // allowing sext_inreg in this context lets us have simple patterns to select
1283 // extract_lane_s instructions. Expanding sext_inreg everywhere would be
1284 // simpler in this file, but would necessitate large and brittle patterns to
1285 // undo the expansion and select extract_lane_s instructions.
1286 assert(!Subtarget->hasSignExt() && Subtarget->hasSIMD128());
Thomas Lively3d9ca002019-06-04 21:08:20 +00001287 if (Op.getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
1288 const SDValue &Extract = Op.getOperand(0);
1289 MVT VecT = Extract.getOperand(0).getSimpleValueType();
1290 MVT ExtractedLaneT = static_cast<VTSDNode *>(Op.getOperand(1).getNode())
1291 ->getVT()
1292 .getSimpleVT();
1293 MVT ExtractedVecT =
1294 MVT::getVectorVT(ExtractedLaneT, 128 / ExtractedLaneT.getSizeInBits());
1295 if (ExtractedVecT == VecT)
1296 return Op;
1297 // Bitcast vector to appropriate type to ensure ISel pattern coverage
1298 const SDValue &Index = Extract.getOperand(1);
1299 unsigned IndexVal =
1300 static_cast<ConstantSDNode *>(Index.getNode())->getZExtValue();
1301 unsigned Scale =
1302 ExtractedVecT.getVectorNumElements() / VecT.getVectorNumElements();
1303 assert(Scale > 1);
1304 SDValue NewIndex =
1305 DAG.getConstant(IndexVal * Scale, DL, Index.getValueType());
1306 SDValue NewExtract = DAG.getNode(
1307 ISD::EXTRACT_VECTOR_ELT, DL, Extract.getValueType(),
1308 DAG.getBitcast(ExtractedVecT, Extract.getOperand(0)), NewIndex);
1309 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, Op.getValueType(),
1310 NewExtract, Op.getOperand(1));
1311 }
Thomas Lively64a39a12019-01-10 22:32:11 +00001312 // Otherwise expand
1313 return SDValue();
1314}
1315
Thomas Lively079816e2019-01-30 02:23:29 +00001316SDValue WebAssemblyTargetLowering::LowerBUILD_VECTOR(SDValue Op,
1317 SelectionDAG &DAG) const {
1318 SDLoc DL(Op);
1319 const EVT VecT = Op.getValueType();
1320 const EVT LaneT = Op.getOperand(0).getValueType();
1321 const size_t Lanes = Op.getNumOperands();
Thomas Livelyd5b7a4e2019-10-09 17:39:19 +00001322 bool CanSwizzle = Subtarget->hasUnimplementedSIMD128() && VecT == MVT::v16i8;
1323
1324 // BUILD_VECTORs are lowered to the instruction that initializes the highest
1325 // possible number of lanes at once followed by a sequence of replace_lane
1326 // instructions to individually initialize any remaining lanes.
1327
1328 // TODO: Tune this. For example, lanewise swizzling is very expensive, so
1329 // swizzled lanes should be given greater weight.
1330
1331 // TODO: Investigate building vectors by shuffling together vectors built by
1332 // separately specialized means.
1333
Thomas Lively079816e2019-01-30 02:23:29 +00001334 auto IsConstant = [](const SDValue &V) {
1335 return V.getOpcode() == ISD::Constant || V.getOpcode() == ISD::ConstantFP;
1336 };
1337
Thomas Livelyd5b7a4e2019-10-09 17:39:19 +00001338 // Returns the source vector and index vector pair if they exist. Checks for:
1339 // (extract_vector_elt
1340 // $src,
1341 // (sign_extend_inreg (extract_vector_elt $indices, $i))
1342 // )
1343 auto GetSwizzleSrcs = [](size_t I, const SDValue &Lane) {
1344 auto Bail = std::make_pair(SDValue(), SDValue());
1345 if (Lane->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
1346 return Bail;
1347 const SDValue &SwizzleSrc = Lane->getOperand(0);
1348 const SDValue &IndexExt = Lane->getOperand(1);
1349 if (IndexExt->getOpcode() != ISD::SIGN_EXTEND_INREG)
1350 return Bail;
1351 const SDValue &Index = IndexExt->getOperand(0);
1352 if (Index->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
1353 return Bail;
1354 const SDValue &SwizzleIndices = Index->getOperand(0);
1355 if (SwizzleSrc.getValueType() != MVT::v16i8 ||
1356 SwizzleIndices.getValueType() != MVT::v16i8 ||
1357 Index->getOperand(1)->getOpcode() != ISD::Constant ||
1358 Index->getConstantOperandVal(1) != I)
1359 return Bail;
1360 return std::make_pair(SwizzleSrc, SwizzleIndices);
1361 };
1362
1363 using ValueEntry = std::pair<SDValue, size_t>;
1364 SmallVector<ValueEntry, 16> SplatValueCounts;
1365
1366 using SwizzleEntry = std::pair<std::pair<SDValue, SDValue>, size_t>;
1367 SmallVector<SwizzleEntry, 16> SwizzleCounts;
1368
1369 auto AddCount = [](auto &Counts, const auto &Val) {
1370 auto CountIt = std::find_if(Counts.begin(), Counts.end(),
1371 [&Val](auto E) { return E.first == Val; });
1372 if (CountIt == Counts.end()) {
1373 Counts.emplace_back(Val, 1);
Thomas Lively079816e2019-01-30 02:23:29 +00001374 } else {
1375 CountIt->second++;
1376 }
Thomas Livelyd5b7a4e2019-10-09 17:39:19 +00001377 };
Thomas Lively079816e2019-01-30 02:23:29 +00001378
Thomas Livelyd5b7a4e2019-10-09 17:39:19 +00001379 auto GetMostCommon = [](auto &Counts) {
1380 auto CommonIt =
1381 std::max_element(Counts.begin(), Counts.end(),
1382 [](auto A, auto B) { return A.second < B.second; });
1383 assert(CommonIt != Counts.end() && "Unexpected all-undef build_vector");
1384 return *CommonIt;
1385 };
1386
1387 size_t NumConstantLanes = 0;
1388
1389 // Count eligible lanes for each type of vector creation op
1390 for (size_t I = 0; I < Lanes; ++I) {
1391 const SDValue &Lane = Op->getOperand(I);
1392 if (Lane.isUndef())
1393 continue;
1394
1395 AddCount(SplatValueCounts, Lane);
1396
1397 if (IsConstant(Lane)) {
1398 NumConstantLanes++;
1399 } else if (CanSwizzle) {
1400 auto SwizzleSrcs = GetSwizzleSrcs(I, Lane);
1401 if (SwizzleSrcs.first)
1402 AddCount(SwizzleCounts, SwizzleSrcs);
1403 }
1404 }
1405
1406 SDValue SplatValue;
1407 size_t NumSplatLanes;
1408 std::tie(SplatValue, NumSplatLanes) = GetMostCommon(SplatValueCounts);
1409
1410 SDValue SwizzleSrc;
1411 SDValue SwizzleIndices;
1412 size_t NumSwizzleLanes = 0;
1413 if (SwizzleCounts.size())
1414 std::forward_as_tuple(std::tie(SwizzleSrc, SwizzleIndices),
1415 NumSwizzleLanes) = GetMostCommon(SwizzleCounts);
1416
1417 // Predicate returning true if the lane is properly initialized by the
1418 // original instruction
1419 std::function<bool(size_t, const SDValue &)> IsLaneConstructed;
1420 SDValue Result;
Thomas Lively079816e2019-01-30 02:23:29 +00001421 if (Subtarget->hasUnimplementedSIMD128()) {
Thomas Livelyd5b7a4e2019-10-09 17:39:19 +00001422 // Prefer swizzles over vector consts over splats
1423 if (NumSwizzleLanes >= NumSplatLanes &&
1424 NumSwizzleLanes >= NumConstantLanes) {
1425 Result = DAG.getNode(WebAssemblyISD::SWIZZLE, DL, VecT, SwizzleSrc,
1426 SwizzleIndices);
1427 auto Swizzled = std::make_pair(SwizzleSrc, SwizzleIndices);
1428 IsLaneConstructed = [&, Swizzled](size_t I, const SDValue &Lane) {
1429 return Swizzled == GetSwizzleSrcs(I, Lane);
1430 };
1431 } else if (NumConstantLanes >= NumSplatLanes) {
Thomas Lively079816e2019-01-30 02:23:29 +00001432 SmallVector<SDValue, 16> ConstLanes;
1433 for (const SDValue &Lane : Op->op_values()) {
1434 if (IsConstant(Lane)) {
1435 ConstLanes.push_back(Lane);
1436 } else if (LaneT.isFloatingPoint()) {
1437 ConstLanes.push_back(DAG.getConstantFP(0, DL, LaneT));
1438 } else {
1439 ConstLanes.push_back(DAG.getConstant(0, DL, LaneT));
1440 }
1441 }
Thomas Livelyd5b7a4e2019-10-09 17:39:19 +00001442 Result = DAG.getBuildVector(VecT, DL, ConstLanes);
1443 IsLaneConstructed = [&](size_t _, const SDValue &Lane) {
1444 return IsConstant(Lane);
1445 };
Thomas Lively079816e2019-01-30 02:23:29 +00001446 }
1447 }
Thomas Livelyd5b7a4e2019-10-09 17:39:19 +00001448 if (!Result) {
1449 // Use a splat, but possibly a load_splat
1450 LoadSDNode *SplattedLoad;
1451 if (Subtarget->hasUnimplementedSIMD128() &&
1452 (SplattedLoad = dyn_cast<LoadSDNode>(SplatValue)) &&
1453 SplattedLoad->getMemoryVT() == VecT.getVectorElementType()) {
Thomas Lively3479fd22019-10-31 20:01:02 -07001454 Result = DAG.getMemIntrinsicNode(
1455 WebAssemblyISD::LOAD_SPLAT, DL, DAG.getVTList(VecT),
1456 {SplattedLoad->getChain(), SplattedLoad->getBasePtr(),
1457 SplattedLoad->getOffset()},
1458 SplattedLoad->getMemoryVT(), SplattedLoad->getMemOperand());
Thomas Livelyd5b7a4e2019-10-09 17:39:19 +00001459 } else {
1460 Result = DAG.getSplatBuildVector(VecT, DL, SplatValue);
1461 }
1462 IsLaneConstructed = [&](size_t _, const SDValue &Lane) {
1463 return Lane == SplatValue;
1464 };
Thomas Lively99d3dd22019-09-23 20:42:12 +00001465 }
Thomas Livelyd5b7a4e2019-10-09 17:39:19 +00001466
1467 // Add replace_lane instructions for any unhandled values
Thomas Lively079816e2019-01-30 02:23:29 +00001468 for (size_t I = 0; I < Lanes; ++I) {
1469 const SDValue &Lane = Op->getOperand(I);
Thomas Livelyd5b7a4e2019-10-09 17:39:19 +00001470 if (!Lane.isUndef() && !IsLaneConstructed(I, Lane))
Thomas Lively079816e2019-01-30 02:23:29 +00001471 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VecT, Result, Lane,
1472 DAG.getConstant(I, DL, MVT::i32));
1473 }
Thomas Livelyd5b7a4e2019-10-09 17:39:19 +00001474
Thomas Lively079816e2019-01-30 02:23:29 +00001475 return Result;
1476}
1477
Thomas Lively64a39a12019-01-10 22:32:11 +00001478SDValue
Thomas Livelya0d25812018-09-07 21:54:46 +00001479WebAssemblyTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
1480 SelectionDAG &DAG) const {
1481 SDLoc DL(Op);
1482 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Op.getNode())->getMask();
1483 MVT VecType = Op.getOperand(0).getSimpleValueType();
1484 assert(VecType.is128BitVector() && "Unexpected shuffle vector type");
1485 size_t LaneBytes = VecType.getVectorElementType().getSizeInBits() / 8;
1486
1487 // Space for two vector args and sixteen mask indices
1488 SDValue Ops[18];
1489 size_t OpIdx = 0;
1490 Ops[OpIdx++] = Op.getOperand(0);
1491 Ops[OpIdx++] = Op.getOperand(1);
1492
1493 // Expand mask indices to byte indices and materialize them as operands
Heejin Ahn18c56a02019-02-04 19:13:39 +00001494 for (int M : Mask) {
Thomas Livelya0d25812018-09-07 21:54:46 +00001495 for (size_t J = 0; J < LaneBytes; ++J) {
Thomas Lively11a332d02018-10-19 19:08:06 +00001496 // Lower undefs (represented by -1 in mask) to zero
Heejin Ahn18c56a02019-02-04 19:13:39 +00001497 uint64_t ByteIndex = M == -1 ? 0 : (uint64_t)M * LaneBytes + J;
Thomas Lively11a332d02018-10-19 19:08:06 +00001498 Ops[OpIdx++] = DAG.getConstant(ByteIndex, DL, MVT::i32);
Thomas Livelya0d25812018-09-07 21:54:46 +00001499 }
1500 }
1501
Thomas Livelyed951342018-10-24 23:27:40 +00001502 return DAG.getNode(WebAssemblyISD::SHUFFLE, DL, Op.getValueType(), Ops);
Thomas Livelya0d25812018-09-07 21:54:46 +00001503}
1504
Thomas Livelyecb7daf2019-11-01 10:21:00 -07001505SDValue WebAssemblyTargetLowering::LowerSETCC(SDValue Op,
1506 SelectionDAG &DAG) const {
1507 SDLoc DL(Op);
1508 // The legalizer does not know how to expand the comparison modes of i64x2
1509 // vectors because no comparison modes are supported. We could solve this by
1510 // expanding all i64x2 SETCC nodes, but that seems to expand f64x2 SETCC nodes
1511 // (which return i64x2 results) as well. So instead we manually unroll i64x2
1512 // comparisons here.
Thomas Livelyecb7daf2019-11-01 10:21:00 -07001513 assert(Op->getOperand(0)->getSimpleValueType(0) == MVT::v2i64);
1514 SmallVector<SDValue, 2> LHS, RHS;
1515 DAG.ExtractVectorElements(Op->getOperand(0), LHS);
1516 DAG.ExtractVectorElements(Op->getOperand(1), RHS);
1517 const SDValue &CC = Op->getOperand(2);
1518 auto MakeLane = [&](unsigned I) {
1519 return DAG.getNode(ISD::SELECT_CC, DL, MVT::i64, LHS[I], RHS[I],
1520 DAG.getConstant(uint64_t(-1), DL, MVT::i64),
1521 DAG.getConstant(uint64_t(0), DL, MVT::i64), CC);
1522 };
1523 return DAG.getBuildVector(Op->getValueType(0), DL,
1524 {MakeLane(0), MakeLane(1)});
1525}
1526
Thomas Livelyfb84fd72018-11-02 00:06:56 +00001527SDValue
1528WebAssemblyTargetLowering::LowerAccessVectorElement(SDValue Op,
1529 SelectionDAG &DAG) const {
1530 // Allow constant lane indices, expand variable lane indices
1531 SDNode *IdxNode = Op.getOperand(Op.getNumOperands() - 1).getNode();
1532 if (isa<ConstantSDNode>(IdxNode) || IdxNode->isUndef())
1533 return Op;
1534 else
1535 // Perform default expansion
1536 return SDValue();
1537}
1538
Heejin Ahn18c56a02019-02-04 19:13:39 +00001539static SDValue unrollVectorShift(SDValue Op, SelectionDAG &DAG) {
Thomas Lively6bf2b402019-01-15 02:16:03 +00001540 EVT LaneT = Op.getSimpleValueType().getVectorElementType();
1541 // 32-bit and 64-bit unrolled shifts will have proper semantics
1542 if (LaneT.bitsGE(MVT::i32))
1543 return DAG.UnrollVectorOp(Op.getNode());
1544 // Otherwise mask the shift value to get proper semantics from 32-bit shift
1545 SDLoc DL(Op);
1546 SDValue ShiftVal = Op.getOperand(1);
1547 uint64_t MaskVal = LaneT.getSizeInBits() - 1;
1548 SDValue MaskedShiftVal = DAG.getNode(
1549 ISD::AND, // mask opcode
1550 DL, ShiftVal.getValueType(), // masked value type
1551 ShiftVal, // original shift value operand
1552 DAG.getConstant(MaskVal, DL, ShiftVal.getValueType()) // mask operand
1553 );
1554
1555 return DAG.UnrollVectorOp(
1556 DAG.getNode(Op.getOpcode(), // original shift opcode
1557 DL, Op.getValueType(), // original return type
1558 Op.getOperand(0), // original vector operand,
1559 MaskedShiftVal // new masked shift value operand
1560 )
1561 .getNode());
1562}
1563
Thomas Lively55735d52018-10-20 01:31:18 +00001564SDValue WebAssemblyTargetLowering::LowerShift(SDValue Op,
1565 SelectionDAG &DAG) const {
1566 SDLoc DL(Op);
Thomas Livelyb2382c82018-11-02 00:39:57 +00001567
1568 // Only manually lower vector shifts
1569 assert(Op.getSimpleValueType().isVector());
1570
1571 // Unroll non-splat vector shifts
1572 BuildVectorSDNode *ShiftVec;
1573 SDValue SplatVal;
1574 if (!(ShiftVec = dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode())) ||
1575 !(SplatVal = ShiftVec->getSplatValue()))
Heejin Ahn18c56a02019-02-04 19:13:39 +00001576 return unrollVectorShift(Op, DAG);
Thomas Livelyb2382c82018-11-02 00:39:57 +00001577
1578 // All splats except i64x2 const splats are handled by patterns
Heejin Ahn18c56a02019-02-04 19:13:39 +00001579 auto *SplatConst = dyn_cast<ConstantSDNode>(SplatVal);
Thomas Livelyb2382c82018-11-02 00:39:57 +00001580 if (!SplatConst || Op.getSimpleValueType() != MVT::v2i64)
Thomas Lively55735d52018-10-20 01:31:18 +00001581 return Op;
Thomas Livelyb2382c82018-11-02 00:39:57 +00001582
1583 // i64x2 const splats are custom lowered to avoid unnecessary wraps
Thomas Lively55735d52018-10-20 01:31:18 +00001584 unsigned Opcode;
1585 switch (Op.getOpcode()) {
1586 case ISD::SHL:
1587 Opcode = WebAssemblyISD::VEC_SHL;
1588 break;
1589 case ISD::SRA:
1590 Opcode = WebAssemblyISD::VEC_SHR_S;
1591 break;
1592 case ISD::SRL:
1593 Opcode = WebAssemblyISD::VEC_SHR_U;
1594 break;
1595 default:
1596 llvm_unreachable("unexpected opcode");
Thomas Lively55735d52018-10-20 01:31:18 +00001597 }
Thomas Livelyb2382c82018-11-02 00:39:57 +00001598 APInt Shift = SplatConst->getAPIntValue().zextOrTrunc(32);
Thomas Lively55735d52018-10-20 01:31:18 +00001599 return DAG.getNode(Opcode, DL, Op.getValueType(), Op.getOperand(0),
Thomas Livelyb2382c82018-11-02 00:39:57 +00001600 DAG.getConstant(Shift, DL, MVT::i32));
Thomas Lively55735d52018-10-20 01:31:18 +00001601}
1602
Dan Gohman10e730a2015-06-29 23:51:55 +00001603//===----------------------------------------------------------------------===//
1604// WebAssembly Optimization Hooks
1605//===----------------------------------------------------------------------===//