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