1 //=- WebAssemblyISelLowering.cpp - WebAssembly DAG Lowering Implementation -==// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 /// 9 /// \file 10 /// This file implements the WebAssemblyTargetLowering class. 11 /// 12 //===----------------------------------------------------------------------===// 13 14 #include "WebAssemblyISelLowering.h" 15 #include "MCTargetDesc/WebAssemblyMCTargetDesc.h" 16 #include "WebAssemblyMachineFunctionInfo.h" 17 #include "WebAssemblySubtarget.h" 18 #include "WebAssemblyTargetMachine.h" 19 #include "llvm/CodeGen/Analysis.h" 20 #include "llvm/CodeGen/CallingConvLower.h" 21 #include "llvm/CodeGen/MachineInstrBuilder.h" 22 #include "llvm/CodeGen/MachineJumpTableInfo.h" 23 #include "llvm/CodeGen/MachineModuleInfo.h" 24 #include "llvm/CodeGen/MachineRegisterInfo.h" 25 #include "llvm/CodeGen/SelectionDAG.h" 26 #include "llvm/CodeGen/WasmEHFuncInfo.h" 27 #include "llvm/IR/DiagnosticInfo.h" 28 #include "llvm/IR/DiagnosticPrinter.h" 29 #include "llvm/IR/Function.h" 30 #include "llvm/IR/Intrinsics.h" 31 #include "llvm/IR/IntrinsicsWebAssembly.h" 32 #include "llvm/Support/Debug.h" 33 #include "llvm/Support/ErrorHandling.h" 34 #include "llvm/Support/raw_ostream.h" 35 #include "llvm/Target/TargetOptions.h" 36 using namespace llvm; 37 38 #define DEBUG_TYPE "wasm-lower" 39 40 WebAssemblyTargetLowering::WebAssemblyTargetLowering( 41 const TargetMachine &TM, const WebAssemblySubtarget &STI) 42 : TargetLowering(TM), Subtarget(&STI) { 43 auto MVTPtr = Subtarget->hasAddr64() ? MVT::i64 : MVT::i32; 44 45 // Booleans always contain 0 or 1. 46 setBooleanContents(ZeroOrOneBooleanContent); 47 // Except in SIMD vectors 48 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent); 49 // We don't know the microarchitecture here, so just reduce register pressure. 50 setSchedulingPreference(Sched::RegPressure); 51 // Tell ISel that we have a stack pointer. 52 setStackPointerRegisterToSaveRestore( 53 Subtarget->hasAddr64() ? WebAssembly::SP64 : WebAssembly::SP32); 54 // Set up the register classes. 55 addRegisterClass(MVT::i32, &WebAssembly::I32RegClass); 56 addRegisterClass(MVT::i64, &WebAssembly::I64RegClass); 57 addRegisterClass(MVT::f32, &WebAssembly::F32RegClass); 58 addRegisterClass(MVT::f64, &WebAssembly::F64RegClass); 59 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); 64 addRegisterClass(MVT::v2i64, &WebAssembly::V128RegClass); 65 addRegisterClass(MVT::v2f64, &WebAssembly::V128RegClass); 66 } 67 // Compute derived properties from the register classes. 68 computeRegisterProperties(Subtarget->getRegisterInfo()); 69 70 setOperationAction(ISD::GlobalAddress, MVTPtr, Custom); 71 setOperationAction(ISD::ExternalSymbol, MVTPtr, Custom); 72 setOperationAction(ISD::JumpTable, MVTPtr, Custom); 73 setOperationAction(ISD::BlockAddress, MVTPtr, Custom); 74 setOperationAction(ISD::BRIND, MVT::Other, Custom); 75 76 // 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 83 for (auto T : {MVT::f32, MVT::f64, MVT::v4f32, MVT::v2f64}) { 84 // 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); 90 // Expand floating-point library function operators. 91 for (auto Op : 92 {ISD::FSIN, ISD::FCOS, ISD::FSINCOS, ISD::FPOW, ISD::FREM, ISD::FMA}) 93 setOperationAction(Op, T, Expand); 94 // Note supported floating-point library function operators that otherwise 95 // default to expand. 96 for (auto Op : 97 {ISD::FCEIL, ISD::FFLOOR, ISD::FTRUNC, ISD::FNEARBYINT, ISD::FRINT}) 98 setOperationAction(Op, T, Legal); 99 // Support minimum and maximum, which otherwise default to expand. 100 setOperationAction(ISD::FMINIMUM, T, Legal); 101 setOperationAction(ISD::FMAXIMUM, T, Legal); 102 // 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); 107 } 108 109 // 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}) { 114 for (auto T : {MVT::i32, MVT::i64}) 115 setOperationAction(Op, T, Expand); 116 if (Subtarget->hasSIMD128()) 117 for (auto T : {MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64}) 118 setOperationAction(Op, T, Expand); 119 } 120 121 // 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 128 // Custom lower BUILD_VECTORs to minimize number of replace_lanes 129 for (auto T : {MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v4f32, MVT::v2i64, 130 MVT::v2f64}) 131 setOperationAction(ISD::BUILD_VECTOR, T, Custom); 132 133 // We have custom shuffle lowering to expose the shuffle mask 134 for (auto T : {MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v4f32, MVT::v2i64, 135 MVT::v2f64}) 136 setOperationAction(ISD::VECTOR_SHUFFLE, T, Custom); 137 138 // Custom lowering since wasm shifts must have a scalar shift amount 139 for (auto Op : {ISD::SHL, ISD::SRA, ISD::SRL}) 140 for (auto T : {MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64}) 141 setOperationAction(Op, T, Custom); 142 143 // Custom lower lane accesses to expand out variable indices 144 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}) 147 setOperationAction(Op, T, Custom); 148 149 // There is no i64x2.mul instruction 150 // TODO: Actually, there is now. Implement it. 151 setOperationAction(ISD::MUL, MVT::v2i64, Expand); 152 153 // There are no vector select instructions 154 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}) 157 setOperationAction(Op, T, Expand); 158 159 // Expand integer operations supported for scalars but not SIMD 160 for (auto Op : {ISD::CTLZ, ISD::CTTZ, ISD::CTPOP, ISD::SDIV, ISD::UDIV, 161 ISD::SREM, ISD::UREM, ISD::ROTL, ISD::ROTR}) 162 for (auto T : {MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64}) 163 setOperationAction(Op, T, Expand); 164 165 // But we do have integer min and max operations 166 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); 169 170 // Expand float operations supported for scalars but not SIMD 171 for (auto Op : {ISD::FCEIL, ISD::FFLOOR, ISD::FTRUNC, ISD::FNEARBYINT, 172 ISD::FCOPYSIGN, ISD::FLOG, ISD::FLOG2, ISD::FLOG10, 173 ISD::FEXP, ISD::FEXP2, ISD::FRINT}) 174 for (auto T : {MVT::v4f32, MVT::v2f64}) 175 setOperationAction(Op, T, Expand); 176 177 // Expand operations not supported for i64x2 vectors 178 for (unsigned CC = 0; CC < ISD::SETCC_INVALID; ++CC) 179 setCondCodeAction(static_cast<ISD::CondCode>(CC), MVT::v2i64, Custom); 180 181 // 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); 187 } 188 189 // As a special case, these operators use the type to mean the type to 190 // sign-extend from. 191 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); 192 if (!Subtarget->hasSignExt()) { 193 // Sign extends are legal only when extending a vector extract 194 auto Action = Subtarget->hasSIMD128() ? Custom : Expand; 195 for (auto T : {MVT::i8, MVT::i16, MVT::i32}) 196 setOperationAction(ISD::SIGN_EXTEND_INREG, T, Action); 197 } 198 for (auto T : MVT::integer_fixedlen_vector_valuetypes()) 199 setOperationAction(ISD::SIGN_EXTEND_INREG, T, Expand); 200 201 // Dynamic stack allocation: use the default expansion. 202 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand); 203 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand); 204 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVTPtr, Expand); 205 206 setOperationAction(ISD::FrameIndex, MVT::i32, Custom); 207 setOperationAction(ISD::CopyToReg, MVT::Other, Custom); 208 209 // 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 217 // WebAssembly doesn't have: 218 // - Floating-point extending loads. 219 // - Floating-point truncating stores. 220 // - i1 extending loads. 221 // - truncating SIMD stores and most extending loads 222 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f32, Expand); 223 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); 227 if (Subtarget->hasSIMD128()) { 228 for (auto T : {MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64, MVT::v4f32, 229 MVT::v2f64}) { 230 for (auto MemT : MVT::fixedlen_vector_valuetypes()) { 231 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 } 238 // 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 } 246 } 247 248 // Don't do anything clever with build_pairs 249 setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand); 250 251 // Trap lowers to wasm unreachable 252 setOperationAction(ISD::TRAP, MVT::Other, Legal); 253 254 // Exception handling intrinsics 255 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 256 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom); 257 258 setMaxAtomicSizeInBitsSupported(64); 259 260 // 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 265 // 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 270 // 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); 274 } 275 276 TargetLowering::AtomicExpansionKind 277 WebAssemblyTargetLowering::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 293 FastISel *WebAssemblyTargetLowering::createFastISel( 294 FunctionLoweringInfo &FuncInfo, const TargetLibraryInfo *LibInfo) const { 295 return WebAssembly::createFastISel(FuncInfo, LibInfo); 296 } 297 298 MVT WebAssemblyTargetLowering::getScalarShiftAmountTy(const DataLayout & /*DL*/, 299 EVT VT) const { 300 unsigned BitWidth = NextPowerOf2(VT.getSizeInBits() - 1); 301 if (BitWidth > 1 && BitWidth < 8) 302 BitWidth = 8; 303 304 if (BitWidth > 64) { 305 // The shift will be lowered to a libcall, and compiler-rt libcalls expect 306 // the count to be an i32. 307 BitWidth = 32; 308 assert(BitWidth >= Log2_32_Ceil(VT.getSizeInBits()) && 309 "32-bit shift counts ought to be enough for anyone"); 310 } 311 312 MVT Result = MVT::getIntegerVT(BitWidth); 313 assert(Result != MVT::INVALID_SIMPLE_VALUE_TYPE && 314 "Unable to represent scalar shift amount type"); 315 return Result; 316 } 317 318 // 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. 321 static MachineBasicBlock *LowerFPToInt(MachineInstr &MI, DebugLoc DL, 322 MachineBasicBlock *BB, 323 const TargetInstrInfo &TII, 324 bool IsUnsigned, bool Int64, 325 bool Float64, unsigned LoweredOpcode) { 326 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 327 328 Register OutReg = MI.getOperand(0).getReg(); 329 Register InReg = MI.getOperand(1).getReg(); 330 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; 334 unsigned GE = Float64 ? WebAssembly::GE_F64 : WebAssembly::GE_F32; 335 unsigned IConst = Int64 ? WebAssembly::CONST_I64 : WebAssembly::CONST_I32; 336 unsigned Eqz = WebAssembly::EQZ_I32; 337 unsigned And = WebAssembly::AND_I32; 338 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; 341 auto &Context = BB->getParent()->getFunction().getContext(); 342 Type *Ty = Float64 ? Type::getDoubleTy(Context) : Type::getFloatTy(Context); 343 344 const BasicBlock *LLVMBB = BB->getBasicBlock(); 345 MachineFunction *F = BB->getParent(); 346 MachineBasicBlock *TrueMBB = F->CreateMachineBasicBlock(LLVMBB); 347 MachineBasicBlock *FalseMBB = F->CreateMachineBasicBlock(LLVMBB); 348 MachineBasicBlock *DoneMBB = F->CreateMachineBasicBlock(LLVMBB); 349 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. 356 DoneMBB->splice(DoneMBB->begin(), BB, std::next(MI.getIterator()), BB->end()); 357 DoneMBB->transferSuccessorsAndUpdatePHIs(BB); 358 359 BB->addSuccessor(TrueMBB); 360 BB->addSuccessor(FalseMBB); 361 TrueMBB->addSuccessor(DoneMBB); 362 FalseMBB->addSuccessor(DoneMBB); 363 364 unsigned Tmp0, Tmp1, CmpReg, EqzReg, FalseReg, TrueReg; 365 Tmp0 = MRI.createVirtualRegister(MRI.getRegClass(InReg)); 366 Tmp1 = MRI.createVirtualRegister(MRI.getRegClass(InReg)); 367 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)); 371 372 MI.eraseFromParent(); 373 // For signed numbers, we can do a single comparison to determine whether 374 // fabs(x) is within range. 375 if (IsUnsigned) { 376 Tmp0 = InReg; 377 } else { 378 BuildMI(BB, DL, TII.get(Abs), Tmp0).addReg(InReg); 379 } 380 BuildMI(BB, DL, TII.get(FConst), Tmp1) 381 .addFPImm(cast<ConstantFP>(ConstantFP::get(Ty, CmpVal))); 382 BuildMI(BB, DL, TII.get(LT), CmpReg).addReg(Tmp0).addReg(Tmp1); 383 384 // For unsigned numbers, we have to do a separate comparison with zero. 385 if (IsUnsigned) { 386 Tmp1 = MRI.createVirtualRegister(MRI.getRegClass(InReg)); 387 Register SecondCmpReg = 388 MRI.createVirtualRegister(&WebAssembly::I32RegClass); 389 Register AndReg = MRI.createVirtualRegister(&WebAssembly::I32RegClass); 390 BuildMI(BB, DL, TII.get(FConst), Tmp1) 391 .addFPImm(cast<ConstantFP>(ConstantFP::get(Ty, 0.0))); 392 BuildMI(BB, DL, TII.get(GE), SecondCmpReg).addReg(Tmp0).addReg(Tmp1); 393 BuildMI(BB, DL, TII.get(And), AndReg).addReg(CmpReg).addReg(SecondCmpReg); 394 CmpReg = AndReg; 395 } 396 397 BuildMI(BB, DL, TII.get(Eqz), EqzReg).addReg(CmpReg); 398 399 // Create the CFG diamond to select between doing the conversion or using 400 // the substitute value. 401 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); 405 BuildMI(*DoneMBB, DoneMBB->begin(), DL, TII.get(TargetOpcode::PHI), OutReg) 406 .addReg(FalseReg) 407 .addMBB(FalseMBB) 408 .addReg(TrueReg) 409 .addMBB(TrueMBB); 410 411 return DoneMBB; 412 } 413 414 MachineBasicBlock *WebAssemblyTargetLowering::EmitInstrWithCustomInserter( 415 MachineInstr &MI, MachineBasicBlock *BB) const { 416 const TargetInstrInfo &TII = *Subtarget->getInstrInfo(); 417 DebugLoc DL = MI.getDebugLoc(); 418 419 switch (MI.getOpcode()) { 420 default: 421 llvm_unreachable("Unexpected instr type to insert"); 422 case WebAssembly::FP_TO_SINT_I32_F32: 423 return LowerFPToInt(MI, DL, BB, TII, false, false, false, 424 WebAssembly::I32_TRUNC_S_F32); 425 case WebAssembly::FP_TO_UINT_I32_F32: 426 return LowerFPToInt(MI, DL, BB, TII, true, false, false, 427 WebAssembly::I32_TRUNC_U_F32); 428 case WebAssembly::FP_TO_SINT_I64_F32: 429 return LowerFPToInt(MI, DL, BB, TII, false, true, false, 430 WebAssembly::I64_TRUNC_S_F32); 431 case WebAssembly::FP_TO_UINT_I64_F32: 432 return LowerFPToInt(MI, DL, BB, TII, true, true, false, 433 WebAssembly::I64_TRUNC_U_F32); 434 case WebAssembly::FP_TO_SINT_I32_F64: 435 return LowerFPToInt(MI, DL, BB, TII, false, false, true, 436 WebAssembly::I32_TRUNC_S_F64); 437 case WebAssembly::FP_TO_UINT_I32_F64: 438 return LowerFPToInt(MI, DL, BB, TII, true, false, true, 439 WebAssembly::I32_TRUNC_U_F64); 440 case WebAssembly::FP_TO_SINT_I64_F64: 441 return LowerFPToInt(MI, DL, BB, TII, false, true, true, 442 WebAssembly::I64_TRUNC_S_F64); 443 case WebAssembly::FP_TO_UINT_I64_F64: 444 return LowerFPToInt(MI, DL, BB, TII, true, true, true, 445 WebAssembly::I64_TRUNC_U_F64); 446 llvm_unreachable("Unexpected instruction to emit with custom inserter"); 447 } 448 } 449 450 const char * 451 WebAssemblyTargetLowering::getTargetNodeName(unsigned Opcode) const { 452 switch (static_cast<WebAssemblyISD::NodeType>(Opcode)) { 453 case WebAssemblyISD::FIRST_NUMBER: 454 case WebAssemblyISD::FIRST_MEM_OPCODE: 455 break; 456 #define HANDLE_NODETYPE(NODE) \ 457 case WebAssemblyISD::NODE: \ 458 return "WebAssemblyISD::" #NODE; 459 #define HANDLE_MEM_NODETYPE(NODE) HANDLE_NODETYPE(NODE) 460 #include "WebAssemblyISD.def" 461 #undef HANDLE_MEM_NODETYPE 462 #undef HANDLE_NODETYPE 463 } 464 return nullptr; 465 } 466 467 std::pair<unsigned, const TargetRegisterClass *> 468 WebAssemblyTargetLowering::getRegForInlineAsmConstraint( 469 const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const { 470 // First, see if this is a constraint that directly corresponds to a 471 // WebAssembly register class. 472 if (Constraint.size() == 1) { 473 switch (Constraint[0]) { 474 case 'r': 475 assert(VT != MVT::iPTR && "Pointer MVT not expected here"); 476 if (Subtarget->hasSIMD128() && VT.isVector()) { 477 if (VT.getSizeInBits() == 128) 478 return std::make_pair(0U, &WebAssembly::V128RegClass); 479 } 480 if (VT.isInteger() && !VT.isVector()) { 481 if (VT.getSizeInBits() <= 32) 482 return std::make_pair(0U, &WebAssembly::I32RegClass); 483 if (VT.getSizeInBits() <= 64) 484 return std::make_pair(0U, &WebAssembly::I64RegClass); 485 } 486 break; 487 default: 488 break; 489 } 490 } 491 492 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 493 } 494 495 bool WebAssemblyTargetLowering::isCheapToSpeculateCttz() const { 496 // Assume ctz is a relatively cheap operation. 497 return true; 498 } 499 500 bool WebAssemblyTargetLowering::isCheapToSpeculateCtlz() const { 501 // Assume clz is a relatively cheap operation. 502 return true; 503 } 504 505 bool WebAssemblyTargetLowering::isLegalAddressingMode(const DataLayout &DL, 506 const AddrMode &AM, 507 Type *Ty, unsigned AS, 508 Instruction *I) const { 509 // WebAssembly offsets are added as unsigned without wrapping. The 510 // isLegalAddressingMode gives us no way to determine if wrapping could be 511 // happening, so we approximate this by accepting only non-negative offsets. 512 if (AM.BaseOffs < 0) 513 return false; 514 515 // WebAssembly has no scale register operands. 516 if (AM.Scale != 0) 517 return false; 518 519 // Everything else is legal. 520 return true; 521 } 522 523 bool WebAssemblyTargetLowering::allowsMisalignedMemoryAccesses( 524 EVT /*VT*/, unsigned /*AddrSpace*/, unsigned /*Align*/, 525 MachineMemOperand::Flags /*Flags*/, bool *Fast) const { 526 // WebAssembly supports unaligned accesses, though it should be declared 527 // with the p2align attribute on loads and stores which do so, and there 528 // may be a performance impact. We tell LLVM they're "fast" because 529 // for the kinds of things that LLVM uses this for (merging adjacent stores 530 // of constants, etc.), WebAssembly implementations will either want the 531 // unaligned access or they'll split anyway. 532 if (Fast) 533 *Fast = true; 534 return true; 535 } 536 537 bool WebAssemblyTargetLowering::isIntDivCheap(EVT VT, 538 AttributeList Attr) const { 539 // The current thinking is that wasm engines will perform this optimization, 540 // so we can save on code size. 541 return true; 542 } 543 544 bool WebAssemblyTargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const { 545 if (!Subtarget->hasUnimplementedSIMD128()) 546 return false; 547 MVT ExtT = ExtVal.getSimpleValueType(); 548 MVT MemT = cast<LoadSDNode>(ExtVal->getOperand(0))->getSimpleValueType(0); 549 return (ExtT == MVT::v8i16 && MemT == MVT::v8i8) || 550 (ExtT == MVT::v4i32 && MemT == MVT::v4i16) || 551 (ExtT == MVT::v2i64 && MemT == MVT::v2i32); 552 } 553 554 EVT WebAssemblyTargetLowering::getSetCCResultType(const DataLayout &DL, 555 LLVMContext &C, 556 EVT VT) const { 557 if (VT.isVector()) 558 return VT.changeVectorElementTypeToInteger(); 559 560 return TargetLowering::getSetCCResultType(DL, C, VT); 561 } 562 563 bool WebAssemblyTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 564 const CallInst &I, 565 MachineFunction &MF, 566 unsigned Intrinsic) const { 567 switch (Intrinsic) { 568 case Intrinsic::wasm_atomic_notify: 569 Info.opc = ISD::INTRINSIC_W_CHAIN; 570 Info.memVT = MVT::i32; 571 Info.ptrVal = I.getArgOperand(0); 572 Info.offset = 0; 573 Info.align = Align(4); 574 // atomic.notify instruction does not really load the memory specified with 575 // this argument, but MachineMemOperand should either be load or store, so 576 // we set this to a load. 577 // FIXME Volatile isn't really correct, but currently all LLVM atomic 578 // instructions are treated as volatiles in the backend, so we should be 579 // consistent. The same applies for wasm_atomic_wait intrinsics too. 580 Info.flags = MachineMemOperand::MOVolatile | MachineMemOperand::MOLoad; 581 return true; 582 case Intrinsic::wasm_atomic_wait_i32: 583 Info.opc = ISD::INTRINSIC_W_CHAIN; 584 Info.memVT = MVT::i32; 585 Info.ptrVal = I.getArgOperand(0); 586 Info.offset = 0; 587 Info.align = Align(4); 588 Info.flags = MachineMemOperand::MOVolatile | MachineMemOperand::MOLoad; 589 return true; 590 case Intrinsic::wasm_atomic_wait_i64: 591 Info.opc = ISD::INTRINSIC_W_CHAIN; 592 Info.memVT = MVT::i64; 593 Info.ptrVal = I.getArgOperand(0); 594 Info.offset = 0; 595 Info.align = Align(8); 596 Info.flags = MachineMemOperand::MOVolatile | MachineMemOperand::MOLoad; 597 return true; 598 default: 599 return false; 600 } 601 } 602 603 //===----------------------------------------------------------------------===// 604 // WebAssembly Lowering private implementation. 605 //===----------------------------------------------------------------------===// 606 607 //===----------------------------------------------------------------------===// 608 // Lowering Code 609 //===----------------------------------------------------------------------===// 610 611 static void fail(const SDLoc &DL, SelectionDAG &DAG, const char *Msg) { 612 MachineFunction &MF = DAG.getMachineFunction(); 613 DAG.getContext()->diagnose( 614 DiagnosticInfoUnsupported(MF.getFunction(), Msg, DL.getDebugLoc())); 615 } 616 617 // Test whether the given calling convention is supported. 618 static bool callingConvSupported(CallingConv::ID CallConv) { 619 // We currently support the language-independent target-independent 620 // conventions. We don't yet have a way to annotate calls with properties like 621 // "cold", and we don't have any call-clobbered registers, so these are mostly 622 // all handled the same. 623 return CallConv == CallingConv::C || CallConv == CallingConv::Fast || 624 CallConv == CallingConv::Cold || 625 CallConv == CallingConv::PreserveMost || 626 CallConv == CallingConv::PreserveAll || 627 CallConv == CallingConv::CXX_FAST_TLS || 628 CallConv == CallingConv::WASM_EmscriptenInvoke || 629 CallConv == CallingConv::Swift; 630 } 631 632 SDValue 633 WebAssemblyTargetLowering::LowerCall(CallLoweringInfo &CLI, 634 SmallVectorImpl<SDValue> &InVals) const { 635 SelectionDAG &DAG = CLI.DAG; 636 SDLoc DL = CLI.DL; 637 SDValue Chain = CLI.Chain; 638 SDValue Callee = CLI.Callee; 639 MachineFunction &MF = DAG.getMachineFunction(); 640 auto Layout = MF.getDataLayout(); 641 642 CallingConv::ID CallConv = CLI.CallConv; 643 if (!callingConvSupported(CallConv)) 644 fail(DL, DAG, 645 "WebAssembly doesn't support language-specific or target-specific " 646 "calling conventions yet"); 647 if (CLI.IsPatchPoint) 648 fail(DL, DAG, "WebAssembly doesn't support patch point yet"); 649 650 if (CLI.IsTailCall) { 651 bool MustTail = CLI.CS && CLI.CS.isMustTailCall(); 652 if (Subtarget->hasTailCall() && !CLI.IsVarArg) { 653 // Do not tail call unless caller and callee return types match 654 const Function &F = MF.getFunction(); 655 const TargetMachine &TM = getTargetMachine(); 656 Type *RetTy = F.getReturnType(); 657 SmallVector<MVT, 4> CallerRetTys; 658 SmallVector<MVT, 4> CalleeRetTys; 659 computeLegalValueVTs(F, TM, RetTy, CallerRetTys); 660 computeLegalValueVTs(F, TM, CLI.RetTy, CalleeRetTys); 661 bool TypesMatch = CallerRetTys.size() == CalleeRetTys.size() && 662 std::equal(CallerRetTys.begin(), CallerRetTys.end(), 663 CalleeRetTys.begin()); 664 if (!TypesMatch) { 665 // musttail in this case would be an LLVM IR validation failure 666 assert(!MustTail); 667 CLI.IsTailCall = false; 668 } 669 } else { 670 CLI.IsTailCall = false; 671 if (MustTail) { 672 if (CLI.IsVarArg) { 673 // The return would pop the argument buffer 674 fail(DL, DAG, "WebAssembly does not support varargs tail calls"); 675 } else { 676 fail(DL, DAG, "WebAssembly 'tail-call' feature not enabled"); 677 } 678 } 679 } 680 } 681 682 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins; 683 if (Ins.size() > 1) 684 fail(DL, DAG, "WebAssembly doesn't support more than 1 returned value yet"); 685 686 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs; 687 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals; 688 689 // The generic code may have added an sret argument. If we're lowering an 690 // invoke function, the ABI requires that the function pointer be the first 691 // argument, so we may have to swap the arguments. 692 if (CallConv == CallingConv::WASM_EmscriptenInvoke && Outs.size() >= 2 && 693 Outs[0].Flags.isSRet()) { 694 std::swap(Outs[0], Outs[1]); 695 std::swap(OutVals[0], OutVals[1]); 696 } 697 698 unsigned NumFixedArgs = 0; 699 for (unsigned I = 0; I < Outs.size(); ++I) { 700 const ISD::OutputArg &Out = Outs[I]; 701 SDValue &OutVal = OutVals[I]; 702 if (Out.Flags.isNest()) 703 fail(DL, DAG, "WebAssembly hasn't implemented nest arguments"); 704 if (Out.Flags.isInAlloca()) 705 fail(DL, DAG, "WebAssembly hasn't implemented inalloca arguments"); 706 if (Out.Flags.isInConsecutiveRegs()) 707 fail(DL, DAG, "WebAssembly hasn't implemented cons regs arguments"); 708 if (Out.Flags.isInConsecutiveRegsLast()) 709 fail(DL, DAG, "WebAssembly hasn't implemented cons regs last arguments"); 710 if (Out.Flags.isByVal() && Out.Flags.getByValSize() != 0) { 711 auto &MFI = MF.getFrameInfo(); 712 int FI = MFI.CreateStackObject(Out.Flags.getByValSize(), 713 Out.Flags.getNonZeroByValAlign(), 714 /*isSS=*/false); 715 SDValue SizeNode = 716 DAG.getConstant(Out.Flags.getByValSize(), DL, MVT::i32); 717 SDValue FINode = DAG.getFrameIndex(FI, getPointerTy(Layout)); 718 Chain = DAG.getMemcpy( 719 Chain, DL, FINode, OutVal, SizeNode, Out.Flags.getNonZeroByValAlign(), 720 /*isVolatile*/ false, /*AlwaysInline=*/false, 721 /*isTailCall*/ false, MachinePointerInfo(), MachinePointerInfo()); 722 OutVal = FINode; 723 } 724 // Count the number of fixed args *after* legalization. 725 NumFixedArgs += Out.IsFixed; 726 } 727 728 bool IsVarArg = CLI.IsVarArg; 729 auto PtrVT = getPointerTy(Layout); 730 731 // Analyze operands of the call, assigning locations to each operand. 732 SmallVector<CCValAssign, 16> ArgLocs; 733 CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 734 735 if (IsVarArg) { 736 // Outgoing non-fixed arguments are placed in a buffer. First 737 // compute their offsets and the total amount of buffer space needed. 738 for (unsigned I = NumFixedArgs; I < Outs.size(); ++I) { 739 const ISD::OutputArg &Out = Outs[I]; 740 SDValue &Arg = OutVals[I]; 741 EVT VT = Arg.getValueType(); 742 assert(VT != MVT::iPTR && "Legalized args should be concrete"); 743 Type *Ty = VT.getTypeForEVT(*DAG.getContext()); 744 unsigned Align = std::max(Out.Flags.getOrigAlign(), 745 Layout.getABITypeAlignment(Ty)); 746 unsigned Offset = CCInfo.AllocateStack(Layout.getTypeAllocSize(Ty), 747 Align); 748 CCInfo.addLoc(CCValAssign::getMem(ArgLocs.size(), VT.getSimpleVT(), 749 Offset, VT.getSimpleVT(), 750 CCValAssign::Full)); 751 } 752 } 753 754 unsigned NumBytes = CCInfo.getAlignedCallFrameSize(); 755 756 SDValue FINode; 757 if (IsVarArg && NumBytes) { 758 // For non-fixed arguments, next emit stores to store the argument values 759 // to the stack buffer at the offsets computed above. 760 int FI = MF.getFrameInfo().CreateStackObject(NumBytes, 761 Layout.getStackAlignment(), 762 /*isSS=*/false); 763 unsigned ValNo = 0; 764 SmallVector<SDValue, 8> Chains; 765 for (SDValue Arg : 766 make_range(OutVals.begin() + NumFixedArgs, OutVals.end())) { 767 assert(ArgLocs[ValNo].getValNo() == ValNo && 768 "ArgLocs should remain in order and only hold varargs args"); 769 unsigned Offset = ArgLocs[ValNo++].getLocMemOffset(); 770 FINode = DAG.getFrameIndex(FI, getPointerTy(Layout)); 771 SDValue Add = DAG.getNode(ISD::ADD, DL, PtrVT, FINode, 772 DAG.getConstant(Offset, DL, PtrVT)); 773 Chains.push_back( 774 DAG.getStore(Chain, DL, Arg, Add, 775 MachinePointerInfo::getFixedStack(MF, FI, Offset), 0)); 776 } 777 if (!Chains.empty()) 778 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains); 779 } else if (IsVarArg) { 780 FINode = DAG.getIntPtrConstant(0, DL); 781 } 782 783 if (Callee->getOpcode() == ISD::GlobalAddress) { 784 // If the callee is a GlobalAddress node (quite common, every direct call 785 // is) turn it into a TargetGlobalAddress node so that LowerGlobalAddress 786 // doesn't at MO_GOT which is not needed for direct calls. 787 GlobalAddressSDNode* GA = cast<GlobalAddressSDNode>(Callee); 788 Callee = DAG.getTargetGlobalAddress(GA->getGlobal(), DL, 789 getPointerTy(DAG.getDataLayout()), 790 GA->getOffset()); 791 Callee = DAG.getNode(WebAssemblyISD::Wrapper, DL, 792 getPointerTy(DAG.getDataLayout()), Callee); 793 } 794 795 // Compute the operands for the CALLn node. 796 SmallVector<SDValue, 16> Ops; 797 Ops.push_back(Chain); 798 Ops.push_back(Callee); 799 800 // Add all fixed arguments. Note that for non-varargs calls, NumFixedArgs 801 // isn't reliable. 802 Ops.append(OutVals.begin(), 803 IsVarArg ? OutVals.begin() + NumFixedArgs : OutVals.end()); 804 // Add a pointer to the vararg buffer. 805 if (IsVarArg) 806 Ops.push_back(FINode); 807 808 SmallVector<EVT, 8> InTys; 809 for (const auto &In : Ins) { 810 assert(!In.Flags.isByVal() && "byval is not valid for return values"); 811 assert(!In.Flags.isNest() && "nest is not valid for return values"); 812 if (In.Flags.isInAlloca()) 813 fail(DL, DAG, "WebAssembly hasn't implemented inalloca return values"); 814 if (In.Flags.isInConsecutiveRegs()) 815 fail(DL, DAG, "WebAssembly hasn't implemented cons regs return values"); 816 if (In.Flags.isInConsecutiveRegsLast()) 817 fail(DL, DAG, 818 "WebAssembly hasn't implemented cons regs last return values"); 819 // Ignore In.getOrigAlign() because all our arguments are passed in 820 // registers. 821 InTys.push_back(In.VT); 822 } 823 824 if (CLI.IsTailCall) { 825 // ret_calls do not return values to the current frame 826 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 827 return DAG.getNode(WebAssemblyISD::RET_CALL, DL, NodeTys, Ops); 828 } 829 830 InTys.push_back(MVT::Other); 831 SDVTList InTyList = DAG.getVTList(InTys); 832 SDValue Res = 833 DAG.getNode(Ins.empty() ? WebAssemblyISD::CALL0 : WebAssemblyISD::CALL1, 834 DL, InTyList, Ops); 835 if (Ins.empty()) { 836 Chain = Res; 837 } else { 838 InVals.push_back(Res); 839 Chain = Res.getValue(1); 840 } 841 842 return Chain; 843 } 844 845 bool WebAssemblyTargetLowering::CanLowerReturn( 846 CallingConv::ID /*CallConv*/, MachineFunction & /*MF*/, bool /*IsVarArg*/, 847 const SmallVectorImpl<ISD::OutputArg> &Outs, 848 LLVMContext & /*Context*/) const { 849 // WebAssembly can only handle returning tuples with multivalue enabled 850 return Subtarget->hasMultivalue() || Outs.size() <= 1; 851 } 852 853 SDValue WebAssemblyTargetLowering::LowerReturn( 854 SDValue Chain, CallingConv::ID CallConv, bool /*IsVarArg*/, 855 const SmallVectorImpl<ISD::OutputArg> &Outs, 856 const SmallVectorImpl<SDValue> &OutVals, const SDLoc &DL, 857 SelectionDAG &DAG) const { 858 assert((Subtarget->hasMultivalue() || Outs.size() <= 1) && 859 "MVP WebAssembly can only return up to one value"); 860 if (!callingConvSupported(CallConv)) 861 fail(DL, DAG, "WebAssembly doesn't support non-C calling conventions"); 862 863 SmallVector<SDValue, 4> RetOps(1, Chain); 864 RetOps.append(OutVals.begin(), OutVals.end()); 865 Chain = DAG.getNode(WebAssemblyISD::RETURN, DL, MVT::Other, RetOps); 866 867 // Record the number and types of the return values. 868 for (const ISD::OutputArg &Out : Outs) { 869 assert(!Out.Flags.isByVal() && "byval is not valid for return values"); 870 assert(!Out.Flags.isNest() && "nest is not valid for return values"); 871 assert(Out.IsFixed && "non-fixed return value is not valid"); 872 if (Out.Flags.isInAlloca()) 873 fail(DL, DAG, "WebAssembly hasn't implemented inalloca results"); 874 if (Out.Flags.isInConsecutiveRegs()) 875 fail(DL, DAG, "WebAssembly hasn't implemented cons regs results"); 876 if (Out.Flags.isInConsecutiveRegsLast()) 877 fail(DL, DAG, "WebAssembly hasn't implemented cons regs last results"); 878 } 879 880 return Chain; 881 } 882 883 SDValue WebAssemblyTargetLowering::LowerFormalArguments( 884 SDValue Chain, CallingConv::ID CallConv, bool IsVarArg, 885 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 886 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 887 if (!callingConvSupported(CallConv)) 888 fail(DL, DAG, "WebAssembly doesn't support non-C calling conventions"); 889 890 MachineFunction &MF = DAG.getMachineFunction(); 891 auto *MFI = MF.getInfo<WebAssemblyFunctionInfo>(); 892 893 // Set up the incoming ARGUMENTS value, which serves to represent the liveness 894 // of the incoming values before they're represented by virtual registers. 895 MF.getRegInfo().addLiveIn(WebAssembly::ARGUMENTS); 896 897 for (const ISD::InputArg &In : Ins) { 898 if (In.Flags.isInAlloca()) 899 fail(DL, DAG, "WebAssembly hasn't implemented inalloca arguments"); 900 if (In.Flags.isNest()) 901 fail(DL, DAG, "WebAssembly hasn't implemented nest arguments"); 902 if (In.Flags.isInConsecutiveRegs()) 903 fail(DL, DAG, "WebAssembly hasn't implemented cons regs arguments"); 904 if (In.Flags.isInConsecutiveRegsLast()) 905 fail(DL, DAG, "WebAssembly hasn't implemented cons regs last arguments"); 906 // Ignore In.getOrigAlign() because all our arguments are passed in 907 // registers. 908 InVals.push_back(In.Used ? DAG.getNode(WebAssemblyISD::ARGUMENT, DL, In.VT, 909 DAG.getTargetConstant(InVals.size(), 910 DL, MVT::i32)) 911 : DAG.getUNDEF(In.VT)); 912 913 // Record the number and types of arguments. 914 MFI->addParam(In.VT); 915 } 916 917 // Varargs are copied into a buffer allocated by the caller, and a pointer to 918 // the buffer is passed as an argument. 919 if (IsVarArg) { 920 MVT PtrVT = getPointerTy(MF.getDataLayout()); 921 Register VarargVreg = 922 MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrVT)); 923 MFI->setVarargBufferVreg(VarargVreg); 924 Chain = DAG.getCopyToReg( 925 Chain, DL, VarargVreg, 926 DAG.getNode(WebAssemblyISD::ARGUMENT, DL, PtrVT, 927 DAG.getTargetConstant(Ins.size(), DL, MVT::i32))); 928 MFI->addParam(PtrVT); 929 } 930 931 // Record the number and types of arguments and results. 932 SmallVector<MVT, 4> Params; 933 SmallVector<MVT, 4> Results; 934 computeSignatureVTs(MF.getFunction().getFunctionType(), MF.getFunction(), 935 DAG.getTarget(), Params, Results); 936 for (MVT VT : Results) 937 MFI->addResult(VT); 938 // TODO: Use signatures in WebAssemblyMachineFunctionInfo too and unify 939 // the param logic here with ComputeSignatureVTs 940 assert(MFI->getParams().size() == Params.size() && 941 std::equal(MFI->getParams().begin(), MFI->getParams().end(), 942 Params.begin())); 943 944 return Chain; 945 } 946 947 void WebAssemblyTargetLowering::ReplaceNodeResults( 948 SDNode *N, SmallVectorImpl<SDValue> &Results, SelectionDAG &DAG) const { 949 switch (N->getOpcode()) { 950 case ISD::SIGN_EXTEND_INREG: 951 // Do not add any results, signifying that N should not be custom lowered 952 // after all. This happens because simd128 turns on custom lowering for 953 // SIGN_EXTEND_INREG, but for non-vector sign extends the result might be an 954 // illegal type. 955 break; 956 default: 957 llvm_unreachable( 958 "ReplaceNodeResults not implemented for this op for WebAssembly!"); 959 } 960 } 961 962 //===----------------------------------------------------------------------===// 963 // Custom lowering hooks. 964 //===----------------------------------------------------------------------===// 965 966 SDValue WebAssemblyTargetLowering::LowerOperation(SDValue Op, 967 SelectionDAG &DAG) const { 968 SDLoc DL(Op); 969 switch (Op.getOpcode()) { 970 default: 971 llvm_unreachable("unimplemented operation lowering"); 972 return SDValue(); 973 case ISD::FrameIndex: 974 return LowerFrameIndex(Op, DAG); 975 case ISD::GlobalAddress: 976 return LowerGlobalAddress(Op, DAG); 977 case ISD::ExternalSymbol: 978 return LowerExternalSymbol(Op, DAG); 979 case ISD::JumpTable: 980 return LowerJumpTable(Op, DAG); 981 case ISD::BR_JT: 982 return LowerBR_JT(Op, DAG); 983 case ISD::VASTART: 984 return LowerVASTART(Op, DAG); 985 case ISD::BlockAddress: 986 case ISD::BRIND: 987 fail(DL, DAG, "WebAssembly hasn't implemented computed gotos"); 988 return SDValue(); 989 case ISD::RETURNADDR: 990 return LowerRETURNADDR(Op, DAG); 991 case ISD::FRAMEADDR: 992 return LowerFRAMEADDR(Op, DAG); 993 case ISD::CopyToReg: 994 return LowerCopyToReg(Op, DAG); 995 case ISD::EXTRACT_VECTOR_ELT: 996 case ISD::INSERT_VECTOR_ELT: 997 return LowerAccessVectorElement(Op, DAG); 998 case ISD::INTRINSIC_VOID: 999 case ISD::INTRINSIC_WO_CHAIN: 1000 case ISD::INTRINSIC_W_CHAIN: 1001 return LowerIntrinsic(Op, DAG); 1002 case ISD::SIGN_EXTEND_INREG: 1003 return LowerSIGN_EXTEND_INREG(Op, DAG); 1004 case ISD::BUILD_VECTOR: 1005 return LowerBUILD_VECTOR(Op, DAG); 1006 case ISD::VECTOR_SHUFFLE: 1007 return LowerVECTOR_SHUFFLE(Op, DAG); 1008 case ISD::SETCC: 1009 return LowerSETCC(Op, DAG); 1010 case ISD::SHL: 1011 case ISD::SRA: 1012 case ISD::SRL: 1013 return LowerShift(Op, DAG); 1014 } 1015 } 1016 1017 SDValue WebAssemblyTargetLowering::LowerCopyToReg(SDValue Op, 1018 SelectionDAG &DAG) const { 1019 SDValue Src = Op.getOperand(2); 1020 if (isa<FrameIndexSDNode>(Src.getNode())) { 1021 // CopyToReg nodes don't support FrameIndex operands. Other targets select 1022 // the FI to some LEA-like instruction, but since we don't have that, we 1023 // need to insert some kind of instruction that can take an FI operand and 1024 // produces a value usable by CopyToReg (i.e. in a vreg). So insert a dummy 1025 // local.copy between Op and its FI operand. 1026 SDValue Chain = Op.getOperand(0); 1027 SDLoc DL(Op); 1028 unsigned Reg = cast<RegisterSDNode>(Op.getOperand(1))->getReg(); 1029 EVT VT = Src.getValueType(); 1030 SDValue Copy(DAG.getMachineNode(VT == MVT::i32 ? WebAssembly::COPY_I32 1031 : WebAssembly::COPY_I64, 1032 DL, VT, Src), 1033 0); 1034 return Op.getNode()->getNumValues() == 1 1035 ? DAG.getCopyToReg(Chain, DL, Reg, Copy) 1036 : DAG.getCopyToReg(Chain, DL, Reg, Copy, 1037 Op.getNumOperands() == 4 ? Op.getOperand(3) 1038 : SDValue()); 1039 } 1040 return SDValue(); 1041 } 1042 1043 SDValue WebAssemblyTargetLowering::LowerFrameIndex(SDValue Op, 1044 SelectionDAG &DAG) const { 1045 int FI = cast<FrameIndexSDNode>(Op)->getIndex(); 1046 return DAG.getTargetFrameIndex(FI, Op.getValueType()); 1047 } 1048 1049 SDValue WebAssemblyTargetLowering::LowerRETURNADDR(SDValue Op, 1050 SelectionDAG &DAG) const { 1051 SDLoc DL(Op); 1052 1053 if (!Subtarget->getTargetTriple().isOSEmscripten()) { 1054 fail(DL, DAG, 1055 "Non-Emscripten WebAssembly hasn't implemented " 1056 "__builtin_return_address"); 1057 return SDValue(); 1058 } 1059 1060 if (verifyReturnAddressArgumentIsConstant(Op, DAG)) 1061 return SDValue(); 1062 1063 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 1064 MakeLibCallOptions CallOptions; 1065 return makeLibCall(DAG, RTLIB::RETURN_ADDRESS, Op.getValueType(), 1066 {DAG.getConstant(Depth, DL, MVT::i32)}, CallOptions, DL) 1067 .first; 1068 } 1069 1070 SDValue WebAssemblyTargetLowering::LowerFRAMEADDR(SDValue Op, 1071 SelectionDAG &DAG) const { 1072 // Non-zero depths are not supported by WebAssembly currently. Use the 1073 // legalizer's default expansion, which is to return 0 (what this function is 1074 // documented to do). 1075 if (Op.getConstantOperandVal(0) > 0) 1076 return SDValue(); 1077 1078 DAG.getMachineFunction().getFrameInfo().setFrameAddressIsTaken(true); 1079 EVT VT = Op.getValueType(); 1080 Register FP = 1081 Subtarget->getRegisterInfo()->getFrameRegister(DAG.getMachineFunction()); 1082 return DAG.getCopyFromReg(DAG.getEntryNode(), SDLoc(Op), FP, VT); 1083 } 1084 1085 SDValue WebAssemblyTargetLowering::LowerGlobalAddress(SDValue Op, 1086 SelectionDAG &DAG) const { 1087 SDLoc DL(Op); 1088 const auto *GA = cast<GlobalAddressSDNode>(Op); 1089 EVT VT = Op.getValueType(); 1090 assert(GA->getTargetFlags() == 0 && 1091 "Unexpected target flags on generic GlobalAddressSDNode"); 1092 if (GA->getAddressSpace() != 0) 1093 fail(DL, DAG, "WebAssembly only expects the 0 address space"); 1094 1095 unsigned OperandFlags = 0; 1096 if (isPositionIndependent()) { 1097 const GlobalValue *GV = GA->getGlobal(); 1098 if (getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV)) { 1099 MachineFunction &MF = DAG.getMachineFunction(); 1100 MVT PtrVT = getPointerTy(MF.getDataLayout()); 1101 const char *BaseName; 1102 if (GV->getValueType()->isFunctionTy()) { 1103 BaseName = MF.createExternalSymbolName("__table_base"); 1104 OperandFlags = WebAssemblyII::MO_TABLE_BASE_REL; 1105 } 1106 else { 1107 BaseName = MF.createExternalSymbolName("__memory_base"); 1108 OperandFlags = WebAssemblyII::MO_MEMORY_BASE_REL; 1109 } 1110 SDValue BaseAddr = 1111 DAG.getNode(WebAssemblyISD::Wrapper, DL, PtrVT, 1112 DAG.getTargetExternalSymbol(BaseName, PtrVT)); 1113 1114 SDValue SymAddr = DAG.getNode( 1115 WebAssemblyISD::WrapperPIC, DL, VT, 1116 DAG.getTargetGlobalAddress(GA->getGlobal(), DL, VT, GA->getOffset(), 1117 OperandFlags)); 1118 1119 return DAG.getNode(ISD::ADD, DL, VT, BaseAddr, SymAddr); 1120 } else { 1121 OperandFlags = WebAssemblyII::MO_GOT; 1122 } 1123 } 1124 1125 return DAG.getNode(WebAssemblyISD::Wrapper, DL, VT, 1126 DAG.getTargetGlobalAddress(GA->getGlobal(), DL, VT, 1127 GA->getOffset(), OperandFlags)); 1128 } 1129 1130 SDValue 1131 WebAssemblyTargetLowering::LowerExternalSymbol(SDValue Op, 1132 SelectionDAG &DAG) const { 1133 SDLoc DL(Op); 1134 const auto *ES = cast<ExternalSymbolSDNode>(Op); 1135 EVT VT = Op.getValueType(); 1136 assert(ES->getTargetFlags() == 0 && 1137 "Unexpected target flags on generic ExternalSymbolSDNode"); 1138 return DAG.getNode(WebAssemblyISD::Wrapper, DL, VT, 1139 DAG.getTargetExternalSymbol(ES->getSymbol(), VT)); 1140 } 1141 1142 SDValue WebAssemblyTargetLowering::LowerJumpTable(SDValue Op, 1143 SelectionDAG &DAG) const { 1144 // There's no need for a Wrapper node because we always incorporate a jump 1145 // table operand into a BR_TABLE instruction, rather than ever 1146 // materializing it in a register. 1147 const JumpTableSDNode *JT = cast<JumpTableSDNode>(Op); 1148 return DAG.getTargetJumpTable(JT->getIndex(), Op.getValueType(), 1149 JT->getTargetFlags()); 1150 } 1151 1152 SDValue WebAssemblyTargetLowering::LowerBR_JT(SDValue Op, 1153 SelectionDAG &DAG) const { 1154 SDLoc DL(Op); 1155 SDValue Chain = Op.getOperand(0); 1156 const auto *JT = cast<JumpTableSDNode>(Op.getOperand(1)); 1157 SDValue Index = Op.getOperand(2); 1158 assert(JT->getTargetFlags() == 0 && "WebAssembly doesn't set target flags"); 1159 1160 SmallVector<SDValue, 8> Ops; 1161 Ops.push_back(Chain); 1162 Ops.push_back(Index); 1163 1164 MachineJumpTableInfo *MJTI = DAG.getMachineFunction().getJumpTableInfo(); 1165 const auto &MBBs = MJTI->getJumpTables()[JT->getIndex()].MBBs; 1166 1167 // Add an operand for each case. 1168 for (auto MBB : MBBs) 1169 Ops.push_back(DAG.getBasicBlock(MBB)); 1170 1171 // TODO: For now, we just pick something arbitrary for a default case for now. 1172 // We really want to sniff out the guard and put in the real default case (and 1173 // delete the guard). 1174 Ops.push_back(DAG.getBasicBlock(MBBs[0])); 1175 1176 return DAG.getNode(WebAssemblyISD::BR_TABLE, DL, MVT::Other, Ops); 1177 } 1178 1179 SDValue WebAssemblyTargetLowering::LowerVASTART(SDValue Op, 1180 SelectionDAG &DAG) const { 1181 SDLoc DL(Op); 1182 EVT PtrVT = getPointerTy(DAG.getMachineFunction().getDataLayout()); 1183 1184 auto *MFI = DAG.getMachineFunction().getInfo<WebAssemblyFunctionInfo>(); 1185 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 1186 1187 SDValue ArgN = DAG.getCopyFromReg(DAG.getEntryNode(), DL, 1188 MFI->getVarargBufferVreg(), PtrVT); 1189 return DAG.getStore(Op.getOperand(0), DL, ArgN, Op.getOperand(1), 1190 MachinePointerInfo(SV), 0); 1191 } 1192 1193 SDValue WebAssemblyTargetLowering::LowerIntrinsic(SDValue Op, 1194 SelectionDAG &DAG) const { 1195 MachineFunction &MF = DAG.getMachineFunction(); 1196 unsigned IntNo; 1197 switch (Op.getOpcode()) { 1198 case ISD::INTRINSIC_VOID: 1199 case ISD::INTRINSIC_W_CHAIN: 1200 IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 1201 break; 1202 case ISD::INTRINSIC_WO_CHAIN: 1203 IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 1204 break; 1205 default: 1206 llvm_unreachable("Invalid intrinsic"); 1207 } 1208 SDLoc DL(Op); 1209 1210 switch (IntNo) { 1211 default: 1212 return SDValue(); // Don't custom lower most intrinsics. 1213 1214 case Intrinsic::wasm_lsda: { 1215 EVT VT = Op.getValueType(); 1216 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1217 MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout()); 1218 auto &Context = MF.getMMI().getContext(); 1219 MCSymbol *S = Context.getOrCreateSymbol(Twine("GCC_except_table") + 1220 Twine(MF.getFunctionNumber())); 1221 return DAG.getNode(WebAssemblyISD::Wrapper, DL, VT, 1222 DAG.getMCSymbol(S, PtrVT)); 1223 } 1224 1225 case Intrinsic::wasm_throw: { 1226 // We only support C++ exceptions for now 1227 int Tag = cast<ConstantSDNode>(Op.getOperand(2).getNode())->getZExtValue(); 1228 if (Tag != CPP_EXCEPTION) 1229 llvm_unreachable("Invalid tag!"); 1230 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1231 MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout()); 1232 const char *SymName = MF.createExternalSymbolName("__cpp_exception"); 1233 SDValue SymNode = DAG.getNode(WebAssemblyISD::Wrapper, DL, PtrVT, 1234 DAG.getTargetExternalSymbol(SymName, PtrVT)); 1235 return DAG.getNode(WebAssemblyISD::THROW, DL, 1236 MVT::Other, // outchain type 1237 { 1238 Op.getOperand(0), // inchain 1239 SymNode, // exception symbol 1240 Op.getOperand(3) // thrown value 1241 }); 1242 } 1243 } 1244 } 1245 1246 SDValue 1247 WebAssemblyTargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op, 1248 SelectionDAG &DAG) const { 1249 SDLoc DL(Op); 1250 // If sign extension operations are disabled, allow sext_inreg only if operand 1251 // is a vector extract. SIMD does not depend on sign extension operations, but 1252 // allowing sext_inreg in this context lets us have simple patterns to select 1253 // extract_lane_s instructions. Expanding sext_inreg everywhere would be 1254 // simpler in this file, but would necessitate large and brittle patterns to 1255 // undo the expansion and select extract_lane_s instructions. 1256 assert(!Subtarget->hasSignExt() && Subtarget->hasSIMD128()); 1257 if (Op.getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 1258 const SDValue &Extract = Op.getOperand(0); 1259 MVT VecT = Extract.getOperand(0).getSimpleValueType(); 1260 MVT ExtractedLaneT = static_cast<VTSDNode *>(Op.getOperand(1).getNode()) 1261 ->getVT() 1262 .getSimpleVT(); 1263 MVT ExtractedVecT = 1264 MVT::getVectorVT(ExtractedLaneT, 128 / ExtractedLaneT.getSizeInBits()); 1265 if (ExtractedVecT == VecT) 1266 return Op; 1267 // Bitcast vector to appropriate type to ensure ISel pattern coverage 1268 const SDValue &Index = Extract.getOperand(1); 1269 unsigned IndexVal = 1270 static_cast<ConstantSDNode *>(Index.getNode())->getZExtValue(); 1271 unsigned Scale = 1272 ExtractedVecT.getVectorNumElements() / VecT.getVectorNumElements(); 1273 assert(Scale > 1); 1274 SDValue NewIndex = 1275 DAG.getConstant(IndexVal * Scale, DL, Index.getValueType()); 1276 SDValue NewExtract = DAG.getNode( 1277 ISD::EXTRACT_VECTOR_ELT, DL, Extract.getValueType(), 1278 DAG.getBitcast(ExtractedVecT, Extract.getOperand(0)), NewIndex); 1279 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, Op.getValueType(), 1280 NewExtract, Op.getOperand(1)); 1281 } 1282 // Otherwise expand 1283 return SDValue(); 1284 } 1285 1286 SDValue WebAssemblyTargetLowering::LowerBUILD_VECTOR(SDValue Op, 1287 SelectionDAG &DAG) const { 1288 SDLoc DL(Op); 1289 const EVT VecT = Op.getValueType(); 1290 const EVT LaneT = Op.getOperand(0).getValueType(); 1291 const size_t Lanes = Op.getNumOperands(); 1292 bool CanSwizzle = Subtarget->hasUnimplementedSIMD128() && VecT == MVT::v16i8; 1293 1294 // BUILD_VECTORs are lowered to the instruction that initializes the highest 1295 // possible number of lanes at once followed by a sequence of replace_lane 1296 // instructions to individually initialize any remaining lanes. 1297 1298 // TODO: Tune this. For example, lanewise swizzling is very expensive, so 1299 // swizzled lanes should be given greater weight. 1300 1301 // TODO: Investigate building vectors by shuffling together vectors built by 1302 // separately specialized means. 1303 1304 auto IsConstant = [](const SDValue &V) { 1305 return V.getOpcode() == ISD::Constant || V.getOpcode() == ISD::ConstantFP; 1306 }; 1307 1308 // Returns the source vector and index vector pair if they exist. Checks for: 1309 // (extract_vector_elt 1310 // $src, 1311 // (sign_extend_inreg (extract_vector_elt $indices, $i)) 1312 // ) 1313 auto GetSwizzleSrcs = [](size_t I, const SDValue &Lane) { 1314 auto Bail = std::make_pair(SDValue(), SDValue()); 1315 if (Lane->getOpcode() != ISD::EXTRACT_VECTOR_ELT) 1316 return Bail; 1317 const SDValue &SwizzleSrc = Lane->getOperand(0); 1318 const SDValue &IndexExt = Lane->getOperand(1); 1319 if (IndexExt->getOpcode() != ISD::SIGN_EXTEND_INREG) 1320 return Bail; 1321 const SDValue &Index = IndexExt->getOperand(0); 1322 if (Index->getOpcode() != ISD::EXTRACT_VECTOR_ELT) 1323 return Bail; 1324 const SDValue &SwizzleIndices = Index->getOperand(0); 1325 if (SwizzleSrc.getValueType() != MVT::v16i8 || 1326 SwizzleIndices.getValueType() != MVT::v16i8 || 1327 Index->getOperand(1)->getOpcode() != ISD::Constant || 1328 Index->getConstantOperandVal(1) != I) 1329 return Bail; 1330 return std::make_pair(SwizzleSrc, SwizzleIndices); 1331 }; 1332 1333 using ValueEntry = std::pair<SDValue, size_t>; 1334 SmallVector<ValueEntry, 16> SplatValueCounts; 1335 1336 using SwizzleEntry = std::pair<std::pair<SDValue, SDValue>, size_t>; 1337 SmallVector<SwizzleEntry, 16> SwizzleCounts; 1338 1339 auto AddCount = [](auto &Counts, const auto &Val) { 1340 auto CountIt = std::find_if(Counts.begin(), Counts.end(), 1341 [&Val](auto E) { return E.first == Val; }); 1342 if (CountIt == Counts.end()) { 1343 Counts.emplace_back(Val, 1); 1344 } else { 1345 CountIt->second++; 1346 } 1347 }; 1348 1349 auto GetMostCommon = [](auto &Counts) { 1350 auto CommonIt = 1351 std::max_element(Counts.begin(), Counts.end(), 1352 [](auto A, auto B) { return A.second < B.second; }); 1353 assert(CommonIt != Counts.end() && "Unexpected all-undef build_vector"); 1354 return *CommonIt; 1355 }; 1356 1357 size_t NumConstantLanes = 0; 1358 1359 // Count eligible lanes for each type of vector creation op 1360 for (size_t I = 0; I < Lanes; ++I) { 1361 const SDValue &Lane = Op->getOperand(I); 1362 if (Lane.isUndef()) 1363 continue; 1364 1365 AddCount(SplatValueCounts, Lane); 1366 1367 if (IsConstant(Lane)) { 1368 NumConstantLanes++; 1369 } else if (CanSwizzle) { 1370 auto SwizzleSrcs = GetSwizzleSrcs(I, Lane); 1371 if (SwizzleSrcs.first) 1372 AddCount(SwizzleCounts, SwizzleSrcs); 1373 } 1374 } 1375 1376 SDValue SplatValue; 1377 size_t NumSplatLanes; 1378 std::tie(SplatValue, NumSplatLanes) = GetMostCommon(SplatValueCounts); 1379 1380 SDValue SwizzleSrc; 1381 SDValue SwizzleIndices; 1382 size_t NumSwizzleLanes = 0; 1383 if (SwizzleCounts.size()) 1384 std::forward_as_tuple(std::tie(SwizzleSrc, SwizzleIndices), 1385 NumSwizzleLanes) = GetMostCommon(SwizzleCounts); 1386 1387 // Predicate returning true if the lane is properly initialized by the 1388 // original instruction 1389 std::function<bool(size_t, const SDValue &)> IsLaneConstructed; 1390 SDValue Result; 1391 if (Subtarget->hasUnimplementedSIMD128()) { 1392 // Prefer swizzles over vector consts over splats 1393 if (NumSwizzleLanes >= NumSplatLanes && 1394 NumSwizzleLanes >= NumConstantLanes) { 1395 Result = DAG.getNode(WebAssemblyISD::SWIZZLE, DL, VecT, SwizzleSrc, 1396 SwizzleIndices); 1397 auto Swizzled = std::make_pair(SwizzleSrc, SwizzleIndices); 1398 IsLaneConstructed = [&, Swizzled](size_t I, const SDValue &Lane) { 1399 return Swizzled == GetSwizzleSrcs(I, Lane); 1400 }; 1401 } else if (NumConstantLanes >= NumSplatLanes) { 1402 SmallVector<SDValue, 16> ConstLanes; 1403 for (const SDValue &Lane : Op->op_values()) { 1404 if (IsConstant(Lane)) { 1405 ConstLanes.push_back(Lane); 1406 } else if (LaneT.isFloatingPoint()) { 1407 ConstLanes.push_back(DAG.getConstantFP(0, DL, LaneT)); 1408 } else { 1409 ConstLanes.push_back(DAG.getConstant(0, DL, LaneT)); 1410 } 1411 } 1412 Result = DAG.getBuildVector(VecT, DL, ConstLanes); 1413 IsLaneConstructed = [&](size_t _, const SDValue &Lane) { 1414 return IsConstant(Lane); 1415 }; 1416 } 1417 } 1418 if (!Result) { 1419 // Use a splat, but possibly a load_splat 1420 LoadSDNode *SplattedLoad; 1421 if (Subtarget->hasUnimplementedSIMD128() && 1422 (SplattedLoad = dyn_cast<LoadSDNode>(SplatValue)) && 1423 SplattedLoad->getMemoryVT() == VecT.getVectorElementType()) { 1424 Result = DAG.getMemIntrinsicNode( 1425 WebAssemblyISD::LOAD_SPLAT, DL, DAG.getVTList(VecT), 1426 {SplattedLoad->getChain(), SplattedLoad->getBasePtr(), 1427 SplattedLoad->getOffset()}, 1428 SplattedLoad->getMemoryVT(), SplattedLoad->getMemOperand()); 1429 } else { 1430 Result = DAG.getSplatBuildVector(VecT, DL, SplatValue); 1431 } 1432 IsLaneConstructed = [&](size_t _, const SDValue &Lane) { 1433 return Lane == SplatValue; 1434 }; 1435 } 1436 1437 // Add replace_lane instructions for any unhandled values 1438 for (size_t I = 0; I < Lanes; ++I) { 1439 const SDValue &Lane = Op->getOperand(I); 1440 if (!Lane.isUndef() && !IsLaneConstructed(I, Lane)) 1441 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VecT, Result, Lane, 1442 DAG.getConstant(I, DL, MVT::i32)); 1443 } 1444 1445 return Result; 1446 } 1447 1448 SDValue 1449 WebAssemblyTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, 1450 SelectionDAG &DAG) const { 1451 SDLoc DL(Op); 1452 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Op.getNode())->getMask(); 1453 MVT VecType = Op.getOperand(0).getSimpleValueType(); 1454 assert(VecType.is128BitVector() && "Unexpected shuffle vector type"); 1455 size_t LaneBytes = VecType.getVectorElementType().getSizeInBits() / 8; 1456 1457 // Space for two vector args and sixteen mask indices 1458 SDValue Ops[18]; 1459 size_t OpIdx = 0; 1460 Ops[OpIdx++] = Op.getOperand(0); 1461 Ops[OpIdx++] = Op.getOperand(1); 1462 1463 // Expand mask indices to byte indices and materialize them as operands 1464 for (int M : Mask) { 1465 for (size_t J = 0; J < LaneBytes; ++J) { 1466 // Lower undefs (represented by -1 in mask) to zero 1467 uint64_t ByteIndex = M == -1 ? 0 : (uint64_t)M * LaneBytes + J; 1468 Ops[OpIdx++] = DAG.getConstant(ByteIndex, DL, MVT::i32); 1469 } 1470 } 1471 1472 return DAG.getNode(WebAssemblyISD::SHUFFLE, DL, Op.getValueType(), Ops); 1473 } 1474 1475 SDValue WebAssemblyTargetLowering::LowerSETCC(SDValue Op, 1476 SelectionDAG &DAG) const { 1477 SDLoc DL(Op); 1478 // The legalizer does not know how to expand the comparison modes of i64x2 1479 // vectors because no comparison modes are supported. We could solve this by 1480 // expanding all i64x2 SETCC nodes, but that seems to expand f64x2 SETCC nodes 1481 // (which return i64x2 results) as well. So instead we manually unroll i64x2 1482 // comparisons here. 1483 assert(Op->getOperand(0)->getSimpleValueType(0) == MVT::v2i64); 1484 SmallVector<SDValue, 2> LHS, RHS; 1485 DAG.ExtractVectorElements(Op->getOperand(0), LHS); 1486 DAG.ExtractVectorElements(Op->getOperand(1), RHS); 1487 const SDValue &CC = Op->getOperand(2); 1488 auto MakeLane = [&](unsigned I) { 1489 return DAG.getNode(ISD::SELECT_CC, DL, MVT::i64, LHS[I], RHS[I], 1490 DAG.getConstant(uint64_t(-1), DL, MVT::i64), 1491 DAG.getConstant(uint64_t(0), DL, MVT::i64), CC); 1492 }; 1493 return DAG.getBuildVector(Op->getValueType(0), DL, 1494 {MakeLane(0), MakeLane(1)}); 1495 } 1496 1497 SDValue 1498 WebAssemblyTargetLowering::LowerAccessVectorElement(SDValue Op, 1499 SelectionDAG &DAG) const { 1500 // Allow constant lane indices, expand variable lane indices 1501 SDNode *IdxNode = Op.getOperand(Op.getNumOperands() - 1).getNode(); 1502 if (isa<ConstantSDNode>(IdxNode) || IdxNode->isUndef()) 1503 return Op; 1504 else 1505 // Perform default expansion 1506 return SDValue(); 1507 } 1508 1509 static SDValue unrollVectorShift(SDValue Op, SelectionDAG &DAG) { 1510 EVT LaneT = Op.getSimpleValueType().getVectorElementType(); 1511 // 32-bit and 64-bit unrolled shifts will have proper semantics 1512 if (LaneT.bitsGE(MVT::i32)) 1513 return DAG.UnrollVectorOp(Op.getNode()); 1514 // Otherwise mask the shift value to get proper semantics from 32-bit shift 1515 SDLoc DL(Op); 1516 SDValue ShiftVal = Op.getOperand(1); 1517 uint64_t MaskVal = LaneT.getSizeInBits() - 1; 1518 SDValue MaskedShiftVal = DAG.getNode( 1519 ISD::AND, // mask opcode 1520 DL, ShiftVal.getValueType(), // masked value type 1521 ShiftVal, // original shift value operand 1522 DAG.getConstant(MaskVal, DL, ShiftVal.getValueType()) // mask operand 1523 ); 1524 1525 return DAG.UnrollVectorOp( 1526 DAG.getNode(Op.getOpcode(), // original shift opcode 1527 DL, Op.getValueType(), // original return type 1528 Op.getOperand(0), // original vector operand, 1529 MaskedShiftVal // new masked shift value operand 1530 ) 1531 .getNode()); 1532 } 1533 1534 SDValue WebAssemblyTargetLowering::LowerShift(SDValue Op, 1535 SelectionDAG &DAG) const { 1536 SDLoc DL(Op); 1537 1538 // Only manually lower vector shifts 1539 assert(Op.getSimpleValueType().isVector()); 1540 1541 // Unroll non-splat vector shifts 1542 BuildVectorSDNode *ShiftVec; 1543 SDValue SplatVal; 1544 if (!(ShiftVec = dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode())) || 1545 !(SplatVal = ShiftVec->getSplatValue())) 1546 return unrollVectorShift(Op, DAG); 1547 1548 // All splats except i64x2 const splats are handled by patterns 1549 auto *SplatConst = dyn_cast<ConstantSDNode>(SplatVal); 1550 if (!SplatConst || Op.getSimpleValueType() != MVT::v2i64) 1551 return Op; 1552 1553 // i64x2 const splats are custom lowered to avoid unnecessary wraps 1554 unsigned Opcode; 1555 switch (Op.getOpcode()) { 1556 case ISD::SHL: 1557 Opcode = WebAssemblyISD::VEC_SHL; 1558 break; 1559 case ISD::SRA: 1560 Opcode = WebAssemblyISD::VEC_SHR_S; 1561 break; 1562 case ISD::SRL: 1563 Opcode = WebAssemblyISD::VEC_SHR_U; 1564 break; 1565 default: 1566 llvm_unreachable("unexpected opcode"); 1567 } 1568 APInt Shift = SplatConst->getAPIntValue().zextOrTrunc(32); 1569 return DAG.getNode(Opcode, DL, Op.getValueType(), Op.getOperand(0), 1570 DAG.getConstant(Shift, DL, MVT::i32)); 1571 } 1572 1573 //===----------------------------------------------------------------------===// 1574 // WebAssembly Optimization Hooks 1575 //===----------------------------------------------------------------------===// 1576