1 //=- WebAssemblyISelLowering.cpp - WebAssembly DAG Lowering Implementation -==// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 /// 10 /// \file 11 /// This file implements the WebAssemblyTargetLowering class. 12 /// 13 //===----------------------------------------------------------------------===// 14 15 #include "WebAssemblyISelLowering.h" 16 #include "MCTargetDesc/WebAssemblyMCTargetDesc.h" 17 #include "WebAssemblyMachineFunctionInfo.h" 18 #include "WebAssemblySubtarget.h" 19 #include "WebAssemblyTargetMachine.h" 20 #include "llvm/CodeGen/Analysis.h" 21 #include "llvm/CodeGen/CallingConvLower.h" 22 #include "llvm/CodeGen/MachineInstrBuilder.h" 23 #include "llvm/CodeGen/MachineJumpTableInfo.h" 24 #include "llvm/CodeGen/MachineModuleInfo.h" 25 #include "llvm/CodeGen/MachineRegisterInfo.h" 26 #include "llvm/CodeGen/SelectionDAG.h" 27 #include "llvm/CodeGen/WasmEHFuncInfo.h" 28 #include "llvm/IR/DiagnosticInfo.h" 29 #include "llvm/IR/DiagnosticPrinter.h" 30 #include "llvm/IR/Function.h" 31 #include "llvm/IR/Intrinsics.h" 32 #include "llvm/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 // Emit proposed instructions that may not have been implemented in engines 41 cl::opt<bool> EnableUnimplementedWasmSIMDInstrs( 42 "wasm-enable-unimplemented-simd", 43 cl::desc("Emit potentially-unimplemented WebAssembly SIMD instructions"), 44 cl::init(false)); 45 46 WebAssemblyTargetLowering::WebAssemblyTargetLowering( 47 const TargetMachine &TM, const WebAssemblySubtarget &STI) 48 : TargetLowering(TM), Subtarget(&STI) { 49 auto MVTPtr = Subtarget->hasAddr64() ? MVT::i64 : MVT::i32; 50 51 // Booleans always contain 0 or 1. 52 setBooleanContents(ZeroOrOneBooleanContent); 53 // Except in SIMD vectors 54 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent); 55 // WebAssembly does not produce floating-point exceptions on normal floating 56 // point operations. 57 setHasFloatingPointExceptions(false); 58 // We don't know the microarchitecture here, so just reduce register pressure. 59 setSchedulingPreference(Sched::RegPressure); 60 // Tell ISel that we have a stack pointer. 61 setStackPointerRegisterToSaveRestore( 62 Subtarget->hasAddr64() ? WebAssembly::SP64 : WebAssembly::SP32); 63 // Set up the register classes. 64 addRegisterClass(MVT::i32, &WebAssembly::I32RegClass); 65 addRegisterClass(MVT::i64, &WebAssembly::I64RegClass); 66 addRegisterClass(MVT::f32, &WebAssembly::F32RegClass); 67 addRegisterClass(MVT::f64, &WebAssembly::F64RegClass); 68 if (Subtarget->hasSIMD128()) { 69 addRegisterClass(MVT::v16i8, &WebAssembly::V128RegClass); 70 addRegisterClass(MVT::v8i16, &WebAssembly::V128RegClass); 71 addRegisterClass(MVT::v4i32, &WebAssembly::V128RegClass); 72 addRegisterClass(MVT::v4f32, &WebAssembly::V128RegClass); 73 if (EnableUnimplementedWasmSIMDInstrs) { 74 addRegisterClass(MVT::v2i64, &WebAssembly::V128RegClass); 75 addRegisterClass(MVT::v2f64, &WebAssembly::V128RegClass); 76 } 77 } 78 // Compute derived properties from the register classes. 79 computeRegisterProperties(Subtarget->getRegisterInfo()); 80 81 setOperationAction(ISD::GlobalAddress, MVTPtr, Custom); 82 setOperationAction(ISD::ExternalSymbol, MVTPtr, Custom); 83 setOperationAction(ISD::JumpTable, MVTPtr, Custom); 84 setOperationAction(ISD::BlockAddress, MVTPtr, Custom); 85 setOperationAction(ISD::BRIND, MVT::Other, Custom); 86 87 // Take the default expansion for va_arg, va_copy, and va_end. There is no 88 // default action for va_start, so we do that custom. 89 setOperationAction(ISD::VASTART, MVT::Other, Custom); 90 setOperationAction(ISD::VAARG, MVT::Other, Expand); 91 setOperationAction(ISD::VACOPY, MVT::Other, Expand); 92 setOperationAction(ISD::VAEND, MVT::Other, Expand); 93 94 for (auto T : {MVT::f32, MVT::f64, MVT::v4f32, MVT::v2f64}) { 95 // Don't expand the floating-point types to constant pools. 96 setOperationAction(ISD::ConstantFP, T, Legal); 97 // Expand floating-point comparisons. 98 for (auto CC : {ISD::SETO, ISD::SETUO, ISD::SETUEQ, ISD::SETONE, 99 ISD::SETULT, ISD::SETULE, ISD::SETUGT, ISD::SETUGE}) 100 setCondCodeAction(CC, T, Expand); 101 // Expand floating-point library function operators. 102 for (auto Op : 103 {ISD::FSIN, ISD::FCOS, ISD::FSINCOS, ISD::FPOW, ISD::FREM, ISD::FMA}) 104 setOperationAction(Op, T, Expand); 105 // Note supported floating-point library function operators that otherwise 106 // default to expand. 107 for (auto Op : 108 {ISD::FCEIL, ISD::FFLOOR, ISD::FTRUNC, ISD::FNEARBYINT, ISD::FRINT}) 109 setOperationAction(Op, T, Legal); 110 // Support minimum and maximum, which otherwise default to expand. 111 setOperationAction(ISD::FMINIMUM, T, Legal); 112 setOperationAction(ISD::FMAXIMUM, T, Legal); 113 // WebAssembly currently has no builtin f16 support. 114 setOperationAction(ISD::FP16_TO_FP, T, Expand); 115 setOperationAction(ISD::FP_TO_FP16, T, Expand); 116 setLoadExtAction(ISD::EXTLOAD, T, MVT::f16, Expand); 117 setTruncStoreAction(T, MVT::f16, Expand); 118 } 119 120 // Support saturating add for i8x16 and i16x8 121 if (Subtarget->hasSIMD128()) 122 for (auto T : {MVT::v16i8, MVT::v8i16}) 123 for (auto Op : {ISD::SADDSAT, ISD::UADDSAT}) 124 setOperationAction(Op, T, Legal); 125 126 // Expand unavailable integer operations. 127 for (auto Op : 128 {ISD::BSWAP, ISD::SMUL_LOHI, ISD::UMUL_LOHI, ISD::MULHS, ISD::MULHU, 129 ISD::SDIVREM, ISD::UDIVREM, ISD::SHL_PARTS, ISD::SRA_PARTS, 130 ISD::SRL_PARTS, ISD::ADDC, ISD::ADDE, ISD::SUBC, ISD::SUBE}) { 131 for (auto T : {MVT::i32, MVT::i64}) { 132 setOperationAction(Op, T, Expand); 133 } 134 if (Subtarget->hasSIMD128()) { 135 for (auto T : {MVT::v16i8, MVT::v8i16, MVT::v4i32}) { 136 setOperationAction(Op, T, Expand); 137 } 138 if (EnableUnimplementedWasmSIMDInstrs) { 139 setOperationAction(Op, MVT::v2i64, Expand); 140 } 141 } 142 } 143 144 // There is no i64x2.mul instruction 145 setOperationAction(ISD::MUL, MVT::v2i64, Expand); 146 147 // We have custom shuffle lowering to expose the shuffle mask 148 if (Subtarget->hasSIMD128()) { 149 for (auto T : {MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v4f32}) { 150 setOperationAction(ISD::VECTOR_SHUFFLE, T, Custom); 151 } 152 if (EnableUnimplementedWasmSIMDInstrs) { 153 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom); 154 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom); 155 } 156 } 157 158 // Custom lowering since wasm shifts must have a scalar shift amount 159 if (Subtarget->hasSIMD128()) { 160 for (auto T : {MVT::v16i8, MVT::v8i16, MVT::v4i32}) 161 for (auto Op : {ISD::SHL, ISD::SRA, ISD::SRL}) 162 setOperationAction(Op, T, Custom); 163 if (EnableUnimplementedWasmSIMDInstrs) 164 for (auto Op : {ISD::SHL, ISD::SRA, ISD::SRL}) 165 setOperationAction(Op, MVT::v2i64, Custom); 166 } 167 168 // There are no select instructions for vectors 169 if (Subtarget->hasSIMD128()) 170 for (auto Op : {ISD::VSELECT, ISD::SELECT_CC, ISD::SELECT}) { 171 for (auto T : {MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v4f32}) 172 setOperationAction(Op, T, Expand); 173 if (EnableUnimplementedWasmSIMDInstrs) 174 for (auto T : {MVT::v2i64, MVT::v2f64}) 175 setOperationAction(Op, T, Expand); 176 } 177 178 // As a special case, these operators use the type to mean the type to 179 // sign-extend from. 180 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); 181 if (!Subtarget->hasSignExt()) { 182 for (auto T : {MVT::i8, MVT::i16, MVT::i32}) 183 setOperationAction(ISD::SIGN_EXTEND_INREG, T, Expand); 184 } 185 for (auto T : MVT::integer_vector_valuetypes()) 186 setOperationAction(ISD::SIGN_EXTEND_INREG, T, Expand); 187 188 // Dynamic stack allocation: use the default expansion. 189 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand); 190 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand); 191 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVTPtr, Expand); 192 193 setOperationAction(ISD::FrameIndex, MVT::i32, Custom); 194 setOperationAction(ISD::CopyToReg, MVT::Other, Custom); 195 196 // Expand these forms; we pattern-match the forms that we can handle in isel. 197 for (auto T : {MVT::i32, MVT::i64, MVT::f32, MVT::f64}) 198 for (auto Op : {ISD::BR_CC, ISD::SELECT_CC}) 199 setOperationAction(Op, T, Expand); 200 201 // We have custom switch handling. 202 setOperationAction(ISD::BR_JT, MVT::Other, Custom); 203 204 // WebAssembly doesn't have: 205 // - Floating-point extending loads. 206 // - Floating-point truncating stores. 207 // - i1 extending loads. 208 // - extending/truncating SIMD loads/stores 209 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f32, Expand); 210 setTruncStoreAction(MVT::f64, MVT::f32, Expand); 211 for (auto T : MVT::integer_valuetypes()) 212 for (auto Ext : {ISD::EXTLOAD, ISD::ZEXTLOAD, ISD::SEXTLOAD}) 213 setLoadExtAction(Ext, T, MVT::i1, Promote); 214 if (Subtarget->hasSIMD128()) { 215 for (auto T : {MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64, MVT::v4f32, 216 MVT::v2f64}) { 217 for (auto MemT : MVT::vector_valuetypes()) { 218 if (MVT(T) != MemT) { 219 setTruncStoreAction(T, MemT, Expand); 220 for (auto Ext : {ISD::EXTLOAD, ISD::ZEXTLOAD, ISD::SEXTLOAD}) 221 setLoadExtAction(Ext, T, MemT, Expand); 222 } 223 } 224 } 225 } 226 227 // Custom lower lane accesses to expand out variable indices 228 if (Subtarget->hasSIMD128()) { 229 for (auto T : {MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v4f32}) { 230 setOperationAction(ISD::EXTRACT_VECTOR_ELT, T, Custom); 231 setOperationAction(ISD::INSERT_VECTOR_ELT, T, Custom); 232 } 233 if (EnableUnimplementedWasmSIMDInstrs) { 234 for (auto T : {MVT::v2i64, MVT::v2f64}) { 235 setOperationAction(ISD::EXTRACT_VECTOR_ELT, T, Custom); 236 setOperationAction(ISD::INSERT_VECTOR_ELT, T, Custom); 237 } 238 } 239 } 240 241 // Trap lowers to wasm unreachable 242 setOperationAction(ISD::TRAP, MVT::Other, Legal); 243 244 // Exception handling intrinsics 245 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 246 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom); 247 248 setMaxAtomicSizeInBitsSupported(64); 249 } 250 251 TargetLowering::AtomicExpansionKind 252 WebAssemblyTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const { 253 // We have wasm instructions for these 254 switch (AI->getOperation()) { 255 case AtomicRMWInst::Add: 256 case AtomicRMWInst::Sub: 257 case AtomicRMWInst::And: 258 case AtomicRMWInst::Or: 259 case AtomicRMWInst::Xor: 260 case AtomicRMWInst::Xchg: 261 return AtomicExpansionKind::None; 262 default: 263 break; 264 } 265 return AtomicExpansionKind::CmpXChg; 266 } 267 268 FastISel *WebAssemblyTargetLowering::createFastISel( 269 FunctionLoweringInfo &FuncInfo, const TargetLibraryInfo *LibInfo) const { 270 return WebAssembly::createFastISel(FuncInfo, LibInfo); 271 } 272 273 bool WebAssemblyTargetLowering::isOffsetFoldingLegal( 274 const GlobalAddressSDNode * /*GA*/) const { 275 // All offsets can be folded. 276 return true; 277 } 278 279 MVT WebAssemblyTargetLowering::getScalarShiftAmountTy(const DataLayout & /*DL*/, 280 EVT VT) const { 281 unsigned BitWidth = NextPowerOf2(VT.getSizeInBits() - 1); 282 if (BitWidth > 1 && BitWidth < 8) 283 BitWidth = 8; 284 285 if (BitWidth > 64) { 286 // The shift will be lowered to a libcall, and compiler-rt libcalls expect 287 // the count to be an i32. 288 BitWidth = 32; 289 assert(BitWidth >= Log2_32_Ceil(VT.getSizeInBits()) && 290 "32-bit shift counts ought to be enough for anyone"); 291 } 292 293 MVT Result = MVT::getIntegerVT(BitWidth); 294 assert(Result != MVT::INVALID_SIMPLE_VALUE_TYPE && 295 "Unable to represent scalar shift amount type"); 296 return Result; 297 } 298 299 // Lower an fp-to-int conversion operator from the LLVM opcode, which has an 300 // undefined result on invalid/overflow, to the WebAssembly opcode, which 301 // traps on invalid/overflow. 302 static MachineBasicBlock *LowerFPToInt(MachineInstr &MI, DebugLoc DL, 303 MachineBasicBlock *BB, 304 const TargetInstrInfo &TII, 305 bool IsUnsigned, bool Int64, 306 bool Float64, unsigned LoweredOpcode) { 307 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 308 309 unsigned OutReg = MI.getOperand(0).getReg(); 310 unsigned InReg = MI.getOperand(1).getReg(); 311 312 unsigned Abs = Float64 ? WebAssembly::ABS_F64 : WebAssembly::ABS_F32; 313 unsigned FConst = Float64 ? WebAssembly::CONST_F64 : WebAssembly::CONST_F32; 314 unsigned LT = Float64 ? WebAssembly::LT_F64 : WebAssembly::LT_F32; 315 unsigned GE = Float64 ? WebAssembly::GE_F64 : WebAssembly::GE_F32; 316 unsigned IConst = Int64 ? WebAssembly::CONST_I64 : WebAssembly::CONST_I32; 317 unsigned Eqz = WebAssembly::EQZ_I32; 318 unsigned And = WebAssembly::AND_I32; 319 int64_t Limit = Int64 ? INT64_MIN : INT32_MIN; 320 int64_t Substitute = IsUnsigned ? 0 : Limit; 321 double CmpVal = IsUnsigned ? -(double)Limit * 2.0 : -(double)Limit; 322 auto &Context = BB->getParent()->getFunction().getContext(); 323 Type *Ty = Float64 ? Type::getDoubleTy(Context) : Type::getFloatTy(Context); 324 325 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 326 MachineFunction *F = BB->getParent(); 327 MachineBasicBlock *TrueMBB = F->CreateMachineBasicBlock(LLVM_BB); 328 MachineBasicBlock *FalseMBB = F->CreateMachineBasicBlock(LLVM_BB); 329 MachineBasicBlock *DoneMBB = F->CreateMachineBasicBlock(LLVM_BB); 330 331 MachineFunction::iterator It = ++BB->getIterator(); 332 F->insert(It, FalseMBB); 333 F->insert(It, TrueMBB); 334 F->insert(It, DoneMBB); 335 336 // Transfer the remainder of BB and its successor edges to DoneMBB. 337 DoneMBB->splice(DoneMBB->begin(), BB, 338 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 339 DoneMBB->transferSuccessorsAndUpdatePHIs(BB); 340 341 BB->addSuccessor(TrueMBB); 342 BB->addSuccessor(FalseMBB); 343 TrueMBB->addSuccessor(DoneMBB); 344 FalseMBB->addSuccessor(DoneMBB); 345 346 unsigned Tmp0, Tmp1, CmpReg, EqzReg, FalseReg, TrueReg; 347 Tmp0 = MRI.createVirtualRegister(MRI.getRegClass(InReg)); 348 Tmp1 = MRI.createVirtualRegister(MRI.getRegClass(InReg)); 349 CmpReg = MRI.createVirtualRegister(&WebAssembly::I32RegClass); 350 EqzReg = MRI.createVirtualRegister(&WebAssembly::I32RegClass); 351 FalseReg = MRI.createVirtualRegister(MRI.getRegClass(OutReg)); 352 TrueReg = MRI.createVirtualRegister(MRI.getRegClass(OutReg)); 353 354 MI.eraseFromParent(); 355 // For signed numbers, we can do a single comparison to determine whether 356 // fabs(x) is within range. 357 if (IsUnsigned) { 358 Tmp0 = InReg; 359 } else { 360 BuildMI(BB, DL, TII.get(Abs), Tmp0).addReg(InReg); 361 } 362 BuildMI(BB, DL, TII.get(FConst), Tmp1) 363 .addFPImm(cast<ConstantFP>(ConstantFP::get(Ty, CmpVal))); 364 BuildMI(BB, DL, TII.get(LT), CmpReg).addReg(Tmp0).addReg(Tmp1); 365 366 // For unsigned numbers, we have to do a separate comparison with zero. 367 if (IsUnsigned) { 368 Tmp1 = MRI.createVirtualRegister(MRI.getRegClass(InReg)); 369 unsigned SecondCmpReg = 370 MRI.createVirtualRegister(&WebAssembly::I32RegClass); 371 unsigned AndReg = MRI.createVirtualRegister(&WebAssembly::I32RegClass); 372 BuildMI(BB, DL, TII.get(FConst), Tmp1) 373 .addFPImm(cast<ConstantFP>(ConstantFP::get(Ty, 0.0))); 374 BuildMI(BB, DL, TII.get(GE), SecondCmpReg).addReg(Tmp0).addReg(Tmp1); 375 BuildMI(BB, DL, TII.get(And), AndReg).addReg(CmpReg).addReg(SecondCmpReg); 376 CmpReg = AndReg; 377 } 378 379 BuildMI(BB, DL, TII.get(Eqz), EqzReg).addReg(CmpReg); 380 381 // Create the CFG diamond to select between doing the conversion or using 382 // the substitute value. 383 BuildMI(BB, DL, TII.get(WebAssembly::BR_IF)).addMBB(TrueMBB).addReg(EqzReg); 384 BuildMI(FalseMBB, DL, TII.get(LoweredOpcode), FalseReg).addReg(InReg); 385 BuildMI(FalseMBB, DL, TII.get(WebAssembly::BR)).addMBB(DoneMBB); 386 BuildMI(TrueMBB, DL, TII.get(IConst), TrueReg).addImm(Substitute); 387 BuildMI(*DoneMBB, DoneMBB->begin(), DL, TII.get(TargetOpcode::PHI), OutReg) 388 .addReg(FalseReg) 389 .addMBB(FalseMBB) 390 .addReg(TrueReg) 391 .addMBB(TrueMBB); 392 393 return DoneMBB; 394 } 395 396 MachineBasicBlock *WebAssemblyTargetLowering::EmitInstrWithCustomInserter( 397 MachineInstr &MI, MachineBasicBlock *BB) const { 398 const TargetInstrInfo &TII = *Subtarget->getInstrInfo(); 399 DebugLoc DL = MI.getDebugLoc(); 400 401 switch (MI.getOpcode()) { 402 default: 403 llvm_unreachable("Unexpected instr type to insert"); 404 case WebAssembly::FP_TO_SINT_I32_F32: 405 return LowerFPToInt(MI, DL, BB, TII, false, false, false, 406 WebAssembly::I32_TRUNC_S_F32); 407 case WebAssembly::FP_TO_UINT_I32_F32: 408 return LowerFPToInt(MI, DL, BB, TII, true, false, false, 409 WebAssembly::I32_TRUNC_U_F32); 410 case WebAssembly::FP_TO_SINT_I64_F32: 411 return LowerFPToInt(MI, DL, BB, TII, false, true, false, 412 WebAssembly::I64_TRUNC_S_F32); 413 case WebAssembly::FP_TO_UINT_I64_F32: 414 return LowerFPToInt(MI, DL, BB, TII, true, true, false, 415 WebAssembly::I64_TRUNC_U_F32); 416 case WebAssembly::FP_TO_SINT_I32_F64: 417 return LowerFPToInt(MI, DL, BB, TII, false, false, true, 418 WebAssembly::I32_TRUNC_S_F64); 419 case WebAssembly::FP_TO_UINT_I32_F64: 420 return LowerFPToInt(MI, DL, BB, TII, true, false, true, 421 WebAssembly::I32_TRUNC_U_F64); 422 case WebAssembly::FP_TO_SINT_I64_F64: 423 return LowerFPToInt(MI, DL, BB, TII, false, true, true, 424 WebAssembly::I64_TRUNC_S_F64); 425 case WebAssembly::FP_TO_UINT_I64_F64: 426 return LowerFPToInt(MI, DL, BB, TII, true, true, true, 427 WebAssembly::I64_TRUNC_U_F64); 428 llvm_unreachable("Unexpected instruction to emit with custom inserter"); 429 } 430 } 431 432 const char * 433 WebAssemblyTargetLowering::getTargetNodeName(unsigned Opcode) const { 434 switch (static_cast<WebAssemblyISD::NodeType>(Opcode)) { 435 case WebAssemblyISD::FIRST_NUMBER: 436 break; 437 #define HANDLE_NODETYPE(NODE) \ 438 case WebAssemblyISD::NODE: \ 439 return "WebAssemblyISD::" #NODE; 440 #include "WebAssemblyISD.def" 441 #undef HANDLE_NODETYPE 442 } 443 return nullptr; 444 } 445 446 std::pair<unsigned, const TargetRegisterClass *> 447 WebAssemblyTargetLowering::getRegForInlineAsmConstraint( 448 const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const { 449 // First, see if this is a constraint that directly corresponds to a 450 // WebAssembly register class. 451 if (Constraint.size() == 1) { 452 switch (Constraint[0]) { 453 case 'r': 454 assert(VT != MVT::iPTR && "Pointer MVT not expected here"); 455 if (Subtarget->hasSIMD128() && VT.isVector()) { 456 if (VT.getSizeInBits() == 128) 457 return std::make_pair(0U, &WebAssembly::V128RegClass); 458 } 459 if (VT.isInteger() && !VT.isVector()) { 460 if (VT.getSizeInBits() <= 32) 461 return std::make_pair(0U, &WebAssembly::I32RegClass); 462 if (VT.getSizeInBits() <= 64) 463 return std::make_pair(0U, &WebAssembly::I64RegClass); 464 } 465 break; 466 default: 467 break; 468 } 469 } 470 471 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 472 } 473 474 bool WebAssemblyTargetLowering::isCheapToSpeculateCttz() const { 475 // Assume ctz is a relatively cheap operation. 476 return true; 477 } 478 479 bool WebAssemblyTargetLowering::isCheapToSpeculateCtlz() const { 480 // Assume clz is a relatively cheap operation. 481 return true; 482 } 483 484 bool WebAssemblyTargetLowering::isLegalAddressingMode(const DataLayout &DL, 485 const AddrMode &AM, 486 Type *Ty, unsigned AS, 487 Instruction *I) const { 488 // WebAssembly offsets are added as unsigned without wrapping. The 489 // isLegalAddressingMode gives us no way to determine if wrapping could be 490 // happening, so we approximate this by accepting only non-negative offsets. 491 if (AM.BaseOffs < 0) 492 return false; 493 494 // WebAssembly has no scale register operands. 495 if (AM.Scale != 0) 496 return false; 497 498 // Everything else is legal. 499 return true; 500 } 501 502 bool WebAssemblyTargetLowering::allowsMisalignedMemoryAccesses( 503 EVT /*VT*/, unsigned /*AddrSpace*/, unsigned /*Align*/, bool *Fast) const { 504 // WebAssembly supports unaligned accesses, though it should be declared 505 // with the p2align attribute on loads and stores which do so, and there 506 // may be a performance impact. We tell LLVM they're "fast" because 507 // for the kinds of things that LLVM uses this for (merging adjacent stores 508 // of constants, etc.), WebAssembly implementations will either want the 509 // unaligned access or they'll split anyway. 510 if (Fast) 511 *Fast = true; 512 return true; 513 } 514 515 bool WebAssemblyTargetLowering::isIntDivCheap(EVT VT, 516 AttributeList Attr) const { 517 // The current thinking is that wasm engines will perform this optimization, 518 // so we can save on code size. 519 return true; 520 } 521 522 EVT WebAssemblyTargetLowering::getSetCCResultType(const DataLayout &DL, 523 LLVMContext &C, 524 EVT VT) const { 525 if (VT.isVector()) 526 return VT.changeVectorElementTypeToInteger(); 527 528 return TargetLowering::getSetCCResultType(DL, C, VT); 529 } 530 531 bool WebAssemblyTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 532 const CallInst &I, 533 MachineFunction &MF, 534 unsigned Intrinsic) const { 535 switch (Intrinsic) { 536 case Intrinsic::wasm_atomic_notify: 537 Info.opc = ISD::INTRINSIC_W_CHAIN; 538 Info.memVT = MVT::i32; 539 Info.ptrVal = I.getArgOperand(0); 540 Info.offset = 0; 541 Info.align = 4; 542 // atomic.notify instruction does not really load the memory specified with 543 // this argument, but MachineMemOperand should either be load or store, so 544 // we set this to a load. 545 // FIXME Volatile isn't really correct, but currently all LLVM atomic 546 // instructions are treated as volatiles in the backend, so we should be 547 // consistent. The same applies for wasm_atomic_wait intrinsics too. 548 Info.flags = MachineMemOperand::MOVolatile | MachineMemOperand::MOLoad; 549 return true; 550 case Intrinsic::wasm_atomic_wait_i32: 551 Info.opc = ISD::INTRINSIC_W_CHAIN; 552 Info.memVT = MVT::i32; 553 Info.ptrVal = I.getArgOperand(0); 554 Info.offset = 0; 555 Info.align = 4; 556 Info.flags = MachineMemOperand::MOVolatile | MachineMemOperand::MOLoad; 557 return true; 558 case Intrinsic::wasm_atomic_wait_i64: 559 Info.opc = ISD::INTRINSIC_W_CHAIN; 560 Info.memVT = MVT::i64; 561 Info.ptrVal = I.getArgOperand(0); 562 Info.offset = 0; 563 Info.align = 8; 564 Info.flags = MachineMemOperand::MOVolatile | MachineMemOperand::MOLoad; 565 return true; 566 default: 567 return false; 568 } 569 } 570 571 //===----------------------------------------------------------------------===// 572 // WebAssembly Lowering private implementation. 573 //===----------------------------------------------------------------------===// 574 575 //===----------------------------------------------------------------------===// 576 // Lowering Code 577 //===----------------------------------------------------------------------===// 578 579 static void fail(const SDLoc &DL, SelectionDAG &DAG, const char *msg) { 580 MachineFunction &MF = DAG.getMachineFunction(); 581 DAG.getContext()->diagnose( 582 DiagnosticInfoUnsupported(MF.getFunction(), msg, DL.getDebugLoc())); 583 } 584 585 // Test whether the given calling convention is supported. 586 static bool CallingConvSupported(CallingConv::ID CallConv) { 587 // We currently support the language-independent target-independent 588 // conventions. We don't yet have a way to annotate calls with properties like 589 // "cold", and we don't have any call-clobbered registers, so these are mostly 590 // all handled the same. 591 return CallConv == CallingConv::C || CallConv == CallingConv::Fast || 592 CallConv == CallingConv::Cold || 593 CallConv == CallingConv::PreserveMost || 594 CallConv == CallingConv::PreserveAll || 595 CallConv == CallingConv::CXX_FAST_TLS; 596 } 597 598 SDValue 599 WebAssemblyTargetLowering::LowerCall(CallLoweringInfo &CLI, 600 SmallVectorImpl<SDValue> &InVals) const { 601 SelectionDAG &DAG = CLI.DAG; 602 SDLoc DL = CLI.DL; 603 SDValue Chain = CLI.Chain; 604 SDValue Callee = CLI.Callee; 605 MachineFunction &MF = DAG.getMachineFunction(); 606 auto Layout = MF.getDataLayout(); 607 608 CallingConv::ID CallConv = CLI.CallConv; 609 if (!CallingConvSupported(CallConv)) 610 fail(DL, DAG, 611 "WebAssembly doesn't support language-specific or target-specific " 612 "calling conventions yet"); 613 if (CLI.IsPatchPoint) 614 fail(DL, DAG, "WebAssembly doesn't support patch point yet"); 615 616 // WebAssembly doesn't currently support explicit tail calls. If they are 617 // required, fail. Otherwise, just disable them. 618 if ((CallConv == CallingConv::Fast && CLI.IsTailCall && 619 MF.getTarget().Options.GuaranteedTailCallOpt) || 620 (CLI.CS && CLI.CS.isMustTailCall())) 621 fail(DL, DAG, "WebAssembly doesn't support tail call yet"); 622 CLI.IsTailCall = false; 623 624 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins; 625 if (Ins.size() > 1) 626 fail(DL, DAG, "WebAssembly doesn't support more than 1 returned value yet"); 627 628 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs; 629 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals; 630 unsigned NumFixedArgs = 0; 631 for (unsigned i = 0; i < Outs.size(); ++i) { 632 const ISD::OutputArg &Out = Outs[i]; 633 SDValue &OutVal = OutVals[i]; 634 if (Out.Flags.isNest()) 635 fail(DL, DAG, "WebAssembly hasn't implemented nest arguments"); 636 if (Out.Flags.isInAlloca()) 637 fail(DL, DAG, "WebAssembly hasn't implemented inalloca arguments"); 638 if (Out.Flags.isInConsecutiveRegs()) 639 fail(DL, DAG, "WebAssembly hasn't implemented cons regs arguments"); 640 if (Out.Flags.isInConsecutiveRegsLast()) 641 fail(DL, DAG, "WebAssembly hasn't implemented cons regs last arguments"); 642 if (Out.Flags.isByVal() && Out.Flags.getByValSize() != 0) { 643 auto &MFI = MF.getFrameInfo(); 644 int FI = MFI.CreateStackObject(Out.Flags.getByValSize(), 645 Out.Flags.getByValAlign(), 646 /*isSS=*/false); 647 SDValue SizeNode = 648 DAG.getConstant(Out.Flags.getByValSize(), DL, MVT::i32); 649 SDValue FINode = DAG.getFrameIndex(FI, getPointerTy(Layout)); 650 Chain = DAG.getMemcpy( 651 Chain, DL, FINode, OutVal, SizeNode, Out.Flags.getByValAlign(), 652 /*isVolatile*/ false, /*AlwaysInline=*/false, 653 /*isTailCall*/ false, MachinePointerInfo(), MachinePointerInfo()); 654 OutVal = FINode; 655 } 656 // Count the number of fixed args *after* legalization. 657 NumFixedArgs += Out.IsFixed; 658 } 659 660 bool IsVarArg = CLI.IsVarArg; 661 auto PtrVT = getPointerTy(Layout); 662 663 // Analyze operands of the call, assigning locations to each operand. 664 SmallVector<CCValAssign, 16> ArgLocs; 665 CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 666 667 if (IsVarArg) { 668 // Outgoing non-fixed arguments are placed in a buffer. First 669 // compute their offsets and the total amount of buffer space needed. 670 for (SDValue Arg : 671 make_range(OutVals.begin() + NumFixedArgs, OutVals.end())) { 672 EVT VT = Arg.getValueType(); 673 assert(VT != MVT::iPTR && "Legalized args should be concrete"); 674 Type *Ty = VT.getTypeForEVT(*DAG.getContext()); 675 unsigned Offset = CCInfo.AllocateStack(Layout.getTypeAllocSize(Ty), 676 Layout.getABITypeAlignment(Ty)); 677 CCInfo.addLoc(CCValAssign::getMem(ArgLocs.size(), VT.getSimpleVT(), 678 Offset, VT.getSimpleVT(), 679 CCValAssign::Full)); 680 } 681 } 682 683 unsigned NumBytes = CCInfo.getAlignedCallFrameSize(); 684 685 SDValue FINode; 686 if (IsVarArg && NumBytes) { 687 // For non-fixed arguments, next emit stores to store the argument values 688 // to the stack buffer at the offsets computed above. 689 int FI = MF.getFrameInfo().CreateStackObject(NumBytes, 690 Layout.getStackAlignment(), 691 /*isSS=*/false); 692 unsigned ValNo = 0; 693 SmallVector<SDValue, 8> Chains; 694 for (SDValue Arg : 695 make_range(OutVals.begin() + NumFixedArgs, OutVals.end())) { 696 assert(ArgLocs[ValNo].getValNo() == ValNo && 697 "ArgLocs should remain in order and only hold varargs args"); 698 unsigned Offset = ArgLocs[ValNo++].getLocMemOffset(); 699 FINode = DAG.getFrameIndex(FI, getPointerTy(Layout)); 700 SDValue Add = DAG.getNode(ISD::ADD, DL, PtrVT, FINode, 701 DAG.getConstant(Offset, DL, PtrVT)); 702 Chains.push_back( 703 DAG.getStore(Chain, DL, Arg, Add, 704 MachinePointerInfo::getFixedStack(MF, FI, Offset), 0)); 705 } 706 if (!Chains.empty()) 707 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains); 708 } else if (IsVarArg) { 709 FINode = DAG.getIntPtrConstant(0, DL); 710 } 711 712 // Compute the operands for the CALLn node. 713 SmallVector<SDValue, 16> Ops; 714 Ops.push_back(Chain); 715 Ops.push_back(Callee); 716 717 // Add all fixed arguments. Note that for non-varargs calls, NumFixedArgs 718 // isn't reliable. 719 Ops.append(OutVals.begin(), 720 IsVarArg ? OutVals.begin() + NumFixedArgs : OutVals.end()); 721 // Add a pointer to the vararg buffer. 722 if (IsVarArg) 723 Ops.push_back(FINode); 724 725 SmallVector<EVT, 8> InTys; 726 for (const auto &In : Ins) { 727 assert(!In.Flags.isByVal() && "byval is not valid for return values"); 728 assert(!In.Flags.isNest() && "nest is not valid for return values"); 729 if (In.Flags.isInAlloca()) 730 fail(DL, DAG, "WebAssembly hasn't implemented inalloca return values"); 731 if (In.Flags.isInConsecutiveRegs()) 732 fail(DL, DAG, "WebAssembly hasn't implemented cons regs return values"); 733 if (In.Flags.isInConsecutiveRegsLast()) 734 fail(DL, DAG, 735 "WebAssembly hasn't implemented cons regs last return values"); 736 // Ignore In.getOrigAlign() because all our arguments are passed in 737 // registers. 738 InTys.push_back(In.VT); 739 } 740 InTys.push_back(MVT::Other); 741 SDVTList InTyList = DAG.getVTList(InTys); 742 SDValue Res = 743 DAG.getNode(Ins.empty() ? WebAssemblyISD::CALL0 : WebAssemblyISD::CALL1, 744 DL, InTyList, Ops); 745 if (Ins.empty()) { 746 Chain = Res; 747 } else { 748 InVals.push_back(Res); 749 Chain = Res.getValue(1); 750 } 751 752 return Chain; 753 } 754 755 bool WebAssemblyTargetLowering::CanLowerReturn( 756 CallingConv::ID /*CallConv*/, MachineFunction & /*MF*/, bool /*IsVarArg*/, 757 const SmallVectorImpl<ISD::OutputArg> &Outs, 758 LLVMContext & /*Context*/) const { 759 // WebAssembly can't currently handle returning tuples. 760 return Outs.size() <= 1; 761 } 762 763 SDValue WebAssemblyTargetLowering::LowerReturn( 764 SDValue Chain, CallingConv::ID CallConv, bool /*IsVarArg*/, 765 const SmallVectorImpl<ISD::OutputArg> &Outs, 766 const SmallVectorImpl<SDValue> &OutVals, const SDLoc &DL, 767 SelectionDAG &DAG) const { 768 assert(Outs.size() <= 1 && "WebAssembly can only return up to one value"); 769 if (!CallingConvSupported(CallConv)) 770 fail(DL, DAG, "WebAssembly doesn't support non-C calling conventions"); 771 772 SmallVector<SDValue, 4> RetOps(1, Chain); 773 RetOps.append(OutVals.begin(), OutVals.end()); 774 Chain = DAG.getNode(WebAssemblyISD::RETURN, DL, MVT::Other, RetOps); 775 776 // Record the number and types of the return values. 777 for (const ISD::OutputArg &Out : Outs) { 778 assert(!Out.Flags.isByVal() && "byval is not valid for return values"); 779 assert(!Out.Flags.isNest() && "nest is not valid for return values"); 780 assert(Out.IsFixed && "non-fixed return value is not valid"); 781 if (Out.Flags.isInAlloca()) 782 fail(DL, DAG, "WebAssembly hasn't implemented inalloca results"); 783 if (Out.Flags.isInConsecutiveRegs()) 784 fail(DL, DAG, "WebAssembly hasn't implemented cons regs results"); 785 if (Out.Flags.isInConsecutiveRegsLast()) 786 fail(DL, DAG, "WebAssembly hasn't implemented cons regs last results"); 787 } 788 789 return Chain; 790 } 791 792 SDValue WebAssemblyTargetLowering::LowerFormalArguments( 793 SDValue Chain, CallingConv::ID CallConv, bool IsVarArg, 794 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 795 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 796 if (!CallingConvSupported(CallConv)) 797 fail(DL, DAG, "WebAssembly doesn't support non-C calling conventions"); 798 799 MachineFunction &MF = DAG.getMachineFunction(); 800 auto *MFI = MF.getInfo<WebAssemblyFunctionInfo>(); 801 802 // Set up the incoming ARGUMENTS value, which serves to represent the liveness 803 // of the incoming values before they're represented by virtual registers. 804 MF.getRegInfo().addLiveIn(WebAssembly::ARGUMENTS); 805 806 for (const ISD::InputArg &In : Ins) { 807 if (In.Flags.isInAlloca()) 808 fail(DL, DAG, "WebAssembly hasn't implemented inalloca arguments"); 809 if (In.Flags.isNest()) 810 fail(DL, DAG, "WebAssembly hasn't implemented nest arguments"); 811 if (In.Flags.isInConsecutiveRegs()) 812 fail(DL, DAG, "WebAssembly hasn't implemented cons regs arguments"); 813 if (In.Flags.isInConsecutiveRegsLast()) 814 fail(DL, DAG, "WebAssembly hasn't implemented cons regs last arguments"); 815 // Ignore In.getOrigAlign() because all our arguments are passed in 816 // registers. 817 InVals.push_back(In.Used ? DAG.getNode(WebAssemblyISD::ARGUMENT, DL, In.VT, 818 DAG.getTargetConstant(InVals.size(), 819 DL, MVT::i32)) 820 : DAG.getUNDEF(In.VT)); 821 822 // Record the number and types of arguments. 823 MFI->addParam(In.VT); 824 } 825 826 // Varargs are copied into a buffer allocated by the caller, and a pointer to 827 // the buffer is passed as an argument. 828 if (IsVarArg) { 829 MVT PtrVT = getPointerTy(MF.getDataLayout()); 830 unsigned VarargVreg = 831 MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrVT)); 832 MFI->setVarargBufferVreg(VarargVreg); 833 Chain = DAG.getCopyToReg( 834 Chain, DL, VarargVreg, 835 DAG.getNode(WebAssemblyISD::ARGUMENT, DL, PtrVT, 836 DAG.getTargetConstant(Ins.size(), DL, MVT::i32))); 837 MFI->addParam(PtrVT); 838 } 839 840 // Record the number and types of arguments and results. 841 SmallVector<MVT, 4> Params; 842 SmallVector<MVT, 4> Results; 843 ComputeSignatureVTs(MF.getFunction().getFunctionType(), MF.getFunction(), 844 DAG.getTarget(), Params, Results); 845 for (MVT VT : Results) 846 MFI->addResult(VT); 847 // TODO: Use signatures in WebAssemblyMachineFunctionInfo too and unify 848 // the param logic here with ComputeSignatureVTs 849 assert(MFI->getParams().size() == Params.size() && 850 std::equal(MFI->getParams().begin(), MFI->getParams().end(), 851 Params.begin())); 852 853 return Chain; 854 } 855 856 //===----------------------------------------------------------------------===// 857 // Custom lowering hooks. 858 //===----------------------------------------------------------------------===// 859 860 SDValue WebAssemblyTargetLowering::LowerOperation(SDValue Op, 861 SelectionDAG &DAG) const { 862 SDLoc DL(Op); 863 switch (Op.getOpcode()) { 864 default: 865 llvm_unreachable("unimplemented operation lowering"); 866 return SDValue(); 867 case ISD::FrameIndex: 868 return LowerFrameIndex(Op, DAG); 869 case ISD::GlobalAddress: 870 return LowerGlobalAddress(Op, DAG); 871 case ISD::ExternalSymbol: 872 return LowerExternalSymbol(Op, DAG); 873 case ISD::JumpTable: 874 return LowerJumpTable(Op, DAG); 875 case ISD::BR_JT: 876 return LowerBR_JT(Op, DAG); 877 case ISD::VASTART: 878 return LowerVASTART(Op, DAG); 879 case ISD::BlockAddress: 880 case ISD::BRIND: 881 fail(DL, DAG, "WebAssembly hasn't implemented computed gotos"); 882 return SDValue(); 883 case ISD::RETURNADDR: // Probably nothing meaningful can be returned here. 884 fail(DL, DAG, "WebAssembly hasn't implemented __builtin_return_address"); 885 return SDValue(); 886 case ISD::FRAMEADDR: 887 return LowerFRAMEADDR(Op, DAG); 888 case ISD::CopyToReg: 889 return LowerCopyToReg(Op, DAG); 890 case ISD::INTRINSIC_WO_CHAIN: 891 return LowerINTRINSIC_WO_CHAIN(Op, DAG); 892 case ISD::EXTRACT_VECTOR_ELT: 893 case ISD::INSERT_VECTOR_ELT: 894 return LowerAccessVectorElement(Op, DAG); 895 case ISD::INTRINSIC_VOID: 896 return LowerINTRINSIC_VOID(Op, DAG); 897 case ISD::VECTOR_SHUFFLE: 898 return LowerVECTOR_SHUFFLE(Op, DAG); 899 case ISD::SHL: 900 case ISD::SRA: 901 case ISD::SRL: 902 return LowerShift(Op, DAG); 903 } 904 } 905 906 SDValue WebAssemblyTargetLowering::LowerCopyToReg(SDValue Op, 907 SelectionDAG &DAG) const { 908 SDValue Src = Op.getOperand(2); 909 if (isa<FrameIndexSDNode>(Src.getNode())) { 910 // CopyToReg nodes don't support FrameIndex operands. Other targets select 911 // the FI to some LEA-like instruction, but since we don't have that, we 912 // need to insert some kind of instruction that can take an FI operand and 913 // produces a value usable by CopyToReg (i.e. in a vreg). So insert a dummy 914 // copy_local between Op and its FI operand. 915 SDValue Chain = Op.getOperand(0); 916 SDLoc DL(Op); 917 unsigned Reg = cast<RegisterSDNode>(Op.getOperand(1))->getReg(); 918 EVT VT = Src.getValueType(); 919 SDValue Copy(DAG.getMachineNode(VT == MVT::i32 ? WebAssembly::COPY_I32 920 : WebAssembly::COPY_I64, 921 DL, VT, Src), 922 0); 923 return Op.getNode()->getNumValues() == 1 924 ? DAG.getCopyToReg(Chain, DL, Reg, Copy) 925 : DAG.getCopyToReg(Chain, DL, Reg, Copy, 926 Op.getNumOperands() == 4 ? Op.getOperand(3) 927 : SDValue()); 928 } 929 return SDValue(); 930 } 931 932 SDValue WebAssemblyTargetLowering::LowerFrameIndex(SDValue Op, 933 SelectionDAG &DAG) const { 934 int FI = cast<FrameIndexSDNode>(Op)->getIndex(); 935 return DAG.getTargetFrameIndex(FI, Op.getValueType()); 936 } 937 938 SDValue WebAssemblyTargetLowering::LowerFRAMEADDR(SDValue Op, 939 SelectionDAG &DAG) const { 940 // Non-zero depths are not supported by WebAssembly currently. Use the 941 // legalizer's default expansion, which is to return 0 (what this function is 942 // documented to do). 943 if (Op.getConstantOperandVal(0) > 0) 944 return SDValue(); 945 946 DAG.getMachineFunction().getFrameInfo().setFrameAddressIsTaken(true); 947 EVT VT = Op.getValueType(); 948 unsigned FP = 949 Subtarget->getRegisterInfo()->getFrameRegister(DAG.getMachineFunction()); 950 return DAG.getCopyFromReg(DAG.getEntryNode(), SDLoc(Op), FP, VT); 951 } 952 953 SDValue WebAssemblyTargetLowering::LowerGlobalAddress(SDValue Op, 954 SelectionDAG &DAG) const { 955 SDLoc DL(Op); 956 const auto *GA = cast<GlobalAddressSDNode>(Op); 957 EVT VT = Op.getValueType(); 958 assert(GA->getTargetFlags() == 0 && 959 "Unexpected target flags on generic GlobalAddressSDNode"); 960 if (GA->getAddressSpace() != 0) 961 fail(DL, DAG, "WebAssembly only expects the 0 address space"); 962 return DAG.getNode( 963 WebAssemblyISD::Wrapper, DL, VT, 964 DAG.getTargetGlobalAddress(GA->getGlobal(), DL, VT, GA->getOffset())); 965 } 966 967 SDValue 968 WebAssemblyTargetLowering::LowerExternalSymbol(SDValue Op, 969 SelectionDAG &DAG) const { 970 SDLoc DL(Op); 971 const auto *ES = cast<ExternalSymbolSDNode>(Op); 972 EVT VT = Op.getValueType(); 973 assert(ES->getTargetFlags() == 0 && 974 "Unexpected target flags on generic ExternalSymbolSDNode"); 975 // Set the TargetFlags to 0x1 which indicates that this is a "function" 976 // symbol rather than a data symbol. We do this unconditionally even though 977 // we don't know anything about the symbol other than its name, because all 978 // external symbols used in target-independent SelectionDAG code are for 979 // functions. 980 return DAG.getNode( 981 WebAssemblyISD::Wrapper, DL, VT, 982 DAG.getTargetExternalSymbol(ES->getSymbol(), VT, 983 WebAssemblyII::MO_SYMBOL_FUNCTION)); 984 } 985 986 SDValue WebAssemblyTargetLowering::LowerJumpTable(SDValue Op, 987 SelectionDAG &DAG) const { 988 // There's no need for a Wrapper node because we always incorporate a jump 989 // table operand into a BR_TABLE instruction, rather than ever 990 // materializing it in a register. 991 const JumpTableSDNode *JT = cast<JumpTableSDNode>(Op); 992 return DAG.getTargetJumpTable(JT->getIndex(), Op.getValueType(), 993 JT->getTargetFlags()); 994 } 995 996 SDValue WebAssemblyTargetLowering::LowerBR_JT(SDValue Op, 997 SelectionDAG &DAG) const { 998 SDLoc DL(Op); 999 SDValue Chain = Op.getOperand(0); 1000 const auto *JT = cast<JumpTableSDNode>(Op.getOperand(1)); 1001 SDValue Index = Op.getOperand(2); 1002 assert(JT->getTargetFlags() == 0 && "WebAssembly doesn't set target flags"); 1003 1004 SmallVector<SDValue, 8> Ops; 1005 Ops.push_back(Chain); 1006 Ops.push_back(Index); 1007 1008 MachineJumpTableInfo *MJTI = DAG.getMachineFunction().getJumpTableInfo(); 1009 const auto &MBBs = MJTI->getJumpTables()[JT->getIndex()].MBBs; 1010 1011 // Add an operand for each case. 1012 for (auto MBB : MBBs) 1013 Ops.push_back(DAG.getBasicBlock(MBB)); 1014 1015 // TODO: For now, we just pick something arbitrary for a default case for now. 1016 // We really want to sniff out the guard and put in the real default case (and 1017 // delete the guard). 1018 Ops.push_back(DAG.getBasicBlock(MBBs[0])); 1019 1020 return DAG.getNode(WebAssemblyISD::BR_TABLE, DL, MVT::Other, Ops); 1021 } 1022 1023 SDValue WebAssemblyTargetLowering::LowerVASTART(SDValue Op, 1024 SelectionDAG &DAG) const { 1025 SDLoc DL(Op); 1026 EVT PtrVT = getPointerTy(DAG.getMachineFunction().getDataLayout()); 1027 1028 auto *MFI = DAG.getMachineFunction().getInfo<WebAssemblyFunctionInfo>(); 1029 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 1030 1031 SDValue ArgN = DAG.getCopyFromReg(DAG.getEntryNode(), DL, 1032 MFI->getVarargBufferVreg(), PtrVT); 1033 return DAG.getStore(Op.getOperand(0), DL, ArgN, Op.getOperand(1), 1034 MachinePointerInfo(SV), 0); 1035 } 1036 1037 SDValue 1038 WebAssemblyTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 1039 SelectionDAG &DAG) const { 1040 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 1041 SDLoc DL(Op); 1042 switch (IntNo) { 1043 default: 1044 return {}; // Don't custom lower most intrinsics. 1045 1046 case Intrinsic::wasm_lsda: { 1047 MachineFunction &MF = DAG.getMachineFunction(); 1048 EVT VT = Op.getValueType(); 1049 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1050 MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout()); 1051 auto &Context = MF.getMMI().getContext(); 1052 MCSymbol *S = Context.getOrCreateSymbol(Twine("GCC_except_table") + 1053 Twine(MF.getFunctionNumber())); 1054 return DAG.getNode(WebAssemblyISD::Wrapper, DL, VT, 1055 DAG.getMCSymbol(S, PtrVT)); 1056 } 1057 } 1058 } 1059 1060 SDValue 1061 WebAssemblyTargetLowering::LowerINTRINSIC_VOID(SDValue Op, 1062 SelectionDAG &DAG) const { 1063 MachineFunction &MF = DAG.getMachineFunction(); 1064 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 1065 SDLoc DL(Op); 1066 1067 switch (IntNo) { 1068 default: 1069 return {}; // Don't custom lower most intrinsics. 1070 1071 case Intrinsic::wasm_throw: { 1072 int Tag = cast<ConstantSDNode>(Op.getOperand(2).getNode())->getZExtValue(); 1073 switch (Tag) { 1074 case CPP_EXCEPTION: { 1075 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1076 MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout()); 1077 const char *SymName = MF.createExternalSymbolName("__cpp_exception"); 1078 SDValue SymNode = 1079 DAG.getNode(WebAssemblyISD::Wrapper, DL, PtrVT, 1080 DAG.getTargetExternalSymbol( 1081 SymName, PtrVT, WebAssemblyII::MO_SYMBOL_EVENT)); 1082 return DAG.getNode(WebAssemblyISD::THROW, DL, 1083 MVT::Other, // outchain type 1084 { 1085 Op.getOperand(0), // inchain 1086 SymNode, // exception symbol 1087 Op.getOperand(3) // thrown value 1088 }); 1089 } 1090 default: 1091 llvm_unreachable("Invalid tag!"); 1092 } 1093 break; 1094 } 1095 } 1096 } 1097 1098 SDValue 1099 WebAssemblyTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, 1100 SelectionDAG &DAG) const { 1101 SDLoc DL(Op); 1102 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Op.getNode())->getMask(); 1103 MVT VecType = Op.getOperand(0).getSimpleValueType(); 1104 assert(VecType.is128BitVector() && "Unexpected shuffle vector type"); 1105 size_t LaneBytes = VecType.getVectorElementType().getSizeInBits() / 8; 1106 1107 // Space for two vector args and sixteen mask indices 1108 SDValue Ops[18]; 1109 size_t OpIdx = 0; 1110 Ops[OpIdx++] = Op.getOperand(0); 1111 Ops[OpIdx++] = Op.getOperand(1); 1112 1113 // Expand mask indices to byte indices and materialize them as operands 1114 for (size_t I = 0, Lanes = Mask.size(); I < Lanes; ++I) { 1115 for (size_t J = 0; J < LaneBytes; ++J) { 1116 // Lower undefs (represented by -1 in mask) to zero 1117 uint64_t ByteIndex = 1118 Mask[I] == -1 ? 0 : (uint64_t)Mask[I] * LaneBytes + J; 1119 Ops[OpIdx++] = DAG.getConstant(ByteIndex, DL, MVT::i32); 1120 } 1121 } 1122 1123 return DAG.getNode(WebAssemblyISD::SHUFFLE, DL, Op.getValueType(), Ops); 1124 } 1125 1126 SDValue 1127 WebAssemblyTargetLowering::LowerAccessVectorElement(SDValue Op, 1128 SelectionDAG &DAG) const { 1129 // Allow constant lane indices, expand variable lane indices 1130 SDNode *IdxNode = Op.getOperand(Op.getNumOperands() - 1).getNode(); 1131 if (isa<ConstantSDNode>(IdxNode) || IdxNode->isUndef()) 1132 return Op; 1133 else 1134 // Perform default expansion 1135 return SDValue(); 1136 } 1137 1138 SDValue WebAssemblyTargetLowering::LowerShift(SDValue Op, 1139 SelectionDAG &DAG) const { 1140 SDLoc DL(Op); 1141 1142 // Only manually lower vector shifts 1143 assert(Op.getSimpleValueType().isVector()); 1144 1145 // Unroll non-splat vector shifts 1146 BuildVectorSDNode *ShiftVec; 1147 SDValue SplatVal; 1148 if (!(ShiftVec = dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode())) || 1149 !(SplatVal = ShiftVec->getSplatValue())) 1150 return DAG.UnrollVectorOp(Op.getNode()); 1151 1152 // All splats except i64x2 const splats are handled by patterns 1153 ConstantSDNode *SplatConst = dyn_cast<ConstantSDNode>(SplatVal); 1154 if (!SplatConst || Op.getSimpleValueType() != MVT::v2i64) 1155 return Op; 1156 1157 // i64x2 const splats are custom lowered to avoid unnecessary wraps 1158 unsigned Opcode; 1159 switch (Op.getOpcode()) { 1160 case ISD::SHL: 1161 Opcode = WebAssemblyISD::VEC_SHL; 1162 break; 1163 case ISD::SRA: 1164 Opcode = WebAssemblyISD::VEC_SHR_S; 1165 break; 1166 case ISD::SRL: 1167 Opcode = WebAssemblyISD::VEC_SHR_U; 1168 break; 1169 default: 1170 llvm_unreachable("unexpected opcode"); 1171 } 1172 APInt Shift = SplatConst->getAPIntValue().zextOrTrunc(32); 1173 return DAG.getNode(Opcode, DL, Op.getValueType(), Op.getOperand(0), 1174 DAG.getConstant(Shift, DL, MVT::i32)); 1175 } 1176 1177 //===----------------------------------------------------------------------===// 1178 // WebAssembly Optimization Hooks 1179 //===----------------------------------------------------------------------===// 1180