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