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