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