blob: e91a9ea037675079c8aa07584676818060b7dcac [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 }
65 if (Subtarget->hasUnimplementedSIMD128()) {
66 addRegisterClass(MVT::v2i64, &WebAssembly::V128RegClass);
67 addRegisterClass(MVT::v2f64, &WebAssembly::V128RegClass);
Derek Schuff39bf39f2016-08-02 23:16:09 +000068 }
JF Bastienb9073fb2015-07-22 21:28:15 +000069 // Compute derived properties from the register classes.
70 computeRegisterProperties(Subtarget->getRegisterInfo());
71
JF Bastienaf111db2015-08-24 22:16:48 +000072 setOperationAction(ISD::GlobalAddress, MVTPtr, Custom);
Dan Gohman2c8fe6a2015-11-25 16:44:29 +000073 setOperationAction(ISD::ExternalSymbol, MVTPtr, Custom);
Dan Gohman950a13c2015-09-16 16:51:30 +000074 setOperationAction(ISD::JumpTable, MVTPtr, Custom);
Derek Schuff51699a82016-02-12 22:56:03 +000075 setOperationAction(ISD::BlockAddress, MVTPtr, Custom);
76 setOperationAction(ISD::BRIND, MVT::Other, Custom);
JF Bastienaf111db2015-08-24 22:16:48 +000077
Dan Gohman35bfb242015-12-04 23:22:35 +000078 // Take the default expansion for va_arg, va_copy, and va_end. There is no
79 // default action for va_start, so we do that custom.
80 setOperationAction(ISD::VASTART, MVT::Other, Custom);
81 setOperationAction(ISD::VAARG, MVT::Other, Expand);
82 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
83 setOperationAction(ISD::VAEND, MVT::Other, Expand);
84
Thomas Livelyebd4c902018-09-12 17:56:00 +000085 for (auto T : {MVT::f32, MVT::f64, MVT::v4f32, MVT::v2f64}) {
JF Bastienda06bce2015-08-11 21:02:46 +000086 // Don't expand the floating-point types to constant pools.
87 setOperationAction(ISD::ConstantFP, T, Legal);
88 // Expand floating-point comparisons.
89 for (auto CC : {ISD::SETO, ISD::SETUO, ISD::SETUEQ, ISD::SETONE,
90 ISD::SETULT, ISD::SETULE, ISD::SETUGT, ISD::SETUGE})
91 setCondCodeAction(CC, T, Expand);
Dan Gohman32907a62015-08-20 22:57:13 +000092 // Expand floating-point library function operators.
Heejin Ahnf208f632018-09-05 01:27:38 +000093 for (auto Op :
94 {ISD::FSIN, ISD::FCOS, ISD::FSINCOS, ISD::FPOW, ISD::FREM, ISD::FMA})
Dan Gohman32907a62015-08-20 22:57:13 +000095 setOperationAction(Op, T, Expand);
Dan Gohman896e53f2015-08-24 18:23:13 +000096 // Note supported floating-point library function operators that otherwise
97 // default to expand.
Dan Gohman7a6b9822015-11-29 22:32:02 +000098 for (auto Op :
99 {ISD::FCEIL, ISD::FFLOOR, ISD::FTRUNC, ISD::FNEARBYINT, ISD::FRINT})
Dan Gohman896e53f2015-08-24 18:23:13 +0000100 setOperationAction(Op, T, Legal);
Thomas Lively30f1d692018-10-24 22:49:55 +0000101 // Support minimum and maximum, which otherwise default to expand.
102 setOperationAction(ISD::FMINIMUM, T, Legal);
103 setOperationAction(ISD::FMAXIMUM, T, Legal);
Dan Gohmana63e8eb2017-02-22 16:28:00 +0000104 // WebAssembly currently has no builtin f16 support.
105 setOperationAction(ISD::FP16_TO_FP, T, Expand);
106 setOperationAction(ISD::FP_TO_FP16, T, Expand);
107 setLoadExtAction(ISD::EXTLOAD, T, MVT::f16, Expand);
108 setTruncStoreAction(T, MVT::f16, Expand);
JF Bastienda06bce2015-08-11 21:02:46 +0000109 }
Dan Gohman32907a62015-08-20 22:57:13 +0000110
Thomas Lively66ea30c2018-11-29 22:01:01 +0000111 // Expand unavailable integer operations.
112 for (auto Op :
113 {ISD::BSWAP, ISD::SMUL_LOHI, ISD::UMUL_LOHI, ISD::MULHS, ISD::MULHU,
114 ISD::SDIVREM, ISD::UDIVREM, ISD::SHL_PARTS, ISD::SRA_PARTS,
115 ISD::SRL_PARTS, ISD::ADDC, ISD::ADDE, ISD::SUBC, ISD::SUBE}) {
Thomas Lively2b8b2972019-01-26 01:25:37 +0000116 for (auto T : {MVT::i32, MVT::i64})
Dan Gohman32907a62015-08-20 22:57:13 +0000117 setOperationAction(Op, T, Expand);
Thomas Lively2b8b2972019-01-26 01:25:37 +0000118 if (Subtarget->hasSIMD128())
119 for (auto T : {MVT::v16i8, MVT::v8i16, MVT::v4i32})
Thomas Lively66ea30c2018-11-29 22:01:01 +0000120 setOperationAction(Op, T, Expand);
Thomas Lively64a39a12019-01-10 22:32:11 +0000121 if (Subtarget->hasUnimplementedSIMD128())
Thomas Lively2b8b2972019-01-26 01:25:37 +0000122 setOperationAction(Op, MVT::v2i64, Expand);
Thomas Livelyb2382c82018-11-02 00:39:57 +0000123 }
Thomas Lively55735d52018-10-20 01:31:18 +0000124
Thomas Lively2b8b2972019-01-26 01:25:37 +0000125 // SIMD-specific configuration
126 if (Subtarget->hasSIMD128()) {
127 // Support saturating add for i8x16 and i16x8
128 for (auto Op : {ISD::SADDSAT, ISD::UADDSAT})
129 for (auto T : {MVT::v16i8, MVT::v8i16})
130 setOperationAction(Op, T, Legal);
131
Thomas Lively079816e2019-01-30 02:23:29 +0000132 // Custom lower BUILD_VECTORs to minimize number of replace_lanes
133 for (auto T : {MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v4f32})
134 setOperationAction(ISD::BUILD_VECTOR, T, Custom);
135 if (Subtarget->hasUnimplementedSIMD128())
136 for (auto T : {MVT::v2i64, MVT::v2f64})
137 setOperationAction(ISD::BUILD_VECTOR, T, Custom);
138
Thomas Lively2b8b2972019-01-26 01:25:37 +0000139 // We have custom shuffle lowering to expose the shuffle mask
140 for (auto T : {MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v4f32})
141 setOperationAction(ISD::VECTOR_SHUFFLE, T, Custom);
142 if (Subtarget->hasUnimplementedSIMD128())
143 for (auto T: {MVT::v2i64, MVT::v2f64})
144 setOperationAction(ISD::VECTOR_SHUFFLE, T, Custom);
145
146 // Custom lowering since wasm shifts must have a scalar shift amount
147 for (auto Op : {ISD::SHL, ISD::SRA, ISD::SRL}) {
148 for (auto T : {MVT::v16i8, MVT::v8i16, MVT::v4i32})
149 setOperationAction(Op, T, Custom);
150 if (Subtarget->hasUnimplementedSIMD128())
151 setOperationAction(Op, MVT::v2i64, Custom);
152 }
153
154 // Custom lower lane accesses to expand out variable indices
155 for (auto Op : {ISD::EXTRACT_VECTOR_ELT, ISD::INSERT_VECTOR_ELT}) {
156 for (auto T : {MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v4f32})
157 setOperationAction(Op, T, Custom);
158 if (Subtarget->hasUnimplementedSIMD128())
159 for (auto T : {MVT::v2i64, MVT::v2f64})
160 setOperationAction(Op, T, Custom);
161 }
162
163 // There is no i64x2.mul instruction
164 setOperationAction(ISD::MUL, MVT::v2i64, Expand);
165
166 // There are no vector select instructions
Thomas Lively38c902b2018-11-09 01:38:44 +0000167 for (auto Op : {ISD::VSELECT, ISD::SELECT_CC, ISD::SELECT}) {
168 for (auto T : {MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v4f32})
169 setOperationAction(Op, T, Expand);
Thomas Lively64a39a12019-01-10 22:32:11 +0000170 if (Subtarget->hasUnimplementedSIMD128())
Thomas Lively38c902b2018-11-09 01:38:44 +0000171 for (auto T : {MVT::v2i64, MVT::v2f64})
172 setOperationAction(Op, T, Expand);
173 }
Thomas Livelyd4891a12018-11-01 00:01:02 +0000174
Thomas Lively43876ae72019-03-02 03:32:25 +0000175 // Expand integer operations supported for scalars but not SIMD
176 for (auto Op : {ISD::CTLZ, ISD::CTTZ, ISD::CTPOP, ISD::SDIV, ISD::UDIV,
177 ISD::SREM, ISD::UREM, ISD::ROTL, ISD::ROTR}) {
178 for (auto T : {MVT::v16i8, MVT::v8i16, MVT::v4i32})
179 setOperationAction(Op, T, Expand);
180 if (Subtarget->hasUnimplementedSIMD128())
181 setOperationAction(Op, MVT::v2i64, Expand);
182 }
183
Thomas Lively3a937562019-12-13 17:08:04 -0800184 // But we do have integer min and max operations
185 if (Subtarget->hasUnimplementedSIMD128()) {
186 for (auto Op : {ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX})
187 for (auto T : {MVT::v16i8, MVT::v8i16, MVT::v4i32})
188 setOperationAction(Op, T, Legal);
189 }
190
Thomas Lively43876ae72019-03-02 03:32:25 +0000191 // Expand float operations supported for scalars but not SIMD
192 for (auto Op : {ISD::FCEIL, ISD::FFLOOR, ISD::FTRUNC, ISD::FNEARBYINT,
Thomas Lively55229f62019-05-24 00:15:04 +0000193 ISD::FCOPYSIGN, ISD::FLOG, ISD::FLOG2, ISD::FLOG10,
194 ISD::FEXP, ISD::FEXP2, ISD::FRINT}) {
Thomas Lively43876ae72019-03-02 03:32:25 +0000195 setOperationAction(Op, MVT::v4f32, Expand);
196 if (Subtarget->hasUnimplementedSIMD128())
197 setOperationAction(Op, MVT::v2f64, Expand);
198 }
199
Thomas Livelyecb7daf2019-11-01 10:21:00 -0700200 // Expand operations not supported for i64x2 vectors
201 if (Subtarget->hasUnimplementedSIMD128())
202 for (unsigned CC = 0; CC < ISD::SETCC_INVALID; ++CC)
203 setCondCodeAction(static_cast<ISD::CondCode>(CC), MVT::v2i64, Custom);
204
Thomas Lively2b8b2972019-01-26 01:25:37 +0000205 // Expand additional SIMD ops that V8 hasn't implemented yet
206 if (!Subtarget->hasUnimplementedSIMD128()) {
207 setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
208 setOperationAction(ISD::FDIV, MVT::v4f32, Expand);
209 }
210 }
211
Dan Gohman32907a62015-08-20 22:57:13 +0000212 // As a special case, these operators use the type to mean the type to
213 // sign-extend from.
Derek Schuffa519fe52017-09-13 00:29:06 +0000214 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
Dan Gohman5d2b9352018-01-19 17:16:24 +0000215 if (!Subtarget->hasSignExt()) {
Thomas Lively64a39a12019-01-10 22:32:11 +0000216 // Sign extends are legal only when extending a vector extract
217 auto Action = Subtarget->hasSIMD128() ? Custom : Expand;
Derek Schuffa519fe52017-09-13 00:29:06 +0000218 for (auto T : {MVT::i8, MVT::i16, MVT::i32})
Thomas Lively64a39a12019-01-10 22:32:11 +0000219 setOperationAction(ISD::SIGN_EXTEND_INREG, T, Action);
Derek Schuffa519fe52017-09-13 00:29:06 +0000220 }
Graham Hunter1a9195d2019-09-17 10:19:23 +0000221 for (auto T : MVT::integer_fixedlen_vector_valuetypes())
Thomas Lively5ea17d42018-10-20 01:35:23 +0000222 setOperationAction(ISD::SIGN_EXTEND_INREG, T, Expand);
Dan Gohman32907a62015-08-20 22:57:13 +0000223
224 // Dynamic stack allocation: use the default expansion.
225 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
226 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
Dan Gohman2683a552015-08-24 22:31:52 +0000227 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVTPtr, Expand);
JF Bastien73ff6af2015-08-31 22:24:11 +0000228
Derek Schuff9769deb2015-12-11 23:49:46 +0000229 setOperationAction(ISD::FrameIndex, MVT::i32, Custom);
Derek Schuffaadc89c2016-02-16 18:18:36 +0000230 setOperationAction(ISD::CopyToReg, MVT::Other, Custom);
Derek Schuff9769deb2015-12-11 23:49:46 +0000231
Dan Gohman950a13c2015-09-16 16:51:30 +0000232 // Expand these forms; we pattern-match the forms that we can handle in isel.
233 for (auto T : {MVT::i32, MVT::i64, MVT::f32, MVT::f64})
234 for (auto Op : {ISD::BR_CC, ISD::SELECT_CC})
235 setOperationAction(Op, T, Expand);
236
237 // We have custom switch handling.
238 setOperationAction(ISD::BR_JT, MVT::Other, Custom);
239
JF Bastien73ff6af2015-08-31 22:24:11 +0000240 // WebAssembly doesn't have:
241 // - Floating-point extending loads.
242 // - Floating-point truncating stores.
243 // - i1 extending loads.
Thomas Lively81125f72019-09-27 02:06:50 +0000244 // - truncating SIMD stores and most extending loads
Dan Gohman60bddf12015-12-10 02:07:53 +0000245 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f32, Expand);
JF Bastien73ff6af2015-08-31 22:24:11 +0000246 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
247 for (auto T : MVT::integer_valuetypes())
248 for (auto Ext : {ISD::EXTLOAD, ISD::ZEXTLOAD, ISD::SEXTLOAD})
249 setLoadExtAction(Ext, T, MVT::i1, Promote);
Thomas Lively325c9c52018-10-25 01:46:07 +0000250 if (Subtarget->hasSIMD128()) {
251 for (auto T : {MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64, MVT::v4f32,
252 MVT::v2f64}) {
Graham Hunter1a9195d2019-09-17 10:19:23 +0000253 for (auto MemT : MVT::fixedlen_vector_valuetypes()) {
Thomas Lively325c9c52018-10-25 01:46:07 +0000254 if (MVT(T) != MemT) {
255 setTruncStoreAction(T, MemT, Expand);
256 for (auto Ext : {ISD::EXTLOAD, ISD::ZEXTLOAD, ISD::SEXTLOAD})
257 setLoadExtAction(Ext, T, MemT, Expand);
258 }
259 }
260 }
Thomas Lively81125f72019-09-27 02:06:50 +0000261 // But some vector extending loads are legal
262 if (Subtarget->hasUnimplementedSIMD128()) {
263 for (auto Ext : {ISD::EXTLOAD, ISD::SEXTLOAD, ISD::ZEXTLOAD}) {
264 setLoadExtAction(Ext, MVT::v8i16, MVT::v8i8, Legal);
265 setLoadExtAction(Ext, MVT::v4i32, MVT::v4i16, Legal);
266 setLoadExtAction(Ext, MVT::v2i64, MVT::v2i32, Legal);
267 }
268 }
Thomas Lively325c9c52018-10-25 01:46:07 +0000269 }
Derek Schuffffa143c2015-11-10 00:30:57 +0000270
Thomas Lively33f87b82019-01-28 23:44:31 +0000271 // Don't do anything clever with build_pairs
272 setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand);
273
Derek Schuffffa143c2015-11-10 00:30:57 +0000274 // Trap lowers to wasm unreachable
275 setOperationAction(ISD::TRAP, MVT::Other, Legal);
Derek Schuff18ba1922017-08-30 18:07:45 +0000276
Heejin Ahn5ef4d5f2018-05-31 22:25:54 +0000277 // Exception handling intrinsics
278 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
Heejin Ahnda419bd2018-11-14 02:46:21 +0000279 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
Heejin Ahn5ef4d5f2018-05-31 22:25:54 +0000280
Derek Schuff18ba1922017-08-30 18:07:45 +0000281 setMaxAtomicSizeInBitsSupported(64);
Thomas Livelyd99af232019-02-05 00:49:55 +0000282
Dan Gohman3a7532e2019-04-30 19:17:59 +0000283 // Override the __gnu_f2h_ieee/__gnu_h2f_ieee names so that the f32 name is
284 // consistent with the f64 and f128 names.
285 setLibcallName(RTLIB::FPEXT_F16_F32, "__extendhfsf2");
286 setLibcallName(RTLIB::FPROUND_F32_F16, "__truncsfhf2");
287
Thomas Lively1a3cbe72019-05-23 01:24:01 +0000288 // Define the emscripten name for return address helper.
289 // TODO: when implementing other WASM backends, make this generic or only do
290 // this on emscripten depending on what they end up doing.
291 setLibcallName(RTLIB::RETURN_ADDRESS, "emscripten_return_address");
292
Heejin Ahnb9f282d2019-04-23 21:30:30 +0000293 // Always convert switches to br_tables unless there is only one case, which
294 // is equivalent to a simple branch. This reduces code size for wasm, and we
295 // defer possible jump table optimizations to the VM.
296 setMinimumJumpTableEntries(2);
Dan Gohmanbfaf7e12015-07-02 21:36:25 +0000297}
Dan Gohman10e730a2015-06-29 23:51:55 +0000298
Heejin Ahne8653bb2018-08-07 00:22:22 +0000299TargetLowering::AtomicExpansionKind
300WebAssemblyTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
301 // We have wasm instructions for these
302 switch (AI->getOperation()) {
303 case AtomicRMWInst::Add:
304 case AtomicRMWInst::Sub:
305 case AtomicRMWInst::And:
306 case AtomicRMWInst::Or:
307 case AtomicRMWInst::Xor:
308 case AtomicRMWInst::Xchg:
309 return AtomicExpansionKind::None;
310 default:
311 break;
312 }
313 return AtomicExpansionKind::CmpXChg;
314}
315
Dan Gohman7b634842015-08-24 18:44:37 +0000316FastISel *WebAssemblyTargetLowering::createFastISel(
317 FunctionLoweringInfo &FuncInfo, const TargetLibraryInfo *LibInfo) const {
318 return WebAssembly::createFastISel(FuncInfo, LibInfo);
319}
320
Dan Gohman7a6b9822015-11-29 22:32:02 +0000321MVT WebAssemblyTargetLowering::getScalarShiftAmountTy(const DataLayout & /*DL*/,
JF Bastienfda53372015-08-03 00:00:11 +0000322 EVT VT) const {
Dan Gohmana8483752015-12-10 00:26:26 +0000323 unsigned BitWidth = NextPowerOf2(VT.getSizeInBits() - 1);
Heejin Ahnf208f632018-09-05 01:27:38 +0000324 if (BitWidth > 1 && BitWidth < 8)
325 BitWidth = 8;
Dan Gohman41729532015-12-16 23:25:51 +0000326
327 if (BitWidth > 64) {
Dan Gohmana01e8bd2016-05-14 02:15:47 +0000328 // The shift will be lowered to a libcall, and compiler-rt libcalls expect
329 // the count to be an i32.
330 BitWidth = 32;
Dan Gohman41729532015-12-16 23:25:51 +0000331 assert(BitWidth >= Log2_32_Ceil(VT.getSizeInBits()) &&
Dan Gohmana01e8bd2016-05-14 02:15:47 +0000332 "32-bit shift counts ought to be enough for anyone");
Dan Gohman41729532015-12-16 23:25:51 +0000333 }
334
Dan Gohmana8483752015-12-10 00:26:26 +0000335 MVT Result = MVT::getIntegerVT(BitWidth);
336 assert(Result != MVT::INVALID_SIMPLE_VALUE_TYPE &&
337 "Unable to represent scalar shift amount type");
338 return Result;
JF Bastienfda53372015-08-03 00:00:11 +0000339}
340
Dan Gohmancdd48b82017-11-28 01:13:40 +0000341// Lower an fp-to-int conversion operator from the LLVM opcode, which has an
342// undefined result on invalid/overflow, to the WebAssembly opcode, which
343// traps on invalid/overflow.
Heejin Ahnf208f632018-09-05 01:27:38 +0000344static MachineBasicBlock *LowerFPToInt(MachineInstr &MI, DebugLoc DL,
345 MachineBasicBlock *BB,
346 const TargetInstrInfo &TII,
347 bool IsUnsigned, bool Int64,
348 bool Float64, unsigned LoweredOpcode) {
Dan Gohmancdd48b82017-11-28 01:13:40 +0000349 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
350
Daniel Sanders05c145d2019-08-12 22:40:45 +0000351 Register OutReg = MI.getOperand(0).getReg();
352 Register InReg = MI.getOperand(1).getReg();
Dan Gohmancdd48b82017-11-28 01:13:40 +0000353
354 unsigned Abs = Float64 ? WebAssembly::ABS_F64 : WebAssembly::ABS_F32;
355 unsigned FConst = Float64 ? WebAssembly::CONST_F64 : WebAssembly::CONST_F32;
356 unsigned LT = Float64 ? WebAssembly::LT_F64 : WebAssembly::LT_F32;
Dan Gohman580c1022017-11-29 20:20:11 +0000357 unsigned GE = Float64 ? WebAssembly::GE_F64 : WebAssembly::GE_F32;
Dan Gohmancdd48b82017-11-28 01:13:40 +0000358 unsigned IConst = Int64 ? WebAssembly::CONST_I64 : WebAssembly::CONST_I32;
Dan Gohman580c1022017-11-29 20:20:11 +0000359 unsigned Eqz = WebAssembly::EQZ_I32;
360 unsigned And = WebAssembly::AND_I32;
Dan Gohmancdd48b82017-11-28 01:13:40 +0000361 int64_t Limit = Int64 ? INT64_MIN : INT32_MIN;
362 int64_t Substitute = IsUnsigned ? 0 : Limit;
363 double CmpVal = IsUnsigned ? -(double)Limit * 2.0 : -(double)Limit;
David Blaikie21109242017-12-15 23:52:06 +0000364 auto &Context = BB->getParent()->getFunction().getContext();
Dan Gohmancdd48b82017-11-28 01:13:40 +0000365 Type *Ty = Float64 ? Type::getDoubleTy(Context) : Type::getFloatTy(Context);
366
Heejin Ahn18c56a02019-02-04 19:13:39 +0000367 const BasicBlock *LLVMBB = BB->getBasicBlock();
Dan Gohmancdd48b82017-11-28 01:13:40 +0000368 MachineFunction *F = BB->getParent();
Heejin Ahn18c56a02019-02-04 19:13:39 +0000369 MachineBasicBlock *TrueMBB = F->CreateMachineBasicBlock(LLVMBB);
370 MachineBasicBlock *FalseMBB = F->CreateMachineBasicBlock(LLVMBB);
371 MachineBasicBlock *DoneMBB = F->CreateMachineBasicBlock(LLVMBB);
Dan Gohmancdd48b82017-11-28 01:13:40 +0000372
373 MachineFunction::iterator It = ++BB->getIterator();
374 F->insert(It, FalseMBB);
375 F->insert(It, TrueMBB);
376 F->insert(It, DoneMBB);
377
378 // Transfer the remainder of BB and its successor edges to DoneMBB.
Heejin Ahn5c644c92019-03-05 21:05:09 +0000379 DoneMBB->splice(DoneMBB->begin(), BB, std::next(MI.getIterator()), BB->end());
Dan Gohmancdd48b82017-11-28 01:13:40 +0000380 DoneMBB->transferSuccessorsAndUpdatePHIs(BB);
381
382 BB->addSuccessor(TrueMBB);
383 BB->addSuccessor(FalseMBB);
384 TrueMBB->addSuccessor(DoneMBB);
385 FalseMBB->addSuccessor(DoneMBB);
386
Dan Gohman580c1022017-11-29 20:20:11 +0000387 unsigned Tmp0, Tmp1, CmpReg, EqzReg, FalseReg, TrueReg;
Dan Gohmancdd48b82017-11-28 01:13:40 +0000388 Tmp0 = MRI.createVirtualRegister(MRI.getRegClass(InReg));
389 Tmp1 = MRI.createVirtualRegister(MRI.getRegClass(InReg));
Dan Gohman580c1022017-11-29 20:20:11 +0000390 CmpReg = MRI.createVirtualRegister(&WebAssembly::I32RegClass);
391 EqzReg = MRI.createVirtualRegister(&WebAssembly::I32RegClass);
392 FalseReg = MRI.createVirtualRegister(MRI.getRegClass(OutReg));
393 TrueReg = MRI.createVirtualRegister(MRI.getRegClass(OutReg));
Dan Gohmancdd48b82017-11-28 01:13:40 +0000394
395 MI.eraseFromParent();
Dan Gohman580c1022017-11-29 20:20:11 +0000396 // For signed numbers, we can do a single comparison to determine whether
397 // fabs(x) is within range.
Dan Gohmancdd48b82017-11-28 01:13:40 +0000398 if (IsUnsigned) {
399 Tmp0 = InReg;
400 } else {
Heejin Ahnf208f632018-09-05 01:27:38 +0000401 BuildMI(BB, DL, TII.get(Abs), Tmp0).addReg(InReg);
Dan Gohmancdd48b82017-11-28 01:13:40 +0000402 }
403 BuildMI(BB, DL, TII.get(FConst), Tmp1)
404 .addFPImm(cast<ConstantFP>(ConstantFP::get(Ty, CmpVal)));
Heejin Ahnf208f632018-09-05 01:27:38 +0000405 BuildMI(BB, DL, TII.get(LT), CmpReg).addReg(Tmp0).addReg(Tmp1);
Dan Gohman580c1022017-11-29 20:20:11 +0000406
407 // For unsigned numbers, we have to do a separate comparison with zero.
408 if (IsUnsigned) {
409 Tmp1 = MRI.createVirtualRegister(MRI.getRegClass(InReg));
Daniel Sanders05c145d2019-08-12 22:40:45 +0000410 Register SecondCmpReg =
Heejin Ahnf208f632018-09-05 01:27:38 +0000411 MRI.createVirtualRegister(&WebAssembly::I32RegClass);
Daniel Sanders05c145d2019-08-12 22:40:45 +0000412 Register AndReg = MRI.createVirtualRegister(&WebAssembly::I32RegClass);
Dan Gohman580c1022017-11-29 20:20:11 +0000413 BuildMI(BB, DL, TII.get(FConst), Tmp1)
414 .addFPImm(cast<ConstantFP>(ConstantFP::get(Ty, 0.0)));
Heejin Ahnf208f632018-09-05 01:27:38 +0000415 BuildMI(BB, DL, TII.get(GE), SecondCmpReg).addReg(Tmp0).addReg(Tmp1);
416 BuildMI(BB, DL, TII.get(And), AndReg).addReg(CmpReg).addReg(SecondCmpReg);
Dan Gohman580c1022017-11-29 20:20:11 +0000417 CmpReg = AndReg;
418 }
419
Heejin Ahnf208f632018-09-05 01:27:38 +0000420 BuildMI(BB, DL, TII.get(Eqz), EqzReg).addReg(CmpReg);
Dan Gohman580c1022017-11-29 20:20:11 +0000421
422 // Create the CFG diamond to select between doing the conversion or using
423 // the substitute value.
Heejin Ahnf208f632018-09-05 01:27:38 +0000424 BuildMI(BB, DL, TII.get(WebAssembly::BR_IF)).addMBB(TrueMBB).addReg(EqzReg);
425 BuildMI(FalseMBB, DL, TII.get(LoweredOpcode), FalseReg).addReg(InReg);
426 BuildMI(FalseMBB, DL, TII.get(WebAssembly::BR)).addMBB(DoneMBB);
427 BuildMI(TrueMBB, DL, TII.get(IConst), TrueReg).addImm(Substitute);
Dan Gohmancdd48b82017-11-28 01:13:40 +0000428 BuildMI(*DoneMBB, DoneMBB->begin(), DL, TII.get(TargetOpcode::PHI), OutReg)
Dan Gohman580c1022017-11-29 20:20:11 +0000429 .addReg(FalseReg)
Dan Gohmancdd48b82017-11-28 01:13:40 +0000430 .addMBB(FalseMBB)
Dan Gohman580c1022017-11-29 20:20:11 +0000431 .addReg(TrueReg)
Dan Gohmancdd48b82017-11-28 01:13:40 +0000432 .addMBB(TrueMBB);
433
434 return DoneMBB;
435}
436
Thomas Lively28857d12019-12-13 15:15:22 -0800437static MachineBasicBlock *LowerCallResults(MachineInstr &CallResults,
438 DebugLoc DL, MachineBasicBlock *BB,
439 const TargetInstrInfo &TII) {
440 MachineInstr &CallParams = *CallResults.getPrevNode();
441 assert(CallParams.getOpcode() == WebAssembly::CALL_PARAMS);
442 assert(CallResults.getOpcode() == WebAssembly::CALL_RESULTS);
443
444 MachineFunction &MF = *BB->getParent();
445 const MCInstrDesc &MCID = TII.get(WebAssembly::CALL);
446 MachineInstrBuilder MIB(MF, MF.CreateMachineInstr(MCID, DL));
447
448 for (auto Def : CallResults.defs())
449 MIB.add(Def);
450 for (auto Use : CallParams.uses())
451 MIB.add(Use);
452
453 BB->insert(CallResults.getIterator(), MIB);
454 CallParams.eraseFromParent();
455 CallResults.eraseFromParent();
456
457 return BB;
458}
459
Heejin Ahnf208f632018-09-05 01:27:38 +0000460MachineBasicBlock *WebAssemblyTargetLowering::EmitInstrWithCustomInserter(
461 MachineInstr &MI, MachineBasicBlock *BB) const {
Dan Gohmancdd48b82017-11-28 01:13:40 +0000462 const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
463 DebugLoc DL = MI.getDebugLoc();
464
465 switch (MI.getOpcode()) {
Heejin Ahnf208f632018-09-05 01:27:38 +0000466 default:
467 llvm_unreachable("Unexpected instr type to insert");
Dan Gohmancdd48b82017-11-28 01:13:40 +0000468 case WebAssembly::FP_TO_SINT_I32_F32:
469 return LowerFPToInt(MI, DL, BB, TII, false, false, false,
470 WebAssembly::I32_TRUNC_S_F32);
471 case WebAssembly::FP_TO_UINT_I32_F32:
472 return LowerFPToInt(MI, DL, BB, TII, true, false, false,
473 WebAssembly::I32_TRUNC_U_F32);
474 case WebAssembly::FP_TO_SINT_I64_F32:
475 return LowerFPToInt(MI, DL, BB, TII, false, true, false,
476 WebAssembly::I64_TRUNC_S_F32);
477 case WebAssembly::FP_TO_UINT_I64_F32:
478 return LowerFPToInt(MI, DL, BB, TII, true, true, false,
479 WebAssembly::I64_TRUNC_U_F32);
480 case WebAssembly::FP_TO_SINT_I32_F64:
481 return LowerFPToInt(MI, DL, BB, TII, false, false, true,
482 WebAssembly::I32_TRUNC_S_F64);
483 case WebAssembly::FP_TO_UINT_I32_F64:
484 return LowerFPToInt(MI, DL, BB, TII, true, false, true,
485 WebAssembly::I32_TRUNC_U_F64);
486 case WebAssembly::FP_TO_SINT_I64_F64:
487 return LowerFPToInt(MI, DL, BB, TII, false, true, true,
488 WebAssembly::I64_TRUNC_S_F64);
489 case WebAssembly::FP_TO_UINT_I64_F64:
490 return LowerFPToInt(MI, DL, BB, TII, true, true, true,
491 WebAssembly::I64_TRUNC_U_F64);
Thomas Lively28857d12019-12-13 15:15:22 -0800492 case WebAssembly::CALL_RESULTS:
493 return LowerCallResults(MI, DL, BB, TII);
Dan Gohmancdd48b82017-11-28 01:13:40 +0000494 }
495}
496
Heejin Ahnf208f632018-09-05 01:27:38 +0000497const char *
498WebAssemblyTargetLowering::getTargetNodeName(unsigned Opcode) const {
JF Bastien480c8402015-08-11 20:13:18 +0000499 switch (static_cast<WebAssemblyISD::NodeType>(Opcode)) {
Heejin Ahnf208f632018-09-05 01:27:38 +0000500 case WebAssemblyISD::FIRST_NUMBER:
Thomas Lively3479fd22019-10-31 20:01:02 -0700501 case WebAssemblyISD::FIRST_MEM_OPCODE:
Heejin Ahnf208f632018-09-05 01:27:38 +0000502 break;
503#define HANDLE_NODETYPE(NODE) \
504 case WebAssemblyISD::NODE: \
JF Bastienaf111db2015-08-24 22:16:48 +0000505 return "WebAssemblyISD::" #NODE;
Thomas Lively3479fd22019-10-31 20:01:02 -0700506#define HANDLE_MEM_NODETYPE(NODE) HANDLE_NODETYPE(NODE)
JF Bastienaf111db2015-08-24 22:16:48 +0000507#include "WebAssemblyISD.def"
Thomas Lively3479fd22019-10-31 20:01:02 -0700508#undef HANDLE_MEM_NODETYPE
JF Bastienaf111db2015-08-24 22:16:48 +0000509#undef HANDLE_NODETYPE
JF Bastien480c8402015-08-11 20:13:18 +0000510 }
511 return nullptr;
512}
513
Dan Gohmanf19ed562015-11-13 01:42:29 +0000514std::pair<unsigned, const TargetRegisterClass *>
515WebAssemblyTargetLowering::getRegForInlineAsmConstraint(
516 const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
517 // First, see if this is a constraint that directly corresponds to a
518 // WebAssembly register class.
519 if (Constraint.size() == 1) {
520 switch (Constraint[0]) {
Heejin Ahnf208f632018-09-05 01:27:38 +0000521 case 'r':
522 assert(VT != MVT::iPTR && "Pointer MVT not expected here");
523 if (Subtarget->hasSIMD128() && VT.isVector()) {
524 if (VT.getSizeInBits() == 128)
525 return std::make_pair(0U, &WebAssembly::V128RegClass);
526 }
527 if (VT.isInteger() && !VT.isVector()) {
528 if (VT.getSizeInBits() <= 32)
529 return std::make_pair(0U, &WebAssembly::I32RegClass);
530 if (VT.getSizeInBits() <= 64)
531 return std::make_pair(0U, &WebAssembly::I64RegClass);
532 }
533 break;
534 default:
535 break;
Dan Gohmanf19ed562015-11-13 01:42:29 +0000536 }
537 }
538
539 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
540}
541
Dan Gohman3192ddf2015-11-19 23:04:59 +0000542bool WebAssemblyTargetLowering::isCheapToSpeculateCttz() const {
543 // Assume ctz is a relatively cheap operation.
544 return true;
545}
546
547bool WebAssemblyTargetLowering::isCheapToSpeculateCtlz() const {
548 // Assume clz is a relatively cheap operation.
549 return true;
550}
551
Dan Gohman4b9d7912015-12-15 22:01:29 +0000552bool WebAssemblyTargetLowering::isLegalAddressingMode(const DataLayout &DL,
553 const AddrMode &AM,
Heejin Ahnf208f632018-09-05 01:27:38 +0000554 Type *Ty, unsigned AS,
Jonas Paulsson024e3192017-07-21 11:59:37 +0000555 Instruction *I) const {
Dan Gohman4b9d7912015-12-15 22:01:29 +0000556 // WebAssembly offsets are added as unsigned without wrapping. The
557 // isLegalAddressingMode gives us no way to determine if wrapping could be
558 // happening, so we approximate this by accepting only non-negative offsets.
Heejin Ahnf208f632018-09-05 01:27:38 +0000559 if (AM.BaseOffs < 0)
560 return false;
Dan Gohman4b9d7912015-12-15 22:01:29 +0000561
562 // WebAssembly has no scale register operands.
Heejin Ahnf208f632018-09-05 01:27:38 +0000563 if (AM.Scale != 0)
564 return false;
Dan Gohman4b9d7912015-12-15 22:01:29 +0000565
566 // Everything else is legal.
567 return true;
568}
569
Dan Gohmanbb372242016-01-26 03:39:31 +0000570bool WebAssemblyTargetLowering::allowsMisalignedMemoryAccesses(
Simon Pilgrim4e0648a2019-06-12 17:14:03 +0000571 EVT /*VT*/, unsigned /*AddrSpace*/, unsigned /*Align*/,
572 MachineMemOperand::Flags /*Flags*/, bool *Fast) const {
Dan Gohmanbb372242016-01-26 03:39:31 +0000573 // WebAssembly supports unaligned accesses, though it should be declared
574 // with the p2align attribute on loads and stores which do so, and there
575 // may be a performance impact. We tell LLVM they're "fast" because
Dan Gohmanfb619e92016-01-26 14:55:17 +0000576 // for the kinds of things that LLVM uses this for (merging adjacent stores
Dan Gohmanbb372242016-01-26 03:39:31 +0000577 // of constants, etc.), WebAssembly implementations will either want the
578 // unaligned access or they'll split anyway.
Heejin Ahnf208f632018-09-05 01:27:38 +0000579 if (Fast)
580 *Fast = true;
Dan Gohmanbb372242016-01-26 03:39:31 +0000581 return true;
582}
583
Reid Klecknerb5180542017-03-21 16:57:19 +0000584bool WebAssemblyTargetLowering::isIntDivCheap(EVT VT,
585 AttributeList Attr) const {
Dan Gohmanb4c3c382016-05-18 14:29:42 +0000586 // The current thinking is that wasm engines will perform this optimization,
587 // so we can save on code size.
588 return true;
589}
590
Thomas Lively81125f72019-09-27 02:06:50 +0000591bool WebAssemblyTargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const {
592 if (!Subtarget->hasUnimplementedSIMD128())
593 return false;
594 MVT ExtT = ExtVal.getSimpleValueType();
595 MVT MemT = cast<LoadSDNode>(ExtVal->getOperand(0))->getSimpleValueType(0);
596 return (ExtT == MVT::v8i16 && MemT == MVT::v8i8) ||
597 (ExtT == MVT::v4i32 && MemT == MVT::v4i16) ||
598 (ExtT == MVT::v2i64 && MemT == MVT::v2i32);
599}
600
Simon Pilgrim99f70162018-06-28 17:27:09 +0000601EVT WebAssemblyTargetLowering::getSetCCResultType(const DataLayout &DL,
602 LLVMContext &C,
603 EVT VT) const {
604 if (VT.isVector())
605 return VT.changeVectorElementTypeToInteger();
606
607 return TargetLowering::getSetCCResultType(DL, C, VT);
608}
609
Heejin Ahn4128cb02018-08-02 21:44:24 +0000610bool WebAssemblyTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
611 const CallInst &I,
612 MachineFunction &MF,
613 unsigned Intrinsic) const {
614 switch (Intrinsic) {
615 case Intrinsic::wasm_atomic_notify:
616 Info.opc = ISD::INTRINSIC_W_CHAIN;
617 Info.memVT = MVT::i32;
618 Info.ptrVal = I.getArgOperand(0);
619 Info.offset = 0;
Guillaume Chateletc97a3d12019-08-05 11:02:05 +0000620 Info.align = Align(4);
Heejin Ahn4128cb02018-08-02 21:44:24 +0000621 // atomic.notify instruction does not really load the memory specified with
622 // this argument, but MachineMemOperand should either be load or store, so
623 // we set this to a load.
624 // FIXME Volatile isn't really correct, but currently all LLVM atomic
625 // instructions are treated as volatiles in the backend, so we should be
626 // consistent. The same applies for wasm_atomic_wait intrinsics too.
627 Info.flags = MachineMemOperand::MOVolatile | MachineMemOperand::MOLoad;
628 return true;
629 case Intrinsic::wasm_atomic_wait_i32:
630 Info.opc = ISD::INTRINSIC_W_CHAIN;
631 Info.memVT = MVT::i32;
632 Info.ptrVal = I.getArgOperand(0);
633 Info.offset = 0;
Guillaume Chateletc97a3d12019-08-05 11:02:05 +0000634 Info.align = Align(4);
Heejin Ahn4128cb02018-08-02 21:44:24 +0000635 Info.flags = MachineMemOperand::MOVolatile | MachineMemOperand::MOLoad;
636 return true;
637 case Intrinsic::wasm_atomic_wait_i64:
638 Info.opc = ISD::INTRINSIC_W_CHAIN;
639 Info.memVT = MVT::i64;
640 Info.ptrVal = I.getArgOperand(0);
641 Info.offset = 0;
Guillaume Chateletc97a3d12019-08-05 11:02:05 +0000642 Info.align = Align(8);
Heejin Ahn4128cb02018-08-02 21:44:24 +0000643 Info.flags = MachineMemOperand::MOVolatile | MachineMemOperand::MOLoad;
644 return true;
645 default:
646 return false;
647 }
648}
649
Dan Gohman10e730a2015-06-29 23:51:55 +0000650//===----------------------------------------------------------------------===//
651// WebAssembly Lowering private implementation.
652//===----------------------------------------------------------------------===//
653
654//===----------------------------------------------------------------------===//
655// Lowering Code
656//===----------------------------------------------------------------------===//
657
Heejin Ahn18c56a02019-02-04 19:13:39 +0000658static void fail(const SDLoc &DL, SelectionDAG &DAG, const char *Msg) {
JF Bastienb9073fb2015-07-22 21:28:15 +0000659 MachineFunction &MF = DAG.getMachineFunction();
660 DAG.getContext()->diagnose(
Heejin Ahn18c56a02019-02-04 19:13:39 +0000661 DiagnosticInfoUnsupported(MF.getFunction(), Msg, DL.getDebugLoc()));
JF Bastienb9073fb2015-07-22 21:28:15 +0000662}
663
Dan Gohman85dbdda2015-12-04 17:16:07 +0000664// Test whether the given calling convention is supported.
Heejin Ahn18c56a02019-02-04 19:13:39 +0000665static bool callingConvSupported(CallingConv::ID CallConv) {
Dan Gohman85dbdda2015-12-04 17:16:07 +0000666 // We currently support the language-independent target-independent
Dan Gohman1ce2b1a2015-12-04 18:27:03 +0000667 // conventions. We don't yet have a way to annotate calls with properties like
668 // "cold", and we don't have any call-clobbered registers, so these are mostly
669 // all handled the same.
Dan Gohmana3f5ce52015-12-04 17:18:32 +0000670 return CallConv == CallingConv::C || CallConv == CallingConv::Fast ||
Dan Gohman1ce2b1a2015-12-04 18:27:03 +0000671 CallConv == CallingConv::Cold ||
672 CallConv == CallingConv::PreserveMost ||
673 CallConv == CallingConv::PreserveAll ||
Keno Fischer5c3cdef2019-08-05 21:36:09 +0000674 CallConv == CallingConv::CXX_FAST_TLS ||
675 CallConv == CallingConv::WASM_EmscriptenInvoke;
Dan Gohman85dbdda2015-12-04 17:16:07 +0000676}
677
Heejin Ahnf208f632018-09-05 01:27:38 +0000678SDValue
679WebAssemblyTargetLowering::LowerCall(CallLoweringInfo &CLI,
680 SmallVectorImpl<SDValue> &InVals) const {
JF Bastiend8a9d662015-08-24 21:59:51 +0000681 SelectionDAG &DAG = CLI.DAG;
682 SDLoc DL = CLI.DL;
683 SDValue Chain = CLI.Chain;
684 SDValue Callee = CLI.Callee;
685 MachineFunction &MF = DAG.getMachineFunction();
Derek Schuff992d83f2016-02-10 20:14:15 +0000686 auto Layout = MF.getDataLayout();
JF Bastiend8a9d662015-08-24 21:59:51 +0000687
688 CallingConv::ID CallConv = CLI.CallConv;
Heejin Ahn18c56a02019-02-04 19:13:39 +0000689 if (!callingConvSupported(CallConv))
Dan Gohman9cc692b2015-10-02 20:54:23 +0000690 fail(DL, DAG,
691 "WebAssembly doesn't support language-specific or target-specific "
692 "calling conventions yet");
JF Bastiend8a9d662015-08-24 21:59:51 +0000693 if (CLI.IsPatchPoint)
694 fail(DL, DAG, "WebAssembly doesn't support patch point yet");
695
Thomas Livelye0a9dce2019-07-30 18:08:39 +0000696 if (CLI.IsTailCall) {
697 bool MustTail = CLI.CS && CLI.CS.isMustTailCall();
698 if (Subtarget->hasTailCall() && !CLI.IsVarArg) {
699 // Do not tail call unless caller and callee return types match
700 const Function &F = MF.getFunction();
701 const TargetMachine &TM = getTargetMachine();
702 Type *RetTy = F.getReturnType();
703 SmallVector<MVT, 4> CallerRetTys;
704 SmallVector<MVT, 4> CalleeRetTys;
705 computeLegalValueVTs(F, TM, RetTy, CallerRetTys);
706 computeLegalValueVTs(F, TM, CLI.RetTy, CalleeRetTys);
707 bool TypesMatch = CallerRetTys.size() == CalleeRetTys.size() &&
708 std::equal(CallerRetTys.begin(), CallerRetTys.end(),
709 CalleeRetTys.begin());
710 if (!TypesMatch) {
711 // musttail in this case would be an LLVM IR validation failure
712 assert(!MustTail);
713 CLI.IsTailCall = false;
714 }
715 } else {
716 CLI.IsTailCall = false;
717 if (MustTail) {
718 if (CLI.IsVarArg) {
719 // The return would pop the argument buffer
720 fail(DL, DAG, "WebAssembly does not support varargs tail calls");
721 } else {
722 fail(DL, DAG, "WebAssembly 'tail-call' feature not enabled");
723 }
724 }
725 }
Thomas Livelya1d97a92019-06-26 16:17:15 +0000726 }
Dan Gohman9cc692b2015-10-02 20:54:23 +0000727
JF Bastiend8a9d662015-08-24 21:59:51 +0000728 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
Dan Gohman2d822e72015-12-04 17:12:52 +0000729 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
Derek Schuff4dd67782016-01-27 21:17:39 +0000730 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
Keno Fischer5c3cdef2019-08-05 21:36:09 +0000731
732 // The generic code may have added an sret argument. If we're lowering an
733 // invoke function, the ABI requires that the function pointer be the first
734 // argument, so we may have to swap the arguments.
735 if (CallConv == CallingConv::WASM_EmscriptenInvoke && Outs.size() >= 2 &&
736 Outs[0].Flags.isSRet()) {
737 std::swap(Outs[0], Outs[1]);
738 std::swap(OutVals[0], OutVals[1]);
739 }
740
Dan Gohman910ba332018-06-26 03:18:38 +0000741 unsigned NumFixedArgs = 0;
Heejin Ahn18c56a02019-02-04 19:13:39 +0000742 for (unsigned I = 0; I < Outs.size(); ++I) {
743 const ISD::OutputArg &Out = Outs[I];
744 SDValue &OutVal = OutVals[I];
Dan Gohman7935fa32015-12-10 00:22:40 +0000745 if (Out.Flags.isNest())
746 fail(DL, DAG, "WebAssembly hasn't implemented nest arguments");
Dan Gohman2d822e72015-12-04 17:12:52 +0000747 if (Out.Flags.isInAlloca())
Dan Gohman7935fa32015-12-10 00:22:40 +0000748 fail(DL, DAG, "WebAssembly hasn't implemented inalloca arguments");
Dan Gohman2d822e72015-12-04 17:12:52 +0000749 if (Out.Flags.isInConsecutiveRegs())
Dan Gohman7935fa32015-12-10 00:22:40 +0000750 fail(DL, DAG, "WebAssembly hasn't implemented cons regs arguments");
Dan Gohman2d822e72015-12-04 17:12:52 +0000751 if (Out.Flags.isInConsecutiveRegsLast())
Dan Gohman7935fa32015-12-10 00:22:40 +0000752 fail(DL, DAG, "WebAssembly hasn't implemented cons regs last arguments");
Dan Gohmana6771b32016-02-12 21:30:18 +0000753 if (Out.Flags.isByVal() && Out.Flags.getByValSize() != 0) {
Matthias Braun941a7052016-07-28 18:40:00 +0000754 auto &MFI = MF.getFrameInfo();
755 int FI = MFI.CreateStackObject(Out.Flags.getByValSize(),
756 Out.Flags.getByValAlign(),
757 /*isSS=*/false);
Derek Schuff4dd67782016-01-27 21:17:39 +0000758 SDValue SizeNode =
759 DAG.getConstant(Out.Flags.getByValSize(), DL, MVT::i32);
Derek Schuff992d83f2016-02-10 20:14:15 +0000760 SDValue FINode = DAG.getFrameIndex(FI, getPointerTy(Layout));
Derek Schuff4dd67782016-01-27 21:17:39 +0000761 Chain = DAG.getMemcpy(
762 Chain, DL, FINode, OutVal, SizeNode, Out.Flags.getByValAlign(),
Dan Gohman476ffce2016-02-17 01:43:37 +0000763 /*isVolatile*/ false, /*AlwaysInline=*/false,
Derek Schuff4dd67782016-01-27 21:17:39 +0000764 /*isTailCall*/ false, MachinePointerInfo(), MachinePointerInfo());
765 OutVal = FINode;
766 }
Dan Gohman910ba332018-06-26 03:18:38 +0000767 // Count the number of fixed args *after* legalization.
768 NumFixedArgs += Out.IsFixed;
Dan Gohman2d822e72015-12-04 17:12:52 +0000769 }
770
JF Bastiend8a9d662015-08-24 21:59:51 +0000771 bool IsVarArg = CLI.IsVarArg;
Derek Schuff992d83f2016-02-10 20:14:15 +0000772 auto PtrVT = getPointerTy(Layout);
Dan Gohmane590b332015-09-09 01:52:45 +0000773
JF Bastiend8a9d662015-08-24 21:59:51 +0000774 // Analyze operands of the call, assigning locations to each operand.
775 SmallVector<CCValAssign, 16> ArgLocs;
776 CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
JF Bastiend8a9d662015-08-24 21:59:51 +0000777
Dan Gohman35bfb242015-12-04 23:22:35 +0000778 if (IsVarArg) {
Derek Schuff27501e22016-02-10 19:51:04 +0000779 // Outgoing non-fixed arguments are placed in a buffer. First
780 // compute their offsets and the total amount of buffer space needed.
Dan Gohmanc71132c2019-02-26 05:20:19 +0000781 for (unsigned I = NumFixedArgs; I < Outs.size(); ++I) {
782 const ISD::OutputArg &Out = Outs[I];
783 SDValue &Arg = OutVals[I];
Dan Gohman35bfb242015-12-04 23:22:35 +0000784 EVT VT = Arg.getValueType();
785 assert(VT != MVT::iPTR && "Legalized args should be concrete");
786 Type *Ty = VT.getTypeForEVT(*DAG.getContext());
Dan Gohmanc71132c2019-02-26 05:20:19 +0000787 unsigned Align = std::max(Out.Flags.getOrigAlign(),
788 Layout.getABITypeAlignment(Ty));
Derek Schuff992d83f2016-02-10 20:14:15 +0000789 unsigned Offset = CCInfo.AllocateStack(Layout.getTypeAllocSize(Ty),
Dan Gohmanc71132c2019-02-26 05:20:19 +0000790 Align);
Dan Gohman35bfb242015-12-04 23:22:35 +0000791 CCInfo.addLoc(CCValAssign::getMem(ArgLocs.size(), VT.getSimpleVT(),
792 Offset, VT.getSimpleVT(),
793 CCValAssign::Full));
794 }
795 }
796
797 unsigned NumBytes = CCInfo.getAlignedCallFrameSize();
798
Derek Schuff27501e22016-02-10 19:51:04 +0000799 SDValue FINode;
800 if (IsVarArg && NumBytes) {
Dan Gohman35bfb242015-12-04 23:22:35 +0000801 // For non-fixed arguments, next emit stores to store the argument values
Derek Schuff27501e22016-02-10 19:51:04 +0000802 // to the stack buffer at the offsets computed above.
Matthias Braun941a7052016-07-28 18:40:00 +0000803 int FI = MF.getFrameInfo().CreateStackObject(NumBytes,
804 Layout.getStackAlignment(),
805 /*isSS=*/false);
Dan Gohman35bfb242015-12-04 23:22:35 +0000806 unsigned ValNo = 0;
807 SmallVector<SDValue, 8> Chains;
808 for (SDValue Arg :
809 make_range(OutVals.begin() + NumFixedArgs, OutVals.end())) {
810 assert(ArgLocs[ValNo].getValNo() == ValNo &&
811 "ArgLocs should remain in order and only hold varargs args");
812 unsigned Offset = ArgLocs[ValNo++].getLocMemOffset();
Derek Schuff992d83f2016-02-10 20:14:15 +0000813 FINode = DAG.getFrameIndex(FI, getPointerTy(Layout));
Derek Schuff27501e22016-02-10 19:51:04 +0000814 SDValue Add = DAG.getNode(ISD::ADD, DL, PtrVT, FINode,
Dan Gohman35bfb242015-12-04 23:22:35 +0000815 DAG.getConstant(Offset, DL, PtrVT));
Heejin Ahnf208f632018-09-05 01:27:38 +0000816 Chains.push_back(
817 DAG.getStore(Chain, DL, Arg, Add,
818 MachinePointerInfo::getFixedStack(MF, FI, Offset), 0));
Dan Gohman35bfb242015-12-04 23:22:35 +0000819 }
820 if (!Chains.empty())
821 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
Derek Schuff27501e22016-02-10 19:51:04 +0000822 } else if (IsVarArg) {
823 FINode = DAG.getIntPtrConstant(0, DL);
Dan Gohman35bfb242015-12-04 23:22:35 +0000824 }
825
Sam Clegg492f7522019-03-26 19:46:15 +0000826 if (Callee->getOpcode() == ISD::GlobalAddress) {
827 // If the callee is a GlobalAddress node (quite common, every direct call
828 // is) turn it into a TargetGlobalAddress node so that LowerGlobalAddress
829 // doesn't at MO_GOT which is not needed for direct calls.
830 GlobalAddressSDNode* GA = cast<GlobalAddressSDNode>(Callee);
831 Callee = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
832 getPointerTy(DAG.getDataLayout()),
833 GA->getOffset());
834 Callee = DAG.getNode(WebAssemblyISD::Wrapper, DL,
835 getPointerTy(DAG.getDataLayout()), Callee);
836 }
837
Dan Gohman35bfb242015-12-04 23:22:35 +0000838 // Compute the operands for the CALLn node.
JF Bastiend8a9d662015-08-24 21:59:51 +0000839 SmallVector<SDValue, 16> Ops;
840 Ops.push_back(Chain);
JF Bastienaf111db2015-08-24 22:16:48 +0000841 Ops.push_back(Callee);
Dan Gohman35bfb242015-12-04 23:22:35 +0000842
843 // Add all fixed arguments. Note that for non-varargs calls, NumFixedArgs
844 // isn't reliable.
845 Ops.append(OutVals.begin(),
846 IsVarArg ? OutVals.begin() + NumFixedArgs : OutVals.end());
Derek Schuff27501e22016-02-10 19:51:04 +0000847 // Add a pointer to the vararg buffer.
Heejin Ahnf208f632018-09-05 01:27:38 +0000848 if (IsVarArg)
849 Ops.push_back(FINode);
JF Bastiend8a9d662015-08-24 21:59:51 +0000850
Derek Schuff27501e22016-02-10 19:51:04 +0000851 SmallVector<EVT, 8> InTys;
Dan Gohman2d822e72015-12-04 17:12:52 +0000852 for (const auto &In : Ins) {
Dan Gohman7935fa32015-12-10 00:22:40 +0000853 assert(!In.Flags.isByVal() && "byval is not valid for return values");
854 assert(!In.Flags.isNest() && "nest is not valid for return values");
Dan Gohman2d822e72015-12-04 17:12:52 +0000855 if (In.Flags.isInAlloca())
Dan Gohman7935fa32015-12-10 00:22:40 +0000856 fail(DL, DAG, "WebAssembly hasn't implemented inalloca return values");
Dan Gohman2d822e72015-12-04 17:12:52 +0000857 if (In.Flags.isInConsecutiveRegs())
Dan Gohman7935fa32015-12-10 00:22:40 +0000858 fail(DL, DAG, "WebAssembly hasn't implemented cons regs return values");
Dan Gohman2d822e72015-12-04 17:12:52 +0000859 if (In.Flags.isInConsecutiveRegsLast())
Dan Gohman4b9d7912015-12-15 22:01:29 +0000860 fail(DL, DAG,
861 "WebAssembly hasn't implemented cons regs last return values");
Dan Gohman2d822e72015-12-04 17:12:52 +0000862 // Ignore In.getOrigAlign() because all our arguments are passed in
863 // registers.
Derek Schuff27501e22016-02-10 19:51:04 +0000864 InTys.push_back(In.VT);
Dan Gohman2d822e72015-12-04 17:12:52 +0000865 }
Thomas Livelya1d97a92019-06-26 16:17:15 +0000866
867 if (CLI.IsTailCall) {
868 // ret_calls do not return values to the current frame
869 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
870 return DAG.getNode(WebAssemblyISD::RET_CALL, DL, NodeTys, Ops);
871 }
872
Derek Schuff27501e22016-02-10 19:51:04 +0000873 InTys.push_back(MVT::Other);
Thomas Lively3ef169e2019-12-13 10:41:25 -0800874 unsigned Opc;
875 // TODO: Remove CALL0 and CALL1 in favor of CALL
876 switch (Ins.size()) {
877 case 0:
878 Opc = WebAssemblyISD::CALL0;
879 break;
880 case 1:
881 Opc = WebAssemblyISD::CALL1;
882 break;
883 default:
884 Opc = WebAssemblyISD::CALL;
885 break;
JF Bastienaf111db2015-08-24 22:16:48 +0000886 }
Thomas Lively3ef169e2019-12-13 10:41:25 -0800887 SDVTList InTyList = DAG.getVTList(InTys);
888 SDValue Res = DAG.getNode(Opc, DL, InTyList, Ops);
JF Bastiend8a9d662015-08-24 21:59:51 +0000889
Thomas Lively3ef169e2019-12-13 10:41:25 -0800890 for (size_t I = 0; I < Ins.size(); ++I)
891 InVals.push_back(Res.getValue(I));
892
893 // Return the chain
894 return Res.getValue(Ins.size());
JF Bastiend8a9d662015-08-24 21:59:51 +0000895}
896
JF Bastienb9073fb2015-07-22 21:28:15 +0000897bool WebAssemblyTargetLowering::CanLowerReturn(
Dan Gohman7a6b9822015-11-29 22:32:02 +0000898 CallingConv::ID /*CallConv*/, MachineFunction & /*MF*/, bool /*IsVarArg*/,
899 const SmallVectorImpl<ISD::OutputArg> &Outs,
900 LLVMContext & /*Context*/) const {
Thomas Lively00f9e5a2019-10-09 21:42:08 +0000901 // WebAssembly can only handle returning tuples with multivalue enabled
902 return Subtarget->hasMultivalue() || Outs.size() <= 1;
JF Bastienb9073fb2015-07-22 21:28:15 +0000903}
904
905SDValue WebAssemblyTargetLowering::LowerReturn(
Dan Gohman35bfb242015-12-04 23:22:35 +0000906 SDValue Chain, CallingConv::ID CallConv, bool /*IsVarArg*/,
JF Bastienb9073fb2015-07-22 21:28:15 +0000907 const SmallVectorImpl<ISD::OutputArg> &Outs,
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000908 const SmallVectorImpl<SDValue> &OutVals, const SDLoc &DL,
JF Bastienb9073fb2015-07-22 21:28:15 +0000909 SelectionDAG &DAG) const {
Simon Pilgrim788ba152019-10-10 12:21:52 +0000910 assert((Subtarget->hasMultivalue() || Outs.size() <= 1) &&
911 "MVP WebAssembly can only return up to one value");
Heejin Ahn18c56a02019-02-04 19:13:39 +0000912 if (!callingConvSupported(CallConv))
JF Bastienb9073fb2015-07-22 21:28:15 +0000913 fail(DL, DAG, "WebAssembly doesn't support non-C calling conventions");
914
JF Bastien600aee92015-07-31 17:53:38 +0000915 SmallVector<SDValue, 4> RetOps(1, Chain);
916 RetOps.append(OutVals.begin(), OutVals.end());
JF Bastien4a2d5602015-07-31 21:04:18 +0000917 Chain = DAG.getNode(WebAssemblyISD::RETURN, DL, MVT::Other, RetOps);
JF Bastienb9073fb2015-07-22 21:28:15 +0000918
Dan Gohman754cd112015-11-11 01:33:02 +0000919 // Record the number and types of the return values.
920 for (const ISD::OutputArg &Out : Outs) {
Dan Gohmanac132e92015-12-02 23:40:03 +0000921 assert(!Out.Flags.isByVal() && "byval is not valid for return values");
922 assert(!Out.Flags.isNest() && "nest is not valid for return values");
Dan Gohman35bfb242015-12-04 23:22:35 +0000923 assert(Out.IsFixed && "non-fixed return value is not valid");
Dan Gohman754cd112015-11-11 01:33:02 +0000924 if (Out.Flags.isInAlloca())
925 fail(DL, DAG, "WebAssembly hasn't implemented inalloca results");
Dan Gohman754cd112015-11-11 01:33:02 +0000926 if (Out.Flags.isInConsecutiveRegs())
927 fail(DL, DAG, "WebAssembly hasn't implemented cons regs results");
928 if (Out.Flags.isInConsecutiveRegsLast())
929 fail(DL, DAG, "WebAssembly hasn't implemented cons regs last results");
Dan Gohman754cd112015-11-11 01:33:02 +0000930 }
931
JF Bastienb9073fb2015-07-22 21:28:15 +0000932 return Chain;
933}
934
935SDValue WebAssemblyTargetLowering::LowerFormalArguments(
Derek Schuff27501e22016-02-10 19:51:04 +0000936 SDValue Chain, CallingConv::ID CallConv, bool IsVarArg,
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000937 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
938 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
Heejin Ahn18c56a02019-02-04 19:13:39 +0000939 if (!callingConvSupported(CallConv))
JF Bastienb9073fb2015-07-22 21:28:15 +0000940 fail(DL, DAG, "WebAssembly doesn't support non-C calling conventions");
JF Bastienb9073fb2015-07-22 21:28:15 +0000941
Dan Gohman2726b882016-10-06 22:29:32 +0000942 MachineFunction &MF = DAG.getMachineFunction();
943 auto *MFI = MF.getInfo<WebAssemblyFunctionInfo>();
944
Dan Gohmanfb3e0592015-11-25 19:36:19 +0000945 // Set up the incoming ARGUMENTS value, which serves to represent the liveness
946 // of the incoming values before they're represented by virtual registers.
947 MF.getRegInfo().addLiveIn(WebAssembly::ARGUMENTS);
948
JF Bastien600aee92015-07-31 17:53:38 +0000949 for (const ISD::InputArg &In : Ins) {
JF Bastien600aee92015-07-31 17:53:38 +0000950 if (In.Flags.isInAlloca())
951 fail(DL, DAG, "WebAssembly hasn't implemented inalloca arguments");
952 if (In.Flags.isNest())
953 fail(DL, DAG, "WebAssembly hasn't implemented nest arguments");
JF Bastien600aee92015-07-31 17:53:38 +0000954 if (In.Flags.isInConsecutiveRegs())
955 fail(DL, DAG, "WebAssembly hasn't implemented cons regs arguments");
956 if (In.Flags.isInConsecutiveRegsLast())
957 fail(DL, DAG, "WebAssembly hasn't implemented cons regs last arguments");
Dan Gohman9c54d3b2015-11-25 18:13:18 +0000958 // Ignore In.getOrigAlign() because all our arguments are passed in
959 // registers.
Heejin Ahnf208f632018-09-05 01:27:38 +0000960 InVals.push_back(In.Used ? DAG.getNode(WebAssemblyISD::ARGUMENT, DL, In.VT,
961 DAG.getTargetConstant(InVals.size(),
962 DL, MVT::i32))
963 : DAG.getUNDEF(In.VT));
Dan Gohman754cd112015-11-11 01:33:02 +0000964
965 // Record the number and types of arguments.
Derek Schuff27501e22016-02-10 19:51:04 +0000966 MFI->addParam(In.VT);
JF Bastien600aee92015-07-31 17:53:38 +0000967 }
JF Bastienb9073fb2015-07-22 21:28:15 +0000968
Derek Schuff27501e22016-02-10 19:51:04 +0000969 // Varargs are copied into a buffer allocated by the caller, and a pointer to
970 // the buffer is passed as an argument.
971 if (IsVarArg) {
972 MVT PtrVT = getPointerTy(MF.getDataLayout());
Daniel Sanders05c145d2019-08-12 22:40:45 +0000973 Register VarargVreg =
Derek Schuff27501e22016-02-10 19:51:04 +0000974 MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrVT));
975 MFI->setVarargBufferVreg(VarargVreg);
976 Chain = DAG.getCopyToReg(
977 Chain, DL, VarargVreg,
978 DAG.getNode(WebAssemblyISD::ARGUMENT, DL, PtrVT,
979 DAG.getTargetConstant(Ins.size(), DL, MVT::i32)));
980 MFI->addParam(PtrVT);
981 }
Dan Gohman35bfb242015-12-04 23:22:35 +0000982
Derek Schuff77a7a382018-10-03 22:22:48 +0000983 // Record the number and types of arguments and results.
Dan Gohman2726b882016-10-06 22:29:32 +0000984 SmallVector<MVT, 4> Params;
985 SmallVector<MVT, 4> Results;
Heejin Ahn18c56a02019-02-04 19:13:39 +0000986 computeSignatureVTs(MF.getFunction().getFunctionType(), MF.getFunction(),
Derek Schuff77a7a382018-10-03 22:22:48 +0000987 DAG.getTarget(), Params, Results);
Dan Gohman2726b882016-10-06 22:29:32 +0000988 for (MVT VT : Results)
989 MFI->addResult(VT);
Derek Schuff77a7a382018-10-03 22:22:48 +0000990 // TODO: Use signatures in WebAssemblyMachineFunctionInfo too and unify
991 // the param logic here with ComputeSignatureVTs
992 assert(MFI->getParams().size() == Params.size() &&
993 std::equal(MFI->getParams().begin(), MFI->getParams().end(),
994 Params.begin()));
Dan Gohman2726b882016-10-06 22:29:32 +0000995
JF Bastienb9073fb2015-07-22 21:28:15 +0000996 return Chain;
997}
998
Thomas Livelye18b5c62019-05-23 18:09:26 +0000999void WebAssemblyTargetLowering::ReplaceNodeResults(
1000 SDNode *N, SmallVectorImpl<SDValue> &Results, SelectionDAG &DAG) const {
1001 switch (N->getOpcode()) {
1002 case ISD::SIGN_EXTEND_INREG:
1003 // Do not add any results, signifying that N should not be custom lowered
1004 // after all. This happens because simd128 turns on custom lowering for
1005 // SIGN_EXTEND_INREG, but for non-vector sign extends the result might be an
1006 // illegal type.
1007 break;
1008 default:
1009 llvm_unreachable(
1010 "ReplaceNodeResults not implemented for this op for WebAssembly!");
1011 }
1012}
1013
Dan Gohman10e730a2015-06-29 23:51:55 +00001014//===----------------------------------------------------------------------===//
JF Bastienaf111db2015-08-24 22:16:48 +00001015// Custom lowering hooks.
Dan Gohman10e730a2015-06-29 23:51:55 +00001016//===----------------------------------------------------------------------===//
1017
JF Bastienaf111db2015-08-24 22:16:48 +00001018SDValue WebAssemblyTargetLowering::LowerOperation(SDValue Op,
1019 SelectionDAG &DAG) const {
Derek Schuff51699a82016-02-12 22:56:03 +00001020 SDLoc DL(Op);
JF Bastienaf111db2015-08-24 22:16:48 +00001021 switch (Op.getOpcode()) {
Heejin Ahnf208f632018-09-05 01:27:38 +00001022 default:
1023 llvm_unreachable("unimplemented operation lowering");
1024 return SDValue();
1025 case ISD::FrameIndex:
1026 return LowerFrameIndex(Op, DAG);
1027 case ISD::GlobalAddress:
1028 return LowerGlobalAddress(Op, DAG);
1029 case ISD::ExternalSymbol:
1030 return LowerExternalSymbol(Op, DAG);
1031 case ISD::JumpTable:
1032 return LowerJumpTable(Op, DAG);
1033 case ISD::BR_JT:
1034 return LowerBR_JT(Op, DAG);
1035 case ISD::VASTART:
1036 return LowerVASTART(Op, DAG);
1037 case ISD::BlockAddress:
1038 case ISD::BRIND:
1039 fail(DL, DAG, "WebAssembly hasn't implemented computed gotos");
1040 return SDValue();
Thomas Lively1a3cbe72019-05-23 01:24:01 +00001041 case ISD::RETURNADDR:
1042 return LowerRETURNADDR(Op, DAG);
Heejin Ahnf208f632018-09-05 01:27:38 +00001043 case ISD::FRAMEADDR:
1044 return LowerFRAMEADDR(Op, DAG);
1045 case ISD::CopyToReg:
1046 return LowerCopyToReg(Op, DAG);
Thomas Livelyfb84fd72018-11-02 00:06:56 +00001047 case ISD::EXTRACT_VECTOR_ELT:
1048 case ISD::INSERT_VECTOR_ELT:
1049 return LowerAccessVectorElement(Op, DAG);
Heejin Ahnda419bd2018-11-14 02:46:21 +00001050 case ISD::INTRINSIC_VOID:
Heejin Ahnd6f48782019-01-30 03:21:57 +00001051 case ISD::INTRINSIC_WO_CHAIN:
1052 case ISD::INTRINSIC_W_CHAIN:
1053 return LowerIntrinsic(Op, DAG);
Thomas Lively64a39a12019-01-10 22:32:11 +00001054 case ISD::SIGN_EXTEND_INREG:
1055 return LowerSIGN_EXTEND_INREG(Op, DAG);
Thomas Lively079816e2019-01-30 02:23:29 +00001056 case ISD::BUILD_VECTOR:
1057 return LowerBUILD_VECTOR(Op, DAG);
Thomas Livelya0d25812018-09-07 21:54:46 +00001058 case ISD::VECTOR_SHUFFLE:
1059 return LowerVECTOR_SHUFFLE(Op, DAG);
Thomas Livelyecb7daf2019-11-01 10:21:00 -07001060 case ISD::SETCC:
1061 return LowerSETCC(Op, DAG);
Thomas Lively55735d52018-10-20 01:31:18 +00001062 case ISD::SHL:
1063 case ISD::SRA:
1064 case ISD::SRL:
1065 return LowerShift(Op, DAG);
JF Bastienaf111db2015-08-24 22:16:48 +00001066 }
1067}
1068
Derek Schuffaadc89c2016-02-16 18:18:36 +00001069SDValue WebAssemblyTargetLowering::LowerCopyToReg(SDValue Op,
1070 SelectionDAG &DAG) const {
1071 SDValue Src = Op.getOperand(2);
1072 if (isa<FrameIndexSDNode>(Src.getNode())) {
1073 // CopyToReg nodes don't support FrameIndex operands. Other targets select
1074 // the FI to some LEA-like instruction, but since we don't have that, we
1075 // need to insert some kind of instruction that can take an FI operand and
1076 // produces a value usable by CopyToReg (i.e. in a vreg). So insert a dummy
Thomas Lively6a87dda2019-01-08 06:25:55 +00001077 // local.copy between Op and its FI operand.
Dan Gohman02c08712016-02-20 23:09:44 +00001078 SDValue Chain = Op.getOperand(0);
Derek Schuffaadc89c2016-02-16 18:18:36 +00001079 SDLoc DL(Op);
Dan Gohman02c08712016-02-20 23:09:44 +00001080 unsigned Reg = cast<RegisterSDNode>(Op.getOperand(1))->getReg();
Derek Schuffaadc89c2016-02-16 18:18:36 +00001081 EVT VT = Src.getValueType();
Heejin Ahnf208f632018-09-05 01:27:38 +00001082 SDValue Copy(DAG.getMachineNode(VT == MVT::i32 ? WebAssembly::COPY_I32
1083 : WebAssembly::COPY_I64,
1084 DL, VT, Src),
1085 0);
Dan Gohman02c08712016-02-20 23:09:44 +00001086 return Op.getNode()->getNumValues() == 1
1087 ? DAG.getCopyToReg(Chain, DL, Reg, Copy)
Heejin Ahnf208f632018-09-05 01:27:38 +00001088 : DAG.getCopyToReg(Chain, DL, Reg, Copy,
1089 Op.getNumOperands() == 4 ? Op.getOperand(3)
1090 : SDValue());
Derek Schuffaadc89c2016-02-16 18:18:36 +00001091 }
1092 return SDValue();
1093}
1094
Derek Schuff9769deb2015-12-11 23:49:46 +00001095SDValue WebAssemblyTargetLowering::LowerFrameIndex(SDValue Op,
1096 SelectionDAG &DAG) const {
1097 int FI = cast<FrameIndexSDNode>(Op)->getIndex();
1098 return DAG.getTargetFrameIndex(FI, Op.getValueType());
1099}
1100
Thomas Lively1a3cbe72019-05-23 01:24:01 +00001101SDValue WebAssemblyTargetLowering::LowerRETURNADDR(SDValue Op,
1102 SelectionDAG &DAG) const {
1103 SDLoc DL(Op);
1104
1105 if (!Subtarget->getTargetTriple().isOSEmscripten()) {
1106 fail(DL, DAG,
1107 "Non-Emscripten WebAssembly hasn't implemented "
1108 "__builtin_return_address");
1109 return SDValue();
1110 }
1111
1112 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
1113 return SDValue();
1114
1115 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
Shiva Chen72a41e72019-08-22 04:59:43 +00001116 MakeLibCallOptions CallOptions;
Thomas Lively1a3cbe72019-05-23 01:24:01 +00001117 return makeLibCall(DAG, RTLIB::RETURN_ADDRESS, Op.getValueType(),
Shiva Chen72a41e72019-08-22 04:59:43 +00001118 {DAG.getConstant(Depth, DL, MVT::i32)}, CallOptions, DL)
Thomas Lively1a3cbe72019-05-23 01:24:01 +00001119 .first;
1120}
1121
Dan Gohman94c65662016-02-16 23:48:04 +00001122SDValue WebAssemblyTargetLowering::LowerFRAMEADDR(SDValue Op,
1123 SelectionDAG &DAG) const {
1124 // Non-zero depths are not supported by WebAssembly currently. Use the
1125 // legalizer's default expansion, which is to return 0 (what this function is
1126 // documented to do).
Dan Gohman1d547bf2016-02-17 00:14:03 +00001127 if (Op.getConstantOperandVal(0) > 0)
Dan Gohman94c65662016-02-16 23:48:04 +00001128 return SDValue();
1129
Matthias Braun941a7052016-07-28 18:40:00 +00001130 DAG.getMachineFunction().getFrameInfo().setFrameAddressIsTaken(true);
Dan Gohman94c65662016-02-16 23:48:04 +00001131 EVT VT = Op.getValueType();
Daniel Sanders05c145d2019-08-12 22:40:45 +00001132 Register FP =
Dan Gohman94c65662016-02-16 23:48:04 +00001133 Subtarget->getRegisterInfo()->getFrameRegister(DAG.getMachineFunction());
1134 return DAG.getCopyFromReg(DAG.getEntryNode(), SDLoc(Op), FP, VT);
1135}
1136
JF Bastienaf111db2015-08-24 22:16:48 +00001137SDValue WebAssemblyTargetLowering::LowerGlobalAddress(SDValue Op,
1138 SelectionDAG &DAG) const {
1139 SDLoc DL(Op);
1140 const auto *GA = cast<GlobalAddressSDNode>(Op);
1141 EVT VT = Op.getValueType();
Dan Gohman26c67652016-01-11 23:38:05 +00001142 assert(GA->getTargetFlags() == 0 &&
1143 "Unexpected target flags on generic GlobalAddressSDNode");
JF Bastienaf111db2015-08-24 22:16:48 +00001144 if (GA->getAddressSpace() != 0)
1145 fail(DL, DAG, "WebAssembly only expects the 0 address space");
Sam Clegg492f7522019-03-26 19:46:15 +00001146
Sam Cleggef4c66c2019-04-03 00:17:29 +00001147 unsigned OperandFlags = 0;
Sam Clegg492f7522019-03-26 19:46:15 +00001148 if (isPositionIndependent()) {
1149 const GlobalValue *GV = GA->getGlobal();
1150 if (getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV)) {
1151 MachineFunction &MF = DAG.getMachineFunction();
1152 MVT PtrVT = getPointerTy(MF.getDataLayout());
1153 const char *BaseName;
Sam Clegg2a7cac92019-04-04 17:43:50 +00001154 if (GV->getValueType()->isFunctionTy()) {
Sam Clegg492f7522019-03-26 19:46:15 +00001155 BaseName = MF.createExternalSymbolName("__table_base");
Sam Clegg2a7cac92019-04-04 17:43:50 +00001156 OperandFlags = WebAssemblyII::MO_TABLE_BASE_REL;
1157 }
1158 else {
Sam Clegg492f7522019-03-26 19:46:15 +00001159 BaseName = MF.createExternalSymbolName("__memory_base");
Sam Clegg2a7cac92019-04-04 17:43:50 +00001160 OperandFlags = WebAssemblyII::MO_MEMORY_BASE_REL;
1161 }
Sam Clegg492f7522019-03-26 19:46:15 +00001162 SDValue BaseAddr =
1163 DAG.getNode(WebAssemblyISD::Wrapper, DL, PtrVT,
1164 DAG.getTargetExternalSymbol(BaseName, PtrVT));
1165
1166 SDValue SymAddr = DAG.getNode(
1167 WebAssemblyISD::WrapperPIC, DL, VT,
Sam Clegg2a7cac92019-04-04 17:43:50 +00001168 DAG.getTargetGlobalAddress(GA->getGlobal(), DL, VT, GA->getOffset(),
1169 OperandFlags));
Sam Clegg492f7522019-03-26 19:46:15 +00001170
1171 return DAG.getNode(ISD::ADD, DL, VT, BaseAddr, SymAddr);
1172 } else {
Sam Cleggef4c66c2019-04-03 00:17:29 +00001173 OperandFlags = WebAssemblyII::MO_GOT;
Sam Clegg492f7522019-03-26 19:46:15 +00001174 }
1175 }
1176
1177 return DAG.getNode(WebAssemblyISD::Wrapper, DL, VT,
1178 DAG.getTargetGlobalAddress(GA->getGlobal(), DL, VT,
Sam Cleggef4c66c2019-04-03 00:17:29 +00001179 GA->getOffset(), OperandFlags));
JF Bastienaf111db2015-08-24 22:16:48 +00001180}
1181
Heejin Ahnf208f632018-09-05 01:27:38 +00001182SDValue
1183WebAssemblyTargetLowering::LowerExternalSymbol(SDValue Op,
1184 SelectionDAG &DAG) const {
Dan Gohman2c8fe6a2015-11-25 16:44:29 +00001185 SDLoc DL(Op);
1186 const auto *ES = cast<ExternalSymbolSDNode>(Op);
1187 EVT VT = Op.getValueType();
Dan Gohman26c67652016-01-11 23:38:05 +00001188 assert(ES->getTargetFlags() == 0 &&
1189 "Unexpected target flags on generic ExternalSymbolSDNode");
Sam Cleggef4c66c2019-04-03 00:17:29 +00001190 return DAG.getNode(WebAssemblyISD::Wrapper, DL, VT,
1191 DAG.getTargetExternalSymbol(ES->getSymbol(), VT));
Dan Gohman2c8fe6a2015-11-25 16:44:29 +00001192}
1193
Dan Gohman950a13c2015-09-16 16:51:30 +00001194SDValue WebAssemblyTargetLowering::LowerJumpTable(SDValue Op,
1195 SelectionDAG &DAG) const {
1196 // There's no need for a Wrapper node because we always incorporate a jump
Dan Gohman14026062016-03-08 03:18:12 +00001197 // table operand into a BR_TABLE instruction, rather than ever
Dan Gohmanbb7ce8e2015-11-20 03:02:49 +00001198 // materializing it in a register.
Dan Gohman950a13c2015-09-16 16:51:30 +00001199 const JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
1200 return DAG.getTargetJumpTable(JT->getIndex(), Op.getValueType(),
1201 JT->getTargetFlags());
1202}
1203
1204SDValue WebAssemblyTargetLowering::LowerBR_JT(SDValue Op,
1205 SelectionDAG &DAG) const {
1206 SDLoc DL(Op);
1207 SDValue Chain = Op.getOperand(0);
1208 const auto *JT = cast<JumpTableSDNode>(Op.getOperand(1));
1209 SDValue Index = Op.getOperand(2);
1210 assert(JT->getTargetFlags() == 0 && "WebAssembly doesn't set target flags");
1211
1212 SmallVector<SDValue, 8> Ops;
1213 Ops.push_back(Chain);
1214 Ops.push_back(Index);
1215
1216 MachineJumpTableInfo *MJTI = DAG.getMachineFunction().getJumpTableInfo();
1217 const auto &MBBs = MJTI->getJumpTables()[JT->getIndex()].MBBs;
1218
Dan Gohman14026062016-03-08 03:18:12 +00001219 // Add an operand for each case.
Heejin Ahnf208f632018-09-05 01:27:38 +00001220 for (auto MBB : MBBs)
1221 Ops.push_back(DAG.getBasicBlock(MBB));
Dan Gohman14026062016-03-08 03:18:12 +00001222
Dan Gohman950a13c2015-09-16 16:51:30 +00001223 // TODO: For now, we just pick something arbitrary for a default case for now.
1224 // We really want to sniff out the guard and put in the real default case (and
1225 // delete the guard).
1226 Ops.push_back(DAG.getBasicBlock(MBBs[0]));
1227
Dan Gohman14026062016-03-08 03:18:12 +00001228 return DAG.getNode(WebAssemblyISD::BR_TABLE, DL, MVT::Other, Ops);
Dan Gohman950a13c2015-09-16 16:51:30 +00001229}
1230
Dan Gohman35bfb242015-12-04 23:22:35 +00001231SDValue WebAssemblyTargetLowering::LowerVASTART(SDValue Op,
1232 SelectionDAG &DAG) const {
1233 SDLoc DL(Op);
1234 EVT PtrVT = getPointerTy(DAG.getMachineFunction().getDataLayout());
1235
Derek Schuff27501e22016-02-10 19:51:04 +00001236 auto *MFI = DAG.getMachineFunction().getInfo<WebAssemblyFunctionInfo>();
Dan Gohman35bfb242015-12-04 23:22:35 +00001237 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
Derek Schuff27501e22016-02-10 19:51:04 +00001238
1239 SDValue ArgN = DAG.getCopyFromReg(DAG.getEntryNode(), DL,
1240 MFI->getVarargBufferVreg(), PtrVT);
1241 return DAG.getStore(Op.getOperand(0), DL, ArgN, Op.getOperand(1),
Derek Schuff1a946e42016-07-15 19:35:43 +00001242 MachinePointerInfo(SV), 0);
Dan Gohman35bfb242015-12-04 23:22:35 +00001243}
1244
Heejin Ahnd6f48782019-01-30 03:21:57 +00001245SDValue WebAssemblyTargetLowering::LowerIntrinsic(SDValue Op,
1246 SelectionDAG &DAG) const {
1247 MachineFunction &MF = DAG.getMachineFunction();
1248 unsigned IntNo;
1249 switch (Op.getOpcode()) {
1250 case ISD::INTRINSIC_VOID:
1251 case ISD::INTRINSIC_W_CHAIN:
1252 IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
1253 break;
1254 case ISD::INTRINSIC_WO_CHAIN:
1255 IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
1256 break;
1257 default:
1258 llvm_unreachable("Invalid intrinsic");
1259 }
Heejin Ahn5ef4d5f2018-05-31 22:25:54 +00001260 SDLoc DL(Op);
Heejin Ahnd6f48782019-01-30 03:21:57 +00001261
Heejin Ahn5ef4d5f2018-05-31 22:25:54 +00001262 switch (IntNo) {
1263 default:
Heejin Ahn18c56a02019-02-04 19:13:39 +00001264 return SDValue(); // Don't custom lower most intrinsics.
Thomas Lively5d461c92018-10-03 23:02:23 +00001265
Heejin Ahn24faf852018-10-25 23:55:10 +00001266 case Intrinsic::wasm_lsda: {
Heejin Ahn24faf852018-10-25 23:55:10 +00001267 EVT VT = Op.getValueType();
1268 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1269 MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
1270 auto &Context = MF.getMMI().getContext();
1271 MCSymbol *S = Context.getOrCreateSymbol(Twine("GCC_except_table") +
1272 Twine(MF.getFunctionNumber()));
1273 return DAG.getNode(WebAssemblyISD::Wrapper, DL, VT,
1274 DAG.getMCSymbol(S, PtrVT));
1275 }
Heejin Ahnda419bd2018-11-14 02:46:21 +00001276
1277 case Intrinsic::wasm_throw: {
Heejin Ahnd6f48782019-01-30 03:21:57 +00001278 // We only support C++ exceptions for now
Heejin Ahnda419bd2018-11-14 02:46:21 +00001279 int Tag = cast<ConstantSDNode>(Op.getOperand(2).getNode())->getZExtValue();
Heejin Ahnd6f48782019-01-30 03:21:57 +00001280 if (Tag != CPP_EXCEPTION)
Heejin Ahnda419bd2018-11-14 02:46:21 +00001281 llvm_unreachable("Invalid tag!");
Heejin Ahnd6f48782019-01-30 03:21:57 +00001282 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1283 MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
1284 const char *SymName = MF.createExternalSymbolName("__cpp_exception");
Sam Cleggef4c66c2019-04-03 00:17:29 +00001285 SDValue SymNode = DAG.getNode(WebAssemblyISD::Wrapper, DL, PtrVT,
1286 DAG.getTargetExternalSymbol(SymName, PtrVT));
Heejin Ahnd6f48782019-01-30 03:21:57 +00001287 return DAG.getNode(WebAssemblyISD::THROW, DL,
1288 MVT::Other, // outchain type
1289 {
1290 Op.getOperand(0), // inchain
1291 SymNode, // exception symbol
1292 Op.getOperand(3) // thrown value
1293 });
Heejin Ahnda419bd2018-11-14 02:46:21 +00001294 }
1295 }
1296}
1297
1298SDValue
Thomas Lively64a39a12019-01-10 22:32:11 +00001299WebAssemblyTargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
1300 SelectionDAG &DAG) const {
Thomas Lively3d9ca002019-06-04 21:08:20 +00001301 SDLoc DL(Op);
Thomas Lively64a39a12019-01-10 22:32:11 +00001302 // If sign extension operations are disabled, allow sext_inreg only if operand
1303 // is a vector extract. SIMD does not depend on sign extension operations, but
1304 // allowing sext_inreg in this context lets us have simple patterns to select
1305 // extract_lane_s instructions. Expanding sext_inreg everywhere would be
1306 // simpler in this file, but would necessitate large and brittle patterns to
1307 // undo the expansion and select extract_lane_s instructions.
1308 assert(!Subtarget->hasSignExt() && Subtarget->hasSIMD128());
Thomas Lively3d9ca002019-06-04 21:08:20 +00001309 if (Op.getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
1310 const SDValue &Extract = Op.getOperand(0);
1311 MVT VecT = Extract.getOperand(0).getSimpleValueType();
1312 MVT ExtractedLaneT = static_cast<VTSDNode *>(Op.getOperand(1).getNode())
1313 ->getVT()
1314 .getSimpleVT();
1315 MVT ExtractedVecT =
1316 MVT::getVectorVT(ExtractedLaneT, 128 / ExtractedLaneT.getSizeInBits());
1317 if (ExtractedVecT == VecT)
1318 return Op;
1319 // Bitcast vector to appropriate type to ensure ISel pattern coverage
1320 const SDValue &Index = Extract.getOperand(1);
1321 unsigned IndexVal =
1322 static_cast<ConstantSDNode *>(Index.getNode())->getZExtValue();
1323 unsigned Scale =
1324 ExtractedVecT.getVectorNumElements() / VecT.getVectorNumElements();
1325 assert(Scale > 1);
1326 SDValue NewIndex =
1327 DAG.getConstant(IndexVal * Scale, DL, Index.getValueType());
1328 SDValue NewExtract = DAG.getNode(
1329 ISD::EXTRACT_VECTOR_ELT, DL, Extract.getValueType(),
1330 DAG.getBitcast(ExtractedVecT, Extract.getOperand(0)), NewIndex);
1331 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, Op.getValueType(),
1332 NewExtract, Op.getOperand(1));
1333 }
Thomas Lively64a39a12019-01-10 22:32:11 +00001334 // Otherwise expand
1335 return SDValue();
1336}
1337
Thomas Lively079816e2019-01-30 02:23:29 +00001338SDValue WebAssemblyTargetLowering::LowerBUILD_VECTOR(SDValue Op,
1339 SelectionDAG &DAG) const {
1340 SDLoc DL(Op);
1341 const EVT VecT = Op.getValueType();
1342 const EVT LaneT = Op.getOperand(0).getValueType();
1343 const size_t Lanes = Op.getNumOperands();
Thomas Livelyd5b7a4e2019-10-09 17:39:19 +00001344 bool CanSwizzle = Subtarget->hasUnimplementedSIMD128() && VecT == MVT::v16i8;
1345
1346 // BUILD_VECTORs are lowered to the instruction that initializes the highest
1347 // possible number of lanes at once followed by a sequence of replace_lane
1348 // instructions to individually initialize any remaining lanes.
1349
1350 // TODO: Tune this. For example, lanewise swizzling is very expensive, so
1351 // swizzled lanes should be given greater weight.
1352
1353 // TODO: Investigate building vectors by shuffling together vectors built by
1354 // separately specialized means.
1355
Thomas Lively079816e2019-01-30 02:23:29 +00001356 auto IsConstant = [](const SDValue &V) {
1357 return V.getOpcode() == ISD::Constant || V.getOpcode() == ISD::ConstantFP;
1358 };
1359
Thomas Livelyd5b7a4e2019-10-09 17:39:19 +00001360 // Returns the source vector and index vector pair if they exist. Checks for:
1361 // (extract_vector_elt
1362 // $src,
1363 // (sign_extend_inreg (extract_vector_elt $indices, $i))
1364 // )
1365 auto GetSwizzleSrcs = [](size_t I, const SDValue &Lane) {
1366 auto Bail = std::make_pair(SDValue(), SDValue());
1367 if (Lane->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
1368 return Bail;
1369 const SDValue &SwizzleSrc = Lane->getOperand(0);
1370 const SDValue &IndexExt = Lane->getOperand(1);
1371 if (IndexExt->getOpcode() != ISD::SIGN_EXTEND_INREG)
1372 return Bail;
1373 const SDValue &Index = IndexExt->getOperand(0);
1374 if (Index->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
1375 return Bail;
1376 const SDValue &SwizzleIndices = Index->getOperand(0);
1377 if (SwizzleSrc.getValueType() != MVT::v16i8 ||
1378 SwizzleIndices.getValueType() != MVT::v16i8 ||
1379 Index->getOperand(1)->getOpcode() != ISD::Constant ||
1380 Index->getConstantOperandVal(1) != I)
1381 return Bail;
1382 return std::make_pair(SwizzleSrc, SwizzleIndices);
1383 };
1384
1385 using ValueEntry = std::pair<SDValue, size_t>;
1386 SmallVector<ValueEntry, 16> SplatValueCounts;
1387
1388 using SwizzleEntry = std::pair<std::pair<SDValue, SDValue>, size_t>;
1389 SmallVector<SwizzleEntry, 16> SwizzleCounts;
1390
1391 auto AddCount = [](auto &Counts, const auto &Val) {
1392 auto CountIt = std::find_if(Counts.begin(), Counts.end(),
1393 [&Val](auto E) { return E.first == Val; });
1394 if (CountIt == Counts.end()) {
1395 Counts.emplace_back(Val, 1);
Thomas Lively079816e2019-01-30 02:23:29 +00001396 } else {
1397 CountIt->second++;
1398 }
Thomas Livelyd5b7a4e2019-10-09 17:39:19 +00001399 };
Thomas Lively079816e2019-01-30 02:23:29 +00001400
Thomas Livelyd5b7a4e2019-10-09 17:39:19 +00001401 auto GetMostCommon = [](auto &Counts) {
1402 auto CommonIt =
1403 std::max_element(Counts.begin(), Counts.end(),
1404 [](auto A, auto B) { return A.second < B.second; });
1405 assert(CommonIt != Counts.end() && "Unexpected all-undef build_vector");
1406 return *CommonIt;
1407 };
1408
1409 size_t NumConstantLanes = 0;
1410
1411 // Count eligible lanes for each type of vector creation op
1412 for (size_t I = 0; I < Lanes; ++I) {
1413 const SDValue &Lane = Op->getOperand(I);
1414 if (Lane.isUndef())
1415 continue;
1416
1417 AddCount(SplatValueCounts, Lane);
1418
1419 if (IsConstant(Lane)) {
1420 NumConstantLanes++;
1421 } else if (CanSwizzle) {
1422 auto SwizzleSrcs = GetSwizzleSrcs(I, Lane);
1423 if (SwizzleSrcs.first)
1424 AddCount(SwizzleCounts, SwizzleSrcs);
1425 }
1426 }
1427
1428 SDValue SplatValue;
1429 size_t NumSplatLanes;
1430 std::tie(SplatValue, NumSplatLanes) = GetMostCommon(SplatValueCounts);
1431
1432 SDValue SwizzleSrc;
1433 SDValue SwizzleIndices;
1434 size_t NumSwizzleLanes = 0;
1435 if (SwizzleCounts.size())
1436 std::forward_as_tuple(std::tie(SwizzleSrc, SwizzleIndices),
1437 NumSwizzleLanes) = GetMostCommon(SwizzleCounts);
1438
1439 // Predicate returning true if the lane is properly initialized by the
1440 // original instruction
1441 std::function<bool(size_t, const SDValue &)> IsLaneConstructed;
1442 SDValue Result;
Thomas Lively079816e2019-01-30 02:23:29 +00001443 if (Subtarget->hasUnimplementedSIMD128()) {
Thomas Livelyd5b7a4e2019-10-09 17:39:19 +00001444 // Prefer swizzles over vector consts over splats
1445 if (NumSwizzleLanes >= NumSplatLanes &&
1446 NumSwizzleLanes >= NumConstantLanes) {
1447 Result = DAG.getNode(WebAssemblyISD::SWIZZLE, DL, VecT, SwizzleSrc,
1448 SwizzleIndices);
1449 auto Swizzled = std::make_pair(SwizzleSrc, SwizzleIndices);
1450 IsLaneConstructed = [&, Swizzled](size_t I, const SDValue &Lane) {
1451 return Swizzled == GetSwizzleSrcs(I, Lane);
1452 };
1453 } else if (NumConstantLanes >= NumSplatLanes) {
Thomas Lively079816e2019-01-30 02:23:29 +00001454 SmallVector<SDValue, 16> ConstLanes;
1455 for (const SDValue &Lane : Op->op_values()) {
1456 if (IsConstant(Lane)) {
1457 ConstLanes.push_back(Lane);
1458 } else if (LaneT.isFloatingPoint()) {
1459 ConstLanes.push_back(DAG.getConstantFP(0, DL, LaneT));
1460 } else {
1461 ConstLanes.push_back(DAG.getConstant(0, DL, LaneT));
1462 }
1463 }
Thomas Livelyd5b7a4e2019-10-09 17:39:19 +00001464 Result = DAG.getBuildVector(VecT, DL, ConstLanes);
1465 IsLaneConstructed = [&](size_t _, const SDValue &Lane) {
1466 return IsConstant(Lane);
1467 };
Thomas Lively079816e2019-01-30 02:23:29 +00001468 }
1469 }
Thomas Livelyd5b7a4e2019-10-09 17:39:19 +00001470 if (!Result) {
1471 // Use a splat, but possibly a load_splat
1472 LoadSDNode *SplattedLoad;
1473 if (Subtarget->hasUnimplementedSIMD128() &&
1474 (SplattedLoad = dyn_cast<LoadSDNode>(SplatValue)) &&
1475 SplattedLoad->getMemoryVT() == VecT.getVectorElementType()) {
Thomas Lively3479fd22019-10-31 20:01:02 -07001476 Result = DAG.getMemIntrinsicNode(
1477 WebAssemblyISD::LOAD_SPLAT, DL, DAG.getVTList(VecT),
1478 {SplattedLoad->getChain(), SplattedLoad->getBasePtr(),
1479 SplattedLoad->getOffset()},
1480 SplattedLoad->getMemoryVT(), SplattedLoad->getMemOperand());
Thomas Livelyd5b7a4e2019-10-09 17:39:19 +00001481 } else {
1482 Result = DAG.getSplatBuildVector(VecT, DL, SplatValue);
1483 }
1484 IsLaneConstructed = [&](size_t _, const SDValue &Lane) {
1485 return Lane == SplatValue;
1486 };
Thomas Lively99d3dd22019-09-23 20:42:12 +00001487 }
Thomas Livelyd5b7a4e2019-10-09 17:39:19 +00001488
1489 // Add replace_lane instructions for any unhandled values
Thomas Lively079816e2019-01-30 02:23:29 +00001490 for (size_t I = 0; I < Lanes; ++I) {
1491 const SDValue &Lane = Op->getOperand(I);
Thomas Livelyd5b7a4e2019-10-09 17:39:19 +00001492 if (!Lane.isUndef() && !IsLaneConstructed(I, Lane))
Thomas Lively079816e2019-01-30 02:23:29 +00001493 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VecT, Result, Lane,
1494 DAG.getConstant(I, DL, MVT::i32));
1495 }
Thomas Livelyd5b7a4e2019-10-09 17:39:19 +00001496
Thomas Lively079816e2019-01-30 02:23:29 +00001497 return Result;
1498}
1499
Thomas Lively64a39a12019-01-10 22:32:11 +00001500SDValue
Thomas Livelya0d25812018-09-07 21:54:46 +00001501WebAssemblyTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
1502 SelectionDAG &DAG) const {
1503 SDLoc DL(Op);
1504 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Op.getNode())->getMask();
1505 MVT VecType = Op.getOperand(0).getSimpleValueType();
1506 assert(VecType.is128BitVector() && "Unexpected shuffle vector type");
1507 size_t LaneBytes = VecType.getVectorElementType().getSizeInBits() / 8;
1508
1509 // Space for two vector args and sixteen mask indices
1510 SDValue Ops[18];
1511 size_t OpIdx = 0;
1512 Ops[OpIdx++] = Op.getOperand(0);
1513 Ops[OpIdx++] = Op.getOperand(1);
1514
1515 // Expand mask indices to byte indices and materialize them as operands
Heejin Ahn18c56a02019-02-04 19:13:39 +00001516 for (int M : Mask) {
Thomas Livelya0d25812018-09-07 21:54:46 +00001517 for (size_t J = 0; J < LaneBytes; ++J) {
Thomas Lively11a332d02018-10-19 19:08:06 +00001518 // Lower undefs (represented by -1 in mask) to zero
Heejin Ahn18c56a02019-02-04 19:13:39 +00001519 uint64_t ByteIndex = M == -1 ? 0 : (uint64_t)M * LaneBytes + J;
Thomas Lively11a332d02018-10-19 19:08:06 +00001520 Ops[OpIdx++] = DAG.getConstant(ByteIndex, DL, MVT::i32);
Thomas Livelya0d25812018-09-07 21:54:46 +00001521 }
1522 }
1523
Thomas Livelyed951342018-10-24 23:27:40 +00001524 return DAG.getNode(WebAssemblyISD::SHUFFLE, DL, Op.getValueType(), Ops);
Thomas Livelya0d25812018-09-07 21:54:46 +00001525}
1526
Thomas Livelyecb7daf2019-11-01 10:21:00 -07001527SDValue WebAssemblyTargetLowering::LowerSETCC(SDValue Op,
1528 SelectionDAG &DAG) const {
1529 SDLoc DL(Op);
1530 // The legalizer does not know how to expand the comparison modes of i64x2
1531 // vectors because no comparison modes are supported. We could solve this by
1532 // expanding all i64x2 SETCC nodes, but that seems to expand f64x2 SETCC nodes
1533 // (which return i64x2 results) as well. So instead we manually unroll i64x2
1534 // comparisons here.
1535 assert(Subtarget->hasUnimplementedSIMD128());
1536 assert(Op->getOperand(0)->getSimpleValueType(0) == MVT::v2i64);
1537 SmallVector<SDValue, 2> LHS, RHS;
1538 DAG.ExtractVectorElements(Op->getOperand(0), LHS);
1539 DAG.ExtractVectorElements(Op->getOperand(1), RHS);
1540 const SDValue &CC = Op->getOperand(2);
1541 auto MakeLane = [&](unsigned I) {
1542 return DAG.getNode(ISD::SELECT_CC, DL, MVT::i64, LHS[I], RHS[I],
1543 DAG.getConstant(uint64_t(-1), DL, MVT::i64),
1544 DAG.getConstant(uint64_t(0), DL, MVT::i64), CC);
1545 };
1546 return DAG.getBuildVector(Op->getValueType(0), DL,
1547 {MakeLane(0), MakeLane(1)});
1548}
1549
Thomas Livelyfb84fd72018-11-02 00:06:56 +00001550SDValue
1551WebAssemblyTargetLowering::LowerAccessVectorElement(SDValue Op,
1552 SelectionDAG &DAG) const {
1553 // Allow constant lane indices, expand variable lane indices
1554 SDNode *IdxNode = Op.getOperand(Op.getNumOperands() - 1).getNode();
1555 if (isa<ConstantSDNode>(IdxNode) || IdxNode->isUndef())
1556 return Op;
1557 else
1558 // Perform default expansion
1559 return SDValue();
1560}
1561
Heejin Ahn18c56a02019-02-04 19:13:39 +00001562static SDValue unrollVectorShift(SDValue Op, SelectionDAG &DAG) {
Thomas Lively6bf2b402019-01-15 02:16:03 +00001563 EVT LaneT = Op.getSimpleValueType().getVectorElementType();
1564 // 32-bit and 64-bit unrolled shifts will have proper semantics
1565 if (LaneT.bitsGE(MVT::i32))
1566 return DAG.UnrollVectorOp(Op.getNode());
1567 // Otherwise mask the shift value to get proper semantics from 32-bit shift
1568 SDLoc DL(Op);
1569 SDValue ShiftVal = Op.getOperand(1);
1570 uint64_t MaskVal = LaneT.getSizeInBits() - 1;
1571 SDValue MaskedShiftVal = DAG.getNode(
1572 ISD::AND, // mask opcode
1573 DL, ShiftVal.getValueType(), // masked value type
1574 ShiftVal, // original shift value operand
1575 DAG.getConstant(MaskVal, DL, ShiftVal.getValueType()) // mask operand
1576 );
1577
1578 return DAG.UnrollVectorOp(
1579 DAG.getNode(Op.getOpcode(), // original shift opcode
1580 DL, Op.getValueType(), // original return type
1581 Op.getOperand(0), // original vector operand,
1582 MaskedShiftVal // new masked shift value operand
1583 )
1584 .getNode());
1585}
1586
Thomas Lively55735d52018-10-20 01:31:18 +00001587SDValue WebAssemblyTargetLowering::LowerShift(SDValue Op,
1588 SelectionDAG &DAG) const {
1589 SDLoc DL(Op);
Thomas Livelyb2382c82018-11-02 00:39:57 +00001590
1591 // Only manually lower vector shifts
1592 assert(Op.getSimpleValueType().isVector());
1593
1594 // Unroll non-splat vector shifts
1595 BuildVectorSDNode *ShiftVec;
1596 SDValue SplatVal;
1597 if (!(ShiftVec = dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode())) ||
1598 !(SplatVal = ShiftVec->getSplatValue()))
Heejin Ahn18c56a02019-02-04 19:13:39 +00001599 return unrollVectorShift(Op, DAG);
Thomas Livelyb2382c82018-11-02 00:39:57 +00001600
1601 // All splats except i64x2 const splats are handled by patterns
Heejin Ahn18c56a02019-02-04 19:13:39 +00001602 auto *SplatConst = dyn_cast<ConstantSDNode>(SplatVal);
Thomas Livelyb2382c82018-11-02 00:39:57 +00001603 if (!SplatConst || Op.getSimpleValueType() != MVT::v2i64)
Thomas Lively55735d52018-10-20 01:31:18 +00001604 return Op;
Thomas Livelyb2382c82018-11-02 00:39:57 +00001605
1606 // i64x2 const splats are custom lowered to avoid unnecessary wraps
Thomas Lively55735d52018-10-20 01:31:18 +00001607 unsigned Opcode;
1608 switch (Op.getOpcode()) {
1609 case ISD::SHL:
1610 Opcode = WebAssemblyISD::VEC_SHL;
1611 break;
1612 case ISD::SRA:
1613 Opcode = WebAssemblyISD::VEC_SHR_S;
1614 break;
1615 case ISD::SRL:
1616 Opcode = WebAssemblyISD::VEC_SHR_U;
1617 break;
1618 default:
1619 llvm_unreachable("unexpected opcode");
Thomas Lively55735d52018-10-20 01:31:18 +00001620 }
Thomas Livelyb2382c82018-11-02 00:39:57 +00001621 APInt Shift = SplatConst->getAPIntValue().zextOrTrunc(32);
Thomas Lively55735d52018-10-20 01:31:18 +00001622 return DAG.getNode(Opcode, DL, Op.getValueType(), Op.getOperand(0),
Thomas Livelyb2382c82018-11-02 00:39:57 +00001623 DAG.getConstant(Shift, DL, MVT::i32));
Thomas Lively55735d52018-10-20 01:31:18 +00001624}
1625
Dan Gohman10e730a2015-06-29 23:51:55 +00001626//===----------------------------------------------------------------------===//
1627// WebAssembly Optimization Hooks
1628//===----------------------------------------------------------------------===//