1 //===- TargetLoweringBase.cpp - Implement the TargetLoweringBase class ----===// 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 // This implements the TargetLoweringBase class. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "llvm/ADT/BitVector.h" 14 #include "llvm/ADT/STLExtras.h" 15 #include "llvm/ADT/SmallVector.h" 16 #include "llvm/ADT/StringExtras.h" 17 #include "llvm/ADT/StringRef.h" 18 #include "llvm/ADT/Twine.h" 19 #include "llvm/Analysis/Loads.h" 20 #include "llvm/Analysis/TargetTransformInfo.h" 21 #include "llvm/CodeGen/Analysis.h" 22 #include "llvm/CodeGen/ISDOpcodes.h" 23 #include "llvm/CodeGen/MachineBasicBlock.h" 24 #include "llvm/CodeGen/MachineFrameInfo.h" 25 #include "llvm/CodeGen/MachineFunction.h" 26 #include "llvm/CodeGen/MachineInstr.h" 27 #include "llvm/CodeGen/MachineInstrBuilder.h" 28 #include "llvm/CodeGen/MachineMemOperand.h" 29 #include "llvm/CodeGen/MachineOperand.h" 30 #include "llvm/CodeGen/MachineRegisterInfo.h" 31 #include "llvm/CodeGen/RuntimeLibcalls.h" 32 #include "llvm/CodeGen/StackMaps.h" 33 #include "llvm/CodeGen/TargetLowering.h" 34 #include "llvm/CodeGen/TargetOpcodes.h" 35 #include "llvm/CodeGen/TargetRegisterInfo.h" 36 #include "llvm/CodeGen/ValueTypes.h" 37 #include "llvm/CodeGenTypes/MachineValueType.h" 38 #include "llvm/IR/Attributes.h" 39 #include "llvm/IR/CallingConv.h" 40 #include "llvm/IR/DataLayout.h" 41 #include "llvm/IR/DerivedTypes.h" 42 #include "llvm/IR/Function.h" 43 #include "llvm/IR/GlobalValue.h" 44 #include "llvm/IR/GlobalVariable.h" 45 #include "llvm/IR/IRBuilder.h" 46 #include "llvm/IR/Module.h" 47 #include "llvm/IR/Type.h" 48 #include "llvm/Support/Casting.h" 49 #include "llvm/Support/CommandLine.h" 50 #include "llvm/Support/Compiler.h" 51 #include "llvm/Support/ErrorHandling.h" 52 #include "llvm/Support/MathExtras.h" 53 #include "llvm/Target/TargetMachine.h" 54 #include "llvm/Target/TargetOptions.h" 55 #include "llvm/TargetParser/Triple.h" 56 #include "llvm/Transforms/Utils/SizeOpts.h" 57 #include <algorithm> 58 #include <cassert> 59 #include <cstdint> 60 #include <cstring> 61 #include <iterator> 62 #include <string> 63 #include <tuple> 64 #include <utility> 65 66 using namespace llvm; 67 68 static cl::opt<bool> JumpIsExpensiveOverride( 69 "jump-is-expensive", cl::init(false), 70 cl::desc("Do not create extra branches to split comparison logic."), 71 cl::Hidden); 72 73 static cl::opt<unsigned> MinimumJumpTableEntries 74 ("min-jump-table-entries", cl::init(4), cl::Hidden, 75 cl::desc("Set minimum number of entries to use a jump table.")); 76 77 static cl::opt<unsigned> MaximumJumpTableSize 78 ("max-jump-table-size", cl::init(UINT_MAX), cl::Hidden, 79 cl::desc("Set maximum size of jump tables.")); 80 81 /// Minimum jump table density for normal functions. 82 static cl::opt<unsigned> 83 JumpTableDensity("jump-table-density", cl::init(10), cl::Hidden, 84 cl::desc("Minimum density for building a jump table in " 85 "a normal function")); 86 87 /// Minimum jump table density for -Os or -Oz functions. 88 static cl::opt<unsigned> OptsizeJumpTableDensity( 89 "optsize-jump-table-density", cl::init(40), cl::Hidden, 90 cl::desc("Minimum density for building a jump table in " 91 "an optsize function")); 92 93 // FIXME: This option is only to test if the strict fp operation processed 94 // correctly by preventing mutating strict fp operation to normal fp operation 95 // during development. When the backend supports strict float operation, this 96 // option will be meaningless. 97 static cl::opt<bool> DisableStrictNodeMutation("disable-strictnode-mutation", 98 cl::desc("Don't mutate strict-float node to a legalize node"), 99 cl::init(false), cl::Hidden); 100 101 static bool darwinHasSinCos(const Triple &TT) { 102 assert(TT.isOSDarwin() && "should be called with darwin triple"); 103 // Don't bother with 32 bit x86. 104 if (TT.getArch() == Triple::x86) 105 return false; 106 // Macos < 10.9 has no sincos_stret. 107 if (TT.isMacOSX()) 108 return !TT.isMacOSXVersionLT(10, 9) && TT.isArch64Bit(); 109 // iOS < 7.0 has no sincos_stret. 110 if (TT.isiOS()) 111 return !TT.isOSVersionLT(7, 0); 112 // Any other darwin such as WatchOS/TvOS is new enough. 113 return true; 114 } 115 116 void TargetLoweringBase::InitLibcalls(const Triple &TT) { 117 #define HANDLE_LIBCALL(code, name) \ 118 setLibcallName(RTLIB::code, name); 119 #include "llvm/IR/RuntimeLibcalls.def" 120 #undef HANDLE_LIBCALL 121 // Initialize calling conventions to their default. 122 for (int LC = 0; LC < RTLIB::UNKNOWN_LIBCALL; ++LC) 123 setLibcallCallingConv((RTLIB::Libcall)LC, CallingConv::C); 124 125 // Use the f128 variants of math functions on x86_64 126 if (TT.getArch() == Triple::ArchType::x86_64 && TT.isGNUEnvironment()) { 127 setLibcallName(RTLIB::REM_F128, "fmodf128"); 128 setLibcallName(RTLIB::FMA_F128, "fmaf128"); 129 setLibcallName(RTLIB::SQRT_F128, "sqrtf128"); 130 setLibcallName(RTLIB::CBRT_F128, "cbrtf128"); 131 setLibcallName(RTLIB::LOG_F128, "logf128"); 132 setLibcallName(RTLIB::LOG_FINITE_F128, "__logf128_finite"); 133 setLibcallName(RTLIB::LOG2_F128, "log2f128"); 134 setLibcallName(RTLIB::LOG2_FINITE_F128, "__log2f128_finite"); 135 setLibcallName(RTLIB::LOG10_F128, "log10f128"); 136 setLibcallName(RTLIB::LOG10_FINITE_F128, "__log10f128_finite"); 137 setLibcallName(RTLIB::EXP_F128, "expf128"); 138 setLibcallName(RTLIB::EXP_FINITE_F128, "__expf128_finite"); 139 setLibcallName(RTLIB::EXP2_F128, "exp2f128"); 140 setLibcallName(RTLIB::EXP2_FINITE_F128, "__exp2f128_finite"); 141 setLibcallName(RTLIB::EXP10_F128, "exp10f128"); 142 setLibcallName(RTLIB::SIN_F128, "sinf128"); 143 setLibcallName(RTLIB::COS_F128, "cosf128"); 144 setLibcallName(RTLIB::TAN_F128, "tanf128"); 145 setLibcallName(RTLIB::SINCOS_F128, "sincosf128"); 146 setLibcallName(RTLIB::POW_F128, "powf128"); 147 setLibcallName(RTLIB::POW_FINITE_F128, "__powf128_finite"); 148 setLibcallName(RTLIB::CEIL_F128, "ceilf128"); 149 setLibcallName(RTLIB::TRUNC_F128, "truncf128"); 150 setLibcallName(RTLIB::RINT_F128, "rintf128"); 151 setLibcallName(RTLIB::NEARBYINT_F128, "nearbyintf128"); 152 setLibcallName(RTLIB::ROUND_F128, "roundf128"); 153 setLibcallName(RTLIB::ROUNDEVEN_F128, "roundevenf128"); 154 setLibcallName(RTLIB::FLOOR_F128, "floorf128"); 155 setLibcallName(RTLIB::COPYSIGN_F128, "copysignf128"); 156 setLibcallName(RTLIB::FMIN_F128, "fminf128"); 157 setLibcallName(RTLIB::FMAX_F128, "fmaxf128"); 158 setLibcallName(RTLIB::LROUND_F128, "lroundf128"); 159 setLibcallName(RTLIB::LLROUND_F128, "llroundf128"); 160 setLibcallName(RTLIB::LRINT_F128, "lrintf128"); 161 setLibcallName(RTLIB::LLRINT_F128, "llrintf128"); 162 setLibcallName(RTLIB::LDEXP_F128, "ldexpf128"); 163 setLibcallName(RTLIB::FREXP_F128, "frexpf128"); 164 } 165 166 // For IEEE quad-precision libcall names, PPC uses "kf" instead of "tf". 167 if (TT.isPPC()) { 168 setLibcallName(RTLIB::ADD_F128, "__addkf3"); 169 setLibcallName(RTLIB::SUB_F128, "__subkf3"); 170 setLibcallName(RTLIB::MUL_F128, "__mulkf3"); 171 setLibcallName(RTLIB::DIV_F128, "__divkf3"); 172 setLibcallName(RTLIB::POWI_F128, "__powikf2"); 173 setLibcallName(RTLIB::FPEXT_F32_F128, "__extendsfkf2"); 174 setLibcallName(RTLIB::FPEXT_F64_F128, "__extenddfkf2"); 175 setLibcallName(RTLIB::FPROUND_F128_F32, "__trunckfsf2"); 176 setLibcallName(RTLIB::FPROUND_F128_F64, "__trunckfdf2"); 177 setLibcallName(RTLIB::FPTOSINT_F128_I32, "__fixkfsi"); 178 setLibcallName(RTLIB::FPTOSINT_F128_I64, "__fixkfdi"); 179 setLibcallName(RTLIB::FPTOSINT_F128_I128, "__fixkfti"); 180 setLibcallName(RTLIB::FPTOUINT_F128_I32, "__fixunskfsi"); 181 setLibcallName(RTLIB::FPTOUINT_F128_I64, "__fixunskfdi"); 182 setLibcallName(RTLIB::FPTOUINT_F128_I128, "__fixunskfti"); 183 setLibcallName(RTLIB::SINTTOFP_I32_F128, "__floatsikf"); 184 setLibcallName(RTLIB::SINTTOFP_I64_F128, "__floatdikf"); 185 setLibcallName(RTLIB::SINTTOFP_I128_F128, "__floattikf"); 186 setLibcallName(RTLIB::UINTTOFP_I32_F128, "__floatunsikf"); 187 setLibcallName(RTLIB::UINTTOFP_I64_F128, "__floatundikf"); 188 setLibcallName(RTLIB::UINTTOFP_I128_F128, "__floatuntikf"); 189 setLibcallName(RTLIB::OEQ_F128, "__eqkf2"); 190 setLibcallName(RTLIB::UNE_F128, "__nekf2"); 191 setLibcallName(RTLIB::OGE_F128, "__gekf2"); 192 setLibcallName(RTLIB::OLT_F128, "__ltkf2"); 193 setLibcallName(RTLIB::OLE_F128, "__lekf2"); 194 setLibcallName(RTLIB::OGT_F128, "__gtkf2"); 195 setLibcallName(RTLIB::UO_F128, "__unordkf2"); 196 } 197 198 // A few names are different on particular architectures or environments. 199 if (TT.isOSDarwin()) { 200 // For f16/f32 conversions, Darwin uses the standard naming scheme, instead 201 // of the gnueabi-style __gnu_*_ieee. 202 // FIXME: What about other targets? 203 setLibcallName(RTLIB::FPEXT_F16_F32, "__extendhfsf2"); 204 setLibcallName(RTLIB::FPROUND_F32_F16, "__truncsfhf2"); 205 206 // Some darwins have an optimized __bzero/bzero function. 207 switch (TT.getArch()) { 208 case Triple::x86: 209 case Triple::x86_64: 210 if (TT.isMacOSX() && !TT.isMacOSXVersionLT(10, 6)) 211 setLibcallName(RTLIB::BZERO, "__bzero"); 212 break; 213 case Triple::aarch64: 214 case Triple::aarch64_32: 215 setLibcallName(RTLIB::BZERO, "bzero"); 216 break; 217 default: 218 break; 219 } 220 221 if (darwinHasSinCos(TT)) { 222 setLibcallName(RTLIB::SINCOS_STRET_F32, "__sincosf_stret"); 223 setLibcallName(RTLIB::SINCOS_STRET_F64, "__sincos_stret"); 224 if (TT.isWatchABI()) { 225 setLibcallCallingConv(RTLIB::SINCOS_STRET_F32, 226 CallingConv::ARM_AAPCS_VFP); 227 setLibcallCallingConv(RTLIB::SINCOS_STRET_F64, 228 CallingConv::ARM_AAPCS_VFP); 229 } 230 } 231 232 switch (TT.getOS()) { 233 case Triple::MacOSX: 234 if (TT.isMacOSXVersionLT(10, 9)) { 235 setLibcallName(RTLIB::EXP10_F32, nullptr); 236 setLibcallName(RTLIB::EXP10_F64, nullptr); 237 } else { 238 setLibcallName(RTLIB::EXP10_F32, "__exp10f"); 239 setLibcallName(RTLIB::EXP10_F64, "__exp10"); 240 } 241 break; 242 case Triple::IOS: 243 case Triple::TvOS: 244 case Triple::WatchOS: 245 case Triple::XROS: 246 if (!TT.isWatchOS() && 247 (TT.isOSVersionLT(7, 0) || (TT.isOSVersionLT(9, 0) && TT.isX86()))) { 248 setLibcallName(RTLIB::EXP10_F32, nullptr); 249 setLibcallName(RTLIB::EXP10_F64, nullptr); 250 } else { 251 setLibcallName(RTLIB::EXP10_F32, "__exp10f"); 252 setLibcallName(RTLIB::EXP10_F64, "__exp10"); 253 } 254 255 break; 256 default: 257 break; 258 } 259 } else { 260 setLibcallName(RTLIB::FPEXT_F16_F32, "__gnu_h2f_ieee"); 261 setLibcallName(RTLIB::FPROUND_F32_F16, "__gnu_f2h_ieee"); 262 } 263 264 if (TT.isGNUEnvironment() || TT.isOSFuchsia() || 265 (TT.isAndroid() && !TT.isAndroidVersionLT(9))) { 266 setLibcallName(RTLIB::SINCOS_F32, "sincosf"); 267 setLibcallName(RTLIB::SINCOS_F64, "sincos"); 268 setLibcallName(RTLIB::SINCOS_F80, "sincosl"); 269 setLibcallName(RTLIB::SINCOS_F128, "sincosl"); 270 setLibcallName(RTLIB::SINCOS_PPCF128, "sincosl"); 271 } 272 273 if (TT.isPS()) { 274 setLibcallName(RTLIB::SINCOS_F32, "sincosf"); 275 setLibcallName(RTLIB::SINCOS_F64, "sincos"); 276 } 277 278 if (TT.isOSOpenBSD()) { 279 setLibcallName(RTLIB::STACKPROTECTOR_CHECK_FAIL, nullptr); 280 } 281 282 if (TT.isOSWindows() && !TT.isOSCygMing()) { 283 setLibcallName(RTLIB::LDEXP_F32, nullptr); 284 setLibcallName(RTLIB::LDEXP_F80, nullptr); 285 setLibcallName(RTLIB::LDEXP_F128, nullptr); 286 setLibcallName(RTLIB::LDEXP_PPCF128, nullptr); 287 288 setLibcallName(RTLIB::FREXP_F32, nullptr); 289 setLibcallName(RTLIB::FREXP_F80, nullptr); 290 setLibcallName(RTLIB::FREXP_F128, nullptr); 291 setLibcallName(RTLIB::FREXP_PPCF128, nullptr); 292 } 293 } 294 295 /// GetFPLibCall - Helper to return the right libcall for the given floating 296 /// point type, or UNKNOWN_LIBCALL if there is none. 297 RTLIB::Libcall RTLIB::getFPLibCall(EVT VT, 298 RTLIB::Libcall Call_F32, 299 RTLIB::Libcall Call_F64, 300 RTLIB::Libcall Call_F80, 301 RTLIB::Libcall Call_F128, 302 RTLIB::Libcall Call_PPCF128) { 303 return 304 VT == MVT::f32 ? Call_F32 : 305 VT == MVT::f64 ? Call_F64 : 306 VT == MVT::f80 ? Call_F80 : 307 VT == MVT::f128 ? Call_F128 : 308 VT == MVT::ppcf128 ? Call_PPCF128 : 309 RTLIB::UNKNOWN_LIBCALL; 310 } 311 312 /// getFPEXT - Return the FPEXT_*_* value for the given types, or 313 /// UNKNOWN_LIBCALL if there is none. 314 RTLIB::Libcall RTLIB::getFPEXT(EVT OpVT, EVT RetVT) { 315 if (OpVT == MVT::f16) { 316 if (RetVT == MVT::f32) 317 return FPEXT_F16_F32; 318 if (RetVT == MVT::f64) 319 return FPEXT_F16_F64; 320 if (RetVT == MVT::f80) 321 return FPEXT_F16_F80; 322 if (RetVT == MVT::f128) 323 return FPEXT_F16_F128; 324 } else if (OpVT == MVT::f32) { 325 if (RetVT == MVT::f64) 326 return FPEXT_F32_F64; 327 if (RetVT == MVT::f128) 328 return FPEXT_F32_F128; 329 if (RetVT == MVT::ppcf128) 330 return FPEXT_F32_PPCF128; 331 } else if (OpVT == MVT::f64) { 332 if (RetVT == MVT::f128) 333 return FPEXT_F64_F128; 334 else if (RetVT == MVT::ppcf128) 335 return FPEXT_F64_PPCF128; 336 } else if (OpVT == MVT::f80) { 337 if (RetVT == MVT::f128) 338 return FPEXT_F80_F128; 339 } else if (OpVT == MVT::bf16) { 340 if (RetVT == MVT::f32) 341 return FPEXT_BF16_F32; 342 } 343 344 return UNKNOWN_LIBCALL; 345 } 346 347 /// getFPROUND - Return the FPROUND_*_* value for the given types, or 348 /// UNKNOWN_LIBCALL if there is none. 349 RTLIB::Libcall RTLIB::getFPROUND(EVT OpVT, EVT RetVT) { 350 if (RetVT == MVT::f16) { 351 if (OpVT == MVT::f32) 352 return FPROUND_F32_F16; 353 if (OpVT == MVT::f64) 354 return FPROUND_F64_F16; 355 if (OpVT == MVT::f80) 356 return FPROUND_F80_F16; 357 if (OpVT == MVT::f128) 358 return FPROUND_F128_F16; 359 if (OpVT == MVT::ppcf128) 360 return FPROUND_PPCF128_F16; 361 } else if (RetVT == MVT::bf16) { 362 if (OpVT == MVT::f32) 363 return FPROUND_F32_BF16; 364 if (OpVT == MVT::f64) 365 return FPROUND_F64_BF16; 366 } else if (RetVT == MVT::f32) { 367 if (OpVT == MVT::f64) 368 return FPROUND_F64_F32; 369 if (OpVT == MVT::f80) 370 return FPROUND_F80_F32; 371 if (OpVT == MVT::f128) 372 return FPROUND_F128_F32; 373 if (OpVT == MVT::ppcf128) 374 return FPROUND_PPCF128_F32; 375 } else if (RetVT == MVT::f64) { 376 if (OpVT == MVT::f80) 377 return FPROUND_F80_F64; 378 if (OpVT == MVT::f128) 379 return FPROUND_F128_F64; 380 if (OpVT == MVT::ppcf128) 381 return FPROUND_PPCF128_F64; 382 } else if (RetVT == MVT::f80) { 383 if (OpVT == MVT::f128) 384 return FPROUND_F128_F80; 385 } 386 387 return UNKNOWN_LIBCALL; 388 } 389 390 /// getFPTOSINT - Return the FPTOSINT_*_* value for the given types, or 391 /// UNKNOWN_LIBCALL if there is none. 392 RTLIB::Libcall RTLIB::getFPTOSINT(EVT OpVT, EVT RetVT) { 393 if (OpVT == MVT::f16) { 394 if (RetVT == MVT::i32) 395 return FPTOSINT_F16_I32; 396 if (RetVT == MVT::i64) 397 return FPTOSINT_F16_I64; 398 if (RetVT == MVT::i128) 399 return FPTOSINT_F16_I128; 400 } else if (OpVT == MVT::f32) { 401 if (RetVT == MVT::i32) 402 return FPTOSINT_F32_I32; 403 if (RetVT == MVT::i64) 404 return FPTOSINT_F32_I64; 405 if (RetVT == MVT::i128) 406 return FPTOSINT_F32_I128; 407 } else if (OpVT == MVT::f64) { 408 if (RetVT == MVT::i32) 409 return FPTOSINT_F64_I32; 410 if (RetVT == MVT::i64) 411 return FPTOSINT_F64_I64; 412 if (RetVT == MVT::i128) 413 return FPTOSINT_F64_I128; 414 } else if (OpVT == MVT::f80) { 415 if (RetVT == MVT::i32) 416 return FPTOSINT_F80_I32; 417 if (RetVT == MVT::i64) 418 return FPTOSINT_F80_I64; 419 if (RetVT == MVT::i128) 420 return FPTOSINT_F80_I128; 421 } else if (OpVT == MVT::f128) { 422 if (RetVT == MVT::i32) 423 return FPTOSINT_F128_I32; 424 if (RetVT == MVT::i64) 425 return FPTOSINT_F128_I64; 426 if (RetVT == MVT::i128) 427 return FPTOSINT_F128_I128; 428 } else if (OpVT == MVT::ppcf128) { 429 if (RetVT == MVT::i32) 430 return FPTOSINT_PPCF128_I32; 431 if (RetVT == MVT::i64) 432 return FPTOSINT_PPCF128_I64; 433 if (RetVT == MVT::i128) 434 return FPTOSINT_PPCF128_I128; 435 } 436 return UNKNOWN_LIBCALL; 437 } 438 439 /// getFPTOUINT - Return the FPTOUINT_*_* value for the given types, or 440 /// UNKNOWN_LIBCALL if there is none. 441 RTLIB::Libcall RTLIB::getFPTOUINT(EVT OpVT, EVT RetVT) { 442 if (OpVT == MVT::f16) { 443 if (RetVT == MVT::i32) 444 return FPTOUINT_F16_I32; 445 if (RetVT == MVT::i64) 446 return FPTOUINT_F16_I64; 447 if (RetVT == MVT::i128) 448 return FPTOUINT_F16_I128; 449 } else if (OpVT == MVT::f32) { 450 if (RetVT == MVT::i32) 451 return FPTOUINT_F32_I32; 452 if (RetVT == MVT::i64) 453 return FPTOUINT_F32_I64; 454 if (RetVT == MVT::i128) 455 return FPTOUINT_F32_I128; 456 } else if (OpVT == MVT::f64) { 457 if (RetVT == MVT::i32) 458 return FPTOUINT_F64_I32; 459 if (RetVT == MVT::i64) 460 return FPTOUINT_F64_I64; 461 if (RetVT == MVT::i128) 462 return FPTOUINT_F64_I128; 463 } else if (OpVT == MVT::f80) { 464 if (RetVT == MVT::i32) 465 return FPTOUINT_F80_I32; 466 if (RetVT == MVT::i64) 467 return FPTOUINT_F80_I64; 468 if (RetVT == MVT::i128) 469 return FPTOUINT_F80_I128; 470 } else if (OpVT == MVT::f128) { 471 if (RetVT == MVT::i32) 472 return FPTOUINT_F128_I32; 473 if (RetVT == MVT::i64) 474 return FPTOUINT_F128_I64; 475 if (RetVT == MVT::i128) 476 return FPTOUINT_F128_I128; 477 } else if (OpVT == MVT::ppcf128) { 478 if (RetVT == MVT::i32) 479 return FPTOUINT_PPCF128_I32; 480 if (RetVT == MVT::i64) 481 return FPTOUINT_PPCF128_I64; 482 if (RetVT == MVT::i128) 483 return FPTOUINT_PPCF128_I128; 484 } 485 return UNKNOWN_LIBCALL; 486 } 487 488 /// getSINTTOFP - Return the SINTTOFP_*_* value for the given types, or 489 /// UNKNOWN_LIBCALL if there is none. 490 RTLIB::Libcall RTLIB::getSINTTOFP(EVT OpVT, EVT RetVT) { 491 if (OpVT == MVT::i32) { 492 if (RetVT == MVT::f16) 493 return SINTTOFP_I32_F16; 494 if (RetVT == MVT::f32) 495 return SINTTOFP_I32_F32; 496 if (RetVT == MVT::f64) 497 return SINTTOFP_I32_F64; 498 if (RetVT == MVT::f80) 499 return SINTTOFP_I32_F80; 500 if (RetVT == MVT::f128) 501 return SINTTOFP_I32_F128; 502 if (RetVT == MVT::ppcf128) 503 return SINTTOFP_I32_PPCF128; 504 } else if (OpVT == MVT::i64) { 505 if (RetVT == MVT::f16) 506 return SINTTOFP_I64_F16; 507 if (RetVT == MVT::f32) 508 return SINTTOFP_I64_F32; 509 if (RetVT == MVT::f64) 510 return SINTTOFP_I64_F64; 511 if (RetVT == MVT::f80) 512 return SINTTOFP_I64_F80; 513 if (RetVT == MVT::f128) 514 return SINTTOFP_I64_F128; 515 if (RetVT == MVT::ppcf128) 516 return SINTTOFP_I64_PPCF128; 517 } else if (OpVT == MVT::i128) { 518 if (RetVT == MVT::f16) 519 return SINTTOFP_I128_F16; 520 if (RetVT == MVT::f32) 521 return SINTTOFP_I128_F32; 522 if (RetVT == MVT::f64) 523 return SINTTOFP_I128_F64; 524 if (RetVT == MVT::f80) 525 return SINTTOFP_I128_F80; 526 if (RetVT == MVT::f128) 527 return SINTTOFP_I128_F128; 528 if (RetVT == MVT::ppcf128) 529 return SINTTOFP_I128_PPCF128; 530 } 531 return UNKNOWN_LIBCALL; 532 } 533 534 /// getUINTTOFP - Return the UINTTOFP_*_* value for the given types, or 535 /// UNKNOWN_LIBCALL if there is none. 536 RTLIB::Libcall RTLIB::getUINTTOFP(EVT OpVT, EVT RetVT) { 537 if (OpVT == MVT::i32) { 538 if (RetVT == MVT::f16) 539 return UINTTOFP_I32_F16; 540 if (RetVT == MVT::f32) 541 return UINTTOFP_I32_F32; 542 if (RetVT == MVT::f64) 543 return UINTTOFP_I32_F64; 544 if (RetVT == MVT::f80) 545 return UINTTOFP_I32_F80; 546 if (RetVT == MVT::f128) 547 return UINTTOFP_I32_F128; 548 if (RetVT == MVT::ppcf128) 549 return UINTTOFP_I32_PPCF128; 550 } else if (OpVT == MVT::i64) { 551 if (RetVT == MVT::f16) 552 return UINTTOFP_I64_F16; 553 if (RetVT == MVT::f32) 554 return UINTTOFP_I64_F32; 555 if (RetVT == MVT::f64) 556 return UINTTOFP_I64_F64; 557 if (RetVT == MVT::f80) 558 return UINTTOFP_I64_F80; 559 if (RetVT == MVT::f128) 560 return UINTTOFP_I64_F128; 561 if (RetVT == MVT::ppcf128) 562 return UINTTOFP_I64_PPCF128; 563 } else if (OpVT == MVT::i128) { 564 if (RetVT == MVT::f16) 565 return UINTTOFP_I128_F16; 566 if (RetVT == MVT::f32) 567 return UINTTOFP_I128_F32; 568 if (RetVT == MVT::f64) 569 return UINTTOFP_I128_F64; 570 if (RetVT == MVT::f80) 571 return UINTTOFP_I128_F80; 572 if (RetVT == MVT::f128) 573 return UINTTOFP_I128_F128; 574 if (RetVT == MVT::ppcf128) 575 return UINTTOFP_I128_PPCF128; 576 } 577 return UNKNOWN_LIBCALL; 578 } 579 580 RTLIB::Libcall RTLIB::getPOWI(EVT RetVT) { 581 return getFPLibCall(RetVT, POWI_F32, POWI_F64, POWI_F80, POWI_F128, 582 POWI_PPCF128); 583 } 584 585 RTLIB::Libcall RTLIB::getLDEXP(EVT RetVT) { 586 return getFPLibCall(RetVT, LDEXP_F32, LDEXP_F64, LDEXP_F80, LDEXP_F128, 587 LDEXP_PPCF128); 588 } 589 590 RTLIB::Libcall RTLIB::getFREXP(EVT RetVT) { 591 return getFPLibCall(RetVT, FREXP_F32, FREXP_F64, FREXP_F80, FREXP_F128, 592 FREXP_PPCF128); 593 } 594 595 RTLIB::Libcall RTLIB::getOutlineAtomicHelper(const Libcall (&LC)[5][4], 596 AtomicOrdering Order, 597 uint64_t MemSize) { 598 unsigned ModeN, ModelN; 599 switch (MemSize) { 600 case 1: 601 ModeN = 0; 602 break; 603 case 2: 604 ModeN = 1; 605 break; 606 case 4: 607 ModeN = 2; 608 break; 609 case 8: 610 ModeN = 3; 611 break; 612 case 16: 613 ModeN = 4; 614 break; 615 default: 616 return RTLIB::UNKNOWN_LIBCALL; 617 } 618 619 switch (Order) { 620 case AtomicOrdering::Monotonic: 621 ModelN = 0; 622 break; 623 case AtomicOrdering::Acquire: 624 ModelN = 1; 625 break; 626 case AtomicOrdering::Release: 627 ModelN = 2; 628 break; 629 case AtomicOrdering::AcquireRelease: 630 case AtomicOrdering::SequentiallyConsistent: 631 ModelN = 3; 632 break; 633 default: 634 return UNKNOWN_LIBCALL; 635 } 636 637 return LC[ModeN][ModelN]; 638 } 639 640 RTLIB::Libcall RTLIB::getOUTLINE_ATOMIC(unsigned Opc, AtomicOrdering Order, 641 MVT VT) { 642 if (!VT.isScalarInteger()) 643 return UNKNOWN_LIBCALL; 644 uint64_t MemSize = VT.getScalarSizeInBits() / 8; 645 646 #define LCALLS(A, B) \ 647 { A##B##_RELAX, A##B##_ACQ, A##B##_REL, A##B##_ACQ_REL } 648 #define LCALL5(A) \ 649 LCALLS(A, 1), LCALLS(A, 2), LCALLS(A, 4), LCALLS(A, 8), LCALLS(A, 16) 650 switch (Opc) { 651 case ISD::ATOMIC_CMP_SWAP: { 652 const Libcall LC[5][4] = {LCALL5(OUTLINE_ATOMIC_CAS)}; 653 return getOutlineAtomicHelper(LC, Order, MemSize); 654 } 655 case ISD::ATOMIC_SWAP: { 656 const Libcall LC[5][4] = {LCALL5(OUTLINE_ATOMIC_SWP)}; 657 return getOutlineAtomicHelper(LC, Order, MemSize); 658 } 659 case ISD::ATOMIC_LOAD_ADD: { 660 const Libcall LC[5][4] = {LCALL5(OUTLINE_ATOMIC_LDADD)}; 661 return getOutlineAtomicHelper(LC, Order, MemSize); 662 } 663 case ISD::ATOMIC_LOAD_OR: { 664 const Libcall LC[5][4] = {LCALL5(OUTLINE_ATOMIC_LDSET)}; 665 return getOutlineAtomicHelper(LC, Order, MemSize); 666 } 667 case ISD::ATOMIC_LOAD_CLR: { 668 const Libcall LC[5][4] = {LCALL5(OUTLINE_ATOMIC_LDCLR)}; 669 return getOutlineAtomicHelper(LC, Order, MemSize); 670 } 671 case ISD::ATOMIC_LOAD_XOR: { 672 const Libcall LC[5][4] = {LCALL5(OUTLINE_ATOMIC_LDEOR)}; 673 return getOutlineAtomicHelper(LC, Order, MemSize); 674 } 675 default: 676 return UNKNOWN_LIBCALL; 677 } 678 #undef LCALLS 679 #undef LCALL5 680 } 681 682 RTLIB::Libcall RTLIB::getSYNC(unsigned Opc, MVT VT) { 683 #define OP_TO_LIBCALL(Name, Enum) \ 684 case Name: \ 685 switch (VT.SimpleTy) { \ 686 default: \ 687 return UNKNOWN_LIBCALL; \ 688 case MVT::i8: \ 689 return Enum##_1; \ 690 case MVT::i16: \ 691 return Enum##_2; \ 692 case MVT::i32: \ 693 return Enum##_4; \ 694 case MVT::i64: \ 695 return Enum##_8; \ 696 case MVT::i128: \ 697 return Enum##_16; \ 698 } 699 700 switch (Opc) { 701 OP_TO_LIBCALL(ISD::ATOMIC_SWAP, SYNC_LOCK_TEST_AND_SET) 702 OP_TO_LIBCALL(ISD::ATOMIC_CMP_SWAP, SYNC_VAL_COMPARE_AND_SWAP) 703 OP_TO_LIBCALL(ISD::ATOMIC_LOAD_ADD, SYNC_FETCH_AND_ADD) 704 OP_TO_LIBCALL(ISD::ATOMIC_LOAD_SUB, SYNC_FETCH_AND_SUB) 705 OP_TO_LIBCALL(ISD::ATOMIC_LOAD_AND, SYNC_FETCH_AND_AND) 706 OP_TO_LIBCALL(ISD::ATOMIC_LOAD_OR, SYNC_FETCH_AND_OR) 707 OP_TO_LIBCALL(ISD::ATOMIC_LOAD_XOR, SYNC_FETCH_AND_XOR) 708 OP_TO_LIBCALL(ISD::ATOMIC_LOAD_NAND, SYNC_FETCH_AND_NAND) 709 OP_TO_LIBCALL(ISD::ATOMIC_LOAD_MAX, SYNC_FETCH_AND_MAX) 710 OP_TO_LIBCALL(ISD::ATOMIC_LOAD_UMAX, SYNC_FETCH_AND_UMAX) 711 OP_TO_LIBCALL(ISD::ATOMIC_LOAD_MIN, SYNC_FETCH_AND_MIN) 712 OP_TO_LIBCALL(ISD::ATOMIC_LOAD_UMIN, SYNC_FETCH_AND_UMIN) 713 } 714 715 #undef OP_TO_LIBCALL 716 717 return UNKNOWN_LIBCALL; 718 } 719 720 RTLIB::Libcall RTLIB::getMEMCPY_ELEMENT_UNORDERED_ATOMIC(uint64_t ElementSize) { 721 switch (ElementSize) { 722 case 1: 723 return MEMCPY_ELEMENT_UNORDERED_ATOMIC_1; 724 case 2: 725 return MEMCPY_ELEMENT_UNORDERED_ATOMIC_2; 726 case 4: 727 return MEMCPY_ELEMENT_UNORDERED_ATOMIC_4; 728 case 8: 729 return MEMCPY_ELEMENT_UNORDERED_ATOMIC_8; 730 case 16: 731 return MEMCPY_ELEMENT_UNORDERED_ATOMIC_16; 732 default: 733 return UNKNOWN_LIBCALL; 734 } 735 } 736 737 RTLIB::Libcall RTLIB::getMEMMOVE_ELEMENT_UNORDERED_ATOMIC(uint64_t ElementSize) { 738 switch (ElementSize) { 739 case 1: 740 return MEMMOVE_ELEMENT_UNORDERED_ATOMIC_1; 741 case 2: 742 return MEMMOVE_ELEMENT_UNORDERED_ATOMIC_2; 743 case 4: 744 return MEMMOVE_ELEMENT_UNORDERED_ATOMIC_4; 745 case 8: 746 return MEMMOVE_ELEMENT_UNORDERED_ATOMIC_8; 747 case 16: 748 return MEMMOVE_ELEMENT_UNORDERED_ATOMIC_16; 749 default: 750 return UNKNOWN_LIBCALL; 751 } 752 } 753 754 RTLIB::Libcall RTLIB::getMEMSET_ELEMENT_UNORDERED_ATOMIC(uint64_t ElementSize) { 755 switch (ElementSize) { 756 case 1: 757 return MEMSET_ELEMENT_UNORDERED_ATOMIC_1; 758 case 2: 759 return MEMSET_ELEMENT_UNORDERED_ATOMIC_2; 760 case 4: 761 return MEMSET_ELEMENT_UNORDERED_ATOMIC_4; 762 case 8: 763 return MEMSET_ELEMENT_UNORDERED_ATOMIC_8; 764 case 16: 765 return MEMSET_ELEMENT_UNORDERED_ATOMIC_16; 766 default: 767 return UNKNOWN_LIBCALL; 768 } 769 } 770 771 /// InitCmpLibcallCCs - Set default comparison libcall CC. 772 static void InitCmpLibcallCCs(ISD::CondCode *CCs) { 773 std::fill(CCs, CCs + RTLIB::UNKNOWN_LIBCALL, ISD::SETCC_INVALID); 774 CCs[RTLIB::OEQ_F32] = ISD::SETEQ; 775 CCs[RTLIB::OEQ_F64] = ISD::SETEQ; 776 CCs[RTLIB::OEQ_F128] = ISD::SETEQ; 777 CCs[RTLIB::OEQ_PPCF128] = ISD::SETEQ; 778 CCs[RTLIB::UNE_F32] = ISD::SETNE; 779 CCs[RTLIB::UNE_F64] = ISD::SETNE; 780 CCs[RTLIB::UNE_F128] = ISD::SETNE; 781 CCs[RTLIB::UNE_PPCF128] = ISD::SETNE; 782 CCs[RTLIB::OGE_F32] = ISD::SETGE; 783 CCs[RTLIB::OGE_F64] = ISD::SETGE; 784 CCs[RTLIB::OGE_F128] = ISD::SETGE; 785 CCs[RTLIB::OGE_PPCF128] = ISD::SETGE; 786 CCs[RTLIB::OLT_F32] = ISD::SETLT; 787 CCs[RTLIB::OLT_F64] = ISD::SETLT; 788 CCs[RTLIB::OLT_F128] = ISD::SETLT; 789 CCs[RTLIB::OLT_PPCF128] = ISD::SETLT; 790 CCs[RTLIB::OLE_F32] = ISD::SETLE; 791 CCs[RTLIB::OLE_F64] = ISD::SETLE; 792 CCs[RTLIB::OLE_F128] = ISD::SETLE; 793 CCs[RTLIB::OLE_PPCF128] = ISD::SETLE; 794 CCs[RTLIB::OGT_F32] = ISD::SETGT; 795 CCs[RTLIB::OGT_F64] = ISD::SETGT; 796 CCs[RTLIB::OGT_F128] = ISD::SETGT; 797 CCs[RTLIB::OGT_PPCF128] = ISD::SETGT; 798 CCs[RTLIB::UO_F32] = ISD::SETNE; 799 CCs[RTLIB::UO_F64] = ISD::SETNE; 800 CCs[RTLIB::UO_F128] = ISD::SETNE; 801 CCs[RTLIB::UO_PPCF128] = ISD::SETNE; 802 } 803 804 /// NOTE: The TargetMachine owns TLOF. 805 TargetLoweringBase::TargetLoweringBase(const TargetMachine &tm) : TM(tm) { 806 initActions(); 807 808 // Perform these initializations only once. 809 MaxStoresPerMemset = MaxStoresPerMemcpy = MaxStoresPerMemmove = 810 MaxLoadsPerMemcmp = 8; 811 MaxGluedStoresPerMemcpy = 0; 812 MaxStoresPerMemsetOptSize = MaxStoresPerMemcpyOptSize = 813 MaxStoresPerMemmoveOptSize = MaxLoadsPerMemcmpOptSize = 4; 814 HasMultipleConditionRegisters = false; 815 HasExtractBitsInsn = false; 816 JumpIsExpensive = JumpIsExpensiveOverride; 817 PredictableSelectIsExpensive = false; 818 EnableExtLdPromotion = false; 819 StackPointerRegisterToSaveRestore = 0; 820 BooleanContents = UndefinedBooleanContent; 821 BooleanFloatContents = UndefinedBooleanContent; 822 BooleanVectorContents = UndefinedBooleanContent; 823 SchedPreferenceInfo = Sched::ILP; 824 GatherAllAliasesMaxDepth = 18; 825 IsStrictFPEnabled = DisableStrictNodeMutation; 826 MaxBytesForAlignment = 0; 827 MaxAtomicSizeInBitsSupported = 0; 828 829 // Assume that even with libcalls, no target supports wider than 128 bit 830 // division. 831 MaxDivRemBitWidthSupported = 128; 832 833 MaxLargeFPConvertBitWidthSupported = llvm::IntegerType::MAX_INT_BITS; 834 835 MinCmpXchgSizeInBits = 0; 836 SupportsUnalignedAtomics = false; 837 838 std::fill(std::begin(LibcallRoutineNames), std::end(LibcallRoutineNames), nullptr); 839 840 InitLibcalls(TM.getTargetTriple()); 841 InitCmpLibcallCCs(CmpLibcallCCs); 842 } 843 844 void TargetLoweringBase::initActions() { 845 // All operations default to being supported. 846 memset(OpActions, 0, sizeof(OpActions)); 847 memset(LoadExtActions, 0, sizeof(LoadExtActions)); 848 memset(TruncStoreActions, 0, sizeof(TruncStoreActions)); 849 memset(IndexedModeActions, 0, sizeof(IndexedModeActions)); 850 memset(CondCodeActions, 0, sizeof(CondCodeActions)); 851 std::fill(std::begin(RegClassForVT), std::end(RegClassForVT), nullptr); 852 std::fill(std::begin(TargetDAGCombineArray), 853 std::end(TargetDAGCombineArray), 0); 854 855 // Let extending atomic loads be unsupported by default. 856 for (MVT ValVT : MVT::all_valuetypes()) 857 for (MVT MemVT : MVT::all_valuetypes()) 858 setAtomicLoadExtAction({ISD::SEXTLOAD, ISD::ZEXTLOAD}, ValVT, MemVT, 859 Expand); 860 861 // We're somewhat special casing MVT::i2 and MVT::i4. Ideally we want to 862 // remove this and targets should individually set these types if not legal. 863 for (ISD::NodeType NT : enum_seq(ISD::DELETED_NODE, ISD::BUILTIN_OP_END, 864 force_iteration_on_noniterable_enum)) { 865 for (MVT VT : {MVT::i2, MVT::i4}) 866 OpActions[(unsigned)VT.SimpleTy][NT] = Expand; 867 } 868 for (MVT AVT : MVT::all_valuetypes()) { 869 for (MVT VT : {MVT::i2, MVT::i4, MVT::v128i2, MVT::v64i4}) { 870 setTruncStoreAction(AVT, VT, Expand); 871 setLoadExtAction(ISD::EXTLOAD, AVT, VT, Expand); 872 setLoadExtAction(ISD::ZEXTLOAD, AVT, VT, Expand); 873 } 874 } 875 for (unsigned IM = (unsigned)ISD::PRE_INC; 876 IM != (unsigned)ISD::LAST_INDEXED_MODE; ++IM) { 877 for (MVT VT : {MVT::i2, MVT::i4}) { 878 setIndexedLoadAction(IM, VT, Expand); 879 setIndexedStoreAction(IM, VT, Expand); 880 setIndexedMaskedLoadAction(IM, VT, Expand); 881 setIndexedMaskedStoreAction(IM, VT, Expand); 882 } 883 } 884 885 for (MVT VT : MVT::fp_valuetypes()) { 886 MVT IntVT = MVT::getIntegerVT(VT.getFixedSizeInBits()); 887 if (IntVT.isValid()) { 888 setOperationAction(ISD::ATOMIC_SWAP, VT, Promote); 889 AddPromotedToType(ISD::ATOMIC_SWAP, VT, IntVT); 890 } 891 } 892 893 // Set default actions for various operations. 894 for (MVT VT : MVT::all_valuetypes()) { 895 // Default all indexed load / store to expand. 896 for (unsigned IM = (unsigned)ISD::PRE_INC; 897 IM != (unsigned)ISD::LAST_INDEXED_MODE; ++IM) { 898 setIndexedLoadAction(IM, VT, Expand); 899 setIndexedStoreAction(IM, VT, Expand); 900 setIndexedMaskedLoadAction(IM, VT, Expand); 901 setIndexedMaskedStoreAction(IM, VT, Expand); 902 } 903 904 // Most backends expect to see the node which just returns the value loaded. 905 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, VT, Expand); 906 907 // These operations default to expand. 908 setOperationAction({ISD::FGETSIGN, ISD::CONCAT_VECTORS, 909 ISD::FMINNUM, ISD::FMAXNUM, 910 ISD::FMINNUM_IEEE, ISD::FMAXNUM_IEEE, 911 ISD::FMINIMUM, ISD::FMAXIMUM, 912 ISD::FMAD, ISD::SMIN, 913 ISD::SMAX, ISD::UMIN, 914 ISD::UMAX, ISD::ABS, 915 ISD::FSHL, ISD::FSHR, 916 ISD::SADDSAT, ISD::UADDSAT, 917 ISD::SSUBSAT, ISD::USUBSAT, 918 ISD::SSHLSAT, ISD::USHLSAT, 919 ISD::SMULFIX, ISD::SMULFIXSAT, 920 ISD::UMULFIX, ISD::UMULFIXSAT, 921 ISD::SDIVFIX, ISD::SDIVFIXSAT, 922 ISD::UDIVFIX, ISD::UDIVFIXSAT, 923 ISD::FP_TO_SINT_SAT, ISD::FP_TO_UINT_SAT, 924 ISD::IS_FPCLASS}, 925 VT, Expand); 926 927 // Overflow operations default to expand 928 setOperationAction({ISD::SADDO, ISD::SSUBO, ISD::UADDO, ISD::USUBO, 929 ISD::SMULO, ISD::UMULO}, 930 VT, Expand); 931 932 // Carry-using overflow operations default to expand. 933 setOperationAction({ISD::UADDO_CARRY, ISD::USUBO_CARRY, ISD::SETCCCARRY, 934 ISD::SADDO_CARRY, ISD::SSUBO_CARRY}, 935 VT, Expand); 936 937 // ADDC/ADDE/SUBC/SUBE default to expand. 938 setOperationAction({ISD::ADDC, ISD::ADDE, ISD::SUBC, ISD::SUBE}, VT, 939 Expand); 940 941 // Halving adds 942 setOperationAction( 943 {ISD::AVGFLOORS, ISD::AVGFLOORU, ISD::AVGCEILS, ISD::AVGCEILU}, VT, 944 Expand); 945 946 // Absolute difference 947 setOperationAction({ISD::ABDS, ISD::ABDU}, VT, Expand); 948 949 // These default to Expand so they will be expanded to CTLZ/CTTZ by default. 950 setOperationAction({ISD::CTLZ_ZERO_UNDEF, ISD::CTTZ_ZERO_UNDEF}, VT, 951 Expand); 952 953 setOperationAction({ISD::BITREVERSE, ISD::PARITY}, VT, Expand); 954 955 // These library functions default to expand. 956 setOperationAction({ISD::FROUND, ISD::FPOWI, ISD::FLDEXP, ISD::FFREXP}, VT, 957 Expand); 958 959 // These operations default to expand for vector types. 960 if (VT.isVector()) 961 setOperationAction( 962 {ISD::FCOPYSIGN, ISD::SIGN_EXTEND_INREG, ISD::ANY_EXTEND_VECTOR_INREG, 963 ISD::SIGN_EXTEND_VECTOR_INREG, ISD::ZERO_EXTEND_VECTOR_INREG, 964 ISD::SPLAT_VECTOR, ISD::LRINT, ISD::LLRINT}, 965 VT, Expand); 966 967 // Constrained floating-point operations default to expand. 968 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \ 969 setOperationAction(ISD::STRICT_##DAGN, VT, Expand); 970 #include "llvm/IR/ConstrainedOps.def" 971 972 // For most targets @llvm.get.dynamic.area.offset just returns 0. 973 setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, VT, Expand); 974 975 // Vector reduction default to expand. 976 setOperationAction( 977 {ISD::VECREDUCE_FADD, ISD::VECREDUCE_FMUL, ISD::VECREDUCE_ADD, 978 ISD::VECREDUCE_MUL, ISD::VECREDUCE_AND, ISD::VECREDUCE_OR, 979 ISD::VECREDUCE_XOR, ISD::VECREDUCE_SMAX, ISD::VECREDUCE_SMIN, 980 ISD::VECREDUCE_UMAX, ISD::VECREDUCE_UMIN, ISD::VECREDUCE_FMAX, 981 ISD::VECREDUCE_FMIN, ISD::VECREDUCE_FMAXIMUM, ISD::VECREDUCE_FMINIMUM, 982 ISD::VECREDUCE_SEQ_FADD, ISD::VECREDUCE_SEQ_FMUL}, 983 VT, Expand); 984 985 // Named vector shuffles default to expand. 986 setOperationAction(ISD::VECTOR_SPLICE, VT, Expand); 987 988 // VP operations default to expand. 989 #define BEGIN_REGISTER_VP_SDNODE(SDOPC, ...) \ 990 setOperationAction(ISD::SDOPC, VT, Expand); 991 #include "llvm/IR/VPIntrinsics.def" 992 993 // FP environment operations default to expand. 994 setOperationAction(ISD::GET_FPENV, VT, Expand); 995 setOperationAction(ISD::SET_FPENV, VT, Expand); 996 setOperationAction(ISD::RESET_FPENV, VT, Expand); 997 } 998 999 // Most targets ignore the @llvm.prefetch intrinsic. 1000 setOperationAction(ISD::PREFETCH, MVT::Other, Expand); 1001 1002 // Most targets also ignore the @llvm.readcyclecounter intrinsic. 1003 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Expand); 1004 1005 // Most targets also ignore the @llvm.readsteadycounter intrinsic. 1006 setOperationAction(ISD::READSTEADYCOUNTER, MVT::i64, Expand); 1007 1008 // ConstantFP nodes default to expand. Targets can either change this to 1009 // Legal, in which case all fp constants are legal, or use isFPImmLegal() 1010 // to optimize expansions for certain constants. 1011 setOperationAction(ISD::ConstantFP, 1012 {MVT::bf16, MVT::f16, MVT::f32, MVT::f64, MVT::f80, MVT::f128}, 1013 Expand); 1014 1015 // These library functions default to expand. 1016 setOperationAction({ISD::FCBRT, ISD::FLOG, ISD::FLOG2, ISD::FLOG10, ISD::FEXP, 1017 ISD::FEXP2, ISD::FEXP10, ISD::FFLOOR, ISD::FNEARBYINT, 1018 ISD::FCEIL, ISD::FRINT, ISD::FTRUNC, ISD::LROUND, 1019 ISD::LLROUND, ISD::LRINT, ISD::LLRINT, ISD::FROUNDEVEN, 1020 ISD::FTAN}, 1021 {MVT::f32, MVT::f64, MVT::f128}, Expand); 1022 1023 // Default ISD::TRAP to expand (which turns it into abort). 1024 setOperationAction(ISD::TRAP, MVT::Other, Expand); 1025 1026 // On most systems, DEBUGTRAP and TRAP have no difference. The "Expand" 1027 // here is to inform DAG Legalizer to replace DEBUGTRAP with TRAP. 1028 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Expand); 1029 1030 setOperationAction(ISD::UBSANTRAP, MVT::Other, Expand); 1031 1032 setOperationAction(ISD::GET_FPENV_MEM, MVT::Other, Expand); 1033 setOperationAction(ISD::SET_FPENV_MEM, MVT::Other, Expand); 1034 1035 for (MVT VT : {MVT::i8, MVT::i16, MVT::i32, MVT::i64}) { 1036 setOperationAction(ISD::GET_FPMODE, VT, Expand); 1037 setOperationAction(ISD::SET_FPMODE, VT, Expand); 1038 } 1039 setOperationAction(ISD::RESET_FPMODE, MVT::Other, Expand); 1040 1041 // This one by default will call __clear_cache unless the target 1042 // wants something different. 1043 setOperationAction(ISD::CLEAR_CACHE, MVT::Other, LibCall); 1044 } 1045 1046 MVT TargetLoweringBase::getScalarShiftAmountTy(const DataLayout &DL, 1047 EVT) const { 1048 return MVT::getIntegerVT(DL.getPointerSizeInBits(0)); 1049 } 1050 1051 EVT TargetLoweringBase::getShiftAmountTy(EVT LHSTy, const DataLayout &DL, 1052 bool LegalTypes) const { 1053 assert(LHSTy.isInteger() && "Shift amount is not an integer type!"); 1054 if (LHSTy.isVector()) 1055 return LHSTy; 1056 MVT ShiftVT = 1057 LegalTypes ? getScalarShiftAmountTy(DL, LHSTy) : getPointerTy(DL); 1058 // If any possible shift value won't fit in the prefered type, just use 1059 // something safe. Assume it will be legalized when the shift is expanded. 1060 if (ShiftVT.getSizeInBits() < Log2_32_Ceil(LHSTy.getSizeInBits())) 1061 ShiftVT = MVT::i32; 1062 assert(ShiftVT.getSizeInBits() >= Log2_32_Ceil(LHSTy.getSizeInBits()) && 1063 "ShiftVT is still too small!"); 1064 return ShiftVT; 1065 } 1066 1067 bool TargetLoweringBase::canOpTrap(unsigned Op, EVT VT) const { 1068 assert(isTypeLegal(VT)); 1069 switch (Op) { 1070 default: 1071 return false; 1072 case ISD::SDIV: 1073 case ISD::UDIV: 1074 case ISD::SREM: 1075 case ISD::UREM: 1076 return true; 1077 } 1078 } 1079 1080 bool TargetLoweringBase::isFreeAddrSpaceCast(unsigned SrcAS, 1081 unsigned DestAS) const { 1082 return TM.isNoopAddrSpaceCast(SrcAS, DestAS); 1083 } 1084 1085 unsigned TargetLoweringBase::getBitWidthForCttzElements( 1086 Type *RetTy, ElementCount EC, bool ZeroIsPoison, 1087 const ConstantRange *VScaleRange) const { 1088 // Find the smallest "sensible" element type to use for the expansion. 1089 ConstantRange CR(APInt(64, EC.getKnownMinValue())); 1090 if (EC.isScalable()) 1091 CR = CR.umul_sat(*VScaleRange); 1092 1093 if (ZeroIsPoison) 1094 CR = CR.subtract(APInt(64, 1)); 1095 1096 unsigned EltWidth = RetTy->getScalarSizeInBits(); 1097 EltWidth = std::min(EltWidth, (unsigned)CR.getActiveBits()); 1098 EltWidth = std::max(llvm::bit_ceil(EltWidth), (unsigned)8); 1099 1100 return EltWidth; 1101 } 1102 1103 void TargetLoweringBase::setJumpIsExpensive(bool isExpensive) { 1104 // If the command-line option was specified, ignore this request. 1105 if (!JumpIsExpensiveOverride.getNumOccurrences()) 1106 JumpIsExpensive = isExpensive; 1107 } 1108 1109 TargetLoweringBase::LegalizeKind 1110 TargetLoweringBase::getTypeConversion(LLVMContext &Context, EVT VT) const { 1111 // If this is a simple type, use the ComputeRegisterProp mechanism. 1112 if (VT.isSimple()) { 1113 MVT SVT = VT.getSimpleVT(); 1114 assert((unsigned)SVT.SimpleTy < std::size(TransformToType)); 1115 MVT NVT = TransformToType[SVT.SimpleTy]; 1116 LegalizeTypeAction LA = ValueTypeActions.getTypeAction(SVT); 1117 1118 assert((LA == TypeLegal || LA == TypeSoftenFloat || 1119 LA == TypeSoftPromoteHalf || 1120 (NVT.isVector() || 1121 ValueTypeActions.getTypeAction(NVT) != TypePromoteInteger)) && 1122 "Promote may not follow Expand or Promote"); 1123 1124 if (LA == TypeSplitVector) 1125 return LegalizeKind(LA, EVT(SVT).getHalfNumVectorElementsVT(Context)); 1126 if (LA == TypeScalarizeVector) 1127 return LegalizeKind(LA, SVT.getVectorElementType()); 1128 return LegalizeKind(LA, NVT); 1129 } 1130 1131 // Handle Extended Scalar Types. 1132 if (!VT.isVector()) { 1133 assert(VT.isInteger() && "Float types must be simple"); 1134 unsigned BitSize = VT.getSizeInBits(); 1135 // First promote to a power-of-two size, then expand if necessary. 1136 if (BitSize < 8 || !isPowerOf2_32(BitSize)) { 1137 EVT NVT = VT.getRoundIntegerType(Context); 1138 assert(NVT != VT && "Unable to round integer VT"); 1139 LegalizeKind NextStep = getTypeConversion(Context, NVT); 1140 // Avoid multi-step promotion. 1141 if (NextStep.first == TypePromoteInteger) 1142 return NextStep; 1143 // Return rounded integer type. 1144 return LegalizeKind(TypePromoteInteger, NVT); 1145 } 1146 1147 return LegalizeKind(TypeExpandInteger, 1148 EVT::getIntegerVT(Context, VT.getSizeInBits() / 2)); 1149 } 1150 1151 // Handle vector types. 1152 ElementCount NumElts = VT.getVectorElementCount(); 1153 EVT EltVT = VT.getVectorElementType(); 1154 1155 // Vectors with only one element are always scalarized. 1156 if (NumElts.isScalar()) 1157 return LegalizeKind(TypeScalarizeVector, EltVT); 1158 1159 // Try to widen vector elements until the element type is a power of two and 1160 // promote it to a legal type later on, for example: 1161 // <3 x i8> -> <4 x i8> -> <4 x i32> 1162 if (EltVT.isInteger()) { 1163 // Vectors with a number of elements that is not a power of two are always 1164 // widened, for example <3 x i8> -> <4 x i8>. 1165 if (!VT.isPow2VectorType()) { 1166 NumElts = NumElts.coefficientNextPowerOf2(); 1167 EVT NVT = EVT::getVectorVT(Context, EltVT, NumElts); 1168 return LegalizeKind(TypeWidenVector, NVT); 1169 } 1170 1171 // Examine the element type. 1172 LegalizeKind LK = getTypeConversion(Context, EltVT); 1173 1174 // If type is to be expanded, split the vector. 1175 // <4 x i140> -> <2 x i140> 1176 if (LK.first == TypeExpandInteger) { 1177 if (VT.getVectorElementCount().isScalable()) 1178 return LegalizeKind(TypeScalarizeScalableVector, EltVT); 1179 return LegalizeKind(TypeSplitVector, 1180 VT.getHalfNumVectorElementsVT(Context)); 1181 } 1182 1183 // Promote the integer element types until a legal vector type is found 1184 // or until the element integer type is too big. If a legal type was not 1185 // found, fallback to the usual mechanism of widening/splitting the 1186 // vector. 1187 EVT OldEltVT = EltVT; 1188 while (true) { 1189 // Increase the bitwidth of the element to the next pow-of-two 1190 // (which is greater than 8 bits). 1191 EltVT = EVT::getIntegerVT(Context, 1 + EltVT.getSizeInBits()) 1192 .getRoundIntegerType(Context); 1193 1194 // Stop trying when getting a non-simple element type. 1195 // Note that vector elements may be greater than legal vector element 1196 // types. Example: X86 XMM registers hold 64bit element on 32bit 1197 // systems. 1198 if (!EltVT.isSimple()) 1199 break; 1200 1201 // Build a new vector type and check if it is legal. 1202 MVT NVT = MVT::getVectorVT(EltVT.getSimpleVT(), NumElts); 1203 // Found a legal promoted vector type. 1204 if (NVT != MVT() && ValueTypeActions.getTypeAction(NVT) == TypeLegal) 1205 return LegalizeKind(TypePromoteInteger, 1206 EVT::getVectorVT(Context, EltVT, NumElts)); 1207 } 1208 1209 // Reset the type to the unexpanded type if we did not find a legal vector 1210 // type with a promoted vector element type. 1211 EltVT = OldEltVT; 1212 } 1213 1214 // Try to widen the vector until a legal type is found. 1215 // If there is no wider legal type, split the vector. 1216 while (true) { 1217 // Round up to the next power of 2. 1218 NumElts = NumElts.coefficientNextPowerOf2(); 1219 1220 // If there is no simple vector type with this many elements then there 1221 // cannot be a larger legal vector type. Note that this assumes that 1222 // there are no skipped intermediate vector types in the simple types. 1223 if (!EltVT.isSimple()) 1224 break; 1225 MVT LargerVector = MVT::getVectorVT(EltVT.getSimpleVT(), NumElts); 1226 if (LargerVector == MVT()) 1227 break; 1228 1229 // If this type is legal then widen the vector. 1230 if (ValueTypeActions.getTypeAction(LargerVector) == TypeLegal) 1231 return LegalizeKind(TypeWidenVector, LargerVector); 1232 } 1233 1234 // Widen odd vectors to next power of two. 1235 if (!VT.isPow2VectorType()) { 1236 EVT NVT = VT.getPow2VectorType(Context); 1237 return LegalizeKind(TypeWidenVector, NVT); 1238 } 1239 1240 if (VT.getVectorElementCount() == ElementCount::getScalable(1)) 1241 return LegalizeKind(TypeScalarizeScalableVector, EltVT); 1242 1243 // Vectors with illegal element types are expanded. 1244 EVT NVT = EVT::getVectorVT(Context, EltVT, 1245 VT.getVectorElementCount().divideCoefficientBy(2)); 1246 return LegalizeKind(TypeSplitVector, NVT); 1247 } 1248 1249 static unsigned getVectorTypeBreakdownMVT(MVT VT, MVT &IntermediateVT, 1250 unsigned &NumIntermediates, 1251 MVT &RegisterVT, 1252 TargetLoweringBase *TLI) { 1253 // Figure out the right, legal destination reg to copy into. 1254 ElementCount EC = VT.getVectorElementCount(); 1255 MVT EltTy = VT.getVectorElementType(); 1256 1257 unsigned NumVectorRegs = 1; 1258 1259 // Scalable vectors cannot be scalarized, so splitting or widening is 1260 // required. 1261 if (VT.isScalableVector() && !isPowerOf2_32(EC.getKnownMinValue())) 1262 llvm_unreachable( 1263 "Splitting or widening of non-power-of-2 MVTs is not implemented."); 1264 1265 // FIXME: We don't support non-power-of-2-sized vectors for now. 1266 // Ideally we could break down into LHS/RHS like LegalizeDAG does. 1267 if (!isPowerOf2_32(EC.getKnownMinValue())) { 1268 // Split EC to unit size (scalable property is preserved). 1269 NumVectorRegs = EC.getKnownMinValue(); 1270 EC = ElementCount::getFixed(1); 1271 } 1272 1273 // Divide the input until we get to a supported size. This will 1274 // always end up with an EC that represent a scalar or a scalable 1275 // scalar. 1276 while (EC.getKnownMinValue() > 1 && 1277 !TLI->isTypeLegal(MVT::getVectorVT(EltTy, EC))) { 1278 EC = EC.divideCoefficientBy(2); 1279 NumVectorRegs <<= 1; 1280 } 1281 1282 NumIntermediates = NumVectorRegs; 1283 1284 MVT NewVT = MVT::getVectorVT(EltTy, EC); 1285 if (!TLI->isTypeLegal(NewVT)) 1286 NewVT = EltTy; 1287 IntermediateVT = NewVT; 1288 1289 unsigned LaneSizeInBits = NewVT.getScalarSizeInBits(); 1290 1291 // Convert sizes such as i33 to i64. 1292 LaneSizeInBits = llvm::bit_ceil(LaneSizeInBits); 1293 1294 MVT DestVT = TLI->getRegisterType(NewVT); 1295 RegisterVT = DestVT; 1296 if (EVT(DestVT).bitsLT(NewVT)) // Value is expanded, e.g. i64 -> i16. 1297 return NumVectorRegs * (LaneSizeInBits / DestVT.getScalarSizeInBits()); 1298 1299 // Otherwise, promotion or legal types use the same number of registers as 1300 // the vector decimated to the appropriate level. 1301 return NumVectorRegs; 1302 } 1303 1304 /// isLegalRC - Return true if the value types that can be represented by the 1305 /// specified register class are all legal. 1306 bool TargetLoweringBase::isLegalRC(const TargetRegisterInfo &TRI, 1307 const TargetRegisterClass &RC) const { 1308 for (const auto *I = TRI.legalclasstypes_begin(RC); *I != MVT::Other; ++I) 1309 if (isTypeLegal(*I)) 1310 return true; 1311 return false; 1312 } 1313 1314 /// Replace/modify any TargetFrameIndex operands with a targte-dependent 1315 /// sequence of memory operands that is recognized by PrologEpilogInserter. 1316 MachineBasicBlock * 1317 TargetLoweringBase::emitPatchPoint(MachineInstr &InitialMI, 1318 MachineBasicBlock *MBB) const { 1319 MachineInstr *MI = &InitialMI; 1320 MachineFunction &MF = *MI->getMF(); 1321 MachineFrameInfo &MFI = MF.getFrameInfo(); 1322 1323 // We're handling multiple types of operands here: 1324 // PATCHPOINT MetaArgs - live-in, read only, direct 1325 // STATEPOINT Deopt Spill - live-through, read only, indirect 1326 // STATEPOINT Deopt Alloca - live-through, read only, direct 1327 // (We're currently conservative and mark the deopt slots read/write in 1328 // practice.) 1329 // STATEPOINT GC Spill - live-through, read/write, indirect 1330 // STATEPOINT GC Alloca - live-through, read/write, direct 1331 // The live-in vs live-through is handled already (the live through ones are 1332 // all stack slots), but we need to handle the different type of stackmap 1333 // operands and memory effects here. 1334 1335 if (llvm::none_of(MI->operands(), 1336 [](MachineOperand &Operand) { return Operand.isFI(); })) 1337 return MBB; 1338 1339 MachineInstrBuilder MIB = BuildMI(MF, MI->getDebugLoc(), MI->getDesc()); 1340 1341 // Inherit previous memory operands. 1342 MIB.cloneMemRefs(*MI); 1343 1344 for (unsigned i = 0; i < MI->getNumOperands(); ++i) { 1345 MachineOperand &MO = MI->getOperand(i); 1346 if (!MO.isFI()) { 1347 // Index of Def operand this Use it tied to. 1348 // Since Defs are coming before Uses, if Use is tied, then 1349 // index of Def must be smaller that index of that Use. 1350 // Also, Defs preserve their position in new MI. 1351 unsigned TiedTo = i; 1352 if (MO.isReg() && MO.isTied()) 1353 TiedTo = MI->findTiedOperandIdx(i); 1354 MIB.add(MO); 1355 if (TiedTo < i) 1356 MIB->tieOperands(TiedTo, MIB->getNumOperands() - 1); 1357 continue; 1358 } 1359 1360 // foldMemoryOperand builds a new MI after replacing a single FI operand 1361 // with the canonical set of five x86 addressing-mode operands. 1362 int FI = MO.getIndex(); 1363 1364 // Add frame index operands recognized by stackmaps.cpp 1365 if (MFI.isStatepointSpillSlotObjectIndex(FI)) { 1366 // indirect-mem-ref tag, size, #FI, offset. 1367 // Used for spills inserted by StatepointLowering. This codepath is not 1368 // used for patchpoints/stackmaps at all, for these spilling is done via 1369 // foldMemoryOperand callback only. 1370 assert(MI->getOpcode() == TargetOpcode::STATEPOINT && "sanity"); 1371 MIB.addImm(StackMaps::IndirectMemRefOp); 1372 MIB.addImm(MFI.getObjectSize(FI)); 1373 MIB.add(MO); 1374 MIB.addImm(0); 1375 } else { 1376 // direct-mem-ref tag, #FI, offset. 1377 // Used by patchpoint, and direct alloca arguments to statepoints 1378 MIB.addImm(StackMaps::DirectMemRefOp); 1379 MIB.add(MO); 1380 MIB.addImm(0); 1381 } 1382 1383 assert(MIB->mayLoad() && "Folded a stackmap use to a non-load!"); 1384 1385 // Add a new memory operand for this FI. 1386 assert(MFI.getObjectOffset(FI) != -1); 1387 1388 // Note: STATEPOINT MMOs are added during SelectionDAG. STACKMAP, and 1389 // PATCHPOINT should be updated to do the same. (TODO) 1390 if (MI->getOpcode() != TargetOpcode::STATEPOINT) { 1391 auto Flags = MachineMemOperand::MOLoad; 1392 MachineMemOperand *MMO = MF.getMachineMemOperand( 1393 MachinePointerInfo::getFixedStack(MF, FI), Flags, 1394 MF.getDataLayout().getPointerSize(), MFI.getObjectAlign(FI)); 1395 MIB->addMemOperand(MF, MMO); 1396 } 1397 } 1398 MBB->insert(MachineBasicBlock::iterator(MI), MIB); 1399 MI->eraseFromParent(); 1400 return MBB; 1401 } 1402 1403 /// findRepresentativeClass - Return the largest legal super-reg register class 1404 /// of the register class for the specified type and its associated "cost". 1405 // This function is in TargetLowering because it uses RegClassForVT which would 1406 // need to be moved to TargetRegisterInfo and would necessitate moving 1407 // isTypeLegal over as well - a massive change that would just require 1408 // TargetLowering having a TargetRegisterInfo class member that it would use. 1409 std::pair<const TargetRegisterClass *, uint8_t> 1410 TargetLoweringBase::findRepresentativeClass(const TargetRegisterInfo *TRI, 1411 MVT VT) const { 1412 const TargetRegisterClass *RC = RegClassForVT[VT.SimpleTy]; 1413 if (!RC) 1414 return std::make_pair(RC, 0); 1415 1416 // Compute the set of all super-register classes. 1417 BitVector SuperRegRC(TRI->getNumRegClasses()); 1418 for (SuperRegClassIterator RCI(RC, TRI); RCI.isValid(); ++RCI) 1419 SuperRegRC.setBitsInMask(RCI.getMask()); 1420 1421 // Find the first legal register class with the largest spill size. 1422 const TargetRegisterClass *BestRC = RC; 1423 for (unsigned i : SuperRegRC.set_bits()) { 1424 const TargetRegisterClass *SuperRC = TRI->getRegClass(i); 1425 // We want the largest possible spill size. 1426 if (TRI->getSpillSize(*SuperRC) <= TRI->getSpillSize(*BestRC)) 1427 continue; 1428 if (!isLegalRC(*TRI, *SuperRC)) 1429 continue; 1430 BestRC = SuperRC; 1431 } 1432 return std::make_pair(BestRC, 1); 1433 } 1434 1435 /// computeRegisterProperties - Once all of the register classes are added, 1436 /// this allows us to compute derived properties we expose. 1437 void TargetLoweringBase::computeRegisterProperties( 1438 const TargetRegisterInfo *TRI) { 1439 // Everything defaults to needing one register. 1440 for (unsigned i = 0; i != MVT::VALUETYPE_SIZE; ++i) { 1441 NumRegistersForVT[i] = 1; 1442 RegisterTypeForVT[i] = TransformToType[i] = (MVT::SimpleValueType)i; 1443 } 1444 // ...except isVoid, which doesn't need any registers. 1445 NumRegistersForVT[MVT::isVoid] = 0; 1446 1447 // Find the largest integer register class. 1448 unsigned LargestIntReg = MVT::LAST_INTEGER_VALUETYPE; 1449 for (; RegClassForVT[LargestIntReg] == nullptr; --LargestIntReg) 1450 assert(LargestIntReg != MVT::i1 && "No integer registers defined!"); 1451 1452 // Every integer value type larger than this largest register takes twice as 1453 // many registers to represent as the previous ValueType. 1454 for (unsigned ExpandedReg = LargestIntReg + 1; 1455 ExpandedReg <= MVT::LAST_INTEGER_VALUETYPE; ++ExpandedReg) { 1456 NumRegistersForVT[ExpandedReg] = 2*NumRegistersForVT[ExpandedReg-1]; 1457 RegisterTypeForVT[ExpandedReg] = (MVT::SimpleValueType)LargestIntReg; 1458 TransformToType[ExpandedReg] = (MVT::SimpleValueType)(ExpandedReg - 1); 1459 ValueTypeActions.setTypeAction((MVT::SimpleValueType)ExpandedReg, 1460 TypeExpandInteger); 1461 } 1462 1463 // Inspect all of the ValueType's smaller than the largest integer 1464 // register to see which ones need promotion. 1465 unsigned LegalIntReg = LargestIntReg; 1466 for (unsigned IntReg = LargestIntReg - 1; 1467 IntReg >= (unsigned)MVT::i1; --IntReg) { 1468 MVT IVT = (MVT::SimpleValueType)IntReg; 1469 if (isTypeLegal(IVT)) { 1470 LegalIntReg = IntReg; 1471 } else { 1472 RegisterTypeForVT[IntReg] = TransformToType[IntReg] = 1473 (MVT::SimpleValueType)LegalIntReg; 1474 ValueTypeActions.setTypeAction(IVT, TypePromoteInteger); 1475 } 1476 } 1477 1478 // ppcf128 type is really two f64's. 1479 if (!isTypeLegal(MVT::ppcf128)) { 1480 if (isTypeLegal(MVT::f64)) { 1481 NumRegistersForVT[MVT::ppcf128] = 2*NumRegistersForVT[MVT::f64]; 1482 RegisterTypeForVT[MVT::ppcf128] = MVT::f64; 1483 TransformToType[MVT::ppcf128] = MVT::f64; 1484 ValueTypeActions.setTypeAction(MVT::ppcf128, TypeExpandFloat); 1485 } else { 1486 NumRegistersForVT[MVT::ppcf128] = NumRegistersForVT[MVT::i128]; 1487 RegisterTypeForVT[MVT::ppcf128] = RegisterTypeForVT[MVT::i128]; 1488 TransformToType[MVT::ppcf128] = MVT::i128; 1489 ValueTypeActions.setTypeAction(MVT::ppcf128, TypeSoftenFloat); 1490 } 1491 } 1492 1493 // Decide how to handle f128. If the target does not have native f128 support, 1494 // expand it to i128 and we will be generating soft float library calls. 1495 if (!isTypeLegal(MVT::f128)) { 1496 NumRegistersForVT[MVT::f128] = NumRegistersForVT[MVT::i128]; 1497 RegisterTypeForVT[MVT::f128] = RegisterTypeForVT[MVT::i128]; 1498 TransformToType[MVT::f128] = MVT::i128; 1499 ValueTypeActions.setTypeAction(MVT::f128, TypeSoftenFloat); 1500 } 1501 1502 // Decide how to handle f80. If the target does not have native f80 support, 1503 // expand it to i96 and we will be generating soft float library calls. 1504 if (!isTypeLegal(MVT::f80)) { 1505 NumRegistersForVT[MVT::f80] = 3*NumRegistersForVT[MVT::i32]; 1506 RegisterTypeForVT[MVT::f80] = RegisterTypeForVT[MVT::i32]; 1507 TransformToType[MVT::f80] = MVT::i32; 1508 ValueTypeActions.setTypeAction(MVT::f80, TypeSoftenFloat); 1509 } 1510 1511 // Decide how to handle f64. If the target does not have native f64 support, 1512 // expand it to i64 and we will be generating soft float library calls. 1513 if (!isTypeLegal(MVT::f64)) { 1514 NumRegistersForVT[MVT::f64] = NumRegistersForVT[MVT::i64]; 1515 RegisterTypeForVT[MVT::f64] = RegisterTypeForVT[MVT::i64]; 1516 TransformToType[MVT::f64] = MVT::i64; 1517 ValueTypeActions.setTypeAction(MVT::f64, TypeSoftenFloat); 1518 } 1519 1520 // Decide how to handle f32. If the target does not have native f32 support, 1521 // expand it to i32 and we will be generating soft float library calls. 1522 if (!isTypeLegal(MVT::f32)) { 1523 NumRegistersForVT[MVT::f32] = NumRegistersForVT[MVT::i32]; 1524 RegisterTypeForVT[MVT::f32] = RegisterTypeForVT[MVT::i32]; 1525 TransformToType[MVT::f32] = MVT::i32; 1526 ValueTypeActions.setTypeAction(MVT::f32, TypeSoftenFloat); 1527 } 1528 1529 // Decide how to handle f16. If the target does not have native f16 support, 1530 // promote it to f32, because there are no f16 library calls (except for 1531 // conversions). 1532 if (!isTypeLegal(MVT::f16)) { 1533 // Allow targets to control how we legalize half. 1534 bool SoftPromoteHalfType = softPromoteHalfType(); 1535 bool UseFPRegsForHalfType = !SoftPromoteHalfType || useFPRegsForHalfType(); 1536 1537 if (!UseFPRegsForHalfType) { 1538 NumRegistersForVT[MVT::f16] = NumRegistersForVT[MVT::i16]; 1539 RegisterTypeForVT[MVT::f16] = RegisterTypeForVT[MVT::i16]; 1540 } else { 1541 NumRegistersForVT[MVT::f16] = NumRegistersForVT[MVT::f32]; 1542 RegisterTypeForVT[MVT::f16] = RegisterTypeForVT[MVT::f32]; 1543 } 1544 TransformToType[MVT::f16] = MVT::f32; 1545 if (SoftPromoteHalfType) { 1546 ValueTypeActions.setTypeAction(MVT::f16, TypeSoftPromoteHalf); 1547 } else { 1548 ValueTypeActions.setTypeAction(MVT::f16, TypePromoteFloat); 1549 } 1550 } 1551 1552 // Decide how to handle bf16. If the target does not have native bf16 support, 1553 // promote it to f32, because there are no bf16 library calls (except for 1554 // converting from f32 to bf16). 1555 if (!isTypeLegal(MVT::bf16)) { 1556 NumRegistersForVT[MVT::bf16] = NumRegistersForVT[MVT::f32]; 1557 RegisterTypeForVT[MVT::bf16] = RegisterTypeForVT[MVT::f32]; 1558 TransformToType[MVT::bf16] = MVT::f32; 1559 ValueTypeActions.setTypeAction(MVT::bf16, TypeSoftPromoteHalf); 1560 } 1561 1562 // Loop over all of the vector value types to see which need transformations. 1563 for (unsigned i = MVT::FIRST_VECTOR_VALUETYPE; 1564 i <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++i) { 1565 MVT VT = (MVT::SimpleValueType) i; 1566 if (isTypeLegal(VT)) 1567 continue; 1568 1569 MVT EltVT = VT.getVectorElementType(); 1570 ElementCount EC = VT.getVectorElementCount(); 1571 bool IsLegalWiderType = false; 1572 bool IsScalable = VT.isScalableVector(); 1573 LegalizeTypeAction PreferredAction = getPreferredVectorAction(VT); 1574 switch (PreferredAction) { 1575 case TypePromoteInteger: { 1576 MVT::SimpleValueType EndVT = IsScalable ? 1577 MVT::LAST_INTEGER_SCALABLE_VECTOR_VALUETYPE : 1578 MVT::LAST_INTEGER_FIXEDLEN_VECTOR_VALUETYPE; 1579 // Try to promote the elements of integer vectors. If no legal 1580 // promotion was found, fall through to the widen-vector method. 1581 for (unsigned nVT = i + 1; 1582 (MVT::SimpleValueType)nVT <= EndVT; ++nVT) { 1583 MVT SVT = (MVT::SimpleValueType) nVT; 1584 // Promote vectors of integers to vectors with the same number 1585 // of elements, with a wider element type. 1586 if (SVT.getScalarSizeInBits() > EltVT.getFixedSizeInBits() && 1587 SVT.getVectorElementCount() == EC && isTypeLegal(SVT)) { 1588 TransformToType[i] = SVT; 1589 RegisterTypeForVT[i] = SVT; 1590 NumRegistersForVT[i] = 1; 1591 ValueTypeActions.setTypeAction(VT, TypePromoteInteger); 1592 IsLegalWiderType = true; 1593 break; 1594 } 1595 } 1596 if (IsLegalWiderType) 1597 break; 1598 [[fallthrough]]; 1599 } 1600 1601 case TypeWidenVector: 1602 if (isPowerOf2_32(EC.getKnownMinValue())) { 1603 // Try to widen the vector. 1604 for (unsigned nVT = i + 1; nVT <= MVT::LAST_VECTOR_VALUETYPE; ++nVT) { 1605 MVT SVT = (MVT::SimpleValueType) nVT; 1606 if (SVT.getVectorElementType() == EltVT && 1607 SVT.isScalableVector() == IsScalable && 1608 SVT.getVectorElementCount().getKnownMinValue() > 1609 EC.getKnownMinValue() && 1610 isTypeLegal(SVT)) { 1611 TransformToType[i] = SVT; 1612 RegisterTypeForVT[i] = SVT; 1613 NumRegistersForVT[i] = 1; 1614 ValueTypeActions.setTypeAction(VT, TypeWidenVector); 1615 IsLegalWiderType = true; 1616 break; 1617 } 1618 } 1619 if (IsLegalWiderType) 1620 break; 1621 } else { 1622 // Only widen to the next power of 2 to keep consistency with EVT. 1623 MVT NVT = VT.getPow2VectorType(); 1624 if (isTypeLegal(NVT)) { 1625 TransformToType[i] = NVT; 1626 ValueTypeActions.setTypeAction(VT, TypeWidenVector); 1627 RegisterTypeForVT[i] = NVT; 1628 NumRegistersForVT[i] = 1; 1629 break; 1630 } 1631 } 1632 [[fallthrough]]; 1633 1634 case TypeSplitVector: 1635 case TypeScalarizeVector: { 1636 MVT IntermediateVT; 1637 MVT RegisterVT; 1638 unsigned NumIntermediates; 1639 unsigned NumRegisters = getVectorTypeBreakdownMVT(VT, IntermediateVT, 1640 NumIntermediates, RegisterVT, this); 1641 NumRegistersForVT[i] = NumRegisters; 1642 assert(NumRegistersForVT[i] == NumRegisters && 1643 "NumRegistersForVT size cannot represent NumRegisters!"); 1644 RegisterTypeForVT[i] = RegisterVT; 1645 1646 MVT NVT = VT.getPow2VectorType(); 1647 if (NVT == VT) { 1648 // Type is already a power of 2. The default action is to split. 1649 TransformToType[i] = MVT::Other; 1650 if (PreferredAction == TypeScalarizeVector) 1651 ValueTypeActions.setTypeAction(VT, TypeScalarizeVector); 1652 else if (PreferredAction == TypeSplitVector) 1653 ValueTypeActions.setTypeAction(VT, TypeSplitVector); 1654 else if (EC.getKnownMinValue() > 1) 1655 ValueTypeActions.setTypeAction(VT, TypeSplitVector); 1656 else 1657 ValueTypeActions.setTypeAction(VT, EC.isScalable() 1658 ? TypeScalarizeScalableVector 1659 : TypeScalarizeVector); 1660 } else { 1661 TransformToType[i] = NVT; 1662 ValueTypeActions.setTypeAction(VT, TypeWidenVector); 1663 } 1664 break; 1665 } 1666 default: 1667 llvm_unreachable("Unknown vector legalization action!"); 1668 } 1669 } 1670 1671 // Determine the 'representative' register class for each value type. 1672 // An representative register class is the largest (meaning one which is 1673 // not a sub-register class / subreg register class) legal register class for 1674 // a group of value types. For example, on i386, i8, i16, and i32 1675 // representative would be GR32; while on x86_64 it's GR64. 1676 for (unsigned i = 0; i != MVT::VALUETYPE_SIZE; ++i) { 1677 const TargetRegisterClass* RRC; 1678 uint8_t Cost; 1679 std::tie(RRC, Cost) = findRepresentativeClass(TRI, (MVT::SimpleValueType)i); 1680 RepRegClassForVT[i] = RRC; 1681 RepRegClassCostForVT[i] = Cost; 1682 } 1683 } 1684 1685 EVT TargetLoweringBase::getSetCCResultType(const DataLayout &DL, LLVMContext &, 1686 EVT VT) const { 1687 assert(!VT.isVector() && "No default SetCC type for vectors!"); 1688 return getPointerTy(DL).SimpleTy; 1689 } 1690 1691 MVT::SimpleValueType TargetLoweringBase::getCmpLibcallReturnType() const { 1692 return MVT::i32; // return the default value 1693 } 1694 1695 /// getVectorTypeBreakdown - Vector types are broken down into some number of 1696 /// legal first class types. For example, MVT::v8f32 maps to 2 MVT::v4f32 1697 /// with Altivec or SSE1, or 8 promoted MVT::f64 values with the X86 FP stack. 1698 /// Similarly, MVT::v2i64 turns into 4 MVT::i32 values with both PPC and X86. 1699 /// 1700 /// This method returns the number of registers needed, and the VT for each 1701 /// register. It also returns the VT and quantity of the intermediate values 1702 /// before they are promoted/expanded. 1703 unsigned TargetLoweringBase::getVectorTypeBreakdown(LLVMContext &Context, 1704 EVT VT, EVT &IntermediateVT, 1705 unsigned &NumIntermediates, 1706 MVT &RegisterVT) const { 1707 ElementCount EltCnt = VT.getVectorElementCount(); 1708 1709 // If there is a wider vector type with the same element type as this one, 1710 // or a promoted vector type that has the same number of elements which 1711 // are wider, then we should convert to that legal vector type. 1712 // This handles things like <2 x float> -> <4 x float> and 1713 // <4 x i1> -> <4 x i32>. 1714 LegalizeTypeAction TA = getTypeAction(Context, VT); 1715 if (!EltCnt.isScalar() && 1716 (TA == TypeWidenVector || TA == TypePromoteInteger)) { 1717 EVT RegisterEVT = getTypeToTransformTo(Context, VT); 1718 if (isTypeLegal(RegisterEVT)) { 1719 IntermediateVT = RegisterEVT; 1720 RegisterVT = RegisterEVT.getSimpleVT(); 1721 NumIntermediates = 1; 1722 return 1; 1723 } 1724 } 1725 1726 // Figure out the right, legal destination reg to copy into. 1727 EVT EltTy = VT.getVectorElementType(); 1728 1729 unsigned NumVectorRegs = 1; 1730 1731 // Scalable vectors cannot be scalarized, so handle the legalisation of the 1732 // types like done elsewhere in SelectionDAG. 1733 if (EltCnt.isScalable()) { 1734 LegalizeKind LK; 1735 EVT PartVT = VT; 1736 do { 1737 // Iterate until we've found a legal (part) type to hold VT. 1738 LK = getTypeConversion(Context, PartVT); 1739 PartVT = LK.second; 1740 } while (LK.first != TypeLegal); 1741 1742 if (!PartVT.isVector()) { 1743 report_fatal_error( 1744 "Don't know how to legalize this scalable vector type"); 1745 } 1746 1747 NumIntermediates = 1748 divideCeil(VT.getVectorElementCount().getKnownMinValue(), 1749 PartVT.getVectorElementCount().getKnownMinValue()); 1750 IntermediateVT = PartVT; 1751 RegisterVT = getRegisterType(Context, IntermediateVT); 1752 return NumIntermediates; 1753 } 1754 1755 // FIXME: We don't support non-power-of-2-sized vectors for now. Ideally 1756 // we could break down into LHS/RHS like LegalizeDAG does. 1757 if (!isPowerOf2_32(EltCnt.getKnownMinValue())) { 1758 NumVectorRegs = EltCnt.getKnownMinValue(); 1759 EltCnt = ElementCount::getFixed(1); 1760 } 1761 1762 // Divide the input until we get to a supported size. This will always 1763 // end with a scalar if the target doesn't support vectors. 1764 while (EltCnt.getKnownMinValue() > 1 && 1765 !isTypeLegal(EVT::getVectorVT(Context, EltTy, EltCnt))) { 1766 EltCnt = EltCnt.divideCoefficientBy(2); 1767 NumVectorRegs <<= 1; 1768 } 1769 1770 NumIntermediates = NumVectorRegs; 1771 1772 EVT NewVT = EVT::getVectorVT(Context, EltTy, EltCnt); 1773 if (!isTypeLegal(NewVT)) 1774 NewVT = EltTy; 1775 IntermediateVT = NewVT; 1776 1777 MVT DestVT = getRegisterType(Context, NewVT); 1778 RegisterVT = DestVT; 1779 1780 if (EVT(DestVT).bitsLT(NewVT)) { // Value is expanded, e.g. i64 -> i16. 1781 TypeSize NewVTSize = NewVT.getSizeInBits(); 1782 // Convert sizes such as i33 to i64. 1783 if (!llvm::has_single_bit<uint32_t>(NewVTSize.getKnownMinValue())) 1784 NewVTSize = NewVTSize.coefficientNextPowerOf2(); 1785 return NumVectorRegs*(NewVTSize/DestVT.getSizeInBits()); 1786 } 1787 1788 // Otherwise, promotion or legal types use the same number of registers as 1789 // the vector decimated to the appropriate level. 1790 return NumVectorRegs; 1791 } 1792 1793 bool TargetLoweringBase::isSuitableForJumpTable(const SwitchInst *SI, 1794 uint64_t NumCases, 1795 uint64_t Range, 1796 ProfileSummaryInfo *PSI, 1797 BlockFrequencyInfo *BFI) const { 1798 // FIXME: This function check the maximum table size and density, but the 1799 // minimum size is not checked. It would be nice if the minimum size is 1800 // also combined within this function. Currently, the minimum size check is 1801 // performed in findJumpTable() in SelectionDAGBuiler and 1802 // getEstimatedNumberOfCaseClusters() in BasicTTIImpl. 1803 const bool OptForSize = 1804 SI->getParent()->getParent()->hasOptSize() || 1805 llvm::shouldOptimizeForSize(SI->getParent(), PSI, BFI); 1806 const unsigned MinDensity = getMinimumJumpTableDensity(OptForSize); 1807 const unsigned MaxJumpTableSize = getMaximumJumpTableSize(); 1808 1809 // Check whether the number of cases is small enough and 1810 // the range is dense enough for a jump table. 1811 return (OptForSize || Range <= MaxJumpTableSize) && 1812 (NumCases * 100 >= Range * MinDensity); 1813 } 1814 1815 MVT TargetLoweringBase::getPreferredSwitchConditionType(LLVMContext &Context, 1816 EVT ConditionVT) const { 1817 return getRegisterType(Context, ConditionVT); 1818 } 1819 1820 /// Get the EVTs and ArgFlags collections that represent the legalized return 1821 /// type of the given function. This does not require a DAG or a return value, 1822 /// and is suitable for use before any DAGs for the function are constructed. 1823 /// TODO: Move this out of TargetLowering.cpp. 1824 void llvm::GetReturnInfo(CallingConv::ID CC, Type *ReturnType, 1825 AttributeList attr, 1826 SmallVectorImpl<ISD::OutputArg> &Outs, 1827 const TargetLowering &TLI, const DataLayout &DL) { 1828 SmallVector<EVT, 4> ValueVTs; 1829 ComputeValueVTs(TLI, DL, ReturnType, ValueVTs); 1830 unsigned NumValues = ValueVTs.size(); 1831 if (NumValues == 0) return; 1832 1833 for (unsigned j = 0, f = NumValues; j != f; ++j) { 1834 EVT VT = ValueVTs[j]; 1835 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 1836 1837 if (attr.hasRetAttr(Attribute::SExt)) 1838 ExtendKind = ISD::SIGN_EXTEND; 1839 else if (attr.hasRetAttr(Attribute::ZExt)) 1840 ExtendKind = ISD::ZERO_EXTEND; 1841 1842 if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger()) 1843 VT = TLI.getTypeForExtReturn(ReturnType->getContext(), VT, ExtendKind); 1844 1845 unsigned NumParts = 1846 TLI.getNumRegistersForCallingConv(ReturnType->getContext(), CC, VT); 1847 MVT PartVT = 1848 TLI.getRegisterTypeForCallingConv(ReturnType->getContext(), CC, VT); 1849 1850 // 'inreg' on function refers to return value 1851 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy(); 1852 if (attr.hasRetAttr(Attribute::InReg)) 1853 Flags.setInReg(); 1854 1855 // Propagate extension type if any 1856 if (attr.hasRetAttr(Attribute::SExt)) 1857 Flags.setSExt(); 1858 else if (attr.hasRetAttr(Attribute::ZExt)) 1859 Flags.setZExt(); 1860 1861 for (unsigned i = 0; i < NumParts; ++i) { 1862 ISD::ArgFlagsTy OutFlags = Flags; 1863 if (NumParts > 1 && i == 0) 1864 OutFlags.setSplit(); 1865 else if (i == NumParts - 1 && i != 0) 1866 OutFlags.setSplitEnd(); 1867 1868 Outs.push_back( 1869 ISD::OutputArg(OutFlags, PartVT, VT, /*isfixed=*/true, 0, 0)); 1870 } 1871 } 1872 } 1873 1874 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate 1875 /// function arguments in the caller parameter area. This is the actual 1876 /// alignment, not its logarithm. 1877 uint64_t TargetLoweringBase::getByValTypeAlignment(Type *Ty, 1878 const DataLayout &DL) const { 1879 return DL.getABITypeAlign(Ty).value(); 1880 } 1881 1882 bool TargetLoweringBase::allowsMemoryAccessForAlignment( 1883 LLVMContext &Context, const DataLayout &DL, EVT VT, unsigned AddrSpace, 1884 Align Alignment, MachineMemOperand::Flags Flags, unsigned *Fast) const { 1885 // Check if the specified alignment is sufficient based on the data layout. 1886 // TODO: While using the data layout works in practice, a better solution 1887 // would be to implement this check directly (make this a virtual function). 1888 // For example, the ABI alignment may change based on software platform while 1889 // this function should only be affected by hardware implementation. 1890 Type *Ty = VT.getTypeForEVT(Context); 1891 if (VT.isZeroSized() || Alignment >= DL.getABITypeAlign(Ty)) { 1892 // Assume that an access that meets the ABI-specified alignment is fast. 1893 if (Fast != nullptr) 1894 *Fast = 1; 1895 return true; 1896 } 1897 1898 // This is a misaligned access. 1899 return allowsMisalignedMemoryAccesses(VT, AddrSpace, Alignment, Flags, Fast); 1900 } 1901 1902 bool TargetLoweringBase::allowsMemoryAccessForAlignment( 1903 LLVMContext &Context, const DataLayout &DL, EVT VT, 1904 const MachineMemOperand &MMO, unsigned *Fast) const { 1905 return allowsMemoryAccessForAlignment(Context, DL, VT, MMO.getAddrSpace(), 1906 MMO.getAlign(), MMO.getFlags(), Fast); 1907 } 1908 1909 bool TargetLoweringBase::allowsMemoryAccess(LLVMContext &Context, 1910 const DataLayout &DL, EVT VT, 1911 unsigned AddrSpace, Align Alignment, 1912 MachineMemOperand::Flags Flags, 1913 unsigned *Fast) const { 1914 return allowsMemoryAccessForAlignment(Context, DL, VT, AddrSpace, Alignment, 1915 Flags, Fast); 1916 } 1917 1918 bool TargetLoweringBase::allowsMemoryAccess(LLVMContext &Context, 1919 const DataLayout &DL, EVT VT, 1920 const MachineMemOperand &MMO, 1921 unsigned *Fast) const { 1922 return allowsMemoryAccess(Context, DL, VT, MMO.getAddrSpace(), MMO.getAlign(), 1923 MMO.getFlags(), Fast); 1924 } 1925 1926 bool TargetLoweringBase::allowsMemoryAccess(LLVMContext &Context, 1927 const DataLayout &DL, LLT Ty, 1928 const MachineMemOperand &MMO, 1929 unsigned *Fast) const { 1930 EVT VT = getApproximateEVTForLLT(Ty, DL, Context); 1931 return allowsMemoryAccess(Context, DL, VT, MMO.getAddrSpace(), MMO.getAlign(), 1932 MMO.getFlags(), Fast); 1933 } 1934 1935 //===----------------------------------------------------------------------===// 1936 // TargetTransformInfo Helpers 1937 //===----------------------------------------------------------------------===// 1938 1939 int TargetLoweringBase::InstructionOpcodeToISD(unsigned Opcode) const { 1940 enum InstructionOpcodes { 1941 #define HANDLE_INST(NUM, OPCODE, CLASS) OPCODE = NUM, 1942 #define LAST_OTHER_INST(NUM) InstructionOpcodesCount = NUM 1943 #include "llvm/IR/Instruction.def" 1944 }; 1945 switch (static_cast<InstructionOpcodes>(Opcode)) { 1946 case Ret: return 0; 1947 case Br: return 0; 1948 case Switch: return 0; 1949 case IndirectBr: return 0; 1950 case Invoke: return 0; 1951 case CallBr: return 0; 1952 case Resume: return 0; 1953 case Unreachable: return 0; 1954 case CleanupRet: return 0; 1955 case CatchRet: return 0; 1956 case CatchPad: return 0; 1957 case CatchSwitch: return 0; 1958 case CleanupPad: return 0; 1959 case FNeg: return ISD::FNEG; 1960 case Add: return ISD::ADD; 1961 case FAdd: return ISD::FADD; 1962 case Sub: return ISD::SUB; 1963 case FSub: return ISD::FSUB; 1964 case Mul: return ISD::MUL; 1965 case FMul: return ISD::FMUL; 1966 case UDiv: return ISD::UDIV; 1967 case SDiv: return ISD::SDIV; 1968 case FDiv: return ISD::FDIV; 1969 case URem: return ISD::UREM; 1970 case SRem: return ISD::SREM; 1971 case FRem: return ISD::FREM; 1972 case Shl: return ISD::SHL; 1973 case LShr: return ISD::SRL; 1974 case AShr: return ISD::SRA; 1975 case And: return ISD::AND; 1976 case Or: return ISD::OR; 1977 case Xor: return ISD::XOR; 1978 case Alloca: return 0; 1979 case Load: return ISD::LOAD; 1980 case Store: return ISD::STORE; 1981 case GetElementPtr: return 0; 1982 case Fence: return 0; 1983 case AtomicCmpXchg: return 0; 1984 case AtomicRMW: return 0; 1985 case Trunc: return ISD::TRUNCATE; 1986 case ZExt: return ISD::ZERO_EXTEND; 1987 case SExt: return ISD::SIGN_EXTEND; 1988 case FPToUI: return ISD::FP_TO_UINT; 1989 case FPToSI: return ISD::FP_TO_SINT; 1990 case UIToFP: return ISD::UINT_TO_FP; 1991 case SIToFP: return ISD::SINT_TO_FP; 1992 case FPTrunc: return ISD::FP_ROUND; 1993 case FPExt: return ISD::FP_EXTEND; 1994 case PtrToInt: return ISD::BITCAST; 1995 case IntToPtr: return ISD::BITCAST; 1996 case BitCast: return ISD::BITCAST; 1997 case AddrSpaceCast: return ISD::ADDRSPACECAST; 1998 case ICmp: return ISD::SETCC; 1999 case FCmp: return ISD::SETCC; 2000 case PHI: return 0; 2001 case Call: return 0; 2002 case Select: return ISD::SELECT; 2003 case UserOp1: return 0; 2004 case UserOp2: return 0; 2005 case VAArg: return 0; 2006 case ExtractElement: return ISD::EXTRACT_VECTOR_ELT; 2007 case InsertElement: return ISD::INSERT_VECTOR_ELT; 2008 case ShuffleVector: return ISD::VECTOR_SHUFFLE; 2009 case ExtractValue: return ISD::MERGE_VALUES; 2010 case InsertValue: return ISD::MERGE_VALUES; 2011 case LandingPad: return 0; 2012 case Freeze: return ISD::FREEZE; 2013 } 2014 2015 llvm_unreachable("Unknown instruction type encountered!"); 2016 } 2017 2018 Value * 2019 TargetLoweringBase::getDefaultSafeStackPointerLocation(IRBuilderBase &IRB, 2020 bool UseTLS) const { 2021 // compiler-rt provides a variable with a magic name. Targets that do not 2022 // link with compiler-rt may also provide such a variable. 2023 Module *M = IRB.GetInsertBlock()->getParent()->getParent(); 2024 const char *UnsafeStackPtrVar = "__safestack_unsafe_stack_ptr"; 2025 auto UnsafeStackPtr = 2026 dyn_cast_or_null<GlobalVariable>(M->getNamedValue(UnsafeStackPtrVar)); 2027 2028 Type *StackPtrTy = PointerType::getUnqual(M->getContext()); 2029 2030 if (!UnsafeStackPtr) { 2031 auto TLSModel = UseTLS ? 2032 GlobalValue::InitialExecTLSModel : 2033 GlobalValue::NotThreadLocal; 2034 // The global variable is not defined yet, define it ourselves. 2035 // We use the initial-exec TLS model because we do not support the 2036 // variable living anywhere other than in the main executable. 2037 UnsafeStackPtr = new GlobalVariable( 2038 *M, StackPtrTy, false, GlobalValue::ExternalLinkage, nullptr, 2039 UnsafeStackPtrVar, nullptr, TLSModel); 2040 } else { 2041 // The variable exists, check its type and attributes. 2042 if (UnsafeStackPtr->getValueType() != StackPtrTy) 2043 report_fatal_error(Twine(UnsafeStackPtrVar) + " must have void* type"); 2044 if (UseTLS != UnsafeStackPtr->isThreadLocal()) 2045 report_fatal_error(Twine(UnsafeStackPtrVar) + " must " + 2046 (UseTLS ? "" : "not ") + "be thread-local"); 2047 } 2048 return UnsafeStackPtr; 2049 } 2050 2051 Value * 2052 TargetLoweringBase::getSafeStackPointerLocation(IRBuilderBase &IRB) const { 2053 if (!TM.getTargetTriple().isAndroid()) 2054 return getDefaultSafeStackPointerLocation(IRB, true); 2055 2056 // Android provides a libc function to retrieve the address of the current 2057 // thread's unsafe stack pointer. 2058 Module *M = IRB.GetInsertBlock()->getParent()->getParent(); 2059 auto *PtrTy = PointerType::getUnqual(M->getContext()); 2060 FunctionCallee Fn = 2061 M->getOrInsertFunction("__safestack_pointer_address", PtrTy); 2062 return IRB.CreateCall(Fn); 2063 } 2064 2065 //===----------------------------------------------------------------------===// 2066 // Loop Strength Reduction hooks 2067 //===----------------------------------------------------------------------===// 2068 2069 /// isLegalAddressingMode - Return true if the addressing mode represented 2070 /// by AM is legal for this target, for a load/store of the specified type. 2071 bool TargetLoweringBase::isLegalAddressingMode(const DataLayout &DL, 2072 const AddrMode &AM, Type *Ty, 2073 unsigned AS, Instruction *I) const { 2074 // The default implementation of this implements a conservative RISCy, r+r and 2075 // r+i addr mode. 2076 2077 // Scalable offsets not supported 2078 if (AM.ScalableOffset) 2079 return false; 2080 2081 // Allows a sign-extended 16-bit immediate field. 2082 if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1) 2083 return false; 2084 2085 // No global is ever allowed as a base. 2086 if (AM.BaseGV) 2087 return false; 2088 2089 // Only support r+r, 2090 switch (AM.Scale) { 2091 case 0: // "r+i" or just "i", depending on HasBaseReg. 2092 break; 2093 case 1: 2094 if (AM.HasBaseReg && AM.BaseOffs) // "r+r+i" is not allowed. 2095 return false; 2096 // Otherwise we have r+r or r+i. 2097 break; 2098 case 2: 2099 if (AM.HasBaseReg || AM.BaseOffs) // 2*r+r or 2*r+i is not allowed. 2100 return false; 2101 // Allow 2*r as r+r. 2102 break; 2103 default: // Don't allow n * r 2104 return false; 2105 } 2106 2107 return true; 2108 } 2109 2110 //===----------------------------------------------------------------------===// 2111 // Stack Protector 2112 //===----------------------------------------------------------------------===// 2113 2114 // For OpenBSD return its special guard variable. Otherwise return nullptr, 2115 // so that SelectionDAG handle SSP. 2116 Value *TargetLoweringBase::getIRStackGuard(IRBuilderBase &IRB) const { 2117 if (getTargetMachine().getTargetTriple().isOSOpenBSD()) { 2118 Module &M = *IRB.GetInsertBlock()->getParent()->getParent(); 2119 PointerType *PtrTy = PointerType::getUnqual(M.getContext()); 2120 Constant *C = M.getOrInsertGlobal("__guard_local", PtrTy); 2121 if (GlobalVariable *G = dyn_cast_or_null<GlobalVariable>(C)) 2122 G->setVisibility(GlobalValue::HiddenVisibility); 2123 return C; 2124 } 2125 return nullptr; 2126 } 2127 2128 // Currently only support "standard" __stack_chk_guard. 2129 // TODO: add LOAD_STACK_GUARD support. 2130 void TargetLoweringBase::insertSSPDeclarations(Module &M) const { 2131 if (!M.getNamedValue("__stack_chk_guard")) { 2132 auto *GV = new GlobalVariable(M, PointerType::getUnqual(M.getContext()), 2133 false, GlobalVariable::ExternalLinkage, 2134 nullptr, "__stack_chk_guard"); 2135 2136 // FreeBSD has "__stack_chk_guard" defined externally on libc.so 2137 if (M.getDirectAccessExternalData() && 2138 !TM.getTargetTriple().isWindowsGNUEnvironment() && 2139 !(TM.getTargetTriple().isPPC64() && 2140 TM.getTargetTriple().isOSFreeBSD()) && 2141 (!TM.getTargetTriple().isOSDarwin() || 2142 TM.getRelocationModel() == Reloc::Static)) 2143 GV->setDSOLocal(true); 2144 } 2145 } 2146 2147 // Currently only support "standard" __stack_chk_guard. 2148 // TODO: add LOAD_STACK_GUARD support. 2149 Value *TargetLoweringBase::getSDagStackGuard(const Module &M) const { 2150 return M.getNamedValue("__stack_chk_guard"); 2151 } 2152 2153 Function *TargetLoweringBase::getSSPStackGuardCheck(const Module &M) const { 2154 return nullptr; 2155 } 2156 2157 unsigned TargetLoweringBase::getMinimumJumpTableEntries() const { 2158 return MinimumJumpTableEntries; 2159 } 2160 2161 void TargetLoweringBase::setMinimumJumpTableEntries(unsigned Val) { 2162 MinimumJumpTableEntries = Val; 2163 } 2164 2165 unsigned TargetLoweringBase::getMinimumJumpTableDensity(bool OptForSize) const { 2166 return OptForSize ? OptsizeJumpTableDensity : JumpTableDensity; 2167 } 2168 2169 unsigned TargetLoweringBase::getMaximumJumpTableSize() const { 2170 return MaximumJumpTableSize; 2171 } 2172 2173 void TargetLoweringBase::setMaximumJumpTableSize(unsigned Val) { 2174 MaximumJumpTableSize = Val; 2175 } 2176 2177 bool TargetLoweringBase::isJumpTableRelative() const { 2178 return getTargetMachine().isPositionIndependent(); 2179 } 2180 2181 Align TargetLoweringBase::getPrefLoopAlignment(MachineLoop *ML) const { 2182 if (TM.Options.LoopAlignment) 2183 return Align(TM.Options.LoopAlignment); 2184 return PrefLoopAlignment; 2185 } 2186 2187 unsigned TargetLoweringBase::getMaxPermittedBytesForAlignment( 2188 MachineBasicBlock *MBB) const { 2189 return MaxBytesForAlignment; 2190 } 2191 2192 //===----------------------------------------------------------------------===// 2193 // Reciprocal Estimates 2194 //===----------------------------------------------------------------------===// 2195 2196 /// Get the reciprocal estimate attribute string for a function that will 2197 /// override the target defaults. 2198 static StringRef getRecipEstimateForFunc(MachineFunction &MF) { 2199 const Function &F = MF.getFunction(); 2200 return F.getFnAttribute("reciprocal-estimates").getValueAsString(); 2201 } 2202 2203 /// Construct a string for the given reciprocal operation of the given type. 2204 /// This string should match the corresponding option to the front-end's 2205 /// "-mrecip" flag assuming those strings have been passed through in an 2206 /// attribute string. For example, "vec-divf" for a division of a vXf32. 2207 static std::string getReciprocalOpName(bool IsSqrt, EVT VT) { 2208 std::string Name = VT.isVector() ? "vec-" : ""; 2209 2210 Name += IsSqrt ? "sqrt" : "div"; 2211 2212 // TODO: Handle other float types? 2213 if (VT.getScalarType() == MVT::f64) { 2214 Name += "d"; 2215 } else if (VT.getScalarType() == MVT::f16) { 2216 Name += "h"; 2217 } else { 2218 assert(VT.getScalarType() == MVT::f32 && 2219 "Unexpected FP type for reciprocal estimate"); 2220 Name += "f"; 2221 } 2222 2223 return Name; 2224 } 2225 2226 /// Return the character position and value (a single numeric character) of a 2227 /// customized refinement operation in the input string if it exists. Return 2228 /// false if there is no customized refinement step count. 2229 static bool parseRefinementStep(StringRef In, size_t &Position, 2230 uint8_t &Value) { 2231 const char RefStepToken = ':'; 2232 Position = In.find(RefStepToken); 2233 if (Position == StringRef::npos) 2234 return false; 2235 2236 StringRef RefStepString = In.substr(Position + 1); 2237 // Allow exactly one numeric character for the additional refinement 2238 // step parameter. 2239 if (RefStepString.size() == 1) { 2240 char RefStepChar = RefStepString[0]; 2241 if (isDigit(RefStepChar)) { 2242 Value = RefStepChar - '0'; 2243 return true; 2244 } 2245 } 2246 report_fatal_error("Invalid refinement step for -recip."); 2247 } 2248 2249 /// For the input attribute string, return one of the ReciprocalEstimate enum 2250 /// status values (enabled, disabled, or not specified) for this operation on 2251 /// the specified data type. 2252 static int getOpEnabled(bool IsSqrt, EVT VT, StringRef Override) { 2253 if (Override.empty()) 2254 return TargetLoweringBase::ReciprocalEstimate::Unspecified; 2255 2256 SmallVector<StringRef, 4> OverrideVector; 2257 Override.split(OverrideVector, ','); 2258 unsigned NumArgs = OverrideVector.size(); 2259 2260 // Check if "all", "none", or "default" was specified. 2261 if (NumArgs == 1) { 2262 // Look for an optional setting of the number of refinement steps needed 2263 // for this type of reciprocal operation. 2264 size_t RefPos; 2265 uint8_t RefSteps; 2266 if (parseRefinementStep(Override, RefPos, RefSteps)) { 2267 // Split the string for further processing. 2268 Override = Override.substr(0, RefPos); 2269 } 2270 2271 // All reciprocal types are enabled. 2272 if (Override == "all") 2273 return TargetLoweringBase::ReciprocalEstimate::Enabled; 2274 2275 // All reciprocal types are disabled. 2276 if (Override == "none") 2277 return TargetLoweringBase::ReciprocalEstimate::Disabled; 2278 2279 // Target defaults for enablement are used. 2280 if (Override == "default") 2281 return TargetLoweringBase::ReciprocalEstimate::Unspecified; 2282 } 2283 2284 // The attribute string may omit the size suffix ('f'/'d'). 2285 std::string VTName = getReciprocalOpName(IsSqrt, VT); 2286 std::string VTNameNoSize = VTName; 2287 VTNameNoSize.pop_back(); 2288 static const char DisabledPrefix = '!'; 2289 2290 for (StringRef RecipType : OverrideVector) { 2291 size_t RefPos; 2292 uint8_t RefSteps; 2293 if (parseRefinementStep(RecipType, RefPos, RefSteps)) 2294 RecipType = RecipType.substr(0, RefPos); 2295 2296 // Ignore the disablement token for string matching. 2297 bool IsDisabled = RecipType[0] == DisabledPrefix; 2298 if (IsDisabled) 2299 RecipType = RecipType.substr(1); 2300 2301 if (RecipType == VTName || RecipType == VTNameNoSize) 2302 return IsDisabled ? TargetLoweringBase::ReciprocalEstimate::Disabled 2303 : TargetLoweringBase::ReciprocalEstimate::Enabled; 2304 } 2305 2306 return TargetLoweringBase::ReciprocalEstimate::Unspecified; 2307 } 2308 2309 /// For the input attribute string, return the customized refinement step count 2310 /// for this operation on the specified data type. If the step count does not 2311 /// exist, return the ReciprocalEstimate enum value for unspecified. 2312 static int getOpRefinementSteps(bool IsSqrt, EVT VT, StringRef Override) { 2313 if (Override.empty()) 2314 return TargetLoweringBase::ReciprocalEstimate::Unspecified; 2315 2316 SmallVector<StringRef, 4> OverrideVector; 2317 Override.split(OverrideVector, ','); 2318 unsigned NumArgs = OverrideVector.size(); 2319 2320 // Check if "all", "default", or "none" was specified. 2321 if (NumArgs == 1) { 2322 // Look for an optional setting of the number of refinement steps needed 2323 // for this type of reciprocal operation. 2324 size_t RefPos; 2325 uint8_t RefSteps; 2326 if (!parseRefinementStep(Override, RefPos, RefSteps)) 2327 return TargetLoweringBase::ReciprocalEstimate::Unspecified; 2328 2329 // Split the string for further processing. 2330 Override = Override.substr(0, RefPos); 2331 assert(Override != "none" && 2332 "Disabled reciprocals, but specifed refinement steps?"); 2333 2334 // If this is a general override, return the specified number of steps. 2335 if (Override == "all" || Override == "default") 2336 return RefSteps; 2337 } 2338 2339 // The attribute string may omit the size suffix ('f'/'d'). 2340 std::string VTName = getReciprocalOpName(IsSqrt, VT); 2341 std::string VTNameNoSize = VTName; 2342 VTNameNoSize.pop_back(); 2343 2344 for (StringRef RecipType : OverrideVector) { 2345 size_t RefPos; 2346 uint8_t RefSteps; 2347 if (!parseRefinementStep(RecipType, RefPos, RefSteps)) 2348 continue; 2349 2350 RecipType = RecipType.substr(0, RefPos); 2351 if (RecipType == VTName || RecipType == VTNameNoSize) 2352 return RefSteps; 2353 } 2354 2355 return TargetLoweringBase::ReciprocalEstimate::Unspecified; 2356 } 2357 2358 int TargetLoweringBase::getRecipEstimateSqrtEnabled(EVT VT, 2359 MachineFunction &MF) const { 2360 return getOpEnabled(true, VT, getRecipEstimateForFunc(MF)); 2361 } 2362 2363 int TargetLoweringBase::getRecipEstimateDivEnabled(EVT VT, 2364 MachineFunction &MF) const { 2365 return getOpEnabled(false, VT, getRecipEstimateForFunc(MF)); 2366 } 2367 2368 int TargetLoweringBase::getSqrtRefinementSteps(EVT VT, 2369 MachineFunction &MF) const { 2370 return getOpRefinementSteps(true, VT, getRecipEstimateForFunc(MF)); 2371 } 2372 2373 int TargetLoweringBase::getDivRefinementSteps(EVT VT, 2374 MachineFunction &MF) const { 2375 return getOpRefinementSteps(false, VT, getRecipEstimateForFunc(MF)); 2376 } 2377 2378 bool TargetLoweringBase::isLoadBitCastBeneficial( 2379 EVT LoadVT, EVT BitcastVT, const SelectionDAG &DAG, 2380 const MachineMemOperand &MMO) const { 2381 // Single-element vectors are scalarized, so we should generally avoid having 2382 // any memory operations on such types, as they would get scalarized too. 2383 if (LoadVT.isFixedLengthVector() && BitcastVT.isFixedLengthVector() && 2384 BitcastVT.getVectorNumElements() == 1) 2385 return false; 2386 2387 // Don't do if we could do an indexed load on the original type, but not on 2388 // the new one. 2389 if (!LoadVT.isSimple() || !BitcastVT.isSimple()) 2390 return true; 2391 2392 MVT LoadMVT = LoadVT.getSimpleVT(); 2393 2394 // Don't bother doing this if it's just going to be promoted again later, as 2395 // doing so might interfere with other combines. 2396 if (getOperationAction(ISD::LOAD, LoadMVT) == Promote && 2397 getTypeToPromoteTo(ISD::LOAD, LoadMVT) == BitcastVT.getSimpleVT()) 2398 return false; 2399 2400 unsigned Fast = 0; 2401 return allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), BitcastVT, 2402 MMO, &Fast) && 2403 Fast; 2404 } 2405 2406 void TargetLoweringBase::finalizeLowering(MachineFunction &MF) const { 2407 MF.getRegInfo().freezeReservedRegs(); 2408 } 2409 2410 MachineMemOperand::Flags TargetLoweringBase::getLoadMemOperandFlags( 2411 const LoadInst &LI, const DataLayout &DL, AssumptionCache *AC, 2412 const TargetLibraryInfo *LibInfo) const { 2413 MachineMemOperand::Flags Flags = MachineMemOperand::MOLoad; 2414 if (LI.isVolatile()) 2415 Flags |= MachineMemOperand::MOVolatile; 2416 2417 if (LI.hasMetadata(LLVMContext::MD_nontemporal)) 2418 Flags |= MachineMemOperand::MONonTemporal; 2419 2420 if (LI.hasMetadata(LLVMContext::MD_invariant_load)) 2421 Flags |= MachineMemOperand::MOInvariant; 2422 2423 if (isDereferenceableAndAlignedPointer(LI.getPointerOperand(), LI.getType(), 2424 LI.getAlign(), DL, &LI, AC, 2425 /*DT=*/nullptr, LibInfo)) 2426 Flags |= MachineMemOperand::MODereferenceable; 2427 2428 Flags |= getTargetMMOFlags(LI); 2429 return Flags; 2430 } 2431 2432 MachineMemOperand::Flags 2433 TargetLoweringBase::getStoreMemOperandFlags(const StoreInst &SI, 2434 const DataLayout &DL) const { 2435 MachineMemOperand::Flags Flags = MachineMemOperand::MOStore; 2436 2437 if (SI.isVolatile()) 2438 Flags |= MachineMemOperand::MOVolatile; 2439 2440 if (SI.hasMetadata(LLVMContext::MD_nontemporal)) 2441 Flags |= MachineMemOperand::MONonTemporal; 2442 2443 // FIXME: Not preserving dereferenceable 2444 Flags |= getTargetMMOFlags(SI); 2445 return Flags; 2446 } 2447 2448 MachineMemOperand::Flags 2449 TargetLoweringBase::getAtomicMemOperandFlags(const Instruction &AI, 2450 const DataLayout &DL) const { 2451 auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 2452 2453 if (const AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(&AI)) { 2454 if (RMW->isVolatile()) 2455 Flags |= MachineMemOperand::MOVolatile; 2456 } else if (const AtomicCmpXchgInst *CmpX = dyn_cast<AtomicCmpXchgInst>(&AI)) { 2457 if (CmpX->isVolatile()) 2458 Flags |= MachineMemOperand::MOVolatile; 2459 } else 2460 llvm_unreachable("not an atomic instruction"); 2461 2462 // FIXME: Not preserving dereferenceable 2463 Flags |= getTargetMMOFlags(AI); 2464 return Flags; 2465 } 2466 2467 Instruction *TargetLoweringBase::emitLeadingFence(IRBuilderBase &Builder, 2468 Instruction *Inst, 2469 AtomicOrdering Ord) const { 2470 if (isReleaseOrStronger(Ord) && Inst->hasAtomicStore()) 2471 return Builder.CreateFence(Ord); 2472 else 2473 return nullptr; 2474 } 2475 2476 Instruction *TargetLoweringBase::emitTrailingFence(IRBuilderBase &Builder, 2477 Instruction *Inst, 2478 AtomicOrdering Ord) const { 2479 if (isAcquireOrStronger(Ord)) 2480 return Builder.CreateFence(Ord); 2481 else 2482 return nullptr; 2483 } 2484 2485 //===----------------------------------------------------------------------===// 2486 // GlobalISel Hooks 2487 //===----------------------------------------------------------------------===// 2488 2489 bool TargetLoweringBase::shouldLocalize(const MachineInstr &MI, 2490 const TargetTransformInfo *TTI) const { 2491 auto &MF = *MI.getMF(); 2492 auto &MRI = MF.getRegInfo(); 2493 // Assuming a spill and reload of a value has a cost of 1 instruction each, 2494 // this helper function computes the maximum number of uses we should consider 2495 // for remat. E.g. on arm64 global addresses take 2 insts to materialize. We 2496 // break even in terms of code size when the original MI has 2 users vs 2497 // choosing to potentially spill. Any more than 2 users we we have a net code 2498 // size increase. This doesn't take into account register pressure though. 2499 auto maxUses = [](unsigned RematCost) { 2500 // A cost of 1 means remats are basically free. 2501 if (RematCost == 1) 2502 return std::numeric_limits<unsigned>::max(); 2503 if (RematCost == 2) 2504 return 2U; 2505 2506 // Remat is too expensive, only sink if there's one user. 2507 if (RematCost > 2) 2508 return 1U; 2509 llvm_unreachable("Unexpected remat cost"); 2510 }; 2511 2512 switch (MI.getOpcode()) { 2513 default: 2514 return false; 2515 // Constants-like instructions should be close to their users. 2516 // We don't want long live-ranges for them. 2517 case TargetOpcode::G_CONSTANT: 2518 case TargetOpcode::G_FCONSTANT: 2519 case TargetOpcode::G_FRAME_INDEX: 2520 case TargetOpcode::G_INTTOPTR: 2521 return true; 2522 case TargetOpcode::G_GLOBAL_VALUE: { 2523 unsigned RematCost = TTI->getGISelRematGlobalCost(); 2524 Register Reg = MI.getOperand(0).getReg(); 2525 unsigned MaxUses = maxUses(RematCost); 2526 if (MaxUses == UINT_MAX) 2527 return true; // Remats are "free" so always localize. 2528 return MRI.hasAtMostUserInstrs(Reg, MaxUses); 2529 } 2530 } 2531 } 2532