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