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