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::FMAD, ISD::SMIN, 717 ISD::SMAX, ISD::UMIN, 718 ISD::UMAX, ISD::ABS, 719 ISD::FSHL, ISD::FSHR, 720 ISD::SADDSAT, ISD::UADDSAT, 721 ISD::SSUBSAT, ISD::USUBSAT, 722 ISD::SSHLSAT, ISD::USHLSAT, 723 ISD::SMULFIX, ISD::SMULFIXSAT, 724 ISD::UMULFIX, ISD::UMULFIXSAT, 725 ISD::SDIVFIX, ISD::SDIVFIXSAT, 726 ISD::UDIVFIX, ISD::UDIVFIXSAT, 727 ISD::FP_TO_SINT_SAT, ISD::FP_TO_UINT_SAT, 728 ISD::IS_FPCLASS}, 729 VT, Expand); 730 731 // Overflow operations default to expand 732 setOperationAction({ISD::SADDO, ISD::SSUBO, ISD::UADDO, ISD::USUBO, 733 ISD::SMULO, ISD::UMULO}, 734 VT, Expand); 735 736 // Carry-using overflow operations default to expand. 737 setOperationAction({ISD::UADDO_CARRY, ISD::USUBO_CARRY, ISD::SETCCCARRY, 738 ISD::SADDO_CARRY, ISD::SSUBO_CARRY}, 739 VT, Expand); 740 741 // ADDC/ADDE/SUBC/SUBE default to expand. 742 setOperationAction({ISD::ADDC, ISD::ADDE, ISD::SUBC, ISD::SUBE}, VT, 743 Expand); 744 745 // [US]CMP default to expand 746 setOperationAction({ISD::UCMP, ISD::SCMP}, VT, Expand); 747 748 // Halving adds 749 setOperationAction( 750 {ISD::AVGFLOORS, ISD::AVGFLOORU, ISD::AVGCEILS, ISD::AVGCEILU}, VT, 751 Expand); 752 753 // Absolute difference 754 setOperationAction({ISD::ABDS, ISD::ABDU}, VT, Expand); 755 756 // These default to Expand so they will be expanded to CTLZ/CTTZ by default. 757 setOperationAction({ISD::CTLZ_ZERO_UNDEF, ISD::CTTZ_ZERO_UNDEF}, VT, 758 Expand); 759 760 setOperationAction({ISD::BITREVERSE, ISD::PARITY}, VT, Expand); 761 762 // These library functions default to expand. 763 setOperationAction({ISD::FROUND, ISD::FPOWI, ISD::FLDEXP, ISD::FFREXP}, VT, 764 Expand); 765 766 // These operations default to expand for vector types. 767 if (VT.isVector()) 768 setOperationAction( 769 {ISD::FCOPYSIGN, ISD::SIGN_EXTEND_INREG, ISD::ANY_EXTEND_VECTOR_INREG, 770 ISD::SIGN_EXTEND_VECTOR_INREG, ISD::ZERO_EXTEND_VECTOR_INREG, 771 ISD::SPLAT_VECTOR, ISD::LRINT, ISD::LLRINT, ISD::FTAN, ISD::FACOS, 772 ISD::FASIN, ISD::FATAN, ISD::FCOSH, ISD::FSINH, ISD::FTANH}, 773 VT, Expand); 774 775 // Constrained floating-point operations default to expand. 776 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \ 777 setOperationAction(ISD::STRICT_##DAGN, VT, Expand); 778 #include "llvm/IR/ConstrainedOps.def" 779 780 // For most targets @llvm.get.dynamic.area.offset just returns 0. 781 setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, VT, Expand); 782 783 // Vector reduction default to expand. 784 setOperationAction( 785 {ISD::VECREDUCE_FADD, ISD::VECREDUCE_FMUL, ISD::VECREDUCE_ADD, 786 ISD::VECREDUCE_MUL, ISD::VECREDUCE_AND, ISD::VECREDUCE_OR, 787 ISD::VECREDUCE_XOR, ISD::VECREDUCE_SMAX, ISD::VECREDUCE_SMIN, 788 ISD::VECREDUCE_UMAX, ISD::VECREDUCE_UMIN, ISD::VECREDUCE_FMAX, 789 ISD::VECREDUCE_FMIN, ISD::VECREDUCE_FMAXIMUM, ISD::VECREDUCE_FMINIMUM, 790 ISD::VECREDUCE_SEQ_FADD, ISD::VECREDUCE_SEQ_FMUL}, 791 VT, Expand); 792 793 // Named vector shuffles default to expand. 794 setOperationAction(ISD::VECTOR_SPLICE, VT, Expand); 795 796 // Only some target support this vector operation. Most need to expand it. 797 setOperationAction(ISD::VECTOR_COMPRESS, VT, Expand); 798 799 // VP operations default to expand. 800 #define BEGIN_REGISTER_VP_SDNODE(SDOPC, ...) \ 801 setOperationAction(ISD::SDOPC, VT, Expand); 802 #include "llvm/IR/VPIntrinsics.def" 803 804 // FP environment operations default to expand. 805 setOperationAction(ISD::GET_FPENV, VT, Expand); 806 setOperationAction(ISD::SET_FPENV, VT, Expand); 807 setOperationAction(ISD::RESET_FPENV, VT, Expand); 808 } 809 810 // Most targets ignore the @llvm.prefetch intrinsic. 811 setOperationAction(ISD::PREFETCH, MVT::Other, Expand); 812 813 // Most targets also ignore the @llvm.readcyclecounter intrinsic. 814 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Expand); 815 816 // Most targets also ignore the @llvm.readsteadycounter intrinsic. 817 setOperationAction(ISD::READSTEADYCOUNTER, MVT::i64, Expand); 818 819 // ConstantFP nodes default to expand. Targets can either change this to 820 // Legal, in which case all fp constants are legal, or use isFPImmLegal() 821 // to optimize expansions for certain constants. 822 setOperationAction(ISD::ConstantFP, 823 {MVT::bf16, MVT::f16, MVT::f32, MVT::f64, MVT::f80, MVT::f128}, 824 Expand); 825 826 // These library functions default to expand. 827 setOperationAction({ISD::FCBRT, ISD::FLOG, ISD::FLOG2, ISD::FLOG10, 828 ISD::FEXP, ISD::FEXP2, ISD::FEXP10, ISD::FFLOOR, 829 ISD::FNEARBYINT, ISD::FCEIL, ISD::FRINT, ISD::FTRUNC, 830 ISD::FROUNDEVEN, ISD::FTAN, ISD::FACOS, ISD::FASIN, 831 ISD::FATAN, ISD::FCOSH, ISD::FSINH, ISD::FTANH}, 832 {MVT::f32, MVT::f64, MVT::f128}, Expand); 833 834 // FIXME: Query RuntimeLibCalls to make the decision. 835 setOperationAction({ISD::LRINT, ISD::LLRINT, ISD::LROUND, ISD::LLROUND}, 836 {MVT::f32, MVT::f64, MVT::f128}, LibCall); 837 838 setOperationAction({ISD::FTAN, ISD::FACOS, ISD::FASIN, ISD::FATAN, ISD::FCOSH, 839 ISD::FSINH, ISD::FTANH}, 840 MVT::f16, Promote); 841 // Default ISD::TRAP to expand (which turns it into abort). 842 setOperationAction(ISD::TRAP, MVT::Other, Expand); 843 844 // On most systems, DEBUGTRAP and TRAP have no difference. The "Expand" 845 // here is to inform DAG Legalizer to replace DEBUGTRAP with TRAP. 846 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Expand); 847 848 setOperationAction(ISD::UBSANTRAP, MVT::Other, Expand); 849 850 setOperationAction(ISD::GET_FPENV_MEM, MVT::Other, Expand); 851 setOperationAction(ISD::SET_FPENV_MEM, MVT::Other, Expand); 852 853 for (MVT VT : {MVT::i8, MVT::i16, MVT::i32, MVT::i64}) { 854 setOperationAction(ISD::GET_FPMODE, VT, Expand); 855 setOperationAction(ISD::SET_FPMODE, VT, Expand); 856 } 857 setOperationAction(ISD::RESET_FPMODE, MVT::Other, Expand); 858 859 // This one by default will call __clear_cache unless the target 860 // wants something different. 861 setOperationAction(ISD::CLEAR_CACHE, MVT::Other, LibCall); 862 } 863 864 MVT TargetLoweringBase::getScalarShiftAmountTy(const DataLayout &DL, 865 EVT) const { 866 return MVT::getIntegerVT(DL.getPointerSizeInBits(0)); 867 } 868 869 EVT TargetLoweringBase::getShiftAmountTy(EVT LHSTy, 870 const DataLayout &DL) const { 871 assert(LHSTy.isInteger() && "Shift amount is not an integer type!"); 872 if (LHSTy.isVector()) 873 return LHSTy; 874 MVT ShiftVT = getScalarShiftAmountTy(DL, LHSTy); 875 // If any possible shift value won't fit in the prefered type, just use 876 // something safe. Assume it will be legalized when the shift is expanded. 877 if (ShiftVT.getSizeInBits() < Log2_32_Ceil(LHSTy.getSizeInBits())) 878 ShiftVT = MVT::i32; 879 assert(ShiftVT.getSizeInBits() >= Log2_32_Ceil(LHSTy.getSizeInBits()) && 880 "ShiftVT is still too small!"); 881 return ShiftVT; 882 } 883 884 bool TargetLoweringBase::canOpTrap(unsigned Op, EVT VT) const { 885 assert(isTypeLegal(VT)); 886 switch (Op) { 887 default: 888 return false; 889 case ISD::SDIV: 890 case ISD::UDIV: 891 case ISD::SREM: 892 case ISD::UREM: 893 return true; 894 } 895 } 896 897 bool TargetLoweringBase::isFreeAddrSpaceCast(unsigned SrcAS, 898 unsigned DestAS) const { 899 return TM.isNoopAddrSpaceCast(SrcAS, DestAS); 900 } 901 902 unsigned TargetLoweringBase::getBitWidthForCttzElements( 903 Type *RetTy, ElementCount EC, bool ZeroIsPoison, 904 const ConstantRange *VScaleRange) const { 905 // Find the smallest "sensible" element type to use for the expansion. 906 ConstantRange CR(APInt(64, EC.getKnownMinValue())); 907 if (EC.isScalable()) 908 CR = CR.umul_sat(*VScaleRange); 909 910 if (ZeroIsPoison) 911 CR = CR.subtract(APInt(64, 1)); 912 913 unsigned EltWidth = RetTy->getScalarSizeInBits(); 914 EltWidth = std::min(EltWidth, (unsigned)CR.getActiveBits()); 915 EltWidth = std::max(llvm::bit_ceil(EltWidth), (unsigned)8); 916 917 return EltWidth; 918 } 919 920 void TargetLoweringBase::setJumpIsExpensive(bool isExpensive) { 921 // If the command-line option was specified, ignore this request. 922 if (!JumpIsExpensiveOverride.getNumOccurrences()) 923 JumpIsExpensive = isExpensive; 924 } 925 926 TargetLoweringBase::LegalizeKind 927 TargetLoweringBase::getTypeConversion(LLVMContext &Context, EVT VT) const { 928 // If this is a simple type, use the ComputeRegisterProp mechanism. 929 if (VT.isSimple()) { 930 MVT SVT = VT.getSimpleVT(); 931 assert((unsigned)SVT.SimpleTy < std::size(TransformToType)); 932 MVT NVT = TransformToType[SVT.SimpleTy]; 933 LegalizeTypeAction LA = ValueTypeActions.getTypeAction(SVT); 934 935 assert((LA == TypeLegal || LA == TypeSoftenFloat || 936 LA == TypeSoftPromoteHalf || 937 (NVT.isVector() || 938 ValueTypeActions.getTypeAction(NVT) != TypePromoteInteger)) && 939 "Promote may not follow Expand or Promote"); 940 941 if (LA == TypeSplitVector) 942 return LegalizeKind(LA, EVT(SVT).getHalfNumVectorElementsVT(Context)); 943 if (LA == TypeScalarizeVector) 944 return LegalizeKind(LA, SVT.getVectorElementType()); 945 return LegalizeKind(LA, NVT); 946 } 947 948 // Handle Extended Scalar Types. 949 if (!VT.isVector()) { 950 assert(VT.isInteger() && "Float types must be simple"); 951 unsigned BitSize = VT.getSizeInBits(); 952 // First promote to a power-of-two size, then expand if necessary. 953 if (BitSize < 8 || !isPowerOf2_32(BitSize)) { 954 EVT NVT = VT.getRoundIntegerType(Context); 955 assert(NVT != VT && "Unable to round integer VT"); 956 LegalizeKind NextStep = getTypeConversion(Context, NVT); 957 // Avoid multi-step promotion. 958 if (NextStep.first == TypePromoteInteger) 959 return NextStep; 960 // Return rounded integer type. 961 return LegalizeKind(TypePromoteInteger, NVT); 962 } 963 964 return LegalizeKind(TypeExpandInteger, 965 EVT::getIntegerVT(Context, VT.getSizeInBits() / 2)); 966 } 967 968 // Handle vector types. 969 ElementCount NumElts = VT.getVectorElementCount(); 970 EVT EltVT = VT.getVectorElementType(); 971 972 // Vectors with only one element are always scalarized. 973 if (NumElts.isScalar()) 974 return LegalizeKind(TypeScalarizeVector, EltVT); 975 976 // Try to widen vector elements until the element type is a power of two and 977 // promote it to a legal type later on, for example: 978 // <3 x i8> -> <4 x i8> -> <4 x i32> 979 if (EltVT.isInteger()) { 980 // Vectors with a number of elements that is not a power of two are always 981 // widened, for example <3 x i8> -> <4 x i8>. 982 if (!VT.isPow2VectorType()) { 983 NumElts = NumElts.coefficientNextPowerOf2(); 984 EVT NVT = EVT::getVectorVT(Context, EltVT, NumElts); 985 return LegalizeKind(TypeWidenVector, NVT); 986 } 987 988 // Examine the element type. 989 LegalizeKind LK = getTypeConversion(Context, EltVT); 990 991 // If type is to be expanded, split the vector. 992 // <4 x i140> -> <2 x i140> 993 if (LK.first == TypeExpandInteger) { 994 if (VT.getVectorElementCount().isScalable()) 995 return LegalizeKind(TypeScalarizeScalableVector, EltVT); 996 return LegalizeKind(TypeSplitVector, 997 VT.getHalfNumVectorElementsVT(Context)); 998 } 999 1000 // Promote the integer element types until a legal vector type is found 1001 // or until the element integer type is too big. If a legal type was not 1002 // found, fallback to the usual mechanism of widening/splitting the 1003 // vector. 1004 EVT OldEltVT = EltVT; 1005 while (true) { 1006 // Increase the bitwidth of the element to the next pow-of-two 1007 // (which is greater than 8 bits). 1008 EltVT = EVT::getIntegerVT(Context, 1 + EltVT.getSizeInBits()) 1009 .getRoundIntegerType(Context); 1010 1011 // Stop trying when getting a non-simple element type. 1012 // Note that vector elements may be greater than legal vector element 1013 // types. Example: X86 XMM registers hold 64bit element on 32bit 1014 // systems. 1015 if (!EltVT.isSimple()) 1016 break; 1017 1018 // Build a new vector type and check if it is legal. 1019 MVT NVT = MVT::getVectorVT(EltVT.getSimpleVT(), NumElts); 1020 // Found a legal promoted vector type. 1021 if (NVT != MVT() && ValueTypeActions.getTypeAction(NVT) == TypeLegal) 1022 return LegalizeKind(TypePromoteInteger, 1023 EVT::getVectorVT(Context, EltVT, NumElts)); 1024 } 1025 1026 // Reset the type to the unexpanded type if we did not find a legal vector 1027 // type with a promoted vector element type. 1028 EltVT = OldEltVT; 1029 } 1030 1031 // Try to widen the vector until a legal type is found. 1032 // If there is no wider legal type, split the vector. 1033 while (true) { 1034 // Round up to the next power of 2. 1035 NumElts = NumElts.coefficientNextPowerOf2(); 1036 1037 // If there is no simple vector type with this many elements then there 1038 // cannot be a larger legal vector type. Note that this assumes that 1039 // there are no skipped intermediate vector types in the simple types. 1040 if (!EltVT.isSimple()) 1041 break; 1042 MVT LargerVector = MVT::getVectorVT(EltVT.getSimpleVT(), NumElts); 1043 if (LargerVector == MVT()) 1044 break; 1045 1046 // If this type is legal then widen the vector. 1047 if (ValueTypeActions.getTypeAction(LargerVector) == TypeLegal) 1048 return LegalizeKind(TypeWidenVector, LargerVector); 1049 } 1050 1051 // Widen odd vectors to next power of two. 1052 if (!VT.isPow2VectorType()) { 1053 EVT NVT = VT.getPow2VectorType(Context); 1054 return LegalizeKind(TypeWidenVector, NVT); 1055 } 1056 1057 if (VT.getVectorElementCount() == ElementCount::getScalable(1)) 1058 return LegalizeKind(TypeScalarizeScalableVector, EltVT); 1059 1060 // Vectors with illegal element types are expanded. 1061 EVT NVT = EVT::getVectorVT(Context, EltVT, 1062 VT.getVectorElementCount().divideCoefficientBy(2)); 1063 return LegalizeKind(TypeSplitVector, NVT); 1064 } 1065 1066 static unsigned getVectorTypeBreakdownMVT(MVT VT, MVT &IntermediateVT, 1067 unsigned &NumIntermediates, 1068 MVT &RegisterVT, 1069 TargetLoweringBase *TLI) { 1070 // Figure out the right, legal destination reg to copy into. 1071 ElementCount EC = VT.getVectorElementCount(); 1072 MVT EltTy = VT.getVectorElementType(); 1073 1074 unsigned NumVectorRegs = 1; 1075 1076 // Scalable vectors cannot be scalarized, so splitting or widening is 1077 // required. 1078 if (VT.isScalableVector() && !isPowerOf2_32(EC.getKnownMinValue())) 1079 llvm_unreachable( 1080 "Splitting or widening of non-power-of-2 MVTs is not implemented."); 1081 1082 // FIXME: We don't support non-power-of-2-sized vectors for now. 1083 // Ideally we could break down into LHS/RHS like LegalizeDAG does. 1084 if (!isPowerOf2_32(EC.getKnownMinValue())) { 1085 // Split EC to unit size (scalable property is preserved). 1086 NumVectorRegs = EC.getKnownMinValue(); 1087 EC = ElementCount::getFixed(1); 1088 } 1089 1090 // Divide the input until we get to a supported size. This will 1091 // always end up with an EC that represent a scalar or a scalable 1092 // scalar. 1093 while (EC.getKnownMinValue() > 1 && 1094 !TLI->isTypeLegal(MVT::getVectorVT(EltTy, EC))) { 1095 EC = EC.divideCoefficientBy(2); 1096 NumVectorRegs <<= 1; 1097 } 1098 1099 NumIntermediates = NumVectorRegs; 1100 1101 MVT NewVT = MVT::getVectorVT(EltTy, EC); 1102 if (!TLI->isTypeLegal(NewVT)) 1103 NewVT = EltTy; 1104 IntermediateVT = NewVT; 1105 1106 unsigned LaneSizeInBits = NewVT.getScalarSizeInBits(); 1107 1108 // Convert sizes such as i33 to i64. 1109 LaneSizeInBits = llvm::bit_ceil(LaneSizeInBits); 1110 1111 MVT DestVT = TLI->getRegisterType(NewVT); 1112 RegisterVT = DestVT; 1113 if (EVT(DestVT).bitsLT(NewVT)) // Value is expanded, e.g. i64 -> i16. 1114 return NumVectorRegs * (LaneSizeInBits / DestVT.getScalarSizeInBits()); 1115 1116 // Otherwise, promotion or legal types use the same number of registers as 1117 // the vector decimated to the appropriate level. 1118 return NumVectorRegs; 1119 } 1120 1121 /// isLegalRC - Return true if the value types that can be represented by the 1122 /// specified register class are all legal. 1123 bool TargetLoweringBase::isLegalRC(const TargetRegisterInfo &TRI, 1124 const TargetRegisterClass &RC) const { 1125 for (const auto *I = TRI.legalclasstypes_begin(RC); *I != MVT::Other; ++I) 1126 if (isTypeLegal(*I)) 1127 return true; 1128 return false; 1129 } 1130 1131 /// Replace/modify any TargetFrameIndex operands with a targte-dependent 1132 /// sequence of memory operands that is recognized by PrologEpilogInserter. 1133 MachineBasicBlock * 1134 TargetLoweringBase::emitPatchPoint(MachineInstr &InitialMI, 1135 MachineBasicBlock *MBB) const { 1136 MachineInstr *MI = &InitialMI; 1137 MachineFunction &MF = *MI->getMF(); 1138 MachineFrameInfo &MFI = MF.getFrameInfo(); 1139 1140 // We're handling multiple types of operands here: 1141 // PATCHPOINT MetaArgs - live-in, read only, direct 1142 // STATEPOINT Deopt Spill - live-through, read only, indirect 1143 // STATEPOINT Deopt Alloca - live-through, read only, direct 1144 // (We're currently conservative and mark the deopt slots read/write in 1145 // practice.) 1146 // STATEPOINT GC Spill - live-through, read/write, indirect 1147 // STATEPOINT GC Alloca - live-through, read/write, direct 1148 // The live-in vs live-through is handled already (the live through ones are 1149 // all stack slots), but we need to handle the different type of stackmap 1150 // operands and memory effects here. 1151 1152 if (llvm::none_of(MI->operands(), 1153 [](MachineOperand &Operand) { return Operand.isFI(); })) 1154 return MBB; 1155 1156 MachineInstrBuilder MIB = BuildMI(MF, MI->getDebugLoc(), MI->getDesc()); 1157 1158 // Inherit previous memory operands. 1159 MIB.cloneMemRefs(*MI); 1160 1161 for (unsigned i = 0; i < MI->getNumOperands(); ++i) { 1162 MachineOperand &MO = MI->getOperand(i); 1163 if (!MO.isFI()) { 1164 // Index of Def operand this Use it tied to. 1165 // Since Defs are coming before Uses, if Use is tied, then 1166 // index of Def must be smaller that index of that Use. 1167 // Also, Defs preserve their position in new MI. 1168 unsigned TiedTo = i; 1169 if (MO.isReg() && MO.isTied()) 1170 TiedTo = MI->findTiedOperandIdx(i); 1171 MIB.add(MO); 1172 if (TiedTo < i) 1173 MIB->tieOperands(TiedTo, MIB->getNumOperands() - 1); 1174 continue; 1175 } 1176 1177 // foldMemoryOperand builds a new MI after replacing a single FI operand 1178 // with the canonical set of five x86 addressing-mode operands. 1179 int FI = MO.getIndex(); 1180 1181 // Add frame index operands recognized by stackmaps.cpp 1182 if (MFI.isStatepointSpillSlotObjectIndex(FI)) { 1183 // indirect-mem-ref tag, size, #FI, offset. 1184 // Used for spills inserted by StatepointLowering. This codepath is not 1185 // used for patchpoints/stackmaps at all, for these spilling is done via 1186 // foldMemoryOperand callback only. 1187 assert(MI->getOpcode() == TargetOpcode::STATEPOINT && "sanity"); 1188 MIB.addImm(StackMaps::IndirectMemRefOp); 1189 MIB.addImm(MFI.getObjectSize(FI)); 1190 MIB.add(MO); 1191 MIB.addImm(0); 1192 } else { 1193 // direct-mem-ref tag, #FI, offset. 1194 // Used by patchpoint, and direct alloca arguments to statepoints 1195 MIB.addImm(StackMaps::DirectMemRefOp); 1196 MIB.add(MO); 1197 MIB.addImm(0); 1198 } 1199 1200 assert(MIB->mayLoad() && "Folded a stackmap use to a non-load!"); 1201 1202 // Add a new memory operand for this FI. 1203 assert(MFI.getObjectOffset(FI) != -1); 1204 1205 // Note: STATEPOINT MMOs are added during SelectionDAG. STACKMAP, and 1206 // PATCHPOINT should be updated to do the same. (TODO) 1207 if (MI->getOpcode() != TargetOpcode::STATEPOINT) { 1208 auto Flags = MachineMemOperand::MOLoad; 1209 MachineMemOperand *MMO = MF.getMachineMemOperand( 1210 MachinePointerInfo::getFixedStack(MF, FI), Flags, 1211 MF.getDataLayout().getPointerSize(), MFI.getObjectAlign(FI)); 1212 MIB->addMemOperand(MF, MMO); 1213 } 1214 } 1215 MBB->insert(MachineBasicBlock::iterator(MI), MIB); 1216 MI->eraseFromParent(); 1217 return MBB; 1218 } 1219 1220 /// findRepresentativeClass - Return the largest legal super-reg register class 1221 /// of the register class for the specified type and its associated "cost". 1222 // This function is in TargetLowering because it uses RegClassForVT which would 1223 // need to be moved to TargetRegisterInfo and would necessitate moving 1224 // isTypeLegal over as well - a massive change that would just require 1225 // TargetLowering having a TargetRegisterInfo class member that it would use. 1226 std::pair<const TargetRegisterClass *, uint8_t> 1227 TargetLoweringBase::findRepresentativeClass(const TargetRegisterInfo *TRI, 1228 MVT VT) const { 1229 const TargetRegisterClass *RC = RegClassForVT[VT.SimpleTy]; 1230 if (!RC) 1231 return std::make_pair(RC, 0); 1232 1233 // Compute the set of all super-register classes. 1234 BitVector SuperRegRC(TRI->getNumRegClasses()); 1235 for (SuperRegClassIterator RCI(RC, TRI); RCI.isValid(); ++RCI) 1236 SuperRegRC.setBitsInMask(RCI.getMask()); 1237 1238 // Find the first legal register class with the largest spill size. 1239 const TargetRegisterClass *BestRC = RC; 1240 for (unsigned i : SuperRegRC.set_bits()) { 1241 const TargetRegisterClass *SuperRC = TRI->getRegClass(i); 1242 // We want the largest possible spill size. 1243 if (TRI->getSpillSize(*SuperRC) <= TRI->getSpillSize(*BestRC)) 1244 continue; 1245 if (!isLegalRC(*TRI, *SuperRC)) 1246 continue; 1247 BestRC = SuperRC; 1248 } 1249 return std::make_pair(BestRC, 1); 1250 } 1251 1252 /// computeRegisterProperties - Once all of the register classes are added, 1253 /// this allows us to compute derived properties we expose. 1254 void TargetLoweringBase::computeRegisterProperties( 1255 const TargetRegisterInfo *TRI) { 1256 // Everything defaults to needing one register. 1257 for (unsigned i = 0; i != MVT::VALUETYPE_SIZE; ++i) { 1258 NumRegistersForVT[i] = 1; 1259 RegisterTypeForVT[i] = TransformToType[i] = (MVT::SimpleValueType)i; 1260 } 1261 // ...except isVoid, which doesn't need any registers. 1262 NumRegistersForVT[MVT::isVoid] = 0; 1263 1264 // Find the largest integer register class. 1265 unsigned LargestIntReg = MVT::LAST_INTEGER_VALUETYPE; 1266 for (; RegClassForVT[LargestIntReg] == nullptr; --LargestIntReg) 1267 assert(LargestIntReg != MVT::i1 && "No integer registers defined!"); 1268 1269 // Every integer value type larger than this largest register takes twice as 1270 // many registers to represent as the previous ValueType. 1271 for (unsigned ExpandedReg = LargestIntReg + 1; 1272 ExpandedReg <= MVT::LAST_INTEGER_VALUETYPE; ++ExpandedReg) { 1273 NumRegistersForVT[ExpandedReg] = 2*NumRegistersForVT[ExpandedReg-1]; 1274 RegisterTypeForVT[ExpandedReg] = (MVT::SimpleValueType)LargestIntReg; 1275 TransformToType[ExpandedReg] = (MVT::SimpleValueType)(ExpandedReg - 1); 1276 ValueTypeActions.setTypeAction((MVT::SimpleValueType)ExpandedReg, 1277 TypeExpandInteger); 1278 } 1279 1280 // Inspect all of the ValueType's smaller than the largest integer 1281 // register to see which ones need promotion. 1282 unsigned LegalIntReg = LargestIntReg; 1283 for (unsigned IntReg = LargestIntReg - 1; 1284 IntReg >= (unsigned)MVT::i1; --IntReg) { 1285 MVT IVT = (MVT::SimpleValueType)IntReg; 1286 if (isTypeLegal(IVT)) { 1287 LegalIntReg = IntReg; 1288 } else { 1289 RegisterTypeForVT[IntReg] = TransformToType[IntReg] = 1290 (MVT::SimpleValueType)LegalIntReg; 1291 ValueTypeActions.setTypeAction(IVT, TypePromoteInteger); 1292 } 1293 } 1294 1295 // ppcf128 type is really two f64's. 1296 if (!isTypeLegal(MVT::ppcf128)) { 1297 if (isTypeLegal(MVT::f64)) { 1298 NumRegistersForVT[MVT::ppcf128] = 2*NumRegistersForVT[MVT::f64]; 1299 RegisterTypeForVT[MVT::ppcf128] = MVT::f64; 1300 TransformToType[MVT::ppcf128] = MVT::f64; 1301 ValueTypeActions.setTypeAction(MVT::ppcf128, TypeExpandFloat); 1302 } else { 1303 NumRegistersForVT[MVT::ppcf128] = NumRegistersForVT[MVT::i128]; 1304 RegisterTypeForVT[MVT::ppcf128] = RegisterTypeForVT[MVT::i128]; 1305 TransformToType[MVT::ppcf128] = MVT::i128; 1306 ValueTypeActions.setTypeAction(MVT::ppcf128, TypeSoftenFloat); 1307 } 1308 } 1309 1310 // Decide how to handle f128. If the target does not have native f128 support, 1311 // expand it to i128 and we will be generating soft float library calls. 1312 if (!isTypeLegal(MVT::f128)) { 1313 NumRegistersForVT[MVT::f128] = NumRegistersForVT[MVT::i128]; 1314 RegisterTypeForVT[MVT::f128] = RegisterTypeForVT[MVT::i128]; 1315 TransformToType[MVT::f128] = MVT::i128; 1316 ValueTypeActions.setTypeAction(MVT::f128, TypeSoftenFloat); 1317 } 1318 1319 // Decide how to handle f80. If the target does not have native f80 support, 1320 // expand it to i96 and we will be generating soft float library calls. 1321 if (!isTypeLegal(MVT::f80)) { 1322 NumRegistersForVT[MVT::f80] = 3*NumRegistersForVT[MVT::i32]; 1323 RegisterTypeForVT[MVT::f80] = RegisterTypeForVT[MVT::i32]; 1324 TransformToType[MVT::f80] = MVT::i32; 1325 ValueTypeActions.setTypeAction(MVT::f80, TypeSoftenFloat); 1326 } 1327 1328 // Decide how to handle f64. If the target does not have native f64 support, 1329 // expand it to i64 and we will be generating soft float library calls. 1330 if (!isTypeLegal(MVT::f64)) { 1331 NumRegistersForVT[MVT::f64] = NumRegistersForVT[MVT::i64]; 1332 RegisterTypeForVT[MVT::f64] = RegisterTypeForVT[MVT::i64]; 1333 TransformToType[MVT::f64] = MVT::i64; 1334 ValueTypeActions.setTypeAction(MVT::f64, TypeSoftenFloat); 1335 } 1336 1337 // Decide how to handle f32. If the target does not have native f32 support, 1338 // expand it to i32 and we will be generating soft float library calls. 1339 if (!isTypeLegal(MVT::f32)) { 1340 NumRegistersForVT[MVT::f32] = NumRegistersForVT[MVT::i32]; 1341 RegisterTypeForVT[MVT::f32] = RegisterTypeForVT[MVT::i32]; 1342 TransformToType[MVT::f32] = MVT::i32; 1343 ValueTypeActions.setTypeAction(MVT::f32, TypeSoftenFloat); 1344 } 1345 1346 // Decide how to handle f16. If the target does not have native f16 support, 1347 // promote it to f32, because there are no f16 library calls (except for 1348 // conversions). 1349 if (!isTypeLegal(MVT::f16)) { 1350 // Allow targets to control how we legalize half. 1351 bool SoftPromoteHalfType = softPromoteHalfType(); 1352 bool UseFPRegsForHalfType = !SoftPromoteHalfType || useFPRegsForHalfType(); 1353 1354 if (!UseFPRegsForHalfType) { 1355 NumRegistersForVT[MVT::f16] = NumRegistersForVT[MVT::i16]; 1356 RegisterTypeForVT[MVT::f16] = RegisterTypeForVT[MVT::i16]; 1357 } else { 1358 NumRegistersForVT[MVT::f16] = NumRegistersForVT[MVT::f32]; 1359 RegisterTypeForVT[MVT::f16] = RegisterTypeForVT[MVT::f32]; 1360 } 1361 TransformToType[MVT::f16] = MVT::f32; 1362 if (SoftPromoteHalfType) { 1363 ValueTypeActions.setTypeAction(MVT::f16, TypeSoftPromoteHalf); 1364 } else { 1365 ValueTypeActions.setTypeAction(MVT::f16, TypePromoteFloat); 1366 } 1367 } 1368 1369 // Decide how to handle bf16. If the target does not have native bf16 support, 1370 // promote it to f32, because there are no bf16 library calls (except for 1371 // converting from f32 to bf16). 1372 if (!isTypeLegal(MVT::bf16)) { 1373 NumRegistersForVT[MVT::bf16] = NumRegistersForVT[MVT::f32]; 1374 RegisterTypeForVT[MVT::bf16] = RegisterTypeForVT[MVT::f32]; 1375 TransformToType[MVT::bf16] = MVT::f32; 1376 ValueTypeActions.setTypeAction(MVT::bf16, TypeSoftPromoteHalf); 1377 } 1378 1379 // Loop over all of the vector value types to see which need transformations. 1380 for (unsigned i = MVT::FIRST_VECTOR_VALUETYPE; 1381 i <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++i) { 1382 MVT VT = (MVT::SimpleValueType) i; 1383 if (isTypeLegal(VT)) 1384 continue; 1385 1386 MVT EltVT = VT.getVectorElementType(); 1387 ElementCount EC = VT.getVectorElementCount(); 1388 bool IsLegalWiderType = false; 1389 bool IsScalable = VT.isScalableVector(); 1390 LegalizeTypeAction PreferredAction = getPreferredVectorAction(VT); 1391 switch (PreferredAction) { 1392 case TypePromoteInteger: { 1393 MVT::SimpleValueType EndVT = IsScalable ? 1394 MVT::LAST_INTEGER_SCALABLE_VECTOR_VALUETYPE : 1395 MVT::LAST_INTEGER_FIXEDLEN_VECTOR_VALUETYPE; 1396 // Try to promote the elements of integer vectors. If no legal 1397 // promotion was found, fall through to the widen-vector method. 1398 for (unsigned nVT = i + 1; 1399 (MVT::SimpleValueType)nVT <= EndVT; ++nVT) { 1400 MVT SVT = (MVT::SimpleValueType) nVT; 1401 // Promote vectors of integers to vectors with the same number 1402 // of elements, with a wider element type. 1403 if (SVT.getScalarSizeInBits() > EltVT.getFixedSizeInBits() && 1404 SVT.getVectorElementCount() == EC && isTypeLegal(SVT)) { 1405 TransformToType[i] = SVT; 1406 RegisterTypeForVT[i] = SVT; 1407 NumRegistersForVT[i] = 1; 1408 ValueTypeActions.setTypeAction(VT, TypePromoteInteger); 1409 IsLegalWiderType = true; 1410 break; 1411 } 1412 } 1413 if (IsLegalWiderType) 1414 break; 1415 [[fallthrough]]; 1416 } 1417 1418 case TypeWidenVector: 1419 if (isPowerOf2_32(EC.getKnownMinValue())) { 1420 // Try to widen the vector. 1421 for (unsigned nVT = i + 1; nVT <= MVT::LAST_VECTOR_VALUETYPE; ++nVT) { 1422 MVT SVT = (MVT::SimpleValueType) nVT; 1423 if (SVT.getVectorElementType() == EltVT && 1424 SVT.isScalableVector() == IsScalable && 1425 SVT.getVectorElementCount().getKnownMinValue() > 1426 EC.getKnownMinValue() && 1427 isTypeLegal(SVT)) { 1428 TransformToType[i] = SVT; 1429 RegisterTypeForVT[i] = SVT; 1430 NumRegistersForVT[i] = 1; 1431 ValueTypeActions.setTypeAction(VT, TypeWidenVector); 1432 IsLegalWiderType = true; 1433 break; 1434 } 1435 } 1436 if (IsLegalWiderType) 1437 break; 1438 } else { 1439 // Only widen to the next power of 2 to keep consistency with EVT. 1440 MVT NVT = VT.getPow2VectorType(); 1441 if (isTypeLegal(NVT)) { 1442 TransformToType[i] = NVT; 1443 ValueTypeActions.setTypeAction(VT, TypeWidenVector); 1444 RegisterTypeForVT[i] = NVT; 1445 NumRegistersForVT[i] = 1; 1446 break; 1447 } 1448 } 1449 [[fallthrough]]; 1450 1451 case TypeSplitVector: 1452 case TypeScalarizeVector: { 1453 MVT IntermediateVT; 1454 MVT RegisterVT; 1455 unsigned NumIntermediates; 1456 unsigned NumRegisters = getVectorTypeBreakdownMVT(VT, IntermediateVT, 1457 NumIntermediates, RegisterVT, this); 1458 NumRegistersForVT[i] = NumRegisters; 1459 assert(NumRegistersForVT[i] == NumRegisters && 1460 "NumRegistersForVT size cannot represent NumRegisters!"); 1461 RegisterTypeForVT[i] = RegisterVT; 1462 1463 MVT NVT = VT.getPow2VectorType(); 1464 if (NVT == VT) { 1465 // Type is already a power of 2. The default action is to split. 1466 TransformToType[i] = MVT::Other; 1467 if (PreferredAction == TypeScalarizeVector) 1468 ValueTypeActions.setTypeAction(VT, TypeScalarizeVector); 1469 else if (PreferredAction == TypeSplitVector) 1470 ValueTypeActions.setTypeAction(VT, TypeSplitVector); 1471 else if (EC.getKnownMinValue() > 1) 1472 ValueTypeActions.setTypeAction(VT, TypeSplitVector); 1473 else 1474 ValueTypeActions.setTypeAction(VT, EC.isScalable() 1475 ? TypeScalarizeScalableVector 1476 : TypeScalarizeVector); 1477 } else { 1478 TransformToType[i] = NVT; 1479 ValueTypeActions.setTypeAction(VT, TypeWidenVector); 1480 } 1481 break; 1482 } 1483 default: 1484 llvm_unreachable("Unknown vector legalization action!"); 1485 } 1486 } 1487 1488 // Determine the 'representative' register class for each value type. 1489 // An representative register class is the largest (meaning one which is 1490 // not a sub-register class / subreg register class) legal register class for 1491 // a group of value types. For example, on i386, i8, i16, and i32 1492 // representative would be GR32; while on x86_64 it's GR64. 1493 for (unsigned i = 0; i != MVT::VALUETYPE_SIZE; ++i) { 1494 const TargetRegisterClass* RRC; 1495 uint8_t Cost; 1496 std::tie(RRC, Cost) = findRepresentativeClass(TRI, (MVT::SimpleValueType)i); 1497 RepRegClassForVT[i] = RRC; 1498 RepRegClassCostForVT[i] = Cost; 1499 } 1500 } 1501 1502 EVT TargetLoweringBase::getSetCCResultType(const DataLayout &DL, LLVMContext &, 1503 EVT VT) const { 1504 assert(!VT.isVector() && "No default SetCC type for vectors!"); 1505 return getPointerTy(DL).SimpleTy; 1506 } 1507 1508 MVT::SimpleValueType TargetLoweringBase::getCmpLibcallReturnType() const { 1509 return MVT::i32; // return the default value 1510 } 1511 1512 /// getVectorTypeBreakdown - Vector types are broken down into some number of 1513 /// legal first class types. For example, MVT::v8f32 maps to 2 MVT::v4f32 1514 /// with Altivec or SSE1, or 8 promoted MVT::f64 values with the X86 FP stack. 1515 /// Similarly, MVT::v2i64 turns into 4 MVT::i32 values with both PPC and X86. 1516 /// 1517 /// This method returns the number of registers needed, and the VT for each 1518 /// register. It also returns the VT and quantity of the intermediate values 1519 /// before they are promoted/expanded. 1520 unsigned TargetLoweringBase::getVectorTypeBreakdown(LLVMContext &Context, 1521 EVT VT, EVT &IntermediateVT, 1522 unsigned &NumIntermediates, 1523 MVT &RegisterVT) const { 1524 ElementCount EltCnt = VT.getVectorElementCount(); 1525 1526 // If there is a wider vector type with the same element type as this one, 1527 // or a promoted vector type that has the same number of elements which 1528 // are wider, then we should convert to that legal vector type. 1529 // This handles things like <2 x float> -> <4 x float> and 1530 // <4 x i1> -> <4 x i32>. 1531 LegalizeTypeAction TA = getTypeAction(Context, VT); 1532 if (!EltCnt.isScalar() && 1533 (TA == TypeWidenVector || TA == TypePromoteInteger)) { 1534 EVT RegisterEVT = getTypeToTransformTo(Context, VT); 1535 if (isTypeLegal(RegisterEVT)) { 1536 IntermediateVT = RegisterEVT; 1537 RegisterVT = RegisterEVT.getSimpleVT(); 1538 NumIntermediates = 1; 1539 return 1; 1540 } 1541 } 1542 1543 // Figure out the right, legal destination reg to copy into. 1544 EVT EltTy = VT.getVectorElementType(); 1545 1546 unsigned NumVectorRegs = 1; 1547 1548 // Scalable vectors cannot be scalarized, so handle the legalisation of the 1549 // types like done elsewhere in SelectionDAG. 1550 if (EltCnt.isScalable()) { 1551 LegalizeKind LK; 1552 EVT PartVT = VT; 1553 do { 1554 // Iterate until we've found a legal (part) type to hold VT. 1555 LK = getTypeConversion(Context, PartVT); 1556 PartVT = LK.second; 1557 } while (LK.first != TypeLegal); 1558 1559 if (!PartVT.isVector()) { 1560 report_fatal_error( 1561 "Don't know how to legalize this scalable vector type"); 1562 } 1563 1564 NumIntermediates = 1565 divideCeil(VT.getVectorElementCount().getKnownMinValue(), 1566 PartVT.getVectorElementCount().getKnownMinValue()); 1567 IntermediateVT = PartVT; 1568 RegisterVT = getRegisterType(Context, IntermediateVT); 1569 return NumIntermediates; 1570 } 1571 1572 // FIXME: We don't support non-power-of-2-sized vectors for now. Ideally 1573 // we could break down into LHS/RHS like LegalizeDAG does. 1574 if (!isPowerOf2_32(EltCnt.getKnownMinValue())) { 1575 NumVectorRegs = EltCnt.getKnownMinValue(); 1576 EltCnt = ElementCount::getFixed(1); 1577 } 1578 1579 // Divide the input until we get to a supported size. This will always 1580 // end with a scalar if the target doesn't support vectors. 1581 while (EltCnt.getKnownMinValue() > 1 && 1582 !isTypeLegal(EVT::getVectorVT(Context, EltTy, EltCnt))) { 1583 EltCnt = EltCnt.divideCoefficientBy(2); 1584 NumVectorRegs <<= 1; 1585 } 1586 1587 NumIntermediates = NumVectorRegs; 1588 1589 EVT NewVT = EVT::getVectorVT(Context, EltTy, EltCnt); 1590 if (!isTypeLegal(NewVT)) 1591 NewVT = EltTy; 1592 IntermediateVT = NewVT; 1593 1594 MVT DestVT = getRegisterType(Context, NewVT); 1595 RegisterVT = DestVT; 1596 1597 if (EVT(DestVT).bitsLT(NewVT)) { // Value is expanded, e.g. i64 -> i16. 1598 TypeSize NewVTSize = NewVT.getSizeInBits(); 1599 // Convert sizes such as i33 to i64. 1600 if (!llvm::has_single_bit<uint32_t>(NewVTSize.getKnownMinValue())) 1601 NewVTSize = NewVTSize.coefficientNextPowerOf2(); 1602 return NumVectorRegs*(NewVTSize/DestVT.getSizeInBits()); 1603 } 1604 1605 // Otherwise, promotion or legal types use the same number of registers as 1606 // the vector decimated to the appropriate level. 1607 return NumVectorRegs; 1608 } 1609 1610 bool TargetLoweringBase::isSuitableForJumpTable(const SwitchInst *SI, 1611 uint64_t NumCases, 1612 uint64_t Range, 1613 ProfileSummaryInfo *PSI, 1614 BlockFrequencyInfo *BFI) const { 1615 // FIXME: This function check the maximum table size and density, but the 1616 // minimum size is not checked. It would be nice if the minimum size is 1617 // also combined within this function. Currently, the minimum size check is 1618 // performed in findJumpTable() in SelectionDAGBuiler and 1619 // getEstimatedNumberOfCaseClusters() in BasicTTIImpl. 1620 const bool OptForSize = 1621 SI->getParent()->getParent()->hasOptSize() || 1622 llvm::shouldOptimizeForSize(SI->getParent(), PSI, BFI); 1623 const unsigned MinDensity = getMinimumJumpTableDensity(OptForSize); 1624 const unsigned MaxJumpTableSize = getMaximumJumpTableSize(); 1625 1626 // Check whether the number of cases is small enough and 1627 // the range is dense enough for a jump table. 1628 return (OptForSize || Range <= MaxJumpTableSize) && 1629 (NumCases * 100 >= Range * MinDensity); 1630 } 1631 1632 MVT TargetLoweringBase::getPreferredSwitchConditionType(LLVMContext &Context, 1633 EVT ConditionVT) const { 1634 return getRegisterType(Context, ConditionVT); 1635 } 1636 1637 /// Get the EVTs and ArgFlags collections that represent the legalized return 1638 /// type of the given function. This does not require a DAG or a return value, 1639 /// and is suitable for use before any DAGs for the function are constructed. 1640 /// TODO: Move this out of TargetLowering.cpp. 1641 void llvm::GetReturnInfo(CallingConv::ID CC, Type *ReturnType, 1642 AttributeList attr, 1643 SmallVectorImpl<ISD::OutputArg> &Outs, 1644 const TargetLowering &TLI, const DataLayout &DL) { 1645 SmallVector<EVT, 4> ValueVTs; 1646 ComputeValueVTs(TLI, DL, ReturnType, ValueVTs); 1647 unsigned NumValues = ValueVTs.size(); 1648 if (NumValues == 0) return; 1649 1650 for (unsigned j = 0, f = NumValues; j != f; ++j) { 1651 EVT VT = ValueVTs[j]; 1652 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 1653 1654 if (attr.hasRetAttr(Attribute::SExt)) 1655 ExtendKind = ISD::SIGN_EXTEND; 1656 else if (attr.hasRetAttr(Attribute::ZExt)) 1657 ExtendKind = ISD::ZERO_EXTEND; 1658 1659 if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger()) 1660 VT = TLI.getTypeForExtReturn(ReturnType->getContext(), VT, ExtendKind); 1661 1662 unsigned NumParts = 1663 TLI.getNumRegistersForCallingConv(ReturnType->getContext(), CC, VT); 1664 MVT PartVT = 1665 TLI.getRegisterTypeForCallingConv(ReturnType->getContext(), CC, VT); 1666 1667 // 'inreg' on function refers to return value 1668 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy(); 1669 if (attr.hasRetAttr(Attribute::InReg)) 1670 Flags.setInReg(); 1671 1672 // Propagate extension type if any 1673 if (attr.hasRetAttr(Attribute::SExt)) 1674 Flags.setSExt(); 1675 else if (attr.hasRetAttr(Attribute::ZExt)) 1676 Flags.setZExt(); 1677 1678 for (unsigned i = 0; i < NumParts; ++i) { 1679 ISD::ArgFlagsTy OutFlags = Flags; 1680 if (NumParts > 1 && i == 0) 1681 OutFlags.setSplit(); 1682 else if (i == NumParts - 1 && i != 0) 1683 OutFlags.setSplitEnd(); 1684 1685 Outs.push_back( 1686 ISD::OutputArg(OutFlags, PartVT, VT, /*isfixed=*/true, 0, 0)); 1687 } 1688 } 1689 } 1690 1691 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate 1692 /// function arguments in the caller parameter area. This is the actual 1693 /// alignment, not its logarithm. 1694 uint64_t TargetLoweringBase::getByValTypeAlignment(Type *Ty, 1695 const DataLayout &DL) const { 1696 return DL.getABITypeAlign(Ty).value(); 1697 } 1698 1699 bool TargetLoweringBase::allowsMemoryAccessForAlignment( 1700 LLVMContext &Context, const DataLayout &DL, EVT VT, unsigned AddrSpace, 1701 Align Alignment, MachineMemOperand::Flags Flags, unsigned *Fast) const { 1702 // Check if the specified alignment is sufficient based on the data layout. 1703 // TODO: While using the data layout works in practice, a better solution 1704 // would be to implement this check directly (make this a virtual function). 1705 // For example, the ABI alignment may change based on software platform while 1706 // this function should only be affected by hardware implementation. 1707 Type *Ty = VT.getTypeForEVT(Context); 1708 if (VT.isZeroSized() || Alignment >= DL.getABITypeAlign(Ty)) { 1709 // Assume that an access that meets the ABI-specified alignment is fast. 1710 if (Fast != nullptr) 1711 *Fast = 1; 1712 return true; 1713 } 1714 1715 // This is a misaligned access. 1716 return allowsMisalignedMemoryAccesses(VT, AddrSpace, Alignment, Flags, Fast); 1717 } 1718 1719 bool TargetLoweringBase::allowsMemoryAccessForAlignment( 1720 LLVMContext &Context, const DataLayout &DL, EVT VT, 1721 const MachineMemOperand &MMO, unsigned *Fast) const { 1722 return allowsMemoryAccessForAlignment(Context, DL, VT, MMO.getAddrSpace(), 1723 MMO.getAlign(), MMO.getFlags(), Fast); 1724 } 1725 1726 bool TargetLoweringBase::allowsMemoryAccess(LLVMContext &Context, 1727 const DataLayout &DL, EVT VT, 1728 unsigned AddrSpace, Align Alignment, 1729 MachineMemOperand::Flags Flags, 1730 unsigned *Fast) const { 1731 return allowsMemoryAccessForAlignment(Context, DL, VT, AddrSpace, Alignment, 1732 Flags, Fast); 1733 } 1734 1735 bool TargetLoweringBase::allowsMemoryAccess(LLVMContext &Context, 1736 const DataLayout &DL, EVT VT, 1737 const MachineMemOperand &MMO, 1738 unsigned *Fast) const { 1739 return allowsMemoryAccess(Context, DL, VT, MMO.getAddrSpace(), MMO.getAlign(), 1740 MMO.getFlags(), Fast); 1741 } 1742 1743 bool TargetLoweringBase::allowsMemoryAccess(LLVMContext &Context, 1744 const DataLayout &DL, LLT Ty, 1745 const MachineMemOperand &MMO, 1746 unsigned *Fast) const { 1747 EVT VT = getApproximateEVTForLLT(Ty, DL, Context); 1748 return allowsMemoryAccess(Context, DL, VT, MMO.getAddrSpace(), MMO.getAlign(), 1749 MMO.getFlags(), Fast); 1750 } 1751 1752 //===----------------------------------------------------------------------===// 1753 // TargetTransformInfo Helpers 1754 //===----------------------------------------------------------------------===// 1755 1756 int TargetLoweringBase::InstructionOpcodeToISD(unsigned Opcode) const { 1757 enum InstructionOpcodes { 1758 #define HANDLE_INST(NUM, OPCODE, CLASS) OPCODE = NUM, 1759 #define LAST_OTHER_INST(NUM) InstructionOpcodesCount = NUM 1760 #include "llvm/IR/Instruction.def" 1761 }; 1762 switch (static_cast<InstructionOpcodes>(Opcode)) { 1763 case Ret: return 0; 1764 case Br: return 0; 1765 case Switch: return 0; 1766 case IndirectBr: return 0; 1767 case Invoke: return 0; 1768 case CallBr: return 0; 1769 case Resume: return 0; 1770 case Unreachable: return 0; 1771 case CleanupRet: return 0; 1772 case CatchRet: return 0; 1773 case CatchPad: return 0; 1774 case CatchSwitch: return 0; 1775 case CleanupPad: return 0; 1776 case FNeg: return ISD::FNEG; 1777 case Add: return ISD::ADD; 1778 case FAdd: return ISD::FADD; 1779 case Sub: return ISD::SUB; 1780 case FSub: return ISD::FSUB; 1781 case Mul: return ISD::MUL; 1782 case FMul: return ISD::FMUL; 1783 case UDiv: return ISD::UDIV; 1784 case SDiv: return ISD::SDIV; 1785 case FDiv: return ISD::FDIV; 1786 case URem: return ISD::UREM; 1787 case SRem: return ISD::SREM; 1788 case FRem: return ISD::FREM; 1789 case Shl: return ISD::SHL; 1790 case LShr: return ISD::SRL; 1791 case AShr: return ISD::SRA; 1792 case And: return ISD::AND; 1793 case Or: return ISD::OR; 1794 case Xor: return ISD::XOR; 1795 case Alloca: return 0; 1796 case Load: return ISD::LOAD; 1797 case Store: return ISD::STORE; 1798 case GetElementPtr: return 0; 1799 case Fence: return 0; 1800 case AtomicCmpXchg: return 0; 1801 case AtomicRMW: return 0; 1802 case Trunc: return ISD::TRUNCATE; 1803 case ZExt: return ISD::ZERO_EXTEND; 1804 case SExt: return ISD::SIGN_EXTEND; 1805 case FPToUI: return ISD::FP_TO_UINT; 1806 case FPToSI: return ISD::FP_TO_SINT; 1807 case UIToFP: return ISD::UINT_TO_FP; 1808 case SIToFP: return ISD::SINT_TO_FP; 1809 case FPTrunc: return ISD::FP_ROUND; 1810 case FPExt: return ISD::FP_EXTEND; 1811 case PtrToInt: return ISD::BITCAST; 1812 case IntToPtr: return ISD::BITCAST; 1813 case BitCast: return ISD::BITCAST; 1814 case AddrSpaceCast: return ISD::ADDRSPACECAST; 1815 case ICmp: return ISD::SETCC; 1816 case FCmp: return ISD::SETCC; 1817 case PHI: return 0; 1818 case Call: return 0; 1819 case Select: return ISD::SELECT; 1820 case UserOp1: return 0; 1821 case UserOp2: return 0; 1822 case VAArg: return 0; 1823 case ExtractElement: return ISD::EXTRACT_VECTOR_ELT; 1824 case InsertElement: return ISD::INSERT_VECTOR_ELT; 1825 case ShuffleVector: return ISD::VECTOR_SHUFFLE; 1826 case ExtractValue: return ISD::MERGE_VALUES; 1827 case InsertValue: return ISD::MERGE_VALUES; 1828 case LandingPad: return 0; 1829 case Freeze: return ISD::FREEZE; 1830 } 1831 1832 llvm_unreachable("Unknown instruction type encountered!"); 1833 } 1834 1835 Value * 1836 TargetLoweringBase::getDefaultSafeStackPointerLocation(IRBuilderBase &IRB, 1837 bool UseTLS) const { 1838 // compiler-rt provides a variable with a magic name. Targets that do not 1839 // link with compiler-rt may also provide such a variable. 1840 Module *M = IRB.GetInsertBlock()->getParent()->getParent(); 1841 const char *UnsafeStackPtrVar = "__safestack_unsafe_stack_ptr"; 1842 auto UnsafeStackPtr = 1843 dyn_cast_or_null<GlobalVariable>(M->getNamedValue(UnsafeStackPtrVar)); 1844 1845 Type *StackPtrTy = PointerType::getUnqual(M->getContext()); 1846 1847 if (!UnsafeStackPtr) { 1848 auto TLSModel = UseTLS ? 1849 GlobalValue::InitialExecTLSModel : 1850 GlobalValue::NotThreadLocal; 1851 // The global variable is not defined yet, define it ourselves. 1852 // We use the initial-exec TLS model because we do not support the 1853 // variable living anywhere other than in the main executable. 1854 UnsafeStackPtr = new GlobalVariable( 1855 *M, StackPtrTy, false, GlobalValue::ExternalLinkage, nullptr, 1856 UnsafeStackPtrVar, nullptr, TLSModel); 1857 } else { 1858 // The variable exists, check its type and attributes. 1859 if (UnsafeStackPtr->getValueType() != StackPtrTy) 1860 report_fatal_error(Twine(UnsafeStackPtrVar) + " must have void* type"); 1861 if (UseTLS != UnsafeStackPtr->isThreadLocal()) 1862 report_fatal_error(Twine(UnsafeStackPtrVar) + " must " + 1863 (UseTLS ? "" : "not ") + "be thread-local"); 1864 } 1865 return UnsafeStackPtr; 1866 } 1867 1868 Value * 1869 TargetLoweringBase::getSafeStackPointerLocation(IRBuilderBase &IRB) const { 1870 if (!TM.getTargetTriple().isAndroid()) 1871 return getDefaultSafeStackPointerLocation(IRB, true); 1872 1873 // Android provides a libc function to retrieve the address of the current 1874 // thread's unsafe stack pointer. 1875 Module *M = IRB.GetInsertBlock()->getParent()->getParent(); 1876 auto *PtrTy = PointerType::getUnqual(M->getContext()); 1877 FunctionCallee Fn = 1878 M->getOrInsertFunction("__safestack_pointer_address", PtrTy); 1879 return IRB.CreateCall(Fn); 1880 } 1881 1882 //===----------------------------------------------------------------------===// 1883 // Loop Strength Reduction hooks 1884 //===----------------------------------------------------------------------===// 1885 1886 /// isLegalAddressingMode - Return true if the addressing mode represented 1887 /// by AM is legal for this target, for a load/store of the specified type. 1888 bool TargetLoweringBase::isLegalAddressingMode(const DataLayout &DL, 1889 const AddrMode &AM, Type *Ty, 1890 unsigned AS, Instruction *I) const { 1891 // The default implementation of this implements a conservative RISCy, r+r and 1892 // r+i addr mode. 1893 1894 // Scalable offsets not supported 1895 if (AM.ScalableOffset) 1896 return false; 1897 1898 // Allows a sign-extended 16-bit immediate field. 1899 if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1) 1900 return false; 1901 1902 // No global is ever allowed as a base. 1903 if (AM.BaseGV) 1904 return false; 1905 1906 // Only support r+r, 1907 switch (AM.Scale) { 1908 case 0: // "r+i" or just "i", depending on HasBaseReg. 1909 break; 1910 case 1: 1911 if (AM.HasBaseReg && AM.BaseOffs) // "r+r+i" is not allowed. 1912 return false; 1913 // Otherwise we have r+r or r+i. 1914 break; 1915 case 2: 1916 if (AM.HasBaseReg || AM.BaseOffs) // 2*r+r or 2*r+i is not allowed. 1917 return false; 1918 // Allow 2*r as r+r. 1919 break; 1920 default: // Don't allow n * r 1921 return false; 1922 } 1923 1924 return true; 1925 } 1926 1927 //===----------------------------------------------------------------------===// 1928 // Stack Protector 1929 //===----------------------------------------------------------------------===// 1930 1931 // For OpenBSD return its special guard variable. Otherwise return nullptr, 1932 // so that SelectionDAG handle SSP. 1933 Value *TargetLoweringBase::getIRStackGuard(IRBuilderBase &IRB) const { 1934 if (getTargetMachine().getTargetTriple().isOSOpenBSD()) { 1935 Module &M = *IRB.GetInsertBlock()->getParent()->getParent(); 1936 PointerType *PtrTy = PointerType::getUnqual(M.getContext()); 1937 Constant *C = M.getOrInsertGlobal("__guard_local", PtrTy); 1938 if (GlobalVariable *G = dyn_cast_or_null<GlobalVariable>(C)) 1939 G->setVisibility(GlobalValue::HiddenVisibility); 1940 return C; 1941 } 1942 return nullptr; 1943 } 1944 1945 // Currently only support "standard" __stack_chk_guard. 1946 // TODO: add LOAD_STACK_GUARD support. 1947 void TargetLoweringBase::insertSSPDeclarations(Module &M) const { 1948 if (!M.getNamedValue("__stack_chk_guard")) { 1949 auto *GV = new GlobalVariable(M, PointerType::getUnqual(M.getContext()), 1950 false, GlobalVariable::ExternalLinkage, 1951 nullptr, "__stack_chk_guard"); 1952 1953 // FreeBSD has "__stack_chk_guard" defined externally on libc.so 1954 if (M.getDirectAccessExternalData() && 1955 !TM.getTargetTriple().isWindowsGNUEnvironment() && 1956 !(TM.getTargetTriple().isPPC64() && 1957 TM.getTargetTriple().isOSFreeBSD()) && 1958 (!TM.getTargetTriple().isOSDarwin() || 1959 TM.getRelocationModel() == Reloc::Static)) 1960 GV->setDSOLocal(true); 1961 } 1962 } 1963 1964 // Currently only support "standard" __stack_chk_guard. 1965 // TODO: add LOAD_STACK_GUARD support. 1966 Value *TargetLoweringBase::getSDagStackGuard(const Module &M) const { 1967 return M.getNamedValue("__stack_chk_guard"); 1968 } 1969 1970 Function *TargetLoweringBase::getSSPStackGuardCheck(const Module &M) const { 1971 return nullptr; 1972 } 1973 1974 unsigned TargetLoweringBase::getMinimumJumpTableEntries() const { 1975 return MinimumJumpTableEntries; 1976 } 1977 1978 void TargetLoweringBase::setMinimumJumpTableEntries(unsigned Val) { 1979 MinimumJumpTableEntries = Val; 1980 } 1981 1982 unsigned TargetLoweringBase::getMinimumJumpTableDensity(bool OptForSize) const { 1983 return OptForSize ? OptsizeJumpTableDensity : JumpTableDensity; 1984 } 1985 1986 unsigned TargetLoweringBase::getMaximumJumpTableSize() const { 1987 return MaximumJumpTableSize; 1988 } 1989 1990 void TargetLoweringBase::setMaximumJumpTableSize(unsigned Val) { 1991 MaximumJumpTableSize = Val; 1992 } 1993 1994 bool TargetLoweringBase::isJumpTableRelative() const { 1995 return getTargetMachine().isPositionIndependent(); 1996 } 1997 1998 Align TargetLoweringBase::getPrefLoopAlignment(MachineLoop *ML) const { 1999 if (TM.Options.LoopAlignment) 2000 return Align(TM.Options.LoopAlignment); 2001 return PrefLoopAlignment; 2002 } 2003 2004 unsigned TargetLoweringBase::getMaxPermittedBytesForAlignment( 2005 MachineBasicBlock *MBB) const { 2006 return MaxBytesForAlignment; 2007 } 2008 2009 //===----------------------------------------------------------------------===// 2010 // Reciprocal Estimates 2011 //===----------------------------------------------------------------------===// 2012 2013 /// Get the reciprocal estimate attribute string for a function that will 2014 /// override the target defaults. 2015 static StringRef getRecipEstimateForFunc(MachineFunction &MF) { 2016 const Function &F = MF.getFunction(); 2017 return F.getFnAttribute("reciprocal-estimates").getValueAsString(); 2018 } 2019 2020 /// Construct a string for the given reciprocal operation of the given type. 2021 /// This string should match the corresponding option to the front-end's 2022 /// "-mrecip" flag assuming those strings have been passed through in an 2023 /// attribute string. For example, "vec-divf" for a division of a vXf32. 2024 static std::string getReciprocalOpName(bool IsSqrt, EVT VT) { 2025 std::string Name = VT.isVector() ? "vec-" : ""; 2026 2027 Name += IsSqrt ? "sqrt" : "div"; 2028 2029 // TODO: Handle other float types? 2030 if (VT.getScalarType() == MVT::f64) { 2031 Name += "d"; 2032 } else if (VT.getScalarType() == MVT::f16) { 2033 Name += "h"; 2034 } else { 2035 assert(VT.getScalarType() == MVT::f32 && 2036 "Unexpected FP type for reciprocal estimate"); 2037 Name += "f"; 2038 } 2039 2040 return Name; 2041 } 2042 2043 /// Return the character position and value (a single numeric character) of a 2044 /// customized refinement operation in the input string if it exists. Return 2045 /// false if there is no customized refinement step count. 2046 static bool parseRefinementStep(StringRef In, size_t &Position, 2047 uint8_t &Value) { 2048 const char RefStepToken = ':'; 2049 Position = In.find(RefStepToken); 2050 if (Position == StringRef::npos) 2051 return false; 2052 2053 StringRef RefStepString = In.substr(Position + 1); 2054 // Allow exactly one numeric character for the additional refinement 2055 // step parameter. 2056 if (RefStepString.size() == 1) { 2057 char RefStepChar = RefStepString[0]; 2058 if (isDigit(RefStepChar)) { 2059 Value = RefStepChar - '0'; 2060 return true; 2061 } 2062 } 2063 report_fatal_error("Invalid refinement step for -recip."); 2064 } 2065 2066 /// For the input attribute string, return one of the ReciprocalEstimate enum 2067 /// status values (enabled, disabled, or not specified) for this operation on 2068 /// the specified data type. 2069 static int getOpEnabled(bool IsSqrt, EVT VT, StringRef Override) { 2070 if (Override.empty()) 2071 return TargetLoweringBase::ReciprocalEstimate::Unspecified; 2072 2073 SmallVector<StringRef, 4> OverrideVector; 2074 Override.split(OverrideVector, ','); 2075 unsigned NumArgs = OverrideVector.size(); 2076 2077 // Check if "all", "none", or "default" was specified. 2078 if (NumArgs == 1) { 2079 // Look for an optional setting of the number of refinement steps needed 2080 // for this type of reciprocal operation. 2081 size_t RefPos; 2082 uint8_t RefSteps; 2083 if (parseRefinementStep(Override, RefPos, RefSteps)) { 2084 // Split the string for further processing. 2085 Override = Override.substr(0, RefPos); 2086 } 2087 2088 // All reciprocal types are enabled. 2089 if (Override == "all") 2090 return TargetLoweringBase::ReciprocalEstimate::Enabled; 2091 2092 // All reciprocal types are disabled. 2093 if (Override == "none") 2094 return TargetLoweringBase::ReciprocalEstimate::Disabled; 2095 2096 // Target defaults for enablement are used. 2097 if (Override == "default") 2098 return TargetLoweringBase::ReciprocalEstimate::Unspecified; 2099 } 2100 2101 // The attribute string may omit the size suffix ('f'/'d'). 2102 std::string VTName = getReciprocalOpName(IsSqrt, VT); 2103 std::string VTNameNoSize = VTName; 2104 VTNameNoSize.pop_back(); 2105 static const char DisabledPrefix = '!'; 2106 2107 for (StringRef RecipType : OverrideVector) { 2108 size_t RefPos; 2109 uint8_t RefSteps; 2110 if (parseRefinementStep(RecipType, RefPos, RefSteps)) 2111 RecipType = RecipType.substr(0, RefPos); 2112 2113 // Ignore the disablement token for string matching. 2114 bool IsDisabled = RecipType[0] == DisabledPrefix; 2115 if (IsDisabled) 2116 RecipType = RecipType.substr(1); 2117 2118 if (RecipType == VTName || RecipType == VTNameNoSize) 2119 return IsDisabled ? TargetLoweringBase::ReciprocalEstimate::Disabled 2120 : TargetLoweringBase::ReciprocalEstimate::Enabled; 2121 } 2122 2123 return TargetLoweringBase::ReciprocalEstimate::Unspecified; 2124 } 2125 2126 /// For the input attribute string, return the customized refinement step count 2127 /// for this operation on the specified data type. If the step count does not 2128 /// exist, return the ReciprocalEstimate enum value for unspecified. 2129 static int getOpRefinementSteps(bool IsSqrt, EVT VT, StringRef Override) { 2130 if (Override.empty()) 2131 return TargetLoweringBase::ReciprocalEstimate::Unspecified; 2132 2133 SmallVector<StringRef, 4> OverrideVector; 2134 Override.split(OverrideVector, ','); 2135 unsigned NumArgs = OverrideVector.size(); 2136 2137 // Check if "all", "default", or "none" was specified. 2138 if (NumArgs == 1) { 2139 // Look for an optional setting of the number of refinement steps needed 2140 // for this type of reciprocal operation. 2141 size_t RefPos; 2142 uint8_t RefSteps; 2143 if (!parseRefinementStep(Override, RefPos, RefSteps)) 2144 return TargetLoweringBase::ReciprocalEstimate::Unspecified; 2145 2146 // Split the string for further processing. 2147 Override = Override.substr(0, RefPos); 2148 assert(Override != "none" && 2149 "Disabled reciprocals, but specifed refinement steps?"); 2150 2151 // If this is a general override, return the specified number of steps. 2152 if (Override == "all" || Override == "default") 2153 return RefSteps; 2154 } 2155 2156 // The attribute string may omit the size suffix ('f'/'d'). 2157 std::string VTName = getReciprocalOpName(IsSqrt, VT); 2158 std::string VTNameNoSize = VTName; 2159 VTNameNoSize.pop_back(); 2160 2161 for (StringRef RecipType : OverrideVector) { 2162 size_t RefPos; 2163 uint8_t RefSteps; 2164 if (!parseRefinementStep(RecipType, RefPos, RefSteps)) 2165 continue; 2166 2167 RecipType = RecipType.substr(0, RefPos); 2168 if (RecipType == VTName || RecipType == VTNameNoSize) 2169 return RefSteps; 2170 } 2171 2172 return TargetLoweringBase::ReciprocalEstimate::Unspecified; 2173 } 2174 2175 int TargetLoweringBase::getRecipEstimateSqrtEnabled(EVT VT, 2176 MachineFunction &MF) const { 2177 return getOpEnabled(true, VT, getRecipEstimateForFunc(MF)); 2178 } 2179 2180 int TargetLoweringBase::getRecipEstimateDivEnabled(EVT VT, 2181 MachineFunction &MF) const { 2182 return getOpEnabled(false, VT, getRecipEstimateForFunc(MF)); 2183 } 2184 2185 int TargetLoweringBase::getSqrtRefinementSteps(EVT VT, 2186 MachineFunction &MF) const { 2187 return getOpRefinementSteps(true, VT, getRecipEstimateForFunc(MF)); 2188 } 2189 2190 int TargetLoweringBase::getDivRefinementSteps(EVT VT, 2191 MachineFunction &MF) const { 2192 return getOpRefinementSteps(false, VT, getRecipEstimateForFunc(MF)); 2193 } 2194 2195 bool TargetLoweringBase::isLoadBitCastBeneficial( 2196 EVT LoadVT, EVT BitcastVT, const SelectionDAG &DAG, 2197 const MachineMemOperand &MMO) const { 2198 // Single-element vectors are scalarized, so we should generally avoid having 2199 // any memory operations on such types, as they would get scalarized too. 2200 if (LoadVT.isFixedLengthVector() && BitcastVT.isFixedLengthVector() && 2201 BitcastVT.getVectorNumElements() == 1) 2202 return false; 2203 2204 // Don't do if we could do an indexed load on the original type, but not on 2205 // the new one. 2206 if (!LoadVT.isSimple() || !BitcastVT.isSimple()) 2207 return true; 2208 2209 MVT LoadMVT = LoadVT.getSimpleVT(); 2210 2211 // Don't bother doing this if it's just going to be promoted again later, as 2212 // doing so might interfere with other combines. 2213 if (getOperationAction(ISD::LOAD, LoadMVT) == Promote && 2214 getTypeToPromoteTo(ISD::LOAD, LoadMVT) == BitcastVT.getSimpleVT()) 2215 return false; 2216 2217 unsigned Fast = 0; 2218 return allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), BitcastVT, 2219 MMO, &Fast) && 2220 Fast; 2221 } 2222 2223 void TargetLoweringBase::finalizeLowering(MachineFunction &MF) const { 2224 MF.getRegInfo().freezeReservedRegs(); 2225 } 2226 2227 MachineMemOperand::Flags TargetLoweringBase::getLoadMemOperandFlags( 2228 const LoadInst &LI, const DataLayout &DL, AssumptionCache *AC, 2229 const TargetLibraryInfo *LibInfo) const { 2230 MachineMemOperand::Flags Flags = MachineMemOperand::MOLoad; 2231 if (LI.isVolatile()) 2232 Flags |= MachineMemOperand::MOVolatile; 2233 2234 if (LI.hasMetadata(LLVMContext::MD_nontemporal)) 2235 Flags |= MachineMemOperand::MONonTemporal; 2236 2237 if (LI.hasMetadata(LLVMContext::MD_invariant_load)) 2238 Flags |= MachineMemOperand::MOInvariant; 2239 2240 if (isDereferenceableAndAlignedPointer(LI.getPointerOperand(), LI.getType(), 2241 LI.getAlign(), DL, &LI, AC, 2242 /*DT=*/nullptr, LibInfo)) 2243 Flags |= MachineMemOperand::MODereferenceable; 2244 2245 Flags |= getTargetMMOFlags(LI); 2246 return Flags; 2247 } 2248 2249 MachineMemOperand::Flags 2250 TargetLoweringBase::getStoreMemOperandFlags(const StoreInst &SI, 2251 const DataLayout &DL) const { 2252 MachineMemOperand::Flags Flags = MachineMemOperand::MOStore; 2253 2254 if (SI.isVolatile()) 2255 Flags |= MachineMemOperand::MOVolatile; 2256 2257 if (SI.hasMetadata(LLVMContext::MD_nontemporal)) 2258 Flags |= MachineMemOperand::MONonTemporal; 2259 2260 // FIXME: Not preserving dereferenceable 2261 Flags |= getTargetMMOFlags(SI); 2262 return Flags; 2263 } 2264 2265 MachineMemOperand::Flags 2266 TargetLoweringBase::getAtomicMemOperandFlags(const Instruction &AI, 2267 const DataLayout &DL) const { 2268 auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 2269 2270 if (const AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(&AI)) { 2271 if (RMW->isVolatile()) 2272 Flags |= MachineMemOperand::MOVolatile; 2273 } else if (const AtomicCmpXchgInst *CmpX = dyn_cast<AtomicCmpXchgInst>(&AI)) { 2274 if (CmpX->isVolatile()) 2275 Flags |= MachineMemOperand::MOVolatile; 2276 } else 2277 llvm_unreachable("not an atomic instruction"); 2278 2279 // FIXME: Not preserving dereferenceable 2280 Flags |= getTargetMMOFlags(AI); 2281 return Flags; 2282 } 2283 2284 Instruction *TargetLoweringBase::emitLeadingFence(IRBuilderBase &Builder, 2285 Instruction *Inst, 2286 AtomicOrdering Ord) const { 2287 if (isReleaseOrStronger(Ord) && Inst->hasAtomicStore()) 2288 return Builder.CreateFence(Ord); 2289 else 2290 return nullptr; 2291 } 2292 2293 Instruction *TargetLoweringBase::emitTrailingFence(IRBuilderBase &Builder, 2294 Instruction *Inst, 2295 AtomicOrdering Ord) const { 2296 if (isAcquireOrStronger(Ord)) 2297 return Builder.CreateFence(Ord); 2298 else 2299 return nullptr; 2300 } 2301 2302 //===----------------------------------------------------------------------===// 2303 // GlobalISel Hooks 2304 //===----------------------------------------------------------------------===// 2305 2306 bool TargetLoweringBase::shouldLocalize(const MachineInstr &MI, 2307 const TargetTransformInfo *TTI) const { 2308 auto &MF = *MI.getMF(); 2309 auto &MRI = MF.getRegInfo(); 2310 // Assuming a spill and reload of a value has a cost of 1 instruction each, 2311 // this helper function computes the maximum number of uses we should consider 2312 // for remat. E.g. on arm64 global addresses take 2 insts to materialize. We 2313 // break even in terms of code size when the original MI has 2 users vs 2314 // choosing to potentially spill. Any more than 2 users we we have a net code 2315 // size increase. This doesn't take into account register pressure though. 2316 auto maxUses = [](unsigned RematCost) { 2317 // A cost of 1 means remats are basically free. 2318 if (RematCost == 1) 2319 return std::numeric_limits<unsigned>::max(); 2320 if (RematCost == 2) 2321 return 2U; 2322 2323 // Remat is too expensive, only sink if there's one user. 2324 if (RematCost > 2) 2325 return 1U; 2326 llvm_unreachable("Unexpected remat cost"); 2327 }; 2328 2329 switch (MI.getOpcode()) { 2330 default: 2331 return false; 2332 // Constants-like instructions should be close to their users. 2333 // We don't want long live-ranges for them. 2334 case TargetOpcode::G_CONSTANT: 2335 case TargetOpcode::G_FCONSTANT: 2336 case TargetOpcode::G_FRAME_INDEX: 2337 case TargetOpcode::G_INTTOPTR: 2338 return true; 2339 case TargetOpcode::G_GLOBAL_VALUE: { 2340 unsigned RematCost = TTI->getGISelRematGlobalCost(); 2341 Register Reg = MI.getOperand(0).getReg(); 2342 unsigned MaxUses = maxUses(RematCost); 2343 if (MaxUses == UINT_MAX) 2344 return true; // Remats are "free" so always localize. 2345 return MRI.hasAtMostUserInstrs(Reg, MaxUses); 2346 } 2347 } 2348 } 2349