1 //===-- PPCISelLowering.cpp - PPC DAG Lowering Implementation -------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file implements the PPCISelLowering class. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "PPCISelLowering.h" 15 #include "MCTargetDesc/PPCPredicates.h" 16 #include "PPC.h" 17 #include "PPCCCState.h" 18 #include "PPCCallingConv.h" 19 #include "PPCFrameLowering.h" 20 #include "PPCInstrInfo.h" 21 #include "PPCMachineFunctionInfo.h" 22 #include "PPCPerfectShuffle.h" 23 #include "PPCRegisterInfo.h" 24 #include "PPCSubtarget.h" 25 #include "PPCTargetMachine.h" 26 #include "llvm/ADT/APFloat.h" 27 #include "llvm/ADT/APInt.h" 28 #include "llvm/ADT/ArrayRef.h" 29 #include "llvm/ADT/DenseMap.h" 30 #include "llvm/ADT/None.h" 31 #include "llvm/ADT/STLExtras.h" 32 #include "llvm/ADT/SmallPtrSet.h" 33 #include "llvm/ADT/SmallSet.h" 34 #include "llvm/ADT/SmallVector.h" 35 #include "llvm/ADT/Statistic.h" 36 #include "llvm/ADT/StringRef.h" 37 #include "llvm/ADT/StringSwitch.h" 38 #include "llvm/CodeGen/CallingConvLower.h" 39 #include "llvm/CodeGen/ISDOpcodes.h" 40 #include "llvm/CodeGen/MachineBasicBlock.h" 41 #include "llvm/CodeGen/MachineFrameInfo.h" 42 #include "llvm/CodeGen/MachineFunction.h" 43 #include "llvm/CodeGen/MachineInstr.h" 44 #include "llvm/CodeGen/MachineInstrBuilder.h" 45 #include "llvm/CodeGen/MachineJumpTableInfo.h" 46 #include "llvm/CodeGen/MachineLoopInfo.h" 47 #include "llvm/CodeGen/MachineMemOperand.h" 48 #include "llvm/CodeGen/MachineOperand.h" 49 #include "llvm/CodeGen/MachineRegisterInfo.h" 50 #include "llvm/CodeGen/RuntimeLibcalls.h" 51 #include "llvm/CodeGen/SelectionDAG.h" 52 #include "llvm/CodeGen/SelectionDAGNodes.h" 53 #include "llvm/CodeGen/TargetInstrInfo.h" 54 #include "llvm/CodeGen/TargetLowering.h" 55 #include "llvm/CodeGen/TargetRegisterInfo.h" 56 #include "llvm/CodeGen/ValueTypes.h" 57 #include "llvm/IR/CallSite.h" 58 #include "llvm/IR/CallingConv.h" 59 #include "llvm/IR/Constant.h" 60 #include "llvm/IR/Constants.h" 61 #include "llvm/IR/DataLayout.h" 62 #include "llvm/IR/DebugLoc.h" 63 #include "llvm/IR/DerivedTypes.h" 64 #include "llvm/IR/Function.h" 65 #include "llvm/IR/GlobalValue.h" 66 #include "llvm/IR/IRBuilder.h" 67 #include "llvm/IR/Instructions.h" 68 #include "llvm/IR/Intrinsics.h" 69 #include "llvm/IR/Module.h" 70 #include "llvm/IR/Type.h" 71 #include "llvm/IR/Use.h" 72 #include "llvm/IR/Value.h" 73 #include "llvm/MC/MCExpr.h" 74 #include "llvm/MC/MCRegisterInfo.h" 75 #include "llvm/Support/AtomicOrdering.h" 76 #include "llvm/Support/BranchProbability.h" 77 #include "llvm/Support/Casting.h" 78 #include "llvm/Support/CodeGen.h" 79 #include "llvm/Support/CommandLine.h" 80 #include "llvm/Support/Compiler.h" 81 #include "llvm/Support/Debug.h" 82 #include "llvm/Support/ErrorHandling.h" 83 #include "llvm/Support/Format.h" 84 #include "llvm/Support/KnownBits.h" 85 #include "llvm/Support/MachineValueType.h" 86 #include "llvm/Support/MathExtras.h" 87 #include "llvm/Support/raw_ostream.h" 88 #include "llvm/Target/TargetMachine.h" 89 #include "llvm/Target/TargetOptions.h" 90 #include <algorithm> 91 #include <cassert> 92 #include <cstdint> 93 #include <iterator> 94 #include <list> 95 #include <utility> 96 #include <vector> 97 98 using namespace llvm; 99 100 #define DEBUG_TYPE "ppc-lowering" 101 102 static cl::opt<bool> DisablePPCPreinc("disable-ppc-preinc", 103 cl::desc("disable preincrement load/store generation on PPC"), cl::Hidden); 104 105 static cl::opt<bool> DisableILPPref("disable-ppc-ilp-pref", 106 cl::desc("disable setting the node scheduling preference to ILP on PPC"), cl::Hidden); 107 108 static cl::opt<bool> DisablePPCUnaligned("disable-ppc-unaligned", 109 cl::desc("disable unaligned load/store generation on PPC"), cl::Hidden); 110 111 static cl::opt<bool> DisableSCO("disable-ppc-sco", 112 cl::desc("disable sibling call optimization on ppc"), cl::Hidden); 113 114 static cl::opt<bool> EnableQuadPrecision("enable-ppc-quad-precision", 115 cl::desc("enable quad precision float support on ppc"), cl::Hidden); 116 117 STATISTIC(NumTailCalls, "Number of tail calls"); 118 STATISTIC(NumSiblingCalls, "Number of sibling calls"); 119 120 static bool isNByteElemShuffleMask(ShuffleVectorSDNode *, unsigned, int); 121 122 // FIXME: Remove this once the bug has been fixed! 123 extern cl::opt<bool> ANDIGlueBug; 124 125 PPCTargetLowering::PPCTargetLowering(const PPCTargetMachine &TM, 126 const PPCSubtarget &STI) 127 : TargetLowering(TM), Subtarget(STI) { 128 // Use _setjmp/_longjmp instead of setjmp/longjmp. 129 setUseUnderscoreSetJmp(true); 130 setUseUnderscoreLongJmp(true); 131 132 // On PPC32/64, arguments smaller than 4/8 bytes are extended, so all 133 // arguments are at least 4/8 bytes aligned. 134 bool isPPC64 = Subtarget.isPPC64(); 135 setMinStackArgumentAlignment(isPPC64 ? 8:4); 136 137 // Set up the register classes. 138 addRegisterClass(MVT::i32, &PPC::GPRCRegClass); 139 if (!useSoftFloat()) { 140 if (hasSPE()) { 141 addRegisterClass(MVT::f32, &PPC::SPE4RCRegClass); 142 addRegisterClass(MVT::f64, &PPC::SPERCRegClass); 143 } else { 144 addRegisterClass(MVT::f32, &PPC::F4RCRegClass); 145 addRegisterClass(MVT::f64, &PPC::F8RCRegClass); 146 } 147 } 148 149 // Match BITREVERSE to customized fast code sequence in the td file. 150 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal); 151 setOperationAction(ISD::BITREVERSE, MVT::i64, Legal); 152 153 // Sub-word ATOMIC_CMP_SWAP need to ensure that the input is zero-extended. 154 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom); 155 156 // PowerPC has an i16 but no i8 (or i1) SEXTLOAD. 157 for (MVT VT : MVT::integer_valuetypes()) { 158 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote); 159 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i8, Expand); 160 } 161 162 setTruncStoreAction(MVT::f64, MVT::f32, Expand); 163 164 // PowerPC has pre-inc load and store's. 165 setIndexedLoadAction(ISD::PRE_INC, MVT::i1, Legal); 166 setIndexedLoadAction(ISD::PRE_INC, MVT::i8, Legal); 167 setIndexedLoadAction(ISD::PRE_INC, MVT::i16, Legal); 168 setIndexedLoadAction(ISD::PRE_INC, MVT::i32, Legal); 169 setIndexedLoadAction(ISD::PRE_INC, MVT::i64, Legal); 170 setIndexedStoreAction(ISD::PRE_INC, MVT::i1, Legal); 171 setIndexedStoreAction(ISD::PRE_INC, MVT::i8, Legal); 172 setIndexedStoreAction(ISD::PRE_INC, MVT::i16, Legal); 173 setIndexedStoreAction(ISD::PRE_INC, MVT::i32, Legal); 174 setIndexedStoreAction(ISD::PRE_INC, MVT::i64, Legal); 175 if (!Subtarget.hasSPE()) { 176 setIndexedLoadAction(ISD::PRE_INC, MVT::f32, Legal); 177 setIndexedLoadAction(ISD::PRE_INC, MVT::f64, Legal); 178 setIndexedStoreAction(ISD::PRE_INC, MVT::f32, Legal); 179 setIndexedStoreAction(ISD::PRE_INC, MVT::f64, Legal); 180 } 181 182 // PowerPC uses ADDC/ADDE/SUBC/SUBE to propagate carry. 183 const MVT ScalarIntVTs[] = { MVT::i32, MVT::i64 }; 184 for (MVT VT : ScalarIntVTs) { 185 setOperationAction(ISD::ADDC, VT, Legal); 186 setOperationAction(ISD::ADDE, VT, Legal); 187 setOperationAction(ISD::SUBC, VT, Legal); 188 setOperationAction(ISD::SUBE, VT, Legal); 189 } 190 191 if (Subtarget.useCRBits()) { 192 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); 193 194 if (isPPC64 || Subtarget.hasFPCVT()) { 195 setOperationAction(ISD::SINT_TO_FP, MVT::i1, Promote); 196 AddPromotedToType (ISD::SINT_TO_FP, MVT::i1, 197 isPPC64 ? MVT::i64 : MVT::i32); 198 setOperationAction(ISD::UINT_TO_FP, MVT::i1, Promote); 199 AddPromotedToType(ISD::UINT_TO_FP, MVT::i1, 200 isPPC64 ? MVT::i64 : MVT::i32); 201 } else { 202 setOperationAction(ISD::SINT_TO_FP, MVT::i1, Custom); 203 setOperationAction(ISD::UINT_TO_FP, MVT::i1, Custom); 204 } 205 206 // PowerPC does not support direct load/store of condition registers. 207 setOperationAction(ISD::LOAD, MVT::i1, Custom); 208 setOperationAction(ISD::STORE, MVT::i1, Custom); 209 210 // FIXME: Remove this once the ANDI glue bug is fixed: 211 if (ANDIGlueBug) 212 setOperationAction(ISD::TRUNCATE, MVT::i1, Custom); 213 214 for (MVT VT : MVT::integer_valuetypes()) { 215 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote); 216 setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote); 217 setTruncStoreAction(VT, MVT::i1, Expand); 218 } 219 220 addRegisterClass(MVT::i1, &PPC::CRBITRCRegClass); 221 } 222 223 // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on 224 // PPC (the libcall is not available). 225 setOperationAction(ISD::FP_TO_SINT, MVT::ppcf128, Custom); 226 setOperationAction(ISD::FP_TO_UINT, MVT::ppcf128, Custom); 227 228 // We do not currently implement these libm ops for PowerPC. 229 setOperationAction(ISD::FFLOOR, MVT::ppcf128, Expand); 230 setOperationAction(ISD::FCEIL, MVT::ppcf128, Expand); 231 setOperationAction(ISD::FTRUNC, MVT::ppcf128, Expand); 232 setOperationAction(ISD::FRINT, MVT::ppcf128, Expand); 233 setOperationAction(ISD::FNEARBYINT, MVT::ppcf128, Expand); 234 setOperationAction(ISD::FREM, MVT::ppcf128, Expand); 235 236 // PowerPC has no SREM/UREM instructions unless we are on P9 237 // On P9 we may use a hardware instruction to compute the remainder. 238 // The instructions are not legalized directly because in the cases where the 239 // result of both the remainder and the division is required it is more 240 // efficient to compute the remainder from the result of the division rather 241 // than use the remainder instruction. 242 if (Subtarget.isISA3_0()) { 243 setOperationAction(ISD::SREM, MVT::i32, Custom); 244 setOperationAction(ISD::UREM, MVT::i32, Custom); 245 setOperationAction(ISD::SREM, MVT::i64, Custom); 246 setOperationAction(ISD::UREM, MVT::i64, Custom); 247 } else { 248 setOperationAction(ISD::SREM, MVT::i32, Expand); 249 setOperationAction(ISD::UREM, MVT::i32, Expand); 250 setOperationAction(ISD::SREM, MVT::i64, Expand); 251 setOperationAction(ISD::UREM, MVT::i64, Expand); 252 } 253 254 if (Subtarget.hasP9Vector()) { 255 setOperationAction(ISD::ABS, MVT::v4i32, Legal); 256 setOperationAction(ISD::ABS, MVT::v8i16, Legal); 257 setOperationAction(ISD::ABS, MVT::v16i8, Legal); 258 } 259 260 // Don't use SMUL_LOHI/UMUL_LOHI or SDIVREM/UDIVREM to lower SREM/UREM. 261 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand); 262 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand); 263 setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand); 264 setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand); 265 setOperationAction(ISD::UDIVREM, MVT::i32, Expand); 266 setOperationAction(ISD::SDIVREM, MVT::i32, Expand); 267 setOperationAction(ISD::UDIVREM, MVT::i64, Expand); 268 setOperationAction(ISD::SDIVREM, MVT::i64, Expand); 269 270 // We don't support sin/cos/sqrt/fmod/pow 271 setOperationAction(ISD::FSIN , MVT::f64, Expand); 272 setOperationAction(ISD::FCOS , MVT::f64, Expand); 273 setOperationAction(ISD::FSINCOS, MVT::f64, Expand); 274 setOperationAction(ISD::FREM , MVT::f64, Expand); 275 setOperationAction(ISD::FPOW , MVT::f64, Expand); 276 setOperationAction(ISD::FSIN , MVT::f32, Expand); 277 setOperationAction(ISD::FCOS , MVT::f32, Expand); 278 setOperationAction(ISD::FSINCOS, MVT::f32, Expand); 279 setOperationAction(ISD::FREM , MVT::f32, Expand); 280 setOperationAction(ISD::FPOW , MVT::f32, Expand); 281 if (Subtarget.hasSPE()) { 282 setOperationAction(ISD::FMA , MVT::f64, Expand); 283 setOperationAction(ISD::FMA , MVT::f32, Expand); 284 } else { 285 setOperationAction(ISD::FMA , MVT::f64, Legal); 286 setOperationAction(ISD::FMA , MVT::f32, Legal); 287 } 288 289 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom); 290 291 // If we're enabling GP optimizations, use hardware square root 292 if (!Subtarget.hasFSQRT() && 293 !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTE() && 294 Subtarget.hasFRE())) 295 setOperationAction(ISD::FSQRT, MVT::f64, Expand); 296 297 if (!Subtarget.hasFSQRT() && 298 !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTES() && 299 Subtarget.hasFRES())) 300 setOperationAction(ISD::FSQRT, MVT::f32, Expand); 301 302 if (Subtarget.hasFCPSGN()) { 303 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Legal); 304 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Legal); 305 } else { 306 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand); 307 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand); 308 } 309 310 if (Subtarget.hasFPRND()) { 311 setOperationAction(ISD::FFLOOR, MVT::f64, Legal); 312 setOperationAction(ISD::FCEIL, MVT::f64, Legal); 313 setOperationAction(ISD::FTRUNC, MVT::f64, Legal); 314 setOperationAction(ISD::FROUND, MVT::f64, Legal); 315 316 setOperationAction(ISD::FFLOOR, MVT::f32, Legal); 317 setOperationAction(ISD::FCEIL, MVT::f32, Legal); 318 setOperationAction(ISD::FTRUNC, MVT::f32, Legal); 319 setOperationAction(ISD::FROUND, MVT::f32, Legal); 320 } 321 322 // PowerPC does not have BSWAP, but we can use vector BSWAP instruction xxbrd 323 // to speed up scalar BSWAP64. 324 // CTPOP or CTTZ were introduced in P8/P9 respectively 325 setOperationAction(ISD::BSWAP, MVT::i32 , Expand); 326 if (Subtarget.isISA3_0()) { 327 setOperationAction(ISD::BSWAP, MVT::i64 , Custom); 328 setOperationAction(ISD::CTTZ , MVT::i32 , Legal); 329 setOperationAction(ISD::CTTZ , MVT::i64 , Legal); 330 } else { 331 setOperationAction(ISD::BSWAP, MVT::i64 , Expand); 332 setOperationAction(ISD::CTTZ , MVT::i32 , Expand); 333 setOperationAction(ISD::CTTZ , MVT::i64 , Expand); 334 } 335 336 if (Subtarget.hasPOPCNTD() == PPCSubtarget::POPCNTD_Fast) { 337 setOperationAction(ISD::CTPOP, MVT::i32 , Legal); 338 setOperationAction(ISD::CTPOP, MVT::i64 , Legal); 339 } else { 340 setOperationAction(ISD::CTPOP, MVT::i32 , Expand); 341 setOperationAction(ISD::CTPOP, MVT::i64 , Expand); 342 } 343 344 // PowerPC does not have ROTR 345 setOperationAction(ISD::ROTR, MVT::i32 , Expand); 346 setOperationAction(ISD::ROTR, MVT::i64 , Expand); 347 348 if (!Subtarget.useCRBits()) { 349 // PowerPC does not have Select 350 setOperationAction(ISD::SELECT, MVT::i32, Expand); 351 setOperationAction(ISD::SELECT, MVT::i64, Expand); 352 setOperationAction(ISD::SELECT, MVT::f32, Expand); 353 setOperationAction(ISD::SELECT, MVT::f64, Expand); 354 } 355 356 // PowerPC wants to turn select_cc of FP into fsel when possible. 357 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom); 358 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom); 359 360 // PowerPC wants to optimize integer setcc a bit 361 if (!Subtarget.useCRBits()) 362 setOperationAction(ISD::SETCC, MVT::i32, Custom); 363 364 // PowerPC does not have BRCOND which requires SetCC 365 if (!Subtarget.useCRBits()) 366 setOperationAction(ISD::BRCOND, MVT::Other, Expand); 367 368 setOperationAction(ISD::BR_JT, MVT::Other, Expand); 369 370 if (Subtarget.hasSPE()) { 371 // SPE has built-in conversions 372 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Legal); 373 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Legal); 374 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Legal); 375 } else { 376 // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores. 377 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 378 379 // PowerPC does not have [U|S]INT_TO_FP 380 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Expand); 381 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand); 382 } 383 384 if (Subtarget.hasDirectMove() && isPPC64) { 385 setOperationAction(ISD::BITCAST, MVT::f32, Legal); 386 setOperationAction(ISD::BITCAST, MVT::i32, Legal); 387 setOperationAction(ISD::BITCAST, MVT::i64, Legal); 388 setOperationAction(ISD::BITCAST, MVT::f64, Legal); 389 } else { 390 setOperationAction(ISD::BITCAST, MVT::f32, Expand); 391 setOperationAction(ISD::BITCAST, MVT::i32, Expand); 392 setOperationAction(ISD::BITCAST, MVT::i64, Expand); 393 setOperationAction(ISD::BITCAST, MVT::f64, Expand); 394 } 395 396 // We cannot sextinreg(i1). Expand to shifts. 397 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); 398 399 // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support 400 // SjLj exception handling but a light-weight setjmp/longjmp replacement to 401 // support continuation, user-level threading, and etc.. As a result, no 402 // other SjLj exception interfaces are implemented and please don't build 403 // your own exception handling based on them. 404 // LLVM/Clang supports zero-cost DWARF exception handling. 405 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom); 406 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom); 407 408 // We want to legalize GlobalAddress and ConstantPool nodes into the 409 // appropriate instructions to materialize the address. 410 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom); 411 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom); 412 setOperationAction(ISD::BlockAddress, MVT::i32, Custom); 413 setOperationAction(ISD::ConstantPool, MVT::i32, Custom); 414 setOperationAction(ISD::JumpTable, MVT::i32, Custom); 415 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom); 416 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom); 417 setOperationAction(ISD::BlockAddress, MVT::i64, Custom); 418 setOperationAction(ISD::ConstantPool, MVT::i64, Custom); 419 setOperationAction(ISD::JumpTable, MVT::i64, Custom); 420 421 // TRAP is legal. 422 setOperationAction(ISD::TRAP, MVT::Other, Legal); 423 424 // TRAMPOLINE is custom lowered. 425 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom); 426 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom); 427 428 // VASTART needs to be custom lowered to use the VarArgsFrameIndex 429 setOperationAction(ISD::VASTART , MVT::Other, Custom); 430 431 if (Subtarget.isSVR4ABI()) { 432 if (isPPC64) { 433 // VAARG always uses double-word chunks, so promote anything smaller. 434 setOperationAction(ISD::VAARG, MVT::i1, Promote); 435 AddPromotedToType (ISD::VAARG, MVT::i1, MVT::i64); 436 setOperationAction(ISD::VAARG, MVT::i8, Promote); 437 AddPromotedToType (ISD::VAARG, MVT::i8, MVT::i64); 438 setOperationAction(ISD::VAARG, MVT::i16, Promote); 439 AddPromotedToType (ISD::VAARG, MVT::i16, MVT::i64); 440 setOperationAction(ISD::VAARG, MVT::i32, Promote); 441 AddPromotedToType (ISD::VAARG, MVT::i32, MVT::i64); 442 setOperationAction(ISD::VAARG, MVT::Other, Expand); 443 } else { 444 // VAARG is custom lowered with the 32-bit SVR4 ABI. 445 setOperationAction(ISD::VAARG, MVT::Other, Custom); 446 setOperationAction(ISD::VAARG, MVT::i64, Custom); 447 } 448 } else 449 setOperationAction(ISD::VAARG, MVT::Other, Expand); 450 451 if (Subtarget.isSVR4ABI() && !isPPC64) 452 // VACOPY is custom lowered with the 32-bit SVR4 ABI. 453 setOperationAction(ISD::VACOPY , MVT::Other, Custom); 454 else 455 setOperationAction(ISD::VACOPY , MVT::Other, Expand); 456 457 // Use the default implementation. 458 setOperationAction(ISD::VAEND , MVT::Other, Expand); 459 setOperationAction(ISD::STACKSAVE , MVT::Other, Expand); 460 setOperationAction(ISD::STACKRESTORE , MVT::Other, Custom); 461 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32 , Custom); 462 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64 , Custom); 463 setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i32, Custom); 464 setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i64, Custom); 465 setOperationAction(ISD::EH_DWARF_CFA, MVT::i32, Custom); 466 setOperationAction(ISD::EH_DWARF_CFA, MVT::i64, Custom); 467 468 // We want to custom lower some of our intrinsics. 469 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 470 471 // To handle counter-based loop conditions. 472 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i1, Custom); 473 474 setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom); 475 setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom); 476 setOperationAction(ISD::INTRINSIC_VOID, MVT::i32, Custom); 477 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom); 478 479 // Comparisons that require checking two conditions. 480 if (Subtarget.hasSPE()) { 481 setCondCodeAction(ISD::SETO, MVT::f32, Expand); 482 setCondCodeAction(ISD::SETO, MVT::f64, Expand); 483 setCondCodeAction(ISD::SETUO, MVT::f32, Expand); 484 setCondCodeAction(ISD::SETUO, MVT::f64, Expand); 485 } 486 setCondCodeAction(ISD::SETULT, MVT::f32, Expand); 487 setCondCodeAction(ISD::SETULT, MVT::f64, Expand); 488 setCondCodeAction(ISD::SETUGT, MVT::f32, Expand); 489 setCondCodeAction(ISD::SETUGT, MVT::f64, Expand); 490 setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand); 491 setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand); 492 setCondCodeAction(ISD::SETOGE, MVT::f32, Expand); 493 setCondCodeAction(ISD::SETOGE, MVT::f64, Expand); 494 setCondCodeAction(ISD::SETOLE, MVT::f32, Expand); 495 setCondCodeAction(ISD::SETOLE, MVT::f64, Expand); 496 setCondCodeAction(ISD::SETONE, MVT::f32, Expand); 497 setCondCodeAction(ISD::SETONE, MVT::f64, Expand); 498 499 if (Subtarget.has64BitSupport()) { 500 // They also have instructions for converting between i64 and fp. 501 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom); 502 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand); 503 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom); 504 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand); 505 // This is just the low 32 bits of a (signed) fp->i64 conversion. 506 // We cannot do this with Promote because i64 is not a legal type. 507 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 508 509 if (Subtarget.hasLFIWAX() || Subtarget.isPPC64()) 510 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom); 511 } else { 512 // PowerPC does not have FP_TO_UINT on 32-bit implementations. 513 if (Subtarget.hasSPE()) 514 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Legal); 515 else 516 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand); 517 } 518 519 // With the instructions enabled under FPCVT, we can do everything. 520 if (Subtarget.hasFPCVT()) { 521 if (Subtarget.has64BitSupport()) { 522 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom); 523 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom); 524 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom); 525 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom); 526 } 527 528 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 529 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 530 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom); 531 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom); 532 } 533 534 if (Subtarget.use64BitRegs()) { 535 // 64-bit PowerPC implementations can support i64 types directly 536 addRegisterClass(MVT::i64, &PPC::G8RCRegClass); 537 // BUILD_PAIR can't be handled natively, and should be expanded to shl/or 538 setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand); 539 // 64-bit PowerPC wants to expand i128 shifts itself. 540 setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom); 541 setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom); 542 setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom); 543 } else { 544 // 32-bit PowerPC wants to expand i64 shifts itself. 545 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom); 546 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom); 547 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom); 548 } 549 550 if (Subtarget.hasAltivec()) { 551 // First set operation action for all vector types to expand. Then we 552 // will selectively turn on ones that can be effectively codegen'd. 553 for (MVT VT : MVT::vector_valuetypes()) { 554 // add/sub are legal for all supported vector VT's. 555 setOperationAction(ISD::ADD, VT, Legal); 556 setOperationAction(ISD::SUB, VT, Legal); 557 558 // Vector instructions introduced in P8 559 if (Subtarget.hasP8Altivec() && (VT.SimpleTy != MVT::v1i128)) { 560 setOperationAction(ISD::CTPOP, VT, Legal); 561 setOperationAction(ISD::CTLZ, VT, Legal); 562 } 563 else { 564 setOperationAction(ISD::CTPOP, VT, Expand); 565 setOperationAction(ISD::CTLZ, VT, Expand); 566 } 567 568 // Vector instructions introduced in P9 569 if (Subtarget.hasP9Altivec() && (VT.SimpleTy != MVT::v1i128)) 570 setOperationAction(ISD::CTTZ, VT, Legal); 571 else 572 setOperationAction(ISD::CTTZ, VT, Expand); 573 574 // We promote all shuffles to v16i8. 575 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Promote); 576 AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8); 577 578 // We promote all non-typed operations to v4i32. 579 setOperationAction(ISD::AND , VT, Promote); 580 AddPromotedToType (ISD::AND , VT, MVT::v4i32); 581 setOperationAction(ISD::OR , VT, Promote); 582 AddPromotedToType (ISD::OR , VT, MVT::v4i32); 583 setOperationAction(ISD::XOR , VT, Promote); 584 AddPromotedToType (ISD::XOR , VT, MVT::v4i32); 585 setOperationAction(ISD::LOAD , VT, Promote); 586 AddPromotedToType (ISD::LOAD , VT, MVT::v4i32); 587 setOperationAction(ISD::SELECT, VT, Promote); 588 AddPromotedToType (ISD::SELECT, VT, MVT::v4i32); 589 setOperationAction(ISD::VSELECT, VT, Legal); 590 setOperationAction(ISD::SELECT_CC, VT, Promote); 591 AddPromotedToType (ISD::SELECT_CC, VT, MVT::v4i32); 592 setOperationAction(ISD::STORE, VT, Promote); 593 AddPromotedToType (ISD::STORE, VT, MVT::v4i32); 594 595 // No other operations are legal. 596 setOperationAction(ISD::MUL , VT, Expand); 597 setOperationAction(ISD::SDIV, VT, Expand); 598 setOperationAction(ISD::SREM, VT, Expand); 599 setOperationAction(ISD::UDIV, VT, Expand); 600 setOperationAction(ISD::UREM, VT, Expand); 601 setOperationAction(ISD::FDIV, VT, Expand); 602 setOperationAction(ISD::FREM, VT, Expand); 603 setOperationAction(ISD::FNEG, VT, Expand); 604 setOperationAction(ISD::FSQRT, VT, Expand); 605 setOperationAction(ISD::FLOG, VT, Expand); 606 setOperationAction(ISD::FLOG10, VT, Expand); 607 setOperationAction(ISD::FLOG2, VT, Expand); 608 setOperationAction(ISD::FEXP, VT, Expand); 609 setOperationAction(ISD::FEXP2, VT, Expand); 610 setOperationAction(ISD::FSIN, VT, Expand); 611 setOperationAction(ISD::FCOS, VT, Expand); 612 setOperationAction(ISD::FABS, VT, Expand); 613 setOperationAction(ISD::FFLOOR, VT, Expand); 614 setOperationAction(ISD::FCEIL, VT, Expand); 615 setOperationAction(ISD::FTRUNC, VT, Expand); 616 setOperationAction(ISD::FRINT, VT, Expand); 617 setOperationAction(ISD::FNEARBYINT, VT, Expand); 618 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand); 619 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand); 620 setOperationAction(ISD::BUILD_VECTOR, VT, Expand); 621 setOperationAction(ISD::MULHU, VT, Expand); 622 setOperationAction(ISD::MULHS, VT, Expand); 623 setOperationAction(ISD::UMUL_LOHI, VT, Expand); 624 setOperationAction(ISD::SMUL_LOHI, VT, Expand); 625 setOperationAction(ISD::UDIVREM, VT, Expand); 626 setOperationAction(ISD::SDIVREM, VT, Expand); 627 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand); 628 setOperationAction(ISD::FPOW, VT, Expand); 629 setOperationAction(ISD::BSWAP, VT, Expand); 630 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand); 631 setOperationAction(ISD::ROTL, VT, Expand); 632 setOperationAction(ISD::ROTR, VT, Expand); 633 634 for (MVT InnerVT : MVT::vector_valuetypes()) { 635 setTruncStoreAction(VT, InnerVT, Expand); 636 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand); 637 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand); 638 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand); 639 } 640 } 641 642 // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle 643 // with merges, splats, etc. 644 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom); 645 646 setOperationAction(ISD::AND , MVT::v4i32, Legal); 647 setOperationAction(ISD::OR , MVT::v4i32, Legal); 648 setOperationAction(ISD::XOR , MVT::v4i32, Legal); 649 setOperationAction(ISD::LOAD , MVT::v4i32, Legal); 650 setOperationAction(ISD::SELECT, MVT::v4i32, 651 Subtarget.useCRBits() ? Legal : Expand); 652 setOperationAction(ISD::STORE , MVT::v4i32, Legal); 653 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal); 654 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal); 655 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal); 656 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal); 657 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal); 658 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal); 659 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal); 660 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal); 661 662 addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass); 663 addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass); 664 addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass); 665 addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass); 666 667 setOperationAction(ISD::MUL, MVT::v4f32, Legal); 668 setOperationAction(ISD::FMA, MVT::v4f32, Legal); 669 670 if (TM.Options.UnsafeFPMath || Subtarget.hasVSX()) { 671 setOperationAction(ISD::FDIV, MVT::v4f32, Legal); 672 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal); 673 } 674 675 if (Subtarget.hasP8Altivec()) 676 setOperationAction(ISD::MUL, MVT::v4i32, Legal); 677 else 678 setOperationAction(ISD::MUL, MVT::v4i32, Custom); 679 680 setOperationAction(ISD::MUL, MVT::v8i16, Custom); 681 setOperationAction(ISD::MUL, MVT::v16i8, Custom); 682 683 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom); 684 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom); 685 686 setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom); 687 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom); 688 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom); 689 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom); 690 691 // Altivec does not contain unordered floating-point compare instructions 692 setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand); 693 setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand); 694 setCondCodeAction(ISD::SETO, MVT::v4f32, Expand); 695 setCondCodeAction(ISD::SETONE, MVT::v4f32, Expand); 696 697 if (Subtarget.hasVSX()) { 698 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal); 699 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal); 700 if (Subtarget.hasP8Vector()) { 701 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal); 702 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Legal); 703 } 704 if (Subtarget.hasDirectMove() && isPPC64) { 705 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Legal); 706 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Legal); 707 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Legal); 708 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i64, Legal); 709 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Legal); 710 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Legal); 711 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Legal); 712 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal); 713 } 714 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal); 715 716 setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal); 717 setOperationAction(ISD::FCEIL, MVT::v2f64, Legal); 718 setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal); 719 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal); 720 setOperationAction(ISD::FROUND, MVT::v2f64, Legal); 721 722 setOperationAction(ISD::FROUND, MVT::v4f32, Legal); 723 724 setOperationAction(ISD::MUL, MVT::v2f64, Legal); 725 setOperationAction(ISD::FMA, MVT::v2f64, Legal); 726 727 setOperationAction(ISD::FDIV, MVT::v2f64, Legal); 728 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal); 729 730 // Share the Altivec comparison restrictions. 731 setCondCodeAction(ISD::SETUO, MVT::v2f64, Expand); 732 setCondCodeAction(ISD::SETUEQ, MVT::v2f64, Expand); 733 setCondCodeAction(ISD::SETO, MVT::v2f64, Expand); 734 setCondCodeAction(ISD::SETONE, MVT::v2f64, Expand); 735 736 setOperationAction(ISD::LOAD, MVT::v2f64, Legal); 737 setOperationAction(ISD::STORE, MVT::v2f64, Legal); 738 739 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Legal); 740 741 if (Subtarget.hasP8Vector()) 742 addRegisterClass(MVT::f32, &PPC::VSSRCRegClass); 743 744 addRegisterClass(MVT::f64, &PPC::VSFRCRegClass); 745 746 addRegisterClass(MVT::v4i32, &PPC::VSRCRegClass); 747 addRegisterClass(MVT::v4f32, &PPC::VSRCRegClass); 748 addRegisterClass(MVT::v2f64, &PPC::VSRCRegClass); 749 750 if (Subtarget.hasP8Altivec()) { 751 setOperationAction(ISD::SHL, MVT::v2i64, Legal); 752 setOperationAction(ISD::SRA, MVT::v2i64, Legal); 753 setOperationAction(ISD::SRL, MVT::v2i64, Legal); 754 755 // 128 bit shifts can be accomplished via 3 instructions for SHL and 756 // SRL, but not for SRA because of the instructions available: 757 // VS{RL} and VS{RL}O. However due to direct move costs, it's not worth 758 // doing 759 setOperationAction(ISD::SHL, MVT::v1i128, Expand); 760 setOperationAction(ISD::SRL, MVT::v1i128, Expand); 761 setOperationAction(ISD::SRA, MVT::v1i128, Expand); 762 763 setOperationAction(ISD::SETCC, MVT::v2i64, Legal); 764 } 765 else { 766 setOperationAction(ISD::SHL, MVT::v2i64, Expand); 767 setOperationAction(ISD::SRA, MVT::v2i64, Expand); 768 setOperationAction(ISD::SRL, MVT::v2i64, Expand); 769 770 setOperationAction(ISD::SETCC, MVT::v2i64, Custom); 771 772 // VSX v2i64 only supports non-arithmetic operations. 773 setOperationAction(ISD::ADD, MVT::v2i64, Expand); 774 setOperationAction(ISD::SUB, MVT::v2i64, Expand); 775 } 776 777 setOperationAction(ISD::LOAD, MVT::v2i64, Promote); 778 AddPromotedToType (ISD::LOAD, MVT::v2i64, MVT::v2f64); 779 setOperationAction(ISD::STORE, MVT::v2i64, Promote); 780 AddPromotedToType (ISD::STORE, MVT::v2i64, MVT::v2f64); 781 782 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Legal); 783 784 setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal); 785 setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal); 786 setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal); 787 setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal); 788 789 setOperationAction(ISD::UINT_TO_FP, MVT::v2i16, Custom); 790 setOperationAction(ISD::SINT_TO_FP, MVT::v2i16, Custom); 791 792 setOperationAction(ISD::FNEG, MVT::v4f32, Legal); 793 setOperationAction(ISD::FNEG, MVT::v2f64, Legal); 794 setOperationAction(ISD::FABS, MVT::v4f32, Legal); 795 setOperationAction(ISD::FABS, MVT::v2f64, Legal); 796 797 if (Subtarget.hasDirectMove()) 798 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom); 799 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom); 800 801 addRegisterClass(MVT::v2i64, &PPC::VSRCRegClass); 802 } 803 804 if (Subtarget.hasP8Altivec()) { 805 addRegisterClass(MVT::v2i64, &PPC::VRRCRegClass); 806 addRegisterClass(MVT::v1i128, &PPC::VRRCRegClass); 807 } 808 809 if (Subtarget.hasP9Vector()) { 810 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom); 811 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom); 812 813 // 128 bit shifts can be accomplished via 3 instructions for SHL and 814 // SRL, but not for SRA because of the instructions available: 815 // VS{RL} and VS{RL}O. 816 setOperationAction(ISD::SHL, MVT::v1i128, Legal); 817 setOperationAction(ISD::SRL, MVT::v1i128, Legal); 818 setOperationAction(ISD::SRA, MVT::v1i128, Expand); 819 820 if (EnableQuadPrecision) { 821 addRegisterClass(MVT::f128, &PPC::VRRCRegClass); 822 setOperationAction(ISD::FADD, MVT::f128, Legal); 823 setOperationAction(ISD::FSUB, MVT::f128, Legal); 824 setOperationAction(ISD::FDIV, MVT::f128, Legal); 825 setOperationAction(ISD::FMUL, MVT::f128, Legal); 826 setOperationAction(ISD::FP_EXTEND, MVT::f128, Legal); 827 // No extending loads to f128 on PPC. 828 for (MVT FPT : MVT::fp_valuetypes()) 829 setLoadExtAction(ISD::EXTLOAD, MVT::f128, FPT, Expand); 830 setOperationAction(ISD::FMA, MVT::f128, Legal); 831 setCondCodeAction(ISD::SETULT, MVT::f128, Expand); 832 setCondCodeAction(ISD::SETUGT, MVT::f128, Expand); 833 setCondCodeAction(ISD::SETUEQ, MVT::f128, Expand); 834 setCondCodeAction(ISD::SETOGE, MVT::f128, Expand); 835 setCondCodeAction(ISD::SETOLE, MVT::f128, Expand); 836 setCondCodeAction(ISD::SETONE, MVT::f128, Expand); 837 838 setOperationAction(ISD::FTRUNC, MVT::f128, Legal); 839 setOperationAction(ISD::FRINT, MVT::f128, Legal); 840 setOperationAction(ISD::FFLOOR, MVT::f128, Legal); 841 setOperationAction(ISD::FCEIL, MVT::f128, Legal); 842 setOperationAction(ISD::FNEARBYINT, MVT::f128, Legal); 843 setOperationAction(ISD::FROUND, MVT::f128, Legal); 844 845 setOperationAction(ISD::SELECT, MVT::f128, Expand); 846 setOperationAction(ISD::FP_ROUND, MVT::f64, Legal); 847 setOperationAction(ISD::FP_ROUND, MVT::f32, Legal); 848 setTruncStoreAction(MVT::f128, MVT::f64, Expand); 849 setTruncStoreAction(MVT::f128, MVT::f32, Expand); 850 setOperationAction(ISD::BITCAST, MVT::i128, Custom); 851 // No implementation for these ops for PowerPC. 852 setOperationAction(ISD::FSIN , MVT::f128, Expand); 853 setOperationAction(ISD::FCOS , MVT::f128, Expand); 854 setOperationAction(ISD::FPOW, MVT::f128, Expand); 855 setOperationAction(ISD::FPOWI, MVT::f128, Expand); 856 setOperationAction(ISD::FREM, MVT::f128, Expand); 857 } 858 859 } 860 861 if (Subtarget.hasP9Altivec()) { 862 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom); 863 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom); 864 } 865 } 866 867 if (Subtarget.hasQPX()) { 868 setOperationAction(ISD::FADD, MVT::v4f64, Legal); 869 setOperationAction(ISD::FSUB, MVT::v4f64, Legal); 870 setOperationAction(ISD::FMUL, MVT::v4f64, Legal); 871 setOperationAction(ISD::FREM, MVT::v4f64, Expand); 872 873 setOperationAction(ISD::FCOPYSIGN, MVT::v4f64, Legal); 874 setOperationAction(ISD::FGETSIGN, MVT::v4f64, Expand); 875 876 setOperationAction(ISD::LOAD , MVT::v4f64, Custom); 877 setOperationAction(ISD::STORE , MVT::v4f64, Custom); 878 879 setTruncStoreAction(MVT::v4f64, MVT::v4f32, Custom); 880 setLoadExtAction(ISD::EXTLOAD, MVT::v4f64, MVT::v4f32, Custom); 881 882 if (!Subtarget.useCRBits()) 883 setOperationAction(ISD::SELECT, MVT::v4f64, Expand); 884 setOperationAction(ISD::VSELECT, MVT::v4f64, Legal); 885 886 setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f64, Legal); 887 setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f64, Expand); 888 setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f64, Expand); 889 setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f64, Expand); 890 setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f64, Custom); 891 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f64, Legal); 892 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f64, Custom); 893 894 setOperationAction(ISD::FP_TO_SINT , MVT::v4f64, Legal); 895 setOperationAction(ISD::FP_TO_UINT , MVT::v4f64, Expand); 896 897 setOperationAction(ISD::FP_ROUND , MVT::v4f32, Legal); 898 setOperationAction(ISD::FP_ROUND_INREG , MVT::v4f32, Expand); 899 setOperationAction(ISD::FP_EXTEND, MVT::v4f64, Legal); 900 901 setOperationAction(ISD::FNEG , MVT::v4f64, Legal); 902 setOperationAction(ISD::FABS , MVT::v4f64, Legal); 903 setOperationAction(ISD::FSIN , MVT::v4f64, Expand); 904 setOperationAction(ISD::FCOS , MVT::v4f64, Expand); 905 setOperationAction(ISD::FPOW , MVT::v4f64, Expand); 906 setOperationAction(ISD::FLOG , MVT::v4f64, Expand); 907 setOperationAction(ISD::FLOG2 , MVT::v4f64, Expand); 908 setOperationAction(ISD::FLOG10 , MVT::v4f64, Expand); 909 setOperationAction(ISD::FEXP , MVT::v4f64, Expand); 910 setOperationAction(ISD::FEXP2 , MVT::v4f64, Expand); 911 912 setOperationAction(ISD::FMINNUM, MVT::v4f64, Legal); 913 setOperationAction(ISD::FMAXNUM, MVT::v4f64, Legal); 914 915 setIndexedLoadAction(ISD::PRE_INC, MVT::v4f64, Legal); 916 setIndexedStoreAction(ISD::PRE_INC, MVT::v4f64, Legal); 917 918 addRegisterClass(MVT::v4f64, &PPC::QFRCRegClass); 919 920 setOperationAction(ISD::FADD, MVT::v4f32, Legal); 921 setOperationAction(ISD::FSUB, MVT::v4f32, Legal); 922 setOperationAction(ISD::FMUL, MVT::v4f32, Legal); 923 setOperationAction(ISD::FREM, MVT::v4f32, Expand); 924 925 setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Legal); 926 setOperationAction(ISD::FGETSIGN, MVT::v4f32, Expand); 927 928 setOperationAction(ISD::LOAD , MVT::v4f32, Custom); 929 setOperationAction(ISD::STORE , MVT::v4f32, Custom); 930 931 if (!Subtarget.useCRBits()) 932 setOperationAction(ISD::SELECT, MVT::v4f32, Expand); 933 setOperationAction(ISD::VSELECT, MVT::v4f32, Legal); 934 935 setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f32, Legal); 936 setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f32, Expand); 937 setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f32, Expand); 938 setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f32, Expand); 939 setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f32, Custom); 940 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal); 941 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom); 942 943 setOperationAction(ISD::FP_TO_SINT , MVT::v4f32, Legal); 944 setOperationAction(ISD::FP_TO_UINT , MVT::v4f32, Expand); 945 946 setOperationAction(ISD::FNEG , MVT::v4f32, Legal); 947 setOperationAction(ISD::FABS , MVT::v4f32, Legal); 948 setOperationAction(ISD::FSIN , MVT::v4f32, Expand); 949 setOperationAction(ISD::FCOS , MVT::v4f32, Expand); 950 setOperationAction(ISD::FPOW , MVT::v4f32, Expand); 951 setOperationAction(ISD::FLOG , MVT::v4f32, Expand); 952 setOperationAction(ISD::FLOG2 , MVT::v4f32, Expand); 953 setOperationAction(ISD::FLOG10 , MVT::v4f32, Expand); 954 setOperationAction(ISD::FEXP , MVT::v4f32, Expand); 955 setOperationAction(ISD::FEXP2 , MVT::v4f32, Expand); 956 957 setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal); 958 setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal); 959 960 setIndexedLoadAction(ISD::PRE_INC, MVT::v4f32, Legal); 961 setIndexedStoreAction(ISD::PRE_INC, MVT::v4f32, Legal); 962 963 addRegisterClass(MVT::v4f32, &PPC::QSRCRegClass); 964 965 setOperationAction(ISD::AND , MVT::v4i1, Legal); 966 setOperationAction(ISD::OR , MVT::v4i1, Legal); 967 setOperationAction(ISD::XOR , MVT::v4i1, Legal); 968 969 if (!Subtarget.useCRBits()) 970 setOperationAction(ISD::SELECT, MVT::v4i1, Expand); 971 setOperationAction(ISD::VSELECT, MVT::v4i1, Legal); 972 973 setOperationAction(ISD::LOAD , MVT::v4i1, Custom); 974 setOperationAction(ISD::STORE , MVT::v4i1, Custom); 975 976 setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4i1, Custom); 977 setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4i1, Expand); 978 setOperationAction(ISD::CONCAT_VECTORS , MVT::v4i1, Expand); 979 setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4i1, Expand); 980 setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4i1, Custom); 981 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i1, Expand); 982 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i1, Custom); 983 984 setOperationAction(ISD::SINT_TO_FP, MVT::v4i1, Custom); 985 setOperationAction(ISD::UINT_TO_FP, MVT::v4i1, Custom); 986 987 addRegisterClass(MVT::v4i1, &PPC::QBRCRegClass); 988 989 setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal); 990 setOperationAction(ISD::FCEIL, MVT::v4f64, Legal); 991 setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal); 992 setOperationAction(ISD::FROUND, MVT::v4f64, Legal); 993 994 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal); 995 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal); 996 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal); 997 setOperationAction(ISD::FROUND, MVT::v4f32, Legal); 998 999 setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Expand); 1000 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand); 1001 1002 // These need to set FE_INEXACT, and so cannot be vectorized here. 1003 setOperationAction(ISD::FRINT, MVT::v4f64, Expand); 1004 setOperationAction(ISD::FRINT, MVT::v4f32, Expand); 1005 1006 if (TM.Options.UnsafeFPMath) { 1007 setOperationAction(ISD::FDIV, MVT::v4f64, Legal); 1008 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal); 1009 1010 setOperationAction(ISD::FDIV, MVT::v4f32, Legal); 1011 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal); 1012 } else { 1013 setOperationAction(ISD::FDIV, MVT::v4f64, Expand); 1014 setOperationAction(ISD::FSQRT, MVT::v4f64, Expand); 1015 1016 setOperationAction(ISD::FDIV, MVT::v4f32, Expand); 1017 setOperationAction(ISD::FSQRT, MVT::v4f32, Expand); 1018 } 1019 } 1020 1021 if (Subtarget.has64BitSupport()) 1022 setOperationAction(ISD::PREFETCH, MVT::Other, Legal); 1023 1024 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, isPPC64 ? Legal : Custom); 1025 1026 if (!isPPC64) { 1027 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Expand); 1028 setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand); 1029 } 1030 1031 setBooleanContents(ZeroOrOneBooleanContent); 1032 1033 if (Subtarget.hasAltivec()) { 1034 // Altivec instructions set fields to all zeros or all ones. 1035 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent); 1036 } 1037 1038 if (!isPPC64) { 1039 // These libcalls are not available in 32-bit. 1040 setLibcallName(RTLIB::SHL_I128, nullptr); 1041 setLibcallName(RTLIB::SRL_I128, nullptr); 1042 setLibcallName(RTLIB::SRA_I128, nullptr); 1043 } 1044 1045 setStackPointerRegisterToSaveRestore(isPPC64 ? PPC::X1 : PPC::R1); 1046 1047 // We have target-specific dag combine patterns for the following nodes: 1048 setTargetDAGCombine(ISD::ADD); 1049 setTargetDAGCombine(ISD::SHL); 1050 setTargetDAGCombine(ISD::SRA); 1051 setTargetDAGCombine(ISD::SRL); 1052 setTargetDAGCombine(ISD::SINT_TO_FP); 1053 setTargetDAGCombine(ISD::BUILD_VECTOR); 1054 if (Subtarget.hasFPCVT()) 1055 setTargetDAGCombine(ISD::UINT_TO_FP); 1056 setTargetDAGCombine(ISD::LOAD); 1057 setTargetDAGCombine(ISD::STORE); 1058 setTargetDAGCombine(ISD::BR_CC); 1059 if (Subtarget.useCRBits()) 1060 setTargetDAGCombine(ISD::BRCOND); 1061 setTargetDAGCombine(ISD::BSWAP); 1062 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN); 1063 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN); 1064 setTargetDAGCombine(ISD::INTRINSIC_VOID); 1065 1066 setTargetDAGCombine(ISD::SIGN_EXTEND); 1067 setTargetDAGCombine(ISD::ZERO_EXTEND); 1068 setTargetDAGCombine(ISD::ANY_EXTEND); 1069 1070 setTargetDAGCombine(ISD::TRUNCATE); 1071 1072 if (Subtarget.useCRBits()) { 1073 setTargetDAGCombine(ISD::TRUNCATE); 1074 setTargetDAGCombine(ISD::SETCC); 1075 setTargetDAGCombine(ISD::SELECT_CC); 1076 } 1077 1078 // Use reciprocal estimates. 1079 if (TM.Options.UnsafeFPMath) { 1080 setTargetDAGCombine(ISD::FDIV); 1081 setTargetDAGCombine(ISD::FSQRT); 1082 } 1083 1084 // Darwin long double math library functions have $LDBL128 appended. 1085 if (Subtarget.isDarwin()) { 1086 setLibcallName(RTLIB::COS_PPCF128, "cosl$LDBL128"); 1087 setLibcallName(RTLIB::POW_PPCF128, "powl$LDBL128"); 1088 setLibcallName(RTLIB::REM_PPCF128, "fmodl$LDBL128"); 1089 setLibcallName(RTLIB::SIN_PPCF128, "sinl$LDBL128"); 1090 setLibcallName(RTLIB::SQRT_PPCF128, "sqrtl$LDBL128"); 1091 setLibcallName(RTLIB::LOG_PPCF128, "logl$LDBL128"); 1092 setLibcallName(RTLIB::LOG2_PPCF128, "log2l$LDBL128"); 1093 setLibcallName(RTLIB::LOG10_PPCF128, "log10l$LDBL128"); 1094 setLibcallName(RTLIB::EXP_PPCF128, "expl$LDBL128"); 1095 setLibcallName(RTLIB::EXP2_PPCF128, "exp2l$LDBL128"); 1096 } 1097 1098 if (EnableQuadPrecision) { 1099 setLibcallName(RTLIB::LOG_F128, "logf128"); 1100 setLibcallName(RTLIB::LOG2_F128, "log2f128"); 1101 setLibcallName(RTLIB::LOG10_F128, "log10f128"); 1102 setLibcallName(RTLIB::EXP_F128, "expf128"); 1103 setLibcallName(RTLIB::EXP2_F128, "exp2f128"); 1104 setLibcallName(RTLIB::SIN_F128, "sinf128"); 1105 setLibcallName(RTLIB::COS_F128, "cosf128"); 1106 setLibcallName(RTLIB::POW_F128, "powf128"); 1107 setLibcallName(RTLIB::FMIN_F128, "fminf128"); 1108 setLibcallName(RTLIB::FMAX_F128, "fmaxf128"); 1109 setLibcallName(RTLIB::POWI_F128, "__powikf2"); 1110 setLibcallName(RTLIB::REM_F128, "fmodf128"); 1111 } 1112 1113 // With 32 condition bits, we don't need to sink (and duplicate) compares 1114 // aggressively in CodeGenPrep. 1115 if (Subtarget.useCRBits()) { 1116 setHasMultipleConditionRegisters(); 1117 setJumpIsExpensive(); 1118 } 1119 1120 setMinFunctionAlignment(2); 1121 if (Subtarget.isDarwin()) 1122 setPrefFunctionAlignment(4); 1123 1124 switch (Subtarget.getDarwinDirective()) { 1125 default: break; 1126 case PPC::DIR_970: 1127 case PPC::DIR_A2: 1128 case PPC::DIR_E500: 1129 case PPC::DIR_E500mc: 1130 case PPC::DIR_E5500: 1131 case PPC::DIR_PWR4: 1132 case PPC::DIR_PWR5: 1133 case PPC::DIR_PWR5X: 1134 case PPC::DIR_PWR6: 1135 case PPC::DIR_PWR6X: 1136 case PPC::DIR_PWR7: 1137 case PPC::DIR_PWR8: 1138 case PPC::DIR_PWR9: 1139 setPrefFunctionAlignment(4); 1140 setPrefLoopAlignment(4); 1141 break; 1142 } 1143 1144 if (Subtarget.enableMachineScheduler()) 1145 setSchedulingPreference(Sched::Source); 1146 else 1147 setSchedulingPreference(Sched::Hybrid); 1148 1149 computeRegisterProperties(STI.getRegisterInfo()); 1150 1151 // The Freescale cores do better with aggressive inlining of memcpy and 1152 // friends. GCC uses same threshold of 128 bytes (= 32 word stores). 1153 if (Subtarget.getDarwinDirective() == PPC::DIR_E500mc || 1154 Subtarget.getDarwinDirective() == PPC::DIR_E5500) { 1155 MaxStoresPerMemset = 32; 1156 MaxStoresPerMemsetOptSize = 16; 1157 MaxStoresPerMemcpy = 32; 1158 MaxStoresPerMemcpyOptSize = 8; 1159 MaxStoresPerMemmove = 32; 1160 MaxStoresPerMemmoveOptSize = 8; 1161 } else if (Subtarget.getDarwinDirective() == PPC::DIR_A2) { 1162 // The A2 also benefits from (very) aggressive inlining of memcpy and 1163 // friends. The overhead of a the function call, even when warm, can be 1164 // over one hundred cycles. 1165 MaxStoresPerMemset = 128; 1166 MaxStoresPerMemcpy = 128; 1167 MaxStoresPerMemmove = 128; 1168 MaxLoadsPerMemcmp = 128; 1169 } else { 1170 MaxLoadsPerMemcmp = 8; 1171 MaxLoadsPerMemcmpOptSize = 4; 1172 } 1173 } 1174 1175 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine 1176 /// the desired ByVal argument alignment. 1177 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign, 1178 unsigned MaxMaxAlign) { 1179 if (MaxAlign == MaxMaxAlign) 1180 return; 1181 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) { 1182 if (MaxMaxAlign >= 32 && VTy->getBitWidth() >= 256) 1183 MaxAlign = 32; 1184 else if (VTy->getBitWidth() >= 128 && MaxAlign < 16) 1185 MaxAlign = 16; 1186 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) { 1187 unsigned EltAlign = 0; 1188 getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign); 1189 if (EltAlign > MaxAlign) 1190 MaxAlign = EltAlign; 1191 } else if (StructType *STy = dyn_cast<StructType>(Ty)) { 1192 for (auto *EltTy : STy->elements()) { 1193 unsigned EltAlign = 0; 1194 getMaxByValAlign(EltTy, EltAlign, MaxMaxAlign); 1195 if (EltAlign > MaxAlign) 1196 MaxAlign = EltAlign; 1197 if (MaxAlign == MaxMaxAlign) 1198 break; 1199 } 1200 } 1201 } 1202 1203 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate 1204 /// function arguments in the caller parameter area. 1205 unsigned PPCTargetLowering::getByValTypeAlignment(Type *Ty, 1206 const DataLayout &DL) const { 1207 // Darwin passes everything on 4 byte boundary. 1208 if (Subtarget.isDarwin()) 1209 return 4; 1210 1211 // 16byte and wider vectors are passed on 16byte boundary. 1212 // The rest is 8 on PPC64 and 4 on PPC32 boundary. 1213 unsigned Align = Subtarget.isPPC64() ? 8 : 4; 1214 if (Subtarget.hasAltivec() || Subtarget.hasQPX()) 1215 getMaxByValAlign(Ty, Align, Subtarget.hasQPX() ? 32 : 16); 1216 return Align; 1217 } 1218 1219 unsigned PPCTargetLowering::getNumRegistersForCallingConv(LLVMContext &Context, 1220 CallingConv:: ID CC, 1221 EVT VT) const { 1222 if (Subtarget.hasSPE() && VT == MVT::f64) 1223 return 2; 1224 return PPCTargetLowering::getNumRegisters(Context, VT); 1225 } 1226 1227 MVT PPCTargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context, 1228 CallingConv:: ID CC, 1229 EVT VT) const { 1230 if (Subtarget.hasSPE() && VT == MVT::f64) 1231 return MVT::i32; 1232 return PPCTargetLowering::getRegisterType(Context, VT); 1233 } 1234 1235 bool PPCTargetLowering::useSoftFloat() const { 1236 return Subtarget.useSoftFloat(); 1237 } 1238 1239 bool PPCTargetLowering::hasSPE() const { 1240 return Subtarget.hasSPE(); 1241 } 1242 1243 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const { 1244 switch ((PPCISD::NodeType)Opcode) { 1245 case PPCISD::FIRST_NUMBER: break; 1246 case PPCISD::FSEL: return "PPCISD::FSEL"; 1247 case PPCISD::FCFID: return "PPCISD::FCFID"; 1248 case PPCISD::FCFIDU: return "PPCISD::FCFIDU"; 1249 case PPCISD::FCFIDS: return "PPCISD::FCFIDS"; 1250 case PPCISD::FCFIDUS: return "PPCISD::FCFIDUS"; 1251 case PPCISD::FCTIDZ: return "PPCISD::FCTIDZ"; 1252 case PPCISD::FCTIWZ: return "PPCISD::FCTIWZ"; 1253 case PPCISD::FCTIDUZ: return "PPCISD::FCTIDUZ"; 1254 case PPCISD::FCTIWUZ: return "PPCISD::FCTIWUZ"; 1255 case PPCISD::FP_TO_UINT_IN_VSR: 1256 return "PPCISD::FP_TO_UINT_IN_VSR,"; 1257 case PPCISD::FP_TO_SINT_IN_VSR: 1258 return "PPCISD::FP_TO_SINT_IN_VSR"; 1259 case PPCISD::FRE: return "PPCISD::FRE"; 1260 case PPCISD::FRSQRTE: return "PPCISD::FRSQRTE"; 1261 case PPCISD::STFIWX: return "PPCISD::STFIWX"; 1262 case PPCISD::VMADDFP: return "PPCISD::VMADDFP"; 1263 case PPCISD::VNMSUBFP: return "PPCISD::VNMSUBFP"; 1264 case PPCISD::VPERM: return "PPCISD::VPERM"; 1265 case PPCISD::XXSPLT: return "PPCISD::XXSPLT"; 1266 case PPCISD::VECINSERT: return "PPCISD::VECINSERT"; 1267 case PPCISD::XXREVERSE: return "PPCISD::XXREVERSE"; 1268 case PPCISD::XXPERMDI: return "PPCISD::XXPERMDI"; 1269 case PPCISD::VECSHL: return "PPCISD::VECSHL"; 1270 case PPCISD::CMPB: return "PPCISD::CMPB"; 1271 case PPCISD::Hi: return "PPCISD::Hi"; 1272 case PPCISD::Lo: return "PPCISD::Lo"; 1273 case PPCISD::TOC_ENTRY: return "PPCISD::TOC_ENTRY"; 1274 case PPCISD::ATOMIC_CMP_SWAP_8: return "PPCISD::ATOMIC_CMP_SWAP_8"; 1275 case PPCISD::ATOMIC_CMP_SWAP_16: return "PPCISD::ATOMIC_CMP_SWAP_16"; 1276 case PPCISD::DYNALLOC: return "PPCISD::DYNALLOC"; 1277 case PPCISD::DYNAREAOFFSET: return "PPCISD::DYNAREAOFFSET"; 1278 case PPCISD::GlobalBaseReg: return "PPCISD::GlobalBaseReg"; 1279 case PPCISD::SRL: return "PPCISD::SRL"; 1280 case PPCISD::SRA: return "PPCISD::SRA"; 1281 case PPCISD::SHL: return "PPCISD::SHL"; 1282 case PPCISD::SRA_ADDZE: return "PPCISD::SRA_ADDZE"; 1283 case PPCISD::CALL: return "PPCISD::CALL"; 1284 case PPCISD::CALL_NOP: return "PPCISD::CALL_NOP"; 1285 case PPCISD::MTCTR: return "PPCISD::MTCTR"; 1286 case PPCISD::BCTRL: return "PPCISD::BCTRL"; 1287 case PPCISD::BCTRL_LOAD_TOC: return "PPCISD::BCTRL_LOAD_TOC"; 1288 case PPCISD::RET_FLAG: return "PPCISD::RET_FLAG"; 1289 case PPCISD::READ_TIME_BASE: return "PPCISD::READ_TIME_BASE"; 1290 case PPCISD::EH_SJLJ_SETJMP: return "PPCISD::EH_SJLJ_SETJMP"; 1291 case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP"; 1292 case PPCISD::MFOCRF: return "PPCISD::MFOCRF"; 1293 case PPCISD::MFVSR: return "PPCISD::MFVSR"; 1294 case PPCISD::MTVSRA: return "PPCISD::MTVSRA"; 1295 case PPCISD::MTVSRZ: return "PPCISD::MTVSRZ"; 1296 case PPCISD::SINT_VEC_TO_FP: return "PPCISD::SINT_VEC_TO_FP"; 1297 case PPCISD::UINT_VEC_TO_FP: return "PPCISD::UINT_VEC_TO_FP"; 1298 case PPCISD::ANDIo_1_EQ_BIT: return "PPCISD::ANDIo_1_EQ_BIT"; 1299 case PPCISD::ANDIo_1_GT_BIT: return "PPCISD::ANDIo_1_GT_BIT"; 1300 case PPCISD::VCMP: return "PPCISD::VCMP"; 1301 case PPCISD::VCMPo: return "PPCISD::VCMPo"; 1302 case PPCISD::LBRX: return "PPCISD::LBRX"; 1303 case PPCISD::STBRX: return "PPCISD::STBRX"; 1304 case PPCISD::LFIWAX: return "PPCISD::LFIWAX"; 1305 case PPCISD::LFIWZX: return "PPCISD::LFIWZX"; 1306 case PPCISD::LXSIZX: return "PPCISD::LXSIZX"; 1307 case PPCISD::STXSIX: return "PPCISD::STXSIX"; 1308 case PPCISD::VEXTS: return "PPCISD::VEXTS"; 1309 case PPCISD::SExtVElems: return "PPCISD::SExtVElems"; 1310 case PPCISD::LXVD2X: return "PPCISD::LXVD2X"; 1311 case PPCISD::STXVD2X: return "PPCISD::STXVD2X"; 1312 case PPCISD::ST_VSR_SCAL_INT: 1313 return "PPCISD::ST_VSR_SCAL_INT"; 1314 case PPCISD::COND_BRANCH: return "PPCISD::COND_BRANCH"; 1315 case PPCISD::BDNZ: return "PPCISD::BDNZ"; 1316 case PPCISD::BDZ: return "PPCISD::BDZ"; 1317 case PPCISD::MFFS: return "PPCISD::MFFS"; 1318 case PPCISD::FADDRTZ: return "PPCISD::FADDRTZ"; 1319 case PPCISD::TC_RETURN: return "PPCISD::TC_RETURN"; 1320 case PPCISD::CR6SET: return "PPCISD::CR6SET"; 1321 case PPCISD::CR6UNSET: return "PPCISD::CR6UNSET"; 1322 case PPCISD::PPC32_GOT: return "PPCISD::PPC32_GOT"; 1323 case PPCISD::PPC32_PICGOT: return "PPCISD::PPC32_PICGOT"; 1324 case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA"; 1325 case PPCISD::LD_GOT_TPREL_L: return "PPCISD::LD_GOT_TPREL_L"; 1326 case PPCISD::ADD_TLS: return "PPCISD::ADD_TLS"; 1327 case PPCISD::ADDIS_TLSGD_HA: return "PPCISD::ADDIS_TLSGD_HA"; 1328 case PPCISD::ADDI_TLSGD_L: return "PPCISD::ADDI_TLSGD_L"; 1329 case PPCISD::GET_TLS_ADDR: return "PPCISD::GET_TLS_ADDR"; 1330 case PPCISD::ADDI_TLSGD_L_ADDR: return "PPCISD::ADDI_TLSGD_L_ADDR"; 1331 case PPCISD::ADDIS_TLSLD_HA: return "PPCISD::ADDIS_TLSLD_HA"; 1332 case PPCISD::ADDI_TLSLD_L: return "PPCISD::ADDI_TLSLD_L"; 1333 case PPCISD::GET_TLSLD_ADDR: return "PPCISD::GET_TLSLD_ADDR"; 1334 case PPCISD::ADDI_TLSLD_L_ADDR: return "PPCISD::ADDI_TLSLD_L_ADDR"; 1335 case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA"; 1336 case PPCISD::ADDI_DTPREL_L: return "PPCISD::ADDI_DTPREL_L"; 1337 case PPCISD::VADD_SPLAT: return "PPCISD::VADD_SPLAT"; 1338 case PPCISD::SC: return "PPCISD::SC"; 1339 case PPCISD::CLRBHRB: return "PPCISD::CLRBHRB"; 1340 case PPCISD::MFBHRBE: return "PPCISD::MFBHRBE"; 1341 case PPCISD::RFEBB: return "PPCISD::RFEBB"; 1342 case PPCISD::XXSWAPD: return "PPCISD::XXSWAPD"; 1343 case PPCISD::SWAP_NO_CHAIN: return "PPCISD::SWAP_NO_CHAIN"; 1344 case PPCISD::QVFPERM: return "PPCISD::QVFPERM"; 1345 case PPCISD::QVGPCI: return "PPCISD::QVGPCI"; 1346 case PPCISD::QVALIGNI: return "PPCISD::QVALIGNI"; 1347 case PPCISD::QVESPLATI: return "PPCISD::QVESPLATI"; 1348 case PPCISD::QBFLT: return "PPCISD::QBFLT"; 1349 case PPCISD::QVLFSb: return "PPCISD::QVLFSb"; 1350 case PPCISD::BUILD_FP128: return "PPCISD::BUILD_FP128"; 1351 case PPCISD::EXTSWSLI: return "PPCISD::EXTSWSLI"; 1352 } 1353 return nullptr; 1354 } 1355 1356 EVT PPCTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &C, 1357 EVT VT) const { 1358 if (!VT.isVector()) 1359 return Subtarget.useCRBits() ? MVT::i1 : MVT::i32; 1360 1361 if (Subtarget.hasQPX()) 1362 return EVT::getVectorVT(C, MVT::i1, VT.getVectorNumElements()); 1363 1364 return VT.changeVectorElementTypeToInteger(); 1365 } 1366 1367 bool PPCTargetLowering::enableAggressiveFMAFusion(EVT VT) const { 1368 assert(VT.isFloatingPoint() && "Non-floating-point FMA?"); 1369 return true; 1370 } 1371 1372 //===----------------------------------------------------------------------===// 1373 // Node matching predicates, for use by the tblgen matching code. 1374 //===----------------------------------------------------------------------===// 1375 1376 /// isFloatingPointZero - Return true if this is 0.0 or -0.0. 1377 static bool isFloatingPointZero(SDValue Op) { 1378 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) 1379 return CFP->getValueAPF().isZero(); 1380 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) { 1381 // Maybe this has already been legalized into the constant pool? 1382 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1))) 1383 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal())) 1384 return CFP->getValueAPF().isZero(); 1385 } 1386 return false; 1387 } 1388 1389 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode. Return 1390 /// true if Op is undef or if it matches the specified value. 1391 static bool isConstantOrUndef(int Op, int Val) { 1392 return Op < 0 || Op == Val; 1393 } 1394 1395 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a 1396 /// VPKUHUM instruction. 1397 /// The ShuffleKind distinguishes between big-endian operations with 1398 /// two different inputs (0), either-endian operations with two identical 1399 /// inputs (1), and little-endian operations with two different inputs (2). 1400 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td). 1401 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind, 1402 SelectionDAG &DAG) { 1403 bool IsLE = DAG.getDataLayout().isLittleEndian(); 1404 if (ShuffleKind == 0) { 1405 if (IsLE) 1406 return false; 1407 for (unsigned i = 0; i != 16; ++i) 1408 if (!isConstantOrUndef(N->getMaskElt(i), i*2+1)) 1409 return false; 1410 } else if (ShuffleKind == 2) { 1411 if (!IsLE) 1412 return false; 1413 for (unsigned i = 0; i != 16; ++i) 1414 if (!isConstantOrUndef(N->getMaskElt(i), i*2)) 1415 return false; 1416 } else if (ShuffleKind == 1) { 1417 unsigned j = IsLE ? 0 : 1; 1418 for (unsigned i = 0; i != 8; ++i) 1419 if (!isConstantOrUndef(N->getMaskElt(i), i*2+j) || 1420 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j)) 1421 return false; 1422 } 1423 return true; 1424 } 1425 1426 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a 1427 /// VPKUWUM instruction. 1428 /// The ShuffleKind distinguishes between big-endian operations with 1429 /// two different inputs (0), either-endian operations with two identical 1430 /// inputs (1), and little-endian operations with two different inputs (2). 1431 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td). 1432 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind, 1433 SelectionDAG &DAG) { 1434 bool IsLE = DAG.getDataLayout().isLittleEndian(); 1435 if (ShuffleKind == 0) { 1436 if (IsLE) 1437 return false; 1438 for (unsigned i = 0; i != 16; i += 2) 1439 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+2) || 1440 !isConstantOrUndef(N->getMaskElt(i+1), i*2+3)) 1441 return false; 1442 } else if (ShuffleKind == 2) { 1443 if (!IsLE) 1444 return false; 1445 for (unsigned i = 0; i != 16; i += 2) 1446 if (!isConstantOrUndef(N->getMaskElt(i ), i*2) || 1447 !isConstantOrUndef(N->getMaskElt(i+1), i*2+1)) 1448 return false; 1449 } else if (ShuffleKind == 1) { 1450 unsigned j = IsLE ? 0 : 2; 1451 for (unsigned i = 0; i != 8; i += 2) 1452 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+j) || 1453 !isConstantOrUndef(N->getMaskElt(i+1), i*2+j+1) || 1454 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j) || 1455 !isConstantOrUndef(N->getMaskElt(i+9), i*2+j+1)) 1456 return false; 1457 } 1458 return true; 1459 } 1460 1461 /// isVPKUDUMShuffleMask - Return true if this is the shuffle mask for a 1462 /// VPKUDUM instruction, AND the VPKUDUM instruction exists for the 1463 /// current subtarget. 1464 /// 1465 /// The ShuffleKind distinguishes between big-endian operations with 1466 /// two different inputs (0), either-endian operations with two identical 1467 /// inputs (1), and little-endian operations with two different inputs (2). 1468 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td). 1469 bool PPC::isVPKUDUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind, 1470 SelectionDAG &DAG) { 1471 const PPCSubtarget& Subtarget = 1472 static_cast<const PPCSubtarget&>(DAG.getSubtarget()); 1473 if (!Subtarget.hasP8Vector()) 1474 return false; 1475 1476 bool IsLE = DAG.getDataLayout().isLittleEndian(); 1477 if (ShuffleKind == 0) { 1478 if (IsLE) 1479 return false; 1480 for (unsigned i = 0; i != 16; i += 4) 1481 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+4) || 1482 !isConstantOrUndef(N->getMaskElt(i+1), i*2+5) || 1483 !isConstantOrUndef(N->getMaskElt(i+2), i*2+6) || 1484 !isConstantOrUndef(N->getMaskElt(i+3), i*2+7)) 1485 return false; 1486 } else if (ShuffleKind == 2) { 1487 if (!IsLE) 1488 return false; 1489 for (unsigned i = 0; i != 16; i += 4) 1490 if (!isConstantOrUndef(N->getMaskElt(i ), i*2) || 1491 !isConstantOrUndef(N->getMaskElt(i+1), i*2+1) || 1492 !isConstantOrUndef(N->getMaskElt(i+2), i*2+2) || 1493 !isConstantOrUndef(N->getMaskElt(i+3), i*2+3)) 1494 return false; 1495 } else if (ShuffleKind == 1) { 1496 unsigned j = IsLE ? 0 : 4; 1497 for (unsigned i = 0; i != 8; i += 4) 1498 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+j) || 1499 !isConstantOrUndef(N->getMaskElt(i+1), i*2+j+1) || 1500 !isConstantOrUndef(N->getMaskElt(i+2), i*2+j+2) || 1501 !isConstantOrUndef(N->getMaskElt(i+3), i*2+j+3) || 1502 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j) || 1503 !isConstantOrUndef(N->getMaskElt(i+9), i*2+j+1) || 1504 !isConstantOrUndef(N->getMaskElt(i+10), i*2+j+2) || 1505 !isConstantOrUndef(N->getMaskElt(i+11), i*2+j+3)) 1506 return false; 1507 } 1508 return true; 1509 } 1510 1511 /// isVMerge - Common function, used to match vmrg* shuffles. 1512 /// 1513 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize, 1514 unsigned LHSStart, unsigned RHSStart) { 1515 if (N->getValueType(0) != MVT::v16i8) 1516 return false; 1517 assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) && 1518 "Unsupported merge size!"); 1519 1520 for (unsigned i = 0; i != 8/UnitSize; ++i) // Step over units 1521 for (unsigned j = 0; j != UnitSize; ++j) { // Step over bytes within unit 1522 if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j), 1523 LHSStart+j+i*UnitSize) || 1524 !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j), 1525 RHSStart+j+i*UnitSize)) 1526 return false; 1527 } 1528 return true; 1529 } 1530 1531 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for 1532 /// a VMRGL* instruction with the specified unit size (1,2 or 4 bytes). 1533 /// The ShuffleKind distinguishes between big-endian merges with two 1534 /// different inputs (0), either-endian merges with two identical inputs (1), 1535 /// and little-endian merges with two different inputs (2). For the latter, 1536 /// the input operands are swapped (see PPCInstrAltivec.td). 1537 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize, 1538 unsigned ShuffleKind, SelectionDAG &DAG) { 1539 if (DAG.getDataLayout().isLittleEndian()) { 1540 if (ShuffleKind == 1) // unary 1541 return isVMerge(N, UnitSize, 0, 0); 1542 else if (ShuffleKind == 2) // swapped 1543 return isVMerge(N, UnitSize, 0, 16); 1544 else 1545 return false; 1546 } else { 1547 if (ShuffleKind == 1) // unary 1548 return isVMerge(N, UnitSize, 8, 8); 1549 else if (ShuffleKind == 0) // normal 1550 return isVMerge(N, UnitSize, 8, 24); 1551 else 1552 return false; 1553 } 1554 } 1555 1556 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for 1557 /// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes). 1558 /// The ShuffleKind distinguishes between big-endian merges with two 1559 /// different inputs (0), either-endian merges with two identical inputs (1), 1560 /// and little-endian merges with two different inputs (2). For the latter, 1561 /// the input operands are swapped (see PPCInstrAltivec.td). 1562 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize, 1563 unsigned ShuffleKind, SelectionDAG &DAG) { 1564 if (DAG.getDataLayout().isLittleEndian()) { 1565 if (ShuffleKind == 1) // unary 1566 return isVMerge(N, UnitSize, 8, 8); 1567 else if (ShuffleKind == 2) // swapped 1568 return isVMerge(N, UnitSize, 8, 24); 1569 else 1570 return false; 1571 } else { 1572 if (ShuffleKind == 1) // unary 1573 return isVMerge(N, UnitSize, 0, 0); 1574 else if (ShuffleKind == 0) // normal 1575 return isVMerge(N, UnitSize, 0, 16); 1576 else 1577 return false; 1578 } 1579 } 1580 1581 /** 1582 * Common function used to match vmrgew and vmrgow shuffles 1583 * 1584 * The indexOffset determines whether to look for even or odd words in 1585 * the shuffle mask. This is based on the of the endianness of the target 1586 * machine. 1587 * - Little Endian: 1588 * - Use offset of 0 to check for odd elements 1589 * - Use offset of 4 to check for even elements 1590 * - Big Endian: 1591 * - Use offset of 0 to check for even elements 1592 * - Use offset of 4 to check for odd elements 1593 * A detailed description of the vector element ordering for little endian and 1594 * big endian can be found at 1595 * http://www.ibm.com/developerworks/library/l-ibm-xl-c-cpp-compiler/index.html 1596 * Targeting your applications - what little endian and big endian IBM XL C/C++ 1597 * compiler differences mean to you 1598 * 1599 * The mask to the shuffle vector instruction specifies the indices of the 1600 * elements from the two input vectors to place in the result. The elements are 1601 * numbered in array-access order, starting with the first vector. These vectors 1602 * are always of type v16i8, thus each vector will contain 16 elements of size 1603 * 8. More info on the shuffle vector can be found in the 1604 * http://llvm.org/docs/LangRef.html#shufflevector-instruction 1605 * Language Reference. 1606 * 1607 * The RHSStartValue indicates whether the same input vectors are used (unary) 1608 * or two different input vectors are used, based on the following: 1609 * - If the instruction uses the same vector for both inputs, the range of the 1610 * indices will be 0 to 15. In this case, the RHSStart value passed should 1611 * be 0. 1612 * - If the instruction has two different vectors then the range of the 1613 * indices will be 0 to 31. In this case, the RHSStart value passed should 1614 * be 16 (indices 0-15 specify elements in the first vector while indices 16 1615 * to 31 specify elements in the second vector). 1616 * 1617 * \param[in] N The shuffle vector SD Node to analyze 1618 * \param[in] IndexOffset Specifies whether to look for even or odd elements 1619 * \param[in] RHSStartValue Specifies the starting index for the righthand input 1620 * vector to the shuffle_vector instruction 1621 * \return true iff this shuffle vector represents an even or odd word merge 1622 */ 1623 static bool isVMerge(ShuffleVectorSDNode *N, unsigned IndexOffset, 1624 unsigned RHSStartValue) { 1625 if (N->getValueType(0) != MVT::v16i8) 1626 return false; 1627 1628 for (unsigned i = 0; i < 2; ++i) 1629 for (unsigned j = 0; j < 4; ++j) 1630 if (!isConstantOrUndef(N->getMaskElt(i*4+j), 1631 i*RHSStartValue+j+IndexOffset) || 1632 !isConstantOrUndef(N->getMaskElt(i*4+j+8), 1633 i*RHSStartValue+j+IndexOffset+8)) 1634 return false; 1635 return true; 1636 } 1637 1638 /** 1639 * Determine if the specified shuffle mask is suitable for the vmrgew or 1640 * vmrgow instructions. 1641 * 1642 * \param[in] N The shuffle vector SD Node to analyze 1643 * \param[in] CheckEven Check for an even merge (true) or an odd merge (false) 1644 * \param[in] ShuffleKind Identify the type of merge: 1645 * - 0 = big-endian merge with two different inputs; 1646 * - 1 = either-endian merge with two identical inputs; 1647 * - 2 = little-endian merge with two different inputs (inputs are swapped for 1648 * little-endian merges). 1649 * \param[in] DAG The current SelectionDAG 1650 * \return true iff this shuffle mask 1651 */ 1652 bool PPC::isVMRGEOShuffleMask(ShuffleVectorSDNode *N, bool CheckEven, 1653 unsigned ShuffleKind, SelectionDAG &DAG) { 1654 if (DAG.getDataLayout().isLittleEndian()) { 1655 unsigned indexOffset = CheckEven ? 4 : 0; 1656 if (ShuffleKind == 1) // Unary 1657 return isVMerge(N, indexOffset, 0); 1658 else if (ShuffleKind == 2) // swapped 1659 return isVMerge(N, indexOffset, 16); 1660 else 1661 return false; 1662 } 1663 else { 1664 unsigned indexOffset = CheckEven ? 0 : 4; 1665 if (ShuffleKind == 1) // Unary 1666 return isVMerge(N, indexOffset, 0); 1667 else if (ShuffleKind == 0) // Normal 1668 return isVMerge(N, indexOffset, 16); 1669 else 1670 return false; 1671 } 1672 return false; 1673 } 1674 1675 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift 1676 /// amount, otherwise return -1. 1677 /// The ShuffleKind distinguishes between big-endian operations with two 1678 /// different inputs (0), either-endian operations with two identical inputs 1679 /// (1), and little-endian operations with two different inputs (2). For the 1680 /// latter, the input operands are swapped (see PPCInstrAltivec.td). 1681 int PPC::isVSLDOIShuffleMask(SDNode *N, unsigned ShuffleKind, 1682 SelectionDAG &DAG) { 1683 if (N->getValueType(0) != MVT::v16i8) 1684 return -1; 1685 1686 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 1687 1688 // Find the first non-undef value in the shuffle mask. 1689 unsigned i; 1690 for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i) 1691 /*search*/; 1692 1693 if (i == 16) return -1; // all undef. 1694 1695 // Otherwise, check to see if the rest of the elements are consecutively 1696 // numbered from this value. 1697 unsigned ShiftAmt = SVOp->getMaskElt(i); 1698 if (ShiftAmt < i) return -1; 1699 1700 ShiftAmt -= i; 1701 bool isLE = DAG.getDataLayout().isLittleEndian(); 1702 1703 if ((ShuffleKind == 0 && !isLE) || (ShuffleKind == 2 && isLE)) { 1704 // Check the rest of the elements to see if they are consecutive. 1705 for (++i; i != 16; ++i) 1706 if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i)) 1707 return -1; 1708 } else if (ShuffleKind == 1) { 1709 // Check the rest of the elements to see if they are consecutive. 1710 for (++i; i != 16; ++i) 1711 if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15)) 1712 return -1; 1713 } else 1714 return -1; 1715 1716 if (isLE) 1717 ShiftAmt = 16 - ShiftAmt; 1718 1719 return ShiftAmt; 1720 } 1721 1722 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand 1723 /// specifies a splat of a single element that is suitable for input to 1724 /// VSPLTB/VSPLTH/VSPLTW. 1725 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) { 1726 assert(N->getValueType(0) == MVT::v16i8 && 1727 (EltSize == 1 || EltSize == 2 || EltSize == 4)); 1728 1729 // The consecutive indices need to specify an element, not part of two 1730 // different elements. So abandon ship early if this isn't the case. 1731 if (N->getMaskElt(0) % EltSize != 0) 1732 return false; 1733 1734 // This is a splat operation if each element of the permute is the same, and 1735 // if the value doesn't reference the second vector. 1736 unsigned ElementBase = N->getMaskElt(0); 1737 1738 // FIXME: Handle UNDEF elements too! 1739 if (ElementBase >= 16) 1740 return false; 1741 1742 // Check that the indices are consecutive, in the case of a multi-byte element 1743 // splatted with a v16i8 mask. 1744 for (unsigned i = 1; i != EltSize; ++i) 1745 if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase)) 1746 return false; 1747 1748 for (unsigned i = EltSize, e = 16; i != e; i += EltSize) { 1749 if (N->getMaskElt(i) < 0) continue; 1750 for (unsigned j = 0; j != EltSize; ++j) 1751 if (N->getMaskElt(i+j) != N->getMaskElt(j)) 1752 return false; 1753 } 1754 return true; 1755 } 1756 1757 /// Check that the mask is shuffling N byte elements. Within each N byte 1758 /// element of the mask, the indices could be either in increasing or 1759 /// decreasing order as long as they are consecutive. 1760 /// \param[in] N the shuffle vector SD Node to analyze 1761 /// \param[in] Width the element width in bytes, could be 2/4/8/16 (HalfWord/ 1762 /// Word/DoubleWord/QuadWord). 1763 /// \param[in] StepLen the delta indices number among the N byte element, if 1764 /// the mask is in increasing/decreasing order then it is 1/-1. 1765 /// \return true iff the mask is shuffling N byte elements. 1766 static bool isNByteElemShuffleMask(ShuffleVectorSDNode *N, unsigned Width, 1767 int StepLen) { 1768 assert((Width == 2 || Width == 4 || Width == 8 || Width == 16) && 1769 "Unexpected element width."); 1770 assert((StepLen == 1 || StepLen == -1) && "Unexpected element width."); 1771 1772 unsigned NumOfElem = 16 / Width; 1773 unsigned MaskVal[16]; // Width is never greater than 16 1774 for (unsigned i = 0; i < NumOfElem; ++i) { 1775 MaskVal[0] = N->getMaskElt(i * Width); 1776 if ((StepLen == 1) && (MaskVal[0] % Width)) { 1777 return false; 1778 } else if ((StepLen == -1) && ((MaskVal[0] + 1) % Width)) { 1779 return false; 1780 } 1781 1782 for (unsigned int j = 1; j < Width; ++j) { 1783 MaskVal[j] = N->getMaskElt(i * Width + j); 1784 if (MaskVal[j] != MaskVal[j-1] + StepLen) { 1785 return false; 1786 } 1787 } 1788 } 1789 1790 return true; 1791 } 1792 1793 bool PPC::isXXINSERTWMask(ShuffleVectorSDNode *N, unsigned &ShiftElts, 1794 unsigned &InsertAtByte, bool &Swap, bool IsLE) { 1795 if (!isNByteElemShuffleMask(N, 4, 1)) 1796 return false; 1797 1798 // Now we look at mask elements 0,4,8,12 1799 unsigned M0 = N->getMaskElt(0) / 4; 1800 unsigned M1 = N->getMaskElt(4) / 4; 1801 unsigned M2 = N->getMaskElt(8) / 4; 1802 unsigned M3 = N->getMaskElt(12) / 4; 1803 unsigned LittleEndianShifts[] = { 2, 1, 0, 3 }; 1804 unsigned BigEndianShifts[] = { 3, 0, 1, 2 }; 1805 1806 // Below, let H and L be arbitrary elements of the shuffle mask 1807 // where H is in the range [4,7] and L is in the range [0,3]. 1808 // H, 1, 2, 3 or L, 5, 6, 7 1809 if ((M0 > 3 && M1 == 1 && M2 == 2 && M3 == 3) || 1810 (M0 < 4 && M1 == 5 && M2 == 6 && M3 == 7)) { 1811 ShiftElts = IsLE ? LittleEndianShifts[M0 & 0x3] : BigEndianShifts[M0 & 0x3]; 1812 InsertAtByte = IsLE ? 12 : 0; 1813 Swap = M0 < 4; 1814 return true; 1815 } 1816 // 0, H, 2, 3 or 4, L, 6, 7 1817 if ((M1 > 3 && M0 == 0 && M2 == 2 && M3 == 3) || 1818 (M1 < 4 && M0 == 4 && M2 == 6 && M3 == 7)) { 1819 ShiftElts = IsLE ? LittleEndianShifts[M1 & 0x3] : BigEndianShifts[M1 & 0x3]; 1820 InsertAtByte = IsLE ? 8 : 4; 1821 Swap = M1 < 4; 1822 return true; 1823 } 1824 // 0, 1, H, 3 or 4, 5, L, 7 1825 if ((M2 > 3 && M0 == 0 && M1 == 1 && M3 == 3) || 1826 (M2 < 4 && M0 == 4 && M1 == 5 && M3 == 7)) { 1827 ShiftElts = IsLE ? LittleEndianShifts[M2 & 0x3] : BigEndianShifts[M2 & 0x3]; 1828 InsertAtByte = IsLE ? 4 : 8; 1829 Swap = M2 < 4; 1830 return true; 1831 } 1832 // 0, 1, 2, H or 4, 5, 6, L 1833 if ((M3 > 3 && M0 == 0 && M1 == 1 && M2 == 2) || 1834 (M3 < 4 && M0 == 4 && M1 == 5 && M2 == 6)) { 1835 ShiftElts = IsLE ? LittleEndianShifts[M3 & 0x3] : BigEndianShifts[M3 & 0x3]; 1836 InsertAtByte = IsLE ? 0 : 12; 1837 Swap = M3 < 4; 1838 return true; 1839 } 1840 1841 // If both vector operands for the shuffle are the same vector, the mask will 1842 // contain only elements from the first one and the second one will be undef. 1843 if (N->getOperand(1).isUndef()) { 1844 ShiftElts = 0; 1845 Swap = true; 1846 unsigned XXINSERTWSrcElem = IsLE ? 2 : 1; 1847 if (M0 == XXINSERTWSrcElem && M1 == 1 && M2 == 2 && M3 == 3) { 1848 InsertAtByte = IsLE ? 12 : 0; 1849 return true; 1850 } 1851 if (M0 == 0 && M1 == XXINSERTWSrcElem && M2 == 2 && M3 == 3) { 1852 InsertAtByte = IsLE ? 8 : 4; 1853 return true; 1854 } 1855 if (M0 == 0 && M1 == 1 && M2 == XXINSERTWSrcElem && M3 == 3) { 1856 InsertAtByte = IsLE ? 4 : 8; 1857 return true; 1858 } 1859 if (M0 == 0 && M1 == 1 && M2 == 2 && M3 == XXINSERTWSrcElem) { 1860 InsertAtByte = IsLE ? 0 : 12; 1861 return true; 1862 } 1863 } 1864 1865 return false; 1866 } 1867 1868 bool PPC::isXXSLDWIShuffleMask(ShuffleVectorSDNode *N, unsigned &ShiftElts, 1869 bool &Swap, bool IsLE) { 1870 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8"); 1871 // Ensure each byte index of the word is consecutive. 1872 if (!isNByteElemShuffleMask(N, 4, 1)) 1873 return false; 1874 1875 // Now we look at mask elements 0,4,8,12, which are the beginning of words. 1876 unsigned M0 = N->getMaskElt(0) / 4; 1877 unsigned M1 = N->getMaskElt(4) / 4; 1878 unsigned M2 = N->getMaskElt(8) / 4; 1879 unsigned M3 = N->getMaskElt(12) / 4; 1880 1881 // If both vector operands for the shuffle are the same vector, the mask will 1882 // contain only elements from the first one and the second one will be undef. 1883 if (N->getOperand(1).isUndef()) { 1884 assert(M0 < 4 && "Indexing into an undef vector?"); 1885 if (M1 != (M0 + 1) % 4 || M2 != (M1 + 1) % 4 || M3 != (M2 + 1) % 4) 1886 return false; 1887 1888 ShiftElts = IsLE ? (4 - M0) % 4 : M0; 1889 Swap = false; 1890 return true; 1891 } 1892 1893 // Ensure each word index of the ShuffleVector Mask is consecutive. 1894 if (M1 != (M0 + 1) % 8 || M2 != (M1 + 1) % 8 || M3 != (M2 + 1) % 8) 1895 return false; 1896 1897 if (IsLE) { 1898 if (M0 == 0 || M0 == 7 || M0 == 6 || M0 == 5) { 1899 // Input vectors don't need to be swapped if the leading element 1900 // of the result is one of the 3 left elements of the second vector 1901 // (or if there is no shift to be done at all). 1902 Swap = false; 1903 ShiftElts = (8 - M0) % 8; 1904 } else if (M0 == 4 || M0 == 3 || M0 == 2 || M0 == 1) { 1905 // Input vectors need to be swapped if the leading element 1906 // of the result is one of the 3 left elements of the first vector 1907 // (or if we're shifting by 4 - thereby simply swapping the vectors). 1908 Swap = true; 1909 ShiftElts = (4 - M0) % 4; 1910 } 1911 1912 return true; 1913 } else { // BE 1914 if (M0 == 0 || M0 == 1 || M0 == 2 || M0 == 3) { 1915 // Input vectors don't need to be swapped if the leading element 1916 // of the result is one of the 4 elements of the first vector. 1917 Swap = false; 1918 ShiftElts = M0; 1919 } else if (M0 == 4 || M0 == 5 || M0 == 6 || M0 == 7) { 1920 // Input vectors need to be swapped if the leading element 1921 // of the result is one of the 4 elements of the right vector. 1922 Swap = true; 1923 ShiftElts = M0 - 4; 1924 } 1925 1926 return true; 1927 } 1928 } 1929 1930 bool static isXXBRShuffleMaskHelper(ShuffleVectorSDNode *N, int Width) { 1931 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8"); 1932 1933 if (!isNByteElemShuffleMask(N, Width, -1)) 1934 return false; 1935 1936 for (int i = 0; i < 16; i += Width) 1937 if (N->getMaskElt(i) != i + Width - 1) 1938 return false; 1939 1940 return true; 1941 } 1942 1943 bool PPC::isXXBRHShuffleMask(ShuffleVectorSDNode *N) { 1944 return isXXBRShuffleMaskHelper(N, 2); 1945 } 1946 1947 bool PPC::isXXBRWShuffleMask(ShuffleVectorSDNode *N) { 1948 return isXXBRShuffleMaskHelper(N, 4); 1949 } 1950 1951 bool PPC::isXXBRDShuffleMask(ShuffleVectorSDNode *N) { 1952 return isXXBRShuffleMaskHelper(N, 8); 1953 } 1954 1955 bool PPC::isXXBRQShuffleMask(ShuffleVectorSDNode *N) { 1956 return isXXBRShuffleMaskHelper(N, 16); 1957 } 1958 1959 /// Can node \p N be lowered to an XXPERMDI instruction? If so, set \p Swap 1960 /// if the inputs to the instruction should be swapped and set \p DM to the 1961 /// value for the immediate. 1962 /// Specifically, set \p Swap to true only if \p N can be lowered to XXPERMDI 1963 /// AND element 0 of the result comes from the first input (LE) or second input 1964 /// (BE). Set \p DM to the calculated result (0-3) only if \p N can be lowered. 1965 /// \return true iff the given mask of shuffle node \p N is a XXPERMDI shuffle 1966 /// mask. 1967 bool PPC::isXXPERMDIShuffleMask(ShuffleVectorSDNode *N, unsigned &DM, 1968 bool &Swap, bool IsLE) { 1969 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8"); 1970 1971 // Ensure each byte index of the double word is consecutive. 1972 if (!isNByteElemShuffleMask(N, 8, 1)) 1973 return false; 1974 1975 unsigned M0 = N->getMaskElt(0) / 8; 1976 unsigned M1 = N->getMaskElt(8) / 8; 1977 assert(((M0 | M1) < 4) && "A mask element out of bounds?"); 1978 1979 // If both vector operands for the shuffle are the same vector, the mask will 1980 // contain only elements from the first one and the second one will be undef. 1981 if (N->getOperand(1).isUndef()) { 1982 if ((M0 | M1) < 2) { 1983 DM = IsLE ? (((~M1) & 1) << 1) + ((~M0) & 1) : (M0 << 1) + (M1 & 1); 1984 Swap = false; 1985 return true; 1986 } else 1987 return false; 1988 } 1989 1990 if (IsLE) { 1991 if (M0 > 1 && M1 < 2) { 1992 Swap = false; 1993 } else if (M0 < 2 && M1 > 1) { 1994 M0 = (M0 + 2) % 4; 1995 M1 = (M1 + 2) % 4; 1996 Swap = true; 1997 } else 1998 return false; 1999 2000 // Note: if control flow comes here that means Swap is already set above 2001 DM = (((~M1) & 1) << 1) + ((~M0) & 1); 2002 return true; 2003 } else { // BE 2004 if (M0 < 2 && M1 > 1) { 2005 Swap = false; 2006 } else if (M0 > 1 && M1 < 2) { 2007 M0 = (M0 + 2) % 4; 2008 M1 = (M1 + 2) % 4; 2009 Swap = true; 2010 } else 2011 return false; 2012 2013 // Note: if control flow comes here that means Swap is already set above 2014 DM = (M0 << 1) + (M1 & 1); 2015 return true; 2016 } 2017 } 2018 2019 2020 /// getVSPLTImmediate - Return the appropriate VSPLT* immediate to splat the 2021 /// specified isSplatShuffleMask VECTOR_SHUFFLE mask. 2022 unsigned PPC::getVSPLTImmediate(SDNode *N, unsigned EltSize, 2023 SelectionDAG &DAG) { 2024 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 2025 assert(isSplatShuffleMask(SVOp, EltSize)); 2026 if (DAG.getDataLayout().isLittleEndian()) 2027 return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize); 2028 else 2029 return SVOp->getMaskElt(0) / EltSize; 2030 } 2031 2032 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed 2033 /// by using a vspltis[bhw] instruction of the specified element size, return 2034 /// the constant being splatted. The ByteSize field indicates the number of 2035 /// bytes of each element [124] -> [bhw]. 2036 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) { 2037 SDValue OpVal(nullptr, 0); 2038 2039 // If ByteSize of the splat is bigger than the element size of the 2040 // build_vector, then we have a case where we are checking for a splat where 2041 // multiple elements of the buildvector are folded together into a single 2042 // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8). 2043 unsigned EltSize = 16/N->getNumOperands(); 2044 if (EltSize < ByteSize) { 2045 unsigned Multiple = ByteSize/EltSize; // Number of BV entries per spltval. 2046 SDValue UniquedVals[4]; 2047 assert(Multiple > 1 && Multiple <= 4 && "How can this happen?"); 2048 2049 // See if all of the elements in the buildvector agree across. 2050 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 2051 if (N->getOperand(i).isUndef()) continue; 2052 // If the element isn't a constant, bail fully out. 2053 if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue(); 2054 2055 if (!UniquedVals[i&(Multiple-1)].getNode()) 2056 UniquedVals[i&(Multiple-1)] = N->getOperand(i); 2057 else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i)) 2058 return SDValue(); // no match. 2059 } 2060 2061 // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains 2062 // either constant or undef values that are identical for each chunk. See 2063 // if these chunks can form into a larger vspltis*. 2064 2065 // Check to see if all of the leading entries are either 0 or -1. If 2066 // neither, then this won't fit into the immediate field. 2067 bool LeadingZero = true; 2068 bool LeadingOnes = true; 2069 for (unsigned i = 0; i != Multiple-1; ++i) { 2070 if (!UniquedVals[i].getNode()) continue; // Must have been undefs. 2071 2072 LeadingZero &= isNullConstant(UniquedVals[i]); 2073 LeadingOnes &= isAllOnesConstant(UniquedVals[i]); 2074 } 2075 // Finally, check the least significant entry. 2076 if (LeadingZero) { 2077 if (!UniquedVals[Multiple-1].getNode()) 2078 return DAG.getTargetConstant(0, SDLoc(N), MVT::i32); // 0,0,0,undef 2079 int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue(); 2080 if (Val < 16) // 0,0,0,4 -> vspltisw(4) 2081 return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32); 2082 } 2083 if (LeadingOnes) { 2084 if (!UniquedVals[Multiple-1].getNode()) 2085 return DAG.getTargetConstant(~0U, SDLoc(N), MVT::i32); // -1,-1,-1,undef 2086 int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue(); 2087 if (Val >= -16) // -1,-1,-1,-2 -> vspltisw(-2) 2088 return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32); 2089 } 2090 2091 return SDValue(); 2092 } 2093 2094 // Check to see if this buildvec has a single non-undef value in its elements. 2095 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 2096 if (N->getOperand(i).isUndef()) continue; 2097 if (!OpVal.getNode()) 2098 OpVal = N->getOperand(i); 2099 else if (OpVal != N->getOperand(i)) 2100 return SDValue(); 2101 } 2102 2103 if (!OpVal.getNode()) return SDValue(); // All UNDEF: use implicit def. 2104 2105 unsigned ValSizeInBytes = EltSize; 2106 uint64_t Value = 0; 2107 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) { 2108 Value = CN->getZExtValue(); 2109 } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) { 2110 assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!"); 2111 Value = FloatToBits(CN->getValueAPF().convertToFloat()); 2112 } 2113 2114 // If the splat value is larger than the element value, then we can never do 2115 // this splat. The only case that we could fit the replicated bits into our 2116 // immediate field for would be zero, and we prefer to use vxor for it. 2117 if (ValSizeInBytes < ByteSize) return SDValue(); 2118 2119 // If the element value is larger than the splat value, check if it consists 2120 // of a repeated bit pattern of size ByteSize. 2121 if (!APInt(ValSizeInBytes * 8, Value).isSplat(ByteSize * 8)) 2122 return SDValue(); 2123 2124 // Properly sign extend the value. 2125 int MaskVal = SignExtend32(Value, ByteSize * 8); 2126 2127 // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros. 2128 if (MaskVal == 0) return SDValue(); 2129 2130 // Finally, if this value fits in a 5 bit sext field, return it 2131 if (SignExtend32<5>(MaskVal) == MaskVal) 2132 return DAG.getTargetConstant(MaskVal, SDLoc(N), MVT::i32); 2133 return SDValue(); 2134 } 2135 2136 /// isQVALIGNIShuffleMask - If this is a qvaligni shuffle mask, return the shift 2137 /// amount, otherwise return -1. 2138 int PPC::isQVALIGNIShuffleMask(SDNode *N) { 2139 EVT VT = N->getValueType(0); 2140 if (VT != MVT::v4f64 && VT != MVT::v4f32 && VT != MVT::v4i1) 2141 return -1; 2142 2143 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 2144 2145 // Find the first non-undef value in the shuffle mask. 2146 unsigned i; 2147 for (i = 0; i != 4 && SVOp->getMaskElt(i) < 0; ++i) 2148 /*search*/; 2149 2150 if (i == 4) return -1; // all undef. 2151 2152 // Otherwise, check to see if the rest of the elements are consecutively 2153 // numbered from this value. 2154 unsigned ShiftAmt = SVOp->getMaskElt(i); 2155 if (ShiftAmt < i) return -1; 2156 ShiftAmt -= i; 2157 2158 // Check the rest of the elements to see if they are consecutive. 2159 for (++i; i != 4; ++i) 2160 if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i)) 2161 return -1; 2162 2163 return ShiftAmt; 2164 } 2165 2166 //===----------------------------------------------------------------------===// 2167 // Addressing Mode Selection 2168 //===----------------------------------------------------------------------===// 2169 2170 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit 2171 /// or 64-bit immediate, and if the value can be accurately represented as a 2172 /// sign extension from a 16-bit value. If so, this returns true and the 2173 /// immediate. 2174 bool llvm::isIntS16Immediate(SDNode *N, int16_t &Imm) { 2175 if (!isa<ConstantSDNode>(N)) 2176 return false; 2177 2178 Imm = (int16_t)cast<ConstantSDNode>(N)->getZExtValue(); 2179 if (N->getValueType(0) == MVT::i32) 2180 return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue(); 2181 else 2182 return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue(); 2183 } 2184 bool llvm::isIntS16Immediate(SDValue Op, int16_t &Imm) { 2185 return isIntS16Immediate(Op.getNode(), Imm); 2186 } 2187 2188 /// SelectAddressRegReg - Given the specified addressed, check to see if it 2189 /// can be represented as an indexed [r+r] operation. Returns false if it 2190 /// can be more efficiently represented with [r+imm]. 2191 bool PPCTargetLowering::SelectAddressRegReg(SDValue N, SDValue &Base, 2192 SDValue &Index, 2193 SelectionDAG &DAG) const { 2194 int16_t imm = 0; 2195 if (N.getOpcode() == ISD::ADD) { 2196 if (isIntS16Immediate(N.getOperand(1), imm)) 2197 return false; // r+i 2198 if (N.getOperand(1).getOpcode() == PPCISD::Lo) 2199 return false; // r+i 2200 2201 Base = N.getOperand(0); 2202 Index = N.getOperand(1); 2203 return true; 2204 } else if (N.getOpcode() == ISD::OR) { 2205 if (isIntS16Immediate(N.getOperand(1), imm)) 2206 return false; // r+i can fold it if we can. 2207 2208 // If this is an or of disjoint bitfields, we can codegen this as an add 2209 // (for better address arithmetic) if the LHS and RHS of the OR are provably 2210 // disjoint. 2211 KnownBits LHSKnown, RHSKnown; 2212 DAG.computeKnownBits(N.getOperand(0), LHSKnown); 2213 2214 if (LHSKnown.Zero.getBoolValue()) { 2215 DAG.computeKnownBits(N.getOperand(1), RHSKnown); 2216 // If all of the bits are known zero on the LHS or RHS, the add won't 2217 // carry. 2218 if (~(LHSKnown.Zero | RHSKnown.Zero) == 0) { 2219 Base = N.getOperand(0); 2220 Index = N.getOperand(1); 2221 return true; 2222 } 2223 } 2224 } 2225 2226 return false; 2227 } 2228 2229 // If we happen to be doing an i64 load or store into a stack slot that has 2230 // less than a 4-byte alignment, then the frame-index elimination may need to 2231 // use an indexed load or store instruction (because the offset may not be a 2232 // multiple of 4). The extra register needed to hold the offset comes from the 2233 // register scavenger, and it is possible that the scavenger will need to use 2234 // an emergency spill slot. As a result, we need to make sure that a spill slot 2235 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned 2236 // stack slot. 2237 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) { 2238 // FIXME: This does not handle the LWA case. 2239 if (VT != MVT::i64) 2240 return; 2241 2242 // NOTE: We'll exclude negative FIs here, which come from argument 2243 // lowering, because there are no known test cases triggering this problem 2244 // using packed structures (or similar). We can remove this exclusion if 2245 // we find such a test case. The reason why this is so test-case driven is 2246 // because this entire 'fixup' is only to prevent crashes (from the 2247 // register scavenger) on not-really-valid inputs. For example, if we have: 2248 // %a = alloca i1 2249 // %b = bitcast i1* %a to i64* 2250 // store i64* a, i64 b 2251 // then the store should really be marked as 'align 1', but is not. If it 2252 // were marked as 'align 1' then the indexed form would have been 2253 // instruction-selected initially, and the problem this 'fixup' is preventing 2254 // won't happen regardless. 2255 if (FrameIdx < 0) 2256 return; 2257 2258 MachineFunction &MF = DAG.getMachineFunction(); 2259 MachineFrameInfo &MFI = MF.getFrameInfo(); 2260 2261 unsigned Align = MFI.getObjectAlignment(FrameIdx); 2262 if (Align >= 4) 2263 return; 2264 2265 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 2266 FuncInfo->setHasNonRISpills(); 2267 } 2268 2269 /// Returns true if the address N can be represented by a base register plus 2270 /// a signed 16-bit displacement [r+imm], and if it is not better 2271 /// represented as reg+reg. If \p Alignment is non-zero, only accept 2272 /// displacements that are multiples of that value. 2273 bool PPCTargetLowering::SelectAddressRegImm(SDValue N, SDValue &Disp, 2274 SDValue &Base, 2275 SelectionDAG &DAG, 2276 unsigned Alignment) const { 2277 // FIXME dl should come from parent load or store, not from address 2278 SDLoc dl(N); 2279 // If this can be more profitably realized as r+r, fail. 2280 if (SelectAddressRegReg(N, Disp, Base, DAG)) 2281 return false; 2282 2283 if (N.getOpcode() == ISD::ADD) { 2284 int16_t imm = 0; 2285 if (isIntS16Immediate(N.getOperand(1), imm) && 2286 (!Alignment || (imm % Alignment) == 0)) { 2287 Disp = DAG.getTargetConstant(imm, dl, N.getValueType()); 2288 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) { 2289 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2290 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 2291 } else { 2292 Base = N.getOperand(0); 2293 } 2294 return true; // [r+i] 2295 } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) { 2296 // Match LOAD (ADD (X, Lo(G))). 2297 assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue() 2298 && "Cannot handle constant offsets yet!"); 2299 Disp = N.getOperand(1).getOperand(0); // The global address. 2300 assert(Disp.getOpcode() == ISD::TargetGlobalAddress || 2301 Disp.getOpcode() == ISD::TargetGlobalTLSAddress || 2302 Disp.getOpcode() == ISD::TargetConstantPool || 2303 Disp.getOpcode() == ISD::TargetJumpTable); 2304 Base = N.getOperand(0); 2305 return true; // [&g+r] 2306 } 2307 } else if (N.getOpcode() == ISD::OR) { 2308 int16_t imm = 0; 2309 if (isIntS16Immediate(N.getOperand(1), imm) && 2310 (!Alignment || (imm % Alignment) == 0)) { 2311 // If this is an or of disjoint bitfields, we can codegen this as an add 2312 // (for better address arithmetic) if the LHS and RHS of the OR are 2313 // provably disjoint. 2314 KnownBits LHSKnown; 2315 DAG.computeKnownBits(N.getOperand(0), LHSKnown); 2316 2317 if ((LHSKnown.Zero.getZExtValue()|~(uint64_t)imm) == ~0ULL) { 2318 // If all of the bits are known zero on the LHS or RHS, the add won't 2319 // carry. 2320 if (FrameIndexSDNode *FI = 2321 dyn_cast<FrameIndexSDNode>(N.getOperand(0))) { 2322 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2323 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 2324 } else { 2325 Base = N.getOperand(0); 2326 } 2327 Disp = DAG.getTargetConstant(imm, dl, N.getValueType()); 2328 return true; 2329 } 2330 } 2331 } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) { 2332 // Loading from a constant address. 2333 2334 // If this address fits entirely in a 16-bit sext immediate field, codegen 2335 // this as "d, 0" 2336 int16_t Imm; 2337 if (isIntS16Immediate(CN, Imm) && (!Alignment || (Imm % Alignment) == 0)) { 2338 Disp = DAG.getTargetConstant(Imm, dl, CN->getValueType(0)); 2339 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO, 2340 CN->getValueType(0)); 2341 return true; 2342 } 2343 2344 // Handle 32-bit sext immediates with LIS + addr mode. 2345 if ((CN->getValueType(0) == MVT::i32 || 2346 (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) && 2347 (!Alignment || (CN->getZExtValue() % Alignment) == 0)) { 2348 int Addr = (int)CN->getZExtValue(); 2349 2350 // Otherwise, break this down into an LIS + disp. 2351 Disp = DAG.getTargetConstant((short)Addr, dl, MVT::i32); 2352 2353 Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, dl, 2354 MVT::i32); 2355 unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8; 2356 Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0); 2357 return true; 2358 } 2359 } 2360 2361 Disp = DAG.getTargetConstant(0, dl, getPointerTy(DAG.getDataLayout())); 2362 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) { 2363 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2364 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 2365 } else 2366 Base = N; 2367 return true; // [r+0] 2368 } 2369 2370 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be 2371 /// represented as an indexed [r+r] operation. 2372 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base, 2373 SDValue &Index, 2374 SelectionDAG &DAG) const { 2375 // Check to see if we can easily represent this as an [r+r] address. This 2376 // will fail if it thinks that the address is more profitably represented as 2377 // reg+imm, e.g. where imm = 0. 2378 if (SelectAddressRegReg(N, Base, Index, DAG)) 2379 return true; 2380 2381 // If the address is the result of an add, we will utilize the fact that the 2382 // address calculation includes an implicit add. However, we can reduce 2383 // register pressure if we do not materialize a constant just for use as the 2384 // index register. We only get rid of the add if it is not an add of a 2385 // value and a 16-bit signed constant and both have a single use. 2386 int16_t imm = 0; 2387 if (N.getOpcode() == ISD::ADD && 2388 (!isIntS16Immediate(N.getOperand(1), imm) || 2389 !N.getOperand(1).hasOneUse() || !N.getOperand(0).hasOneUse())) { 2390 Base = N.getOperand(0); 2391 Index = N.getOperand(1); 2392 return true; 2393 } 2394 2395 // Otherwise, do it the hard way, using R0 as the base register. 2396 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO, 2397 N.getValueType()); 2398 Index = N; 2399 return true; 2400 } 2401 2402 /// Returns true if we should use a direct load into vector instruction 2403 /// (such as lxsd or lfd), instead of a load into gpr + direct move sequence. 2404 static bool usePartialVectorLoads(SDNode *N) { 2405 if (!N->hasOneUse()) 2406 return false; 2407 2408 // If there are any other uses other than scalar to vector, then we should 2409 // keep it as a scalar load -> direct move pattern to prevent multiple 2410 // loads. Currently, only check for i64 since we have lxsd/lfd to do this 2411 // efficiently, but no update equivalent. 2412 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 2413 EVT MemVT = LD->getMemoryVT(); 2414 if (MemVT.isSimple() && MemVT.getSimpleVT().SimpleTy == MVT::i64) { 2415 SDNode *User = *(LD->use_begin()); 2416 if (User->getOpcode() == ISD::SCALAR_TO_VECTOR) 2417 return true; 2418 } 2419 } 2420 2421 return false; 2422 } 2423 2424 /// getPreIndexedAddressParts - returns true by value, base pointer and 2425 /// offset pointer and addressing mode by reference if the node's address 2426 /// can be legally represented as pre-indexed load / store address. 2427 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base, 2428 SDValue &Offset, 2429 ISD::MemIndexedMode &AM, 2430 SelectionDAG &DAG) const { 2431 if (DisablePPCPreinc) return false; 2432 2433 bool isLoad = true; 2434 SDValue Ptr; 2435 EVT VT; 2436 unsigned Alignment; 2437 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 2438 Ptr = LD->getBasePtr(); 2439 VT = LD->getMemoryVT(); 2440 Alignment = LD->getAlignment(); 2441 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 2442 Ptr = ST->getBasePtr(); 2443 VT = ST->getMemoryVT(); 2444 Alignment = ST->getAlignment(); 2445 isLoad = false; 2446 } else 2447 return false; 2448 2449 // Do not generate pre-inc forms for specific loads that feed scalar_to_vector 2450 // instructions because we can fold these into a more efficient instruction 2451 // instead, (such as LXSD). 2452 if (isLoad && usePartialVectorLoads(N)) { 2453 return false; 2454 } 2455 2456 // PowerPC doesn't have preinc load/store instructions for vectors (except 2457 // for QPX, which does have preinc r+r forms). 2458 if (VT.isVector()) { 2459 if (!Subtarget.hasQPX() || (VT != MVT::v4f64 && VT != MVT::v4f32)) { 2460 return false; 2461 } else if (SelectAddressRegRegOnly(Ptr, Offset, Base, DAG)) { 2462 AM = ISD::PRE_INC; 2463 return true; 2464 } 2465 } 2466 2467 if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) { 2468 // Common code will reject creating a pre-inc form if the base pointer 2469 // is a frame index, or if N is a store and the base pointer is either 2470 // the same as or a predecessor of the value being stored. Check for 2471 // those situations here, and try with swapped Base/Offset instead. 2472 bool Swap = false; 2473 2474 if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base)) 2475 Swap = true; 2476 else if (!isLoad) { 2477 SDValue Val = cast<StoreSDNode>(N)->getValue(); 2478 if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode())) 2479 Swap = true; 2480 } 2481 2482 if (Swap) 2483 std::swap(Base, Offset); 2484 2485 AM = ISD::PRE_INC; 2486 return true; 2487 } 2488 2489 // LDU/STU can only handle immediates that are a multiple of 4. 2490 if (VT != MVT::i64) { 2491 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, 0)) 2492 return false; 2493 } else { 2494 // LDU/STU need an address with at least 4-byte alignment. 2495 if (Alignment < 4) 2496 return false; 2497 2498 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, 4)) 2499 return false; 2500 } 2501 2502 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 2503 // PPC64 doesn't have lwau, but it does have lwaux. Reject preinc load of 2504 // sext i32 to i64 when addr mode is r+i. 2505 if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 && 2506 LD->getExtensionType() == ISD::SEXTLOAD && 2507 isa<ConstantSDNode>(Offset)) 2508 return false; 2509 } 2510 2511 AM = ISD::PRE_INC; 2512 return true; 2513 } 2514 2515 //===----------------------------------------------------------------------===// 2516 // LowerOperation implementation 2517 //===----------------------------------------------------------------------===// 2518 2519 /// Return true if we should reference labels using a PICBase, set the HiOpFlags 2520 /// and LoOpFlags to the target MO flags. 2521 static void getLabelAccessInfo(bool IsPIC, const PPCSubtarget &Subtarget, 2522 unsigned &HiOpFlags, unsigned &LoOpFlags, 2523 const GlobalValue *GV = nullptr) { 2524 HiOpFlags = PPCII::MO_HA; 2525 LoOpFlags = PPCII::MO_LO; 2526 2527 // Don't use the pic base if not in PIC relocation model. 2528 if (IsPIC) { 2529 HiOpFlags |= PPCII::MO_PIC_FLAG; 2530 LoOpFlags |= PPCII::MO_PIC_FLAG; 2531 } 2532 2533 // If this is a reference to a global value that requires a non-lazy-ptr, make 2534 // sure that instruction lowering adds it. 2535 if (GV && Subtarget.hasLazyResolverStub(GV)) { 2536 HiOpFlags |= PPCII::MO_NLP_FLAG; 2537 LoOpFlags |= PPCII::MO_NLP_FLAG; 2538 2539 if (GV->hasHiddenVisibility()) { 2540 HiOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG; 2541 LoOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG; 2542 } 2543 } 2544 } 2545 2546 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC, 2547 SelectionDAG &DAG) { 2548 SDLoc DL(HiPart); 2549 EVT PtrVT = HiPart.getValueType(); 2550 SDValue Zero = DAG.getConstant(0, DL, PtrVT); 2551 2552 SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero); 2553 SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero); 2554 2555 // With PIC, the first instruction is actually "GR+hi(&G)". 2556 if (isPIC) 2557 Hi = DAG.getNode(ISD::ADD, DL, PtrVT, 2558 DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi); 2559 2560 // Generate non-pic code that has direct accesses to the constant pool. 2561 // The address of the global is just (hi(&g)+lo(&g)). 2562 return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo); 2563 } 2564 2565 static void setUsesTOCBasePtr(MachineFunction &MF) { 2566 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 2567 FuncInfo->setUsesTOCBasePtr(); 2568 } 2569 2570 static void setUsesTOCBasePtr(SelectionDAG &DAG) { 2571 setUsesTOCBasePtr(DAG.getMachineFunction()); 2572 } 2573 2574 static SDValue getTOCEntry(SelectionDAG &DAG, const SDLoc &dl, bool Is64Bit, 2575 SDValue GA) { 2576 EVT VT = Is64Bit ? MVT::i64 : MVT::i32; 2577 SDValue Reg = Is64Bit ? DAG.getRegister(PPC::X2, VT) : 2578 DAG.getNode(PPCISD::GlobalBaseReg, dl, VT); 2579 2580 SDValue Ops[] = { GA, Reg }; 2581 return DAG.getMemIntrinsicNode( 2582 PPCISD::TOC_ENTRY, dl, DAG.getVTList(VT, MVT::Other), Ops, VT, 2583 MachinePointerInfo::getGOT(DAG.getMachineFunction()), 0, 2584 MachineMemOperand::MOLoad); 2585 } 2586 2587 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op, 2588 SelectionDAG &DAG) const { 2589 EVT PtrVT = Op.getValueType(); 2590 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op); 2591 const Constant *C = CP->getConstVal(); 2592 2593 // 64-bit SVR4 ABI code is always position-independent. 2594 // The actual address of the GlobalValue is stored in the TOC. 2595 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) { 2596 setUsesTOCBasePtr(DAG); 2597 SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0); 2598 return getTOCEntry(DAG, SDLoc(CP), true, GA); 2599 } 2600 2601 unsigned MOHiFlag, MOLoFlag; 2602 bool IsPIC = isPositionIndependent(); 2603 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag); 2604 2605 if (IsPIC && Subtarget.isSVR4ABI()) { 2606 SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 2607 PPCII::MO_PIC_FLAG); 2608 return getTOCEntry(DAG, SDLoc(CP), false, GA); 2609 } 2610 2611 SDValue CPIHi = 2612 DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOHiFlag); 2613 SDValue CPILo = 2614 DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOLoFlag); 2615 return LowerLabelRef(CPIHi, CPILo, IsPIC, DAG); 2616 } 2617 2618 // For 64-bit PowerPC, prefer the more compact relative encodings. 2619 // This trades 32 bits per jump table entry for one or two instructions 2620 // on the jump site. 2621 unsigned PPCTargetLowering::getJumpTableEncoding() const { 2622 if (isJumpTableRelative()) 2623 return MachineJumpTableInfo::EK_LabelDifference32; 2624 2625 return TargetLowering::getJumpTableEncoding(); 2626 } 2627 2628 bool PPCTargetLowering::isJumpTableRelative() const { 2629 if (Subtarget.isPPC64()) 2630 return true; 2631 return TargetLowering::isJumpTableRelative(); 2632 } 2633 2634 SDValue PPCTargetLowering::getPICJumpTableRelocBase(SDValue Table, 2635 SelectionDAG &DAG) const { 2636 if (!Subtarget.isPPC64()) 2637 return TargetLowering::getPICJumpTableRelocBase(Table, DAG); 2638 2639 switch (getTargetMachine().getCodeModel()) { 2640 case CodeModel::Small: 2641 case CodeModel::Medium: 2642 return TargetLowering::getPICJumpTableRelocBase(Table, DAG); 2643 default: 2644 return DAG.getNode(PPCISD::GlobalBaseReg, SDLoc(), 2645 getPointerTy(DAG.getDataLayout())); 2646 } 2647 } 2648 2649 const MCExpr * 2650 PPCTargetLowering::getPICJumpTableRelocBaseExpr(const MachineFunction *MF, 2651 unsigned JTI, 2652 MCContext &Ctx) const { 2653 if (!Subtarget.isPPC64()) 2654 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx); 2655 2656 switch (getTargetMachine().getCodeModel()) { 2657 case CodeModel::Small: 2658 case CodeModel::Medium: 2659 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx); 2660 default: 2661 return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx); 2662 } 2663 } 2664 2665 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const { 2666 EVT PtrVT = Op.getValueType(); 2667 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op); 2668 2669 // 64-bit SVR4 ABI code is always position-independent. 2670 // The actual address of the GlobalValue is stored in the TOC. 2671 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) { 2672 setUsesTOCBasePtr(DAG); 2673 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT); 2674 return getTOCEntry(DAG, SDLoc(JT), true, GA); 2675 } 2676 2677 unsigned MOHiFlag, MOLoFlag; 2678 bool IsPIC = isPositionIndependent(); 2679 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag); 2680 2681 if (IsPIC && Subtarget.isSVR4ABI()) { 2682 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, 2683 PPCII::MO_PIC_FLAG); 2684 return getTOCEntry(DAG, SDLoc(GA), false, GA); 2685 } 2686 2687 SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag); 2688 SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag); 2689 return LowerLabelRef(JTIHi, JTILo, IsPIC, DAG); 2690 } 2691 2692 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op, 2693 SelectionDAG &DAG) const { 2694 EVT PtrVT = Op.getValueType(); 2695 BlockAddressSDNode *BASDN = cast<BlockAddressSDNode>(Op); 2696 const BlockAddress *BA = BASDN->getBlockAddress(); 2697 2698 // 64-bit SVR4 ABI code is always position-independent. 2699 // The actual BlockAddress is stored in the TOC. 2700 if (Subtarget.isSVR4ABI() && 2701 (Subtarget.isPPC64() || isPositionIndependent())) { 2702 if (Subtarget.isPPC64()) 2703 setUsesTOCBasePtr(DAG); 2704 SDValue GA = DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset()); 2705 return getTOCEntry(DAG, SDLoc(BASDN), Subtarget.isPPC64(), GA); 2706 } 2707 2708 unsigned MOHiFlag, MOLoFlag; 2709 bool IsPIC = isPositionIndependent(); 2710 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag); 2711 SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag); 2712 SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag); 2713 return LowerLabelRef(TgtBAHi, TgtBALo, IsPIC, DAG); 2714 } 2715 2716 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op, 2717 SelectionDAG &DAG) const { 2718 // FIXME: TLS addresses currently use medium model code sequences, 2719 // which is the most useful form. Eventually support for small and 2720 // large models could be added if users need it, at the cost of 2721 // additional complexity. 2722 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op); 2723 if (DAG.getTarget().useEmulatedTLS()) 2724 return LowerToTLSEmulatedModel(GA, DAG); 2725 2726 SDLoc dl(GA); 2727 const GlobalValue *GV = GA->getGlobal(); 2728 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2729 bool is64bit = Subtarget.isPPC64(); 2730 const Module *M = DAG.getMachineFunction().getFunction().getParent(); 2731 PICLevel::Level picLevel = M->getPICLevel(); 2732 2733 TLSModel::Model Model = getTargetMachine().getTLSModel(GV); 2734 2735 if (Model == TLSModel::LocalExec) { 2736 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 2737 PPCII::MO_TPREL_HA); 2738 SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 2739 PPCII::MO_TPREL_LO); 2740 SDValue TLSReg = is64bit ? DAG.getRegister(PPC::X13, MVT::i64) 2741 : DAG.getRegister(PPC::R2, MVT::i32); 2742 2743 SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg); 2744 return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi); 2745 } 2746 2747 if (Model == TLSModel::InitialExec) { 2748 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0); 2749 SDValue TGATLS = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 2750 PPCII::MO_TLS); 2751 SDValue GOTPtr; 2752 if (is64bit) { 2753 setUsesTOCBasePtr(DAG); 2754 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64); 2755 GOTPtr = DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl, 2756 PtrVT, GOTReg, TGA); 2757 } else 2758 GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT); 2759 SDValue TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl, 2760 PtrVT, TGA, GOTPtr); 2761 return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS); 2762 } 2763 2764 if (Model == TLSModel::GeneralDynamic) { 2765 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0); 2766 SDValue GOTPtr; 2767 if (is64bit) { 2768 setUsesTOCBasePtr(DAG); 2769 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64); 2770 GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT, 2771 GOTReg, TGA); 2772 } else { 2773 if (picLevel == PICLevel::SmallPIC) 2774 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT); 2775 else 2776 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT); 2777 } 2778 return DAG.getNode(PPCISD::ADDI_TLSGD_L_ADDR, dl, PtrVT, 2779 GOTPtr, TGA, TGA); 2780 } 2781 2782 if (Model == TLSModel::LocalDynamic) { 2783 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0); 2784 SDValue GOTPtr; 2785 if (is64bit) { 2786 setUsesTOCBasePtr(DAG); 2787 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64); 2788 GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT, 2789 GOTReg, TGA); 2790 } else { 2791 if (picLevel == PICLevel::SmallPIC) 2792 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT); 2793 else 2794 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT); 2795 } 2796 SDValue TLSAddr = DAG.getNode(PPCISD::ADDI_TLSLD_L_ADDR, dl, 2797 PtrVT, GOTPtr, TGA, TGA); 2798 SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl, 2799 PtrVT, TLSAddr, TGA); 2800 return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA); 2801 } 2802 2803 llvm_unreachable("Unknown TLS model!"); 2804 } 2805 2806 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op, 2807 SelectionDAG &DAG) const { 2808 EVT PtrVT = Op.getValueType(); 2809 GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op); 2810 SDLoc DL(GSDN); 2811 const GlobalValue *GV = GSDN->getGlobal(); 2812 2813 // 64-bit SVR4 ABI code is always position-independent. 2814 // The actual address of the GlobalValue is stored in the TOC. 2815 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) { 2816 setUsesTOCBasePtr(DAG); 2817 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset()); 2818 return getTOCEntry(DAG, DL, true, GA); 2819 } 2820 2821 unsigned MOHiFlag, MOLoFlag; 2822 bool IsPIC = isPositionIndependent(); 2823 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag, GV); 2824 2825 if (IsPIC && Subtarget.isSVR4ABI()) { 2826 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 2827 GSDN->getOffset(), 2828 PPCII::MO_PIC_FLAG); 2829 return getTOCEntry(DAG, DL, false, GA); 2830 } 2831 2832 SDValue GAHi = 2833 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag); 2834 SDValue GALo = 2835 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag); 2836 2837 SDValue Ptr = LowerLabelRef(GAHi, GALo, IsPIC, DAG); 2838 2839 // If the global reference is actually to a non-lazy-pointer, we have to do an 2840 // extra load to get the address of the global. 2841 if (MOHiFlag & PPCII::MO_NLP_FLAG) 2842 Ptr = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo()); 2843 return Ptr; 2844 } 2845 2846 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const { 2847 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get(); 2848 SDLoc dl(Op); 2849 2850 if (Op.getValueType() == MVT::v2i64) { 2851 // When the operands themselves are v2i64 values, we need to do something 2852 // special because VSX has no underlying comparison operations for these. 2853 if (Op.getOperand(0).getValueType() == MVT::v2i64) { 2854 // Equality can be handled by casting to the legal type for Altivec 2855 // comparisons, everything else needs to be expanded. 2856 if (CC == ISD::SETEQ || CC == ISD::SETNE) { 2857 return DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, 2858 DAG.getSetCC(dl, MVT::v4i32, 2859 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0)), 2860 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(1)), 2861 CC)); 2862 } 2863 2864 return SDValue(); 2865 } 2866 2867 // We handle most of these in the usual way. 2868 return Op; 2869 } 2870 2871 // If we're comparing for equality to zero, expose the fact that this is 2872 // implemented as a ctlz/srl pair on ppc, so that the dag combiner can 2873 // fold the new nodes. 2874 if (SDValue V = lowerCmpEqZeroToCtlzSrl(Op, DAG)) 2875 return V; 2876 2877 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 2878 // Leave comparisons against 0 and -1 alone for now, since they're usually 2879 // optimized. FIXME: revisit this when we can custom lower all setcc 2880 // optimizations. 2881 if (C->isAllOnesValue() || C->isNullValue()) 2882 return SDValue(); 2883 } 2884 2885 // If we have an integer seteq/setne, turn it into a compare against zero 2886 // by xor'ing the rhs with the lhs, which is faster than setting a 2887 // condition register, reading it back out, and masking the correct bit. The 2888 // normal approach here uses sub to do this instead of xor. Using xor exposes 2889 // the result to other bit-twiddling opportunities. 2890 EVT LHSVT = Op.getOperand(0).getValueType(); 2891 if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) { 2892 EVT VT = Op.getValueType(); 2893 SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0), 2894 Op.getOperand(1)); 2895 return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, dl, LHSVT), CC); 2896 } 2897 return SDValue(); 2898 } 2899 2900 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const { 2901 SDNode *Node = Op.getNode(); 2902 EVT VT = Node->getValueType(0); 2903 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2904 SDValue InChain = Node->getOperand(0); 2905 SDValue VAListPtr = Node->getOperand(1); 2906 const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue(); 2907 SDLoc dl(Node); 2908 2909 assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only"); 2910 2911 // gpr_index 2912 SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain, 2913 VAListPtr, MachinePointerInfo(SV), MVT::i8); 2914 InChain = GprIndex.getValue(1); 2915 2916 if (VT == MVT::i64) { 2917 // Check if GprIndex is even 2918 SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex, 2919 DAG.getConstant(1, dl, MVT::i32)); 2920 SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd, 2921 DAG.getConstant(0, dl, MVT::i32), ISD::SETNE); 2922 SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex, 2923 DAG.getConstant(1, dl, MVT::i32)); 2924 // Align GprIndex to be even if it isn't 2925 GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne, 2926 GprIndex); 2927 } 2928 2929 // fpr index is 1 byte after gpr 2930 SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, 2931 DAG.getConstant(1, dl, MVT::i32)); 2932 2933 // fpr 2934 SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain, 2935 FprPtr, MachinePointerInfo(SV), MVT::i8); 2936 InChain = FprIndex.getValue(1); 2937 2938 SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, 2939 DAG.getConstant(8, dl, MVT::i32)); 2940 2941 SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, 2942 DAG.getConstant(4, dl, MVT::i32)); 2943 2944 // areas 2945 SDValue OverflowArea = 2946 DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr, MachinePointerInfo()); 2947 InChain = OverflowArea.getValue(1); 2948 2949 SDValue RegSaveArea = 2950 DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr, MachinePointerInfo()); 2951 InChain = RegSaveArea.getValue(1); 2952 2953 // select overflow_area if index > 8 2954 SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex, 2955 DAG.getConstant(8, dl, MVT::i32), ISD::SETLT); 2956 2957 // adjustment constant gpr_index * 4/8 2958 SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32, 2959 VT.isInteger() ? GprIndex : FprIndex, 2960 DAG.getConstant(VT.isInteger() ? 4 : 8, dl, 2961 MVT::i32)); 2962 2963 // OurReg = RegSaveArea + RegConstant 2964 SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea, 2965 RegConstant); 2966 2967 // Floating types are 32 bytes into RegSaveArea 2968 if (VT.isFloatingPoint()) 2969 OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg, 2970 DAG.getConstant(32, dl, MVT::i32)); 2971 2972 // increase {f,g}pr_index by 1 (or 2 if VT is i64) 2973 SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32, 2974 VT.isInteger() ? GprIndex : FprIndex, 2975 DAG.getConstant(VT == MVT::i64 ? 2 : 1, dl, 2976 MVT::i32)); 2977 2978 InChain = DAG.getTruncStore(InChain, dl, IndexPlus1, 2979 VT.isInteger() ? VAListPtr : FprPtr, 2980 MachinePointerInfo(SV), MVT::i8); 2981 2982 // determine if we should load from reg_save_area or overflow_area 2983 SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea); 2984 2985 // increase overflow_area by 4/8 if gpr/fpr > 8 2986 SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea, 2987 DAG.getConstant(VT.isInteger() ? 4 : 8, 2988 dl, MVT::i32)); 2989 2990 OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea, 2991 OverflowAreaPlusN); 2992 2993 InChain = DAG.getTruncStore(InChain, dl, OverflowArea, OverflowAreaPtr, 2994 MachinePointerInfo(), MVT::i32); 2995 2996 return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo()); 2997 } 2998 2999 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const { 3000 assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only"); 3001 3002 // We have to copy the entire va_list struct: 3003 // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte 3004 return DAG.getMemcpy(Op.getOperand(0), Op, 3005 Op.getOperand(1), Op.getOperand(2), 3006 DAG.getConstant(12, SDLoc(Op), MVT::i32), 8, false, true, 3007 false, MachinePointerInfo(), MachinePointerInfo()); 3008 } 3009 3010 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op, 3011 SelectionDAG &DAG) const { 3012 return Op.getOperand(0); 3013 } 3014 3015 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op, 3016 SelectionDAG &DAG) const { 3017 SDValue Chain = Op.getOperand(0); 3018 SDValue Trmp = Op.getOperand(1); // trampoline 3019 SDValue FPtr = Op.getOperand(2); // nested function 3020 SDValue Nest = Op.getOperand(3); // 'nest' parameter value 3021 SDLoc dl(Op); 3022 3023 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3024 bool isPPC64 = (PtrVT == MVT::i64); 3025 Type *IntPtrTy = DAG.getDataLayout().getIntPtrType(*DAG.getContext()); 3026 3027 TargetLowering::ArgListTy Args; 3028 TargetLowering::ArgListEntry Entry; 3029 3030 Entry.Ty = IntPtrTy; 3031 Entry.Node = Trmp; Args.push_back(Entry); 3032 3033 // TrampSize == (isPPC64 ? 48 : 40); 3034 Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40, dl, 3035 isPPC64 ? MVT::i64 : MVT::i32); 3036 Args.push_back(Entry); 3037 3038 Entry.Node = FPtr; Args.push_back(Entry); 3039 Entry.Node = Nest; Args.push_back(Entry); 3040 3041 // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg) 3042 TargetLowering::CallLoweringInfo CLI(DAG); 3043 CLI.setDebugLoc(dl).setChain(Chain).setLibCallee( 3044 CallingConv::C, Type::getVoidTy(*DAG.getContext()), 3045 DAG.getExternalSymbol("__trampoline_setup", PtrVT), std::move(Args)); 3046 3047 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 3048 return CallResult.second; 3049 } 3050 3051 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const { 3052 MachineFunction &MF = DAG.getMachineFunction(); 3053 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 3054 EVT PtrVT = getPointerTy(MF.getDataLayout()); 3055 3056 SDLoc dl(Op); 3057 3058 if (Subtarget.isDarwinABI() || Subtarget.isPPC64()) { 3059 // vastart just stores the address of the VarArgsFrameIndex slot into the 3060 // memory location argument. 3061 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 3062 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 3063 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1), 3064 MachinePointerInfo(SV)); 3065 } 3066 3067 // For the 32-bit SVR4 ABI we follow the layout of the va_list struct. 3068 // We suppose the given va_list is already allocated. 3069 // 3070 // typedef struct { 3071 // char gpr; /* index into the array of 8 GPRs 3072 // * stored in the register save area 3073 // * gpr=0 corresponds to r3, 3074 // * gpr=1 to r4, etc. 3075 // */ 3076 // char fpr; /* index into the array of 8 FPRs 3077 // * stored in the register save area 3078 // * fpr=0 corresponds to f1, 3079 // * fpr=1 to f2, etc. 3080 // */ 3081 // char *overflow_arg_area; 3082 // /* location on stack that holds 3083 // * the next overflow argument 3084 // */ 3085 // char *reg_save_area; 3086 // /* where r3:r10 and f1:f8 (if saved) 3087 // * are stored 3088 // */ 3089 // } va_list[1]; 3090 3091 SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), dl, MVT::i32); 3092 SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), dl, MVT::i32); 3093 SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(), 3094 PtrVT); 3095 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), 3096 PtrVT); 3097 3098 uint64_t FrameOffset = PtrVT.getSizeInBits()/8; 3099 SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, dl, PtrVT); 3100 3101 uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1; 3102 SDValue ConstStackOffset = DAG.getConstant(StackOffset, dl, PtrVT); 3103 3104 uint64_t FPROffset = 1; 3105 SDValue ConstFPROffset = DAG.getConstant(FPROffset, dl, PtrVT); 3106 3107 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 3108 3109 // Store first byte : number of int regs 3110 SDValue firstStore = 3111 DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR, Op.getOperand(1), 3112 MachinePointerInfo(SV), MVT::i8); 3113 uint64_t nextOffset = FPROffset; 3114 SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1), 3115 ConstFPROffset); 3116 3117 // Store second byte : number of float regs 3118 SDValue secondStore = 3119 DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr, 3120 MachinePointerInfo(SV, nextOffset), MVT::i8); 3121 nextOffset += StackOffset; 3122 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset); 3123 3124 // Store second word : arguments given on stack 3125 SDValue thirdStore = DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr, 3126 MachinePointerInfo(SV, nextOffset)); 3127 nextOffset += FrameOffset; 3128 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset); 3129 3130 // Store third word : arguments given in registers 3131 return DAG.getStore(thirdStore, dl, FR, nextPtr, 3132 MachinePointerInfo(SV, nextOffset)); 3133 } 3134 3135 #include "PPCGenCallingConv.inc" 3136 3137 // Function whose sole purpose is to kill compiler warnings 3138 // stemming from unused functions included from PPCGenCallingConv.inc. 3139 CCAssignFn *PPCTargetLowering::useFastISelCCs(unsigned Flag) const { 3140 return Flag ? CC_PPC64_ELF_FIS : RetCC_PPC64_ELF_FIS; 3141 } 3142 3143 bool llvm::CC_PPC32_SVR4_Custom_Dummy(unsigned &ValNo, MVT &ValVT, MVT &LocVT, 3144 CCValAssign::LocInfo &LocInfo, 3145 ISD::ArgFlagsTy &ArgFlags, 3146 CCState &State) { 3147 return true; 3148 } 3149 3150 bool llvm::CC_PPC32_SVR4_Custom_AlignArgRegs(unsigned &ValNo, MVT &ValVT, 3151 MVT &LocVT, 3152 CCValAssign::LocInfo &LocInfo, 3153 ISD::ArgFlagsTy &ArgFlags, 3154 CCState &State) { 3155 static const MCPhysReg ArgRegs[] = { 3156 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 3157 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 3158 }; 3159 const unsigned NumArgRegs = array_lengthof(ArgRegs); 3160 3161 unsigned RegNum = State.getFirstUnallocated(ArgRegs); 3162 3163 // Skip one register if the first unallocated register has an even register 3164 // number and there are still argument registers available which have not been 3165 // allocated yet. RegNum is actually an index into ArgRegs, which means we 3166 // need to skip a register if RegNum is odd. 3167 if (RegNum != NumArgRegs && RegNum % 2 == 1) { 3168 State.AllocateReg(ArgRegs[RegNum]); 3169 } 3170 3171 // Always return false here, as this function only makes sure that the first 3172 // unallocated register has an odd register number and does not actually 3173 // allocate a register for the current argument. 3174 return false; 3175 } 3176 3177 bool 3178 llvm::CC_PPC32_SVR4_Custom_SkipLastArgRegsPPCF128(unsigned &ValNo, MVT &ValVT, 3179 MVT &LocVT, 3180 CCValAssign::LocInfo &LocInfo, 3181 ISD::ArgFlagsTy &ArgFlags, 3182 CCState &State) { 3183 static const MCPhysReg ArgRegs[] = { 3184 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 3185 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 3186 }; 3187 const unsigned NumArgRegs = array_lengthof(ArgRegs); 3188 3189 unsigned RegNum = State.getFirstUnallocated(ArgRegs); 3190 int RegsLeft = NumArgRegs - RegNum; 3191 3192 // Skip if there is not enough registers left for long double type (4 gpr regs 3193 // in soft float mode) and put long double argument on the stack. 3194 if (RegNum != NumArgRegs && RegsLeft < 4) { 3195 for (int i = 0; i < RegsLeft; i++) { 3196 State.AllocateReg(ArgRegs[RegNum + i]); 3197 } 3198 } 3199 3200 return false; 3201 } 3202 3203 bool llvm::CC_PPC32_SVR4_Custom_AlignFPArgRegs(unsigned &ValNo, MVT &ValVT, 3204 MVT &LocVT, 3205 CCValAssign::LocInfo &LocInfo, 3206 ISD::ArgFlagsTy &ArgFlags, 3207 CCState &State) { 3208 static const MCPhysReg ArgRegs[] = { 3209 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7, 3210 PPC::F8 3211 }; 3212 3213 const unsigned NumArgRegs = array_lengthof(ArgRegs); 3214 3215 unsigned RegNum = State.getFirstUnallocated(ArgRegs); 3216 3217 // If there is only one Floating-point register left we need to put both f64 3218 // values of a split ppc_fp128 value on the stack. 3219 if (RegNum != NumArgRegs && ArgRegs[RegNum] == PPC::F8) { 3220 State.AllocateReg(ArgRegs[RegNum]); 3221 } 3222 3223 // Always return false here, as this function only makes sure that the two f64 3224 // values a ppc_fp128 value is split into are both passed in registers or both 3225 // passed on the stack and does not actually allocate a register for the 3226 // current argument. 3227 return false; 3228 } 3229 3230 /// FPR - The set of FP registers that should be allocated for arguments, 3231 /// on Darwin. 3232 static const MCPhysReg FPR[] = {PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, 3233 PPC::F6, PPC::F7, PPC::F8, PPC::F9, PPC::F10, 3234 PPC::F11, PPC::F12, PPC::F13}; 3235 3236 /// QFPR - The set of QPX registers that should be allocated for arguments. 3237 static const MCPhysReg QFPR[] = { 3238 PPC::QF1, PPC::QF2, PPC::QF3, PPC::QF4, PPC::QF5, PPC::QF6, PPC::QF7, 3239 PPC::QF8, PPC::QF9, PPC::QF10, PPC::QF11, PPC::QF12, PPC::QF13}; 3240 3241 /// CalculateStackSlotSize - Calculates the size reserved for this argument on 3242 /// the stack. 3243 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags, 3244 unsigned PtrByteSize) { 3245 unsigned ArgSize = ArgVT.getStoreSize(); 3246 if (Flags.isByVal()) 3247 ArgSize = Flags.getByValSize(); 3248 3249 // Round up to multiples of the pointer size, except for array members, 3250 // which are always packed. 3251 if (!Flags.isInConsecutiveRegs()) 3252 ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3253 3254 return ArgSize; 3255 } 3256 3257 /// CalculateStackSlotAlignment - Calculates the alignment of this argument 3258 /// on the stack. 3259 static unsigned CalculateStackSlotAlignment(EVT ArgVT, EVT OrigVT, 3260 ISD::ArgFlagsTy Flags, 3261 unsigned PtrByteSize) { 3262 unsigned Align = PtrByteSize; 3263 3264 // Altivec parameters are padded to a 16 byte boundary. 3265 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 || 3266 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 || 3267 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 || 3268 ArgVT == MVT::v1i128 || ArgVT == MVT::f128) 3269 Align = 16; 3270 // QPX vector types stored in double-precision are padded to a 32 byte 3271 // boundary. 3272 else if (ArgVT == MVT::v4f64 || ArgVT == MVT::v4i1) 3273 Align = 32; 3274 3275 // ByVal parameters are aligned as requested. 3276 if (Flags.isByVal()) { 3277 unsigned BVAlign = Flags.getByValAlign(); 3278 if (BVAlign > PtrByteSize) { 3279 if (BVAlign % PtrByteSize != 0) 3280 llvm_unreachable( 3281 "ByVal alignment is not a multiple of the pointer size"); 3282 3283 Align = BVAlign; 3284 } 3285 } 3286 3287 // Array members are always packed to their original alignment. 3288 if (Flags.isInConsecutiveRegs()) { 3289 // If the array member was split into multiple registers, the first 3290 // needs to be aligned to the size of the full type. (Except for 3291 // ppcf128, which is only aligned as its f64 components.) 3292 if (Flags.isSplit() && OrigVT != MVT::ppcf128) 3293 Align = OrigVT.getStoreSize(); 3294 else 3295 Align = ArgVT.getStoreSize(); 3296 } 3297 3298 return Align; 3299 } 3300 3301 /// CalculateStackSlotUsed - Return whether this argument will use its 3302 /// stack slot (instead of being passed in registers). ArgOffset, 3303 /// AvailableFPRs, and AvailableVRs must hold the current argument 3304 /// position, and will be updated to account for this argument. 3305 static bool CalculateStackSlotUsed(EVT ArgVT, EVT OrigVT, 3306 ISD::ArgFlagsTy Flags, 3307 unsigned PtrByteSize, 3308 unsigned LinkageSize, 3309 unsigned ParamAreaSize, 3310 unsigned &ArgOffset, 3311 unsigned &AvailableFPRs, 3312 unsigned &AvailableVRs, bool HasQPX) { 3313 bool UseMemory = false; 3314 3315 // Respect alignment of argument on the stack. 3316 unsigned Align = 3317 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize); 3318 ArgOffset = ((ArgOffset + Align - 1) / Align) * Align; 3319 // If there's no space left in the argument save area, we must 3320 // use memory (this check also catches zero-sized arguments). 3321 if (ArgOffset >= LinkageSize + ParamAreaSize) 3322 UseMemory = true; 3323 3324 // Allocate argument on the stack. 3325 ArgOffset += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize); 3326 if (Flags.isInConsecutiveRegsLast()) 3327 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3328 // If we overran the argument save area, we must use memory 3329 // (this check catches arguments passed partially in memory) 3330 if (ArgOffset > LinkageSize + ParamAreaSize) 3331 UseMemory = true; 3332 3333 // However, if the argument is actually passed in an FPR or a VR, 3334 // we don't use memory after all. 3335 if (!Flags.isByVal()) { 3336 if (ArgVT == MVT::f32 || ArgVT == MVT::f64 || 3337 // QPX registers overlap with the scalar FP registers. 3338 (HasQPX && (ArgVT == MVT::v4f32 || 3339 ArgVT == MVT::v4f64 || 3340 ArgVT == MVT::v4i1))) 3341 if (AvailableFPRs > 0) { 3342 --AvailableFPRs; 3343 return false; 3344 } 3345 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 || 3346 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 || 3347 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 || 3348 ArgVT == MVT::v1i128 || ArgVT == MVT::f128) 3349 if (AvailableVRs > 0) { 3350 --AvailableVRs; 3351 return false; 3352 } 3353 } 3354 3355 return UseMemory; 3356 } 3357 3358 /// EnsureStackAlignment - Round stack frame size up from NumBytes to 3359 /// ensure minimum alignment required for target. 3360 static unsigned EnsureStackAlignment(const PPCFrameLowering *Lowering, 3361 unsigned NumBytes) { 3362 unsigned TargetAlign = Lowering->getStackAlignment(); 3363 unsigned AlignMask = TargetAlign - 1; 3364 NumBytes = (NumBytes + AlignMask) & ~AlignMask; 3365 return NumBytes; 3366 } 3367 3368 SDValue PPCTargetLowering::LowerFormalArguments( 3369 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3370 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3371 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3372 if (Subtarget.isSVR4ABI()) { 3373 if (Subtarget.isPPC64()) 3374 return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins, 3375 dl, DAG, InVals); 3376 else 3377 return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins, 3378 dl, DAG, InVals); 3379 } else { 3380 return LowerFormalArguments_Darwin(Chain, CallConv, isVarArg, Ins, 3381 dl, DAG, InVals); 3382 } 3383 } 3384 3385 SDValue PPCTargetLowering::LowerFormalArguments_32SVR4( 3386 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3387 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3388 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3389 3390 // 32-bit SVR4 ABI Stack Frame Layout: 3391 // +-----------------------------------+ 3392 // +--> | Back chain | 3393 // | +-----------------------------------+ 3394 // | | Floating-point register save area | 3395 // | +-----------------------------------+ 3396 // | | General register save area | 3397 // | +-----------------------------------+ 3398 // | | CR save word | 3399 // | +-----------------------------------+ 3400 // | | VRSAVE save word | 3401 // | +-----------------------------------+ 3402 // | | Alignment padding | 3403 // | +-----------------------------------+ 3404 // | | Vector register save area | 3405 // | +-----------------------------------+ 3406 // | | Local variable space | 3407 // | +-----------------------------------+ 3408 // | | Parameter list area | 3409 // | +-----------------------------------+ 3410 // | | LR save word | 3411 // | +-----------------------------------+ 3412 // SP--> +--- | Back chain | 3413 // +-----------------------------------+ 3414 // 3415 // Specifications: 3416 // System V Application Binary Interface PowerPC Processor Supplement 3417 // AltiVec Technology Programming Interface Manual 3418 3419 MachineFunction &MF = DAG.getMachineFunction(); 3420 MachineFrameInfo &MFI = MF.getFrameInfo(); 3421 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 3422 3423 EVT PtrVT = getPointerTy(MF.getDataLayout()); 3424 // Potential tail calls could cause overwriting of argument stack slots. 3425 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt && 3426 (CallConv == CallingConv::Fast)); 3427 unsigned PtrByteSize = 4; 3428 3429 // Assign locations to all of the incoming arguments. 3430 SmallVector<CCValAssign, 16> ArgLocs; 3431 PPCCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 3432 *DAG.getContext()); 3433 3434 // Reserve space for the linkage area on the stack. 3435 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 3436 CCInfo.AllocateStack(LinkageSize, PtrByteSize); 3437 if (useSoftFloat() || hasSPE()) 3438 CCInfo.PreAnalyzeFormalArguments(Ins); 3439 3440 CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4); 3441 CCInfo.clearWasPPCF128(); 3442 3443 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 3444 CCValAssign &VA = ArgLocs[i]; 3445 3446 // Arguments stored in registers. 3447 if (VA.isRegLoc()) { 3448 const TargetRegisterClass *RC; 3449 EVT ValVT = VA.getValVT(); 3450 3451 switch (ValVT.getSimpleVT().SimpleTy) { 3452 default: 3453 llvm_unreachable("ValVT not supported by formal arguments Lowering"); 3454 case MVT::i1: 3455 case MVT::i32: 3456 RC = &PPC::GPRCRegClass; 3457 break; 3458 case MVT::f32: 3459 if (Subtarget.hasP8Vector()) 3460 RC = &PPC::VSSRCRegClass; 3461 else if (Subtarget.hasSPE()) 3462 RC = &PPC::SPE4RCRegClass; 3463 else 3464 RC = &PPC::F4RCRegClass; 3465 break; 3466 case MVT::f64: 3467 if (Subtarget.hasVSX()) 3468 RC = &PPC::VSFRCRegClass; 3469 else if (Subtarget.hasSPE()) 3470 RC = &PPC::SPERCRegClass; 3471 else 3472 RC = &PPC::F8RCRegClass; 3473 break; 3474 case MVT::v16i8: 3475 case MVT::v8i16: 3476 case MVT::v4i32: 3477 RC = &PPC::VRRCRegClass; 3478 break; 3479 case MVT::v4f32: 3480 RC = Subtarget.hasQPX() ? &PPC::QSRCRegClass : &PPC::VRRCRegClass; 3481 break; 3482 case MVT::v2f64: 3483 case MVT::v2i64: 3484 RC = &PPC::VRRCRegClass; 3485 break; 3486 case MVT::v4f64: 3487 RC = &PPC::QFRCRegClass; 3488 break; 3489 case MVT::v4i1: 3490 RC = &PPC::QBRCRegClass; 3491 break; 3492 } 3493 3494 // Transform the arguments stored in physical registers into virtual ones. 3495 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC); 3496 SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, 3497 ValVT == MVT::i1 ? MVT::i32 : ValVT); 3498 3499 if (ValVT == MVT::i1) 3500 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue); 3501 3502 InVals.push_back(ArgValue); 3503 } else { 3504 // Argument stored in memory. 3505 assert(VA.isMemLoc()); 3506 3507 // Get the extended size of the argument type in stack 3508 unsigned ArgSize = VA.getLocVT().getStoreSize(); 3509 // Get the actual size of the argument type 3510 unsigned ObjSize = VA.getValVT().getStoreSize(); 3511 unsigned ArgOffset = VA.getLocMemOffset(); 3512 // Stack objects in PPC32 are right justified. 3513 ArgOffset += ArgSize - ObjSize; 3514 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, isImmutable); 3515 3516 // Create load nodes to retrieve arguments from the stack. 3517 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3518 InVals.push_back( 3519 DAG.getLoad(VA.getValVT(), dl, Chain, FIN, MachinePointerInfo())); 3520 } 3521 } 3522 3523 // Assign locations to all of the incoming aggregate by value arguments. 3524 // Aggregates passed by value are stored in the local variable space of the 3525 // caller's stack frame, right above the parameter list area. 3526 SmallVector<CCValAssign, 16> ByValArgLocs; 3527 CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(), 3528 ByValArgLocs, *DAG.getContext()); 3529 3530 // Reserve stack space for the allocations in CCInfo. 3531 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize); 3532 3533 CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal); 3534 3535 // Area that is at least reserved in the caller of this function. 3536 unsigned MinReservedArea = CCByValInfo.getNextStackOffset(); 3537 MinReservedArea = std::max(MinReservedArea, LinkageSize); 3538 3539 // Set the size that is at least reserved in caller of this function. Tail 3540 // call optimized function's reserved stack space needs to be aligned so that 3541 // taking the difference between two stack areas will result in an aligned 3542 // stack. 3543 MinReservedArea = 3544 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea); 3545 FuncInfo->setMinReservedArea(MinReservedArea); 3546 3547 SmallVector<SDValue, 8> MemOps; 3548 3549 // If the function takes variable number of arguments, make a frame index for 3550 // the start of the first vararg value... for expansion of llvm.va_start. 3551 if (isVarArg) { 3552 static const MCPhysReg GPArgRegs[] = { 3553 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 3554 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 3555 }; 3556 const unsigned NumGPArgRegs = array_lengthof(GPArgRegs); 3557 3558 static const MCPhysReg FPArgRegs[] = { 3559 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7, 3560 PPC::F8 3561 }; 3562 unsigned NumFPArgRegs = array_lengthof(FPArgRegs); 3563 3564 if (useSoftFloat() || hasSPE()) 3565 NumFPArgRegs = 0; 3566 3567 FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs)); 3568 FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs)); 3569 3570 // Make room for NumGPArgRegs and NumFPArgRegs. 3571 int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 + 3572 NumFPArgRegs * MVT(MVT::f64).getSizeInBits()/8; 3573 3574 FuncInfo->setVarArgsStackOffset( 3575 MFI.CreateFixedObject(PtrVT.getSizeInBits()/8, 3576 CCInfo.getNextStackOffset(), true)); 3577 3578 FuncInfo->setVarArgsFrameIndex(MFI.CreateStackObject(Depth, 8, false)); 3579 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 3580 3581 // The fixed integer arguments of a variadic function are stored to the 3582 // VarArgsFrameIndex on the stack so that they may be loaded by 3583 // dereferencing the result of va_next. 3584 for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) { 3585 // Get an existing live-in vreg, or add a new one. 3586 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]); 3587 if (!VReg) 3588 VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass); 3589 3590 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 3591 SDValue Store = 3592 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 3593 MemOps.push_back(Store); 3594 // Increment the address by four for the next argument to store 3595 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT); 3596 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 3597 } 3598 3599 // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6 3600 // is set. 3601 // The double arguments are stored to the VarArgsFrameIndex 3602 // on the stack. 3603 for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) { 3604 // Get an existing live-in vreg, or add a new one. 3605 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]); 3606 if (!VReg) 3607 VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass); 3608 3609 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64); 3610 SDValue Store = 3611 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 3612 MemOps.push_back(Store); 3613 // Increment the address by eight for the next argument to store 3614 SDValue PtrOff = DAG.getConstant(MVT(MVT::f64).getSizeInBits()/8, dl, 3615 PtrVT); 3616 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 3617 } 3618 } 3619 3620 if (!MemOps.empty()) 3621 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 3622 3623 return Chain; 3624 } 3625 3626 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote 3627 // value to MVT::i64 and then truncate to the correct register size. 3628 SDValue PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags, 3629 EVT ObjectVT, SelectionDAG &DAG, 3630 SDValue ArgVal, 3631 const SDLoc &dl) const { 3632 if (Flags.isSExt()) 3633 ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal, 3634 DAG.getValueType(ObjectVT)); 3635 else if (Flags.isZExt()) 3636 ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal, 3637 DAG.getValueType(ObjectVT)); 3638 3639 return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal); 3640 } 3641 3642 SDValue PPCTargetLowering::LowerFormalArguments_64SVR4( 3643 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3644 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3645 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3646 // TODO: add description of PPC stack frame format, or at least some docs. 3647 // 3648 bool isELFv2ABI = Subtarget.isELFv2ABI(); 3649 bool isLittleEndian = Subtarget.isLittleEndian(); 3650 MachineFunction &MF = DAG.getMachineFunction(); 3651 MachineFrameInfo &MFI = MF.getFrameInfo(); 3652 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 3653 3654 assert(!(CallConv == CallingConv::Fast && isVarArg) && 3655 "fastcc not supported on varargs functions"); 3656 3657 EVT PtrVT = getPointerTy(MF.getDataLayout()); 3658 // Potential tail calls could cause overwriting of argument stack slots. 3659 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt && 3660 (CallConv == CallingConv::Fast)); 3661 unsigned PtrByteSize = 8; 3662 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 3663 3664 static const MCPhysReg GPR[] = { 3665 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 3666 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 3667 }; 3668 static const MCPhysReg VR[] = { 3669 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 3670 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 3671 }; 3672 3673 const unsigned Num_GPR_Regs = array_lengthof(GPR); 3674 const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13; 3675 const unsigned Num_VR_Regs = array_lengthof(VR); 3676 const unsigned Num_QFPR_Regs = Num_FPR_Regs; 3677 3678 // Do a first pass over the arguments to determine whether the ABI 3679 // guarantees that our caller has allocated the parameter save area 3680 // on its stack frame. In the ELFv1 ABI, this is always the case; 3681 // in the ELFv2 ABI, it is true if this is a vararg function or if 3682 // any parameter is located in a stack slot. 3683 3684 bool HasParameterArea = !isELFv2ABI || isVarArg; 3685 unsigned ParamAreaSize = Num_GPR_Regs * PtrByteSize; 3686 unsigned NumBytes = LinkageSize; 3687 unsigned AvailableFPRs = Num_FPR_Regs; 3688 unsigned AvailableVRs = Num_VR_Regs; 3689 for (unsigned i = 0, e = Ins.size(); i != e; ++i) { 3690 if (Ins[i].Flags.isNest()) 3691 continue; 3692 3693 if (CalculateStackSlotUsed(Ins[i].VT, Ins[i].ArgVT, Ins[i].Flags, 3694 PtrByteSize, LinkageSize, ParamAreaSize, 3695 NumBytes, AvailableFPRs, AvailableVRs, 3696 Subtarget.hasQPX())) 3697 HasParameterArea = true; 3698 } 3699 3700 // Add DAG nodes to load the arguments or copy them out of registers. On 3701 // entry to a function on PPC, the arguments start after the linkage area, 3702 // although the first ones are often in registers. 3703 3704 unsigned ArgOffset = LinkageSize; 3705 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 3706 unsigned &QFPR_idx = FPR_idx; 3707 SmallVector<SDValue, 8> MemOps; 3708 Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin(); 3709 unsigned CurArgIdx = 0; 3710 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) { 3711 SDValue ArgVal; 3712 bool needsLoad = false; 3713 EVT ObjectVT = Ins[ArgNo].VT; 3714 EVT OrigVT = Ins[ArgNo].ArgVT; 3715 unsigned ObjSize = ObjectVT.getStoreSize(); 3716 unsigned ArgSize = ObjSize; 3717 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags; 3718 if (Ins[ArgNo].isOrigArg()) { 3719 std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx); 3720 CurArgIdx = Ins[ArgNo].getOrigArgIndex(); 3721 } 3722 // We re-align the argument offset for each argument, except when using the 3723 // fast calling convention, when we need to make sure we do that only when 3724 // we'll actually use a stack slot. 3725 unsigned CurArgOffset, Align; 3726 auto ComputeArgOffset = [&]() { 3727 /* Respect alignment of argument on the stack. */ 3728 Align = CalculateStackSlotAlignment(ObjectVT, OrigVT, Flags, PtrByteSize); 3729 ArgOffset = ((ArgOffset + Align - 1) / Align) * Align; 3730 CurArgOffset = ArgOffset; 3731 }; 3732 3733 if (CallConv != CallingConv::Fast) { 3734 ComputeArgOffset(); 3735 3736 /* Compute GPR index associated with argument offset. */ 3737 GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize; 3738 GPR_idx = std::min(GPR_idx, Num_GPR_Regs); 3739 } 3740 3741 // FIXME the codegen can be much improved in some cases. 3742 // We do not have to keep everything in memory. 3743 if (Flags.isByVal()) { 3744 assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit"); 3745 3746 if (CallConv == CallingConv::Fast) 3747 ComputeArgOffset(); 3748 3749 // ObjSize is the true size, ArgSize rounded up to multiple of registers. 3750 ObjSize = Flags.getByValSize(); 3751 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3752 // Empty aggregate parameters do not take up registers. Examples: 3753 // struct { } a; 3754 // union { } b; 3755 // int c[0]; 3756 // etc. However, we have to provide a place-holder in InVals, so 3757 // pretend we have an 8-byte item at the current address for that 3758 // purpose. 3759 if (!ObjSize) { 3760 int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true); 3761 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3762 InVals.push_back(FIN); 3763 continue; 3764 } 3765 3766 // Create a stack object covering all stack doublewords occupied 3767 // by the argument. If the argument is (fully or partially) on 3768 // the stack, or if the argument is fully in registers but the 3769 // caller has allocated the parameter save anyway, we can refer 3770 // directly to the caller's stack frame. Otherwise, create a 3771 // local copy in our own frame. 3772 int FI; 3773 if (HasParameterArea || 3774 ArgSize + ArgOffset > LinkageSize + Num_GPR_Regs * PtrByteSize) 3775 FI = MFI.CreateFixedObject(ArgSize, ArgOffset, false, true); 3776 else 3777 FI = MFI.CreateStackObject(ArgSize, Align, false); 3778 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3779 3780 // Handle aggregates smaller than 8 bytes. 3781 if (ObjSize < PtrByteSize) { 3782 // The value of the object is its address, which differs from the 3783 // address of the enclosing doubleword on big-endian systems. 3784 SDValue Arg = FIN; 3785 if (!isLittleEndian) { 3786 SDValue ArgOff = DAG.getConstant(PtrByteSize - ObjSize, dl, PtrVT); 3787 Arg = DAG.getNode(ISD::ADD, dl, ArgOff.getValueType(), Arg, ArgOff); 3788 } 3789 InVals.push_back(Arg); 3790 3791 if (GPR_idx != Num_GPR_Regs) { 3792 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass); 3793 FuncInfo->addLiveInAttr(VReg, Flags); 3794 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 3795 SDValue Store; 3796 3797 if (ObjSize==1 || ObjSize==2 || ObjSize==4) { 3798 EVT ObjType = (ObjSize == 1 ? MVT::i8 : 3799 (ObjSize == 2 ? MVT::i16 : MVT::i32)); 3800 Store = DAG.getTruncStore(Val.getValue(1), dl, Val, Arg, 3801 MachinePointerInfo(&*FuncArg), ObjType); 3802 } else { 3803 // For sizes that don't fit a truncating store (3, 5, 6, 7), 3804 // store the whole register as-is to the parameter save area 3805 // slot. 3806 Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, 3807 MachinePointerInfo(&*FuncArg)); 3808 } 3809 3810 MemOps.push_back(Store); 3811 } 3812 // Whether we copied from a register or not, advance the offset 3813 // into the parameter save area by a full doubleword. 3814 ArgOffset += PtrByteSize; 3815 continue; 3816 } 3817 3818 // The value of the object is its address, which is the address of 3819 // its first stack doubleword. 3820 InVals.push_back(FIN); 3821 3822 // Store whatever pieces of the object are in registers to memory. 3823 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) { 3824 if (GPR_idx == Num_GPR_Regs) 3825 break; 3826 3827 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 3828 FuncInfo->addLiveInAttr(VReg, Flags); 3829 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 3830 SDValue Addr = FIN; 3831 if (j) { 3832 SDValue Off = DAG.getConstant(j, dl, PtrVT); 3833 Addr = DAG.getNode(ISD::ADD, dl, Off.getValueType(), Addr, Off); 3834 } 3835 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, Addr, 3836 MachinePointerInfo(&*FuncArg, j)); 3837 MemOps.push_back(Store); 3838 ++GPR_idx; 3839 } 3840 ArgOffset += ArgSize; 3841 continue; 3842 } 3843 3844 switch (ObjectVT.getSimpleVT().SimpleTy) { 3845 default: llvm_unreachable("Unhandled argument type!"); 3846 case MVT::i1: 3847 case MVT::i32: 3848 case MVT::i64: 3849 if (Flags.isNest()) { 3850 // The 'nest' parameter, if any, is passed in R11. 3851 unsigned VReg = MF.addLiveIn(PPC::X11, &PPC::G8RCRegClass); 3852 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 3853 3854 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1) 3855 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl); 3856 3857 break; 3858 } 3859 3860 // These can be scalar arguments or elements of an integer array type 3861 // passed directly. Clang may use those instead of "byval" aggregate 3862 // types to avoid forcing arguments to memory unnecessarily. 3863 if (GPR_idx != Num_GPR_Regs) { 3864 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass); 3865 FuncInfo->addLiveInAttr(VReg, Flags); 3866 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 3867 3868 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1) 3869 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote 3870 // value to MVT::i64 and then truncate to the correct register size. 3871 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl); 3872 } else { 3873 if (CallConv == CallingConv::Fast) 3874 ComputeArgOffset(); 3875 3876 needsLoad = true; 3877 ArgSize = PtrByteSize; 3878 } 3879 if (CallConv != CallingConv::Fast || needsLoad) 3880 ArgOffset += 8; 3881 break; 3882 3883 case MVT::f32: 3884 case MVT::f64: 3885 // These can be scalar arguments or elements of a float array type 3886 // passed directly. The latter are used to implement ELFv2 homogenous 3887 // float aggregates. 3888 if (FPR_idx != Num_FPR_Regs) { 3889 unsigned VReg; 3890 3891 if (ObjectVT == MVT::f32) 3892 VReg = MF.addLiveIn(FPR[FPR_idx], 3893 Subtarget.hasP8Vector() 3894 ? &PPC::VSSRCRegClass 3895 : &PPC::F4RCRegClass); 3896 else 3897 VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX() 3898 ? &PPC::VSFRCRegClass 3899 : &PPC::F8RCRegClass); 3900 3901 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 3902 ++FPR_idx; 3903 } else if (GPR_idx != Num_GPR_Regs && CallConv != CallingConv::Fast) { 3904 // FIXME: We may want to re-enable this for CallingConv::Fast on the P8 3905 // once we support fp <-> gpr moves. 3906 3907 // This can only ever happen in the presence of f32 array types, 3908 // since otherwise we never run out of FPRs before running out 3909 // of GPRs. 3910 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass); 3911 FuncInfo->addLiveInAttr(VReg, Flags); 3912 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 3913 3914 if (ObjectVT == MVT::f32) { 3915 if ((ArgOffset % PtrByteSize) == (isLittleEndian ? 4 : 0)) 3916 ArgVal = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgVal, 3917 DAG.getConstant(32, dl, MVT::i32)); 3918 ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal); 3919 } 3920 3921 ArgVal = DAG.getNode(ISD::BITCAST, dl, ObjectVT, ArgVal); 3922 } else { 3923 if (CallConv == CallingConv::Fast) 3924 ComputeArgOffset(); 3925 3926 needsLoad = true; 3927 } 3928 3929 // When passing an array of floats, the array occupies consecutive 3930 // space in the argument area; only round up to the next doubleword 3931 // at the end of the array. Otherwise, each float takes 8 bytes. 3932 if (CallConv != CallingConv::Fast || needsLoad) { 3933 ArgSize = Flags.isInConsecutiveRegs() ? ObjSize : PtrByteSize; 3934 ArgOffset += ArgSize; 3935 if (Flags.isInConsecutiveRegsLast()) 3936 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3937 } 3938 break; 3939 case MVT::v4f32: 3940 case MVT::v4i32: 3941 case MVT::v8i16: 3942 case MVT::v16i8: 3943 case MVT::v2f64: 3944 case MVT::v2i64: 3945 case MVT::v1i128: 3946 case MVT::f128: 3947 if (!Subtarget.hasQPX()) { 3948 // These can be scalar arguments or elements of a vector array type 3949 // passed directly. The latter are used to implement ELFv2 homogenous 3950 // vector aggregates. 3951 if (VR_idx != Num_VR_Regs) { 3952 unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass); 3953 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 3954 ++VR_idx; 3955 } else { 3956 if (CallConv == CallingConv::Fast) 3957 ComputeArgOffset(); 3958 needsLoad = true; 3959 } 3960 if (CallConv != CallingConv::Fast || needsLoad) 3961 ArgOffset += 16; 3962 break; 3963 } // not QPX 3964 3965 assert(ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 && 3966 "Invalid QPX parameter type"); 3967 LLVM_FALLTHROUGH; 3968 3969 case MVT::v4f64: 3970 case MVT::v4i1: 3971 // QPX vectors are treated like their scalar floating-point subregisters 3972 // (except that they're larger). 3973 unsigned Sz = ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 ? 16 : 32; 3974 if (QFPR_idx != Num_QFPR_Regs) { 3975 const TargetRegisterClass *RC; 3976 switch (ObjectVT.getSimpleVT().SimpleTy) { 3977 case MVT::v4f64: RC = &PPC::QFRCRegClass; break; 3978 case MVT::v4f32: RC = &PPC::QSRCRegClass; break; 3979 default: RC = &PPC::QBRCRegClass; break; 3980 } 3981 3982 unsigned VReg = MF.addLiveIn(QFPR[QFPR_idx], RC); 3983 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 3984 ++QFPR_idx; 3985 } else { 3986 if (CallConv == CallingConv::Fast) 3987 ComputeArgOffset(); 3988 needsLoad = true; 3989 } 3990 if (CallConv != CallingConv::Fast || needsLoad) 3991 ArgOffset += Sz; 3992 break; 3993 } 3994 3995 // We need to load the argument to a virtual register if we determined 3996 // above that we ran out of physical registers of the appropriate type. 3997 if (needsLoad) { 3998 if (ObjSize < ArgSize && !isLittleEndian) 3999 CurArgOffset += ArgSize - ObjSize; 4000 int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, isImmutable); 4001 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4002 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo()); 4003 } 4004 4005 InVals.push_back(ArgVal); 4006 } 4007 4008 // Area that is at least reserved in the caller of this function. 4009 unsigned MinReservedArea; 4010 if (HasParameterArea) 4011 MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize); 4012 else 4013 MinReservedArea = LinkageSize; 4014 4015 // Set the size that is at least reserved in caller of this function. Tail 4016 // call optimized functions' reserved stack space needs to be aligned so that 4017 // taking the difference between two stack areas will result in an aligned 4018 // stack. 4019 MinReservedArea = 4020 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea); 4021 FuncInfo->setMinReservedArea(MinReservedArea); 4022 4023 // If the function takes variable number of arguments, make a frame index for 4024 // the start of the first vararg value... for expansion of llvm.va_start. 4025 if (isVarArg) { 4026 int Depth = ArgOffset; 4027 4028 FuncInfo->setVarArgsFrameIndex( 4029 MFI.CreateFixedObject(PtrByteSize, Depth, true)); 4030 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 4031 4032 // If this function is vararg, store any remaining integer argument regs 4033 // to their spots on the stack so that they may be loaded by dereferencing 4034 // the result of va_next. 4035 for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize; 4036 GPR_idx < Num_GPR_Regs; ++GPR_idx) { 4037 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4038 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4039 SDValue Store = 4040 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 4041 MemOps.push_back(Store); 4042 // Increment the address by four for the next argument to store 4043 SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT); 4044 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 4045 } 4046 } 4047 4048 if (!MemOps.empty()) 4049 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 4050 4051 return Chain; 4052 } 4053 4054 SDValue PPCTargetLowering::LowerFormalArguments_Darwin( 4055 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 4056 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 4057 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 4058 // TODO: add description of PPC stack frame format, or at least some docs. 4059 // 4060 MachineFunction &MF = DAG.getMachineFunction(); 4061 MachineFrameInfo &MFI = MF.getFrameInfo(); 4062 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 4063 4064 EVT PtrVT = getPointerTy(MF.getDataLayout()); 4065 bool isPPC64 = PtrVT == MVT::i64; 4066 // Potential tail calls could cause overwriting of argument stack slots. 4067 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt && 4068 (CallConv == CallingConv::Fast)); 4069 unsigned PtrByteSize = isPPC64 ? 8 : 4; 4070 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 4071 unsigned ArgOffset = LinkageSize; 4072 // Area that is at least reserved in caller of this function. 4073 unsigned MinReservedArea = ArgOffset; 4074 4075 static const MCPhysReg GPR_32[] = { // 32-bit registers. 4076 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 4077 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 4078 }; 4079 static const MCPhysReg GPR_64[] = { // 64-bit registers. 4080 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 4081 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 4082 }; 4083 static const MCPhysReg VR[] = { 4084 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 4085 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 4086 }; 4087 4088 const unsigned Num_GPR_Regs = array_lengthof(GPR_32); 4089 const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13; 4090 const unsigned Num_VR_Regs = array_lengthof( VR); 4091 4092 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 4093 4094 const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32; 4095 4096 // In 32-bit non-varargs functions, the stack space for vectors is after the 4097 // stack space for non-vectors. We do not use this space unless we have 4098 // too many vectors to fit in registers, something that only occurs in 4099 // constructed examples:), but we have to walk the arglist to figure 4100 // that out...for the pathological case, compute VecArgOffset as the 4101 // start of the vector parameter area. Computing VecArgOffset is the 4102 // entire point of the following loop. 4103 unsigned VecArgOffset = ArgOffset; 4104 if (!isVarArg && !isPPC64) { 4105 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; 4106 ++ArgNo) { 4107 EVT ObjectVT = Ins[ArgNo].VT; 4108 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags; 4109 4110 if (Flags.isByVal()) { 4111 // ObjSize is the true size, ArgSize rounded up to multiple of regs. 4112 unsigned ObjSize = Flags.getByValSize(); 4113 unsigned ArgSize = 4114 ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 4115 VecArgOffset += ArgSize; 4116 continue; 4117 } 4118 4119 switch(ObjectVT.getSimpleVT().SimpleTy) { 4120 default: llvm_unreachable("Unhandled argument type!"); 4121 case MVT::i1: 4122 case MVT::i32: 4123 case MVT::f32: 4124 VecArgOffset += 4; 4125 break; 4126 case MVT::i64: // PPC64 4127 case MVT::f64: 4128 // FIXME: We are guaranteed to be !isPPC64 at this point. 4129 // Does MVT::i64 apply? 4130 VecArgOffset += 8; 4131 break; 4132 case MVT::v4f32: 4133 case MVT::v4i32: 4134 case MVT::v8i16: 4135 case MVT::v16i8: 4136 // Nothing to do, we're only looking at Nonvector args here. 4137 break; 4138 } 4139 } 4140 } 4141 // We've found where the vector parameter area in memory is. Skip the 4142 // first 12 parameters; these don't use that memory. 4143 VecArgOffset = ((VecArgOffset+15)/16)*16; 4144 VecArgOffset += 12*16; 4145 4146 // Add DAG nodes to load the arguments or copy them out of registers. On 4147 // entry to a function on PPC, the arguments start after the linkage area, 4148 // although the first ones are often in registers. 4149 4150 SmallVector<SDValue, 8> MemOps; 4151 unsigned nAltivecParamsAtEnd = 0; 4152 Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin(); 4153 unsigned CurArgIdx = 0; 4154 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) { 4155 SDValue ArgVal; 4156 bool needsLoad = false; 4157 EVT ObjectVT = Ins[ArgNo].VT; 4158 unsigned ObjSize = ObjectVT.getSizeInBits()/8; 4159 unsigned ArgSize = ObjSize; 4160 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags; 4161 if (Ins[ArgNo].isOrigArg()) { 4162 std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx); 4163 CurArgIdx = Ins[ArgNo].getOrigArgIndex(); 4164 } 4165 unsigned CurArgOffset = ArgOffset; 4166 4167 // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary. 4168 if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 || 4169 ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) { 4170 if (isVarArg || isPPC64) { 4171 MinReservedArea = ((MinReservedArea+15)/16)*16; 4172 MinReservedArea += CalculateStackSlotSize(ObjectVT, 4173 Flags, 4174 PtrByteSize); 4175 } else nAltivecParamsAtEnd++; 4176 } else 4177 // Calculate min reserved area. 4178 MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT, 4179 Flags, 4180 PtrByteSize); 4181 4182 // FIXME the codegen can be much improved in some cases. 4183 // We do not have to keep everything in memory. 4184 if (Flags.isByVal()) { 4185 assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit"); 4186 4187 // ObjSize is the true size, ArgSize rounded up to multiple of registers. 4188 ObjSize = Flags.getByValSize(); 4189 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 4190 // Objects of size 1 and 2 are right justified, everything else is 4191 // left justified. This means the memory address is adjusted forwards. 4192 if (ObjSize==1 || ObjSize==2) { 4193 CurArgOffset = CurArgOffset + (4 - ObjSize); 4194 } 4195 // The value of the object is its address. 4196 int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, false, true); 4197 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4198 InVals.push_back(FIN); 4199 if (ObjSize==1 || ObjSize==2) { 4200 if (GPR_idx != Num_GPR_Regs) { 4201 unsigned VReg; 4202 if (isPPC64) 4203 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4204 else 4205 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 4206 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4207 EVT ObjType = ObjSize == 1 ? MVT::i8 : MVT::i16; 4208 SDValue Store = 4209 DAG.getTruncStore(Val.getValue(1), dl, Val, FIN, 4210 MachinePointerInfo(&*FuncArg), ObjType); 4211 MemOps.push_back(Store); 4212 ++GPR_idx; 4213 } 4214 4215 ArgOffset += PtrByteSize; 4216 4217 continue; 4218 } 4219 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) { 4220 // Store whatever pieces of the object are in registers 4221 // to memory. ArgOffset will be the address of the beginning 4222 // of the object. 4223 if (GPR_idx != Num_GPR_Regs) { 4224 unsigned VReg; 4225 if (isPPC64) 4226 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4227 else 4228 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 4229 int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true); 4230 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4231 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4232 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, 4233 MachinePointerInfo(&*FuncArg, j)); 4234 MemOps.push_back(Store); 4235 ++GPR_idx; 4236 ArgOffset += PtrByteSize; 4237 } else { 4238 ArgOffset += ArgSize - (ArgOffset-CurArgOffset); 4239 break; 4240 } 4241 } 4242 continue; 4243 } 4244 4245 switch (ObjectVT.getSimpleVT().SimpleTy) { 4246 default: llvm_unreachable("Unhandled argument type!"); 4247 case MVT::i1: 4248 case MVT::i32: 4249 if (!isPPC64) { 4250 if (GPR_idx != Num_GPR_Regs) { 4251 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 4252 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32); 4253 4254 if (ObjectVT == MVT::i1) 4255 ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgVal); 4256 4257 ++GPR_idx; 4258 } else { 4259 needsLoad = true; 4260 ArgSize = PtrByteSize; 4261 } 4262 // All int arguments reserve stack space in the Darwin ABI. 4263 ArgOffset += PtrByteSize; 4264 break; 4265 } 4266 LLVM_FALLTHROUGH; 4267 case MVT::i64: // PPC64 4268 if (GPR_idx != Num_GPR_Regs) { 4269 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4270 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 4271 4272 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1) 4273 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote 4274 // value to MVT::i64 and then truncate to the correct register size. 4275 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl); 4276 4277 ++GPR_idx; 4278 } else { 4279 needsLoad = true; 4280 ArgSize = PtrByteSize; 4281 } 4282 // All int arguments reserve stack space in the Darwin ABI. 4283 ArgOffset += 8; 4284 break; 4285 4286 case MVT::f32: 4287 case MVT::f64: 4288 // Every 4 bytes of argument space consumes one of the GPRs available for 4289 // argument passing. 4290 if (GPR_idx != Num_GPR_Regs) { 4291 ++GPR_idx; 4292 if (ObjSize == 8 && GPR_idx != Num_GPR_Regs && !isPPC64) 4293 ++GPR_idx; 4294 } 4295 if (FPR_idx != Num_FPR_Regs) { 4296 unsigned VReg; 4297 4298 if (ObjectVT == MVT::f32) 4299 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass); 4300 else 4301 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass); 4302 4303 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 4304 ++FPR_idx; 4305 } else { 4306 needsLoad = true; 4307 } 4308 4309 // All FP arguments reserve stack space in the Darwin ABI. 4310 ArgOffset += isPPC64 ? 8 : ObjSize; 4311 break; 4312 case MVT::v4f32: 4313 case MVT::v4i32: 4314 case MVT::v8i16: 4315 case MVT::v16i8: 4316 // Note that vector arguments in registers don't reserve stack space, 4317 // except in varargs functions. 4318 if (VR_idx != Num_VR_Regs) { 4319 unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass); 4320 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 4321 if (isVarArg) { 4322 while ((ArgOffset % 16) != 0) { 4323 ArgOffset += PtrByteSize; 4324 if (GPR_idx != Num_GPR_Regs) 4325 GPR_idx++; 4326 } 4327 ArgOffset += 16; 4328 GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64? 4329 } 4330 ++VR_idx; 4331 } else { 4332 if (!isVarArg && !isPPC64) { 4333 // Vectors go after all the nonvectors. 4334 CurArgOffset = VecArgOffset; 4335 VecArgOffset += 16; 4336 } else { 4337 // Vectors are aligned. 4338 ArgOffset = ((ArgOffset+15)/16)*16; 4339 CurArgOffset = ArgOffset; 4340 ArgOffset += 16; 4341 } 4342 needsLoad = true; 4343 } 4344 break; 4345 } 4346 4347 // We need to load the argument to a virtual register if we determined above 4348 // that we ran out of physical registers of the appropriate type. 4349 if (needsLoad) { 4350 int FI = MFI.CreateFixedObject(ObjSize, 4351 CurArgOffset + (ArgSize - ObjSize), 4352 isImmutable); 4353 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4354 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo()); 4355 } 4356 4357 InVals.push_back(ArgVal); 4358 } 4359 4360 // Allow for Altivec parameters at the end, if needed. 4361 if (nAltivecParamsAtEnd) { 4362 MinReservedArea = ((MinReservedArea+15)/16)*16; 4363 MinReservedArea += 16*nAltivecParamsAtEnd; 4364 } 4365 4366 // Area that is at least reserved in the caller of this function. 4367 MinReservedArea = std::max(MinReservedArea, LinkageSize + 8 * PtrByteSize); 4368 4369 // Set the size that is at least reserved in caller of this function. Tail 4370 // call optimized functions' reserved stack space needs to be aligned so that 4371 // taking the difference between two stack areas will result in an aligned 4372 // stack. 4373 MinReservedArea = 4374 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea); 4375 FuncInfo->setMinReservedArea(MinReservedArea); 4376 4377 // If the function takes variable number of arguments, make a frame index for 4378 // the start of the first vararg value... for expansion of llvm.va_start. 4379 if (isVarArg) { 4380 int Depth = ArgOffset; 4381 4382 FuncInfo->setVarArgsFrameIndex( 4383 MFI.CreateFixedObject(PtrVT.getSizeInBits()/8, 4384 Depth, true)); 4385 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 4386 4387 // If this function is vararg, store any remaining integer argument regs 4388 // to their spots on the stack so that they may be loaded by dereferencing 4389 // the result of va_next. 4390 for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) { 4391 unsigned VReg; 4392 4393 if (isPPC64) 4394 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4395 else 4396 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 4397 4398 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4399 SDValue Store = 4400 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 4401 MemOps.push_back(Store); 4402 // Increment the address by four for the next argument to store 4403 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT); 4404 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 4405 } 4406 } 4407 4408 if (!MemOps.empty()) 4409 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 4410 4411 return Chain; 4412 } 4413 4414 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be 4415 /// adjusted to accommodate the arguments for the tailcall. 4416 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall, 4417 unsigned ParamSize) { 4418 4419 if (!isTailCall) return 0; 4420 4421 PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>(); 4422 unsigned CallerMinReservedArea = FI->getMinReservedArea(); 4423 int SPDiff = (int)CallerMinReservedArea - (int)ParamSize; 4424 // Remember only if the new adjustment is bigger. 4425 if (SPDiff < FI->getTailCallSPDelta()) 4426 FI->setTailCallSPDelta(SPDiff); 4427 4428 return SPDiff; 4429 } 4430 4431 static bool isFunctionGlobalAddress(SDValue Callee); 4432 4433 static bool 4434 callsShareTOCBase(const Function *Caller, SDValue Callee, 4435 const TargetMachine &TM) { 4436 // If !G, Callee can be an external symbol. 4437 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee); 4438 if (!G) 4439 return false; 4440 4441 // The medium and large code models are expected to provide a sufficiently 4442 // large TOC to provide all data addressing needs of a module with a 4443 // single TOC. Since each module will be addressed with a single TOC then we 4444 // only need to check that caller and callee don't cross dso boundaries. 4445 if (CodeModel::Medium == TM.getCodeModel() || 4446 CodeModel::Large == TM.getCodeModel()) 4447 return TM.shouldAssumeDSOLocal(*Caller->getParent(), G->getGlobal()); 4448 4449 // Otherwise we need to ensure callee and caller are in the same section, 4450 // since the linker may allocate multiple TOCs, and we don't know which 4451 // sections will belong to the same TOC base. 4452 4453 const GlobalValue *GV = G->getGlobal(); 4454 if (!GV->isStrongDefinitionForLinker()) 4455 return false; 4456 4457 // Any explicitly-specified sections and section prefixes must also match. 4458 // Also, if we're using -ffunction-sections, then each function is always in 4459 // a different section (the same is true for COMDAT functions). 4460 if (TM.getFunctionSections() || GV->hasComdat() || Caller->hasComdat() || 4461 GV->getSection() != Caller->getSection()) 4462 return false; 4463 if (const auto *F = dyn_cast<Function>(GV)) { 4464 if (F->getSectionPrefix() != Caller->getSectionPrefix()) 4465 return false; 4466 } 4467 4468 // If the callee might be interposed, then we can't assume the ultimate call 4469 // target will be in the same section. Even in cases where we can assume that 4470 // interposition won't happen, in any case where the linker might insert a 4471 // stub to allow for interposition, we must generate code as though 4472 // interposition might occur. To understand why this matters, consider a 4473 // situation where: a -> b -> c where the arrows indicate calls. b and c are 4474 // in the same section, but a is in a different module (i.e. has a different 4475 // TOC base pointer). If the linker allows for interposition between b and c, 4476 // then it will generate a stub for the call edge between b and c which will 4477 // save the TOC pointer into the designated stack slot allocated by b. If we 4478 // return true here, and therefore allow a tail call between b and c, that 4479 // stack slot won't exist and the b -> c stub will end up saving b'c TOC base 4480 // pointer into the stack slot allocated by a (where the a -> b stub saved 4481 // a's TOC base pointer). If we're not considering a tail call, but rather, 4482 // whether a nop is needed after the call instruction in b, because the linker 4483 // will insert a stub, it might complain about a missing nop if we omit it 4484 // (although many don't complain in this case). 4485 if (!TM.shouldAssumeDSOLocal(*Caller->getParent(), GV)) 4486 return false; 4487 4488 return true; 4489 } 4490 4491 static bool 4492 needStackSlotPassParameters(const PPCSubtarget &Subtarget, 4493 const SmallVectorImpl<ISD::OutputArg> &Outs) { 4494 assert(Subtarget.isSVR4ABI() && Subtarget.isPPC64()); 4495 4496 const unsigned PtrByteSize = 8; 4497 const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 4498 4499 static const MCPhysReg GPR[] = { 4500 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 4501 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 4502 }; 4503 static const MCPhysReg VR[] = { 4504 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 4505 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 4506 }; 4507 4508 const unsigned NumGPRs = array_lengthof(GPR); 4509 const unsigned NumFPRs = 13; 4510 const unsigned NumVRs = array_lengthof(VR); 4511 const unsigned ParamAreaSize = NumGPRs * PtrByteSize; 4512 4513 unsigned NumBytes = LinkageSize; 4514 unsigned AvailableFPRs = NumFPRs; 4515 unsigned AvailableVRs = NumVRs; 4516 4517 for (const ISD::OutputArg& Param : Outs) { 4518 if (Param.Flags.isNest()) continue; 4519 4520 if (CalculateStackSlotUsed(Param.VT, Param.ArgVT, Param.Flags, 4521 PtrByteSize, LinkageSize, ParamAreaSize, 4522 NumBytes, AvailableFPRs, AvailableVRs, 4523 Subtarget.hasQPX())) 4524 return true; 4525 } 4526 return false; 4527 } 4528 4529 static bool 4530 hasSameArgumentList(const Function *CallerFn, ImmutableCallSite CS) { 4531 if (CS.arg_size() != CallerFn->arg_size()) 4532 return false; 4533 4534 ImmutableCallSite::arg_iterator CalleeArgIter = CS.arg_begin(); 4535 ImmutableCallSite::arg_iterator CalleeArgEnd = CS.arg_end(); 4536 Function::const_arg_iterator CallerArgIter = CallerFn->arg_begin(); 4537 4538 for (; CalleeArgIter != CalleeArgEnd; ++CalleeArgIter, ++CallerArgIter) { 4539 const Value* CalleeArg = *CalleeArgIter; 4540 const Value* CallerArg = &(*CallerArgIter); 4541 if (CalleeArg == CallerArg) 4542 continue; 4543 4544 // e.g. @caller([4 x i64] %a, [4 x i64] %b) { 4545 // tail call @callee([4 x i64] undef, [4 x i64] %b) 4546 // } 4547 // 1st argument of callee is undef and has the same type as caller. 4548 if (CalleeArg->getType() == CallerArg->getType() && 4549 isa<UndefValue>(CalleeArg)) 4550 continue; 4551 4552 return false; 4553 } 4554 4555 return true; 4556 } 4557 4558 // Returns true if TCO is possible between the callers and callees 4559 // calling conventions. 4560 static bool 4561 areCallingConvEligibleForTCO_64SVR4(CallingConv::ID CallerCC, 4562 CallingConv::ID CalleeCC) { 4563 // Tail calls are possible with fastcc and ccc. 4564 auto isTailCallableCC = [] (CallingConv::ID CC){ 4565 return CC == CallingConv::C || CC == CallingConv::Fast; 4566 }; 4567 if (!isTailCallableCC(CallerCC) || !isTailCallableCC(CalleeCC)) 4568 return false; 4569 4570 // We can safely tail call both fastcc and ccc callees from a c calling 4571 // convention caller. If the caller is fastcc, we may have less stack space 4572 // than a non-fastcc caller with the same signature so disable tail-calls in 4573 // that case. 4574 return CallerCC == CallingConv::C || CallerCC == CalleeCC; 4575 } 4576 4577 bool 4578 PPCTargetLowering::IsEligibleForTailCallOptimization_64SVR4( 4579 SDValue Callee, 4580 CallingConv::ID CalleeCC, 4581 ImmutableCallSite CS, 4582 bool isVarArg, 4583 const SmallVectorImpl<ISD::OutputArg> &Outs, 4584 const SmallVectorImpl<ISD::InputArg> &Ins, 4585 SelectionDAG& DAG) const { 4586 bool TailCallOpt = getTargetMachine().Options.GuaranteedTailCallOpt; 4587 4588 if (DisableSCO && !TailCallOpt) return false; 4589 4590 // Variadic argument functions are not supported. 4591 if (isVarArg) return false; 4592 4593 auto &Caller = DAG.getMachineFunction().getFunction(); 4594 // Check that the calling conventions are compatible for tco. 4595 if (!areCallingConvEligibleForTCO_64SVR4(Caller.getCallingConv(), CalleeCC)) 4596 return false; 4597 4598 // Caller contains any byval parameter is not supported. 4599 if (any_of(Ins, [](const ISD::InputArg &IA) { return IA.Flags.isByVal(); })) 4600 return false; 4601 4602 // Callee contains any byval parameter is not supported, too. 4603 // Note: This is a quick work around, because in some cases, e.g. 4604 // caller's stack size > callee's stack size, we are still able to apply 4605 // sibling call optimization. For example, gcc is able to do SCO for caller1 4606 // in the following example, but not for caller2. 4607 // struct test { 4608 // long int a; 4609 // char ary[56]; 4610 // } gTest; 4611 // __attribute__((noinline)) int callee(struct test v, struct test *b) { 4612 // b->a = v.a; 4613 // return 0; 4614 // } 4615 // void caller1(struct test a, struct test c, struct test *b) { 4616 // callee(gTest, b); } 4617 // void caller2(struct test *b) { callee(gTest, b); } 4618 if (any_of(Outs, [](const ISD::OutputArg& OA) { return OA.Flags.isByVal(); })) 4619 return false; 4620 4621 // If callee and caller use different calling conventions, we cannot pass 4622 // parameters on stack since offsets for the parameter area may be different. 4623 if (Caller.getCallingConv() != CalleeCC && 4624 needStackSlotPassParameters(Subtarget, Outs)) 4625 return false; 4626 4627 // No TCO/SCO on indirect call because Caller have to restore its TOC 4628 if (!isFunctionGlobalAddress(Callee) && 4629 !isa<ExternalSymbolSDNode>(Callee)) 4630 return false; 4631 4632 // If the caller and callee potentially have different TOC bases then we 4633 // cannot tail call since we need to restore the TOC pointer after the call. 4634 // ref: https://bugzilla.mozilla.org/show_bug.cgi?id=973977 4635 if (!callsShareTOCBase(&Caller, Callee, getTargetMachine())) 4636 return false; 4637 4638 // TCO allows altering callee ABI, so we don't have to check further. 4639 if (CalleeCC == CallingConv::Fast && TailCallOpt) 4640 return true; 4641 4642 if (DisableSCO) return false; 4643 4644 // If callee use the same argument list that caller is using, then we can 4645 // apply SCO on this case. If it is not, then we need to check if callee needs 4646 // stack for passing arguments. 4647 if (!hasSameArgumentList(&Caller, CS) && 4648 needStackSlotPassParameters(Subtarget, Outs)) { 4649 return false; 4650 } 4651 4652 return true; 4653 } 4654 4655 /// IsEligibleForTailCallOptimization - Check whether the call is eligible 4656 /// for tail call optimization. Targets which want to do tail call 4657 /// optimization should implement this function. 4658 bool 4659 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee, 4660 CallingConv::ID CalleeCC, 4661 bool isVarArg, 4662 const SmallVectorImpl<ISD::InputArg> &Ins, 4663 SelectionDAG& DAG) const { 4664 if (!getTargetMachine().Options.GuaranteedTailCallOpt) 4665 return false; 4666 4667 // Variable argument functions are not supported. 4668 if (isVarArg) 4669 return false; 4670 4671 MachineFunction &MF = DAG.getMachineFunction(); 4672 CallingConv::ID CallerCC = MF.getFunction().getCallingConv(); 4673 if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) { 4674 // Functions containing by val parameters are not supported. 4675 for (unsigned i = 0; i != Ins.size(); i++) { 4676 ISD::ArgFlagsTy Flags = Ins[i].Flags; 4677 if (Flags.isByVal()) return false; 4678 } 4679 4680 // Non-PIC/GOT tail calls are supported. 4681 if (getTargetMachine().getRelocationModel() != Reloc::PIC_) 4682 return true; 4683 4684 // At the moment we can only do local tail calls (in same module, hidden 4685 // or protected) if we are generating PIC. 4686 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) 4687 return G->getGlobal()->hasHiddenVisibility() 4688 || G->getGlobal()->hasProtectedVisibility(); 4689 } 4690 4691 return false; 4692 } 4693 4694 /// isCallCompatibleAddress - Return the immediate to use if the specified 4695 /// 32-bit value is representable in the immediate field of a BxA instruction. 4696 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) { 4697 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op); 4698 if (!C) return nullptr; 4699 4700 int Addr = C->getZExtValue(); 4701 if ((Addr & 3) != 0 || // Low 2 bits are implicitly zero. 4702 SignExtend32<26>(Addr) != Addr) 4703 return nullptr; // Top 6 bits have to be sext of immediate. 4704 4705 return DAG 4706 .getConstant( 4707 (int)C->getZExtValue() >> 2, SDLoc(Op), 4708 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout())) 4709 .getNode(); 4710 } 4711 4712 namespace { 4713 4714 struct TailCallArgumentInfo { 4715 SDValue Arg; 4716 SDValue FrameIdxOp; 4717 int FrameIdx = 0; 4718 4719 TailCallArgumentInfo() = default; 4720 }; 4721 4722 } // end anonymous namespace 4723 4724 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot. 4725 static void StoreTailCallArgumentsToStackSlot( 4726 SelectionDAG &DAG, SDValue Chain, 4727 const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs, 4728 SmallVectorImpl<SDValue> &MemOpChains, const SDLoc &dl) { 4729 for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) { 4730 SDValue Arg = TailCallArgs[i].Arg; 4731 SDValue FIN = TailCallArgs[i].FrameIdxOp; 4732 int FI = TailCallArgs[i].FrameIdx; 4733 // Store relative to framepointer. 4734 MemOpChains.push_back(DAG.getStore( 4735 Chain, dl, Arg, FIN, 4736 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI))); 4737 } 4738 } 4739 4740 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to 4741 /// the appropriate stack slot for the tail call optimized function call. 4742 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG, SDValue Chain, 4743 SDValue OldRetAddr, SDValue OldFP, 4744 int SPDiff, const SDLoc &dl) { 4745 if (SPDiff) { 4746 // Calculate the new stack slot for the return address. 4747 MachineFunction &MF = DAG.getMachineFunction(); 4748 const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>(); 4749 const PPCFrameLowering *FL = Subtarget.getFrameLowering(); 4750 bool isPPC64 = Subtarget.isPPC64(); 4751 int SlotSize = isPPC64 ? 8 : 4; 4752 int NewRetAddrLoc = SPDiff + FL->getReturnSaveOffset(); 4753 int NewRetAddr = MF.getFrameInfo().CreateFixedObject(SlotSize, 4754 NewRetAddrLoc, true); 4755 EVT VT = isPPC64 ? MVT::i64 : MVT::i32; 4756 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT); 4757 Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx, 4758 MachinePointerInfo::getFixedStack(MF, NewRetAddr)); 4759 4760 // When using the 32/64-bit SVR4 ABI there is no need to move the FP stack 4761 // slot as the FP is never overwritten. 4762 if (Subtarget.isDarwinABI()) { 4763 int NewFPLoc = SPDiff + FL->getFramePointerSaveOffset(); 4764 int NewFPIdx = MF.getFrameInfo().CreateFixedObject(SlotSize, NewFPLoc, 4765 true); 4766 SDValue NewFramePtrIdx = DAG.getFrameIndex(NewFPIdx, VT); 4767 Chain = DAG.getStore(Chain, dl, OldFP, NewFramePtrIdx, 4768 MachinePointerInfo::getFixedStack( 4769 DAG.getMachineFunction(), NewFPIdx)); 4770 } 4771 } 4772 return Chain; 4773 } 4774 4775 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate 4776 /// the position of the argument. 4777 static void 4778 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64, 4779 SDValue Arg, int SPDiff, unsigned ArgOffset, 4780 SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) { 4781 int Offset = ArgOffset + SPDiff; 4782 uint32_t OpSize = (Arg.getValueSizeInBits() + 7) / 8; 4783 int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true); 4784 EVT VT = isPPC64 ? MVT::i64 : MVT::i32; 4785 SDValue FIN = DAG.getFrameIndex(FI, VT); 4786 TailCallArgumentInfo Info; 4787 Info.Arg = Arg; 4788 Info.FrameIdxOp = FIN; 4789 Info.FrameIdx = FI; 4790 TailCallArguments.push_back(Info); 4791 } 4792 4793 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address 4794 /// stack slot. Returns the chain as result and the loaded frame pointers in 4795 /// LROpOut/FPOpout. Used when tail calling. 4796 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr( 4797 SelectionDAG &DAG, int SPDiff, SDValue Chain, SDValue &LROpOut, 4798 SDValue &FPOpOut, const SDLoc &dl) const { 4799 if (SPDiff) { 4800 // Load the LR and FP stack slot for later adjusting. 4801 EVT VT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32; 4802 LROpOut = getReturnAddrFrameIndex(DAG); 4803 LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo()); 4804 Chain = SDValue(LROpOut.getNode(), 1); 4805 4806 // When using the 32/64-bit SVR4 ABI there is no need to load the FP stack 4807 // slot as the FP is never overwritten. 4808 if (Subtarget.isDarwinABI()) { 4809 FPOpOut = getFramePointerFrameIndex(DAG); 4810 FPOpOut = DAG.getLoad(VT, dl, Chain, FPOpOut, MachinePointerInfo()); 4811 Chain = SDValue(FPOpOut.getNode(), 1); 4812 } 4813 } 4814 return Chain; 4815 } 4816 4817 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified 4818 /// by "Src" to address "Dst" of size "Size". Alignment information is 4819 /// specified by the specific parameter attribute. The copy will be passed as 4820 /// a byval function parameter. 4821 /// Sometimes what we are copying is the end of a larger object, the part that 4822 /// does not fit in registers. 4823 static SDValue CreateCopyOfByValArgument(SDValue Src, SDValue Dst, 4824 SDValue Chain, ISD::ArgFlagsTy Flags, 4825 SelectionDAG &DAG, const SDLoc &dl) { 4826 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32); 4827 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(), 4828 false, false, false, MachinePointerInfo(), 4829 MachinePointerInfo()); 4830 } 4831 4832 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of 4833 /// tail calls. 4834 static void LowerMemOpCallTo( 4835 SelectionDAG &DAG, MachineFunction &MF, SDValue Chain, SDValue Arg, 4836 SDValue PtrOff, int SPDiff, unsigned ArgOffset, bool isPPC64, 4837 bool isTailCall, bool isVector, SmallVectorImpl<SDValue> &MemOpChains, 4838 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments, const SDLoc &dl) { 4839 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 4840 if (!isTailCall) { 4841 if (isVector) { 4842 SDValue StackPtr; 4843 if (isPPC64) 4844 StackPtr = DAG.getRegister(PPC::X1, MVT::i64); 4845 else 4846 StackPtr = DAG.getRegister(PPC::R1, MVT::i32); 4847 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, 4848 DAG.getConstant(ArgOffset, dl, PtrVT)); 4849 } 4850 MemOpChains.push_back( 4851 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo())); 4852 // Calculate and remember argument location. 4853 } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset, 4854 TailCallArguments); 4855 } 4856 4857 static void 4858 PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain, 4859 const SDLoc &dl, int SPDiff, unsigned NumBytes, SDValue LROp, 4860 SDValue FPOp, 4861 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) { 4862 // Emit a sequence of copyto/copyfrom virtual registers for arguments that 4863 // might overwrite each other in case of tail call optimization. 4864 SmallVector<SDValue, 8> MemOpChains2; 4865 // Do not flag preceding copytoreg stuff together with the following stuff. 4866 InFlag = SDValue(); 4867 StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments, 4868 MemOpChains2, dl); 4869 if (!MemOpChains2.empty()) 4870 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2); 4871 4872 // Store the return address to the appropriate stack slot. 4873 Chain = EmitTailCallStoreFPAndRetAddr(DAG, Chain, LROp, FPOp, SPDiff, dl); 4874 4875 // Emit callseq_end just before tailcall node. 4876 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true), 4877 DAG.getIntPtrConstant(0, dl, true), InFlag, dl); 4878 InFlag = Chain.getValue(1); 4879 } 4880 4881 // Is this global address that of a function that can be called by name? (as 4882 // opposed to something that must hold a descriptor for an indirect call). 4883 static bool isFunctionGlobalAddress(SDValue Callee) { 4884 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 4885 if (Callee.getOpcode() == ISD::GlobalTLSAddress || 4886 Callee.getOpcode() == ISD::TargetGlobalTLSAddress) 4887 return false; 4888 4889 return G->getGlobal()->getValueType()->isFunctionTy(); 4890 } 4891 4892 return false; 4893 } 4894 4895 static unsigned 4896 PrepareCall(SelectionDAG &DAG, SDValue &Callee, SDValue &InFlag, SDValue &Chain, 4897 SDValue CallSeqStart, const SDLoc &dl, int SPDiff, bool isTailCall, 4898 bool isPatchPoint, bool hasNest, 4899 SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass, 4900 SmallVectorImpl<SDValue> &Ops, std::vector<EVT> &NodeTys, 4901 ImmutableCallSite CS, const PPCSubtarget &Subtarget) { 4902 bool isPPC64 = Subtarget.isPPC64(); 4903 bool isSVR4ABI = Subtarget.isSVR4ABI(); 4904 bool isELFv2ABI = Subtarget.isELFv2ABI(); 4905 4906 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 4907 NodeTys.push_back(MVT::Other); // Returns a chain 4908 NodeTys.push_back(MVT::Glue); // Returns a flag for retval copy to use. 4909 4910 unsigned CallOpc = PPCISD::CALL; 4911 4912 bool needIndirectCall = true; 4913 if (!isSVR4ABI || !isPPC64) 4914 if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG)) { 4915 // If this is an absolute destination address, use the munged value. 4916 Callee = SDValue(Dest, 0); 4917 needIndirectCall = false; 4918 } 4919 4920 // PC-relative references to external symbols should go through $stub, unless 4921 // we're building with the leopard linker or later, which automatically 4922 // synthesizes these stubs. 4923 const TargetMachine &TM = DAG.getTarget(); 4924 const Module *Mod = DAG.getMachineFunction().getFunction().getParent(); 4925 const GlobalValue *GV = nullptr; 4926 if (auto *G = dyn_cast<GlobalAddressSDNode>(Callee)) 4927 GV = G->getGlobal(); 4928 bool Local = TM.shouldAssumeDSOLocal(*Mod, GV); 4929 bool UsePlt = !Local && Subtarget.isTargetELF() && !isPPC64; 4930 4931 if (isFunctionGlobalAddress(Callee)) { 4932 GlobalAddressSDNode *G = cast<GlobalAddressSDNode>(Callee); 4933 // A call to a TLS address is actually an indirect call to a 4934 // thread-specific pointer. 4935 unsigned OpFlags = 0; 4936 if (UsePlt) 4937 OpFlags = PPCII::MO_PLT; 4938 4939 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, 4940 // every direct call is) turn it into a TargetGlobalAddress / 4941 // TargetExternalSymbol node so that legalize doesn't hack it. 4942 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl, 4943 Callee.getValueType(), 0, OpFlags); 4944 needIndirectCall = false; 4945 } 4946 4947 if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) { 4948 unsigned char OpFlags = 0; 4949 4950 if (UsePlt) 4951 OpFlags = PPCII::MO_PLT; 4952 4953 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), Callee.getValueType(), 4954 OpFlags); 4955 needIndirectCall = false; 4956 } 4957 4958 if (isPatchPoint) { 4959 // We'll form an invalid direct call when lowering a patchpoint; the full 4960 // sequence for an indirect call is complicated, and many of the 4961 // instructions introduced might have side effects (and, thus, can't be 4962 // removed later). The call itself will be removed as soon as the 4963 // argument/return lowering is complete, so the fact that it has the wrong 4964 // kind of operands should not really matter. 4965 needIndirectCall = false; 4966 } 4967 4968 if (needIndirectCall) { 4969 // Otherwise, this is an indirect call. We have to use a MTCTR/BCTRL pair 4970 // to do the call, we can't use PPCISD::CALL. 4971 SDValue MTCTROps[] = {Chain, Callee, InFlag}; 4972 4973 if (isSVR4ABI && isPPC64 && !isELFv2ABI) { 4974 // Function pointers in the 64-bit SVR4 ABI do not point to the function 4975 // entry point, but to the function descriptor (the function entry point 4976 // address is part of the function descriptor though). 4977 // The function descriptor is a three doubleword structure with the 4978 // following fields: function entry point, TOC base address and 4979 // environment pointer. 4980 // Thus for a call through a function pointer, the following actions need 4981 // to be performed: 4982 // 1. Save the TOC of the caller in the TOC save area of its stack 4983 // frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()). 4984 // 2. Load the address of the function entry point from the function 4985 // descriptor. 4986 // 3. Load the TOC of the callee from the function descriptor into r2. 4987 // 4. Load the environment pointer from the function descriptor into 4988 // r11. 4989 // 5. Branch to the function entry point address. 4990 // 6. On return of the callee, the TOC of the caller needs to be 4991 // restored (this is done in FinishCall()). 4992 // 4993 // The loads are scheduled at the beginning of the call sequence, and the 4994 // register copies are flagged together to ensure that no other 4995 // operations can be scheduled in between. E.g. without flagging the 4996 // copies together, a TOC access in the caller could be scheduled between 4997 // the assignment of the callee TOC and the branch to the callee, which 4998 // results in the TOC access going through the TOC of the callee instead 4999 // of going through the TOC of the caller, which leads to incorrect code. 5000 5001 // Load the address of the function entry point from the function 5002 // descriptor. 5003 SDValue LDChain = CallSeqStart.getValue(CallSeqStart->getNumValues()-1); 5004 if (LDChain.getValueType() == MVT::Glue) 5005 LDChain = CallSeqStart.getValue(CallSeqStart->getNumValues()-2); 5006 5007 auto MMOFlags = Subtarget.hasInvariantFunctionDescriptors() 5008 ? (MachineMemOperand::MODereferenceable | 5009 MachineMemOperand::MOInvariant) 5010 : MachineMemOperand::MONone; 5011 5012 MachinePointerInfo MPI(CS ? CS.getCalledValue() : nullptr); 5013 SDValue LoadFuncPtr = DAG.getLoad(MVT::i64, dl, LDChain, Callee, MPI, 5014 /* Alignment = */ 8, MMOFlags); 5015 5016 // Load environment pointer into r11. 5017 SDValue PtrOff = DAG.getIntPtrConstant(16, dl); 5018 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, PtrOff); 5019 SDValue LoadEnvPtr = 5020 DAG.getLoad(MVT::i64, dl, LDChain, AddPtr, MPI.getWithOffset(16), 5021 /* Alignment = */ 8, MMOFlags); 5022 5023 SDValue TOCOff = DAG.getIntPtrConstant(8, dl); 5024 SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, TOCOff); 5025 SDValue TOCPtr = 5026 DAG.getLoad(MVT::i64, dl, LDChain, AddTOC, MPI.getWithOffset(8), 5027 /* Alignment = */ 8, MMOFlags); 5028 5029 setUsesTOCBasePtr(DAG); 5030 SDValue TOCVal = DAG.getCopyToReg(Chain, dl, PPC::X2, TOCPtr, 5031 InFlag); 5032 Chain = TOCVal.getValue(0); 5033 InFlag = TOCVal.getValue(1); 5034 5035 // If the function call has an explicit 'nest' parameter, it takes the 5036 // place of the environment pointer. 5037 if (!hasNest) { 5038 SDValue EnvVal = DAG.getCopyToReg(Chain, dl, PPC::X11, LoadEnvPtr, 5039 InFlag); 5040 5041 Chain = EnvVal.getValue(0); 5042 InFlag = EnvVal.getValue(1); 5043 } 5044 5045 MTCTROps[0] = Chain; 5046 MTCTROps[1] = LoadFuncPtr; 5047 MTCTROps[2] = InFlag; 5048 } 5049 5050 Chain = DAG.getNode(PPCISD::MTCTR, dl, NodeTys, 5051 makeArrayRef(MTCTROps, InFlag.getNode() ? 3 : 2)); 5052 InFlag = Chain.getValue(1); 5053 5054 NodeTys.clear(); 5055 NodeTys.push_back(MVT::Other); 5056 NodeTys.push_back(MVT::Glue); 5057 Ops.push_back(Chain); 5058 CallOpc = PPCISD::BCTRL; 5059 Callee.setNode(nullptr); 5060 // Add use of X11 (holding environment pointer) 5061 if (isSVR4ABI && isPPC64 && !isELFv2ABI && !hasNest) 5062 Ops.push_back(DAG.getRegister(PPC::X11, PtrVT)); 5063 // Add CTR register as callee so a bctr can be emitted later. 5064 if (isTailCall) 5065 Ops.push_back(DAG.getRegister(isPPC64 ? PPC::CTR8 : PPC::CTR, PtrVT)); 5066 } 5067 5068 // If this is a direct call, pass the chain and the callee. 5069 if (Callee.getNode()) { 5070 Ops.push_back(Chain); 5071 Ops.push_back(Callee); 5072 } 5073 // If this is a tail call add stack pointer delta. 5074 if (isTailCall) 5075 Ops.push_back(DAG.getConstant(SPDiff, dl, MVT::i32)); 5076 5077 // Add argument registers to the end of the list so that they are known live 5078 // into the call. 5079 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) 5080 Ops.push_back(DAG.getRegister(RegsToPass[i].first, 5081 RegsToPass[i].second.getValueType())); 5082 5083 // All calls, in both the ELF V1 and V2 ABIs, need the TOC register live 5084 // into the call. 5085 if (isSVR4ABI && isPPC64 && !isPatchPoint) { 5086 setUsesTOCBasePtr(DAG); 5087 Ops.push_back(DAG.getRegister(PPC::X2, PtrVT)); 5088 } 5089 5090 return CallOpc; 5091 } 5092 5093 SDValue PPCTargetLowering::LowerCallResult( 5094 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg, 5095 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 5096 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 5097 SmallVector<CCValAssign, 16> RVLocs; 5098 CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 5099 *DAG.getContext()); 5100 5101 CCRetInfo.AnalyzeCallResult( 5102 Ins, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold) 5103 ? RetCC_PPC_Cold 5104 : RetCC_PPC); 5105 5106 // Copy all of the result registers out of their specified physreg. 5107 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) { 5108 CCValAssign &VA = RVLocs[i]; 5109 assert(VA.isRegLoc() && "Can only return in registers!"); 5110 5111 SDValue Val = DAG.getCopyFromReg(Chain, dl, 5112 VA.getLocReg(), VA.getLocVT(), InFlag); 5113 Chain = Val.getValue(1); 5114 InFlag = Val.getValue(2); 5115 5116 switch (VA.getLocInfo()) { 5117 default: llvm_unreachable("Unknown loc info!"); 5118 case CCValAssign::Full: break; 5119 case CCValAssign::AExt: 5120 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val); 5121 break; 5122 case CCValAssign::ZExt: 5123 Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val, 5124 DAG.getValueType(VA.getValVT())); 5125 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val); 5126 break; 5127 case CCValAssign::SExt: 5128 Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val, 5129 DAG.getValueType(VA.getValVT())); 5130 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val); 5131 break; 5132 } 5133 5134 InVals.push_back(Val); 5135 } 5136 5137 return Chain; 5138 } 5139 5140 SDValue PPCTargetLowering::FinishCall( 5141 CallingConv::ID CallConv, const SDLoc &dl, bool isTailCall, bool isVarArg, 5142 bool isPatchPoint, bool hasNest, SelectionDAG &DAG, 5143 SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, SDValue InFlag, 5144 SDValue Chain, SDValue CallSeqStart, SDValue &Callee, int SPDiff, 5145 unsigned NumBytes, const SmallVectorImpl<ISD::InputArg> &Ins, 5146 SmallVectorImpl<SDValue> &InVals, ImmutableCallSite CS) const { 5147 std::vector<EVT> NodeTys; 5148 SmallVector<SDValue, 8> Ops; 5149 unsigned CallOpc = PrepareCall(DAG, Callee, InFlag, Chain, CallSeqStart, dl, 5150 SPDiff, isTailCall, isPatchPoint, hasNest, 5151 RegsToPass, Ops, NodeTys, CS, Subtarget); 5152 5153 // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls 5154 if (isVarArg && Subtarget.isSVR4ABI() && !Subtarget.isPPC64()) 5155 Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32)); 5156 5157 // When performing tail call optimization the callee pops its arguments off 5158 // the stack. Account for this here so these bytes can be pushed back on in 5159 // PPCFrameLowering::eliminateCallFramePseudoInstr. 5160 int BytesCalleePops = 5161 (CallConv == CallingConv::Fast && 5162 getTargetMachine().Options.GuaranteedTailCallOpt) ? NumBytes : 0; 5163 5164 // Add a register mask operand representing the call-preserved registers. 5165 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo(); 5166 const uint32_t *Mask = 5167 TRI->getCallPreservedMask(DAG.getMachineFunction(), CallConv); 5168 assert(Mask && "Missing call preserved mask for calling convention"); 5169 Ops.push_back(DAG.getRegisterMask(Mask)); 5170 5171 if (InFlag.getNode()) 5172 Ops.push_back(InFlag); 5173 5174 // Emit tail call. 5175 if (isTailCall) { 5176 assert(((Callee.getOpcode() == ISD::Register && 5177 cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) || 5178 Callee.getOpcode() == ISD::TargetExternalSymbol || 5179 Callee.getOpcode() == ISD::TargetGlobalAddress || 5180 isa<ConstantSDNode>(Callee)) && 5181 "Expecting an global address, external symbol, absolute value or register"); 5182 5183 DAG.getMachineFunction().getFrameInfo().setHasTailCall(); 5184 return DAG.getNode(PPCISD::TC_RETURN, dl, MVT::Other, Ops); 5185 } 5186 5187 // Add a NOP immediately after the branch instruction when using the 64-bit 5188 // SVR4 ABI. At link time, if caller and callee are in a different module and 5189 // thus have a different TOC, the call will be replaced with a call to a stub 5190 // function which saves the current TOC, loads the TOC of the callee and 5191 // branches to the callee. The NOP will be replaced with a load instruction 5192 // which restores the TOC of the caller from the TOC save slot of the current 5193 // stack frame. If caller and callee belong to the same module (and have the 5194 // same TOC), the NOP will remain unchanged. 5195 5196 MachineFunction &MF = DAG.getMachineFunction(); 5197 if (!isTailCall && Subtarget.isSVR4ABI()&& Subtarget.isPPC64() && 5198 !isPatchPoint) { 5199 if (CallOpc == PPCISD::BCTRL) { 5200 // This is a call through a function pointer. 5201 // Restore the caller TOC from the save area into R2. 5202 // See PrepareCall() for more information about calls through function 5203 // pointers in the 64-bit SVR4 ABI. 5204 // We are using a target-specific load with r2 hard coded, because the 5205 // result of a target-independent load would never go directly into r2, 5206 // since r2 is a reserved register (which prevents the register allocator 5207 // from allocating it), resulting in an additional register being 5208 // allocated and an unnecessary move instruction being generated. 5209 CallOpc = PPCISD::BCTRL_LOAD_TOC; 5210 5211 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 5212 SDValue StackPtr = DAG.getRegister(PPC::X1, PtrVT); 5213 unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset(); 5214 SDValue TOCOff = DAG.getIntPtrConstant(TOCSaveOffset, dl); 5215 SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, StackPtr, TOCOff); 5216 5217 // The address needs to go after the chain input but before the flag (or 5218 // any other variadic arguments). 5219 Ops.insert(std::next(Ops.begin()), AddTOC); 5220 } else if (CallOpc == PPCISD::CALL && 5221 !callsShareTOCBase(&MF.getFunction(), Callee, DAG.getTarget())) { 5222 // Otherwise insert NOP for non-local calls. 5223 CallOpc = PPCISD::CALL_NOP; 5224 } 5225 } 5226 5227 Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops); 5228 InFlag = Chain.getValue(1); 5229 5230 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true), 5231 DAG.getIntPtrConstant(BytesCalleePops, dl, true), 5232 InFlag, dl); 5233 if (!Ins.empty()) 5234 InFlag = Chain.getValue(1); 5235 5236 return LowerCallResult(Chain, InFlag, CallConv, isVarArg, 5237 Ins, dl, DAG, InVals); 5238 } 5239 5240 SDValue 5241 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI, 5242 SmallVectorImpl<SDValue> &InVals) const { 5243 SelectionDAG &DAG = CLI.DAG; 5244 SDLoc &dl = CLI.DL; 5245 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs; 5246 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals; 5247 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins; 5248 SDValue Chain = CLI.Chain; 5249 SDValue Callee = CLI.Callee; 5250 bool &isTailCall = CLI.IsTailCall; 5251 CallingConv::ID CallConv = CLI.CallConv; 5252 bool isVarArg = CLI.IsVarArg; 5253 bool isPatchPoint = CLI.IsPatchPoint; 5254 ImmutableCallSite CS = CLI.CS; 5255 5256 if (isTailCall) { 5257 if (Subtarget.useLongCalls() && !(CS && CS.isMustTailCall())) 5258 isTailCall = false; 5259 else if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) 5260 isTailCall = 5261 IsEligibleForTailCallOptimization_64SVR4(Callee, CallConv, CS, 5262 isVarArg, Outs, Ins, DAG); 5263 else 5264 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg, 5265 Ins, DAG); 5266 if (isTailCall) { 5267 ++NumTailCalls; 5268 if (!getTargetMachine().Options.GuaranteedTailCallOpt) 5269 ++NumSiblingCalls; 5270 5271 assert(isa<GlobalAddressSDNode>(Callee) && 5272 "Callee should be an llvm::Function object."); 5273 LLVM_DEBUG( 5274 const GlobalValue *GV = 5275 cast<GlobalAddressSDNode>(Callee)->getGlobal(); 5276 const unsigned Width = 5277 80 - strlen("TCO caller: ") - strlen(", callee linkage: 0, 0"); 5278 dbgs() << "TCO caller: " 5279 << left_justify(DAG.getMachineFunction().getName(), Width) 5280 << ", callee linkage: " << GV->getVisibility() << ", " 5281 << GV->getLinkage() << "\n"); 5282 } 5283 } 5284 5285 if (!isTailCall && CS && CS.isMustTailCall()) 5286 report_fatal_error("failed to perform tail call elimination on a call " 5287 "site marked musttail"); 5288 5289 // When long calls (i.e. indirect calls) are always used, calls are always 5290 // made via function pointer. If we have a function name, first translate it 5291 // into a pointer. 5292 if (Subtarget.useLongCalls() && isa<GlobalAddressSDNode>(Callee) && 5293 !isTailCall) 5294 Callee = LowerGlobalAddress(Callee, DAG); 5295 5296 if (Subtarget.isSVR4ABI()) { 5297 if (Subtarget.isPPC64()) 5298 return LowerCall_64SVR4(Chain, Callee, CallConv, isVarArg, 5299 isTailCall, isPatchPoint, Outs, OutVals, Ins, 5300 dl, DAG, InVals, CS); 5301 else 5302 return LowerCall_32SVR4(Chain, Callee, CallConv, isVarArg, 5303 isTailCall, isPatchPoint, Outs, OutVals, Ins, 5304 dl, DAG, InVals, CS); 5305 } 5306 5307 return LowerCall_Darwin(Chain, Callee, CallConv, isVarArg, 5308 isTailCall, isPatchPoint, Outs, OutVals, Ins, 5309 dl, DAG, InVals, CS); 5310 } 5311 5312 SDValue PPCTargetLowering::LowerCall_32SVR4( 5313 SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg, 5314 bool isTailCall, bool isPatchPoint, 5315 const SmallVectorImpl<ISD::OutputArg> &Outs, 5316 const SmallVectorImpl<SDValue> &OutVals, 5317 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 5318 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 5319 ImmutableCallSite CS) const { 5320 // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description 5321 // of the 32-bit SVR4 ABI stack frame layout. 5322 5323 assert((CallConv == CallingConv::C || 5324 CallConv == CallingConv::Cold || 5325 CallConv == CallingConv::Fast) && "Unknown calling convention!"); 5326 5327 unsigned PtrByteSize = 4; 5328 5329 MachineFunction &MF = DAG.getMachineFunction(); 5330 5331 // Mark this function as potentially containing a function that contains a 5332 // tail call. As a consequence the frame pointer will be used for dynamicalloc 5333 // and restoring the callers stack pointer in this functions epilog. This is 5334 // done because by tail calling the called function might overwrite the value 5335 // in this function's (MF) stack pointer stack slot 0(SP). 5336 if (getTargetMachine().Options.GuaranteedTailCallOpt && 5337 CallConv == CallingConv::Fast) 5338 MF.getInfo<PPCFunctionInfo>()->setHasFastCall(); 5339 5340 // Count how many bytes are to be pushed on the stack, including the linkage 5341 // area, parameter list area and the part of the local variable space which 5342 // contains copies of aggregates which are passed by value. 5343 5344 // Assign locations to all of the outgoing arguments. 5345 SmallVector<CCValAssign, 16> ArgLocs; 5346 PPCCCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext()); 5347 5348 // Reserve space for the linkage area on the stack. 5349 CCInfo.AllocateStack(Subtarget.getFrameLowering()->getLinkageSize(), 5350 PtrByteSize); 5351 if (useSoftFloat()) 5352 CCInfo.PreAnalyzeCallOperands(Outs); 5353 5354 if (isVarArg) { 5355 // Handle fixed and variable vector arguments differently. 5356 // Fixed vector arguments go into registers as long as registers are 5357 // available. Variable vector arguments always go into memory. 5358 unsigned NumArgs = Outs.size(); 5359 5360 for (unsigned i = 0; i != NumArgs; ++i) { 5361 MVT ArgVT = Outs[i].VT; 5362 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 5363 bool Result; 5364 5365 if (Outs[i].IsFixed) { 5366 Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, 5367 CCInfo); 5368 } else { 5369 Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full, 5370 ArgFlags, CCInfo); 5371 } 5372 5373 if (Result) { 5374 #ifndef NDEBUG 5375 errs() << "Call operand #" << i << " has unhandled type " 5376 << EVT(ArgVT).getEVTString() << "\n"; 5377 #endif 5378 llvm_unreachable(nullptr); 5379 } 5380 } 5381 } else { 5382 // All arguments are treated the same. 5383 CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4); 5384 } 5385 CCInfo.clearWasPPCF128(); 5386 5387 // Assign locations to all of the outgoing aggregate by value arguments. 5388 SmallVector<CCValAssign, 16> ByValArgLocs; 5389 CCState CCByValInfo(CallConv, isVarArg, MF, ByValArgLocs, *DAG.getContext()); 5390 5391 // Reserve stack space for the allocations in CCInfo. 5392 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize); 5393 5394 CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal); 5395 5396 // Size of the linkage area, parameter list area and the part of the local 5397 // space variable where copies of aggregates which are passed by value are 5398 // stored. 5399 unsigned NumBytes = CCByValInfo.getNextStackOffset(); 5400 5401 // Calculate by how many bytes the stack has to be adjusted in case of tail 5402 // call optimization. 5403 int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes); 5404 5405 // Adjust the stack pointer for the new arguments... 5406 // These operations are automatically eliminated by the prolog/epilog pass 5407 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 5408 SDValue CallSeqStart = Chain; 5409 5410 // Load the return address and frame pointer so it can be moved somewhere else 5411 // later. 5412 SDValue LROp, FPOp; 5413 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl); 5414 5415 // Set up a copy of the stack pointer for use loading and storing any 5416 // arguments that may not fit in the registers available for argument 5417 // passing. 5418 SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32); 5419 5420 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 5421 SmallVector<TailCallArgumentInfo, 8> TailCallArguments; 5422 SmallVector<SDValue, 8> MemOpChains; 5423 5424 bool seenFloatArg = false; 5425 // Walk the register/memloc assignments, inserting copies/loads. 5426 for (unsigned i = 0, j = 0, e = ArgLocs.size(); 5427 i != e; 5428 ++i) { 5429 CCValAssign &VA = ArgLocs[i]; 5430 SDValue Arg = OutVals[i]; 5431 ISD::ArgFlagsTy Flags = Outs[i].Flags; 5432 5433 if (Flags.isByVal()) { 5434 // Argument is an aggregate which is passed by value, thus we need to 5435 // create a copy of it in the local variable space of the current stack 5436 // frame (which is the stack frame of the caller) and pass the address of 5437 // this copy to the callee. 5438 assert((j < ByValArgLocs.size()) && "Index out of bounds!"); 5439 CCValAssign &ByValVA = ByValArgLocs[j++]; 5440 assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!"); 5441 5442 // Memory reserved in the local variable space of the callers stack frame. 5443 unsigned LocMemOffset = ByValVA.getLocMemOffset(); 5444 5445 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 5446 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()), 5447 StackPtr, PtrOff); 5448 5449 // Create a copy of the argument in the local area of the current 5450 // stack frame. 5451 SDValue MemcpyCall = 5452 CreateCopyOfByValArgument(Arg, PtrOff, 5453 CallSeqStart.getNode()->getOperand(0), 5454 Flags, DAG, dl); 5455 5456 // This must go outside the CALLSEQ_START..END. 5457 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, NumBytes, 0, 5458 SDLoc(MemcpyCall)); 5459 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(), 5460 NewCallSeqStart.getNode()); 5461 Chain = CallSeqStart = NewCallSeqStart; 5462 5463 // Pass the address of the aggregate copy on the stack either in a 5464 // physical register or in the parameter list area of the current stack 5465 // frame to the callee. 5466 Arg = PtrOff; 5467 } 5468 5469 // When useCRBits() is true, there can be i1 arguments. 5470 // It is because getRegisterType(MVT::i1) => MVT::i1, 5471 // and for other integer types getRegisterType() => MVT::i32. 5472 // Extend i1 and ensure callee will get i32. 5473 if (Arg.getValueType() == MVT::i1) 5474 Arg = DAG.getNode(Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, 5475 dl, MVT::i32, Arg); 5476 5477 if (VA.isRegLoc()) { 5478 seenFloatArg |= VA.getLocVT().isFloatingPoint(); 5479 // Put argument in a physical register. 5480 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 5481 } else { 5482 // Put argument in the parameter list area of the current stack frame. 5483 assert(VA.isMemLoc()); 5484 unsigned LocMemOffset = VA.getLocMemOffset(); 5485 5486 if (!isTailCall) { 5487 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 5488 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()), 5489 StackPtr, PtrOff); 5490 5491 MemOpChains.push_back( 5492 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo())); 5493 } else { 5494 // Calculate and remember argument location. 5495 CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset, 5496 TailCallArguments); 5497 } 5498 } 5499 } 5500 5501 if (!MemOpChains.empty()) 5502 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 5503 5504 // Build a sequence of copy-to-reg nodes chained together with token chain 5505 // and flag operands which copy the outgoing args into the appropriate regs. 5506 SDValue InFlag; 5507 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 5508 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 5509 RegsToPass[i].second, InFlag); 5510 InFlag = Chain.getValue(1); 5511 } 5512 5513 // Set CR bit 6 to true if this is a vararg call with floating args passed in 5514 // registers. 5515 if (isVarArg) { 5516 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue); 5517 SDValue Ops[] = { Chain, InFlag }; 5518 5519 Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET, 5520 dl, VTs, makeArrayRef(Ops, InFlag.getNode() ? 2 : 1)); 5521 5522 InFlag = Chain.getValue(1); 5523 } 5524 5525 if (isTailCall) 5526 PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp, 5527 TailCallArguments); 5528 5529 return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint, 5530 /* unused except on PPC64 ELFv1 */ false, DAG, 5531 RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff, 5532 NumBytes, Ins, InVals, CS); 5533 } 5534 5535 // Copy an argument into memory, being careful to do this outside the 5536 // call sequence for the call to which the argument belongs. 5537 SDValue PPCTargetLowering::createMemcpyOutsideCallSeq( 5538 SDValue Arg, SDValue PtrOff, SDValue CallSeqStart, ISD::ArgFlagsTy Flags, 5539 SelectionDAG &DAG, const SDLoc &dl) const { 5540 SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff, 5541 CallSeqStart.getNode()->getOperand(0), 5542 Flags, DAG, dl); 5543 // The MEMCPY must go outside the CALLSEQ_START..END. 5544 int64_t FrameSize = CallSeqStart.getConstantOperandVal(1); 5545 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, FrameSize, 0, 5546 SDLoc(MemcpyCall)); 5547 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(), 5548 NewCallSeqStart.getNode()); 5549 return NewCallSeqStart; 5550 } 5551 5552 SDValue PPCTargetLowering::LowerCall_64SVR4( 5553 SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg, 5554 bool isTailCall, bool isPatchPoint, 5555 const SmallVectorImpl<ISD::OutputArg> &Outs, 5556 const SmallVectorImpl<SDValue> &OutVals, 5557 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 5558 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 5559 ImmutableCallSite CS) const { 5560 bool isELFv2ABI = Subtarget.isELFv2ABI(); 5561 bool isLittleEndian = Subtarget.isLittleEndian(); 5562 unsigned NumOps = Outs.size(); 5563 bool hasNest = false; 5564 bool IsSibCall = false; 5565 5566 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 5567 unsigned PtrByteSize = 8; 5568 5569 MachineFunction &MF = DAG.getMachineFunction(); 5570 5571 if (isTailCall && !getTargetMachine().Options.GuaranteedTailCallOpt) 5572 IsSibCall = true; 5573 5574 // Mark this function as potentially containing a function that contains a 5575 // tail call. As a consequence the frame pointer will be used for dynamicalloc 5576 // and restoring the callers stack pointer in this functions epilog. This is 5577 // done because by tail calling the called function might overwrite the value 5578 // in this function's (MF) stack pointer stack slot 0(SP). 5579 if (getTargetMachine().Options.GuaranteedTailCallOpt && 5580 CallConv == CallingConv::Fast) 5581 MF.getInfo<PPCFunctionInfo>()->setHasFastCall(); 5582 5583 assert(!(CallConv == CallingConv::Fast && isVarArg) && 5584 "fastcc not supported on varargs functions"); 5585 5586 // Count how many bytes are to be pushed on the stack, including the linkage 5587 // area, and parameter passing area. On ELFv1, the linkage area is 48 bytes 5588 // reserved space for [SP][CR][LR][2 x unused][TOC]; on ELFv2, the linkage 5589 // area is 32 bytes reserved space for [SP][CR][LR][TOC]. 5590 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 5591 unsigned NumBytes = LinkageSize; 5592 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 5593 unsigned &QFPR_idx = FPR_idx; 5594 5595 static const MCPhysReg GPR[] = { 5596 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 5597 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 5598 }; 5599 static const MCPhysReg VR[] = { 5600 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 5601 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 5602 }; 5603 5604 const unsigned NumGPRs = array_lengthof(GPR); 5605 const unsigned NumFPRs = useSoftFloat() ? 0 : 13; 5606 const unsigned NumVRs = array_lengthof(VR); 5607 const unsigned NumQFPRs = NumFPRs; 5608 5609 // On ELFv2, we can avoid allocating the parameter area if all the arguments 5610 // can be passed to the callee in registers. 5611 // For the fast calling convention, there is another check below. 5612 // Note: We should keep consistent with LowerFormalArguments_64SVR4() 5613 bool HasParameterArea = !isELFv2ABI || isVarArg || CallConv == CallingConv::Fast; 5614 if (!HasParameterArea) { 5615 unsigned ParamAreaSize = NumGPRs * PtrByteSize; 5616 unsigned AvailableFPRs = NumFPRs; 5617 unsigned AvailableVRs = NumVRs; 5618 unsigned NumBytesTmp = NumBytes; 5619 for (unsigned i = 0; i != NumOps; ++i) { 5620 if (Outs[i].Flags.isNest()) continue; 5621 if (CalculateStackSlotUsed(Outs[i].VT, Outs[i].ArgVT, Outs[i].Flags, 5622 PtrByteSize, LinkageSize, ParamAreaSize, 5623 NumBytesTmp, AvailableFPRs, AvailableVRs, 5624 Subtarget.hasQPX())) 5625 HasParameterArea = true; 5626 } 5627 } 5628 5629 // When using the fast calling convention, we don't provide backing for 5630 // arguments that will be in registers. 5631 unsigned NumGPRsUsed = 0, NumFPRsUsed = 0, NumVRsUsed = 0; 5632 5633 // Avoid allocating parameter area for fastcc functions if all the arguments 5634 // can be passed in the registers. 5635 if (CallConv == CallingConv::Fast) 5636 HasParameterArea = false; 5637 5638 // Add up all the space actually used. 5639 for (unsigned i = 0; i != NumOps; ++i) { 5640 ISD::ArgFlagsTy Flags = Outs[i].Flags; 5641 EVT ArgVT = Outs[i].VT; 5642 EVT OrigVT = Outs[i].ArgVT; 5643 5644 if (Flags.isNest()) 5645 continue; 5646 5647 if (CallConv == CallingConv::Fast) { 5648 if (Flags.isByVal()) { 5649 NumGPRsUsed += (Flags.getByValSize()+7)/8; 5650 if (NumGPRsUsed > NumGPRs) 5651 HasParameterArea = true; 5652 } else { 5653 switch (ArgVT.getSimpleVT().SimpleTy) { 5654 default: llvm_unreachable("Unexpected ValueType for argument!"); 5655 case MVT::i1: 5656 case MVT::i32: 5657 case MVT::i64: 5658 if (++NumGPRsUsed <= NumGPRs) 5659 continue; 5660 break; 5661 case MVT::v4i32: 5662 case MVT::v8i16: 5663 case MVT::v16i8: 5664 case MVT::v2f64: 5665 case MVT::v2i64: 5666 case MVT::v1i128: 5667 case MVT::f128: 5668 if (++NumVRsUsed <= NumVRs) 5669 continue; 5670 break; 5671 case MVT::v4f32: 5672 // When using QPX, this is handled like a FP register, otherwise, it 5673 // is an Altivec register. 5674 if (Subtarget.hasQPX()) { 5675 if (++NumFPRsUsed <= NumFPRs) 5676 continue; 5677 } else { 5678 if (++NumVRsUsed <= NumVRs) 5679 continue; 5680 } 5681 break; 5682 case MVT::f32: 5683 case MVT::f64: 5684 case MVT::v4f64: // QPX 5685 case MVT::v4i1: // QPX 5686 if (++NumFPRsUsed <= NumFPRs) 5687 continue; 5688 break; 5689 } 5690 HasParameterArea = true; 5691 } 5692 } 5693 5694 /* Respect alignment of argument on the stack. */ 5695 unsigned Align = 5696 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize); 5697 NumBytes = ((NumBytes + Align - 1) / Align) * Align; 5698 5699 NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize); 5700 if (Flags.isInConsecutiveRegsLast()) 5701 NumBytes = ((NumBytes + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 5702 } 5703 5704 unsigned NumBytesActuallyUsed = NumBytes; 5705 5706 // In the old ELFv1 ABI, 5707 // the prolog code of the callee may store up to 8 GPR argument registers to 5708 // the stack, allowing va_start to index over them in memory if its varargs. 5709 // Because we cannot tell if this is needed on the caller side, we have to 5710 // conservatively assume that it is needed. As such, make sure we have at 5711 // least enough stack space for the caller to store the 8 GPRs. 5712 // In the ELFv2 ABI, we allocate the parameter area iff a callee 5713 // really requires memory operands, e.g. a vararg function. 5714 if (HasParameterArea) 5715 NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize); 5716 else 5717 NumBytes = LinkageSize; 5718 5719 // Tail call needs the stack to be aligned. 5720 if (getTargetMachine().Options.GuaranteedTailCallOpt && 5721 CallConv == CallingConv::Fast) 5722 NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes); 5723 5724 int SPDiff = 0; 5725 5726 // Calculate by how many bytes the stack has to be adjusted in case of tail 5727 // call optimization. 5728 if (!IsSibCall) 5729 SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes); 5730 5731 // To protect arguments on the stack from being clobbered in a tail call, 5732 // force all the loads to happen before doing any other lowering. 5733 if (isTailCall) 5734 Chain = DAG.getStackArgumentTokenFactor(Chain); 5735 5736 // Adjust the stack pointer for the new arguments... 5737 // These operations are automatically eliminated by the prolog/epilog pass 5738 if (!IsSibCall) 5739 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 5740 SDValue CallSeqStart = Chain; 5741 5742 // Load the return address and frame pointer so it can be move somewhere else 5743 // later. 5744 SDValue LROp, FPOp; 5745 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl); 5746 5747 // Set up a copy of the stack pointer for use loading and storing any 5748 // arguments that may not fit in the registers available for argument 5749 // passing. 5750 SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64); 5751 5752 // Figure out which arguments are going to go in registers, and which in 5753 // memory. Also, if this is a vararg function, floating point operations 5754 // must be stored to our stack, and loaded into integer regs as well, if 5755 // any integer regs are available for argument passing. 5756 unsigned ArgOffset = LinkageSize; 5757 5758 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 5759 SmallVector<TailCallArgumentInfo, 8> TailCallArguments; 5760 5761 SmallVector<SDValue, 8> MemOpChains; 5762 for (unsigned i = 0; i != NumOps; ++i) { 5763 SDValue Arg = OutVals[i]; 5764 ISD::ArgFlagsTy Flags = Outs[i].Flags; 5765 EVT ArgVT = Outs[i].VT; 5766 EVT OrigVT = Outs[i].ArgVT; 5767 5768 // PtrOff will be used to store the current argument to the stack if a 5769 // register cannot be found for it. 5770 SDValue PtrOff; 5771 5772 // We re-align the argument offset for each argument, except when using the 5773 // fast calling convention, when we need to make sure we do that only when 5774 // we'll actually use a stack slot. 5775 auto ComputePtrOff = [&]() { 5776 /* Respect alignment of argument on the stack. */ 5777 unsigned Align = 5778 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize); 5779 ArgOffset = ((ArgOffset + Align - 1) / Align) * Align; 5780 5781 PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType()); 5782 5783 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 5784 }; 5785 5786 if (CallConv != CallingConv::Fast) { 5787 ComputePtrOff(); 5788 5789 /* Compute GPR index associated with argument offset. */ 5790 GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize; 5791 GPR_idx = std::min(GPR_idx, NumGPRs); 5792 } 5793 5794 // Promote integers to 64-bit values. 5795 if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) { 5796 // FIXME: Should this use ANY_EXTEND if neither sext nor zext? 5797 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 5798 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg); 5799 } 5800 5801 // FIXME memcpy is used way more than necessary. Correctness first. 5802 // Note: "by value" is code for passing a structure by value, not 5803 // basic types. 5804 if (Flags.isByVal()) { 5805 // Note: Size includes alignment padding, so 5806 // struct x { short a; char b; } 5807 // will have Size = 4. With #pragma pack(1), it will have Size = 3. 5808 // These are the proper values we need for right-justifying the 5809 // aggregate in a parameter register. 5810 unsigned Size = Flags.getByValSize(); 5811 5812 // An empty aggregate parameter takes up no storage and no 5813 // registers. 5814 if (Size == 0) 5815 continue; 5816 5817 if (CallConv == CallingConv::Fast) 5818 ComputePtrOff(); 5819 5820 // All aggregates smaller than 8 bytes must be passed right-justified. 5821 if (Size==1 || Size==2 || Size==4) { 5822 EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32); 5823 if (GPR_idx != NumGPRs) { 5824 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg, 5825 MachinePointerInfo(), VT); 5826 MemOpChains.push_back(Load.getValue(1)); 5827 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 5828 5829 ArgOffset += PtrByteSize; 5830 continue; 5831 } 5832 } 5833 5834 if (GPR_idx == NumGPRs && Size < 8) { 5835 SDValue AddPtr = PtrOff; 5836 if (!isLittleEndian) { 5837 SDValue Const = DAG.getConstant(PtrByteSize - Size, dl, 5838 PtrOff.getValueType()); 5839 AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const); 5840 } 5841 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr, 5842 CallSeqStart, 5843 Flags, DAG, dl); 5844 ArgOffset += PtrByteSize; 5845 continue; 5846 } 5847 // Copy entire object into memory. There are cases where gcc-generated 5848 // code assumes it is there, even if it could be put entirely into 5849 // registers. (This is not what the doc says.) 5850 5851 // FIXME: The above statement is likely due to a misunderstanding of the 5852 // documents. All arguments must be copied into the parameter area BY 5853 // THE CALLEE in the event that the callee takes the address of any 5854 // formal argument. That has not yet been implemented. However, it is 5855 // reasonable to use the stack area as a staging area for the register 5856 // load. 5857 5858 // Skip this for small aggregates, as we will use the same slot for a 5859 // right-justified copy, below. 5860 if (Size >= 8) 5861 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff, 5862 CallSeqStart, 5863 Flags, DAG, dl); 5864 5865 // When a register is available, pass a small aggregate right-justified. 5866 if (Size < 8 && GPR_idx != NumGPRs) { 5867 // The easiest way to get this right-justified in a register 5868 // is to copy the structure into the rightmost portion of a 5869 // local variable slot, then load the whole slot into the 5870 // register. 5871 // FIXME: The memcpy seems to produce pretty awful code for 5872 // small aggregates, particularly for packed ones. 5873 // FIXME: It would be preferable to use the slot in the 5874 // parameter save area instead of a new local variable. 5875 SDValue AddPtr = PtrOff; 5876 if (!isLittleEndian) { 5877 SDValue Const = DAG.getConstant(8 - Size, dl, PtrOff.getValueType()); 5878 AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const); 5879 } 5880 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr, 5881 CallSeqStart, 5882 Flags, DAG, dl); 5883 5884 // Load the slot into the register. 5885 SDValue Load = 5886 DAG.getLoad(PtrVT, dl, Chain, PtrOff, MachinePointerInfo()); 5887 MemOpChains.push_back(Load.getValue(1)); 5888 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 5889 5890 // Done with this argument. 5891 ArgOffset += PtrByteSize; 5892 continue; 5893 } 5894 5895 // For aggregates larger than PtrByteSize, copy the pieces of the 5896 // object that fit into registers from the parameter save area. 5897 for (unsigned j=0; j<Size; j+=PtrByteSize) { 5898 SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType()); 5899 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const); 5900 if (GPR_idx != NumGPRs) { 5901 SDValue Load = 5902 DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo()); 5903 MemOpChains.push_back(Load.getValue(1)); 5904 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 5905 ArgOffset += PtrByteSize; 5906 } else { 5907 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize; 5908 break; 5909 } 5910 } 5911 continue; 5912 } 5913 5914 switch (Arg.getSimpleValueType().SimpleTy) { 5915 default: llvm_unreachable("Unexpected ValueType for argument!"); 5916 case MVT::i1: 5917 case MVT::i32: 5918 case MVT::i64: 5919 if (Flags.isNest()) { 5920 // The 'nest' parameter, if any, is passed in R11. 5921 RegsToPass.push_back(std::make_pair(PPC::X11, Arg)); 5922 hasNest = true; 5923 break; 5924 } 5925 5926 // These can be scalar arguments or elements of an integer array type 5927 // passed directly. Clang may use those instead of "byval" aggregate 5928 // types to avoid forcing arguments to memory unnecessarily. 5929 if (GPR_idx != NumGPRs) { 5930 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg)); 5931 } else { 5932 if (CallConv == CallingConv::Fast) 5933 ComputePtrOff(); 5934 5935 assert(HasParameterArea && 5936 "Parameter area must exist to pass an argument in memory."); 5937 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 5938 true, isTailCall, false, MemOpChains, 5939 TailCallArguments, dl); 5940 if (CallConv == CallingConv::Fast) 5941 ArgOffset += PtrByteSize; 5942 } 5943 if (CallConv != CallingConv::Fast) 5944 ArgOffset += PtrByteSize; 5945 break; 5946 case MVT::f32: 5947 case MVT::f64: { 5948 // These can be scalar arguments or elements of a float array type 5949 // passed directly. The latter are used to implement ELFv2 homogenous 5950 // float aggregates. 5951 5952 // Named arguments go into FPRs first, and once they overflow, the 5953 // remaining arguments go into GPRs and then the parameter save area. 5954 // Unnamed arguments for vararg functions always go to GPRs and 5955 // then the parameter save area. For now, put all arguments to vararg 5956 // routines always in both locations (FPR *and* GPR or stack slot). 5957 bool NeedGPROrStack = isVarArg || FPR_idx == NumFPRs; 5958 bool NeededLoad = false; 5959 5960 // First load the argument into the next available FPR. 5961 if (FPR_idx != NumFPRs) 5962 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg)); 5963 5964 // Next, load the argument into GPR or stack slot if needed. 5965 if (!NeedGPROrStack) 5966 ; 5967 else if (GPR_idx != NumGPRs && CallConv != CallingConv::Fast) { 5968 // FIXME: We may want to re-enable this for CallingConv::Fast on the P8 5969 // once we support fp <-> gpr moves. 5970 5971 // In the non-vararg case, this can only ever happen in the 5972 // presence of f32 array types, since otherwise we never run 5973 // out of FPRs before running out of GPRs. 5974 SDValue ArgVal; 5975 5976 // Double values are always passed in a single GPR. 5977 if (Arg.getValueType() != MVT::f32) { 5978 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg); 5979 5980 // Non-array float values are extended and passed in a GPR. 5981 } else if (!Flags.isInConsecutiveRegs()) { 5982 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg); 5983 ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal); 5984 5985 // If we have an array of floats, we collect every odd element 5986 // together with its predecessor into one GPR. 5987 } else if (ArgOffset % PtrByteSize != 0) { 5988 SDValue Lo, Hi; 5989 Lo = DAG.getNode(ISD::BITCAST, dl, MVT::i32, OutVals[i - 1]); 5990 Hi = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg); 5991 if (!isLittleEndian) 5992 std::swap(Lo, Hi); 5993 ArgVal = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi); 5994 5995 // The final element, if even, goes into the first half of a GPR. 5996 } else if (Flags.isInConsecutiveRegsLast()) { 5997 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg); 5998 ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal); 5999 if (!isLittleEndian) 6000 ArgVal = DAG.getNode(ISD::SHL, dl, MVT::i64, ArgVal, 6001 DAG.getConstant(32, dl, MVT::i32)); 6002 6003 // Non-final even elements are skipped; they will be handled 6004 // together the with subsequent argument on the next go-around. 6005 } else 6006 ArgVal = SDValue(); 6007 6008 if (ArgVal.getNode()) 6009 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], ArgVal)); 6010 } else { 6011 if (CallConv == CallingConv::Fast) 6012 ComputePtrOff(); 6013 6014 // Single-precision floating-point values are mapped to the 6015 // second (rightmost) word of the stack doubleword. 6016 if (Arg.getValueType() == MVT::f32 && 6017 !isLittleEndian && !Flags.isInConsecutiveRegs()) { 6018 SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType()); 6019 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour); 6020 } 6021 6022 assert(HasParameterArea && 6023 "Parameter area must exist to pass an argument in memory."); 6024 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6025 true, isTailCall, false, MemOpChains, 6026 TailCallArguments, dl); 6027 6028 NeededLoad = true; 6029 } 6030 // When passing an array of floats, the array occupies consecutive 6031 // space in the argument area; only round up to the next doubleword 6032 // at the end of the array. Otherwise, each float takes 8 bytes. 6033 if (CallConv != CallingConv::Fast || NeededLoad) { 6034 ArgOffset += (Arg.getValueType() == MVT::f32 && 6035 Flags.isInConsecutiveRegs()) ? 4 : 8; 6036 if (Flags.isInConsecutiveRegsLast()) 6037 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 6038 } 6039 break; 6040 } 6041 case MVT::v4f32: 6042 case MVT::v4i32: 6043 case MVT::v8i16: 6044 case MVT::v16i8: 6045 case MVT::v2f64: 6046 case MVT::v2i64: 6047 case MVT::v1i128: 6048 case MVT::f128: 6049 if (!Subtarget.hasQPX()) { 6050 // These can be scalar arguments or elements of a vector array type 6051 // passed directly. The latter are used to implement ELFv2 homogenous 6052 // vector aggregates. 6053 6054 // For a varargs call, named arguments go into VRs or on the stack as 6055 // usual; unnamed arguments always go to the stack or the corresponding 6056 // GPRs when within range. For now, we always put the value in both 6057 // locations (or even all three). 6058 if (isVarArg) { 6059 assert(HasParameterArea && 6060 "Parameter area must exist if we have a varargs call."); 6061 // We could elide this store in the case where the object fits 6062 // entirely in R registers. Maybe later. 6063 SDValue Store = 6064 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 6065 MemOpChains.push_back(Store); 6066 if (VR_idx != NumVRs) { 6067 SDValue Load = 6068 DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo()); 6069 MemOpChains.push_back(Load.getValue(1)); 6070 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load)); 6071 } 6072 ArgOffset += 16; 6073 for (unsigned i=0; i<16; i+=PtrByteSize) { 6074 if (GPR_idx == NumGPRs) 6075 break; 6076 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, 6077 DAG.getConstant(i, dl, PtrVT)); 6078 SDValue Load = 6079 DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo()); 6080 MemOpChains.push_back(Load.getValue(1)); 6081 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6082 } 6083 break; 6084 } 6085 6086 // Non-varargs Altivec params go into VRs or on the stack. 6087 if (VR_idx != NumVRs) { 6088 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg)); 6089 } else { 6090 if (CallConv == CallingConv::Fast) 6091 ComputePtrOff(); 6092 6093 assert(HasParameterArea && 6094 "Parameter area must exist to pass an argument in memory."); 6095 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6096 true, isTailCall, true, MemOpChains, 6097 TailCallArguments, dl); 6098 if (CallConv == CallingConv::Fast) 6099 ArgOffset += 16; 6100 } 6101 6102 if (CallConv != CallingConv::Fast) 6103 ArgOffset += 16; 6104 break; 6105 } // not QPX 6106 6107 assert(Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32 && 6108 "Invalid QPX parameter type"); 6109 6110 LLVM_FALLTHROUGH; 6111 case MVT::v4f64: 6112 case MVT::v4i1: { 6113 bool IsF32 = Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32; 6114 if (isVarArg) { 6115 assert(HasParameterArea && 6116 "Parameter area must exist if we have a varargs call."); 6117 // We could elide this store in the case where the object fits 6118 // entirely in R registers. Maybe later. 6119 SDValue Store = 6120 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 6121 MemOpChains.push_back(Store); 6122 if (QFPR_idx != NumQFPRs) { 6123 SDValue Load = DAG.getLoad(IsF32 ? MVT::v4f32 : MVT::v4f64, dl, Store, 6124 PtrOff, MachinePointerInfo()); 6125 MemOpChains.push_back(Load.getValue(1)); 6126 RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Load)); 6127 } 6128 ArgOffset += (IsF32 ? 16 : 32); 6129 for (unsigned i = 0; i < (IsF32 ? 16U : 32U); i += PtrByteSize) { 6130 if (GPR_idx == NumGPRs) 6131 break; 6132 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, 6133 DAG.getConstant(i, dl, PtrVT)); 6134 SDValue Load = 6135 DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo()); 6136 MemOpChains.push_back(Load.getValue(1)); 6137 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6138 } 6139 break; 6140 } 6141 6142 // Non-varargs QPX params go into registers or on the stack. 6143 if (QFPR_idx != NumQFPRs) { 6144 RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Arg)); 6145 } else { 6146 if (CallConv == CallingConv::Fast) 6147 ComputePtrOff(); 6148 6149 assert(HasParameterArea && 6150 "Parameter area must exist to pass an argument in memory."); 6151 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6152 true, isTailCall, true, MemOpChains, 6153 TailCallArguments, dl); 6154 if (CallConv == CallingConv::Fast) 6155 ArgOffset += (IsF32 ? 16 : 32); 6156 } 6157 6158 if (CallConv != CallingConv::Fast) 6159 ArgOffset += (IsF32 ? 16 : 32); 6160 break; 6161 } 6162 } 6163 } 6164 6165 assert((!HasParameterArea || NumBytesActuallyUsed == ArgOffset) && 6166 "mismatch in size of parameter area"); 6167 (void)NumBytesActuallyUsed; 6168 6169 if (!MemOpChains.empty()) 6170 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 6171 6172 // Check if this is an indirect call (MTCTR/BCTRL). 6173 // See PrepareCall() for more information about calls through function 6174 // pointers in the 64-bit SVR4 ABI. 6175 if (!isTailCall && !isPatchPoint && 6176 !isFunctionGlobalAddress(Callee) && 6177 !isa<ExternalSymbolSDNode>(Callee)) { 6178 // Load r2 into a virtual register and store it to the TOC save area. 6179 setUsesTOCBasePtr(DAG); 6180 SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64); 6181 // TOC save area offset. 6182 unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset(); 6183 SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl); 6184 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 6185 Chain = DAG.getStore( 6186 Val.getValue(1), dl, Val, AddPtr, 6187 MachinePointerInfo::getStack(DAG.getMachineFunction(), TOCSaveOffset)); 6188 // In the ELFv2 ABI, R12 must contain the address of an indirect callee. 6189 // This does not mean the MTCTR instruction must use R12; it's easier 6190 // to model this as an extra parameter, so do that. 6191 if (isELFv2ABI && !isPatchPoint) 6192 RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee)); 6193 } 6194 6195 // Build a sequence of copy-to-reg nodes chained together with token chain 6196 // and flag operands which copy the outgoing args into the appropriate regs. 6197 SDValue InFlag; 6198 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 6199 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 6200 RegsToPass[i].second, InFlag); 6201 InFlag = Chain.getValue(1); 6202 } 6203 6204 if (isTailCall && !IsSibCall) 6205 PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp, 6206 TailCallArguments); 6207 6208 return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint, hasNest, 6209 DAG, RegsToPass, InFlag, Chain, CallSeqStart, Callee, 6210 SPDiff, NumBytes, Ins, InVals, CS); 6211 } 6212 6213 SDValue PPCTargetLowering::LowerCall_Darwin( 6214 SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg, 6215 bool isTailCall, bool isPatchPoint, 6216 const SmallVectorImpl<ISD::OutputArg> &Outs, 6217 const SmallVectorImpl<SDValue> &OutVals, 6218 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 6219 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 6220 ImmutableCallSite CS) const { 6221 unsigned NumOps = Outs.size(); 6222 6223 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 6224 bool isPPC64 = PtrVT == MVT::i64; 6225 unsigned PtrByteSize = isPPC64 ? 8 : 4; 6226 6227 MachineFunction &MF = DAG.getMachineFunction(); 6228 6229 // Mark this function as potentially containing a function that contains a 6230 // tail call. As a consequence the frame pointer will be used for dynamicalloc 6231 // and restoring the callers stack pointer in this functions epilog. This is 6232 // done because by tail calling the called function might overwrite the value 6233 // in this function's (MF) stack pointer stack slot 0(SP). 6234 if (getTargetMachine().Options.GuaranteedTailCallOpt && 6235 CallConv == CallingConv::Fast) 6236 MF.getInfo<PPCFunctionInfo>()->setHasFastCall(); 6237 6238 // Count how many bytes are to be pushed on the stack, including the linkage 6239 // area, and parameter passing area. We start with 24/48 bytes, which is 6240 // prereserved space for [SP][CR][LR][3 x unused]. 6241 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 6242 unsigned NumBytes = LinkageSize; 6243 6244 // Add up all the space actually used. 6245 // In 32-bit non-varargs calls, Altivec parameters all go at the end; usually 6246 // they all go in registers, but we must reserve stack space for them for 6247 // possible use by the caller. In varargs or 64-bit calls, parameters are 6248 // assigned stack space in order, with padding so Altivec parameters are 6249 // 16-byte aligned. 6250 unsigned nAltivecParamsAtEnd = 0; 6251 for (unsigned i = 0; i != NumOps; ++i) { 6252 ISD::ArgFlagsTy Flags = Outs[i].Flags; 6253 EVT ArgVT = Outs[i].VT; 6254 // Varargs Altivec parameters are padded to a 16 byte boundary. 6255 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 || 6256 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 || 6257 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64) { 6258 if (!isVarArg && !isPPC64) { 6259 // Non-varargs Altivec parameters go after all the non-Altivec 6260 // parameters; handle those later so we know how much padding we need. 6261 nAltivecParamsAtEnd++; 6262 continue; 6263 } 6264 // Varargs and 64-bit Altivec parameters are padded to 16 byte boundary. 6265 NumBytes = ((NumBytes+15)/16)*16; 6266 } 6267 NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize); 6268 } 6269 6270 // Allow for Altivec parameters at the end, if needed. 6271 if (nAltivecParamsAtEnd) { 6272 NumBytes = ((NumBytes+15)/16)*16; 6273 NumBytes += 16*nAltivecParamsAtEnd; 6274 } 6275 6276 // The prolog code of the callee may store up to 8 GPR argument registers to 6277 // the stack, allowing va_start to index over them in memory if its varargs. 6278 // Because we cannot tell if this is needed on the caller side, we have to 6279 // conservatively assume that it is needed. As such, make sure we have at 6280 // least enough stack space for the caller to store the 8 GPRs. 6281 NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize); 6282 6283 // Tail call needs the stack to be aligned. 6284 if (getTargetMachine().Options.GuaranteedTailCallOpt && 6285 CallConv == CallingConv::Fast) 6286 NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes); 6287 6288 // Calculate by how many bytes the stack has to be adjusted in case of tail 6289 // call optimization. 6290 int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes); 6291 6292 // To protect arguments on the stack from being clobbered in a tail call, 6293 // force all the loads to happen before doing any other lowering. 6294 if (isTailCall) 6295 Chain = DAG.getStackArgumentTokenFactor(Chain); 6296 6297 // Adjust the stack pointer for the new arguments... 6298 // These operations are automatically eliminated by the prolog/epilog pass 6299 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 6300 SDValue CallSeqStart = Chain; 6301 6302 // Load the return address and frame pointer so it can be move somewhere else 6303 // later. 6304 SDValue LROp, FPOp; 6305 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl); 6306 6307 // Set up a copy of the stack pointer for use loading and storing any 6308 // arguments that may not fit in the registers available for argument 6309 // passing. 6310 SDValue StackPtr; 6311 if (isPPC64) 6312 StackPtr = DAG.getRegister(PPC::X1, MVT::i64); 6313 else 6314 StackPtr = DAG.getRegister(PPC::R1, MVT::i32); 6315 6316 // Figure out which arguments are going to go in registers, and which in 6317 // memory. Also, if this is a vararg function, floating point operations 6318 // must be stored to our stack, and loaded into integer regs as well, if 6319 // any integer regs are available for argument passing. 6320 unsigned ArgOffset = LinkageSize; 6321 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 6322 6323 static const MCPhysReg GPR_32[] = { // 32-bit registers. 6324 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 6325 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 6326 }; 6327 static const MCPhysReg GPR_64[] = { // 64-bit registers. 6328 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 6329 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 6330 }; 6331 static const MCPhysReg VR[] = { 6332 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 6333 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 6334 }; 6335 const unsigned NumGPRs = array_lengthof(GPR_32); 6336 const unsigned NumFPRs = 13; 6337 const unsigned NumVRs = array_lengthof(VR); 6338 6339 const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32; 6340 6341 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 6342 SmallVector<TailCallArgumentInfo, 8> TailCallArguments; 6343 6344 SmallVector<SDValue, 8> MemOpChains; 6345 for (unsigned i = 0; i != NumOps; ++i) { 6346 SDValue Arg = OutVals[i]; 6347 ISD::ArgFlagsTy Flags = Outs[i].Flags; 6348 6349 // PtrOff will be used to store the current argument to the stack if a 6350 // register cannot be found for it. 6351 SDValue PtrOff; 6352 6353 PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType()); 6354 6355 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 6356 6357 // On PPC64, promote integers to 64-bit values. 6358 if (isPPC64 && Arg.getValueType() == MVT::i32) { 6359 // FIXME: Should this use ANY_EXTEND if neither sext nor zext? 6360 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 6361 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg); 6362 } 6363 6364 // FIXME memcpy is used way more than necessary. Correctness first. 6365 // Note: "by value" is code for passing a structure by value, not 6366 // basic types. 6367 if (Flags.isByVal()) { 6368 unsigned Size = Flags.getByValSize(); 6369 // Very small objects are passed right-justified. Everything else is 6370 // passed left-justified. 6371 if (Size==1 || Size==2) { 6372 EVT VT = (Size==1) ? MVT::i8 : MVT::i16; 6373 if (GPR_idx != NumGPRs) { 6374 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg, 6375 MachinePointerInfo(), VT); 6376 MemOpChains.push_back(Load.getValue(1)); 6377 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6378 6379 ArgOffset += PtrByteSize; 6380 } else { 6381 SDValue Const = DAG.getConstant(PtrByteSize - Size, dl, 6382 PtrOff.getValueType()); 6383 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const); 6384 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr, 6385 CallSeqStart, 6386 Flags, DAG, dl); 6387 ArgOffset += PtrByteSize; 6388 } 6389 continue; 6390 } 6391 // Copy entire object into memory. There are cases where gcc-generated 6392 // code assumes it is there, even if it could be put entirely into 6393 // registers. (This is not what the doc says.) 6394 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff, 6395 CallSeqStart, 6396 Flags, DAG, dl); 6397 6398 // For small aggregates (Darwin only) and aggregates >= PtrByteSize, 6399 // copy the pieces of the object that fit into registers from the 6400 // parameter save area. 6401 for (unsigned j=0; j<Size; j+=PtrByteSize) { 6402 SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType()); 6403 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const); 6404 if (GPR_idx != NumGPRs) { 6405 SDValue Load = 6406 DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo()); 6407 MemOpChains.push_back(Load.getValue(1)); 6408 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6409 ArgOffset += PtrByteSize; 6410 } else { 6411 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize; 6412 break; 6413 } 6414 } 6415 continue; 6416 } 6417 6418 switch (Arg.getSimpleValueType().SimpleTy) { 6419 default: llvm_unreachable("Unexpected ValueType for argument!"); 6420 case MVT::i1: 6421 case MVT::i32: 6422 case MVT::i64: 6423 if (GPR_idx != NumGPRs) { 6424 if (Arg.getValueType() == MVT::i1) 6425 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, PtrVT, Arg); 6426 6427 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg)); 6428 } else { 6429 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6430 isPPC64, isTailCall, false, MemOpChains, 6431 TailCallArguments, dl); 6432 } 6433 ArgOffset += PtrByteSize; 6434 break; 6435 case MVT::f32: 6436 case MVT::f64: 6437 if (FPR_idx != NumFPRs) { 6438 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg)); 6439 6440 if (isVarArg) { 6441 SDValue Store = 6442 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 6443 MemOpChains.push_back(Store); 6444 6445 // Float varargs are always shadowed in available integer registers 6446 if (GPR_idx != NumGPRs) { 6447 SDValue Load = 6448 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo()); 6449 MemOpChains.push_back(Load.getValue(1)); 6450 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6451 } 6452 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && !isPPC64){ 6453 SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType()); 6454 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour); 6455 SDValue Load = 6456 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo()); 6457 MemOpChains.push_back(Load.getValue(1)); 6458 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6459 } 6460 } else { 6461 // If we have any FPRs remaining, we may also have GPRs remaining. 6462 // Args passed in FPRs consume either 1 (f32) or 2 (f64) available 6463 // GPRs. 6464 if (GPR_idx != NumGPRs) 6465 ++GPR_idx; 6466 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && 6467 !isPPC64) // PPC64 has 64-bit GPR's obviously :) 6468 ++GPR_idx; 6469 } 6470 } else 6471 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6472 isPPC64, isTailCall, false, MemOpChains, 6473 TailCallArguments, dl); 6474 if (isPPC64) 6475 ArgOffset += 8; 6476 else 6477 ArgOffset += Arg.getValueType() == MVT::f32 ? 4 : 8; 6478 break; 6479 case MVT::v4f32: 6480 case MVT::v4i32: 6481 case MVT::v8i16: 6482 case MVT::v16i8: 6483 if (isVarArg) { 6484 // These go aligned on the stack, or in the corresponding R registers 6485 // when within range. The Darwin PPC ABI doc claims they also go in 6486 // V registers; in fact gcc does this only for arguments that are 6487 // prototyped, not for those that match the ... We do it for all 6488 // arguments, seems to work. 6489 while (ArgOffset % 16 !=0) { 6490 ArgOffset += PtrByteSize; 6491 if (GPR_idx != NumGPRs) 6492 GPR_idx++; 6493 } 6494 // We could elide this store in the case where the object fits 6495 // entirely in R registers. Maybe later. 6496 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, 6497 DAG.getConstant(ArgOffset, dl, PtrVT)); 6498 SDValue Store = 6499 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 6500 MemOpChains.push_back(Store); 6501 if (VR_idx != NumVRs) { 6502 SDValue Load = 6503 DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo()); 6504 MemOpChains.push_back(Load.getValue(1)); 6505 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load)); 6506 } 6507 ArgOffset += 16; 6508 for (unsigned i=0; i<16; i+=PtrByteSize) { 6509 if (GPR_idx == NumGPRs) 6510 break; 6511 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, 6512 DAG.getConstant(i, dl, PtrVT)); 6513 SDValue Load = 6514 DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo()); 6515 MemOpChains.push_back(Load.getValue(1)); 6516 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6517 } 6518 break; 6519 } 6520 6521 // Non-varargs Altivec params generally go in registers, but have 6522 // stack space allocated at the end. 6523 if (VR_idx != NumVRs) { 6524 // Doesn't have GPR space allocated. 6525 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg)); 6526 } else if (nAltivecParamsAtEnd==0) { 6527 // We are emitting Altivec params in order. 6528 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6529 isPPC64, isTailCall, true, MemOpChains, 6530 TailCallArguments, dl); 6531 ArgOffset += 16; 6532 } 6533 break; 6534 } 6535 } 6536 // If all Altivec parameters fit in registers, as they usually do, 6537 // they get stack space following the non-Altivec parameters. We 6538 // don't track this here because nobody below needs it. 6539 // If there are more Altivec parameters than fit in registers emit 6540 // the stores here. 6541 if (!isVarArg && nAltivecParamsAtEnd > NumVRs) { 6542 unsigned j = 0; 6543 // Offset is aligned; skip 1st 12 params which go in V registers. 6544 ArgOffset = ((ArgOffset+15)/16)*16; 6545 ArgOffset += 12*16; 6546 for (unsigned i = 0; i != NumOps; ++i) { 6547 SDValue Arg = OutVals[i]; 6548 EVT ArgType = Outs[i].VT; 6549 if (ArgType==MVT::v4f32 || ArgType==MVT::v4i32 || 6550 ArgType==MVT::v8i16 || ArgType==MVT::v16i8) { 6551 if (++j > NumVRs) { 6552 SDValue PtrOff; 6553 // We are emitting Altivec params in order. 6554 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6555 isPPC64, isTailCall, true, MemOpChains, 6556 TailCallArguments, dl); 6557 ArgOffset += 16; 6558 } 6559 } 6560 } 6561 } 6562 6563 if (!MemOpChains.empty()) 6564 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 6565 6566 // On Darwin, R12 must contain the address of an indirect callee. This does 6567 // not mean the MTCTR instruction must use R12; it's easier to model this as 6568 // an extra parameter, so do that. 6569 if (!isTailCall && 6570 !isFunctionGlobalAddress(Callee) && 6571 !isa<ExternalSymbolSDNode>(Callee) && 6572 !isBLACompatibleAddress(Callee, DAG)) 6573 RegsToPass.push_back(std::make_pair((unsigned)(isPPC64 ? PPC::X12 : 6574 PPC::R12), Callee)); 6575 6576 // Build a sequence of copy-to-reg nodes chained together with token chain 6577 // and flag operands which copy the outgoing args into the appropriate regs. 6578 SDValue InFlag; 6579 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 6580 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 6581 RegsToPass[i].second, InFlag); 6582 InFlag = Chain.getValue(1); 6583 } 6584 6585 if (isTailCall) 6586 PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp, 6587 TailCallArguments); 6588 6589 return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint, 6590 /* unused except on PPC64 ELFv1 */ false, DAG, 6591 RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff, 6592 NumBytes, Ins, InVals, CS); 6593 } 6594 6595 bool 6596 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv, 6597 MachineFunction &MF, bool isVarArg, 6598 const SmallVectorImpl<ISD::OutputArg> &Outs, 6599 LLVMContext &Context) const { 6600 SmallVector<CCValAssign, 16> RVLocs; 6601 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context); 6602 return CCInfo.CheckReturn( 6603 Outs, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold) 6604 ? RetCC_PPC_Cold 6605 : RetCC_PPC); 6606 } 6607 6608 SDValue 6609 PPCTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 6610 bool isVarArg, 6611 const SmallVectorImpl<ISD::OutputArg> &Outs, 6612 const SmallVectorImpl<SDValue> &OutVals, 6613 const SDLoc &dl, SelectionDAG &DAG) const { 6614 SmallVector<CCValAssign, 16> RVLocs; 6615 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 6616 *DAG.getContext()); 6617 CCInfo.AnalyzeReturn(Outs, 6618 (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold) 6619 ? RetCC_PPC_Cold 6620 : RetCC_PPC); 6621 6622 SDValue Flag; 6623 SmallVector<SDValue, 4> RetOps(1, Chain); 6624 6625 // Copy the result values into the output registers. 6626 for (unsigned i = 0; i != RVLocs.size(); ++i) { 6627 CCValAssign &VA = RVLocs[i]; 6628 assert(VA.isRegLoc() && "Can only return in registers!"); 6629 6630 SDValue Arg = OutVals[i]; 6631 6632 switch (VA.getLocInfo()) { 6633 default: llvm_unreachable("Unknown loc info!"); 6634 case CCValAssign::Full: break; 6635 case CCValAssign::AExt: 6636 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg); 6637 break; 6638 case CCValAssign::ZExt: 6639 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg); 6640 break; 6641 case CCValAssign::SExt: 6642 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg); 6643 break; 6644 } 6645 6646 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag); 6647 Flag = Chain.getValue(1); 6648 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 6649 } 6650 6651 const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo(); 6652 const MCPhysReg *I = 6653 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction()); 6654 if (I) { 6655 for (; *I; ++I) { 6656 6657 if (PPC::G8RCRegClass.contains(*I)) 6658 RetOps.push_back(DAG.getRegister(*I, MVT::i64)); 6659 else if (PPC::F8RCRegClass.contains(*I)) 6660 RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64))); 6661 else if (PPC::CRRCRegClass.contains(*I)) 6662 RetOps.push_back(DAG.getRegister(*I, MVT::i1)); 6663 else if (PPC::VRRCRegClass.contains(*I)) 6664 RetOps.push_back(DAG.getRegister(*I, MVT::Other)); 6665 else 6666 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 6667 } 6668 } 6669 6670 RetOps[0] = Chain; // Update chain. 6671 6672 // Add the flag if we have it. 6673 if (Flag.getNode()) 6674 RetOps.push_back(Flag); 6675 6676 return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, RetOps); 6677 } 6678 6679 SDValue 6680 PPCTargetLowering::LowerGET_DYNAMIC_AREA_OFFSET(SDValue Op, 6681 SelectionDAG &DAG) const { 6682 SDLoc dl(Op); 6683 6684 // Get the correct type for integers. 6685 EVT IntVT = Op.getValueType(); 6686 6687 // Get the inputs. 6688 SDValue Chain = Op.getOperand(0); 6689 SDValue FPSIdx = getFramePointerFrameIndex(DAG); 6690 // Build a DYNAREAOFFSET node. 6691 SDValue Ops[2] = {Chain, FPSIdx}; 6692 SDVTList VTs = DAG.getVTList(IntVT); 6693 return DAG.getNode(PPCISD::DYNAREAOFFSET, dl, VTs, Ops); 6694 } 6695 6696 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op, 6697 SelectionDAG &DAG) const { 6698 // When we pop the dynamic allocation we need to restore the SP link. 6699 SDLoc dl(Op); 6700 6701 // Get the correct type for pointers. 6702 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 6703 6704 // Construct the stack pointer operand. 6705 bool isPPC64 = Subtarget.isPPC64(); 6706 unsigned SP = isPPC64 ? PPC::X1 : PPC::R1; 6707 SDValue StackPtr = DAG.getRegister(SP, PtrVT); 6708 6709 // Get the operands for the STACKRESTORE. 6710 SDValue Chain = Op.getOperand(0); 6711 SDValue SaveSP = Op.getOperand(1); 6712 6713 // Load the old link SP. 6714 SDValue LoadLinkSP = 6715 DAG.getLoad(PtrVT, dl, Chain, StackPtr, MachinePointerInfo()); 6716 6717 // Restore the stack pointer. 6718 Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP); 6719 6720 // Store the old link SP. 6721 return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo()); 6722 } 6723 6724 SDValue PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG &DAG) const { 6725 MachineFunction &MF = DAG.getMachineFunction(); 6726 bool isPPC64 = Subtarget.isPPC64(); 6727 EVT PtrVT = getPointerTy(MF.getDataLayout()); 6728 6729 // Get current frame pointer save index. The users of this index will be 6730 // primarily DYNALLOC instructions. 6731 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>(); 6732 int RASI = FI->getReturnAddrSaveIndex(); 6733 6734 // If the frame pointer save index hasn't been defined yet. 6735 if (!RASI) { 6736 // Find out what the fix offset of the frame pointer save area. 6737 int LROffset = Subtarget.getFrameLowering()->getReturnSaveOffset(); 6738 // Allocate the frame index for frame pointer save area. 6739 RASI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, LROffset, false); 6740 // Save the result. 6741 FI->setReturnAddrSaveIndex(RASI); 6742 } 6743 return DAG.getFrameIndex(RASI, PtrVT); 6744 } 6745 6746 SDValue 6747 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const { 6748 MachineFunction &MF = DAG.getMachineFunction(); 6749 bool isPPC64 = Subtarget.isPPC64(); 6750 EVT PtrVT = getPointerTy(MF.getDataLayout()); 6751 6752 // Get current frame pointer save index. The users of this index will be 6753 // primarily DYNALLOC instructions. 6754 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>(); 6755 int FPSI = FI->getFramePointerSaveIndex(); 6756 6757 // If the frame pointer save index hasn't been defined yet. 6758 if (!FPSI) { 6759 // Find out what the fix offset of the frame pointer save area. 6760 int FPOffset = Subtarget.getFrameLowering()->getFramePointerSaveOffset(); 6761 // Allocate the frame index for frame pointer save area. 6762 FPSI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, FPOffset, true); 6763 // Save the result. 6764 FI->setFramePointerSaveIndex(FPSI); 6765 } 6766 return DAG.getFrameIndex(FPSI, PtrVT); 6767 } 6768 6769 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, 6770 SelectionDAG &DAG) const { 6771 // Get the inputs. 6772 SDValue Chain = Op.getOperand(0); 6773 SDValue Size = Op.getOperand(1); 6774 SDLoc dl(Op); 6775 6776 // Get the correct type for pointers. 6777 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 6778 // Negate the size. 6779 SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT, 6780 DAG.getConstant(0, dl, PtrVT), Size); 6781 // Construct a node for the frame pointer save index. 6782 SDValue FPSIdx = getFramePointerFrameIndex(DAG); 6783 // Build a DYNALLOC node. 6784 SDValue Ops[3] = { Chain, NegSize, FPSIdx }; 6785 SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other); 6786 return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops); 6787 } 6788 6789 SDValue PPCTargetLowering::LowerEH_DWARF_CFA(SDValue Op, 6790 SelectionDAG &DAG) const { 6791 MachineFunction &MF = DAG.getMachineFunction(); 6792 6793 bool isPPC64 = Subtarget.isPPC64(); 6794 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 6795 6796 int FI = MF.getFrameInfo().CreateFixedObject(isPPC64 ? 8 : 4, 0, false); 6797 return DAG.getFrameIndex(FI, PtrVT); 6798 } 6799 6800 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op, 6801 SelectionDAG &DAG) const { 6802 SDLoc DL(Op); 6803 return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL, 6804 DAG.getVTList(MVT::i32, MVT::Other), 6805 Op.getOperand(0), Op.getOperand(1)); 6806 } 6807 6808 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op, 6809 SelectionDAG &DAG) const { 6810 SDLoc DL(Op); 6811 return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other, 6812 Op.getOperand(0), Op.getOperand(1)); 6813 } 6814 6815 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const { 6816 if (Op.getValueType().isVector()) 6817 return LowerVectorLoad(Op, DAG); 6818 6819 assert(Op.getValueType() == MVT::i1 && 6820 "Custom lowering only for i1 loads"); 6821 6822 // First, load 8 bits into 32 bits, then truncate to 1 bit. 6823 6824 SDLoc dl(Op); 6825 LoadSDNode *LD = cast<LoadSDNode>(Op); 6826 6827 SDValue Chain = LD->getChain(); 6828 SDValue BasePtr = LD->getBasePtr(); 6829 MachineMemOperand *MMO = LD->getMemOperand(); 6830 6831 SDValue NewLD = 6832 DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(DAG.getDataLayout()), Chain, 6833 BasePtr, MVT::i8, MMO); 6834 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD); 6835 6836 SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) }; 6837 return DAG.getMergeValues(Ops, dl); 6838 } 6839 6840 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const { 6841 if (Op.getOperand(1).getValueType().isVector()) 6842 return LowerVectorStore(Op, DAG); 6843 6844 assert(Op.getOperand(1).getValueType() == MVT::i1 && 6845 "Custom lowering only for i1 stores"); 6846 6847 // First, zero extend to 32 bits, then use a truncating store to 8 bits. 6848 6849 SDLoc dl(Op); 6850 StoreSDNode *ST = cast<StoreSDNode>(Op); 6851 6852 SDValue Chain = ST->getChain(); 6853 SDValue BasePtr = ST->getBasePtr(); 6854 SDValue Value = ST->getValue(); 6855 MachineMemOperand *MMO = ST->getMemOperand(); 6856 6857 Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(DAG.getDataLayout()), 6858 Value); 6859 return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO); 6860 } 6861 6862 // FIXME: Remove this once the ANDI glue bug is fixed: 6863 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const { 6864 assert(Op.getValueType() == MVT::i1 && 6865 "Custom lowering only for i1 results"); 6866 6867 SDLoc DL(Op); 6868 return DAG.getNode(PPCISD::ANDIo_1_GT_BIT, DL, MVT::i1, 6869 Op.getOperand(0)); 6870 } 6871 6872 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when 6873 /// possible. 6874 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const { 6875 // Not FP? Not a fsel. 6876 if (!Op.getOperand(0).getValueType().isFloatingPoint() || 6877 !Op.getOperand(2).getValueType().isFloatingPoint()) 6878 return Op; 6879 6880 // We might be able to do better than this under some circumstances, but in 6881 // general, fsel-based lowering of select is a finite-math-only optimization. 6882 // For more information, see section F.3 of the 2.06 ISA specification. 6883 if (!DAG.getTarget().Options.NoInfsFPMath || 6884 !DAG.getTarget().Options.NoNaNsFPMath) 6885 return Op; 6886 // TODO: Propagate flags from the select rather than global settings. 6887 SDNodeFlags Flags; 6888 Flags.setNoInfs(true); 6889 Flags.setNoNaNs(true); 6890 6891 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get(); 6892 6893 EVT ResVT = Op.getValueType(); 6894 EVT CmpVT = Op.getOperand(0).getValueType(); 6895 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 6896 SDValue TV = Op.getOperand(2), FV = Op.getOperand(3); 6897 SDLoc dl(Op); 6898 6899 // If the RHS of the comparison is a 0.0, we don't need to do the 6900 // subtraction at all. 6901 SDValue Sel1; 6902 if (isFloatingPointZero(RHS)) 6903 switch (CC) { 6904 default: break; // SETUO etc aren't handled by fsel. 6905 case ISD::SETNE: 6906 std::swap(TV, FV); 6907 LLVM_FALLTHROUGH; 6908 case ISD::SETEQ: 6909 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits 6910 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); 6911 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV); 6912 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits 6913 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1); 6914 return DAG.getNode(PPCISD::FSEL, dl, ResVT, 6915 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV); 6916 case ISD::SETULT: 6917 case ISD::SETLT: 6918 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt 6919 LLVM_FALLTHROUGH; 6920 case ISD::SETOGE: 6921 case ISD::SETGE: 6922 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits 6923 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); 6924 return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV); 6925 case ISD::SETUGT: 6926 case ISD::SETGT: 6927 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt 6928 LLVM_FALLTHROUGH; 6929 case ISD::SETOLE: 6930 case ISD::SETLE: 6931 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits 6932 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); 6933 return DAG.getNode(PPCISD::FSEL, dl, ResVT, 6934 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV); 6935 } 6936 6937 SDValue Cmp; 6938 switch (CC) { 6939 default: break; // SETUO etc aren't handled by fsel. 6940 case ISD::SETNE: 6941 std::swap(TV, FV); 6942 LLVM_FALLTHROUGH; 6943 case ISD::SETEQ: 6944 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags); 6945 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 6946 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 6947 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); 6948 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits 6949 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1); 6950 return DAG.getNode(PPCISD::FSEL, dl, ResVT, 6951 DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV); 6952 case ISD::SETULT: 6953 case ISD::SETLT: 6954 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags); 6955 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 6956 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 6957 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV); 6958 case ISD::SETOGE: 6959 case ISD::SETGE: 6960 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags); 6961 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 6962 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 6963 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); 6964 case ISD::SETUGT: 6965 case ISD::SETGT: 6966 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags); 6967 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 6968 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 6969 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV); 6970 case ISD::SETOLE: 6971 case ISD::SETLE: 6972 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags); 6973 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 6974 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 6975 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); 6976 } 6977 return Op; 6978 } 6979 6980 void PPCTargetLowering::LowerFP_TO_INTForReuse(SDValue Op, ReuseLoadInfo &RLI, 6981 SelectionDAG &DAG, 6982 const SDLoc &dl) const { 6983 assert(Op.getOperand(0).getValueType().isFloatingPoint()); 6984 SDValue Src = Op.getOperand(0); 6985 if (Src.getValueType() == MVT::f32) 6986 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src); 6987 6988 SDValue Tmp; 6989 switch (Op.getSimpleValueType().SimpleTy) { 6990 default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!"); 6991 case MVT::i32: 6992 Tmp = DAG.getNode( 6993 Op.getOpcode() == ISD::FP_TO_SINT 6994 ? PPCISD::FCTIWZ 6995 : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ), 6996 dl, MVT::f64, Src); 6997 break; 6998 case MVT::i64: 6999 assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) && 7000 "i64 FP_TO_UINT is supported only with FPCVT"); 7001 Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ : 7002 PPCISD::FCTIDUZ, 7003 dl, MVT::f64, Src); 7004 break; 7005 } 7006 7007 // Convert the FP value to an int value through memory. 7008 bool i32Stack = Op.getValueType() == MVT::i32 && Subtarget.hasSTFIWX() && 7009 (Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()); 7010 SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64); 7011 int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex(); 7012 MachinePointerInfo MPI = 7013 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI); 7014 7015 // Emit a store to the stack slot. 7016 SDValue Chain; 7017 if (i32Stack) { 7018 MachineFunction &MF = DAG.getMachineFunction(); 7019 MachineMemOperand *MMO = 7020 MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, 4); 7021 SDValue Ops[] = { DAG.getEntryNode(), Tmp, FIPtr }; 7022 Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl, 7023 DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO); 7024 } else 7025 Chain = DAG.getStore(DAG.getEntryNode(), dl, Tmp, FIPtr, MPI); 7026 7027 // Result is a load from the stack slot. If loading 4 bytes, make sure to 7028 // add in a bias on big endian. 7029 if (Op.getValueType() == MVT::i32 && !i32Stack) { 7030 FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr, 7031 DAG.getConstant(4, dl, FIPtr.getValueType())); 7032 MPI = MPI.getWithOffset(Subtarget.isLittleEndian() ? 0 : 4); 7033 } 7034 7035 RLI.Chain = Chain; 7036 RLI.Ptr = FIPtr; 7037 RLI.MPI = MPI; 7038 } 7039 7040 /// Custom lowers floating point to integer conversions to use 7041 /// the direct move instructions available in ISA 2.07 to avoid the 7042 /// need for load/store combinations. 7043 SDValue PPCTargetLowering::LowerFP_TO_INTDirectMove(SDValue Op, 7044 SelectionDAG &DAG, 7045 const SDLoc &dl) const { 7046 assert(Op.getOperand(0).getValueType().isFloatingPoint()); 7047 SDValue Src = Op.getOperand(0); 7048 7049 if (Src.getValueType() == MVT::f32) 7050 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src); 7051 7052 SDValue Tmp; 7053 switch (Op.getSimpleValueType().SimpleTy) { 7054 default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!"); 7055 case MVT::i32: 7056 Tmp = DAG.getNode( 7057 Op.getOpcode() == ISD::FP_TO_SINT 7058 ? PPCISD::FCTIWZ 7059 : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ), 7060 dl, MVT::f64, Src); 7061 Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i32, Tmp); 7062 break; 7063 case MVT::i64: 7064 assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) && 7065 "i64 FP_TO_UINT is supported only with FPCVT"); 7066 Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ : 7067 PPCISD::FCTIDUZ, 7068 dl, MVT::f64, Src); 7069 Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i64, Tmp); 7070 break; 7071 } 7072 return Tmp; 7073 } 7074 7075 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG, 7076 const SDLoc &dl) const { 7077 7078 // FP to INT conversions are legal for f128. 7079 if (EnableQuadPrecision && (Op->getOperand(0).getValueType() == MVT::f128)) 7080 return Op; 7081 7082 // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on 7083 // PPC (the libcall is not available). 7084 if (Op.getOperand(0).getValueType() == MVT::ppcf128) { 7085 if (Op.getValueType() == MVT::i32) { 7086 if (Op.getOpcode() == ISD::FP_TO_SINT) { 7087 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, 7088 MVT::f64, Op.getOperand(0), 7089 DAG.getIntPtrConstant(0, dl)); 7090 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, 7091 MVT::f64, Op.getOperand(0), 7092 DAG.getIntPtrConstant(1, dl)); 7093 7094 // Add the two halves of the long double in round-to-zero mode. 7095 SDValue Res = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi); 7096 7097 // Now use a smaller FP_TO_SINT. 7098 return DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Res); 7099 } 7100 if (Op.getOpcode() == ISD::FP_TO_UINT) { 7101 const uint64_t TwoE31[] = {0x41e0000000000000LL, 0}; 7102 APFloat APF = APFloat(APFloat::PPCDoubleDouble(), APInt(128, TwoE31)); 7103 SDValue Tmp = DAG.getConstantFP(APF, dl, MVT::ppcf128); 7104 // X>=2^31 ? (int)(X-2^31)+0x80000000 : (int)X 7105 // FIXME: generated code sucks. 7106 // TODO: Are there fast-math-flags to propagate to this FSUB? 7107 SDValue True = DAG.getNode(ISD::FSUB, dl, MVT::ppcf128, 7108 Op.getOperand(0), Tmp); 7109 True = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, True); 7110 True = DAG.getNode(ISD::ADD, dl, MVT::i32, True, 7111 DAG.getConstant(0x80000000, dl, MVT::i32)); 7112 SDValue False = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, 7113 Op.getOperand(0)); 7114 return DAG.getSelectCC(dl, Op.getOperand(0), Tmp, True, False, 7115 ISD::SETGE); 7116 } 7117 } 7118 7119 return SDValue(); 7120 } 7121 7122 if (Subtarget.hasDirectMove() && Subtarget.isPPC64()) 7123 return LowerFP_TO_INTDirectMove(Op, DAG, dl); 7124 7125 ReuseLoadInfo RLI; 7126 LowerFP_TO_INTForReuse(Op, RLI, DAG, dl); 7127 7128 return DAG.getLoad(Op.getValueType(), dl, RLI.Chain, RLI.Ptr, RLI.MPI, 7129 RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges); 7130 } 7131 7132 // We're trying to insert a regular store, S, and then a load, L. If the 7133 // incoming value, O, is a load, we might just be able to have our load use the 7134 // address used by O. However, we don't know if anything else will store to 7135 // that address before we can load from it. To prevent this situation, we need 7136 // to insert our load, L, into the chain as a peer of O. To do this, we give L 7137 // the same chain operand as O, we create a token factor from the chain results 7138 // of O and L, and we replace all uses of O's chain result with that token 7139 // factor (see spliceIntoChain below for this last part). 7140 bool PPCTargetLowering::canReuseLoadAddress(SDValue Op, EVT MemVT, 7141 ReuseLoadInfo &RLI, 7142 SelectionDAG &DAG, 7143 ISD::LoadExtType ET) const { 7144 SDLoc dl(Op); 7145 if (ET == ISD::NON_EXTLOAD && 7146 (Op.getOpcode() == ISD::FP_TO_UINT || 7147 Op.getOpcode() == ISD::FP_TO_SINT) && 7148 isOperationLegalOrCustom(Op.getOpcode(), 7149 Op.getOperand(0).getValueType())) { 7150 7151 LowerFP_TO_INTForReuse(Op, RLI, DAG, dl); 7152 return true; 7153 } 7154 7155 LoadSDNode *LD = dyn_cast<LoadSDNode>(Op); 7156 if (!LD || LD->getExtensionType() != ET || LD->isVolatile() || 7157 LD->isNonTemporal()) 7158 return false; 7159 if (LD->getMemoryVT() != MemVT) 7160 return false; 7161 7162 RLI.Ptr = LD->getBasePtr(); 7163 if (LD->isIndexed() && !LD->getOffset().isUndef()) { 7164 assert(LD->getAddressingMode() == ISD::PRE_INC && 7165 "Non-pre-inc AM on PPC?"); 7166 RLI.Ptr = DAG.getNode(ISD::ADD, dl, RLI.Ptr.getValueType(), RLI.Ptr, 7167 LD->getOffset()); 7168 } 7169 7170 RLI.Chain = LD->getChain(); 7171 RLI.MPI = LD->getPointerInfo(); 7172 RLI.IsDereferenceable = LD->isDereferenceable(); 7173 RLI.IsInvariant = LD->isInvariant(); 7174 RLI.Alignment = LD->getAlignment(); 7175 RLI.AAInfo = LD->getAAInfo(); 7176 RLI.Ranges = LD->getRanges(); 7177 7178 RLI.ResChain = SDValue(LD, LD->isIndexed() ? 2 : 1); 7179 return true; 7180 } 7181 7182 // Given the head of the old chain, ResChain, insert a token factor containing 7183 // it and NewResChain, and make users of ResChain now be users of that token 7184 // factor. 7185 // TODO: Remove and use DAG::makeEquivalentMemoryOrdering() instead. 7186 void PPCTargetLowering::spliceIntoChain(SDValue ResChain, 7187 SDValue NewResChain, 7188 SelectionDAG &DAG) const { 7189 if (!ResChain) 7190 return; 7191 7192 SDLoc dl(NewResChain); 7193 7194 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 7195 NewResChain, DAG.getUNDEF(MVT::Other)); 7196 assert(TF.getNode() != NewResChain.getNode() && 7197 "A new TF really is required here"); 7198 7199 DAG.ReplaceAllUsesOfValueWith(ResChain, TF); 7200 DAG.UpdateNodeOperands(TF.getNode(), ResChain, NewResChain); 7201 } 7202 7203 /// Analyze profitability of direct move 7204 /// prefer float load to int load plus direct move 7205 /// when there is no integer use of int load 7206 bool PPCTargetLowering::directMoveIsProfitable(const SDValue &Op) const { 7207 SDNode *Origin = Op.getOperand(0).getNode(); 7208 if (Origin->getOpcode() != ISD::LOAD) 7209 return true; 7210 7211 // If there is no LXSIBZX/LXSIHZX, like Power8, 7212 // prefer direct move if the memory size is 1 or 2 bytes. 7213 MachineMemOperand *MMO = cast<LoadSDNode>(Origin)->getMemOperand(); 7214 if (!Subtarget.hasP9Vector() && MMO->getSize() <= 2) 7215 return true; 7216 7217 for (SDNode::use_iterator UI = Origin->use_begin(), 7218 UE = Origin->use_end(); 7219 UI != UE; ++UI) { 7220 7221 // Only look at the users of the loaded value. 7222 if (UI.getUse().get().getResNo() != 0) 7223 continue; 7224 7225 if (UI->getOpcode() != ISD::SINT_TO_FP && 7226 UI->getOpcode() != ISD::UINT_TO_FP) 7227 return true; 7228 } 7229 7230 return false; 7231 } 7232 7233 /// Custom lowers integer to floating point conversions to use 7234 /// the direct move instructions available in ISA 2.07 to avoid the 7235 /// need for load/store combinations. 7236 SDValue PPCTargetLowering::LowerINT_TO_FPDirectMove(SDValue Op, 7237 SelectionDAG &DAG, 7238 const SDLoc &dl) const { 7239 assert((Op.getValueType() == MVT::f32 || 7240 Op.getValueType() == MVT::f64) && 7241 "Invalid floating point type as target of conversion"); 7242 assert(Subtarget.hasFPCVT() && 7243 "Int to FP conversions with direct moves require FPCVT"); 7244 SDValue FP; 7245 SDValue Src = Op.getOperand(0); 7246 bool SinglePrec = Op.getValueType() == MVT::f32; 7247 bool WordInt = Src.getSimpleValueType().SimpleTy == MVT::i32; 7248 bool Signed = Op.getOpcode() == ISD::SINT_TO_FP; 7249 unsigned ConvOp = Signed ? (SinglePrec ? PPCISD::FCFIDS : PPCISD::FCFID) : 7250 (SinglePrec ? PPCISD::FCFIDUS : PPCISD::FCFIDU); 7251 7252 if (WordInt) { 7253 FP = DAG.getNode(Signed ? PPCISD::MTVSRA : PPCISD::MTVSRZ, 7254 dl, MVT::f64, Src); 7255 FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP); 7256 } 7257 else { 7258 FP = DAG.getNode(PPCISD::MTVSRA, dl, MVT::f64, Src); 7259 FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP); 7260 } 7261 7262 return FP; 7263 } 7264 7265 static SDValue widenVec(SelectionDAG &DAG, SDValue Vec, const SDLoc &dl) { 7266 7267 EVT VecVT = Vec.getValueType(); 7268 assert(VecVT.isVector() && "Expected a vector type."); 7269 assert(VecVT.getSizeInBits() < 128 && "Vector is already full width."); 7270 7271 EVT EltVT = VecVT.getVectorElementType(); 7272 unsigned WideNumElts = 128 / EltVT.getSizeInBits(); 7273 EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts); 7274 7275 unsigned NumConcat = WideNumElts / VecVT.getVectorNumElements(); 7276 SmallVector<SDValue, 16> Ops(NumConcat); 7277 Ops[0] = Vec; 7278 SDValue UndefVec = DAG.getUNDEF(VecVT); 7279 for (unsigned i = 1; i < NumConcat; ++i) 7280 Ops[i] = UndefVec; 7281 7282 return DAG.getNode(ISD::CONCAT_VECTORS, dl, WideVT, Ops); 7283 } 7284 7285 SDValue PPCTargetLowering::LowerINT_TO_FPVector(SDValue Op, 7286 SelectionDAG &DAG, 7287 const SDLoc &dl) const { 7288 7289 unsigned Opc = Op.getOpcode(); 7290 assert((Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP) && 7291 "Unexpected conversion type"); 7292 assert(Op.getValueType() == MVT::v2f64 && "Supports v2f64 only."); 7293 7294 // CPU's prior to P9 don't have a way to sign-extend in vectors. 7295 bool SignedConv = Opc == ISD::SINT_TO_FP; 7296 if (SignedConv && !Subtarget.hasP9Altivec()) 7297 return SDValue(); 7298 7299 SDValue Wide = widenVec(DAG, Op.getOperand(0), dl); 7300 EVT WideVT = Wide.getValueType(); 7301 unsigned WideNumElts = WideVT.getVectorNumElements(); 7302 7303 SmallVector<int, 16> ShuffV; 7304 for (unsigned i = 0; i < WideNumElts; ++i) 7305 ShuffV.push_back(i + WideNumElts); 7306 7307 if (Subtarget.isLittleEndian()) { 7308 ShuffV[0] = 0; 7309 ShuffV[WideNumElts / 2] = 1; 7310 } 7311 else { 7312 ShuffV[WideNumElts / 2 - 1] = 0; 7313 ShuffV[WideNumElts - 1] = 1; 7314 } 7315 7316 SDValue ShuffleSrc2 = SignedConv ? DAG.getUNDEF(WideVT) : 7317 DAG.getConstant(0, dl, WideVT); 7318 SDValue Arrange = DAG.getVectorShuffle(WideVT, dl, Wide, ShuffleSrc2, ShuffV); 7319 unsigned ExtendOp = SignedConv ? (unsigned) PPCISD::SExtVElems : 7320 (unsigned) ISD::BITCAST; 7321 SDValue Extend = DAG.getNode(ExtendOp, dl, MVT::v2i64, Arrange); 7322 7323 return DAG.getNode(Opc, dl, Op.getValueType(), Extend); 7324 } 7325 7326 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op, 7327 SelectionDAG &DAG) const { 7328 SDLoc dl(Op); 7329 7330 if (Op.getValueType() == MVT::v2f64 && 7331 Op.getOperand(0).getValueType() == MVT::v2i16) 7332 return LowerINT_TO_FPVector(Op, DAG, dl); 7333 7334 // Conversions to f128 are legal. 7335 if (EnableQuadPrecision && (Op.getValueType() == MVT::f128)) 7336 return Op; 7337 7338 if (Subtarget.hasQPX() && Op.getOperand(0).getValueType() == MVT::v4i1) { 7339 if (Op.getValueType() != MVT::v4f32 && Op.getValueType() != MVT::v4f64) 7340 return SDValue(); 7341 7342 SDValue Value = Op.getOperand(0); 7343 // The values are now known to be -1 (false) or 1 (true). To convert this 7344 // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5). 7345 // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5 7346 Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value); 7347 7348 SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64); 7349 7350 Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs); 7351 7352 if (Op.getValueType() != MVT::v4f64) 7353 Value = DAG.getNode(ISD::FP_ROUND, dl, 7354 Op.getValueType(), Value, 7355 DAG.getIntPtrConstant(1, dl)); 7356 return Value; 7357 } 7358 7359 // Don't handle ppc_fp128 here; let it be lowered to a libcall. 7360 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64) 7361 return SDValue(); 7362 7363 if (Op.getOperand(0).getValueType() == MVT::i1) 7364 return DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Op.getOperand(0), 7365 DAG.getConstantFP(1.0, dl, Op.getValueType()), 7366 DAG.getConstantFP(0.0, dl, Op.getValueType())); 7367 7368 // If we have direct moves, we can do all the conversion, skip the store/load 7369 // however, without FPCVT we can't do most conversions. 7370 if (Subtarget.hasDirectMove() && directMoveIsProfitable(Op) && 7371 Subtarget.isPPC64() && Subtarget.hasFPCVT()) 7372 return LowerINT_TO_FPDirectMove(Op, DAG, dl); 7373 7374 assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) && 7375 "UINT_TO_FP is supported only with FPCVT"); 7376 7377 // If we have FCFIDS, then use it when converting to single-precision. 7378 // Otherwise, convert to double-precision and then round. 7379 unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 7380 ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS 7381 : PPCISD::FCFIDS) 7382 : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU 7383 : PPCISD::FCFID); 7384 MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 7385 ? MVT::f32 7386 : MVT::f64; 7387 7388 if (Op.getOperand(0).getValueType() == MVT::i64) { 7389 SDValue SINT = Op.getOperand(0); 7390 // When converting to single-precision, we actually need to convert 7391 // to double-precision first and then round to single-precision. 7392 // To avoid double-rounding effects during that operation, we have 7393 // to prepare the input operand. Bits that might be truncated when 7394 // converting to double-precision are replaced by a bit that won't 7395 // be lost at this stage, but is below the single-precision rounding 7396 // position. 7397 // 7398 // However, if -enable-unsafe-fp-math is in effect, accept double 7399 // rounding to avoid the extra overhead. 7400 if (Op.getValueType() == MVT::f32 && 7401 !Subtarget.hasFPCVT() && 7402 !DAG.getTarget().Options.UnsafeFPMath) { 7403 7404 // Twiddle input to make sure the low 11 bits are zero. (If this 7405 // is the case, we are guaranteed the value will fit into the 53 bit 7406 // mantissa of an IEEE double-precision value without rounding.) 7407 // If any of those low 11 bits were not zero originally, make sure 7408 // bit 12 (value 2048) is set instead, so that the final rounding 7409 // to single-precision gets the correct result. 7410 SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64, 7411 SINT, DAG.getConstant(2047, dl, MVT::i64)); 7412 Round = DAG.getNode(ISD::ADD, dl, MVT::i64, 7413 Round, DAG.getConstant(2047, dl, MVT::i64)); 7414 Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT); 7415 Round = DAG.getNode(ISD::AND, dl, MVT::i64, 7416 Round, DAG.getConstant(-2048, dl, MVT::i64)); 7417 7418 // However, we cannot use that value unconditionally: if the magnitude 7419 // of the input value is small, the bit-twiddling we did above might 7420 // end up visibly changing the output. Fortunately, in that case, we 7421 // don't need to twiddle bits since the original input will convert 7422 // exactly to double-precision floating-point already. Therefore, 7423 // construct a conditional to use the original value if the top 11 7424 // bits are all sign-bit copies, and use the rounded value computed 7425 // above otherwise. 7426 SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64, 7427 SINT, DAG.getConstant(53, dl, MVT::i32)); 7428 Cond = DAG.getNode(ISD::ADD, dl, MVT::i64, 7429 Cond, DAG.getConstant(1, dl, MVT::i64)); 7430 Cond = DAG.getSetCC(dl, MVT::i32, 7431 Cond, DAG.getConstant(1, dl, MVT::i64), ISD::SETUGT); 7432 7433 SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT); 7434 } 7435 7436 ReuseLoadInfo RLI; 7437 SDValue Bits; 7438 7439 MachineFunction &MF = DAG.getMachineFunction(); 7440 if (canReuseLoadAddress(SINT, MVT::i64, RLI, DAG)) { 7441 Bits = DAG.getLoad(MVT::f64, dl, RLI.Chain, RLI.Ptr, RLI.MPI, 7442 RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges); 7443 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG); 7444 } else if (Subtarget.hasLFIWAX() && 7445 canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::SEXTLOAD)) { 7446 MachineMemOperand *MMO = 7447 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 7448 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 7449 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 7450 Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWAX, dl, 7451 DAG.getVTList(MVT::f64, MVT::Other), 7452 Ops, MVT::i32, MMO); 7453 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG); 7454 } else if (Subtarget.hasFPCVT() && 7455 canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::ZEXTLOAD)) { 7456 MachineMemOperand *MMO = 7457 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 7458 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 7459 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 7460 Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWZX, dl, 7461 DAG.getVTList(MVT::f64, MVT::Other), 7462 Ops, MVT::i32, MMO); 7463 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG); 7464 } else if (((Subtarget.hasLFIWAX() && 7465 SINT.getOpcode() == ISD::SIGN_EXTEND) || 7466 (Subtarget.hasFPCVT() && 7467 SINT.getOpcode() == ISD::ZERO_EXTEND)) && 7468 SINT.getOperand(0).getValueType() == MVT::i32) { 7469 MachineFrameInfo &MFI = MF.getFrameInfo(); 7470 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7471 7472 int FrameIdx = MFI.CreateStackObject(4, 4, false); 7473 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 7474 7475 SDValue Store = 7476 DAG.getStore(DAG.getEntryNode(), dl, SINT.getOperand(0), FIdx, 7477 MachinePointerInfo::getFixedStack( 7478 DAG.getMachineFunction(), FrameIdx)); 7479 7480 assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 && 7481 "Expected an i32 store"); 7482 7483 RLI.Ptr = FIdx; 7484 RLI.Chain = Store; 7485 RLI.MPI = 7486 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 7487 RLI.Alignment = 4; 7488 7489 MachineMemOperand *MMO = 7490 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 7491 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 7492 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 7493 Bits = DAG.getMemIntrinsicNode(SINT.getOpcode() == ISD::ZERO_EXTEND ? 7494 PPCISD::LFIWZX : PPCISD::LFIWAX, 7495 dl, DAG.getVTList(MVT::f64, MVT::Other), 7496 Ops, MVT::i32, MMO); 7497 } else 7498 Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT); 7499 7500 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Bits); 7501 7502 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) 7503 FP = DAG.getNode(ISD::FP_ROUND, dl, 7504 MVT::f32, FP, DAG.getIntPtrConstant(0, dl)); 7505 return FP; 7506 } 7507 7508 assert(Op.getOperand(0).getValueType() == MVT::i32 && 7509 "Unhandled INT_TO_FP type in custom expander!"); 7510 // Since we only generate this in 64-bit mode, we can take advantage of 7511 // 64-bit registers. In particular, sign extend the input value into the 7512 // 64-bit register with extsw, store the WHOLE 64-bit value into the stack 7513 // then lfd it and fcfid it. 7514 MachineFunction &MF = DAG.getMachineFunction(); 7515 MachineFrameInfo &MFI = MF.getFrameInfo(); 7516 EVT PtrVT = getPointerTy(MF.getDataLayout()); 7517 7518 SDValue Ld; 7519 if (Subtarget.hasLFIWAX() || Subtarget.hasFPCVT()) { 7520 ReuseLoadInfo RLI; 7521 bool ReusingLoad; 7522 if (!(ReusingLoad = canReuseLoadAddress(Op.getOperand(0), MVT::i32, RLI, 7523 DAG))) { 7524 int FrameIdx = MFI.CreateStackObject(4, 4, false); 7525 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 7526 7527 SDValue Store = 7528 DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx, 7529 MachinePointerInfo::getFixedStack( 7530 DAG.getMachineFunction(), FrameIdx)); 7531 7532 assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 && 7533 "Expected an i32 store"); 7534 7535 RLI.Ptr = FIdx; 7536 RLI.Chain = Store; 7537 RLI.MPI = 7538 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 7539 RLI.Alignment = 4; 7540 } 7541 7542 MachineMemOperand *MMO = 7543 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 7544 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 7545 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 7546 Ld = DAG.getMemIntrinsicNode(Op.getOpcode() == ISD::UINT_TO_FP ? 7547 PPCISD::LFIWZX : PPCISD::LFIWAX, 7548 dl, DAG.getVTList(MVT::f64, MVT::Other), 7549 Ops, MVT::i32, MMO); 7550 if (ReusingLoad) 7551 spliceIntoChain(RLI.ResChain, Ld.getValue(1), DAG); 7552 } else { 7553 assert(Subtarget.isPPC64() && 7554 "i32->FP without LFIWAX supported only on PPC64"); 7555 7556 int FrameIdx = MFI.CreateStackObject(8, 8, false); 7557 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 7558 7559 SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64, 7560 Op.getOperand(0)); 7561 7562 // STD the extended value into the stack slot. 7563 SDValue Store = DAG.getStore( 7564 DAG.getEntryNode(), dl, Ext64, FIdx, 7565 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx)); 7566 7567 // Load the value as a double. 7568 Ld = DAG.getLoad( 7569 MVT::f64, dl, Store, FIdx, 7570 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx)); 7571 } 7572 7573 // FCFID it and return it. 7574 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Ld); 7575 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) 7576 FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP, 7577 DAG.getIntPtrConstant(0, dl)); 7578 return FP; 7579 } 7580 7581 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op, 7582 SelectionDAG &DAG) const { 7583 SDLoc dl(Op); 7584 /* 7585 The rounding mode is in bits 30:31 of FPSR, and has the following 7586 settings: 7587 00 Round to nearest 7588 01 Round to 0 7589 10 Round to +inf 7590 11 Round to -inf 7591 7592 FLT_ROUNDS, on the other hand, expects the following: 7593 -1 Undefined 7594 0 Round to 0 7595 1 Round to nearest 7596 2 Round to +inf 7597 3 Round to -inf 7598 7599 To perform the conversion, we do: 7600 ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1)) 7601 */ 7602 7603 MachineFunction &MF = DAG.getMachineFunction(); 7604 EVT VT = Op.getValueType(); 7605 EVT PtrVT = getPointerTy(MF.getDataLayout()); 7606 7607 // Save FP Control Word to register 7608 EVT NodeTys[] = { 7609 MVT::f64, // return register 7610 MVT::Glue // unused in this context 7611 }; 7612 SDValue Chain = DAG.getNode(PPCISD::MFFS, dl, NodeTys, None); 7613 7614 // Save FP register to stack slot 7615 int SSFI = MF.getFrameInfo().CreateStackObject(8, 8, false); 7616 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT); 7617 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Chain, StackSlot, 7618 MachinePointerInfo()); 7619 7620 // Load FP Control Word from low 32 bits of stack slot. 7621 SDValue Four = DAG.getConstant(4, dl, PtrVT); 7622 SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four); 7623 SDValue CWD = DAG.getLoad(MVT::i32, dl, Store, Addr, MachinePointerInfo()); 7624 7625 // Transform as necessary 7626 SDValue CWD1 = 7627 DAG.getNode(ISD::AND, dl, MVT::i32, 7628 CWD, DAG.getConstant(3, dl, MVT::i32)); 7629 SDValue CWD2 = 7630 DAG.getNode(ISD::SRL, dl, MVT::i32, 7631 DAG.getNode(ISD::AND, dl, MVT::i32, 7632 DAG.getNode(ISD::XOR, dl, MVT::i32, 7633 CWD, DAG.getConstant(3, dl, MVT::i32)), 7634 DAG.getConstant(3, dl, MVT::i32)), 7635 DAG.getConstant(1, dl, MVT::i32)); 7636 7637 SDValue RetVal = 7638 DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2); 7639 7640 return DAG.getNode((VT.getSizeInBits() < 16 ? 7641 ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal); 7642 } 7643 7644 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const { 7645 EVT VT = Op.getValueType(); 7646 unsigned BitWidth = VT.getSizeInBits(); 7647 SDLoc dl(Op); 7648 assert(Op.getNumOperands() == 3 && 7649 VT == Op.getOperand(1).getValueType() && 7650 "Unexpected SHL!"); 7651 7652 // Expand into a bunch of logical ops. Note that these ops 7653 // depend on the PPC behavior for oversized shift amounts. 7654 SDValue Lo = Op.getOperand(0); 7655 SDValue Hi = Op.getOperand(1); 7656 SDValue Amt = Op.getOperand(2); 7657 EVT AmtVT = Amt.getValueType(); 7658 7659 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, 7660 DAG.getConstant(BitWidth, dl, AmtVT), Amt); 7661 SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt); 7662 SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1); 7663 SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3); 7664 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, 7665 DAG.getConstant(-BitWidth, dl, AmtVT)); 7666 SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5); 7667 SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6); 7668 SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt); 7669 SDValue OutOps[] = { OutLo, OutHi }; 7670 return DAG.getMergeValues(OutOps, dl); 7671 } 7672 7673 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const { 7674 EVT VT = Op.getValueType(); 7675 SDLoc dl(Op); 7676 unsigned BitWidth = VT.getSizeInBits(); 7677 assert(Op.getNumOperands() == 3 && 7678 VT == Op.getOperand(1).getValueType() && 7679 "Unexpected SRL!"); 7680 7681 // Expand into a bunch of logical ops. Note that these ops 7682 // depend on the PPC behavior for oversized shift amounts. 7683 SDValue Lo = Op.getOperand(0); 7684 SDValue Hi = Op.getOperand(1); 7685 SDValue Amt = Op.getOperand(2); 7686 EVT AmtVT = Amt.getValueType(); 7687 7688 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, 7689 DAG.getConstant(BitWidth, dl, AmtVT), Amt); 7690 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt); 7691 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1); 7692 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3); 7693 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, 7694 DAG.getConstant(-BitWidth, dl, AmtVT)); 7695 SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5); 7696 SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6); 7697 SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt); 7698 SDValue OutOps[] = { OutLo, OutHi }; 7699 return DAG.getMergeValues(OutOps, dl); 7700 } 7701 7702 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const { 7703 SDLoc dl(Op); 7704 EVT VT = Op.getValueType(); 7705 unsigned BitWidth = VT.getSizeInBits(); 7706 assert(Op.getNumOperands() == 3 && 7707 VT == Op.getOperand(1).getValueType() && 7708 "Unexpected SRA!"); 7709 7710 // Expand into a bunch of logical ops, followed by a select_cc. 7711 SDValue Lo = Op.getOperand(0); 7712 SDValue Hi = Op.getOperand(1); 7713 SDValue Amt = Op.getOperand(2); 7714 EVT AmtVT = Amt.getValueType(); 7715 7716 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, 7717 DAG.getConstant(BitWidth, dl, AmtVT), Amt); 7718 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt); 7719 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1); 7720 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3); 7721 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, 7722 DAG.getConstant(-BitWidth, dl, AmtVT)); 7723 SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5); 7724 SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt); 7725 SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, dl, AmtVT), 7726 Tmp4, Tmp6, ISD::SETLE); 7727 SDValue OutOps[] = { OutLo, OutHi }; 7728 return DAG.getMergeValues(OutOps, dl); 7729 } 7730 7731 //===----------------------------------------------------------------------===// 7732 // Vector related lowering. 7733 // 7734 7735 /// BuildSplatI - Build a canonical splati of Val with an element size of 7736 /// SplatSize. Cast the result to VT. 7737 static SDValue BuildSplatI(int Val, unsigned SplatSize, EVT VT, 7738 SelectionDAG &DAG, const SDLoc &dl) { 7739 assert(Val >= -16 && Val <= 15 && "vsplti is out of range!"); 7740 7741 static const MVT VTys[] = { // canonical VT to use for each size. 7742 MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32 7743 }; 7744 7745 EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1]; 7746 7747 // Force vspltis[hw] -1 to vspltisb -1 to canonicalize. 7748 if (Val == -1) 7749 SplatSize = 1; 7750 7751 EVT CanonicalVT = VTys[SplatSize-1]; 7752 7753 // Build a canonical splat for this value. 7754 return DAG.getBitcast(ReqVT, DAG.getConstant(Val, dl, CanonicalVT)); 7755 } 7756 7757 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the 7758 /// specified intrinsic ID. 7759 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op, SelectionDAG &DAG, 7760 const SDLoc &dl, EVT DestVT = MVT::Other) { 7761 if (DestVT == MVT::Other) DestVT = Op.getValueType(); 7762 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 7763 DAG.getConstant(IID, dl, MVT::i32), Op); 7764 } 7765 7766 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the 7767 /// specified intrinsic ID. 7768 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS, 7769 SelectionDAG &DAG, const SDLoc &dl, 7770 EVT DestVT = MVT::Other) { 7771 if (DestVT == MVT::Other) DestVT = LHS.getValueType(); 7772 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 7773 DAG.getConstant(IID, dl, MVT::i32), LHS, RHS); 7774 } 7775 7776 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the 7777 /// specified intrinsic ID. 7778 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1, 7779 SDValue Op2, SelectionDAG &DAG, const SDLoc &dl, 7780 EVT DestVT = MVT::Other) { 7781 if (DestVT == MVT::Other) DestVT = Op0.getValueType(); 7782 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 7783 DAG.getConstant(IID, dl, MVT::i32), Op0, Op1, Op2); 7784 } 7785 7786 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified 7787 /// amount. The result has the specified value type. 7788 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt, EVT VT, 7789 SelectionDAG &DAG, const SDLoc &dl) { 7790 // Force LHS/RHS to be the right type. 7791 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS); 7792 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS); 7793 7794 int Ops[16]; 7795 for (unsigned i = 0; i != 16; ++i) 7796 Ops[i] = i + Amt; 7797 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops); 7798 return DAG.getNode(ISD::BITCAST, dl, VT, T); 7799 } 7800 7801 /// Do we have an efficient pattern in a .td file for this node? 7802 /// 7803 /// \param V - pointer to the BuildVectorSDNode being matched 7804 /// \param HasDirectMove - does this subtarget have VSR <-> GPR direct moves? 7805 /// 7806 /// There are some patterns where it is beneficial to keep a BUILD_VECTOR 7807 /// node as a BUILD_VECTOR node rather than expanding it. The patterns where 7808 /// the opposite is true (expansion is beneficial) are: 7809 /// - The node builds a vector out of integers that are not 32 or 64-bits 7810 /// - The node builds a vector out of constants 7811 /// - The node is a "load-and-splat" 7812 /// In all other cases, we will choose to keep the BUILD_VECTOR. 7813 static bool haveEfficientBuildVectorPattern(BuildVectorSDNode *V, 7814 bool HasDirectMove, 7815 bool HasP8Vector) { 7816 EVT VecVT = V->getValueType(0); 7817 bool RightType = VecVT == MVT::v2f64 || 7818 (HasP8Vector && VecVT == MVT::v4f32) || 7819 (HasDirectMove && (VecVT == MVT::v2i64 || VecVT == MVT::v4i32)); 7820 if (!RightType) 7821 return false; 7822 7823 bool IsSplat = true; 7824 bool IsLoad = false; 7825 SDValue Op0 = V->getOperand(0); 7826 7827 // This function is called in a block that confirms the node is not a constant 7828 // splat. So a constant BUILD_VECTOR here means the vector is built out of 7829 // different constants. 7830 if (V->isConstant()) 7831 return false; 7832 for (int i = 0, e = V->getNumOperands(); i < e; ++i) { 7833 if (V->getOperand(i).isUndef()) 7834 return false; 7835 // We want to expand nodes that represent load-and-splat even if the 7836 // loaded value is a floating point truncation or conversion to int. 7837 if (V->getOperand(i).getOpcode() == ISD::LOAD || 7838 (V->getOperand(i).getOpcode() == ISD::FP_ROUND && 7839 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) || 7840 (V->getOperand(i).getOpcode() == ISD::FP_TO_SINT && 7841 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) || 7842 (V->getOperand(i).getOpcode() == ISD::FP_TO_UINT && 7843 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD)) 7844 IsLoad = true; 7845 // If the operands are different or the input is not a load and has more 7846 // uses than just this BV node, then it isn't a splat. 7847 if (V->getOperand(i) != Op0 || 7848 (!IsLoad && !V->isOnlyUserOf(V->getOperand(i).getNode()))) 7849 IsSplat = false; 7850 } 7851 return !(IsSplat && IsLoad); 7852 } 7853 7854 // Lower BITCAST(f128, (build_pair i64, i64)) to BUILD_FP128. 7855 SDValue PPCTargetLowering::LowerBITCAST(SDValue Op, SelectionDAG &DAG) const { 7856 7857 SDLoc dl(Op); 7858 SDValue Op0 = Op->getOperand(0); 7859 7860 if (!EnableQuadPrecision || 7861 (Op.getValueType() != MVT::f128 ) || 7862 (Op0.getOpcode() != ISD::BUILD_PAIR) || 7863 (Op0.getOperand(0).getValueType() != MVT::i64) || 7864 (Op0.getOperand(1).getValueType() != MVT::i64)) 7865 return SDValue(); 7866 7867 return DAG.getNode(PPCISD::BUILD_FP128, dl, MVT::f128, Op0.getOperand(0), 7868 Op0.getOperand(1)); 7869 } 7870 7871 // If this is a case we can't handle, return null and let the default 7872 // expansion code take care of it. If we CAN select this case, and if it 7873 // selects to a single instruction, return Op. Otherwise, if we can codegen 7874 // this case more efficiently than a constant pool load, lower it to the 7875 // sequence of ops that should be used. 7876 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op, 7877 SelectionDAG &DAG) const { 7878 SDLoc dl(Op); 7879 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode()); 7880 assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR"); 7881 7882 if (Subtarget.hasQPX() && Op.getValueType() == MVT::v4i1) { 7883 // We first build an i32 vector, load it into a QPX register, 7884 // then convert it to a floating-point vector and compare it 7885 // to a zero vector to get the boolean result. 7886 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 7887 int FrameIdx = MFI.CreateStackObject(16, 16, false); 7888 MachinePointerInfo PtrInfo = 7889 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 7890 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7891 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 7892 7893 assert(BVN->getNumOperands() == 4 && 7894 "BUILD_VECTOR for v4i1 does not have 4 operands"); 7895 7896 bool IsConst = true; 7897 for (unsigned i = 0; i < 4; ++i) { 7898 if (BVN->getOperand(i).isUndef()) continue; 7899 if (!isa<ConstantSDNode>(BVN->getOperand(i))) { 7900 IsConst = false; 7901 break; 7902 } 7903 } 7904 7905 if (IsConst) { 7906 Constant *One = 7907 ConstantFP::get(Type::getFloatTy(*DAG.getContext()), 1.0); 7908 Constant *NegOne = 7909 ConstantFP::get(Type::getFloatTy(*DAG.getContext()), -1.0); 7910 7911 Constant *CV[4]; 7912 for (unsigned i = 0; i < 4; ++i) { 7913 if (BVN->getOperand(i).isUndef()) 7914 CV[i] = UndefValue::get(Type::getFloatTy(*DAG.getContext())); 7915 else if (isNullConstant(BVN->getOperand(i))) 7916 CV[i] = NegOne; 7917 else 7918 CV[i] = One; 7919 } 7920 7921 Constant *CP = ConstantVector::get(CV); 7922 SDValue CPIdx = DAG.getConstantPool(CP, getPointerTy(DAG.getDataLayout()), 7923 16 /* alignment */); 7924 7925 SDValue Ops[] = {DAG.getEntryNode(), CPIdx}; 7926 SDVTList VTs = DAG.getVTList({MVT::v4i1, /*chain*/ MVT::Other}); 7927 return DAG.getMemIntrinsicNode( 7928 PPCISD::QVLFSb, dl, VTs, Ops, MVT::v4f32, 7929 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 7930 } 7931 7932 SmallVector<SDValue, 4> Stores; 7933 for (unsigned i = 0; i < 4; ++i) { 7934 if (BVN->getOperand(i).isUndef()) continue; 7935 7936 unsigned Offset = 4*i; 7937 SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType()); 7938 Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx); 7939 7940 unsigned StoreSize = BVN->getOperand(i).getValueType().getStoreSize(); 7941 if (StoreSize > 4) { 7942 Stores.push_back( 7943 DAG.getTruncStore(DAG.getEntryNode(), dl, BVN->getOperand(i), Idx, 7944 PtrInfo.getWithOffset(Offset), MVT::i32)); 7945 } else { 7946 SDValue StoreValue = BVN->getOperand(i); 7947 if (StoreSize < 4) 7948 StoreValue = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, StoreValue); 7949 7950 Stores.push_back(DAG.getStore(DAG.getEntryNode(), dl, StoreValue, Idx, 7951 PtrInfo.getWithOffset(Offset))); 7952 } 7953 } 7954 7955 SDValue StoreChain; 7956 if (!Stores.empty()) 7957 StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores); 7958 else 7959 StoreChain = DAG.getEntryNode(); 7960 7961 // Now load from v4i32 into the QPX register; this will extend it to 7962 // v4i64 but not yet convert it to a floating point. Nevertheless, this 7963 // is typed as v4f64 because the QPX register integer states are not 7964 // explicitly represented. 7965 7966 SDValue Ops[] = {StoreChain, 7967 DAG.getConstant(Intrinsic::ppc_qpx_qvlfiwz, dl, MVT::i32), 7968 FIdx}; 7969 SDVTList VTs = DAG.getVTList({MVT::v4f64, /*chain*/ MVT::Other}); 7970 7971 SDValue LoadedVect = DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, 7972 dl, VTs, Ops, MVT::v4i32, PtrInfo); 7973 LoadedVect = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64, 7974 DAG.getConstant(Intrinsic::ppc_qpx_qvfcfidu, dl, MVT::i32), 7975 LoadedVect); 7976 7977 SDValue FPZeros = DAG.getConstantFP(0.0, dl, MVT::v4f64); 7978 7979 return DAG.getSetCC(dl, MVT::v4i1, LoadedVect, FPZeros, ISD::SETEQ); 7980 } 7981 7982 // All other QPX vectors are handled by generic code. 7983 if (Subtarget.hasQPX()) 7984 return SDValue(); 7985 7986 // Check if this is a splat of a constant value. 7987 APInt APSplatBits, APSplatUndef; 7988 unsigned SplatBitSize; 7989 bool HasAnyUndefs; 7990 if (! BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize, 7991 HasAnyUndefs, 0, !Subtarget.isLittleEndian()) || 7992 SplatBitSize > 32) { 7993 // BUILD_VECTOR nodes that are not constant splats of up to 32-bits can be 7994 // lowered to VSX instructions under certain conditions. 7995 // Without VSX, there is no pattern more efficient than expanding the node. 7996 if (Subtarget.hasVSX() && 7997 haveEfficientBuildVectorPattern(BVN, Subtarget.hasDirectMove(), 7998 Subtarget.hasP8Vector())) 7999 return Op; 8000 return SDValue(); 8001 } 8002 8003 unsigned SplatBits = APSplatBits.getZExtValue(); 8004 unsigned SplatUndef = APSplatUndef.getZExtValue(); 8005 unsigned SplatSize = SplatBitSize / 8; 8006 8007 // First, handle single instruction cases. 8008 8009 // All zeros? 8010 if (SplatBits == 0) { 8011 // Canonicalize all zero vectors to be v4i32. 8012 if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) { 8013 SDValue Z = DAG.getConstant(0, dl, MVT::v4i32); 8014 Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z); 8015 } 8016 return Op; 8017 } 8018 8019 // We have XXSPLTIB for constant splats one byte wide 8020 if (Subtarget.hasP9Vector() && SplatSize == 1) { 8021 // This is a splat of 1-byte elements with some elements potentially undef. 8022 // Rather than trying to match undef in the SDAG patterns, ensure that all 8023 // elements are the same constant. 8024 if (HasAnyUndefs || ISD::isBuildVectorAllOnes(BVN)) { 8025 SmallVector<SDValue, 16> Ops(16, DAG.getConstant(SplatBits, 8026 dl, MVT::i32)); 8027 SDValue NewBV = DAG.getBuildVector(MVT::v16i8, dl, Ops); 8028 if (Op.getValueType() != MVT::v16i8) 8029 return DAG.getBitcast(Op.getValueType(), NewBV); 8030 return NewBV; 8031 } 8032 8033 // BuildVectorSDNode::isConstantSplat() is actually pretty smart. It'll 8034 // detect that constant splats like v8i16: 0xABAB are really just splats 8035 // of a 1-byte constant. In this case, we need to convert the node to a 8036 // splat of v16i8 and a bitcast. 8037 if (Op.getValueType() != MVT::v16i8) 8038 return DAG.getBitcast(Op.getValueType(), 8039 DAG.getConstant(SplatBits, dl, MVT::v16i8)); 8040 8041 return Op; 8042 } 8043 8044 // If the sign extended value is in the range [-16,15], use VSPLTI[bhw]. 8045 int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >> 8046 (32-SplatBitSize)); 8047 if (SextVal >= -16 && SextVal <= 15) 8048 return BuildSplatI(SextVal, SplatSize, Op.getValueType(), DAG, dl); 8049 8050 // Two instruction sequences. 8051 8052 // If this value is in the range [-32,30] and is even, use: 8053 // VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2) 8054 // If this value is in the range [17,31] and is odd, use: 8055 // VSPLTI[bhw](val-16) - VSPLTI[bhw](-16) 8056 // If this value is in the range [-31,-17] and is odd, use: 8057 // VSPLTI[bhw](val+16) + VSPLTI[bhw](-16) 8058 // Note the last two are three-instruction sequences. 8059 if (SextVal >= -32 && SextVal <= 31) { 8060 // To avoid having these optimizations undone by constant folding, 8061 // we convert to a pseudo that will be expanded later into one of 8062 // the above forms. 8063 SDValue Elt = DAG.getConstant(SextVal, dl, MVT::i32); 8064 EVT VT = (SplatSize == 1 ? MVT::v16i8 : 8065 (SplatSize == 2 ? MVT::v8i16 : MVT::v4i32)); 8066 SDValue EltSize = DAG.getConstant(SplatSize, dl, MVT::i32); 8067 SDValue RetVal = DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize); 8068 if (VT == Op.getValueType()) 8069 return RetVal; 8070 else 8071 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), RetVal); 8072 } 8073 8074 // If this is 0x8000_0000 x 4, turn into vspltisw + vslw. If it is 8075 // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000). This is important 8076 // for fneg/fabs. 8077 if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) { 8078 // Make -1 and vspltisw -1: 8079 SDValue OnesV = BuildSplatI(-1, 4, MVT::v4i32, DAG, dl); 8080 8081 // Make the VSLW intrinsic, computing 0x8000_0000. 8082 SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV, 8083 OnesV, DAG, dl); 8084 8085 // xor by OnesV to invert it. 8086 Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV); 8087 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 8088 } 8089 8090 // Check to see if this is a wide variety of vsplti*, binop self cases. 8091 static const signed char SplatCsts[] = { 8092 -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7, 8093 -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16 8094 }; 8095 8096 for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) { 8097 // Indirect through the SplatCsts array so that we favor 'vsplti -1' for 8098 // cases which are ambiguous (e.g. formation of 0x8000_0000). 'vsplti -1' 8099 int i = SplatCsts[idx]; 8100 8101 // Figure out what shift amount will be used by altivec if shifted by i in 8102 // this splat size. 8103 unsigned TypeShiftAmt = i & (SplatBitSize-1); 8104 8105 // vsplti + shl self. 8106 if (SextVal == (int)((unsigned)i << TypeShiftAmt)) { 8107 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl); 8108 static const unsigned IIDs[] = { // Intrinsic to use for each size. 8109 Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0, 8110 Intrinsic::ppc_altivec_vslw 8111 }; 8112 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 8113 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 8114 } 8115 8116 // vsplti + srl self. 8117 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) { 8118 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl); 8119 static const unsigned IIDs[] = { // Intrinsic to use for each size. 8120 Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0, 8121 Intrinsic::ppc_altivec_vsrw 8122 }; 8123 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 8124 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 8125 } 8126 8127 // vsplti + sra self. 8128 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) { 8129 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl); 8130 static const unsigned IIDs[] = { // Intrinsic to use for each size. 8131 Intrinsic::ppc_altivec_vsrab, Intrinsic::ppc_altivec_vsrah, 0, 8132 Intrinsic::ppc_altivec_vsraw 8133 }; 8134 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 8135 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 8136 } 8137 8138 // vsplti + rol self. 8139 if (SextVal == (int)(((unsigned)i << TypeShiftAmt) | 8140 ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) { 8141 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl); 8142 static const unsigned IIDs[] = { // Intrinsic to use for each size. 8143 Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0, 8144 Intrinsic::ppc_altivec_vrlw 8145 }; 8146 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 8147 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 8148 } 8149 8150 // t = vsplti c, result = vsldoi t, t, 1 8151 if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) { 8152 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl); 8153 unsigned Amt = Subtarget.isLittleEndian() ? 15 : 1; 8154 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl); 8155 } 8156 // t = vsplti c, result = vsldoi t, t, 2 8157 if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) { 8158 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl); 8159 unsigned Amt = Subtarget.isLittleEndian() ? 14 : 2; 8160 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl); 8161 } 8162 // t = vsplti c, result = vsldoi t, t, 3 8163 if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) { 8164 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl); 8165 unsigned Amt = Subtarget.isLittleEndian() ? 13 : 3; 8166 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl); 8167 } 8168 } 8169 8170 return SDValue(); 8171 } 8172 8173 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit 8174 /// the specified operations to build the shuffle. 8175 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS, 8176 SDValue RHS, SelectionDAG &DAG, 8177 const SDLoc &dl) { 8178 unsigned OpNum = (PFEntry >> 26) & 0x0F; 8179 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1); 8180 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1); 8181 8182 enum { 8183 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3> 8184 OP_VMRGHW, 8185 OP_VMRGLW, 8186 OP_VSPLTISW0, 8187 OP_VSPLTISW1, 8188 OP_VSPLTISW2, 8189 OP_VSPLTISW3, 8190 OP_VSLDOI4, 8191 OP_VSLDOI8, 8192 OP_VSLDOI12 8193 }; 8194 8195 if (OpNum == OP_COPY) { 8196 if (LHSID == (1*9+2)*9+3) return LHS; 8197 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!"); 8198 return RHS; 8199 } 8200 8201 SDValue OpLHS, OpRHS; 8202 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl); 8203 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl); 8204 8205 int ShufIdxs[16]; 8206 switch (OpNum) { 8207 default: llvm_unreachable("Unknown i32 permute!"); 8208 case OP_VMRGHW: 8209 ShufIdxs[ 0] = 0; ShufIdxs[ 1] = 1; ShufIdxs[ 2] = 2; ShufIdxs[ 3] = 3; 8210 ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19; 8211 ShufIdxs[ 8] = 4; ShufIdxs[ 9] = 5; ShufIdxs[10] = 6; ShufIdxs[11] = 7; 8212 ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23; 8213 break; 8214 case OP_VMRGLW: 8215 ShufIdxs[ 0] = 8; ShufIdxs[ 1] = 9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11; 8216 ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27; 8217 ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15; 8218 ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31; 8219 break; 8220 case OP_VSPLTISW0: 8221 for (unsigned i = 0; i != 16; ++i) 8222 ShufIdxs[i] = (i&3)+0; 8223 break; 8224 case OP_VSPLTISW1: 8225 for (unsigned i = 0; i != 16; ++i) 8226 ShufIdxs[i] = (i&3)+4; 8227 break; 8228 case OP_VSPLTISW2: 8229 for (unsigned i = 0; i != 16; ++i) 8230 ShufIdxs[i] = (i&3)+8; 8231 break; 8232 case OP_VSPLTISW3: 8233 for (unsigned i = 0; i != 16; ++i) 8234 ShufIdxs[i] = (i&3)+12; 8235 break; 8236 case OP_VSLDOI4: 8237 return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl); 8238 case OP_VSLDOI8: 8239 return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl); 8240 case OP_VSLDOI12: 8241 return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl); 8242 } 8243 EVT VT = OpLHS.getValueType(); 8244 OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS); 8245 OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS); 8246 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs); 8247 return DAG.getNode(ISD::BITCAST, dl, VT, T); 8248 } 8249 8250 /// lowerToVINSERTB - Return the SDValue if this VECTOR_SHUFFLE can be handled 8251 /// by the VINSERTB instruction introduced in ISA 3.0, else just return default 8252 /// SDValue. 8253 SDValue PPCTargetLowering::lowerToVINSERTB(ShuffleVectorSDNode *N, 8254 SelectionDAG &DAG) const { 8255 const unsigned BytesInVector = 16; 8256 bool IsLE = Subtarget.isLittleEndian(); 8257 SDLoc dl(N); 8258 SDValue V1 = N->getOperand(0); 8259 SDValue V2 = N->getOperand(1); 8260 unsigned ShiftElts = 0, InsertAtByte = 0; 8261 bool Swap = false; 8262 8263 // Shifts required to get the byte we want at element 7. 8264 unsigned LittleEndianShifts[] = {8, 7, 6, 5, 4, 3, 2, 1, 8265 0, 15, 14, 13, 12, 11, 10, 9}; 8266 unsigned BigEndianShifts[] = {9, 10, 11, 12, 13, 14, 15, 0, 8267 1, 2, 3, 4, 5, 6, 7, 8}; 8268 8269 ArrayRef<int> Mask = N->getMask(); 8270 int OriginalOrder[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}; 8271 8272 // For each mask element, find out if we're just inserting something 8273 // from V2 into V1 or vice versa. 8274 // Possible permutations inserting an element from V2 into V1: 8275 // X, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 8276 // 0, X, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 8277 // ... 8278 // 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, X 8279 // Inserting from V1 into V2 will be similar, except mask range will be 8280 // [16,31]. 8281 8282 bool FoundCandidate = false; 8283 // If both vector operands for the shuffle are the same vector, the mask 8284 // will contain only elements from the first one and the second one will be 8285 // undef. 8286 unsigned VINSERTBSrcElem = IsLE ? 8 : 7; 8287 // Go through the mask of half-words to find an element that's being moved 8288 // from one vector to the other. 8289 for (unsigned i = 0; i < BytesInVector; ++i) { 8290 unsigned CurrentElement = Mask[i]; 8291 // If 2nd operand is undefined, we should only look for element 7 in the 8292 // Mask. 8293 if (V2.isUndef() && CurrentElement != VINSERTBSrcElem) 8294 continue; 8295 8296 bool OtherElementsInOrder = true; 8297 // Examine the other elements in the Mask to see if they're in original 8298 // order. 8299 for (unsigned j = 0; j < BytesInVector; ++j) { 8300 if (j == i) 8301 continue; 8302 // If CurrentElement is from V1 [0,15], then we the rest of the Mask to be 8303 // from V2 [16,31] and vice versa. Unless the 2nd operand is undefined, 8304 // in which we always assume we're always picking from the 1st operand. 8305 int MaskOffset = 8306 (!V2.isUndef() && CurrentElement < BytesInVector) ? BytesInVector : 0; 8307 if (Mask[j] != OriginalOrder[j] + MaskOffset) { 8308 OtherElementsInOrder = false; 8309 break; 8310 } 8311 } 8312 // If other elements are in original order, we record the number of shifts 8313 // we need to get the element we want into element 7. Also record which byte 8314 // in the vector we should insert into. 8315 if (OtherElementsInOrder) { 8316 // If 2nd operand is undefined, we assume no shifts and no swapping. 8317 if (V2.isUndef()) { 8318 ShiftElts = 0; 8319 Swap = false; 8320 } else { 8321 // Only need the last 4-bits for shifts because operands will be swapped if CurrentElement is >= 2^4. 8322 ShiftElts = IsLE ? LittleEndianShifts[CurrentElement & 0xF] 8323 : BigEndianShifts[CurrentElement & 0xF]; 8324 Swap = CurrentElement < BytesInVector; 8325 } 8326 InsertAtByte = IsLE ? BytesInVector - (i + 1) : i; 8327 FoundCandidate = true; 8328 break; 8329 } 8330 } 8331 8332 if (!FoundCandidate) 8333 return SDValue(); 8334 8335 // Candidate found, construct the proper SDAG sequence with VINSERTB, 8336 // optionally with VECSHL if shift is required. 8337 if (Swap) 8338 std::swap(V1, V2); 8339 if (V2.isUndef()) 8340 V2 = V1; 8341 if (ShiftElts) { 8342 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2, 8343 DAG.getConstant(ShiftElts, dl, MVT::i32)); 8344 return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, Shl, 8345 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 8346 } 8347 return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, V2, 8348 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 8349 } 8350 8351 /// lowerToVINSERTH - Return the SDValue if this VECTOR_SHUFFLE can be handled 8352 /// by the VINSERTH instruction introduced in ISA 3.0, else just return default 8353 /// SDValue. 8354 SDValue PPCTargetLowering::lowerToVINSERTH(ShuffleVectorSDNode *N, 8355 SelectionDAG &DAG) const { 8356 const unsigned NumHalfWords = 8; 8357 const unsigned BytesInVector = NumHalfWords * 2; 8358 // Check that the shuffle is on half-words. 8359 if (!isNByteElemShuffleMask(N, 2, 1)) 8360 return SDValue(); 8361 8362 bool IsLE = Subtarget.isLittleEndian(); 8363 SDLoc dl(N); 8364 SDValue V1 = N->getOperand(0); 8365 SDValue V2 = N->getOperand(1); 8366 unsigned ShiftElts = 0, InsertAtByte = 0; 8367 bool Swap = false; 8368 8369 // Shifts required to get the half-word we want at element 3. 8370 unsigned LittleEndianShifts[] = {4, 3, 2, 1, 0, 7, 6, 5}; 8371 unsigned BigEndianShifts[] = {5, 6, 7, 0, 1, 2, 3, 4}; 8372 8373 uint32_t Mask = 0; 8374 uint32_t OriginalOrderLow = 0x1234567; 8375 uint32_t OriginalOrderHigh = 0x89ABCDEF; 8376 // Now we look at mask elements 0,2,4,6,8,10,12,14. Pack the mask into a 8377 // 32-bit space, only need 4-bit nibbles per element. 8378 for (unsigned i = 0; i < NumHalfWords; ++i) { 8379 unsigned MaskShift = (NumHalfWords - 1 - i) * 4; 8380 Mask |= ((uint32_t)(N->getMaskElt(i * 2) / 2) << MaskShift); 8381 } 8382 8383 // For each mask element, find out if we're just inserting something 8384 // from V2 into V1 or vice versa. Possible permutations inserting an element 8385 // from V2 into V1: 8386 // X, 1, 2, 3, 4, 5, 6, 7 8387 // 0, X, 2, 3, 4, 5, 6, 7 8388 // 0, 1, X, 3, 4, 5, 6, 7 8389 // 0, 1, 2, X, 4, 5, 6, 7 8390 // 0, 1, 2, 3, X, 5, 6, 7 8391 // 0, 1, 2, 3, 4, X, 6, 7 8392 // 0, 1, 2, 3, 4, 5, X, 7 8393 // 0, 1, 2, 3, 4, 5, 6, X 8394 // Inserting from V1 into V2 will be similar, except mask range will be [8,15]. 8395 8396 bool FoundCandidate = false; 8397 // Go through the mask of half-words to find an element that's being moved 8398 // from one vector to the other. 8399 for (unsigned i = 0; i < NumHalfWords; ++i) { 8400 unsigned MaskShift = (NumHalfWords - 1 - i) * 4; 8401 uint32_t MaskOneElt = (Mask >> MaskShift) & 0xF; 8402 uint32_t MaskOtherElts = ~(0xF << MaskShift); 8403 uint32_t TargetOrder = 0x0; 8404 8405 // If both vector operands for the shuffle are the same vector, the mask 8406 // will contain only elements from the first one and the second one will be 8407 // undef. 8408 if (V2.isUndef()) { 8409 ShiftElts = 0; 8410 unsigned VINSERTHSrcElem = IsLE ? 4 : 3; 8411 TargetOrder = OriginalOrderLow; 8412 Swap = false; 8413 // Skip if not the correct element or mask of other elements don't equal 8414 // to our expected order. 8415 if (MaskOneElt == VINSERTHSrcElem && 8416 (Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) { 8417 InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2; 8418 FoundCandidate = true; 8419 break; 8420 } 8421 } else { // If both operands are defined. 8422 // Target order is [8,15] if the current mask is between [0,7]. 8423 TargetOrder = 8424 (MaskOneElt < NumHalfWords) ? OriginalOrderHigh : OriginalOrderLow; 8425 // Skip if mask of other elements don't equal our expected order. 8426 if ((Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) { 8427 // We only need the last 3 bits for the number of shifts. 8428 ShiftElts = IsLE ? LittleEndianShifts[MaskOneElt & 0x7] 8429 : BigEndianShifts[MaskOneElt & 0x7]; 8430 InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2; 8431 Swap = MaskOneElt < NumHalfWords; 8432 FoundCandidate = true; 8433 break; 8434 } 8435 } 8436 } 8437 8438 if (!FoundCandidate) 8439 return SDValue(); 8440 8441 // Candidate found, construct the proper SDAG sequence with VINSERTH, 8442 // optionally with VECSHL if shift is required. 8443 if (Swap) 8444 std::swap(V1, V2); 8445 if (V2.isUndef()) 8446 V2 = V1; 8447 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1); 8448 if (ShiftElts) { 8449 // Double ShiftElts because we're left shifting on v16i8 type. 8450 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2, 8451 DAG.getConstant(2 * ShiftElts, dl, MVT::i32)); 8452 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, Shl); 8453 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2, 8454 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 8455 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 8456 } 8457 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2); 8458 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2, 8459 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 8460 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 8461 } 8462 8463 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE. If this 8464 /// is a shuffle we can handle in a single instruction, return it. Otherwise, 8465 /// return the code it can be lowered into. Worst case, it can always be 8466 /// lowered into a vperm. 8467 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, 8468 SelectionDAG &DAG) const { 8469 SDLoc dl(Op); 8470 SDValue V1 = Op.getOperand(0); 8471 SDValue V2 = Op.getOperand(1); 8472 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op); 8473 EVT VT = Op.getValueType(); 8474 bool isLittleEndian = Subtarget.isLittleEndian(); 8475 8476 unsigned ShiftElts, InsertAtByte; 8477 bool Swap = false; 8478 if (Subtarget.hasP9Vector() && 8479 PPC::isXXINSERTWMask(SVOp, ShiftElts, InsertAtByte, Swap, 8480 isLittleEndian)) { 8481 if (Swap) 8482 std::swap(V1, V2); 8483 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 8484 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2); 8485 if (ShiftElts) { 8486 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv2, Conv2, 8487 DAG.getConstant(ShiftElts, dl, MVT::i32)); 8488 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Shl, 8489 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 8490 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 8491 } 8492 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Conv2, 8493 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 8494 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 8495 } 8496 8497 if (Subtarget.hasP9Altivec()) { 8498 SDValue NewISDNode; 8499 if ((NewISDNode = lowerToVINSERTH(SVOp, DAG))) 8500 return NewISDNode; 8501 8502 if ((NewISDNode = lowerToVINSERTB(SVOp, DAG))) 8503 return NewISDNode; 8504 } 8505 8506 if (Subtarget.hasVSX() && 8507 PPC::isXXSLDWIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) { 8508 if (Swap) 8509 std::swap(V1, V2); 8510 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 8511 SDValue Conv2 = 8512 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2.isUndef() ? V1 : V2); 8513 8514 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv1, Conv2, 8515 DAG.getConstant(ShiftElts, dl, MVT::i32)); 8516 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Shl); 8517 } 8518 8519 if (Subtarget.hasVSX() && 8520 PPC::isXXPERMDIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) { 8521 if (Swap) 8522 std::swap(V1, V2); 8523 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1); 8524 SDValue Conv2 = 8525 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2.isUndef() ? V1 : V2); 8526 8527 SDValue PermDI = DAG.getNode(PPCISD::XXPERMDI, dl, MVT::v2i64, Conv1, Conv2, 8528 DAG.getConstant(ShiftElts, dl, MVT::i32)); 8529 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, PermDI); 8530 } 8531 8532 if (Subtarget.hasP9Vector()) { 8533 if (PPC::isXXBRHShuffleMask(SVOp)) { 8534 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1); 8535 SDValue ReveHWord = DAG.getNode(PPCISD::XXREVERSE, dl, MVT::v8i16, Conv); 8536 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveHWord); 8537 } else if (PPC::isXXBRWShuffleMask(SVOp)) { 8538 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 8539 SDValue ReveWord = DAG.getNode(PPCISD::XXREVERSE, dl, MVT::v4i32, Conv); 8540 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveWord); 8541 } else if (PPC::isXXBRDShuffleMask(SVOp)) { 8542 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1); 8543 SDValue ReveDWord = DAG.getNode(PPCISD::XXREVERSE, dl, MVT::v2i64, Conv); 8544 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveDWord); 8545 } else if (PPC::isXXBRQShuffleMask(SVOp)) { 8546 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, V1); 8547 SDValue ReveQWord = DAG.getNode(PPCISD::XXREVERSE, dl, MVT::v1i128, Conv); 8548 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveQWord); 8549 } 8550 } 8551 8552 if (Subtarget.hasVSX()) { 8553 if (V2.isUndef() && PPC::isSplatShuffleMask(SVOp, 4)) { 8554 int SplatIdx = PPC::getVSPLTImmediate(SVOp, 4, DAG); 8555 8556 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 8557 SDValue Splat = DAG.getNode(PPCISD::XXSPLT, dl, MVT::v4i32, Conv, 8558 DAG.getConstant(SplatIdx, dl, MVT::i32)); 8559 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Splat); 8560 } 8561 8562 // Left shifts of 8 bytes are actually swaps. Convert accordingly. 8563 if (V2.isUndef() && PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) == 8) { 8564 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1); 8565 SDValue Swap = DAG.getNode(PPCISD::SWAP_NO_CHAIN, dl, MVT::v2f64, Conv); 8566 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Swap); 8567 } 8568 } 8569 8570 if (Subtarget.hasQPX()) { 8571 if (VT.getVectorNumElements() != 4) 8572 return SDValue(); 8573 8574 if (V2.isUndef()) V2 = V1; 8575 8576 int AlignIdx = PPC::isQVALIGNIShuffleMask(SVOp); 8577 if (AlignIdx != -1) { 8578 return DAG.getNode(PPCISD::QVALIGNI, dl, VT, V1, V2, 8579 DAG.getConstant(AlignIdx, dl, MVT::i32)); 8580 } else if (SVOp->isSplat()) { 8581 int SplatIdx = SVOp->getSplatIndex(); 8582 if (SplatIdx >= 4) { 8583 std::swap(V1, V2); 8584 SplatIdx -= 4; 8585 } 8586 8587 return DAG.getNode(PPCISD::QVESPLATI, dl, VT, V1, 8588 DAG.getConstant(SplatIdx, dl, MVT::i32)); 8589 } 8590 8591 // Lower this into a qvgpci/qvfperm pair. 8592 8593 // Compute the qvgpci literal 8594 unsigned idx = 0; 8595 for (unsigned i = 0; i < 4; ++i) { 8596 int m = SVOp->getMaskElt(i); 8597 unsigned mm = m >= 0 ? (unsigned) m : i; 8598 idx |= mm << (3-i)*3; 8599 } 8600 8601 SDValue V3 = DAG.getNode(PPCISD::QVGPCI, dl, MVT::v4f64, 8602 DAG.getConstant(idx, dl, MVT::i32)); 8603 return DAG.getNode(PPCISD::QVFPERM, dl, VT, V1, V2, V3); 8604 } 8605 8606 // Cases that are handled by instructions that take permute immediates 8607 // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be 8608 // selected by the instruction selector. 8609 if (V2.isUndef()) { 8610 if (PPC::isSplatShuffleMask(SVOp, 1) || 8611 PPC::isSplatShuffleMask(SVOp, 2) || 8612 PPC::isSplatShuffleMask(SVOp, 4) || 8613 PPC::isVPKUWUMShuffleMask(SVOp, 1, DAG) || 8614 PPC::isVPKUHUMShuffleMask(SVOp, 1, DAG) || 8615 PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) != -1 || 8616 PPC::isVMRGLShuffleMask(SVOp, 1, 1, DAG) || 8617 PPC::isVMRGLShuffleMask(SVOp, 2, 1, DAG) || 8618 PPC::isVMRGLShuffleMask(SVOp, 4, 1, DAG) || 8619 PPC::isVMRGHShuffleMask(SVOp, 1, 1, DAG) || 8620 PPC::isVMRGHShuffleMask(SVOp, 2, 1, DAG) || 8621 PPC::isVMRGHShuffleMask(SVOp, 4, 1, DAG) || 8622 (Subtarget.hasP8Altivec() && ( 8623 PPC::isVPKUDUMShuffleMask(SVOp, 1, DAG) || 8624 PPC::isVMRGEOShuffleMask(SVOp, true, 1, DAG) || 8625 PPC::isVMRGEOShuffleMask(SVOp, false, 1, DAG)))) { 8626 return Op; 8627 } 8628 } 8629 8630 // Altivec has a variety of "shuffle immediates" that take two vector inputs 8631 // and produce a fixed permutation. If any of these match, do not lower to 8632 // VPERM. 8633 unsigned int ShuffleKind = isLittleEndian ? 2 : 0; 8634 if (PPC::isVPKUWUMShuffleMask(SVOp, ShuffleKind, DAG) || 8635 PPC::isVPKUHUMShuffleMask(SVOp, ShuffleKind, DAG) || 8636 PPC::isVSLDOIShuffleMask(SVOp, ShuffleKind, DAG) != -1 || 8637 PPC::isVMRGLShuffleMask(SVOp, 1, ShuffleKind, DAG) || 8638 PPC::isVMRGLShuffleMask(SVOp, 2, ShuffleKind, DAG) || 8639 PPC::isVMRGLShuffleMask(SVOp, 4, ShuffleKind, DAG) || 8640 PPC::isVMRGHShuffleMask(SVOp, 1, ShuffleKind, DAG) || 8641 PPC::isVMRGHShuffleMask(SVOp, 2, ShuffleKind, DAG) || 8642 PPC::isVMRGHShuffleMask(SVOp, 4, ShuffleKind, DAG) || 8643 (Subtarget.hasP8Altivec() && ( 8644 PPC::isVPKUDUMShuffleMask(SVOp, ShuffleKind, DAG) || 8645 PPC::isVMRGEOShuffleMask(SVOp, true, ShuffleKind, DAG) || 8646 PPC::isVMRGEOShuffleMask(SVOp, false, ShuffleKind, DAG)))) 8647 return Op; 8648 8649 // Check to see if this is a shuffle of 4-byte values. If so, we can use our 8650 // perfect shuffle table to emit an optimal matching sequence. 8651 ArrayRef<int> PermMask = SVOp->getMask(); 8652 8653 unsigned PFIndexes[4]; 8654 bool isFourElementShuffle = true; 8655 for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number 8656 unsigned EltNo = 8; // Start out undef. 8657 for (unsigned j = 0; j != 4; ++j) { // Intra-element byte. 8658 if (PermMask[i*4+j] < 0) 8659 continue; // Undef, ignore it. 8660 8661 unsigned ByteSource = PermMask[i*4+j]; 8662 if ((ByteSource & 3) != j) { 8663 isFourElementShuffle = false; 8664 break; 8665 } 8666 8667 if (EltNo == 8) { 8668 EltNo = ByteSource/4; 8669 } else if (EltNo != ByteSource/4) { 8670 isFourElementShuffle = false; 8671 break; 8672 } 8673 } 8674 PFIndexes[i] = EltNo; 8675 } 8676 8677 // If this shuffle can be expressed as a shuffle of 4-byte elements, use the 8678 // perfect shuffle vector to determine if it is cost effective to do this as 8679 // discrete instructions, or whether we should use a vperm. 8680 // For now, we skip this for little endian until such time as we have a 8681 // little-endian perfect shuffle table. 8682 if (isFourElementShuffle && !isLittleEndian) { 8683 // Compute the index in the perfect shuffle table. 8684 unsigned PFTableIndex = 8685 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3]; 8686 8687 unsigned PFEntry = PerfectShuffleTable[PFTableIndex]; 8688 unsigned Cost = (PFEntry >> 30); 8689 8690 // Determining when to avoid vperm is tricky. Many things affect the cost 8691 // of vperm, particularly how many times the perm mask needs to be computed. 8692 // For example, if the perm mask can be hoisted out of a loop or is already 8693 // used (perhaps because there are multiple permutes with the same shuffle 8694 // mask?) the vperm has a cost of 1. OTOH, hoisting the permute mask out of 8695 // the loop requires an extra register. 8696 // 8697 // As a compromise, we only emit discrete instructions if the shuffle can be 8698 // generated in 3 or fewer operations. When we have loop information 8699 // available, if this block is within a loop, we should avoid using vperm 8700 // for 3-operation perms and use a constant pool load instead. 8701 if (Cost < 3) 8702 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl); 8703 } 8704 8705 // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant 8706 // vector that will get spilled to the constant pool. 8707 if (V2.isUndef()) V2 = V1; 8708 8709 // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except 8710 // that it is in input element units, not in bytes. Convert now. 8711 8712 // For little endian, the order of the input vectors is reversed, and 8713 // the permutation mask is complemented with respect to 31. This is 8714 // necessary to produce proper semantics with the big-endian-biased vperm 8715 // instruction. 8716 EVT EltVT = V1.getValueType().getVectorElementType(); 8717 unsigned BytesPerElement = EltVT.getSizeInBits()/8; 8718 8719 SmallVector<SDValue, 16> ResultMask; 8720 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) { 8721 unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i]; 8722 8723 for (unsigned j = 0; j != BytesPerElement; ++j) 8724 if (isLittleEndian) 8725 ResultMask.push_back(DAG.getConstant(31 - (SrcElt*BytesPerElement + j), 8726 dl, MVT::i32)); 8727 else 8728 ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement + j, dl, 8729 MVT::i32)); 8730 } 8731 8732 SDValue VPermMask = DAG.getBuildVector(MVT::v16i8, dl, ResultMask); 8733 if (isLittleEndian) 8734 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(), 8735 V2, V1, VPermMask); 8736 else 8737 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(), 8738 V1, V2, VPermMask); 8739 } 8740 8741 /// getVectorCompareInfo - Given an intrinsic, return false if it is not a 8742 /// vector comparison. If it is, return true and fill in Opc/isDot with 8743 /// information about the intrinsic. 8744 static bool getVectorCompareInfo(SDValue Intrin, int &CompareOpc, 8745 bool &isDot, const PPCSubtarget &Subtarget) { 8746 unsigned IntrinsicID = 8747 cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue(); 8748 CompareOpc = -1; 8749 isDot = false; 8750 switch (IntrinsicID) { 8751 default: 8752 return false; 8753 // Comparison predicates. 8754 case Intrinsic::ppc_altivec_vcmpbfp_p: 8755 CompareOpc = 966; 8756 isDot = true; 8757 break; 8758 case Intrinsic::ppc_altivec_vcmpeqfp_p: 8759 CompareOpc = 198; 8760 isDot = true; 8761 break; 8762 case Intrinsic::ppc_altivec_vcmpequb_p: 8763 CompareOpc = 6; 8764 isDot = true; 8765 break; 8766 case Intrinsic::ppc_altivec_vcmpequh_p: 8767 CompareOpc = 70; 8768 isDot = true; 8769 break; 8770 case Intrinsic::ppc_altivec_vcmpequw_p: 8771 CompareOpc = 134; 8772 isDot = true; 8773 break; 8774 case Intrinsic::ppc_altivec_vcmpequd_p: 8775 if (Subtarget.hasP8Altivec()) { 8776 CompareOpc = 199; 8777 isDot = true; 8778 } else 8779 return false; 8780 break; 8781 case Intrinsic::ppc_altivec_vcmpneb_p: 8782 case Intrinsic::ppc_altivec_vcmpneh_p: 8783 case Intrinsic::ppc_altivec_vcmpnew_p: 8784 case Intrinsic::ppc_altivec_vcmpnezb_p: 8785 case Intrinsic::ppc_altivec_vcmpnezh_p: 8786 case Intrinsic::ppc_altivec_vcmpnezw_p: 8787 if (Subtarget.hasP9Altivec()) { 8788 switch (IntrinsicID) { 8789 default: 8790 llvm_unreachable("Unknown comparison intrinsic."); 8791 case Intrinsic::ppc_altivec_vcmpneb_p: 8792 CompareOpc = 7; 8793 break; 8794 case Intrinsic::ppc_altivec_vcmpneh_p: 8795 CompareOpc = 71; 8796 break; 8797 case Intrinsic::ppc_altivec_vcmpnew_p: 8798 CompareOpc = 135; 8799 break; 8800 case Intrinsic::ppc_altivec_vcmpnezb_p: 8801 CompareOpc = 263; 8802 break; 8803 case Intrinsic::ppc_altivec_vcmpnezh_p: 8804 CompareOpc = 327; 8805 break; 8806 case Intrinsic::ppc_altivec_vcmpnezw_p: 8807 CompareOpc = 391; 8808 break; 8809 } 8810 isDot = true; 8811 } else 8812 return false; 8813 break; 8814 case Intrinsic::ppc_altivec_vcmpgefp_p: 8815 CompareOpc = 454; 8816 isDot = true; 8817 break; 8818 case Intrinsic::ppc_altivec_vcmpgtfp_p: 8819 CompareOpc = 710; 8820 isDot = true; 8821 break; 8822 case Intrinsic::ppc_altivec_vcmpgtsb_p: 8823 CompareOpc = 774; 8824 isDot = true; 8825 break; 8826 case Intrinsic::ppc_altivec_vcmpgtsh_p: 8827 CompareOpc = 838; 8828 isDot = true; 8829 break; 8830 case Intrinsic::ppc_altivec_vcmpgtsw_p: 8831 CompareOpc = 902; 8832 isDot = true; 8833 break; 8834 case Intrinsic::ppc_altivec_vcmpgtsd_p: 8835 if (Subtarget.hasP8Altivec()) { 8836 CompareOpc = 967; 8837 isDot = true; 8838 } else 8839 return false; 8840 break; 8841 case Intrinsic::ppc_altivec_vcmpgtub_p: 8842 CompareOpc = 518; 8843 isDot = true; 8844 break; 8845 case Intrinsic::ppc_altivec_vcmpgtuh_p: 8846 CompareOpc = 582; 8847 isDot = true; 8848 break; 8849 case Intrinsic::ppc_altivec_vcmpgtuw_p: 8850 CompareOpc = 646; 8851 isDot = true; 8852 break; 8853 case Intrinsic::ppc_altivec_vcmpgtud_p: 8854 if (Subtarget.hasP8Altivec()) { 8855 CompareOpc = 711; 8856 isDot = true; 8857 } else 8858 return false; 8859 break; 8860 8861 // VSX predicate comparisons use the same infrastructure 8862 case Intrinsic::ppc_vsx_xvcmpeqdp_p: 8863 case Intrinsic::ppc_vsx_xvcmpgedp_p: 8864 case Intrinsic::ppc_vsx_xvcmpgtdp_p: 8865 case Intrinsic::ppc_vsx_xvcmpeqsp_p: 8866 case Intrinsic::ppc_vsx_xvcmpgesp_p: 8867 case Intrinsic::ppc_vsx_xvcmpgtsp_p: 8868 if (Subtarget.hasVSX()) { 8869 switch (IntrinsicID) { 8870 case Intrinsic::ppc_vsx_xvcmpeqdp_p: 8871 CompareOpc = 99; 8872 break; 8873 case Intrinsic::ppc_vsx_xvcmpgedp_p: 8874 CompareOpc = 115; 8875 break; 8876 case Intrinsic::ppc_vsx_xvcmpgtdp_p: 8877 CompareOpc = 107; 8878 break; 8879 case Intrinsic::ppc_vsx_xvcmpeqsp_p: 8880 CompareOpc = 67; 8881 break; 8882 case Intrinsic::ppc_vsx_xvcmpgesp_p: 8883 CompareOpc = 83; 8884 break; 8885 case Intrinsic::ppc_vsx_xvcmpgtsp_p: 8886 CompareOpc = 75; 8887 break; 8888 } 8889 isDot = true; 8890 } else 8891 return false; 8892 break; 8893 8894 // Normal Comparisons. 8895 case Intrinsic::ppc_altivec_vcmpbfp: 8896 CompareOpc = 966; 8897 break; 8898 case Intrinsic::ppc_altivec_vcmpeqfp: 8899 CompareOpc = 198; 8900 break; 8901 case Intrinsic::ppc_altivec_vcmpequb: 8902 CompareOpc = 6; 8903 break; 8904 case Intrinsic::ppc_altivec_vcmpequh: 8905 CompareOpc = 70; 8906 break; 8907 case Intrinsic::ppc_altivec_vcmpequw: 8908 CompareOpc = 134; 8909 break; 8910 case Intrinsic::ppc_altivec_vcmpequd: 8911 if (Subtarget.hasP8Altivec()) 8912 CompareOpc = 199; 8913 else 8914 return false; 8915 break; 8916 case Intrinsic::ppc_altivec_vcmpneb: 8917 case Intrinsic::ppc_altivec_vcmpneh: 8918 case Intrinsic::ppc_altivec_vcmpnew: 8919 case Intrinsic::ppc_altivec_vcmpnezb: 8920 case Intrinsic::ppc_altivec_vcmpnezh: 8921 case Intrinsic::ppc_altivec_vcmpnezw: 8922 if (Subtarget.hasP9Altivec()) 8923 switch (IntrinsicID) { 8924 default: 8925 llvm_unreachable("Unknown comparison intrinsic."); 8926 case Intrinsic::ppc_altivec_vcmpneb: 8927 CompareOpc = 7; 8928 break; 8929 case Intrinsic::ppc_altivec_vcmpneh: 8930 CompareOpc = 71; 8931 break; 8932 case Intrinsic::ppc_altivec_vcmpnew: 8933 CompareOpc = 135; 8934 break; 8935 case Intrinsic::ppc_altivec_vcmpnezb: 8936 CompareOpc = 263; 8937 break; 8938 case Intrinsic::ppc_altivec_vcmpnezh: 8939 CompareOpc = 327; 8940 break; 8941 case Intrinsic::ppc_altivec_vcmpnezw: 8942 CompareOpc = 391; 8943 break; 8944 } 8945 else 8946 return false; 8947 break; 8948 case Intrinsic::ppc_altivec_vcmpgefp: 8949 CompareOpc = 454; 8950 break; 8951 case Intrinsic::ppc_altivec_vcmpgtfp: 8952 CompareOpc = 710; 8953 break; 8954 case Intrinsic::ppc_altivec_vcmpgtsb: 8955 CompareOpc = 774; 8956 break; 8957 case Intrinsic::ppc_altivec_vcmpgtsh: 8958 CompareOpc = 838; 8959 break; 8960 case Intrinsic::ppc_altivec_vcmpgtsw: 8961 CompareOpc = 902; 8962 break; 8963 case Intrinsic::ppc_altivec_vcmpgtsd: 8964 if (Subtarget.hasP8Altivec()) 8965 CompareOpc = 967; 8966 else 8967 return false; 8968 break; 8969 case Intrinsic::ppc_altivec_vcmpgtub: 8970 CompareOpc = 518; 8971 break; 8972 case Intrinsic::ppc_altivec_vcmpgtuh: 8973 CompareOpc = 582; 8974 break; 8975 case Intrinsic::ppc_altivec_vcmpgtuw: 8976 CompareOpc = 646; 8977 break; 8978 case Intrinsic::ppc_altivec_vcmpgtud: 8979 if (Subtarget.hasP8Altivec()) 8980 CompareOpc = 711; 8981 else 8982 return false; 8983 break; 8984 } 8985 return true; 8986 } 8987 8988 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom 8989 /// lower, do it, otherwise return null. 8990 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 8991 SelectionDAG &DAG) const { 8992 unsigned IntrinsicID = 8993 cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 8994 8995 SDLoc dl(Op); 8996 8997 if (IntrinsicID == Intrinsic::thread_pointer) { 8998 // Reads the thread pointer register, used for __builtin_thread_pointer. 8999 if (Subtarget.isPPC64()) 9000 return DAG.getRegister(PPC::X13, MVT::i64); 9001 return DAG.getRegister(PPC::R2, MVT::i32); 9002 } 9003 9004 // We are looking for absolute values here. 9005 // The idea is to try to fit one of two patterns: 9006 // max (a, (0-a)) OR max ((0-a), a) 9007 if (Subtarget.hasP9Vector() && 9008 (IntrinsicID == Intrinsic::ppc_altivec_vmaxsw || 9009 IntrinsicID == Intrinsic::ppc_altivec_vmaxsh || 9010 IntrinsicID == Intrinsic::ppc_altivec_vmaxsb)) { 9011 SDValue V1 = Op.getOperand(1); 9012 SDValue V2 = Op.getOperand(2); 9013 if (V1.getSimpleValueType() == V2.getSimpleValueType() && 9014 (V1.getSimpleValueType() == MVT::v4i32 || 9015 V1.getSimpleValueType() == MVT::v8i16 || 9016 V1.getSimpleValueType() == MVT::v16i8)) { 9017 if ( V1.getOpcode() == ISD::SUB && 9018 ISD::isBuildVectorAllZeros(V1.getOperand(0).getNode()) && 9019 V1.getOperand(1) == V2 ) { 9020 // Generate the abs instruction with the operands 9021 return DAG.getNode(ISD::ABS, dl, V2.getValueType(),V2); 9022 } 9023 9024 if ( V2.getOpcode() == ISD::SUB && 9025 ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()) && 9026 V2.getOperand(1) == V1 ) { 9027 // Generate the abs instruction with the operands 9028 return DAG.getNode(ISD::ABS, dl, V1.getValueType(),V1); 9029 } 9030 } 9031 } 9032 9033 // If this is a lowered altivec predicate compare, CompareOpc is set to the 9034 // opcode number of the comparison. 9035 int CompareOpc; 9036 bool isDot; 9037 if (!getVectorCompareInfo(Op, CompareOpc, isDot, Subtarget)) 9038 return SDValue(); // Don't custom lower most intrinsics. 9039 9040 // If this is a non-dot comparison, make the VCMP node and we are done. 9041 if (!isDot) { 9042 SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(), 9043 Op.getOperand(1), Op.getOperand(2), 9044 DAG.getConstant(CompareOpc, dl, MVT::i32)); 9045 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp); 9046 } 9047 9048 // Create the PPCISD altivec 'dot' comparison node. 9049 SDValue Ops[] = { 9050 Op.getOperand(2), // LHS 9051 Op.getOperand(3), // RHS 9052 DAG.getConstant(CompareOpc, dl, MVT::i32) 9053 }; 9054 EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue }; 9055 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops); 9056 9057 // Now that we have the comparison, emit a copy from the CR to a GPR. 9058 // This is flagged to the above dot comparison. 9059 SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32, 9060 DAG.getRegister(PPC::CR6, MVT::i32), 9061 CompNode.getValue(1)); 9062 9063 // Unpack the result based on how the target uses it. 9064 unsigned BitNo; // Bit # of CR6. 9065 bool InvertBit; // Invert result? 9066 switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) { 9067 default: // Can't happen, don't crash on invalid number though. 9068 case 0: // Return the value of the EQ bit of CR6. 9069 BitNo = 0; InvertBit = false; 9070 break; 9071 case 1: // Return the inverted value of the EQ bit of CR6. 9072 BitNo = 0; InvertBit = true; 9073 break; 9074 case 2: // Return the value of the LT bit of CR6. 9075 BitNo = 2; InvertBit = false; 9076 break; 9077 case 3: // Return the inverted value of the LT bit of CR6. 9078 BitNo = 2; InvertBit = true; 9079 break; 9080 } 9081 9082 // Shift the bit into the low position. 9083 Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags, 9084 DAG.getConstant(8 - (3 - BitNo), dl, MVT::i32)); 9085 // Isolate the bit. 9086 Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags, 9087 DAG.getConstant(1, dl, MVT::i32)); 9088 9089 // If we are supposed to, toggle the bit. 9090 if (InvertBit) 9091 Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags, 9092 DAG.getConstant(1, dl, MVT::i32)); 9093 return Flags; 9094 } 9095 9096 SDValue PPCTargetLowering::LowerINTRINSIC_VOID(SDValue Op, 9097 SelectionDAG &DAG) const { 9098 // SelectionDAGBuilder::visitTargetIntrinsic may insert one extra chain to 9099 // the beginning of the argument list. 9100 int ArgStart = isa<ConstantSDNode>(Op.getOperand(0)) ? 0 : 1; 9101 SDLoc DL(Op); 9102 switch (cast<ConstantSDNode>(Op.getOperand(ArgStart))->getZExtValue()) { 9103 case Intrinsic::ppc_cfence: { 9104 assert(ArgStart == 1 && "llvm.ppc.cfence must carry a chain argument."); 9105 assert(Subtarget.isPPC64() && "Only 64-bit is supported for now."); 9106 return SDValue(DAG.getMachineNode(PPC::CFENCE8, DL, MVT::Other, 9107 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, 9108 Op.getOperand(ArgStart + 1)), 9109 Op.getOperand(0)), 9110 0); 9111 } 9112 default: 9113 break; 9114 } 9115 return SDValue(); 9116 } 9117 9118 SDValue PPCTargetLowering::LowerREM(SDValue Op, SelectionDAG &DAG) const { 9119 // Check for a DIV with the same operands as this REM. 9120 for (auto UI : Op.getOperand(1)->uses()) { 9121 if ((Op.getOpcode() == ISD::SREM && UI->getOpcode() == ISD::SDIV) || 9122 (Op.getOpcode() == ISD::UREM && UI->getOpcode() == ISD::UDIV)) 9123 if (UI->getOperand(0) == Op.getOperand(0) && 9124 UI->getOperand(1) == Op.getOperand(1)) 9125 return SDValue(); 9126 } 9127 return Op; 9128 } 9129 9130 // Lower scalar BSWAP64 to xxbrd. 9131 SDValue PPCTargetLowering::LowerBSWAP(SDValue Op, SelectionDAG &DAG) const { 9132 SDLoc dl(Op); 9133 // MTVSRDD 9134 Op = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i64, Op.getOperand(0), 9135 Op.getOperand(0)); 9136 // XXBRD 9137 Op = DAG.getNode(PPCISD::XXREVERSE, dl, MVT::v2i64, Op); 9138 // MFVSRD 9139 int VectorIndex = 0; 9140 if (Subtarget.isLittleEndian()) 9141 VectorIndex = 1; 9142 Op = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Op, 9143 DAG.getTargetConstant(VectorIndex, dl, MVT::i32)); 9144 return Op; 9145 } 9146 9147 // ATOMIC_CMP_SWAP for i8/i16 needs to zero-extend its input since it will be 9148 // compared to a value that is atomically loaded (atomic loads zero-extend). 9149 SDValue PPCTargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, 9150 SelectionDAG &DAG) const { 9151 assert(Op.getOpcode() == ISD::ATOMIC_CMP_SWAP && 9152 "Expecting an atomic compare-and-swap here."); 9153 SDLoc dl(Op); 9154 auto *AtomicNode = cast<AtomicSDNode>(Op.getNode()); 9155 EVT MemVT = AtomicNode->getMemoryVT(); 9156 if (MemVT.getSizeInBits() >= 32) 9157 return Op; 9158 9159 SDValue CmpOp = Op.getOperand(2); 9160 // If this is already correctly zero-extended, leave it alone. 9161 auto HighBits = APInt::getHighBitsSet(32, 32 - MemVT.getSizeInBits()); 9162 if (DAG.MaskedValueIsZero(CmpOp, HighBits)) 9163 return Op; 9164 9165 // Clear the high bits of the compare operand. 9166 unsigned MaskVal = (1 << MemVT.getSizeInBits()) - 1; 9167 SDValue NewCmpOp = 9168 DAG.getNode(ISD::AND, dl, MVT::i32, CmpOp, 9169 DAG.getConstant(MaskVal, dl, MVT::i32)); 9170 9171 // Replace the existing compare operand with the properly zero-extended one. 9172 SmallVector<SDValue, 4> Ops; 9173 for (int i = 0, e = AtomicNode->getNumOperands(); i < e; i++) 9174 Ops.push_back(AtomicNode->getOperand(i)); 9175 Ops[2] = NewCmpOp; 9176 MachineMemOperand *MMO = AtomicNode->getMemOperand(); 9177 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::Other); 9178 auto NodeTy = 9179 (MemVT == MVT::i8) ? PPCISD::ATOMIC_CMP_SWAP_8 : PPCISD::ATOMIC_CMP_SWAP_16; 9180 return DAG.getMemIntrinsicNode(NodeTy, dl, Tys, Ops, MemVT, MMO); 9181 } 9182 9183 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, 9184 SelectionDAG &DAG) const { 9185 SDLoc dl(Op); 9186 // Create a stack slot that is 16-byte aligned. 9187 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 9188 int FrameIdx = MFI.CreateStackObject(16, 16, false); 9189 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 9190 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 9191 9192 // Store the input value into Value#0 of the stack slot. 9193 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx, 9194 MachinePointerInfo()); 9195 // Load it out. 9196 return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo()); 9197 } 9198 9199 SDValue PPCTargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, 9200 SelectionDAG &DAG) const { 9201 assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && 9202 "Should only be called for ISD::INSERT_VECTOR_ELT"); 9203 9204 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(2)); 9205 // We have legal lowering for constant indices but not for variable ones. 9206 if (!C) 9207 return SDValue(); 9208 9209 EVT VT = Op.getValueType(); 9210 SDLoc dl(Op); 9211 SDValue V1 = Op.getOperand(0); 9212 SDValue V2 = Op.getOperand(1); 9213 // We can use MTVSRZ + VECINSERT for v8i16 and v16i8 types. 9214 if (VT == MVT::v8i16 || VT == MVT::v16i8) { 9215 SDValue Mtvsrz = DAG.getNode(PPCISD::MTVSRZ, dl, VT, V2); 9216 unsigned BytesInEachElement = VT.getVectorElementType().getSizeInBits() / 8; 9217 unsigned InsertAtElement = C->getZExtValue(); 9218 unsigned InsertAtByte = InsertAtElement * BytesInEachElement; 9219 if (Subtarget.isLittleEndian()) { 9220 InsertAtByte = (16 - BytesInEachElement) - InsertAtByte; 9221 } 9222 return DAG.getNode(PPCISD::VECINSERT, dl, VT, V1, Mtvsrz, 9223 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9224 } 9225 return Op; 9226 } 9227 9228 SDValue PPCTargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op, 9229 SelectionDAG &DAG) const { 9230 SDLoc dl(Op); 9231 SDNode *N = Op.getNode(); 9232 9233 assert(N->getOperand(0).getValueType() == MVT::v4i1 && 9234 "Unknown extract_vector_elt type"); 9235 9236 SDValue Value = N->getOperand(0); 9237 9238 // The first part of this is like the store lowering except that we don't 9239 // need to track the chain. 9240 9241 // The values are now known to be -1 (false) or 1 (true). To convert this 9242 // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5). 9243 // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5 9244 Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value); 9245 9246 // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to 9247 // understand how to form the extending load. 9248 SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64); 9249 9250 Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs); 9251 9252 // Now convert to an integer and store. 9253 Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64, 9254 DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32), 9255 Value); 9256 9257 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 9258 int FrameIdx = MFI.CreateStackObject(16, 16, false); 9259 MachinePointerInfo PtrInfo = 9260 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 9261 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 9262 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 9263 9264 SDValue StoreChain = DAG.getEntryNode(); 9265 SDValue Ops[] = {StoreChain, 9266 DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32), 9267 Value, FIdx}; 9268 SDVTList VTs = DAG.getVTList(/*chain*/ MVT::Other); 9269 9270 StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, 9271 dl, VTs, Ops, MVT::v4i32, PtrInfo); 9272 9273 // Extract the value requested. 9274 unsigned Offset = 4*cast<ConstantSDNode>(N->getOperand(1))->getZExtValue(); 9275 SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType()); 9276 Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx); 9277 9278 SDValue IntVal = 9279 DAG.getLoad(MVT::i32, dl, StoreChain, Idx, PtrInfo.getWithOffset(Offset)); 9280 9281 if (!Subtarget.useCRBits()) 9282 return IntVal; 9283 9284 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, IntVal); 9285 } 9286 9287 /// Lowering for QPX v4i1 loads 9288 SDValue PPCTargetLowering::LowerVectorLoad(SDValue Op, 9289 SelectionDAG &DAG) const { 9290 SDLoc dl(Op); 9291 LoadSDNode *LN = cast<LoadSDNode>(Op.getNode()); 9292 SDValue LoadChain = LN->getChain(); 9293 SDValue BasePtr = LN->getBasePtr(); 9294 9295 if (Op.getValueType() == MVT::v4f64 || 9296 Op.getValueType() == MVT::v4f32) { 9297 EVT MemVT = LN->getMemoryVT(); 9298 unsigned Alignment = LN->getAlignment(); 9299 9300 // If this load is properly aligned, then it is legal. 9301 if (Alignment >= MemVT.getStoreSize()) 9302 return Op; 9303 9304 EVT ScalarVT = Op.getValueType().getScalarType(), 9305 ScalarMemVT = MemVT.getScalarType(); 9306 unsigned Stride = ScalarMemVT.getStoreSize(); 9307 9308 SDValue Vals[4], LoadChains[4]; 9309 for (unsigned Idx = 0; Idx < 4; ++Idx) { 9310 SDValue Load; 9311 if (ScalarVT != ScalarMemVT) 9312 Load = DAG.getExtLoad(LN->getExtensionType(), dl, ScalarVT, LoadChain, 9313 BasePtr, 9314 LN->getPointerInfo().getWithOffset(Idx * Stride), 9315 ScalarMemVT, MinAlign(Alignment, Idx * Stride), 9316 LN->getMemOperand()->getFlags(), LN->getAAInfo()); 9317 else 9318 Load = DAG.getLoad(ScalarVT, dl, LoadChain, BasePtr, 9319 LN->getPointerInfo().getWithOffset(Idx * Stride), 9320 MinAlign(Alignment, Idx * Stride), 9321 LN->getMemOperand()->getFlags(), LN->getAAInfo()); 9322 9323 if (Idx == 0 && LN->isIndexed()) { 9324 assert(LN->getAddressingMode() == ISD::PRE_INC && 9325 "Unknown addressing mode on vector load"); 9326 Load = DAG.getIndexedLoad(Load, dl, BasePtr, LN->getOffset(), 9327 LN->getAddressingMode()); 9328 } 9329 9330 Vals[Idx] = Load; 9331 LoadChains[Idx] = Load.getValue(1); 9332 9333 BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, 9334 DAG.getConstant(Stride, dl, 9335 BasePtr.getValueType())); 9336 } 9337 9338 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains); 9339 SDValue Value = DAG.getBuildVector(Op.getValueType(), dl, Vals); 9340 9341 if (LN->isIndexed()) { 9342 SDValue RetOps[] = { Value, Vals[0].getValue(1), TF }; 9343 return DAG.getMergeValues(RetOps, dl); 9344 } 9345 9346 SDValue RetOps[] = { Value, TF }; 9347 return DAG.getMergeValues(RetOps, dl); 9348 } 9349 9350 assert(Op.getValueType() == MVT::v4i1 && "Unknown load to lower"); 9351 assert(LN->isUnindexed() && "Indexed v4i1 loads are not supported"); 9352 9353 // To lower v4i1 from a byte array, we load the byte elements of the 9354 // vector and then reuse the BUILD_VECTOR logic. 9355 9356 SDValue VectElmts[4], VectElmtChains[4]; 9357 for (unsigned i = 0; i < 4; ++i) { 9358 SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType()); 9359 Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx); 9360 9361 VectElmts[i] = DAG.getExtLoad( 9362 ISD::EXTLOAD, dl, MVT::i32, LoadChain, Idx, 9363 LN->getPointerInfo().getWithOffset(i), MVT::i8, 9364 /* Alignment = */ 1, LN->getMemOperand()->getFlags(), LN->getAAInfo()); 9365 VectElmtChains[i] = VectElmts[i].getValue(1); 9366 } 9367 9368 LoadChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, VectElmtChains); 9369 SDValue Value = DAG.getBuildVector(MVT::v4i1, dl, VectElmts); 9370 9371 SDValue RVals[] = { Value, LoadChain }; 9372 return DAG.getMergeValues(RVals, dl); 9373 } 9374 9375 /// Lowering for QPX v4i1 stores 9376 SDValue PPCTargetLowering::LowerVectorStore(SDValue Op, 9377 SelectionDAG &DAG) const { 9378 SDLoc dl(Op); 9379 StoreSDNode *SN = cast<StoreSDNode>(Op.getNode()); 9380 SDValue StoreChain = SN->getChain(); 9381 SDValue BasePtr = SN->getBasePtr(); 9382 SDValue Value = SN->getValue(); 9383 9384 if (Value.getValueType() == MVT::v4f64 || 9385 Value.getValueType() == MVT::v4f32) { 9386 EVT MemVT = SN->getMemoryVT(); 9387 unsigned Alignment = SN->getAlignment(); 9388 9389 // If this store is properly aligned, then it is legal. 9390 if (Alignment >= MemVT.getStoreSize()) 9391 return Op; 9392 9393 EVT ScalarVT = Value.getValueType().getScalarType(), 9394 ScalarMemVT = MemVT.getScalarType(); 9395 unsigned Stride = ScalarMemVT.getStoreSize(); 9396 9397 SDValue Stores[4]; 9398 for (unsigned Idx = 0; Idx < 4; ++Idx) { 9399 SDValue Ex = DAG.getNode( 9400 ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, Value, 9401 DAG.getConstant(Idx, dl, getVectorIdxTy(DAG.getDataLayout()))); 9402 SDValue Store; 9403 if (ScalarVT != ScalarMemVT) 9404 Store = 9405 DAG.getTruncStore(StoreChain, dl, Ex, BasePtr, 9406 SN->getPointerInfo().getWithOffset(Idx * Stride), 9407 ScalarMemVT, MinAlign(Alignment, Idx * Stride), 9408 SN->getMemOperand()->getFlags(), SN->getAAInfo()); 9409 else 9410 Store = DAG.getStore(StoreChain, dl, Ex, BasePtr, 9411 SN->getPointerInfo().getWithOffset(Idx * Stride), 9412 MinAlign(Alignment, Idx * Stride), 9413 SN->getMemOperand()->getFlags(), SN->getAAInfo()); 9414 9415 if (Idx == 0 && SN->isIndexed()) { 9416 assert(SN->getAddressingMode() == ISD::PRE_INC && 9417 "Unknown addressing mode on vector store"); 9418 Store = DAG.getIndexedStore(Store, dl, BasePtr, SN->getOffset(), 9419 SN->getAddressingMode()); 9420 } 9421 9422 BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, 9423 DAG.getConstant(Stride, dl, 9424 BasePtr.getValueType())); 9425 Stores[Idx] = Store; 9426 } 9427 9428 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores); 9429 9430 if (SN->isIndexed()) { 9431 SDValue RetOps[] = { TF, Stores[0].getValue(1) }; 9432 return DAG.getMergeValues(RetOps, dl); 9433 } 9434 9435 return TF; 9436 } 9437 9438 assert(SN->isUnindexed() && "Indexed v4i1 stores are not supported"); 9439 assert(Value.getValueType() == MVT::v4i1 && "Unknown store to lower"); 9440 9441 // The values are now known to be -1 (false) or 1 (true). To convert this 9442 // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5). 9443 // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5 9444 Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value); 9445 9446 // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to 9447 // understand how to form the extending load. 9448 SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64); 9449 9450 Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs); 9451 9452 // Now convert to an integer and store. 9453 Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64, 9454 DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32), 9455 Value); 9456 9457 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 9458 int FrameIdx = MFI.CreateStackObject(16, 16, false); 9459 MachinePointerInfo PtrInfo = 9460 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 9461 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 9462 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 9463 9464 SDValue Ops[] = {StoreChain, 9465 DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32), 9466 Value, FIdx}; 9467 SDVTList VTs = DAG.getVTList(/*chain*/ MVT::Other); 9468 9469 StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, 9470 dl, VTs, Ops, MVT::v4i32, PtrInfo); 9471 9472 // Move data into the byte array. 9473 SDValue Loads[4], LoadChains[4]; 9474 for (unsigned i = 0; i < 4; ++i) { 9475 unsigned Offset = 4*i; 9476 SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType()); 9477 Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx); 9478 9479 Loads[i] = DAG.getLoad(MVT::i32, dl, StoreChain, Idx, 9480 PtrInfo.getWithOffset(Offset)); 9481 LoadChains[i] = Loads[i].getValue(1); 9482 } 9483 9484 StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains); 9485 9486 SDValue Stores[4]; 9487 for (unsigned i = 0; i < 4; ++i) { 9488 SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType()); 9489 Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx); 9490 9491 Stores[i] = DAG.getTruncStore( 9492 StoreChain, dl, Loads[i], Idx, SN->getPointerInfo().getWithOffset(i), 9493 MVT::i8, /* Alignment = */ 1, SN->getMemOperand()->getFlags(), 9494 SN->getAAInfo()); 9495 } 9496 9497 StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores); 9498 9499 return StoreChain; 9500 } 9501 9502 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const { 9503 SDLoc dl(Op); 9504 if (Op.getValueType() == MVT::v4i32) { 9505 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 9506 9507 SDValue Zero = BuildSplatI( 0, 1, MVT::v4i32, DAG, dl); 9508 SDValue Neg16 = BuildSplatI(-16, 4, MVT::v4i32, DAG, dl);//+16 as shift amt. 9509 9510 SDValue RHSSwap = // = vrlw RHS, 16 9511 BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl); 9512 9513 // Shrinkify inputs to v8i16. 9514 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS); 9515 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS); 9516 RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap); 9517 9518 // Low parts multiplied together, generating 32-bit results (we ignore the 9519 // top parts). 9520 SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh, 9521 LHS, RHS, DAG, dl, MVT::v4i32); 9522 9523 SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm, 9524 LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32); 9525 // Shift the high parts up 16 bits. 9526 HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd, 9527 Neg16, DAG, dl); 9528 return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd); 9529 } else if (Op.getValueType() == MVT::v8i16) { 9530 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 9531 9532 SDValue Zero = BuildSplatI(0, 1, MVT::v8i16, DAG, dl); 9533 9534 return BuildIntrinsicOp(Intrinsic::ppc_altivec_vmladduhm, 9535 LHS, RHS, Zero, DAG, dl); 9536 } else if (Op.getValueType() == MVT::v16i8) { 9537 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 9538 bool isLittleEndian = Subtarget.isLittleEndian(); 9539 9540 // Multiply the even 8-bit parts, producing 16-bit sums. 9541 SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub, 9542 LHS, RHS, DAG, dl, MVT::v8i16); 9543 EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts); 9544 9545 // Multiply the odd 8-bit parts, producing 16-bit sums. 9546 SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub, 9547 LHS, RHS, DAG, dl, MVT::v8i16); 9548 OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts); 9549 9550 // Merge the results together. Because vmuleub and vmuloub are 9551 // instructions with a big-endian bias, we must reverse the 9552 // element numbering and reverse the meaning of "odd" and "even" 9553 // when generating little endian code. 9554 int Ops[16]; 9555 for (unsigned i = 0; i != 8; ++i) { 9556 if (isLittleEndian) { 9557 Ops[i*2 ] = 2*i; 9558 Ops[i*2+1] = 2*i+16; 9559 } else { 9560 Ops[i*2 ] = 2*i+1; 9561 Ops[i*2+1] = 2*i+1+16; 9562 } 9563 } 9564 if (isLittleEndian) 9565 return DAG.getVectorShuffle(MVT::v16i8, dl, OddParts, EvenParts, Ops); 9566 else 9567 return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops); 9568 } else { 9569 llvm_unreachable("Unknown mul to lower!"); 9570 } 9571 } 9572 9573 /// LowerOperation - Provide custom lowering hooks for some operations. 9574 /// 9575 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 9576 switch (Op.getOpcode()) { 9577 default: llvm_unreachable("Wasn't expecting to be able to lower this!"); 9578 case ISD::ConstantPool: return LowerConstantPool(Op, DAG); 9579 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG); 9580 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG); 9581 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG); 9582 case ISD::JumpTable: return LowerJumpTable(Op, DAG); 9583 case ISD::SETCC: return LowerSETCC(Op, DAG); 9584 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG); 9585 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG); 9586 9587 // Variable argument lowering. 9588 case ISD::VASTART: return LowerVASTART(Op, DAG); 9589 case ISD::VAARG: return LowerVAARG(Op, DAG); 9590 case ISD::VACOPY: return LowerVACOPY(Op, DAG); 9591 9592 case ISD::STACKRESTORE: return LowerSTACKRESTORE(Op, DAG); 9593 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG); 9594 case ISD::GET_DYNAMIC_AREA_OFFSET: 9595 return LowerGET_DYNAMIC_AREA_OFFSET(Op, DAG); 9596 9597 // Exception handling lowering. 9598 case ISD::EH_DWARF_CFA: return LowerEH_DWARF_CFA(Op, DAG); 9599 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG); 9600 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG); 9601 9602 case ISD::LOAD: return LowerLOAD(Op, DAG); 9603 case ISD::STORE: return LowerSTORE(Op, DAG); 9604 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG); 9605 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG); 9606 case ISD::FP_TO_UINT: 9607 case ISD::FP_TO_SINT: return LowerFP_TO_INT(Op, DAG, SDLoc(Op)); 9608 case ISD::UINT_TO_FP: 9609 case ISD::SINT_TO_FP: return LowerINT_TO_FP(Op, DAG); 9610 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG); 9611 9612 // Lower 64-bit shifts. 9613 case ISD::SHL_PARTS: return LowerSHL_PARTS(Op, DAG); 9614 case ISD::SRL_PARTS: return LowerSRL_PARTS(Op, DAG); 9615 case ISD::SRA_PARTS: return LowerSRA_PARTS(Op, DAG); 9616 9617 // Vector-related lowering. 9618 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG); 9619 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG); 9620 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG); 9621 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG); 9622 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG); 9623 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG); 9624 case ISD::MUL: return LowerMUL(Op, DAG); 9625 9626 // For counter-based loop handling. 9627 case ISD::INTRINSIC_W_CHAIN: return SDValue(); 9628 9629 case ISD::BITCAST: return LowerBITCAST(Op, DAG); 9630 9631 // Frame & Return address. 9632 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG); 9633 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG); 9634 9635 case ISD::INTRINSIC_VOID: 9636 return LowerINTRINSIC_VOID(Op, DAG); 9637 case ISD::SREM: 9638 case ISD::UREM: 9639 return LowerREM(Op, DAG); 9640 case ISD::BSWAP: 9641 return LowerBSWAP(Op, DAG); 9642 case ISD::ATOMIC_CMP_SWAP: 9643 return LowerATOMIC_CMP_SWAP(Op, DAG); 9644 } 9645 } 9646 9647 void PPCTargetLowering::ReplaceNodeResults(SDNode *N, 9648 SmallVectorImpl<SDValue>&Results, 9649 SelectionDAG &DAG) const { 9650 SDLoc dl(N); 9651 switch (N->getOpcode()) { 9652 default: 9653 llvm_unreachable("Do not know how to custom type legalize this operation!"); 9654 case ISD::READCYCLECOUNTER: { 9655 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other); 9656 SDValue RTB = DAG.getNode(PPCISD::READ_TIME_BASE, dl, VTs, N->getOperand(0)); 9657 9658 Results.push_back(RTB); 9659 Results.push_back(RTB.getValue(1)); 9660 Results.push_back(RTB.getValue(2)); 9661 break; 9662 } 9663 case ISD::INTRINSIC_W_CHAIN: { 9664 if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 9665 Intrinsic::ppc_is_decremented_ctr_nonzero) 9666 break; 9667 9668 assert(N->getValueType(0) == MVT::i1 && 9669 "Unexpected result type for CTR decrement intrinsic"); 9670 EVT SVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 9671 N->getValueType(0)); 9672 SDVTList VTs = DAG.getVTList(SVT, MVT::Other); 9673 SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0), 9674 N->getOperand(1)); 9675 9676 Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewInt)); 9677 Results.push_back(NewInt.getValue(1)); 9678 break; 9679 } 9680 case ISD::VAARG: { 9681 if (!Subtarget.isSVR4ABI() || Subtarget.isPPC64()) 9682 return; 9683 9684 EVT VT = N->getValueType(0); 9685 9686 if (VT == MVT::i64) { 9687 SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG); 9688 9689 Results.push_back(NewNode); 9690 Results.push_back(NewNode.getValue(1)); 9691 } 9692 return; 9693 } 9694 case ISD::FP_TO_SINT: 9695 case ISD::FP_TO_UINT: 9696 // LowerFP_TO_INT() can only handle f32 and f64. 9697 if (N->getOperand(0).getValueType() == MVT::ppcf128) 9698 return; 9699 Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl)); 9700 return; 9701 case ISD::BITCAST: 9702 // Don't handle bitcast here. 9703 return; 9704 } 9705 } 9706 9707 //===----------------------------------------------------------------------===// 9708 // Other Lowering Code 9709 //===----------------------------------------------------------------------===// 9710 9711 static Instruction* callIntrinsic(IRBuilder<> &Builder, Intrinsic::ID Id) { 9712 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 9713 Function *Func = Intrinsic::getDeclaration(M, Id); 9714 return Builder.CreateCall(Func, {}); 9715 } 9716 9717 // The mappings for emitLeading/TrailingFence is taken from 9718 // http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html 9719 Instruction *PPCTargetLowering::emitLeadingFence(IRBuilder<> &Builder, 9720 Instruction *Inst, 9721 AtomicOrdering Ord) const { 9722 if (Ord == AtomicOrdering::SequentiallyConsistent) 9723 return callIntrinsic(Builder, Intrinsic::ppc_sync); 9724 if (isReleaseOrStronger(Ord)) 9725 return callIntrinsic(Builder, Intrinsic::ppc_lwsync); 9726 return nullptr; 9727 } 9728 9729 Instruction *PPCTargetLowering::emitTrailingFence(IRBuilder<> &Builder, 9730 Instruction *Inst, 9731 AtomicOrdering Ord) const { 9732 if (Inst->hasAtomicLoad() && isAcquireOrStronger(Ord)) { 9733 // See http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html and 9734 // http://www.rdrop.com/users/paulmck/scalability/paper/N2745r.2011.03.04a.html 9735 // and http://www.cl.cam.ac.uk/~pes20/cppppc/ for justification. 9736 if (isa<LoadInst>(Inst) && Subtarget.isPPC64()) 9737 return Builder.CreateCall( 9738 Intrinsic::getDeclaration( 9739 Builder.GetInsertBlock()->getParent()->getParent(), 9740 Intrinsic::ppc_cfence, {Inst->getType()}), 9741 {Inst}); 9742 // FIXME: Can use isync for rmw operation. 9743 return callIntrinsic(Builder, Intrinsic::ppc_lwsync); 9744 } 9745 return nullptr; 9746 } 9747 9748 MachineBasicBlock * 9749 PPCTargetLowering::EmitAtomicBinary(MachineInstr &MI, MachineBasicBlock *BB, 9750 unsigned AtomicSize, 9751 unsigned BinOpcode, 9752 unsigned CmpOpcode, 9753 unsigned CmpPred) const { 9754 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0. 9755 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 9756 9757 auto LoadMnemonic = PPC::LDARX; 9758 auto StoreMnemonic = PPC::STDCX; 9759 switch (AtomicSize) { 9760 default: 9761 llvm_unreachable("Unexpected size of atomic entity"); 9762 case 1: 9763 LoadMnemonic = PPC::LBARX; 9764 StoreMnemonic = PPC::STBCX; 9765 assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4"); 9766 break; 9767 case 2: 9768 LoadMnemonic = PPC::LHARX; 9769 StoreMnemonic = PPC::STHCX; 9770 assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4"); 9771 break; 9772 case 4: 9773 LoadMnemonic = PPC::LWARX; 9774 StoreMnemonic = PPC::STWCX; 9775 break; 9776 case 8: 9777 LoadMnemonic = PPC::LDARX; 9778 StoreMnemonic = PPC::STDCX; 9779 break; 9780 } 9781 9782 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 9783 MachineFunction *F = BB->getParent(); 9784 MachineFunction::iterator It = ++BB->getIterator(); 9785 9786 unsigned dest = MI.getOperand(0).getReg(); 9787 unsigned ptrA = MI.getOperand(1).getReg(); 9788 unsigned ptrB = MI.getOperand(2).getReg(); 9789 unsigned incr = MI.getOperand(3).getReg(); 9790 DebugLoc dl = MI.getDebugLoc(); 9791 9792 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB); 9793 MachineBasicBlock *loop2MBB = 9794 CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr; 9795 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 9796 F->insert(It, loopMBB); 9797 if (CmpOpcode) 9798 F->insert(It, loop2MBB); 9799 F->insert(It, exitMBB); 9800 exitMBB->splice(exitMBB->begin(), BB, 9801 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 9802 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 9803 9804 MachineRegisterInfo &RegInfo = F->getRegInfo(); 9805 unsigned TmpReg = (!BinOpcode) ? incr : 9806 RegInfo.createVirtualRegister( AtomicSize == 8 ? &PPC::G8RCRegClass 9807 : &PPC::GPRCRegClass); 9808 9809 // thisMBB: 9810 // ... 9811 // fallthrough --> loopMBB 9812 BB->addSuccessor(loopMBB); 9813 9814 // loopMBB: 9815 // l[wd]arx dest, ptr 9816 // add r0, dest, incr 9817 // st[wd]cx. r0, ptr 9818 // bne- loopMBB 9819 // fallthrough --> exitMBB 9820 9821 // For max/min... 9822 // loopMBB: 9823 // l[wd]arx dest, ptr 9824 // cmpl?[wd] incr, dest 9825 // bgt exitMBB 9826 // loop2MBB: 9827 // st[wd]cx. dest, ptr 9828 // bne- loopMBB 9829 // fallthrough --> exitMBB 9830 9831 BB = loopMBB; 9832 BuildMI(BB, dl, TII->get(LoadMnemonic), dest) 9833 .addReg(ptrA).addReg(ptrB); 9834 if (BinOpcode) 9835 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest); 9836 if (CmpOpcode) { 9837 // Signed comparisons of byte or halfword values must be sign-extended. 9838 if (CmpOpcode == PPC::CMPW && AtomicSize < 4) { 9839 unsigned ExtReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass); 9840 BuildMI(BB, dl, TII->get(AtomicSize == 1 ? PPC::EXTSB : PPC::EXTSH), 9841 ExtReg).addReg(dest); 9842 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0) 9843 .addReg(incr).addReg(ExtReg); 9844 } else 9845 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0) 9846 .addReg(incr).addReg(dest); 9847 9848 BuildMI(BB, dl, TII->get(PPC::BCC)) 9849 .addImm(CmpPred).addReg(PPC::CR0).addMBB(exitMBB); 9850 BB->addSuccessor(loop2MBB); 9851 BB->addSuccessor(exitMBB); 9852 BB = loop2MBB; 9853 } 9854 BuildMI(BB, dl, TII->get(StoreMnemonic)) 9855 .addReg(TmpReg).addReg(ptrA).addReg(ptrB); 9856 BuildMI(BB, dl, TII->get(PPC::BCC)) 9857 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB); 9858 BB->addSuccessor(loopMBB); 9859 BB->addSuccessor(exitMBB); 9860 9861 // exitMBB: 9862 // ... 9863 BB = exitMBB; 9864 return BB; 9865 } 9866 9867 MachineBasicBlock * 9868 PPCTargetLowering::EmitPartwordAtomicBinary(MachineInstr &MI, 9869 MachineBasicBlock *BB, 9870 bool is8bit, // operation 9871 unsigned BinOpcode, 9872 unsigned CmpOpcode, 9873 unsigned CmpPred) const { 9874 // If we support part-word atomic mnemonics, just use them 9875 if (Subtarget.hasPartwordAtomics()) 9876 return EmitAtomicBinary(MI, BB, is8bit ? 1 : 2, BinOpcode, 9877 CmpOpcode, CmpPred); 9878 9879 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0. 9880 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 9881 // In 64 bit mode we have to use 64 bits for addresses, even though the 9882 // lwarx/stwcx are 32 bits. With the 32-bit atomics we can use address 9883 // registers without caring whether they're 32 or 64, but here we're 9884 // doing actual arithmetic on the addresses. 9885 bool is64bit = Subtarget.isPPC64(); 9886 bool isLittleEndian = Subtarget.isLittleEndian(); 9887 unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO; 9888 9889 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 9890 MachineFunction *F = BB->getParent(); 9891 MachineFunction::iterator It = ++BB->getIterator(); 9892 9893 unsigned dest = MI.getOperand(0).getReg(); 9894 unsigned ptrA = MI.getOperand(1).getReg(); 9895 unsigned ptrB = MI.getOperand(2).getReg(); 9896 unsigned incr = MI.getOperand(3).getReg(); 9897 DebugLoc dl = MI.getDebugLoc(); 9898 9899 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB); 9900 MachineBasicBlock *loop2MBB = 9901 CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr; 9902 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 9903 F->insert(It, loopMBB); 9904 if (CmpOpcode) 9905 F->insert(It, loop2MBB); 9906 F->insert(It, exitMBB); 9907 exitMBB->splice(exitMBB->begin(), BB, 9908 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 9909 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 9910 9911 MachineRegisterInfo &RegInfo = F->getRegInfo(); 9912 const TargetRegisterClass *RC = is64bit ? &PPC::G8RCRegClass 9913 : &PPC::GPRCRegClass; 9914 unsigned PtrReg = RegInfo.createVirtualRegister(RC); 9915 unsigned Shift1Reg = RegInfo.createVirtualRegister(RC); 9916 unsigned ShiftReg = 9917 isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(RC); 9918 unsigned Incr2Reg = RegInfo.createVirtualRegister(RC); 9919 unsigned MaskReg = RegInfo.createVirtualRegister(RC); 9920 unsigned Mask2Reg = RegInfo.createVirtualRegister(RC); 9921 unsigned Mask3Reg = RegInfo.createVirtualRegister(RC); 9922 unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC); 9923 unsigned Tmp3Reg = RegInfo.createVirtualRegister(RC); 9924 unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC); 9925 unsigned TmpDestReg = RegInfo.createVirtualRegister(RC); 9926 unsigned Ptr1Reg; 9927 unsigned TmpReg = (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(RC); 9928 9929 // thisMBB: 9930 // ... 9931 // fallthrough --> loopMBB 9932 BB->addSuccessor(loopMBB); 9933 9934 // The 4-byte load must be aligned, while a char or short may be 9935 // anywhere in the word. Hence all this nasty bookkeeping code. 9936 // add ptr1, ptrA, ptrB [copy if ptrA==0] 9937 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27] 9938 // xori shift, shift1, 24 [16] 9939 // rlwinm ptr, ptr1, 0, 0, 29 9940 // slw incr2, incr, shift 9941 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535] 9942 // slw mask, mask2, shift 9943 // loopMBB: 9944 // lwarx tmpDest, ptr 9945 // add tmp, tmpDest, incr2 9946 // andc tmp2, tmpDest, mask 9947 // and tmp3, tmp, mask 9948 // or tmp4, tmp3, tmp2 9949 // stwcx. tmp4, ptr 9950 // bne- loopMBB 9951 // fallthrough --> exitMBB 9952 // srw dest, tmpDest, shift 9953 if (ptrA != ZeroReg) { 9954 Ptr1Reg = RegInfo.createVirtualRegister(RC); 9955 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg) 9956 .addReg(ptrA).addReg(ptrB); 9957 } else { 9958 Ptr1Reg = ptrB; 9959 } 9960 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg) 9961 .addImm(3).addImm(27).addImm(is8bit ? 28 : 27); 9962 if (!isLittleEndian) 9963 BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg) 9964 .addReg(Shift1Reg).addImm(is8bit ? 24 : 16); 9965 if (is64bit) 9966 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg) 9967 .addReg(Ptr1Reg).addImm(0).addImm(61); 9968 else 9969 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg) 9970 .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29); 9971 BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg) 9972 .addReg(incr).addReg(ShiftReg); 9973 if (is8bit) 9974 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255); 9975 else { 9976 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0); 9977 BuildMI(BB, dl, TII->get(PPC::ORI),Mask2Reg).addReg(Mask3Reg).addImm(65535); 9978 } 9979 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg) 9980 .addReg(Mask2Reg).addReg(ShiftReg); 9981 9982 BB = loopMBB; 9983 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg) 9984 .addReg(ZeroReg).addReg(PtrReg); 9985 if (BinOpcode) 9986 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg) 9987 .addReg(Incr2Reg).addReg(TmpDestReg); 9988 BuildMI(BB, dl, TII->get(is64bit ? PPC::ANDC8 : PPC::ANDC), Tmp2Reg) 9989 .addReg(TmpDestReg).addReg(MaskReg); 9990 BuildMI(BB, dl, TII->get(is64bit ? PPC::AND8 : PPC::AND), Tmp3Reg) 9991 .addReg(TmpReg).addReg(MaskReg); 9992 if (CmpOpcode) { 9993 // For unsigned comparisons, we can directly compare the shifted values. 9994 // For signed comparisons we shift and sign extend. 9995 unsigned SReg = RegInfo.createVirtualRegister(RC); 9996 BuildMI(BB, dl, TII->get(is64bit ? PPC::AND8 : PPC::AND), SReg) 9997 .addReg(TmpDestReg).addReg(MaskReg); 9998 unsigned ValueReg = SReg; 9999 unsigned CmpReg = Incr2Reg; 10000 if (CmpOpcode == PPC::CMPW) { 10001 ValueReg = RegInfo.createVirtualRegister(RC); 10002 BuildMI(BB, dl, TII->get(PPC::SRW), ValueReg) 10003 .addReg(SReg).addReg(ShiftReg); 10004 unsigned ValueSReg = RegInfo.createVirtualRegister(RC); 10005 BuildMI(BB, dl, TII->get(is8bit ? PPC::EXTSB : PPC::EXTSH), ValueSReg) 10006 .addReg(ValueReg); 10007 ValueReg = ValueSReg; 10008 CmpReg = incr; 10009 } 10010 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0) 10011 .addReg(CmpReg).addReg(ValueReg); 10012 BuildMI(BB, dl, TII->get(PPC::BCC)) 10013 .addImm(CmpPred).addReg(PPC::CR0).addMBB(exitMBB); 10014 BB->addSuccessor(loop2MBB); 10015 BB->addSuccessor(exitMBB); 10016 BB = loop2MBB; 10017 } 10018 BuildMI(BB, dl, TII->get(is64bit ? PPC::OR8 : PPC::OR), Tmp4Reg) 10019 .addReg(Tmp3Reg).addReg(Tmp2Reg); 10020 BuildMI(BB, dl, TII->get(PPC::STWCX)) 10021 .addReg(Tmp4Reg).addReg(ZeroReg).addReg(PtrReg); 10022 BuildMI(BB, dl, TII->get(PPC::BCC)) 10023 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB); 10024 BB->addSuccessor(loopMBB); 10025 BB->addSuccessor(exitMBB); 10026 10027 // exitMBB: 10028 // ... 10029 BB = exitMBB; 10030 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest).addReg(TmpDestReg) 10031 .addReg(ShiftReg); 10032 return BB; 10033 } 10034 10035 llvm::MachineBasicBlock * 10036 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr &MI, 10037 MachineBasicBlock *MBB) const { 10038 DebugLoc DL = MI.getDebugLoc(); 10039 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 10040 const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo(); 10041 10042 MachineFunction *MF = MBB->getParent(); 10043 MachineRegisterInfo &MRI = MF->getRegInfo(); 10044 10045 const BasicBlock *BB = MBB->getBasicBlock(); 10046 MachineFunction::iterator I = ++MBB->getIterator(); 10047 10048 unsigned DstReg = MI.getOperand(0).getReg(); 10049 const TargetRegisterClass *RC = MRI.getRegClass(DstReg); 10050 assert(TRI->isTypeLegalForClass(*RC, MVT::i32) && "Invalid destination!"); 10051 unsigned mainDstReg = MRI.createVirtualRegister(RC); 10052 unsigned restoreDstReg = MRI.createVirtualRegister(RC); 10053 10054 MVT PVT = getPointerTy(MF->getDataLayout()); 10055 assert((PVT == MVT::i64 || PVT == MVT::i32) && 10056 "Invalid Pointer Size!"); 10057 // For v = setjmp(buf), we generate 10058 // 10059 // thisMBB: 10060 // SjLjSetup mainMBB 10061 // bl mainMBB 10062 // v_restore = 1 10063 // b sinkMBB 10064 // 10065 // mainMBB: 10066 // buf[LabelOffset] = LR 10067 // v_main = 0 10068 // 10069 // sinkMBB: 10070 // v = phi(main, restore) 10071 // 10072 10073 MachineBasicBlock *thisMBB = MBB; 10074 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB); 10075 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB); 10076 MF->insert(I, mainMBB); 10077 MF->insert(I, sinkMBB); 10078 10079 MachineInstrBuilder MIB; 10080 10081 // Transfer the remainder of BB and its successor edges to sinkMBB. 10082 sinkMBB->splice(sinkMBB->begin(), MBB, 10083 std::next(MachineBasicBlock::iterator(MI)), MBB->end()); 10084 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB); 10085 10086 // Note that the structure of the jmp_buf used here is not compatible 10087 // with that used by libc, and is not designed to be. Specifically, it 10088 // stores only those 'reserved' registers that LLVM does not otherwise 10089 // understand how to spill. Also, by convention, by the time this 10090 // intrinsic is called, Clang has already stored the frame address in the 10091 // first slot of the buffer and stack address in the third. Following the 10092 // X86 target code, we'll store the jump address in the second slot. We also 10093 // need to save the TOC pointer (R2) to handle jumps between shared 10094 // libraries, and that will be stored in the fourth slot. The thread 10095 // identifier (R13) is not affected. 10096 10097 // thisMBB: 10098 const int64_t LabelOffset = 1 * PVT.getStoreSize(); 10099 const int64_t TOCOffset = 3 * PVT.getStoreSize(); 10100 const int64_t BPOffset = 4 * PVT.getStoreSize(); 10101 10102 // Prepare IP either in reg. 10103 const TargetRegisterClass *PtrRC = getRegClassFor(PVT); 10104 unsigned LabelReg = MRI.createVirtualRegister(PtrRC); 10105 unsigned BufReg = MI.getOperand(1).getReg(); 10106 10107 if (Subtarget.isPPC64() && Subtarget.isSVR4ABI()) { 10108 setUsesTOCBasePtr(*MBB->getParent()); 10109 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD)) 10110 .addReg(PPC::X2) 10111 .addImm(TOCOffset) 10112 .addReg(BufReg) 10113 .cloneMemRefs(MI); 10114 } 10115 10116 // Naked functions never have a base pointer, and so we use r1. For all 10117 // other functions, this decision must be delayed until during PEI. 10118 unsigned BaseReg; 10119 if (MF->getFunction().hasFnAttribute(Attribute::Naked)) 10120 BaseReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1; 10121 else 10122 BaseReg = Subtarget.isPPC64() ? PPC::BP8 : PPC::BP; 10123 10124 MIB = BuildMI(*thisMBB, MI, DL, 10125 TII->get(Subtarget.isPPC64() ? PPC::STD : PPC::STW)) 10126 .addReg(BaseReg) 10127 .addImm(BPOffset) 10128 .addReg(BufReg) 10129 .cloneMemRefs(MI); 10130 10131 // Setup 10132 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB); 10133 MIB.addRegMask(TRI->getNoPreservedMask()); 10134 10135 BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1); 10136 10137 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup)) 10138 .addMBB(mainMBB); 10139 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB); 10140 10141 thisMBB->addSuccessor(mainMBB, BranchProbability::getZero()); 10142 thisMBB->addSuccessor(sinkMBB, BranchProbability::getOne()); 10143 10144 // mainMBB: 10145 // mainDstReg = 0 10146 MIB = 10147 BuildMI(mainMBB, DL, 10148 TII->get(Subtarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg); 10149 10150 // Store IP 10151 if (Subtarget.isPPC64()) { 10152 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD)) 10153 .addReg(LabelReg) 10154 .addImm(LabelOffset) 10155 .addReg(BufReg); 10156 } else { 10157 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW)) 10158 .addReg(LabelReg) 10159 .addImm(LabelOffset) 10160 .addReg(BufReg); 10161 } 10162 MIB.cloneMemRefs(MI); 10163 10164 BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0); 10165 mainMBB->addSuccessor(sinkMBB); 10166 10167 // sinkMBB: 10168 BuildMI(*sinkMBB, sinkMBB->begin(), DL, 10169 TII->get(PPC::PHI), DstReg) 10170 .addReg(mainDstReg).addMBB(mainMBB) 10171 .addReg(restoreDstReg).addMBB(thisMBB); 10172 10173 MI.eraseFromParent(); 10174 return sinkMBB; 10175 } 10176 10177 MachineBasicBlock * 10178 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr &MI, 10179 MachineBasicBlock *MBB) const { 10180 DebugLoc DL = MI.getDebugLoc(); 10181 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 10182 10183 MachineFunction *MF = MBB->getParent(); 10184 MachineRegisterInfo &MRI = MF->getRegInfo(); 10185 10186 MVT PVT = getPointerTy(MF->getDataLayout()); 10187 assert((PVT == MVT::i64 || PVT == MVT::i32) && 10188 "Invalid Pointer Size!"); 10189 10190 const TargetRegisterClass *RC = 10191 (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 10192 unsigned Tmp = MRI.createVirtualRegister(RC); 10193 // Since FP is only updated here but NOT referenced, it's treated as GPR. 10194 unsigned FP = (PVT == MVT::i64) ? PPC::X31 : PPC::R31; 10195 unsigned SP = (PVT == MVT::i64) ? PPC::X1 : PPC::R1; 10196 unsigned BP = 10197 (PVT == MVT::i64) 10198 ? PPC::X30 10199 : (Subtarget.isSVR4ABI() && isPositionIndependent() ? PPC::R29 10200 : PPC::R30); 10201 10202 MachineInstrBuilder MIB; 10203 10204 const int64_t LabelOffset = 1 * PVT.getStoreSize(); 10205 const int64_t SPOffset = 2 * PVT.getStoreSize(); 10206 const int64_t TOCOffset = 3 * PVT.getStoreSize(); 10207 const int64_t BPOffset = 4 * PVT.getStoreSize(); 10208 10209 unsigned BufReg = MI.getOperand(0).getReg(); 10210 10211 // Reload FP (the jumped-to function may not have had a 10212 // frame pointer, and if so, then its r31 will be restored 10213 // as necessary). 10214 if (PVT == MVT::i64) { 10215 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP) 10216 .addImm(0) 10217 .addReg(BufReg); 10218 } else { 10219 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP) 10220 .addImm(0) 10221 .addReg(BufReg); 10222 } 10223 MIB.cloneMemRefs(MI); 10224 10225 // Reload IP 10226 if (PVT == MVT::i64) { 10227 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp) 10228 .addImm(LabelOffset) 10229 .addReg(BufReg); 10230 } else { 10231 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp) 10232 .addImm(LabelOffset) 10233 .addReg(BufReg); 10234 } 10235 MIB.cloneMemRefs(MI); 10236 10237 // Reload SP 10238 if (PVT == MVT::i64) { 10239 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP) 10240 .addImm(SPOffset) 10241 .addReg(BufReg); 10242 } else { 10243 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP) 10244 .addImm(SPOffset) 10245 .addReg(BufReg); 10246 } 10247 MIB.cloneMemRefs(MI); 10248 10249 // Reload BP 10250 if (PVT == MVT::i64) { 10251 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP) 10252 .addImm(BPOffset) 10253 .addReg(BufReg); 10254 } else { 10255 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP) 10256 .addImm(BPOffset) 10257 .addReg(BufReg); 10258 } 10259 MIB.cloneMemRefs(MI); 10260 10261 // Reload TOC 10262 if (PVT == MVT::i64 && Subtarget.isSVR4ABI()) { 10263 setUsesTOCBasePtr(*MBB->getParent()); 10264 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2) 10265 .addImm(TOCOffset) 10266 .addReg(BufReg) 10267 .cloneMemRefs(MI); 10268 } 10269 10270 // Jump 10271 BuildMI(*MBB, MI, DL, 10272 TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp); 10273 BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR)); 10274 10275 MI.eraseFromParent(); 10276 return MBB; 10277 } 10278 10279 MachineBasicBlock * 10280 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI, 10281 MachineBasicBlock *BB) const { 10282 if (MI.getOpcode() == TargetOpcode::STACKMAP || 10283 MI.getOpcode() == TargetOpcode::PATCHPOINT) { 10284 if (Subtarget.isPPC64() && Subtarget.isSVR4ABI() && 10285 MI.getOpcode() == TargetOpcode::PATCHPOINT) { 10286 // Call lowering should have added an r2 operand to indicate a dependence 10287 // on the TOC base pointer value. It can't however, because there is no 10288 // way to mark the dependence as implicit there, and so the stackmap code 10289 // will confuse it with a regular operand. Instead, add the dependence 10290 // here. 10291 setUsesTOCBasePtr(*BB->getParent()); 10292 MI.addOperand(MachineOperand::CreateReg(PPC::X2, false, true)); 10293 } 10294 10295 return emitPatchPoint(MI, BB); 10296 } 10297 10298 if (MI.getOpcode() == PPC::EH_SjLj_SetJmp32 || 10299 MI.getOpcode() == PPC::EH_SjLj_SetJmp64) { 10300 return emitEHSjLjSetJmp(MI, BB); 10301 } else if (MI.getOpcode() == PPC::EH_SjLj_LongJmp32 || 10302 MI.getOpcode() == PPC::EH_SjLj_LongJmp64) { 10303 return emitEHSjLjLongJmp(MI, BB); 10304 } 10305 10306 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 10307 10308 // To "insert" these instructions we actually have to insert their 10309 // control-flow patterns. 10310 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 10311 MachineFunction::iterator It = ++BB->getIterator(); 10312 10313 MachineFunction *F = BB->getParent(); 10314 10315 if (MI.getOpcode() == PPC::SELECT_CC_I4 || 10316 MI.getOpcode() == PPC::SELECT_CC_I8 || 10317 MI.getOpcode() == PPC::SELECT_I4 || MI.getOpcode() == PPC::SELECT_I8) { 10318 SmallVector<MachineOperand, 2> Cond; 10319 if (MI.getOpcode() == PPC::SELECT_CC_I4 || 10320 MI.getOpcode() == PPC::SELECT_CC_I8) 10321 Cond.push_back(MI.getOperand(4)); 10322 else 10323 Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET)); 10324 Cond.push_back(MI.getOperand(1)); 10325 10326 DebugLoc dl = MI.getDebugLoc(); 10327 TII->insertSelect(*BB, MI, dl, MI.getOperand(0).getReg(), Cond, 10328 MI.getOperand(2).getReg(), MI.getOperand(3).getReg()); 10329 } else if (MI.getOpcode() == PPC::SELECT_CC_I4 || 10330 MI.getOpcode() == PPC::SELECT_CC_I8 || 10331 MI.getOpcode() == PPC::SELECT_CC_F4 || 10332 MI.getOpcode() == PPC::SELECT_CC_F8 || 10333 MI.getOpcode() == PPC::SELECT_CC_F16 || 10334 MI.getOpcode() == PPC::SELECT_CC_QFRC || 10335 MI.getOpcode() == PPC::SELECT_CC_QSRC || 10336 MI.getOpcode() == PPC::SELECT_CC_QBRC || 10337 MI.getOpcode() == PPC::SELECT_CC_VRRC || 10338 MI.getOpcode() == PPC::SELECT_CC_VSFRC || 10339 MI.getOpcode() == PPC::SELECT_CC_VSSRC || 10340 MI.getOpcode() == PPC::SELECT_CC_VSRC || 10341 MI.getOpcode() == PPC::SELECT_CC_SPE4 || 10342 MI.getOpcode() == PPC::SELECT_CC_SPE || 10343 MI.getOpcode() == PPC::SELECT_I4 || 10344 MI.getOpcode() == PPC::SELECT_I8 || 10345 MI.getOpcode() == PPC::SELECT_F4 || 10346 MI.getOpcode() == PPC::SELECT_F8 || 10347 MI.getOpcode() == PPC::SELECT_F16 || 10348 MI.getOpcode() == PPC::SELECT_QFRC || 10349 MI.getOpcode() == PPC::SELECT_QSRC || 10350 MI.getOpcode() == PPC::SELECT_QBRC || 10351 MI.getOpcode() == PPC::SELECT_SPE || 10352 MI.getOpcode() == PPC::SELECT_SPE4 || 10353 MI.getOpcode() == PPC::SELECT_VRRC || 10354 MI.getOpcode() == PPC::SELECT_VSFRC || 10355 MI.getOpcode() == PPC::SELECT_VSSRC || 10356 MI.getOpcode() == PPC::SELECT_VSRC) { 10357 // The incoming instruction knows the destination vreg to set, the 10358 // condition code register to branch on, the true/false values to 10359 // select between, and a branch opcode to use. 10360 10361 // thisMBB: 10362 // ... 10363 // TrueVal = ... 10364 // cmpTY ccX, r1, r2 10365 // bCC copy1MBB 10366 // fallthrough --> copy0MBB 10367 MachineBasicBlock *thisMBB = BB; 10368 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB); 10369 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 10370 DebugLoc dl = MI.getDebugLoc(); 10371 F->insert(It, copy0MBB); 10372 F->insert(It, sinkMBB); 10373 10374 // Transfer the remainder of BB and its successor edges to sinkMBB. 10375 sinkMBB->splice(sinkMBB->begin(), BB, 10376 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 10377 sinkMBB->transferSuccessorsAndUpdatePHIs(BB); 10378 10379 // Next, add the true and fallthrough blocks as its successors. 10380 BB->addSuccessor(copy0MBB); 10381 BB->addSuccessor(sinkMBB); 10382 10383 if (MI.getOpcode() == PPC::SELECT_I4 || MI.getOpcode() == PPC::SELECT_I8 || 10384 MI.getOpcode() == PPC::SELECT_F4 || MI.getOpcode() == PPC::SELECT_F8 || 10385 MI.getOpcode() == PPC::SELECT_F16 || 10386 MI.getOpcode() == PPC::SELECT_SPE4 || 10387 MI.getOpcode() == PPC::SELECT_SPE || 10388 MI.getOpcode() == PPC::SELECT_QFRC || 10389 MI.getOpcode() == PPC::SELECT_QSRC || 10390 MI.getOpcode() == PPC::SELECT_QBRC || 10391 MI.getOpcode() == PPC::SELECT_VRRC || 10392 MI.getOpcode() == PPC::SELECT_VSFRC || 10393 MI.getOpcode() == PPC::SELECT_VSSRC || 10394 MI.getOpcode() == PPC::SELECT_VSRC) { 10395 BuildMI(BB, dl, TII->get(PPC::BC)) 10396 .addReg(MI.getOperand(1).getReg()) 10397 .addMBB(sinkMBB); 10398 } else { 10399 unsigned SelectPred = MI.getOperand(4).getImm(); 10400 BuildMI(BB, dl, TII->get(PPC::BCC)) 10401 .addImm(SelectPred) 10402 .addReg(MI.getOperand(1).getReg()) 10403 .addMBB(sinkMBB); 10404 } 10405 10406 // copy0MBB: 10407 // %FalseValue = ... 10408 // # fallthrough to sinkMBB 10409 BB = copy0MBB; 10410 10411 // Update machine-CFG edges 10412 BB->addSuccessor(sinkMBB); 10413 10414 // sinkMBB: 10415 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ] 10416 // ... 10417 BB = sinkMBB; 10418 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::PHI), MI.getOperand(0).getReg()) 10419 .addReg(MI.getOperand(3).getReg()) 10420 .addMBB(copy0MBB) 10421 .addReg(MI.getOperand(2).getReg()) 10422 .addMBB(thisMBB); 10423 } else if (MI.getOpcode() == PPC::ReadTB) { 10424 // To read the 64-bit time-base register on a 32-bit target, we read the 10425 // two halves. Should the counter have wrapped while it was being read, we 10426 // need to try again. 10427 // ... 10428 // readLoop: 10429 // mfspr Rx,TBU # load from TBU 10430 // mfspr Ry,TB # load from TB 10431 // mfspr Rz,TBU # load from TBU 10432 // cmpw crX,Rx,Rz # check if 'old'='new' 10433 // bne readLoop # branch if they're not equal 10434 // ... 10435 10436 MachineBasicBlock *readMBB = F->CreateMachineBasicBlock(LLVM_BB); 10437 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 10438 DebugLoc dl = MI.getDebugLoc(); 10439 F->insert(It, readMBB); 10440 F->insert(It, sinkMBB); 10441 10442 // Transfer the remainder of BB and its successor edges to sinkMBB. 10443 sinkMBB->splice(sinkMBB->begin(), BB, 10444 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 10445 sinkMBB->transferSuccessorsAndUpdatePHIs(BB); 10446 10447 BB->addSuccessor(readMBB); 10448 BB = readMBB; 10449 10450 MachineRegisterInfo &RegInfo = F->getRegInfo(); 10451 unsigned ReadAgainReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass); 10452 unsigned LoReg = MI.getOperand(0).getReg(); 10453 unsigned HiReg = MI.getOperand(1).getReg(); 10454 10455 BuildMI(BB, dl, TII->get(PPC::MFSPR), HiReg).addImm(269); 10456 BuildMI(BB, dl, TII->get(PPC::MFSPR), LoReg).addImm(268); 10457 BuildMI(BB, dl, TII->get(PPC::MFSPR), ReadAgainReg).addImm(269); 10458 10459 unsigned CmpReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass); 10460 10461 BuildMI(BB, dl, TII->get(PPC::CMPW), CmpReg) 10462 .addReg(HiReg).addReg(ReadAgainReg); 10463 BuildMI(BB, dl, TII->get(PPC::BCC)) 10464 .addImm(PPC::PRED_NE).addReg(CmpReg).addMBB(readMBB); 10465 10466 BB->addSuccessor(readMBB); 10467 BB->addSuccessor(sinkMBB); 10468 } else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I8) 10469 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4); 10470 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I16) 10471 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4); 10472 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I32) 10473 BB = EmitAtomicBinary(MI, BB, 4, PPC::ADD4); 10474 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I64) 10475 BB = EmitAtomicBinary(MI, BB, 8, PPC::ADD8); 10476 10477 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I8) 10478 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND); 10479 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I16) 10480 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND); 10481 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I32) 10482 BB = EmitAtomicBinary(MI, BB, 4, PPC::AND); 10483 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I64) 10484 BB = EmitAtomicBinary(MI, BB, 8, PPC::AND8); 10485 10486 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I8) 10487 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR); 10488 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I16) 10489 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR); 10490 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I32) 10491 BB = EmitAtomicBinary(MI, BB, 4, PPC::OR); 10492 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I64) 10493 BB = EmitAtomicBinary(MI, BB, 8, PPC::OR8); 10494 10495 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I8) 10496 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR); 10497 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I16) 10498 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR); 10499 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I32) 10500 BB = EmitAtomicBinary(MI, BB, 4, PPC::XOR); 10501 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I64) 10502 BB = EmitAtomicBinary(MI, BB, 8, PPC::XOR8); 10503 10504 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I8) 10505 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::NAND); 10506 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I16) 10507 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::NAND); 10508 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I32) 10509 BB = EmitAtomicBinary(MI, BB, 4, PPC::NAND); 10510 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I64) 10511 BB = EmitAtomicBinary(MI, BB, 8, PPC::NAND8); 10512 10513 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I8) 10514 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF); 10515 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I16) 10516 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF); 10517 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I32) 10518 BB = EmitAtomicBinary(MI, BB, 4, PPC::SUBF); 10519 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I64) 10520 BB = EmitAtomicBinary(MI, BB, 8, PPC::SUBF8); 10521 10522 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I8) 10523 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_GE); 10524 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I16) 10525 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_GE); 10526 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I32) 10527 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_GE); 10528 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I64) 10529 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_GE); 10530 10531 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I8) 10532 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_LE); 10533 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I16) 10534 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_LE); 10535 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I32) 10536 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_LE); 10537 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I64) 10538 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_LE); 10539 10540 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I8) 10541 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_GE); 10542 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I16) 10543 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_GE); 10544 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I32) 10545 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_GE); 10546 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I64) 10547 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_GE); 10548 10549 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I8) 10550 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_LE); 10551 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I16) 10552 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_LE); 10553 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I32) 10554 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_LE); 10555 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I64) 10556 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_LE); 10557 10558 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I8) 10559 BB = EmitPartwordAtomicBinary(MI, BB, true, 0); 10560 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I16) 10561 BB = EmitPartwordAtomicBinary(MI, BB, false, 0); 10562 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I32) 10563 BB = EmitAtomicBinary(MI, BB, 4, 0); 10564 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I64) 10565 BB = EmitAtomicBinary(MI, BB, 8, 0); 10566 else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 || 10567 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64 || 10568 (Subtarget.hasPartwordAtomics() && 10569 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8) || 10570 (Subtarget.hasPartwordAtomics() && 10571 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16)) { 10572 bool is64bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64; 10573 10574 auto LoadMnemonic = PPC::LDARX; 10575 auto StoreMnemonic = PPC::STDCX; 10576 switch (MI.getOpcode()) { 10577 default: 10578 llvm_unreachable("Compare and swap of unknown size"); 10579 case PPC::ATOMIC_CMP_SWAP_I8: 10580 LoadMnemonic = PPC::LBARX; 10581 StoreMnemonic = PPC::STBCX; 10582 assert(Subtarget.hasPartwordAtomics() && "No support partword atomics."); 10583 break; 10584 case PPC::ATOMIC_CMP_SWAP_I16: 10585 LoadMnemonic = PPC::LHARX; 10586 StoreMnemonic = PPC::STHCX; 10587 assert(Subtarget.hasPartwordAtomics() && "No support partword atomics."); 10588 break; 10589 case PPC::ATOMIC_CMP_SWAP_I32: 10590 LoadMnemonic = PPC::LWARX; 10591 StoreMnemonic = PPC::STWCX; 10592 break; 10593 case PPC::ATOMIC_CMP_SWAP_I64: 10594 LoadMnemonic = PPC::LDARX; 10595 StoreMnemonic = PPC::STDCX; 10596 break; 10597 } 10598 unsigned dest = MI.getOperand(0).getReg(); 10599 unsigned ptrA = MI.getOperand(1).getReg(); 10600 unsigned ptrB = MI.getOperand(2).getReg(); 10601 unsigned oldval = MI.getOperand(3).getReg(); 10602 unsigned newval = MI.getOperand(4).getReg(); 10603 DebugLoc dl = MI.getDebugLoc(); 10604 10605 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB); 10606 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB); 10607 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB); 10608 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 10609 F->insert(It, loop1MBB); 10610 F->insert(It, loop2MBB); 10611 F->insert(It, midMBB); 10612 F->insert(It, exitMBB); 10613 exitMBB->splice(exitMBB->begin(), BB, 10614 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 10615 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 10616 10617 // thisMBB: 10618 // ... 10619 // fallthrough --> loopMBB 10620 BB->addSuccessor(loop1MBB); 10621 10622 // loop1MBB: 10623 // l[bhwd]arx dest, ptr 10624 // cmp[wd] dest, oldval 10625 // bne- midMBB 10626 // loop2MBB: 10627 // st[bhwd]cx. newval, ptr 10628 // bne- loopMBB 10629 // b exitBB 10630 // midMBB: 10631 // st[bhwd]cx. dest, ptr 10632 // exitBB: 10633 BB = loop1MBB; 10634 BuildMI(BB, dl, TII->get(LoadMnemonic), dest) 10635 .addReg(ptrA).addReg(ptrB); 10636 BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0) 10637 .addReg(oldval).addReg(dest); 10638 BuildMI(BB, dl, TII->get(PPC::BCC)) 10639 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB); 10640 BB->addSuccessor(loop2MBB); 10641 BB->addSuccessor(midMBB); 10642 10643 BB = loop2MBB; 10644 BuildMI(BB, dl, TII->get(StoreMnemonic)) 10645 .addReg(newval).addReg(ptrA).addReg(ptrB); 10646 BuildMI(BB, dl, TII->get(PPC::BCC)) 10647 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB); 10648 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB); 10649 BB->addSuccessor(loop1MBB); 10650 BB->addSuccessor(exitMBB); 10651 10652 BB = midMBB; 10653 BuildMI(BB, dl, TII->get(StoreMnemonic)) 10654 .addReg(dest).addReg(ptrA).addReg(ptrB); 10655 BB->addSuccessor(exitMBB); 10656 10657 // exitMBB: 10658 // ... 10659 BB = exitMBB; 10660 } else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 || 10661 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) { 10662 // We must use 64-bit registers for addresses when targeting 64-bit, 10663 // since we're actually doing arithmetic on them. Other registers 10664 // can be 32-bit. 10665 bool is64bit = Subtarget.isPPC64(); 10666 bool isLittleEndian = Subtarget.isLittleEndian(); 10667 bool is8bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8; 10668 10669 unsigned dest = MI.getOperand(0).getReg(); 10670 unsigned ptrA = MI.getOperand(1).getReg(); 10671 unsigned ptrB = MI.getOperand(2).getReg(); 10672 unsigned oldval = MI.getOperand(3).getReg(); 10673 unsigned newval = MI.getOperand(4).getReg(); 10674 DebugLoc dl = MI.getDebugLoc(); 10675 10676 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB); 10677 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB); 10678 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB); 10679 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 10680 F->insert(It, loop1MBB); 10681 F->insert(It, loop2MBB); 10682 F->insert(It, midMBB); 10683 F->insert(It, exitMBB); 10684 exitMBB->splice(exitMBB->begin(), BB, 10685 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 10686 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 10687 10688 MachineRegisterInfo &RegInfo = F->getRegInfo(); 10689 const TargetRegisterClass *RC = is64bit ? &PPC::G8RCRegClass 10690 : &PPC::GPRCRegClass; 10691 unsigned PtrReg = RegInfo.createVirtualRegister(RC); 10692 unsigned Shift1Reg = RegInfo.createVirtualRegister(RC); 10693 unsigned ShiftReg = 10694 isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(RC); 10695 unsigned NewVal2Reg = RegInfo.createVirtualRegister(RC); 10696 unsigned NewVal3Reg = RegInfo.createVirtualRegister(RC); 10697 unsigned OldVal2Reg = RegInfo.createVirtualRegister(RC); 10698 unsigned OldVal3Reg = RegInfo.createVirtualRegister(RC); 10699 unsigned MaskReg = RegInfo.createVirtualRegister(RC); 10700 unsigned Mask2Reg = RegInfo.createVirtualRegister(RC); 10701 unsigned Mask3Reg = RegInfo.createVirtualRegister(RC); 10702 unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC); 10703 unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC); 10704 unsigned TmpDestReg = RegInfo.createVirtualRegister(RC); 10705 unsigned Ptr1Reg; 10706 unsigned TmpReg = RegInfo.createVirtualRegister(RC); 10707 unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO; 10708 // thisMBB: 10709 // ... 10710 // fallthrough --> loopMBB 10711 BB->addSuccessor(loop1MBB); 10712 10713 // The 4-byte load must be aligned, while a char or short may be 10714 // anywhere in the word. Hence all this nasty bookkeeping code. 10715 // add ptr1, ptrA, ptrB [copy if ptrA==0] 10716 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27] 10717 // xori shift, shift1, 24 [16] 10718 // rlwinm ptr, ptr1, 0, 0, 29 10719 // slw newval2, newval, shift 10720 // slw oldval2, oldval,shift 10721 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535] 10722 // slw mask, mask2, shift 10723 // and newval3, newval2, mask 10724 // and oldval3, oldval2, mask 10725 // loop1MBB: 10726 // lwarx tmpDest, ptr 10727 // and tmp, tmpDest, mask 10728 // cmpw tmp, oldval3 10729 // bne- midMBB 10730 // loop2MBB: 10731 // andc tmp2, tmpDest, mask 10732 // or tmp4, tmp2, newval3 10733 // stwcx. tmp4, ptr 10734 // bne- loop1MBB 10735 // b exitBB 10736 // midMBB: 10737 // stwcx. tmpDest, ptr 10738 // exitBB: 10739 // srw dest, tmpDest, shift 10740 if (ptrA != ZeroReg) { 10741 Ptr1Reg = RegInfo.createVirtualRegister(RC); 10742 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg) 10743 .addReg(ptrA).addReg(ptrB); 10744 } else { 10745 Ptr1Reg = ptrB; 10746 } 10747 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg) 10748 .addImm(3).addImm(27).addImm(is8bit ? 28 : 27); 10749 if (!isLittleEndian) 10750 BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg) 10751 .addReg(Shift1Reg).addImm(is8bit ? 24 : 16); 10752 if (is64bit) 10753 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg) 10754 .addReg(Ptr1Reg).addImm(0).addImm(61); 10755 else 10756 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg) 10757 .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29); 10758 BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg) 10759 .addReg(newval).addReg(ShiftReg); 10760 BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg) 10761 .addReg(oldval).addReg(ShiftReg); 10762 if (is8bit) 10763 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255); 10764 else { 10765 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0); 10766 BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg) 10767 .addReg(Mask3Reg).addImm(65535); 10768 } 10769 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg) 10770 .addReg(Mask2Reg).addReg(ShiftReg); 10771 BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg) 10772 .addReg(NewVal2Reg).addReg(MaskReg); 10773 BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg) 10774 .addReg(OldVal2Reg).addReg(MaskReg); 10775 10776 BB = loop1MBB; 10777 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg) 10778 .addReg(ZeroReg).addReg(PtrReg); 10779 BuildMI(BB, dl, TII->get(PPC::AND),TmpReg) 10780 .addReg(TmpDestReg).addReg(MaskReg); 10781 BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0) 10782 .addReg(TmpReg).addReg(OldVal3Reg); 10783 BuildMI(BB, dl, TII->get(PPC::BCC)) 10784 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB); 10785 BB->addSuccessor(loop2MBB); 10786 BB->addSuccessor(midMBB); 10787 10788 BB = loop2MBB; 10789 BuildMI(BB, dl, TII->get(PPC::ANDC),Tmp2Reg) 10790 .addReg(TmpDestReg).addReg(MaskReg); 10791 BuildMI(BB, dl, TII->get(PPC::OR),Tmp4Reg) 10792 .addReg(Tmp2Reg).addReg(NewVal3Reg); 10793 BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(Tmp4Reg) 10794 .addReg(ZeroReg).addReg(PtrReg); 10795 BuildMI(BB, dl, TII->get(PPC::BCC)) 10796 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB); 10797 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB); 10798 BB->addSuccessor(loop1MBB); 10799 BB->addSuccessor(exitMBB); 10800 10801 BB = midMBB; 10802 BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(TmpDestReg) 10803 .addReg(ZeroReg).addReg(PtrReg); 10804 BB->addSuccessor(exitMBB); 10805 10806 // exitMBB: 10807 // ... 10808 BB = exitMBB; 10809 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW),dest).addReg(TmpReg) 10810 .addReg(ShiftReg); 10811 } else if (MI.getOpcode() == PPC::FADDrtz) { 10812 // This pseudo performs an FADD with rounding mode temporarily forced 10813 // to round-to-zero. We emit this via custom inserter since the FPSCR 10814 // is not modeled at the SelectionDAG level. 10815 unsigned Dest = MI.getOperand(0).getReg(); 10816 unsigned Src1 = MI.getOperand(1).getReg(); 10817 unsigned Src2 = MI.getOperand(2).getReg(); 10818 DebugLoc dl = MI.getDebugLoc(); 10819 10820 MachineRegisterInfo &RegInfo = F->getRegInfo(); 10821 unsigned MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass); 10822 10823 // Save FPSCR value. 10824 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg); 10825 10826 // Set rounding mode to round-to-zero. 10827 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1)).addImm(31); 10828 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0)).addImm(30); 10829 10830 // Perform addition. 10831 BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest).addReg(Src1).addReg(Src2); 10832 10833 // Restore FPSCR value. 10834 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSFb)).addImm(1).addReg(MFFSReg); 10835 } else if (MI.getOpcode() == PPC::ANDIo_1_EQ_BIT || 10836 MI.getOpcode() == PPC::ANDIo_1_GT_BIT || 10837 MI.getOpcode() == PPC::ANDIo_1_EQ_BIT8 || 10838 MI.getOpcode() == PPC::ANDIo_1_GT_BIT8) { 10839 unsigned Opcode = (MI.getOpcode() == PPC::ANDIo_1_EQ_BIT8 || 10840 MI.getOpcode() == PPC::ANDIo_1_GT_BIT8) 10841 ? PPC::ANDIo8 10842 : PPC::ANDIo; 10843 bool isEQ = (MI.getOpcode() == PPC::ANDIo_1_EQ_BIT || 10844 MI.getOpcode() == PPC::ANDIo_1_EQ_BIT8); 10845 10846 MachineRegisterInfo &RegInfo = F->getRegInfo(); 10847 unsigned Dest = RegInfo.createVirtualRegister(Opcode == PPC::ANDIo ? 10848 &PPC::GPRCRegClass : 10849 &PPC::G8RCRegClass); 10850 10851 DebugLoc dl = MI.getDebugLoc(); 10852 BuildMI(*BB, MI, dl, TII->get(Opcode), Dest) 10853 .addReg(MI.getOperand(1).getReg()) 10854 .addImm(1); 10855 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), 10856 MI.getOperand(0).getReg()) 10857 .addReg(isEQ ? PPC::CR0EQ : PPC::CR0GT); 10858 } else if (MI.getOpcode() == PPC::TCHECK_RET) { 10859 DebugLoc Dl = MI.getDebugLoc(); 10860 MachineRegisterInfo &RegInfo = F->getRegInfo(); 10861 unsigned CRReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass); 10862 BuildMI(*BB, MI, Dl, TII->get(PPC::TCHECK), CRReg); 10863 return BB; 10864 } else { 10865 llvm_unreachable("Unexpected instr type to insert"); 10866 } 10867 10868 MI.eraseFromParent(); // The pseudo instruction is gone now. 10869 return BB; 10870 } 10871 10872 //===----------------------------------------------------------------------===// 10873 // Target Optimization Hooks 10874 //===----------------------------------------------------------------------===// 10875 10876 static int getEstimateRefinementSteps(EVT VT, const PPCSubtarget &Subtarget) { 10877 // For the estimates, convergence is quadratic, so we essentially double the 10878 // number of digits correct after every iteration. For both FRE and FRSQRTE, 10879 // the minimum architected relative accuracy is 2^-5. When hasRecipPrec(), 10880 // this is 2^-14. IEEE float has 23 digits and double has 52 digits. 10881 int RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3; 10882 if (VT.getScalarType() == MVT::f64) 10883 RefinementSteps++; 10884 return RefinementSteps; 10885 } 10886 10887 SDValue PPCTargetLowering::getSqrtEstimate(SDValue Operand, SelectionDAG &DAG, 10888 int Enabled, int &RefinementSteps, 10889 bool &UseOneConstNR, 10890 bool Reciprocal) const { 10891 EVT VT = Operand.getValueType(); 10892 if ((VT == MVT::f32 && Subtarget.hasFRSQRTES()) || 10893 (VT == MVT::f64 && Subtarget.hasFRSQRTE()) || 10894 (VT == MVT::v4f32 && Subtarget.hasAltivec()) || 10895 (VT == MVT::v2f64 && Subtarget.hasVSX()) || 10896 (VT == MVT::v4f32 && Subtarget.hasQPX()) || 10897 (VT == MVT::v4f64 && Subtarget.hasQPX())) { 10898 if (RefinementSteps == ReciprocalEstimate::Unspecified) 10899 RefinementSteps = getEstimateRefinementSteps(VT, Subtarget); 10900 10901 UseOneConstNR = true; 10902 return DAG.getNode(PPCISD::FRSQRTE, SDLoc(Operand), VT, Operand); 10903 } 10904 return SDValue(); 10905 } 10906 10907 SDValue PPCTargetLowering::getRecipEstimate(SDValue Operand, SelectionDAG &DAG, 10908 int Enabled, 10909 int &RefinementSteps) const { 10910 EVT VT = Operand.getValueType(); 10911 if ((VT == MVT::f32 && Subtarget.hasFRES()) || 10912 (VT == MVT::f64 && Subtarget.hasFRE()) || 10913 (VT == MVT::v4f32 && Subtarget.hasAltivec()) || 10914 (VT == MVT::v2f64 && Subtarget.hasVSX()) || 10915 (VT == MVT::v4f32 && Subtarget.hasQPX()) || 10916 (VT == MVT::v4f64 && Subtarget.hasQPX())) { 10917 if (RefinementSteps == ReciprocalEstimate::Unspecified) 10918 RefinementSteps = getEstimateRefinementSteps(VT, Subtarget); 10919 return DAG.getNode(PPCISD::FRE, SDLoc(Operand), VT, Operand); 10920 } 10921 return SDValue(); 10922 } 10923 10924 unsigned PPCTargetLowering::combineRepeatedFPDivisors() const { 10925 // Note: This functionality is used only when unsafe-fp-math is enabled, and 10926 // on cores with reciprocal estimates (which are used when unsafe-fp-math is 10927 // enabled for division), this functionality is redundant with the default 10928 // combiner logic (once the division -> reciprocal/multiply transformation 10929 // has taken place). As a result, this matters more for older cores than for 10930 // newer ones. 10931 10932 // Combine multiple FDIVs with the same divisor into multiple FMULs by the 10933 // reciprocal if there are two or more FDIVs (for embedded cores with only 10934 // one FP pipeline) for three or more FDIVs (for generic OOO cores). 10935 switch (Subtarget.getDarwinDirective()) { 10936 default: 10937 return 3; 10938 case PPC::DIR_440: 10939 case PPC::DIR_A2: 10940 case PPC::DIR_E500: 10941 case PPC::DIR_E500mc: 10942 case PPC::DIR_E5500: 10943 return 2; 10944 } 10945 } 10946 10947 // isConsecutiveLSLoc needs to work even if all adds have not yet been 10948 // collapsed, and so we need to look through chains of them. 10949 static void getBaseWithConstantOffset(SDValue Loc, SDValue &Base, 10950 int64_t& Offset, SelectionDAG &DAG) { 10951 if (DAG.isBaseWithConstantOffset(Loc)) { 10952 Base = Loc.getOperand(0); 10953 Offset += cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue(); 10954 10955 // The base might itself be a base plus an offset, and if so, accumulate 10956 // that as well. 10957 getBaseWithConstantOffset(Loc.getOperand(0), Base, Offset, DAG); 10958 } 10959 } 10960 10961 static bool isConsecutiveLSLoc(SDValue Loc, EVT VT, LSBaseSDNode *Base, 10962 unsigned Bytes, int Dist, 10963 SelectionDAG &DAG) { 10964 if (VT.getSizeInBits() / 8 != Bytes) 10965 return false; 10966 10967 SDValue BaseLoc = Base->getBasePtr(); 10968 if (Loc.getOpcode() == ISD::FrameIndex) { 10969 if (BaseLoc.getOpcode() != ISD::FrameIndex) 10970 return false; 10971 const MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 10972 int FI = cast<FrameIndexSDNode>(Loc)->getIndex(); 10973 int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex(); 10974 int FS = MFI.getObjectSize(FI); 10975 int BFS = MFI.getObjectSize(BFI); 10976 if (FS != BFS || FS != (int)Bytes) return false; 10977 return MFI.getObjectOffset(FI) == (MFI.getObjectOffset(BFI) + Dist*Bytes); 10978 } 10979 10980 SDValue Base1 = Loc, Base2 = BaseLoc; 10981 int64_t Offset1 = 0, Offset2 = 0; 10982 getBaseWithConstantOffset(Loc, Base1, Offset1, DAG); 10983 getBaseWithConstantOffset(BaseLoc, Base2, Offset2, DAG); 10984 if (Base1 == Base2 && Offset1 == (Offset2 + Dist * Bytes)) 10985 return true; 10986 10987 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10988 const GlobalValue *GV1 = nullptr; 10989 const GlobalValue *GV2 = nullptr; 10990 Offset1 = 0; 10991 Offset2 = 0; 10992 bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1); 10993 bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2); 10994 if (isGA1 && isGA2 && GV1 == GV2) 10995 return Offset1 == (Offset2 + Dist*Bytes); 10996 return false; 10997 } 10998 10999 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does 11000 // not enforce equality of the chain operands. 11001 static bool isConsecutiveLS(SDNode *N, LSBaseSDNode *Base, 11002 unsigned Bytes, int Dist, 11003 SelectionDAG &DAG) { 11004 if (LSBaseSDNode *LS = dyn_cast<LSBaseSDNode>(N)) { 11005 EVT VT = LS->getMemoryVT(); 11006 SDValue Loc = LS->getBasePtr(); 11007 return isConsecutiveLSLoc(Loc, VT, Base, Bytes, Dist, DAG); 11008 } 11009 11010 if (N->getOpcode() == ISD::INTRINSIC_W_CHAIN) { 11011 EVT VT; 11012 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 11013 default: return false; 11014 case Intrinsic::ppc_qpx_qvlfd: 11015 case Intrinsic::ppc_qpx_qvlfda: 11016 VT = MVT::v4f64; 11017 break; 11018 case Intrinsic::ppc_qpx_qvlfs: 11019 case Intrinsic::ppc_qpx_qvlfsa: 11020 VT = MVT::v4f32; 11021 break; 11022 case Intrinsic::ppc_qpx_qvlfcd: 11023 case Intrinsic::ppc_qpx_qvlfcda: 11024 VT = MVT::v2f64; 11025 break; 11026 case Intrinsic::ppc_qpx_qvlfcs: 11027 case Intrinsic::ppc_qpx_qvlfcsa: 11028 VT = MVT::v2f32; 11029 break; 11030 case Intrinsic::ppc_qpx_qvlfiwa: 11031 case Intrinsic::ppc_qpx_qvlfiwz: 11032 case Intrinsic::ppc_altivec_lvx: 11033 case Intrinsic::ppc_altivec_lvxl: 11034 case Intrinsic::ppc_vsx_lxvw4x: 11035 case Intrinsic::ppc_vsx_lxvw4x_be: 11036 VT = MVT::v4i32; 11037 break; 11038 case Intrinsic::ppc_vsx_lxvd2x: 11039 case Intrinsic::ppc_vsx_lxvd2x_be: 11040 VT = MVT::v2f64; 11041 break; 11042 case Intrinsic::ppc_altivec_lvebx: 11043 VT = MVT::i8; 11044 break; 11045 case Intrinsic::ppc_altivec_lvehx: 11046 VT = MVT::i16; 11047 break; 11048 case Intrinsic::ppc_altivec_lvewx: 11049 VT = MVT::i32; 11050 break; 11051 } 11052 11053 return isConsecutiveLSLoc(N->getOperand(2), VT, Base, Bytes, Dist, DAG); 11054 } 11055 11056 if (N->getOpcode() == ISD::INTRINSIC_VOID) { 11057 EVT VT; 11058 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 11059 default: return false; 11060 case Intrinsic::ppc_qpx_qvstfd: 11061 case Intrinsic::ppc_qpx_qvstfda: 11062 VT = MVT::v4f64; 11063 break; 11064 case Intrinsic::ppc_qpx_qvstfs: 11065 case Intrinsic::ppc_qpx_qvstfsa: 11066 VT = MVT::v4f32; 11067 break; 11068 case Intrinsic::ppc_qpx_qvstfcd: 11069 case Intrinsic::ppc_qpx_qvstfcda: 11070 VT = MVT::v2f64; 11071 break; 11072 case Intrinsic::ppc_qpx_qvstfcs: 11073 case Intrinsic::ppc_qpx_qvstfcsa: 11074 VT = MVT::v2f32; 11075 break; 11076 case Intrinsic::ppc_qpx_qvstfiw: 11077 case Intrinsic::ppc_qpx_qvstfiwa: 11078 case Intrinsic::ppc_altivec_stvx: 11079 case Intrinsic::ppc_altivec_stvxl: 11080 case Intrinsic::ppc_vsx_stxvw4x: 11081 VT = MVT::v4i32; 11082 break; 11083 case Intrinsic::ppc_vsx_stxvd2x: 11084 VT = MVT::v2f64; 11085 break; 11086 case Intrinsic::ppc_vsx_stxvw4x_be: 11087 VT = MVT::v4i32; 11088 break; 11089 case Intrinsic::ppc_vsx_stxvd2x_be: 11090 VT = MVT::v2f64; 11091 break; 11092 case Intrinsic::ppc_altivec_stvebx: 11093 VT = MVT::i8; 11094 break; 11095 case Intrinsic::ppc_altivec_stvehx: 11096 VT = MVT::i16; 11097 break; 11098 case Intrinsic::ppc_altivec_stvewx: 11099 VT = MVT::i32; 11100 break; 11101 } 11102 11103 return isConsecutiveLSLoc(N->getOperand(3), VT, Base, Bytes, Dist, DAG); 11104 } 11105 11106 return false; 11107 } 11108 11109 // Return true is there is a nearyby consecutive load to the one provided 11110 // (regardless of alignment). We search up and down the chain, looking though 11111 // token factors and other loads (but nothing else). As a result, a true result 11112 // indicates that it is safe to create a new consecutive load adjacent to the 11113 // load provided. 11114 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) { 11115 SDValue Chain = LD->getChain(); 11116 EVT VT = LD->getMemoryVT(); 11117 11118 SmallSet<SDNode *, 16> LoadRoots; 11119 SmallVector<SDNode *, 8> Queue(1, Chain.getNode()); 11120 SmallSet<SDNode *, 16> Visited; 11121 11122 // First, search up the chain, branching to follow all token-factor operands. 11123 // If we find a consecutive load, then we're done, otherwise, record all 11124 // nodes just above the top-level loads and token factors. 11125 while (!Queue.empty()) { 11126 SDNode *ChainNext = Queue.pop_back_val(); 11127 if (!Visited.insert(ChainNext).second) 11128 continue; 11129 11130 if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(ChainNext)) { 11131 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG)) 11132 return true; 11133 11134 if (!Visited.count(ChainLD->getChain().getNode())) 11135 Queue.push_back(ChainLD->getChain().getNode()); 11136 } else if (ChainNext->getOpcode() == ISD::TokenFactor) { 11137 for (const SDUse &O : ChainNext->ops()) 11138 if (!Visited.count(O.getNode())) 11139 Queue.push_back(O.getNode()); 11140 } else 11141 LoadRoots.insert(ChainNext); 11142 } 11143 11144 // Second, search down the chain, starting from the top-level nodes recorded 11145 // in the first phase. These top-level nodes are the nodes just above all 11146 // loads and token factors. Starting with their uses, recursively look though 11147 // all loads (just the chain uses) and token factors to find a consecutive 11148 // load. 11149 Visited.clear(); 11150 Queue.clear(); 11151 11152 for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(), 11153 IE = LoadRoots.end(); I != IE; ++I) { 11154 Queue.push_back(*I); 11155 11156 while (!Queue.empty()) { 11157 SDNode *LoadRoot = Queue.pop_back_val(); 11158 if (!Visited.insert(LoadRoot).second) 11159 continue; 11160 11161 if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(LoadRoot)) 11162 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG)) 11163 return true; 11164 11165 for (SDNode::use_iterator UI = LoadRoot->use_begin(), 11166 UE = LoadRoot->use_end(); UI != UE; ++UI) 11167 if (((isa<MemSDNode>(*UI) && 11168 cast<MemSDNode>(*UI)->getChain().getNode() == LoadRoot) || 11169 UI->getOpcode() == ISD::TokenFactor) && !Visited.count(*UI)) 11170 Queue.push_back(*UI); 11171 } 11172 } 11173 11174 return false; 11175 } 11176 11177 /// This function is called when we have proved that a SETCC node can be replaced 11178 /// by subtraction (and other supporting instructions) so that the result of 11179 /// comparison is kept in a GPR instead of CR. This function is purely for 11180 /// codegen purposes and has some flags to guide the codegen process. 11181 static SDValue generateEquivalentSub(SDNode *N, int Size, bool Complement, 11182 bool Swap, SDLoc &DL, SelectionDAG &DAG) { 11183 assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected."); 11184 11185 // Zero extend the operands to the largest legal integer. Originally, they 11186 // must be of a strictly smaller size. 11187 auto Op0 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(0), 11188 DAG.getConstant(Size, DL, MVT::i32)); 11189 auto Op1 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1), 11190 DAG.getConstant(Size, DL, MVT::i32)); 11191 11192 // Swap if needed. Depends on the condition code. 11193 if (Swap) 11194 std::swap(Op0, Op1); 11195 11196 // Subtract extended integers. 11197 auto SubNode = DAG.getNode(ISD::SUB, DL, MVT::i64, Op0, Op1); 11198 11199 // Move the sign bit to the least significant position and zero out the rest. 11200 // Now the least significant bit carries the result of original comparison. 11201 auto Shifted = DAG.getNode(ISD::SRL, DL, MVT::i64, SubNode, 11202 DAG.getConstant(Size - 1, DL, MVT::i32)); 11203 auto Final = Shifted; 11204 11205 // Complement the result if needed. Based on the condition code. 11206 if (Complement) 11207 Final = DAG.getNode(ISD::XOR, DL, MVT::i64, Shifted, 11208 DAG.getConstant(1, DL, MVT::i64)); 11209 11210 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Final); 11211 } 11212 11213 SDValue PPCTargetLowering::ConvertSETCCToSubtract(SDNode *N, 11214 DAGCombinerInfo &DCI) const { 11215 assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected."); 11216 11217 SelectionDAG &DAG = DCI.DAG; 11218 SDLoc DL(N); 11219 11220 // Size of integers being compared has a critical role in the following 11221 // analysis, so we prefer to do this when all types are legal. 11222 if (!DCI.isAfterLegalizeDAG()) 11223 return SDValue(); 11224 11225 // If all users of SETCC extend its value to a legal integer type 11226 // then we replace SETCC with a subtraction 11227 for (SDNode::use_iterator UI = N->use_begin(), 11228 UE = N->use_end(); UI != UE; ++UI) { 11229 if (UI->getOpcode() != ISD::ZERO_EXTEND) 11230 return SDValue(); 11231 } 11232 11233 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 11234 auto OpSize = N->getOperand(0).getValueSizeInBits(); 11235 11236 unsigned Size = DAG.getDataLayout().getLargestLegalIntTypeSizeInBits(); 11237 11238 if (OpSize < Size) { 11239 switch (CC) { 11240 default: break; 11241 case ISD::SETULT: 11242 return generateEquivalentSub(N, Size, false, false, DL, DAG); 11243 case ISD::SETULE: 11244 return generateEquivalentSub(N, Size, true, true, DL, DAG); 11245 case ISD::SETUGT: 11246 return generateEquivalentSub(N, Size, false, true, DL, DAG); 11247 case ISD::SETUGE: 11248 return generateEquivalentSub(N, Size, true, false, DL, DAG); 11249 } 11250 } 11251 11252 return SDValue(); 11253 } 11254 11255 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N, 11256 DAGCombinerInfo &DCI) const { 11257 SelectionDAG &DAG = DCI.DAG; 11258 SDLoc dl(N); 11259 11260 assert(Subtarget.useCRBits() && "Expecting to be tracking CR bits"); 11261 // If we're tracking CR bits, we need to be careful that we don't have: 11262 // trunc(binary-ops(zext(x), zext(y))) 11263 // or 11264 // trunc(binary-ops(binary-ops(zext(x), zext(y)), ...) 11265 // such that we're unnecessarily moving things into GPRs when it would be 11266 // better to keep them in CR bits. 11267 11268 // Note that trunc here can be an actual i1 trunc, or can be the effective 11269 // truncation that comes from a setcc or select_cc. 11270 if (N->getOpcode() == ISD::TRUNCATE && 11271 N->getValueType(0) != MVT::i1) 11272 return SDValue(); 11273 11274 if (N->getOperand(0).getValueType() != MVT::i32 && 11275 N->getOperand(0).getValueType() != MVT::i64) 11276 return SDValue(); 11277 11278 if (N->getOpcode() == ISD::SETCC || 11279 N->getOpcode() == ISD::SELECT_CC) { 11280 // If we're looking at a comparison, then we need to make sure that the 11281 // high bits (all except for the first) don't matter the result. 11282 ISD::CondCode CC = 11283 cast<CondCodeSDNode>(N->getOperand( 11284 N->getOpcode() == ISD::SETCC ? 2 : 4))->get(); 11285 unsigned OpBits = N->getOperand(0).getValueSizeInBits(); 11286 11287 if (ISD::isSignedIntSetCC(CC)) { 11288 if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits || 11289 DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits) 11290 return SDValue(); 11291 } else if (ISD::isUnsignedIntSetCC(CC)) { 11292 if (!DAG.MaskedValueIsZero(N->getOperand(0), 11293 APInt::getHighBitsSet(OpBits, OpBits-1)) || 11294 !DAG.MaskedValueIsZero(N->getOperand(1), 11295 APInt::getHighBitsSet(OpBits, OpBits-1))) 11296 return (N->getOpcode() == ISD::SETCC ? ConvertSETCCToSubtract(N, DCI) 11297 : SDValue()); 11298 } else { 11299 // This is neither a signed nor an unsigned comparison, just make sure 11300 // that the high bits are equal. 11301 KnownBits Op1Known, Op2Known; 11302 DAG.computeKnownBits(N->getOperand(0), Op1Known); 11303 DAG.computeKnownBits(N->getOperand(1), Op2Known); 11304 11305 // We don't really care about what is known about the first bit (if 11306 // anything), so clear it in all masks prior to comparing them. 11307 Op1Known.Zero.clearBit(0); Op1Known.One.clearBit(0); 11308 Op2Known.Zero.clearBit(0); Op2Known.One.clearBit(0); 11309 11310 if (Op1Known.Zero != Op2Known.Zero || Op1Known.One != Op2Known.One) 11311 return SDValue(); 11312 } 11313 } 11314 11315 // We now know that the higher-order bits are irrelevant, we just need to 11316 // make sure that all of the intermediate operations are bit operations, and 11317 // all inputs are extensions. 11318 if (N->getOperand(0).getOpcode() != ISD::AND && 11319 N->getOperand(0).getOpcode() != ISD::OR && 11320 N->getOperand(0).getOpcode() != ISD::XOR && 11321 N->getOperand(0).getOpcode() != ISD::SELECT && 11322 N->getOperand(0).getOpcode() != ISD::SELECT_CC && 11323 N->getOperand(0).getOpcode() != ISD::TRUNCATE && 11324 N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND && 11325 N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND && 11326 N->getOperand(0).getOpcode() != ISD::ANY_EXTEND) 11327 return SDValue(); 11328 11329 if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) && 11330 N->getOperand(1).getOpcode() != ISD::AND && 11331 N->getOperand(1).getOpcode() != ISD::OR && 11332 N->getOperand(1).getOpcode() != ISD::XOR && 11333 N->getOperand(1).getOpcode() != ISD::SELECT && 11334 N->getOperand(1).getOpcode() != ISD::SELECT_CC && 11335 N->getOperand(1).getOpcode() != ISD::TRUNCATE && 11336 N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND && 11337 N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND && 11338 N->getOperand(1).getOpcode() != ISD::ANY_EXTEND) 11339 return SDValue(); 11340 11341 SmallVector<SDValue, 4> Inputs; 11342 SmallVector<SDValue, 8> BinOps, PromOps; 11343 SmallPtrSet<SDNode *, 16> Visited; 11344 11345 for (unsigned i = 0; i < 2; ++i) { 11346 if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND || 11347 N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND || 11348 N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) && 11349 N->getOperand(i).getOperand(0).getValueType() == MVT::i1) || 11350 isa<ConstantSDNode>(N->getOperand(i))) 11351 Inputs.push_back(N->getOperand(i)); 11352 else 11353 BinOps.push_back(N->getOperand(i)); 11354 11355 if (N->getOpcode() == ISD::TRUNCATE) 11356 break; 11357 } 11358 11359 // Visit all inputs, collect all binary operations (and, or, xor and 11360 // select) that are all fed by extensions. 11361 while (!BinOps.empty()) { 11362 SDValue BinOp = BinOps.back(); 11363 BinOps.pop_back(); 11364 11365 if (!Visited.insert(BinOp.getNode()).second) 11366 continue; 11367 11368 PromOps.push_back(BinOp); 11369 11370 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) { 11371 // The condition of the select is not promoted. 11372 if (BinOp.getOpcode() == ISD::SELECT && i == 0) 11373 continue; 11374 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3) 11375 continue; 11376 11377 if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND || 11378 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND || 11379 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) && 11380 BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) || 11381 isa<ConstantSDNode>(BinOp.getOperand(i))) { 11382 Inputs.push_back(BinOp.getOperand(i)); 11383 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND || 11384 BinOp.getOperand(i).getOpcode() == ISD::OR || 11385 BinOp.getOperand(i).getOpcode() == ISD::XOR || 11386 BinOp.getOperand(i).getOpcode() == ISD::SELECT || 11387 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC || 11388 BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE || 11389 BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND || 11390 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND || 11391 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) { 11392 BinOps.push_back(BinOp.getOperand(i)); 11393 } else { 11394 // We have an input that is not an extension or another binary 11395 // operation; we'll abort this transformation. 11396 return SDValue(); 11397 } 11398 } 11399 } 11400 11401 // Make sure that this is a self-contained cluster of operations (which 11402 // is not quite the same thing as saying that everything has only one 11403 // use). 11404 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 11405 if (isa<ConstantSDNode>(Inputs[i])) 11406 continue; 11407 11408 for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(), 11409 UE = Inputs[i].getNode()->use_end(); 11410 UI != UE; ++UI) { 11411 SDNode *User = *UI; 11412 if (User != N && !Visited.count(User)) 11413 return SDValue(); 11414 11415 // Make sure that we're not going to promote the non-output-value 11416 // operand(s) or SELECT or SELECT_CC. 11417 // FIXME: Although we could sometimes handle this, and it does occur in 11418 // practice that one of the condition inputs to the select is also one of 11419 // the outputs, we currently can't deal with this. 11420 if (User->getOpcode() == ISD::SELECT) { 11421 if (User->getOperand(0) == Inputs[i]) 11422 return SDValue(); 11423 } else if (User->getOpcode() == ISD::SELECT_CC) { 11424 if (User->getOperand(0) == Inputs[i] || 11425 User->getOperand(1) == Inputs[i]) 11426 return SDValue(); 11427 } 11428 } 11429 } 11430 11431 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) { 11432 for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(), 11433 UE = PromOps[i].getNode()->use_end(); 11434 UI != UE; ++UI) { 11435 SDNode *User = *UI; 11436 if (User != N && !Visited.count(User)) 11437 return SDValue(); 11438 11439 // Make sure that we're not going to promote the non-output-value 11440 // operand(s) or SELECT or SELECT_CC. 11441 // FIXME: Although we could sometimes handle this, and it does occur in 11442 // practice that one of the condition inputs to the select is also one of 11443 // the outputs, we currently can't deal with this. 11444 if (User->getOpcode() == ISD::SELECT) { 11445 if (User->getOperand(0) == PromOps[i]) 11446 return SDValue(); 11447 } else if (User->getOpcode() == ISD::SELECT_CC) { 11448 if (User->getOperand(0) == PromOps[i] || 11449 User->getOperand(1) == PromOps[i]) 11450 return SDValue(); 11451 } 11452 } 11453 } 11454 11455 // Replace all inputs with the extension operand. 11456 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 11457 // Constants may have users outside the cluster of to-be-promoted nodes, 11458 // and so we need to replace those as we do the promotions. 11459 if (isa<ConstantSDNode>(Inputs[i])) 11460 continue; 11461 else 11462 DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0)); 11463 } 11464 11465 std::list<HandleSDNode> PromOpHandles; 11466 for (auto &PromOp : PromOps) 11467 PromOpHandles.emplace_back(PromOp); 11468 11469 // Replace all operations (these are all the same, but have a different 11470 // (i1) return type). DAG.getNode will validate that the types of 11471 // a binary operator match, so go through the list in reverse so that 11472 // we've likely promoted both operands first. Any intermediate truncations or 11473 // extensions disappear. 11474 while (!PromOpHandles.empty()) { 11475 SDValue PromOp = PromOpHandles.back().getValue(); 11476 PromOpHandles.pop_back(); 11477 11478 if (PromOp.getOpcode() == ISD::TRUNCATE || 11479 PromOp.getOpcode() == ISD::SIGN_EXTEND || 11480 PromOp.getOpcode() == ISD::ZERO_EXTEND || 11481 PromOp.getOpcode() == ISD::ANY_EXTEND) { 11482 if (!isa<ConstantSDNode>(PromOp.getOperand(0)) && 11483 PromOp.getOperand(0).getValueType() != MVT::i1) { 11484 // The operand is not yet ready (see comment below). 11485 PromOpHandles.emplace_front(PromOp); 11486 continue; 11487 } 11488 11489 SDValue RepValue = PromOp.getOperand(0); 11490 if (isa<ConstantSDNode>(RepValue)) 11491 RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue); 11492 11493 DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue); 11494 continue; 11495 } 11496 11497 unsigned C; 11498 switch (PromOp.getOpcode()) { 11499 default: C = 0; break; 11500 case ISD::SELECT: C = 1; break; 11501 case ISD::SELECT_CC: C = 2; break; 11502 } 11503 11504 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) && 11505 PromOp.getOperand(C).getValueType() != MVT::i1) || 11506 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) && 11507 PromOp.getOperand(C+1).getValueType() != MVT::i1)) { 11508 // The to-be-promoted operands of this node have not yet been 11509 // promoted (this should be rare because we're going through the 11510 // list backward, but if one of the operands has several users in 11511 // this cluster of to-be-promoted nodes, it is possible). 11512 PromOpHandles.emplace_front(PromOp); 11513 continue; 11514 } 11515 11516 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(), 11517 PromOp.getNode()->op_end()); 11518 11519 // If there are any constant inputs, make sure they're replaced now. 11520 for (unsigned i = 0; i < 2; ++i) 11521 if (isa<ConstantSDNode>(Ops[C+i])) 11522 Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]); 11523 11524 DAG.ReplaceAllUsesOfValueWith(PromOp, 11525 DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops)); 11526 } 11527 11528 // Now we're left with the initial truncation itself. 11529 if (N->getOpcode() == ISD::TRUNCATE) 11530 return N->getOperand(0); 11531 11532 // Otherwise, this is a comparison. The operands to be compared have just 11533 // changed type (to i1), but everything else is the same. 11534 return SDValue(N, 0); 11535 } 11536 11537 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N, 11538 DAGCombinerInfo &DCI) const { 11539 SelectionDAG &DAG = DCI.DAG; 11540 SDLoc dl(N); 11541 11542 // If we're tracking CR bits, we need to be careful that we don't have: 11543 // zext(binary-ops(trunc(x), trunc(y))) 11544 // or 11545 // zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...) 11546 // such that we're unnecessarily moving things into CR bits that can more 11547 // efficiently stay in GPRs. Note that if we're not certain that the high 11548 // bits are set as required by the final extension, we still may need to do 11549 // some masking to get the proper behavior. 11550 11551 // This same functionality is important on PPC64 when dealing with 11552 // 32-to-64-bit extensions; these occur often when 32-bit values are used as 11553 // the return values of functions. Because it is so similar, it is handled 11554 // here as well. 11555 11556 if (N->getValueType(0) != MVT::i32 && 11557 N->getValueType(0) != MVT::i64) 11558 return SDValue(); 11559 11560 if (!((N->getOperand(0).getValueType() == MVT::i1 && Subtarget.useCRBits()) || 11561 (N->getOperand(0).getValueType() == MVT::i32 && Subtarget.isPPC64()))) 11562 return SDValue(); 11563 11564 if (N->getOperand(0).getOpcode() != ISD::AND && 11565 N->getOperand(0).getOpcode() != ISD::OR && 11566 N->getOperand(0).getOpcode() != ISD::XOR && 11567 N->getOperand(0).getOpcode() != ISD::SELECT && 11568 N->getOperand(0).getOpcode() != ISD::SELECT_CC) 11569 return SDValue(); 11570 11571 SmallVector<SDValue, 4> Inputs; 11572 SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps; 11573 SmallPtrSet<SDNode *, 16> Visited; 11574 11575 // Visit all inputs, collect all binary operations (and, or, xor and 11576 // select) that are all fed by truncations. 11577 while (!BinOps.empty()) { 11578 SDValue BinOp = BinOps.back(); 11579 BinOps.pop_back(); 11580 11581 if (!Visited.insert(BinOp.getNode()).second) 11582 continue; 11583 11584 PromOps.push_back(BinOp); 11585 11586 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) { 11587 // The condition of the select is not promoted. 11588 if (BinOp.getOpcode() == ISD::SELECT && i == 0) 11589 continue; 11590 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3) 11591 continue; 11592 11593 if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE || 11594 isa<ConstantSDNode>(BinOp.getOperand(i))) { 11595 Inputs.push_back(BinOp.getOperand(i)); 11596 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND || 11597 BinOp.getOperand(i).getOpcode() == ISD::OR || 11598 BinOp.getOperand(i).getOpcode() == ISD::XOR || 11599 BinOp.getOperand(i).getOpcode() == ISD::SELECT || 11600 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) { 11601 BinOps.push_back(BinOp.getOperand(i)); 11602 } else { 11603 // We have an input that is not a truncation or another binary 11604 // operation; we'll abort this transformation. 11605 return SDValue(); 11606 } 11607 } 11608 } 11609 11610 // The operands of a select that must be truncated when the select is 11611 // promoted because the operand is actually part of the to-be-promoted set. 11612 DenseMap<SDNode *, EVT> SelectTruncOp[2]; 11613 11614 // Make sure that this is a self-contained cluster of operations (which 11615 // is not quite the same thing as saying that everything has only one 11616 // use). 11617 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 11618 if (isa<ConstantSDNode>(Inputs[i])) 11619 continue; 11620 11621 for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(), 11622 UE = Inputs[i].getNode()->use_end(); 11623 UI != UE; ++UI) { 11624 SDNode *User = *UI; 11625 if (User != N && !Visited.count(User)) 11626 return SDValue(); 11627 11628 // If we're going to promote the non-output-value operand(s) or SELECT or 11629 // SELECT_CC, record them for truncation. 11630 if (User->getOpcode() == ISD::SELECT) { 11631 if (User->getOperand(0) == Inputs[i]) 11632 SelectTruncOp[0].insert(std::make_pair(User, 11633 User->getOperand(0).getValueType())); 11634 } else if (User->getOpcode() == ISD::SELECT_CC) { 11635 if (User->getOperand(0) == Inputs[i]) 11636 SelectTruncOp[0].insert(std::make_pair(User, 11637 User->getOperand(0).getValueType())); 11638 if (User->getOperand(1) == Inputs[i]) 11639 SelectTruncOp[1].insert(std::make_pair(User, 11640 User->getOperand(1).getValueType())); 11641 } 11642 } 11643 } 11644 11645 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) { 11646 for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(), 11647 UE = PromOps[i].getNode()->use_end(); 11648 UI != UE; ++UI) { 11649 SDNode *User = *UI; 11650 if (User != N && !Visited.count(User)) 11651 return SDValue(); 11652 11653 // If we're going to promote the non-output-value operand(s) or SELECT or 11654 // SELECT_CC, record them for truncation. 11655 if (User->getOpcode() == ISD::SELECT) { 11656 if (User->getOperand(0) == PromOps[i]) 11657 SelectTruncOp[0].insert(std::make_pair(User, 11658 User->getOperand(0).getValueType())); 11659 } else if (User->getOpcode() == ISD::SELECT_CC) { 11660 if (User->getOperand(0) == PromOps[i]) 11661 SelectTruncOp[0].insert(std::make_pair(User, 11662 User->getOperand(0).getValueType())); 11663 if (User->getOperand(1) == PromOps[i]) 11664 SelectTruncOp[1].insert(std::make_pair(User, 11665 User->getOperand(1).getValueType())); 11666 } 11667 } 11668 } 11669 11670 unsigned PromBits = N->getOperand(0).getValueSizeInBits(); 11671 bool ReallyNeedsExt = false; 11672 if (N->getOpcode() != ISD::ANY_EXTEND) { 11673 // If all of the inputs are not already sign/zero extended, then 11674 // we'll still need to do that at the end. 11675 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 11676 if (isa<ConstantSDNode>(Inputs[i])) 11677 continue; 11678 11679 unsigned OpBits = 11680 Inputs[i].getOperand(0).getValueSizeInBits(); 11681 assert(PromBits < OpBits && "Truncation not to a smaller bit count?"); 11682 11683 if ((N->getOpcode() == ISD::ZERO_EXTEND && 11684 !DAG.MaskedValueIsZero(Inputs[i].getOperand(0), 11685 APInt::getHighBitsSet(OpBits, 11686 OpBits-PromBits))) || 11687 (N->getOpcode() == ISD::SIGN_EXTEND && 11688 DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) < 11689 (OpBits-(PromBits-1)))) { 11690 ReallyNeedsExt = true; 11691 break; 11692 } 11693 } 11694 } 11695 11696 // Replace all inputs, either with the truncation operand, or a 11697 // truncation or extension to the final output type. 11698 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 11699 // Constant inputs need to be replaced with the to-be-promoted nodes that 11700 // use them because they might have users outside of the cluster of 11701 // promoted nodes. 11702 if (isa<ConstantSDNode>(Inputs[i])) 11703 continue; 11704 11705 SDValue InSrc = Inputs[i].getOperand(0); 11706 if (Inputs[i].getValueType() == N->getValueType(0)) 11707 DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc); 11708 else if (N->getOpcode() == ISD::SIGN_EXTEND) 11709 DAG.ReplaceAllUsesOfValueWith(Inputs[i], 11710 DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0))); 11711 else if (N->getOpcode() == ISD::ZERO_EXTEND) 11712 DAG.ReplaceAllUsesOfValueWith(Inputs[i], 11713 DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0))); 11714 else 11715 DAG.ReplaceAllUsesOfValueWith(Inputs[i], 11716 DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0))); 11717 } 11718 11719 std::list<HandleSDNode> PromOpHandles; 11720 for (auto &PromOp : PromOps) 11721 PromOpHandles.emplace_back(PromOp); 11722 11723 // Replace all operations (these are all the same, but have a different 11724 // (promoted) return type). DAG.getNode will validate that the types of 11725 // a binary operator match, so go through the list in reverse so that 11726 // we've likely promoted both operands first. 11727 while (!PromOpHandles.empty()) { 11728 SDValue PromOp = PromOpHandles.back().getValue(); 11729 PromOpHandles.pop_back(); 11730 11731 unsigned C; 11732 switch (PromOp.getOpcode()) { 11733 default: C = 0; break; 11734 case ISD::SELECT: C = 1; break; 11735 case ISD::SELECT_CC: C = 2; break; 11736 } 11737 11738 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) && 11739 PromOp.getOperand(C).getValueType() != N->getValueType(0)) || 11740 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) && 11741 PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) { 11742 // The to-be-promoted operands of this node have not yet been 11743 // promoted (this should be rare because we're going through the 11744 // list backward, but if one of the operands has several users in 11745 // this cluster of to-be-promoted nodes, it is possible). 11746 PromOpHandles.emplace_front(PromOp); 11747 continue; 11748 } 11749 11750 // For SELECT and SELECT_CC nodes, we do a similar check for any 11751 // to-be-promoted comparison inputs. 11752 if (PromOp.getOpcode() == ISD::SELECT || 11753 PromOp.getOpcode() == ISD::SELECT_CC) { 11754 if ((SelectTruncOp[0].count(PromOp.getNode()) && 11755 PromOp.getOperand(0).getValueType() != N->getValueType(0)) || 11756 (SelectTruncOp[1].count(PromOp.getNode()) && 11757 PromOp.getOperand(1).getValueType() != N->getValueType(0))) { 11758 PromOpHandles.emplace_front(PromOp); 11759 continue; 11760 } 11761 } 11762 11763 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(), 11764 PromOp.getNode()->op_end()); 11765 11766 // If this node has constant inputs, then they'll need to be promoted here. 11767 for (unsigned i = 0; i < 2; ++i) { 11768 if (!isa<ConstantSDNode>(Ops[C+i])) 11769 continue; 11770 if (Ops[C+i].getValueType() == N->getValueType(0)) 11771 continue; 11772 11773 if (N->getOpcode() == ISD::SIGN_EXTEND) 11774 Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); 11775 else if (N->getOpcode() == ISD::ZERO_EXTEND) 11776 Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); 11777 else 11778 Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); 11779 } 11780 11781 // If we've promoted the comparison inputs of a SELECT or SELECT_CC, 11782 // truncate them again to the original value type. 11783 if (PromOp.getOpcode() == ISD::SELECT || 11784 PromOp.getOpcode() == ISD::SELECT_CC) { 11785 auto SI0 = SelectTruncOp[0].find(PromOp.getNode()); 11786 if (SI0 != SelectTruncOp[0].end()) 11787 Ops[0] = DAG.getNode(ISD::TRUNCATE, dl, SI0->second, Ops[0]); 11788 auto SI1 = SelectTruncOp[1].find(PromOp.getNode()); 11789 if (SI1 != SelectTruncOp[1].end()) 11790 Ops[1] = DAG.getNode(ISD::TRUNCATE, dl, SI1->second, Ops[1]); 11791 } 11792 11793 DAG.ReplaceAllUsesOfValueWith(PromOp, 11794 DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops)); 11795 } 11796 11797 // Now we're left with the initial extension itself. 11798 if (!ReallyNeedsExt) 11799 return N->getOperand(0); 11800 11801 // To zero extend, just mask off everything except for the first bit (in the 11802 // i1 case). 11803 if (N->getOpcode() == ISD::ZERO_EXTEND) 11804 return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0), 11805 DAG.getConstant(APInt::getLowBitsSet( 11806 N->getValueSizeInBits(0), PromBits), 11807 dl, N->getValueType(0))); 11808 11809 assert(N->getOpcode() == ISD::SIGN_EXTEND && 11810 "Invalid extension type"); 11811 EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0), DAG.getDataLayout()); 11812 SDValue ShiftCst = 11813 DAG.getConstant(N->getValueSizeInBits(0) - PromBits, dl, ShiftAmountTy); 11814 return DAG.getNode( 11815 ISD::SRA, dl, N->getValueType(0), 11816 DAG.getNode(ISD::SHL, dl, N->getValueType(0), N->getOperand(0), ShiftCst), 11817 ShiftCst); 11818 } 11819 11820 SDValue PPCTargetLowering::combineSetCC(SDNode *N, 11821 DAGCombinerInfo &DCI) const { 11822 assert(N->getOpcode() == ISD::SETCC && 11823 "Should be called with a SETCC node"); 11824 11825 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 11826 if (CC == ISD::SETNE || CC == ISD::SETEQ) { 11827 SDValue LHS = N->getOperand(0); 11828 SDValue RHS = N->getOperand(1); 11829 11830 // If there is a '0 - y' pattern, canonicalize the pattern to the RHS. 11831 if (LHS.getOpcode() == ISD::SUB && isNullConstant(LHS.getOperand(0)) && 11832 LHS.hasOneUse()) 11833 std::swap(LHS, RHS); 11834 11835 // x == 0-y --> x+y == 0 11836 // x != 0-y --> x+y != 0 11837 if (RHS.getOpcode() == ISD::SUB && isNullConstant(RHS.getOperand(0)) && 11838 RHS.hasOneUse()) { 11839 SDLoc DL(N); 11840 SelectionDAG &DAG = DCI.DAG; 11841 EVT VT = N->getValueType(0); 11842 EVT OpVT = LHS.getValueType(); 11843 SDValue Add = DAG.getNode(ISD::ADD, DL, OpVT, LHS, RHS.getOperand(1)); 11844 return DAG.getSetCC(DL, VT, Add, DAG.getConstant(0, DL, OpVT), CC); 11845 } 11846 } 11847 11848 return DAGCombineTruncBoolExt(N, DCI); 11849 } 11850 11851 // Is this an extending load from an f32 to an f64? 11852 static bool isFPExtLoad(SDValue Op) { 11853 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op.getNode())) 11854 return LD->getExtensionType() == ISD::EXTLOAD && 11855 Op.getValueType() == MVT::f64; 11856 return false; 11857 } 11858 11859 /// Reduces the number of fp-to-int conversion when building a vector. 11860 /// 11861 /// If this vector is built out of floating to integer conversions, 11862 /// transform it to a vector built out of floating point values followed by a 11863 /// single floating to integer conversion of the vector. 11864 /// Namely (build_vector (fptosi $A), (fptosi $B), ...) 11865 /// becomes (fptosi (build_vector ($A, $B, ...))) 11866 SDValue PPCTargetLowering:: 11867 combineElementTruncationToVectorTruncation(SDNode *N, 11868 DAGCombinerInfo &DCI) const { 11869 assert(N->getOpcode() == ISD::BUILD_VECTOR && 11870 "Should be called with a BUILD_VECTOR node"); 11871 11872 SelectionDAG &DAG = DCI.DAG; 11873 SDLoc dl(N); 11874 11875 SDValue FirstInput = N->getOperand(0); 11876 assert(FirstInput.getOpcode() == PPCISD::MFVSR && 11877 "The input operand must be an fp-to-int conversion."); 11878 11879 // This combine happens after legalization so the fp_to_[su]i nodes are 11880 // already converted to PPCSISD nodes. 11881 unsigned FirstConversion = FirstInput.getOperand(0).getOpcode(); 11882 if (FirstConversion == PPCISD::FCTIDZ || 11883 FirstConversion == PPCISD::FCTIDUZ || 11884 FirstConversion == PPCISD::FCTIWZ || 11885 FirstConversion == PPCISD::FCTIWUZ) { 11886 bool IsSplat = true; 11887 bool Is32Bit = FirstConversion == PPCISD::FCTIWZ || 11888 FirstConversion == PPCISD::FCTIWUZ; 11889 EVT SrcVT = FirstInput.getOperand(0).getValueType(); 11890 SmallVector<SDValue, 4> Ops; 11891 EVT TargetVT = N->getValueType(0); 11892 for (int i = 0, e = N->getNumOperands(); i < e; ++i) { 11893 SDValue NextOp = N->getOperand(i); 11894 if (NextOp.getOpcode() != PPCISD::MFVSR) 11895 return SDValue(); 11896 unsigned NextConversion = NextOp.getOperand(0).getOpcode(); 11897 if (NextConversion != FirstConversion) 11898 return SDValue(); 11899 // If we are converting to 32-bit integers, we need to add an FP_ROUND. 11900 // This is not valid if the input was originally double precision. It is 11901 // also not profitable to do unless this is an extending load in which 11902 // case doing this combine will allow us to combine consecutive loads. 11903 if (Is32Bit && !isFPExtLoad(NextOp.getOperand(0).getOperand(0))) 11904 return SDValue(); 11905 if (N->getOperand(i) != FirstInput) 11906 IsSplat = false; 11907 } 11908 11909 // If this is a splat, we leave it as-is since there will be only a single 11910 // fp-to-int conversion followed by a splat of the integer. This is better 11911 // for 32-bit and smaller ints and neutral for 64-bit ints. 11912 if (IsSplat) 11913 return SDValue(); 11914 11915 // Now that we know we have the right type of node, get its operands 11916 for (int i = 0, e = N->getNumOperands(); i < e; ++i) { 11917 SDValue In = N->getOperand(i).getOperand(0); 11918 if (Is32Bit) { 11919 // For 32-bit values, we need to add an FP_ROUND node (if we made it 11920 // here, we know that all inputs are extending loads so this is safe). 11921 if (In.isUndef()) 11922 Ops.push_back(DAG.getUNDEF(SrcVT)); 11923 else { 11924 SDValue Trunc = DAG.getNode(ISD::FP_ROUND, dl, 11925 MVT::f32, In.getOperand(0), 11926 DAG.getIntPtrConstant(1, dl)); 11927 Ops.push_back(Trunc); 11928 } 11929 } else 11930 Ops.push_back(In.isUndef() ? DAG.getUNDEF(SrcVT) : In.getOperand(0)); 11931 } 11932 11933 unsigned Opcode; 11934 if (FirstConversion == PPCISD::FCTIDZ || 11935 FirstConversion == PPCISD::FCTIWZ) 11936 Opcode = ISD::FP_TO_SINT; 11937 else 11938 Opcode = ISD::FP_TO_UINT; 11939 11940 EVT NewVT = TargetVT == MVT::v2i64 ? MVT::v2f64 : MVT::v4f32; 11941 SDValue BV = DAG.getBuildVector(NewVT, dl, Ops); 11942 return DAG.getNode(Opcode, dl, TargetVT, BV); 11943 } 11944 return SDValue(); 11945 } 11946 11947 /// Reduce the number of loads when building a vector. 11948 /// 11949 /// Building a vector out of multiple loads can be converted to a load 11950 /// of the vector type if the loads are consecutive. If the loads are 11951 /// consecutive but in descending order, a shuffle is added at the end 11952 /// to reorder the vector. 11953 static SDValue combineBVOfConsecutiveLoads(SDNode *N, SelectionDAG &DAG) { 11954 assert(N->getOpcode() == ISD::BUILD_VECTOR && 11955 "Should be called with a BUILD_VECTOR node"); 11956 11957 SDLoc dl(N); 11958 bool InputsAreConsecutiveLoads = true; 11959 bool InputsAreReverseConsecutive = true; 11960 unsigned ElemSize = N->getValueType(0).getScalarSizeInBits() / 8; 11961 SDValue FirstInput = N->getOperand(0); 11962 bool IsRoundOfExtLoad = false; 11963 11964 if (FirstInput.getOpcode() == ISD::FP_ROUND && 11965 FirstInput.getOperand(0).getOpcode() == ISD::LOAD) { 11966 LoadSDNode *LD = dyn_cast<LoadSDNode>(FirstInput.getOperand(0)); 11967 IsRoundOfExtLoad = LD->getExtensionType() == ISD::EXTLOAD; 11968 } 11969 // Not a build vector of (possibly fp_rounded) loads. 11970 if ((!IsRoundOfExtLoad && FirstInput.getOpcode() != ISD::LOAD) || 11971 N->getNumOperands() == 1) 11972 return SDValue(); 11973 11974 for (int i = 1, e = N->getNumOperands(); i < e; ++i) { 11975 // If any inputs are fp_round(extload), they all must be. 11976 if (IsRoundOfExtLoad && N->getOperand(i).getOpcode() != ISD::FP_ROUND) 11977 return SDValue(); 11978 11979 SDValue NextInput = IsRoundOfExtLoad ? N->getOperand(i).getOperand(0) : 11980 N->getOperand(i); 11981 if (NextInput.getOpcode() != ISD::LOAD) 11982 return SDValue(); 11983 11984 SDValue PreviousInput = 11985 IsRoundOfExtLoad ? N->getOperand(i-1).getOperand(0) : N->getOperand(i-1); 11986 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(PreviousInput); 11987 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(NextInput); 11988 11989 // If any inputs are fp_round(extload), they all must be. 11990 if (IsRoundOfExtLoad && LD2->getExtensionType() != ISD::EXTLOAD) 11991 return SDValue(); 11992 11993 if (!isConsecutiveLS(LD2, LD1, ElemSize, 1, DAG)) 11994 InputsAreConsecutiveLoads = false; 11995 if (!isConsecutiveLS(LD1, LD2, ElemSize, 1, DAG)) 11996 InputsAreReverseConsecutive = false; 11997 11998 // Exit early if the loads are neither consecutive nor reverse consecutive. 11999 if (!InputsAreConsecutiveLoads && !InputsAreReverseConsecutive) 12000 return SDValue(); 12001 } 12002 12003 assert(!(InputsAreConsecutiveLoads && InputsAreReverseConsecutive) && 12004 "The loads cannot be both consecutive and reverse consecutive."); 12005 12006 SDValue FirstLoadOp = 12007 IsRoundOfExtLoad ? FirstInput.getOperand(0) : FirstInput; 12008 SDValue LastLoadOp = 12009 IsRoundOfExtLoad ? N->getOperand(N->getNumOperands()-1).getOperand(0) : 12010 N->getOperand(N->getNumOperands()-1); 12011 12012 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(FirstLoadOp); 12013 LoadSDNode *LDL = dyn_cast<LoadSDNode>(LastLoadOp); 12014 if (InputsAreConsecutiveLoads) { 12015 assert(LD1 && "Input needs to be a LoadSDNode."); 12016 return DAG.getLoad(N->getValueType(0), dl, LD1->getChain(), 12017 LD1->getBasePtr(), LD1->getPointerInfo(), 12018 LD1->getAlignment()); 12019 } 12020 if (InputsAreReverseConsecutive) { 12021 assert(LDL && "Input needs to be a LoadSDNode."); 12022 SDValue Load = DAG.getLoad(N->getValueType(0), dl, LDL->getChain(), 12023 LDL->getBasePtr(), LDL->getPointerInfo(), 12024 LDL->getAlignment()); 12025 SmallVector<int, 16> Ops; 12026 for (int i = N->getNumOperands() - 1; i >= 0; i--) 12027 Ops.push_back(i); 12028 12029 return DAG.getVectorShuffle(N->getValueType(0), dl, Load, 12030 DAG.getUNDEF(N->getValueType(0)), Ops); 12031 } 12032 return SDValue(); 12033 } 12034 12035 // This function adds the required vector_shuffle needed to get 12036 // the elements of the vector extract in the correct position 12037 // as specified by the CorrectElems encoding. 12038 static SDValue addShuffleForVecExtend(SDNode *N, SelectionDAG &DAG, 12039 SDValue Input, uint64_t Elems, 12040 uint64_t CorrectElems) { 12041 SDLoc dl(N); 12042 12043 unsigned NumElems = Input.getValueType().getVectorNumElements(); 12044 SmallVector<int, 16> ShuffleMask(NumElems, -1); 12045 12046 // Knowing the element indices being extracted from the original 12047 // vector and the order in which they're being inserted, just put 12048 // them at element indices required for the instruction. 12049 for (unsigned i = 0; i < N->getNumOperands(); i++) { 12050 if (DAG.getDataLayout().isLittleEndian()) 12051 ShuffleMask[CorrectElems & 0xF] = Elems & 0xF; 12052 else 12053 ShuffleMask[(CorrectElems & 0xF0) >> 4] = (Elems & 0xF0) >> 4; 12054 CorrectElems = CorrectElems >> 8; 12055 Elems = Elems >> 8; 12056 } 12057 12058 SDValue Shuffle = 12059 DAG.getVectorShuffle(Input.getValueType(), dl, Input, 12060 DAG.getUNDEF(Input.getValueType()), ShuffleMask); 12061 12062 EVT Ty = N->getValueType(0); 12063 SDValue BV = DAG.getNode(PPCISD::SExtVElems, dl, Ty, Shuffle); 12064 return BV; 12065 } 12066 12067 // Look for build vector patterns where input operands come from sign 12068 // extended vector_extract elements of specific indices. If the correct indices 12069 // aren't used, add a vector shuffle to fix up the indices and create a new 12070 // PPCISD:SExtVElems node which selects the vector sign extend instructions 12071 // during instruction selection. 12072 static SDValue combineBVOfVecSExt(SDNode *N, SelectionDAG &DAG) { 12073 // This array encodes the indices that the vector sign extend instructions 12074 // extract from when extending from one type to another for both BE and LE. 12075 // The right nibble of each byte corresponds to the LE incides. 12076 // and the left nibble of each byte corresponds to the BE incides. 12077 // For example: 0x3074B8FC byte->word 12078 // For LE: the allowed indices are: 0x0,0x4,0x8,0xC 12079 // For BE: the allowed indices are: 0x3,0x7,0xB,0xF 12080 // For example: 0x000070F8 byte->double word 12081 // For LE: the allowed indices are: 0x0,0x8 12082 // For BE: the allowed indices are: 0x7,0xF 12083 uint64_t TargetElems[] = { 12084 0x3074B8FC, // b->w 12085 0x000070F8, // b->d 12086 0x10325476, // h->w 12087 0x00003074, // h->d 12088 0x00001032, // w->d 12089 }; 12090 12091 uint64_t Elems = 0; 12092 int Index; 12093 SDValue Input; 12094 12095 auto isSExtOfVecExtract = [&](SDValue Op) -> bool { 12096 if (!Op) 12097 return false; 12098 if (Op.getOpcode() != ISD::SIGN_EXTEND && 12099 Op.getOpcode() != ISD::SIGN_EXTEND_INREG) 12100 return false; 12101 12102 // A SIGN_EXTEND_INREG might be fed by an ANY_EXTEND to produce a value 12103 // of the right width. 12104 SDValue Extract = Op.getOperand(0); 12105 if (Extract.getOpcode() == ISD::ANY_EXTEND) 12106 Extract = Extract.getOperand(0); 12107 if (Extract.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 12108 return false; 12109 12110 ConstantSDNode *ExtOp = dyn_cast<ConstantSDNode>(Extract.getOperand(1)); 12111 if (!ExtOp) 12112 return false; 12113 12114 Index = ExtOp->getZExtValue(); 12115 if (Input && Input != Extract.getOperand(0)) 12116 return false; 12117 12118 if (!Input) 12119 Input = Extract.getOperand(0); 12120 12121 Elems = Elems << 8; 12122 Index = DAG.getDataLayout().isLittleEndian() ? Index : Index << 4; 12123 Elems |= Index; 12124 12125 return true; 12126 }; 12127 12128 // If the build vector operands aren't sign extended vector extracts, 12129 // of the same input vector, then return. 12130 for (unsigned i = 0; i < N->getNumOperands(); i++) { 12131 if (!isSExtOfVecExtract(N->getOperand(i))) { 12132 return SDValue(); 12133 } 12134 } 12135 12136 // If the vector extract indicies are not correct, add the appropriate 12137 // vector_shuffle. 12138 int TgtElemArrayIdx; 12139 int InputSize = Input.getValueType().getScalarSizeInBits(); 12140 int OutputSize = N->getValueType(0).getScalarSizeInBits(); 12141 if (InputSize + OutputSize == 40) 12142 TgtElemArrayIdx = 0; 12143 else if (InputSize + OutputSize == 72) 12144 TgtElemArrayIdx = 1; 12145 else if (InputSize + OutputSize == 48) 12146 TgtElemArrayIdx = 2; 12147 else if (InputSize + OutputSize == 80) 12148 TgtElemArrayIdx = 3; 12149 else if (InputSize + OutputSize == 96) 12150 TgtElemArrayIdx = 4; 12151 else 12152 return SDValue(); 12153 12154 uint64_t CorrectElems = TargetElems[TgtElemArrayIdx]; 12155 CorrectElems = DAG.getDataLayout().isLittleEndian() 12156 ? CorrectElems & 0x0F0F0F0F0F0F0F0F 12157 : CorrectElems & 0xF0F0F0F0F0F0F0F0; 12158 if (Elems != CorrectElems) { 12159 return addShuffleForVecExtend(N, DAG, Input, Elems, CorrectElems); 12160 } 12161 12162 // Regular lowering will catch cases where a shuffle is not needed. 12163 return SDValue(); 12164 } 12165 12166 SDValue PPCTargetLowering::DAGCombineBuildVector(SDNode *N, 12167 DAGCombinerInfo &DCI) const { 12168 assert(N->getOpcode() == ISD::BUILD_VECTOR && 12169 "Should be called with a BUILD_VECTOR node"); 12170 12171 SelectionDAG &DAG = DCI.DAG; 12172 SDLoc dl(N); 12173 12174 if (!Subtarget.hasVSX()) 12175 return SDValue(); 12176 12177 // The target independent DAG combiner will leave a build_vector of 12178 // float-to-int conversions intact. We can generate MUCH better code for 12179 // a float-to-int conversion of a vector of floats. 12180 SDValue FirstInput = N->getOperand(0); 12181 if (FirstInput.getOpcode() == PPCISD::MFVSR) { 12182 SDValue Reduced = combineElementTruncationToVectorTruncation(N, DCI); 12183 if (Reduced) 12184 return Reduced; 12185 } 12186 12187 // If we're building a vector out of consecutive loads, just load that 12188 // vector type. 12189 SDValue Reduced = combineBVOfConsecutiveLoads(N, DAG); 12190 if (Reduced) 12191 return Reduced; 12192 12193 // If we're building a vector out of extended elements from another vector 12194 // we have P9 vector integer extend instructions. The code assumes legal 12195 // input types (i.e. it can't handle things like v4i16) so do not run before 12196 // legalization. 12197 if (Subtarget.hasP9Altivec() && !DCI.isBeforeLegalize()) { 12198 Reduced = combineBVOfVecSExt(N, DAG); 12199 if (Reduced) 12200 return Reduced; 12201 } 12202 12203 12204 if (N->getValueType(0) != MVT::v2f64) 12205 return SDValue(); 12206 12207 // Looking for: 12208 // (build_vector ([su]int_to_fp (extractelt 0)), [su]int_to_fp (extractelt 1)) 12209 if (FirstInput.getOpcode() != ISD::SINT_TO_FP && 12210 FirstInput.getOpcode() != ISD::UINT_TO_FP) 12211 return SDValue(); 12212 if (N->getOperand(1).getOpcode() != ISD::SINT_TO_FP && 12213 N->getOperand(1).getOpcode() != ISD::UINT_TO_FP) 12214 return SDValue(); 12215 if (FirstInput.getOpcode() != N->getOperand(1).getOpcode()) 12216 return SDValue(); 12217 12218 SDValue Ext1 = FirstInput.getOperand(0); 12219 SDValue Ext2 = N->getOperand(1).getOperand(0); 12220 if(Ext1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 12221 Ext2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 12222 return SDValue(); 12223 12224 ConstantSDNode *Ext1Op = dyn_cast<ConstantSDNode>(Ext1.getOperand(1)); 12225 ConstantSDNode *Ext2Op = dyn_cast<ConstantSDNode>(Ext2.getOperand(1)); 12226 if (!Ext1Op || !Ext2Op) 12227 return SDValue(); 12228 if (Ext1.getValueType() != MVT::i32 || 12229 Ext2.getValueType() != MVT::i32) 12230 if (Ext1.getOperand(0) != Ext2.getOperand(0)) 12231 return SDValue(); 12232 12233 int FirstElem = Ext1Op->getZExtValue(); 12234 int SecondElem = Ext2Op->getZExtValue(); 12235 int SubvecIdx; 12236 if (FirstElem == 0 && SecondElem == 1) 12237 SubvecIdx = Subtarget.isLittleEndian() ? 1 : 0; 12238 else if (FirstElem == 2 && SecondElem == 3) 12239 SubvecIdx = Subtarget.isLittleEndian() ? 0 : 1; 12240 else 12241 return SDValue(); 12242 12243 SDValue SrcVec = Ext1.getOperand(0); 12244 auto NodeType = (N->getOperand(1).getOpcode() == ISD::SINT_TO_FP) ? 12245 PPCISD::SINT_VEC_TO_FP : PPCISD::UINT_VEC_TO_FP; 12246 return DAG.getNode(NodeType, dl, MVT::v2f64, 12247 SrcVec, DAG.getIntPtrConstant(SubvecIdx, dl)); 12248 } 12249 12250 SDValue PPCTargetLowering::combineFPToIntToFP(SDNode *N, 12251 DAGCombinerInfo &DCI) const { 12252 assert((N->getOpcode() == ISD::SINT_TO_FP || 12253 N->getOpcode() == ISD::UINT_TO_FP) && 12254 "Need an int -> FP conversion node here"); 12255 12256 if (useSoftFloat() || !Subtarget.has64BitSupport()) 12257 return SDValue(); 12258 12259 SelectionDAG &DAG = DCI.DAG; 12260 SDLoc dl(N); 12261 SDValue Op(N, 0); 12262 12263 // Don't handle ppc_fp128 here or conversions that are out-of-range capable 12264 // from the hardware. 12265 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64) 12266 return SDValue(); 12267 if (Op.getOperand(0).getValueType().getSimpleVT() <= MVT(MVT::i1) || 12268 Op.getOperand(0).getValueType().getSimpleVT() > MVT(MVT::i64)) 12269 return SDValue(); 12270 12271 SDValue FirstOperand(Op.getOperand(0)); 12272 bool SubWordLoad = FirstOperand.getOpcode() == ISD::LOAD && 12273 (FirstOperand.getValueType() == MVT::i8 || 12274 FirstOperand.getValueType() == MVT::i16); 12275 if (Subtarget.hasP9Vector() && Subtarget.hasP9Altivec() && SubWordLoad) { 12276 bool Signed = N->getOpcode() == ISD::SINT_TO_FP; 12277 bool DstDouble = Op.getValueType() == MVT::f64; 12278 unsigned ConvOp = Signed ? 12279 (DstDouble ? PPCISD::FCFID : PPCISD::FCFIDS) : 12280 (DstDouble ? PPCISD::FCFIDU : PPCISD::FCFIDUS); 12281 SDValue WidthConst = 12282 DAG.getIntPtrConstant(FirstOperand.getValueType() == MVT::i8 ? 1 : 2, 12283 dl, false); 12284 LoadSDNode *LDN = cast<LoadSDNode>(FirstOperand.getNode()); 12285 SDValue Ops[] = { LDN->getChain(), LDN->getBasePtr(), WidthConst }; 12286 SDValue Ld = DAG.getMemIntrinsicNode(PPCISD::LXSIZX, dl, 12287 DAG.getVTList(MVT::f64, MVT::Other), 12288 Ops, MVT::i8, LDN->getMemOperand()); 12289 12290 // For signed conversion, we need to sign-extend the value in the VSR 12291 if (Signed) { 12292 SDValue ExtOps[] = { Ld, WidthConst }; 12293 SDValue Ext = DAG.getNode(PPCISD::VEXTS, dl, MVT::f64, ExtOps); 12294 return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ext); 12295 } else 12296 return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ld); 12297 } 12298 12299 12300 // For i32 intermediate values, unfortunately, the conversion functions 12301 // leave the upper 32 bits of the value are undefined. Within the set of 12302 // scalar instructions, we have no method for zero- or sign-extending the 12303 // value. Thus, we cannot handle i32 intermediate values here. 12304 if (Op.getOperand(0).getValueType() == MVT::i32) 12305 return SDValue(); 12306 12307 assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) && 12308 "UINT_TO_FP is supported only with FPCVT"); 12309 12310 // If we have FCFIDS, then use it when converting to single-precision. 12311 // Otherwise, convert to double-precision and then round. 12312 unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 12313 ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS 12314 : PPCISD::FCFIDS) 12315 : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU 12316 : PPCISD::FCFID); 12317 MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 12318 ? MVT::f32 12319 : MVT::f64; 12320 12321 // If we're converting from a float, to an int, and back to a float again, 12322 // then we don't need the store/load pair at all. 12323 if ((Op.getOperand(0).getOpcode() == ISD::FP_TO_UINT && 12324 Subtarget.hasFPCVT()) || 12325 (Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT)) { 12326 SDValue Src = Op.getOperand(0).getOperand(0); 12327 if (Src.getValueType() == MVT::f32) { 12328 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src); 12329 DCI.AddToWorklist(Src.getNode()); 12330 } else if (Src.getValueType() != MVT::f64) { 12331 // Make sure that we don't pick up a ppc_fp128 source value. 12332 return SDValue(); 12333 } 12334 12335 unsigned FCTOp = 12336 Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT ? PPCISD::FCTIDZ : 12337 PPCISD::FCTIDUZ; 12338 12339 SDValue Tmp = DAG.getNode(FCTOp, dl, MVT::f64, Src); 12340 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Tmp); 12341 12342 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) { 12343 FP = DAG.getNode(ISD::FP_ROUND, dl, 12344 MVT::f32, FP, DAG.getIntPtrConstant(0, dl)); 12345 DCI.AddToWorklist(FP.getNode()); 12346 } 12347 12348 return FP; 12349 } 12350 12351 return SDValue(); 12352 } 12353 12354 // expandVSXLoadForLE - Convert VSX loads (which may be intrinsics for 12355 // builtins) into loads with swaps. 12356 SDValue PPCTargetLowering::expandVSXLoadForLE(SDNode *N, 12357 DAGCombinerInfo &DCI) const { 12358 SelectionDAG &DAG = DCI.DAG; 12359 SDLoc dl(N); 12360 SDValue Chain; 12361 SDValue Base; 12362 MachineMemOperand *MMO; 12363 12364 switch (N->getOpcode()) { 12365 default: 12366 llvm_unreachable("Unexpected opcode for little endian VSX load"); 12367 case ISD::LOAD: { 12368 LoadSDNode *LD = cast<LoadSDNode>(N); 12369 Chain = LD->getChain(); 12370 Base = LD->getBasePtr(); 12371 MMO = LD->getMemOperand(); 12372 // If the MMO suggests this isn't a load of a full vector, leave 12373 // things alone. For a built-in, we have to make the change for 12374 // correctness, so if there is a size problem that will be a bug. 12375 if (MMO->getSize() < 16) 12376 return SDValue(); 12377 break; 12378 } 12379 case ISD::INTRINSIC_W_CHAIN: { 12380 MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N); 12381 Chain = Intrin->getChain(); 12382 // Similarly to the store case below, Intrin->getBasePtr() doesn't get 12383 // us what we want. Get operand 2 instead. 12384 Base = Intrin->getOperand(2); 12385 MMO = Intrin->getMemOperand(); 12386 break; 12387 } 12388 } 12389 12390 MVT VecTy = N->getValueType(0).getSimpleVT(); 12391 12392 // Do not expand to PPCISD::LXVD2X + PPCISD::XXSWAPD when the load is 12393 // aligned and the type is a vector with elements up to 4 bytes 12394 if (Subtarget.needsSwapsForVSXMemOps() && !(MMO->getAlignment()%16) 12395 && VecTy.getScalarSizeInBits() <= 32 ) { 12396 return SDValue(); 12397 } 12398 12399 SDValue LoadOps[] = { Chain, Base }; 12400 SDValue Load = DAG.getMemIntrinsicNode(PPCISD::LXVD2X, dl, 12401 DAG.getVTList(MVT::v2f64, MVT::Other), 12402 LoadOps, MVT::v2f64, MMO); 12403 12404 DCI.AddToWorklist(Load.getNode()); 12405 Chain = Load.getValue(1); 12406 SDValue Swap = DAG.getNode( 12407 PPCISD::XXSWAPD, dl, DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Load); 12408 DCI.AddToWorklist(Swap.getNode()); 12409 12410 // Add a bitcast if the resulting load type doesn't match v2f64. 12411 if (VecTy != MVT::v2f64) { 12412 SDValue N = DAG.getNode(ISD::BITCAST, dl, VecTy, Swap); 12413 DCI.AddToWorklist(N.getNode()); 12414 // Package {bitcast value, swap's chain} to match Load's shape. 12415 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VecTy, MVT::Other), 12416 N, Swap.getValue(1)); 12417 } 12418 12419 return Swap; 12420 } 12421 12422 // expandVSXStoreForLE - Convert VSX stores (which may be intrinsics for 12423 // builtins) into stores with swaps. 12424 SDValue PPCTargetLowering::expandVSXStoreForLE(SDNode *N, 12425 DAGCombinerInfo &DCI) const { 12426 SelectionDAG &DAG = DCI.DAG; 12427 SDLoc dl(N); 12428 SDValue Chain; 12429 SDValue Base; 12430 unsigned SrcOpnd; 12431 MachineMemOperand *MMO; 12432 12433 switch (N->getOpcode()) { 12434 default: 12435 llvm_unreachable("Unexpected opcode for little endian VSX store"); 12436 case ISD::STORE: { 12437 StoreSDNode *ST = cast<StoreSDNode>(N); 12438 Chain = ST->getChain(); 12439 Base = ST->getBasePtr(); 12440 MMO = ST->getMemOperand(); 12441 SrcOpnd = 1; 12442 // If the MMO suggests this isn't a store of a full vector, leave 12443 // things alone. For a built-in, we have to make the change for 12444 // correctness, so if there is a size problem that will be a bug. 12445 if (MMO->getSize() < 16) 12446 return SDValue(); 12447 break; 12448 } 12449 case ISD::INTRINSIC_VOID: { 12450 MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N); 12451 Chain = Intrin->getChain(); 12452 // Intrin->getBasePtr() oddly does not get what we want. 12453 Base = Intrin->getOperand(3); 12454 MMO = Intrin->getMemOperand(); 12455 SrcOpnd = 2; 12456 break; 12457 } 12458 } 12459 12460 SDValue Src = N->getOperand(SrcOpnd); 12461 MVT VecTy = Src.getValueType().getSimpleVT(); 12462 12463 // Do not expand to PPCISD::XXSWAPD and PPCISD::STXVD2X when the load is 12464 // aligned and the type is a vector with elements up to 4 bytes 12465 if (Subtarget.needsSwapsForVSXMemOps() && !(MMO->getAlignment()%16) 12466 && VecTy.getScalarSizeInBits() <= 32 ) { 12467 return SDValue(); 12468 } 12469 12470 // All stores are done as v2f64 and possible bit cast. 12471 if (VecTy != MVT::v2f64) { 12472 Src = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Src); 12473 DCI.AddToWorklist(Src.getNode()); 12474 } 12475 12476 SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl, 12477 DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Src); 12478 DCI.AddToWorklist(Swap.getNode()); 12479 Chain = Swap.getValue(1); 12480 SDValue StoreOps[] = { Chain, Swap, Base }; 12481 SDValue Store = DAG.getMemIntrinsicNode(PPCISD::STXVD2X, dl, 12482 DAG.getVTList(MVT::Other), 12483 StoreOps, VecTy, MMO); 12484 DCI.AddToWorklist(Store.getNode()); 12485 return Store; 12486 } 12487 12488 // Handle DAG combine for STORE (FP_TO_INT F). 12489 SDValue PPCTargetLowering::combineStoreFPToInt(SDNode *N, 12490 DAGCombinerInfo &DCI) const { 12491 12492 SelectionDAG &DAG = DCI.DAG; 12493 SDLoc dl(N); 12494 unsigned Opcode = N->getOperand(1).getOpcode(); 12495 12496 assert((Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT) 12497 && "Not a FP_TO_INT Instruction!"); 12498 12499 SDValue Val = N->getOperand(1).getOperand(0); 12500 EVT Op1VT = N->getOperand(1).getValueType(); 12501 EVT ResVT = Val.getValueType(); 12502 12503 // Floating point types smaller than 32 bits are not legal on Power. 12504 if (ResVT.getScalarSizeInBits() < 32) 12505 return SDValue(); 12506 12507 // Only perform combine for conversion to i64/i32 or power9 i16/i8. 12508 bool ValidTypeForStoreFltAsInt = 12509 (Op1VT == MVT::i32 || Op1VT == MVT::i64 || 12510 (Subtarget.hasP9Vector() && (Op1VT == MVT::i16 || Op1VT == MVT::i8))); 12511 12512 if (ResVT == MVT::ppcf128 || !Subtarget.hasP8Altivec() || 12513 cast<StoreSDNode>(N)->isTruncatingStore() || !ValidTypeForStoreFltAsInt) 12514 return SDValue(); 12515 12516 // Extend f32 values to f64 12517 if (ResVT.getScalarSizeInBits() == 32) { 12518 Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val); 12519 DCI.AddToWorklist(Val.getNode()); 12520 } 12521 12522 // Set signed or unsigned conversion opcode. 12523 unsigned ConvOpcode = (Opcode == ISD::FP_TO_SINT) ? 12524 PPCISD::FP_TO_SINT_IN_VSR : 12525 PPCISD::FP_TO_UINT_IN_VSR; 12526 12527 Val = DAG.getNode(ConvOpcode, 12528 dl, ResVT == MVT::f128 ? MVT::f128 : MVT::f64, Val); 12529 DCI.AddToWorklist(Val.getNode()); 12530 12531 // Set number of bytes being converted. 12532 unsigned ByteSize = Op1VT.getScalarSizeInBits() / 8; 12533 SDValue Ops[] = { N->getOperand(0), Val, N->getOperand(2), 12534 DAG.getIntPtrConstant(ByteSize, dl, false), 12535 DAG.getValueType(Op1VT) }; 12536 12537 Val = DAG.getMemIntrinsicNode(PPCISD::ST_VSR_SCAL_INT, dl, 12538 DAG.getVTList(MVT::Other), Ops, 12539 cast<StoreSDNode>(N)->getMemoryVT(), 12540 cast<StoreSDNode>(N)->getMemOperand()); 12541 12542 DCI.AddToWorklist(Val.getNode()); 12543 return Val; 12544 } 12545 12546 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N, 12547 DAGCombinerInfo &DCI) const { 12548 SelectionDAG &DAG = DCI.DAG; 12549 SDLoc dl(N); 12550 switch (N->getOpcode()) { 12551 default: break; 12552 case ISD::ADD: 12553 return combineADD(N, DCI); 12554 case ISD::SHL: 12555 return combineSHL(N, DCI); 12556 case ISD::SRA: 12557 return combineSRA(N, DCI); 12558 case ISD::SRL: 12559 return combineSRL(N, DCI); 12560 case PPCISD::SHL: 12561 if (isNullConstant(N->getOperand(0))) // 0 << V -> 0. 12562 return N->getOperand(0); 12563 break; 12564 case PPCISD::SRL: 12565 if (isNullConstant(N->getOperand(0))) // 0 >>u V -> 0. 12566 return N->getOperand(0); 12567 break; 12568 case PPCISD::SRA: 12569 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) { 12570 if (C->isNullValue() || // 0 >>s V -> 0. 12571 C->isAllOnesValue()) // -1 >>s V -> -1. 12572 return N->getOperand(0); 12573 } 12574 break; 12575 case ISD::SIGN_EXTEND: 12576 case ISD::ZERO_EXTEND: 12577 case ISD::ANY_EXTEND: 12578 return DAGCombineExtBoolTrunc(N, DCI); 12579 case ISD::TRUNCATE: 12580 return combineTRUNCATE(N, DCI); 12581 case ISD::SETCC: 12582 if (SDValue CSCC = combineSetCC(N, DCI)) 12583 return CSCC; 12584 LLVM_FALLTHROUGH; 12585 case ISD::SELECT_CC: 12586 return DAGCombineTruncBoolExt(N, DCI); 12587 case ISD::SINT_TO_FP: 12588 case ISD::UINT_TO_FP: 12589 return combineFPToIntToFP(N, DCI); 12590 case ISD::STORE: { 12591 12592 EVT Op1VT = N->getOperand(1).getValueType(); 12593 unsigned Opcode = N->getOperand(1).getOpcode(); 12594 12595 if (Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT) { 12596 SDValue Val= combineStoreFPToInt(N, DCI); 12597 if (Val) 12598 return Val; 12599 } 12600 12601 // Turn STORE (BSWAP) -> sthbrx/stwbrx. 12602 if (cast<StoreSDNode>(N)->isUnindexed() && Opcode == ISD::BSWAP && 12603 N->getOperand(1).getNode()->hasOneUse() && 12604 (Op1VT == MVT::i32 || Op1VT == MVT::i16 || 12605 (Subtarget.hasLDBRX() && Subtarget.isPPC64() && Op1VT == MVT::i64))) { 12606 12607 // STBRX can only handle simple types. 12608 EVT mVT = cast<StoreSDNode>(N)->getMemoryVT(); 12609 if (mVT.isExtended()) 12610 break; 12611 12612 SDValue BSwapOp = N->getOperand(1).getOperand(0); 12613 // Do an any-extend to 32-bits if this is a half-word input. 12614 if (BSwapOp.getValueType() == MVT::i16) 12615 BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp); 12616 12617 // If the type of BSWAP operand is wider than stored memory width 12618 // it need to be shifted to the right side before STBRX. 12619 if (Op1VT.bitsGT(mVT)) { 12620 int Shift = Op1VT.getSizeInBits() - mVT.getSizeInBits(); 12621 BSwapOp = DAG.getNode(ISD::SRL, dl, Op1VT, BSwapOp, 12622 DAG.getConstant(Shift, dl, MVT::i32)); 12623 // Need to truncate if this is a bswap of i64 stored as i32/i16. 12624 if (Op1VT == MVT::i64) 12625 BSwapOp = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BSwapOp); 12626 } 12627 12628 SDValue Ops[] = { 12629 N->getOperand(0), BSwapOp, N->getOperand(2), DAG.getValueType(mVT) 12630 }; 12631 return 12632 DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other), 12633 Ops, cast<StoreSDNode>(N)->getMemoryVT(), 12634 cast<StoreSDNode>(N)->getMemOperand()); 12635 } 12636 12637 // STORE Constant:i32<0> -> STORE<trunc to i32> Constant:i64<0> 12638 // So it can increase the chance of CSE constant construction. 12639 if (Subtarget.isPPC64() && !DCI.isBeforeLegalize() && 12640 isa<ConstantSDNode>(N->getOperand(1)) && Op1VT == MVT::i32) { 12641 // Need to sign-extended to 64-bits to handle negative values. 12642 EVT MemVT = cast<StoreSDNode>(N)->getMemoryVT(); 12643 uint64_t Val64 = SignExtend64(N->getConstantOperandVal(1), 12644 MemVT.getSizeInBits()); 12645 SDValue Const64 = DAG.getConstant(Val64, dl, MVT::i64); 12646 12647 // DAG.getTruncStore() can't be used here because it doesn't accept 12648 // the general (base + offset) addressing mode. 12649 // So we use UpdateNodeOperands and setTruncatingStore instead. 12650 DAG.UpdateNodeOperands(N, N->getOperand(0), Const64, N->getOperand(2), 12651 N->getOperand(3)); 12652 cast<StoreSDNode>(N)->setTruncatingStore(true); 12653 return SDValue(N, 0); 12654 } 12655 12656 // For little endian, VSX stores require generating xxswapd/lxvd2x. 12657 // Not needed on ISA 3.0 based CPUs since we have a non-permuting store. 12658 if (Op1VT.isSimple()) { 12659 MVT StoreVT = Op1VT.getSimpleVT(); 12660 if (Subtarget.needsSwapsForVSXMemOps() && 12661 (StoreVT == MVT::v2f64 || StoreVT == MVT::v2i64 || 12662 StoreVT == MVT::v4f32 || StoreVT == MVT::v4i32)) 12663 return expandVSXStoreForLE(N, DCI); 12664 } 12665 break; 12666 } 12667 case ISD::LOAD: { 12668 LoadSDNode *LD = cast<LoadSDNode>(N); 12669 EVT VT = LD->getValueType(0); 12670 12671 // For little endian, VSX loads require generating lxvd2x/xxswapd. 12672 // Not needed on ISA 3.0 based CPUs since we have a non-permuting load. 12673 if (VT.isSimple()) { 12674 MVT LoadVT = VT.getSimpleVT(); 12675 if (Subtarget.needsSwapsForVSXMemOps() && 12676 (LoadVT == MVT::v2f64 || LoadVT == MVT::v2i64 || 12677 LoadVT == MVT::v4f32 || LoadVT == MVT::v4i32)) 12678 return expandVSXLoadForLE(N, DCI); 12679 } 12680 12681 // We sometimes end up with a 64-bit integer load, from which we extract 12682 // two single-precision floating-point numbers. This happens with 12683 // std::complex<float>, and other similar structures, because of the way we 12684 // canonicalize structure copies. However, if we lack direct moves, 12685 // then the final bitcasts from the extracted integer values to the 12686 // floating-point numbers turn into store/load pairs. Even with direct moves, 12687 // just loading the two floating-point numbers is likely better. 12688 auto ReplaceTwoFloatLoad = [&]() { 12689 if (VT != MVT::i64) 12690 return false; 12691 12692 if (LD->getExtensionType() != ISD::NON_EXTLOAD || 12693 LD->isVolatile()) 12694 return false; 12695 12696 // We're looking for a sequence like this: 12697 // t13: i64,ch = load<LD8[%ref.tmp]> t0, t6, undef:i64 12698 // t16: i64 = srl t13, Constant:i32<32> 12699 // t17: i32 = truncate t16 12700 // t18: f32 = bitcast t17 12701 // t19: i32 = truncate t13 12702 // t20: f32 = bitcast t19 12703 12704 if (!LD->hasNUsesOfValue(2, 0)) 12705 return false; 12706 12707 auto UI = LD->use_begin(); 12708 while (UI.getUse().getResNo() != 0) ++UI; 12709 SDNode *Trunc = *UI++; 12710 while (UI.getUse().getResNo() != 0) ++UI; 12711 SDNode *RightShift = *UI; 12712 if (Trunc->getOpcode() != ISD::TRUNCATE) 12713 std::swap(Trunc, RightShift); 12714 12715 if (Trunc->getOpcode() != ISD::TRUNCATE || 12716 Trunc->getValueType(0) != MVT::i32 || 12717 !Trunc->hasOneUse()) 12718 return false; 12719 if (RightShift->getOpcode() != ISD::SRL || 12720 !isa<ConstantSDNode>(RightShift->getOperand(1)) || 12721 RightShift->getConstantOperandVal(1) != 32 || 12722 !RightShift->hasOneUse()) 12723 return false; 12724 12725 SDNode *Trunc2 = *RightShift->use_begin(); 12726 if (Trunc2->getOpcode() != ISD::TRUNCATE || 12727 Trunc2->getValueType(0) != MVT::i32 || 12728 !Trunc2->hasOneUse()) 12729 return false; 12730 12731 SDNode *Bitcast = *Trunc->use_begin(); 12732 SDNode *Bitcast2 = *Trunc2->use_begin(); 12733 12734 if (Bitcast->getOpcode() != ISD::BITCAST || 12735 Bitcast->getValueType(0) != MVT::f32) 12736 return false; 12737 if (Bitcast2->getOpcode() != ISD::BITCAST || 12738 Bitcast2->getValueType(0) != MVT::f32) 12739 return false; 12740 12741 if (Subtarget.isLittleEndian()) 12742 std::swap(Bitcast, Bitcast2); 12743 12744 // Bitcast has the second float (in memory-layout order) and Bitcast2 12745 // has the first one. 12746 12747 SDValue BasePtr = LD->getBasePtr(); 12748 if (LD->isIndexed()) { 12749 assert(LD->getAddressingMode() == ISD::PRE_INC && 12750 "Non-pre-inc AM on PPC?"); 12751 BasePtr = 12752 DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, 12753 LD->getOffset()); 12754 } 12755 12756 auto MMOFlags = 12757 LD->getMemOperand()->getFlags() & ~MachineMemOperand::MOVolatile; 12758 SDValue FloatLoad = DAG.getLoad(MVT::f32, dl, LD->getChain(), BasePtr, 12759 LD->getPointerInfo(), LD->getAlignment(), 12760 MMOFlags, LD->getAAInfo()); 12761 SDValue AddPtr = 12762 DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), 12763 BasePtr, DAG.getIntPtrConstant(4, dl)); 12764 SDValue FloatLoad2 = DAG.getLoad( 12765 MVT::f32, dl, SDValue(FloatLoad.getNode(), 1), AddPtr, 12766 LD->getPointerInfo().getWithOffset(4), 12767 MinAlign(LD->getAlignment(), 4), MMOFlags, LD->getAAInfo()); 12768 12769 if (LD->isIndexed()) { 12770 // Note that DAGCombine should re-form any pre-increment load(s) from 12771 // what is produced here if that makes sense. 12772 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), BasePtr); 12773 } 12774 12775 DCI.CombineTo(Bitcast2, FloatLoad); 12776 DCI.CombineTo(Bitcast, FloatLoad2); 12777 12778 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, LD->isIndexed() ? 2 : 1), 12779 SDValue(FloatLoad2.getNode(), 1)); 12780 return true; 12781 }; 12782 12783 if (ReplaceTwoFloatLoad()) 12784 return SDValue(N, 0); 12785 12786 EVT MemVT = LD->getMemoryVT(); 12787 Type *Ty = MemVT.getTypeForEVT(*DAG.getContext()); 12788 unsigned ABIAlignment = DAG.getDataLayout().getABITypeAlignment(Ty); 12789 Type *STy = MemVT.getScalarType().getTypeForEVT(*DAG.getContext()); 12790 unsigned ScalarABIAlignment = DAG.getDataLayout().getABITypeAlignment(STy); 12791 if (LD->isUnindexed() && VT.isVector() && 12792 ((Subtarget.hasAltivec() && ISD::isNON_EXTLoad(N) && 12793 // P8 and later hardware should just use LOAD. 12794 !Subtarget.hasP8Vector() && (VT == MVT::v16i8 || VT == MVT::v8i16 || 12795 VT == MVT::v4i32 || VT == MVT::v4f32)) || 12796 (Subtarget.hasQPX() && (VT == MVT::v4f64 || VT == MVT::v4f32) && 12797 LD->getAlignment() >= ScalarABIAlignment)) && 12798 LD->getAlignment() < ABIAlignment) { 12799 // This is a type-legal unaligned Altivec or QPX load. 12800 SDValue Chain = LD->getChain(); 12801 SDValue Ptr = LD->getBasePtr(); 12802 bool isLittleEndian = Subtarget.isLittleEndian(); 12803 12804 // This implements the loading of unaligned vectors as described in 12805 // the venerable Apple Velocity Engine overview. Specifically: 12806 // https://developer.apple.com/hardwaredrivers/ve/alignment.html 12807 // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html 12808 // 12809 // The general idea is to expand a sequence of one or more unaligned 12810 // loads into an alignment-based permutation-control instruction (lvsl 12811 // or lvsr), a series of regular vector loads (which always truncate 12812 // their input address to an aligned address), and a series of 12813 // permutations. The results of these permutations are the requested 12814 // loaded values. The trick is that the last "extra" load is not taken 12815 // from the address you might suspect (sizeof(vector) bytes after the 12816 // last requested load), but rather sizeof(vector) - 1 bytes after the 12817 // last requested vector. The point of this is to avoid a page fault if 12818 // the base address happened to be aligned. This works because if the 12819 // base address is aligned, then adding less than a full vector length 12820 // will cause the last vector in the sequence to be (re)loaded. 12821 // Otherwise, the next vector will be fetched as you might suspect was 12822 // necessary. 12823 12824 // We might be able to reuse the permutation generation from 12825 // a different base address offset from this one by an aligned amount. 12826 // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this 12827 // optimization later. 12828 Intrinsic::ID Intr, IntrLD, IntrPerm; 12829 MVT PermCntlTy, PermTy, LDTy; 12830 if (Subtarget.hasAltivec()) { 12831 Intr = isLittleEndian ? Intrinsic::ppc_altivec_lvsr : 12832 Intrinsic::ppc_altivec_lvsl; 12833 IntrLD = Intrinsic::ppc_altivec_lvx; 12834 IntrPerm = Intrinsic::ppc_altivec_vperm; 12835 PermCntlTy = MVT::v16i8; 12836 PermTy = MVT::v4i32; 12837 LDTy = MVT::v4i32; 12838 } else { 12839 Intr = MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlpcld : 12840 Intrinsic::ppc_qpx_qvlpcls; 12841 IntrLD = MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlfd : 12842 Intrinsic::ppc_qpx_qvlfs; 12843 IntrPerm = Intrinsic::ppc_qpx_qvfperm; 12844 PermCntlTy = MVT::v4f64; 12845 PermTy = MVT::v4f64; 12846 LDTy = MemVT.getSimpleVT(); 12847 } 12848 12849 SDValue PermCntl = BuildIntrinsicOp(Intr, Ptr, DAG, dl, PermCntlTy); 12850 12851 // Create the new MMO for the new base load. It is like the original MMO, 12852 // but represents an area in memory almost twice the vector size centered 12853 // on the original address. If the address is unaligned, we might start 12854 // reading up to (sizeof(vector)-1) bytes below the address of the 12855 // original unaligned load. 12856 MachineFunction &MF = DAG.getMachineFunction(); 12857 MachineMemOperand *BaseMMO = 12858 MF.getMachineMemOperand(LD->getMemOperand(), 12859 -(long)MemVT.getStoreSize()+1, 12860 2*MemVT.getStoreSize()-1); 12861 12862 // Create the new base load. 12863 SDValue LDXIntID = 12864 DAG.getTargetConstant(IntrLD, dl, getPointerTy(MF.getDataLayout())); 12865 SDValue BaseLoadOps[] = { Chain, LDXIntID, Ptr }; 12866 SDValue BaseLoad = 12867 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl, 12868 DAG.getVTList(PermTy, MVT::Other), 12869 BaseLoadOps, LDTy, BaseMMO); 12870 12871 // Note that the value of IncOffset (which is provided to the next 12872 // load's pointer info offset value, and thus used to calculate the 12873 // alignment), and the value of IncValue (which is actually used to 12874 // increment the pointer value) are different! This is because we 12875 // require the next load to appear to be aligned, even though it 12876 // is actually offset from the base pointer by a lesser amount. 12877 int IncOffset = VT.getSizeInBits() / 8; 12878 int IncValue = IncOffset; 12879 12880 // Walk (both up and down) the chain looking for another load at the real 12881 // (aligned) offset (the alignment of the other load does not matter in 12882 // this case). If found, then do not use the offset reduction trick, as 12883 // that will prevent the loads from being later combined (as they would 12884 // otherwise be duplicates). 12885 if (!findConsecutiveLoad(LD, DAG)) 12886 --IncValue; 12887 12888 SDValue Increment = 12889 DAG.getConstant(IncValue, dl, getPointerTy(MF.getDataLayout())); 12890 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment); 12891 12892 MachineMemOperand *ExtraMMO = 12893 MF.getMachineMemOperand(LD->getMemOperand(), 12894 1, 2*MemVT.getStoreSize()-1); 12895 SDValue ExtraLoadOps[] = { Chain, LDXIntID, Ptr }; 12896 SDValue ExtraLoad = 12897 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl, 12898 DAG.getVTList(PermTy, MVT::Other), 12899 ExtraLoadOps, LDTy, ExtraMMO); 12900 12901 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 12902 BaseLoad.getValue(1), ExtraLoad.getValue(1)); 12903 12904 // Because vperm has a big-endian bias, we must reverse the order 12905 // of the input vectors and complement the permute control vector 12906 // when generating little endian code. We have already handled the 12907 // latter by using lvsr instead of lvsl, so just reverse BaseLoad 12908 // and ExtraLoad here. 12909 SDValue Perm; 12910 if (isLittleEndian) 12911 Perm = BuildIntrinsicOp(IntrPerm, 12912 ExtraLoad, BaseLoad, PermCntl, DAG, dl); 12913 else 12914 Perm = BuildIntrinsicOp(IntrPerm, 12915 BaseLoad, ExtraLoad, PermCntl, DAG, dl); 12916 12917 if (VT != PermTy) 12918 Perm = Subtarget.hasAltivec() ? 12919 DAG.getNode(ISD::BITCAST, dl, VT, Perm) : 12920 DAG.getNode(ISD::FP_ROUND, dl, VT, Perm, // QPX 12921 DAG.getTargetConstant(1, dl, MVT::i64)); 12922 // second argument is 1 because this rounding 12923 // is always exact. 12924 12925 // The output of the permutation is our loaded result, the TokenFactor is 12926 // our new chain. 12927 DCI.CombineTo(N, Perm, TF); 12928 return SDValue(N, 0); 12929 } 12930 } 12931 break; 12932 case ISD::INTRINSIC_WO_CHAIN: { 12933 bool isLittleEndian = Subtarget.isLittleEndian(); 12934 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 12935 Intrinsic::ID Intr = (isLittleEndian ? Intrinsic::ppc_altivec_lvsr 12936 : Intrinsic::ppc_altivec_lvsl); 12937 if ((IID == Intr || 12938 IID == Intrinsic::ppc_qpx_qvlpcld || 12939 IID == Intrinsic::ppc_qpx_qvlpcls) && 12940 N->getOperand(1)->getOpcode() == ISD::ADD) { 12941 SDValue Add = N->getOperand(1); 12942 12943 int Bits = IID == Intrinsic::ppc_qpx_qvlpcld ? 12944 5 /* 32 byte alignment */ : 4 /* 16 byte alignment */; 12945 12946 if (DAG.MaskedValueIsZero(Add->getOperand(1), 12947 APInt::getAllOnesValue(Bits /* alignment */) 12948 .zext(Add.getScalarValueSizeInBits()))) { 12949 SDNode *BasePtr = Add->getOperand(0).getNode(); 12950 for (SDNode::use_iterator UI = BasePtr->use_begin(), 12951 UE = BasePtr->use_end(); 12952 UI != UE; ++UI) { 12953 if (UI->getOpcode() == ISD::INTRINSIC_WO_CHAIN && 12954 cast<ConstantSDNode>(UI->getOperand(0))->getZExtValue() == IID) { 12955 // We've found another LVSL/LVSR, and this address is an aligned 12956 // multiple of that one. The results will be the same, so use the 12957 // one we've just found instead. 12958 12959 return SDValue(*UI, 0); 12960 } 12961 } 12962 } 12963 12964 if (isa<ConstantSDNode>(Add->getOperand(1))) { 12965 SDNode *BasePtr = Add->getOperand(0).getNode(); 12966 for (SDNode::use_iterator UI = BasePtr->use_begin(), 12967 UE = BasePtr->use_end(); UI != UE; ++UI) { 12968 if (UI->getOpcode() == ISD::ADD && 12969 isa<ConstantSDNode>(UI->getOperand(1)) && 12970 (cast<ConstantSDNode>(Add->getOperand(1))->getZExtValue() - 12971 cast<ConstantSDNode>(UI->getOperand(1))->getZExtValue()) % 12972 (1ULL << Bits) == 0) { 12973 SDNode *OtherAdd = *UI; 12974 for (SDNode::use_iterator VI = OtherAdd->use_begin(), 12975 VE = OtherAdd->use_end(); VI != VE; ++VI) { 12976 if (VI->getOpcode() == ISD::INTRINSIC_WO_CHAIN && 12977 cast<ConstantSDNode>(VI->getOperand(0))->getZExtValue() == IID) { 12978 return SDValue(*VI, 0); 12979 } 12980 } 12981 } 12982 } 12983 } 12984 } 12985 } 12986 12987 break; 12988 case ISD::INTRINSIC_W_CHAIN: 12989 // For little endian, VSX loads require generating lxvd2x/xxswapd. 12990 // Not needed on ISA 3.0 based CPUs since we have a non-permuting load. 12991 if (Subtarget.needsSwapsForVSXMemOps()) { 12992 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 12993 default: 12994 break; 12995 case Intrinsic::ppc_vsx_lxvw4x: 12996 case Intrinsic::ppc_vsx_lxvd2x: 12997 return expandVSXLoadForLE(N, DCI); 12998 } 12999 } 13000 break; 13001 case ISD::INTRINSIC_VOID: 13002 // For little endian, VSX stores require generating xxswapd/stxvd2x. 13003 // Not needed on ISA 3.0 based CPUs since we have a non-permuting store. 13004 if (Subtarget.needsSwapsForVSXMemOps()) { 13005 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 13006 default: 13007 break; 13008 case Intrinsic::ppc_vsx_stxvw4x: 13009 case Intrinsic::ppc_vsx_stxvd2x: 13010 return expandVSXStoreForLE(N, DCI); 13011 } 13012 } 13013 break; 13014 case ISD::BSWAP: 13015 // Turn BSWAP (LOAD) -> lhbrx/lwbrx. 13016 if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) && 13017 N->getOperand(0).hasOneUse() && 13018 (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 || 13019 (Subtarget.hasLDBRX() && Subtarget.isPPC64() && 13020 N->getValueType(0) == MVT::i64))) { 13021 SDValue Load = N->getOperand(0); 13022 LoadSDNode *LD = cast<LoadSDNode>(Load); 13023 // Create the byte-swapping load. 13024 SDValue Ops[] = { 13025 LD->getChain(), // Chain 13026 LD->getBasePtr(), // Ptr 13027 DAG.getValueType(N->getValueType(0)) // VT 13028 }; 13029 SDValue BSLoad = 13030 DAG.getMemIntrinsicNode(PPCISD::LBRX, dl, 13031 DAG.getVTList(N->getValueType(0) == MVT::i64 ? 13032 MVT::i64 : MVT::i32, MVT::Other), 13033 Ops, LD->getMemoryVT(), LD->getMemOperand()); 13034 13035 // If this is an i16 load, insert the truncate. 13036 SDValue ResVal = BSLoad; 13037 if (N->getValueType(0) == MVT::i16) 13038 ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad); 13039 13040 // First, combine the bswap away. This makes the value produced by the 13041 // load dead. 13042 DCI.CombineTo(N, ResVal); 13043 13044 // Next, combine the load away, we give it a bogus result value but a real 13045 // chain result. The result value is dead because the bswap is dead. 13046 DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1)); 13047 13048 // Return N so it doesn't get rechecked! 13049 return SDValue(N, 0); 13050 } 13051 break; 13052 case PPCISD::VCMP: 13053 // If a VCMPo node already exists with exactly the same operands as this 13054 // node, use its result instead of this node (VCMPo computes both a CR6 and 13055 // a normal output). 13056 // 13057 if (!N->getOperand(0).hasOneUse() && 13058 !N->getOperand(1).hasOneUse() && 13059 !N->getOperand(2).hasOneUse()) { 13060 13061 // Scan all of the users of the LHS, looking for VCMPo's that match. 13062 SDNode *VCMPoNode = nullptr; 13063 13064 SDNode *LHSN = N->getOperand(0).getNode(); 13065 for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end(); 13066 UI != E; ++UI) 13067 if (UI->getOpcode() == PPCISD::VCMPo && 13068 UI->getOperand(1) == N->getOperand(1) && 13069 UI->getOperand(2) == N->getOperand(2) && 13070 UI->getOperand(0) == N->getOperand(0)) { 13071 VCMPoNode = *UI; 13072 break; 13073 } 13074 13075 // If there is no VCMPo node, or if the flag value has a single use, don't 13076 // transform this. 13077 if (!VCMPoNode || VCMPoNode->hasNUsesOfValue(0, 1)) 13078 break; 13079 13080 // Look at the (necessarily single) use of the flag value. If it has a 13081 // chain, this transformation is more complex. Note that multiple things 13082 // could use the value result, which we should ignore. 13083 SDNode *FlagUser = nullptr; 13084 for (SDNode::use_iterator UI = VCMPoNode->use_begin(); 13085 FlagUser == nullptr; ++UI) { 13086 assert(UI != VCMPoNode->use_end() && "Didn't find user!"); 13087 SDNode *User = *UI; 13088 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) { 13089 if (User->getOperand(i) == SDValue(VCMPoNode, 1)) { 13090 FlagUser = User; 13091 break; 13092 } 13093 } 13094 } 13095 13096 // If the user is a MFOCRF instruction, we know this is safe. 13097 // Otherwise we give up for right now. 13098 if (FlagUser->getOpcode() == PPCISD::MFOCRF) 13099 return SDValue(VCMPoNode, 0); 13100 } 13101 break; 13102 case ISD::BRCOND: { 13103 SDValue Cond = N->getOperand(1); 13104 SDValue Target = N->getOperand(2); 13105 13106 if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN && 13107 cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() == 13108 Intrinsic::ppc_is_decremented_ctr_nonzero) { 13109 13110 // We now need to make the intrinsic dead (it cannot be instruction 13111 // selected). 13112 DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0)); 13113 assert(Cond.getNode()->hasOneUse() && 13114 "Counter decrement has more than one use"); 13115 13116 return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other, 13117 N->getOperand(0), Target); 13118 } 13119 } 13120 break; 13121 case ISD::BR_CC: { 13122 // If this is a branch on an altivec predicate comparison, lower this so 13123 // that we don't have to do a MFOCRF: instead, branch directly on CR6. This 13124 // lowering is done pre-legalize, because the legalizer lowers the predicate 13125 // compare down to code that is difficult to reassemble. 13126 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get(); 13127 SDValue LHS = N->getOperand(2), RHS = N->getOperand(3); 13128 13129 // Sometimes the promoted value of the intrinsic is ANDed by some non-zero 13130 // value. If so, pass-through the AND to get to the intrinsic. 13131 if (LHS.getOpcode() == ISD::AND && 13132 LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN && 13133 cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() == 13134 Intrinsic::ppc_is_decremented_ctr_nonzero && 13135 isa<ConstantSDNode>(LHS.getOperand(1)) && 13136 !isNullConstant(LHS.getOperand(1))) 13137 LHS = LHS.getOperand(0); 13138 13139 if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN && 13140 cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() == 13141 Intrinsic::ppc_is_decremented_ctr_nonzero && 13142 isa<ConstantSDNode>(RHS)) { 13143 assert((CC == ISD::SETEQ || CC == ISD::SETNE) && 13144 "Counter decrement comparison is not EQ or NE"); 13145 13146 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue(); 13147 bool isBDNZ = (CC == ISD::SETEQ && Val) || 13148 (CC == ISD::SETNE && !Val); 13149 13150 // We now need to make the intrinsic dead (it cannot be instruction 13151 // selected). 13152 DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0)); 13153 assert(LHS.getNode()->hasOneUse() && 13154 "Counter decrement has more than one use"); 13155 13156 return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other, 13157 N->getOperand(0), N->getOperand(4)); 13158 } 13159 13160 int CompareOpc; 13161 bool isDot; 13162 13163 if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN && 13164 isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) && 13165 getVectorCompareInfo(LHS, CompareOpc, isDot, Subtarget)) { 13166 assert(isDot && "Can't compare against a vector result!"); 13167 13168 // If this is a comparison against something other than 0/1, then we know 13169 // that the condition is never/always true. 13170 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue(); 13171 if (Val != 0 && Val != 1) { 13172 if (CC == ISD::SETEQ) // Cond never true, remove branch. 13173 return N->getOperand(0); 13174 // Always !=, turn it into an unconditional branch. 13175 return DAG.getNode(ISD::BR, dl, MVT::Other, 13176 N->getOperand(0), N->getOperand(4)); 13177 } 13178 13179 bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0); 13180 13181 // Create the PPCISD altivec 'dot' comparison node. 13182 SDValue Ops[] = { 13183 LHS.getOperand(2), // LHS of compare 13184 LHS.getOperand(3), // RHS of compare 13185 DAG.getConstant(CompareOpc, dl, MVT::i32) 13186 }; 13187 EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue }; 13188 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops); 13189 13190 // Unpack the result based on how the target uses it. 13191 PPC::Predicate CompOpc; 13192 switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) { 13193 default: // Can't happen, don't crash on invalid number though. 13194 case 0: // Branch on the value of the EQ bit of CR6. 13195 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE; 13196 break; 13197 case 1: // Branch on the inverted value of the EQ bit of CR6. 13198 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ; 13199 break; 13200 case 2: // Branch on the value of the LT bit of CR6. 13201 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE; 13202 break; 13203 case 3: // Branch on the inverted value of the LT bit of CR6. 13204 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT; 13205 break; 13206 } 13207 13208 return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0), 13209 DAG.getConstant(CompOpc, dl, MVT::i32), 13210 DAG.getRegister(PPC::CR6, MVT::i32), 13211 N->getOperand(4), CompNode.getValue(1)); 13212 } 13213 break; 13214 } 13215 case ISD::BUILD_VECTOR: 13216 return DAGCombineBuildVector(N, DCI); 13217 } 13218 13219 return SDValue(); 13220 } 13221 13222 SDValue 13223 PPCTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor, 13224 SelectionDAG &DAG, 13225 SmallVectorImpl<SDNode *> &Created) const { 13226 // fold (sdiv X, pow2) 13227 EVT VT = N->getValueType(0); 13228 if (VT == MVT::i64 && !Subtarget.isPPC64()) 13229 return SDValue(); 13230 if ((VT != MVT::i32 && VT != MVT::i64) || 13231 !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2())) 13232 return SDValue(); 13233 13234 SDLoc DL(N); 13235 SDValue N0 = N->getOperand(0); 13236 13237 bool IsNegPow2 = (-Divisor).isPowerOf2(); 13238 unsigned Lg2 = (IsNegPow2 ? -Divisor : Divisor).countTrailingZeros(); 13239 SDValue ShiftAmt = DAG.getConstant(Lg2, DL, VT); 13240 13241 SDValue Op = DAG.getNode(PPCISD::SRA_ADDZE, DL, VT, N0, ShiftAmt); 13242 Created.push_back(Op.getNode()); 13243 13244 if (IsNegPow2) { 13245 Op = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Op); 13246 Created.push_back(Op.getNode()); 13247 } 13248 13249 return Op; 13250 } 13251 13252 //===----------------------------------------------------------------------===// 13253 // Inline Assembly Support 13254 //===----------------------------------------------------------------------===// 13255 13256 void PPCTargetLowering::computeKnownBitsForTargetNode(const SDValue Op, 13257 KnownBits &Known, 13258 const APInt &DemandedElts, 13259 const SelectionDAG &DAG, 13260 unsigned Depth) const { 13261 Known.resetAll(); 13262 switch (Op.getOpcode()) { 13263 default: break; 13264 case PPCISD::LBRX: { 13265 // lhbrx is known to have the top bits cleared out. 13266 if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16) 13267 Known.Zero = 0xFFFF0000; 13268 break; 13269 } 13270 case ISD::INTRINSIC_WO_CHAIN: { 13271 switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) { 13272 default: break; 13273 case Intrinsic::ppc_altivec_vcmpbfp_p: 13274 case Intrinsic::ppc_altivec_vcmpeqfp_p: 13275 case Intrinsic::ppc_altivec_vcmpequb_p: 13276 case Intrinsic::ppc_altivec_vcmpequh_p: 13277 case Intrinsic::ppc_altivec_vcmpequw_p: 13278 case Intrinsic::ppc_altivec_vcmpequd_p: 13279 case Intrinsic::ppc_altivec_vcmpgefp_p: 13280 case Intrinsic::ppc_altivec_vcmpgtfp_p: 13281 case Intrinsic::ppc_altivec_vcmpgtsb_p: 13282 case Intrinsic::ppc_altivec_vcmpgtsh_p: 13283 case Intrinsic::ppc_altivec_vcmpgtsw_p: 13284 case Intrinsic::ppc_altivec_vcmpgtsd_p: 13285 case Intrinsic::ppc_altivec_vcmpgtub_p: 13286 case Intrinsic::ppc_altivec_vcmpgtuh_p: 13287 case Intrinsic::ppc_altivec_vcmpgtuw_p: 13288 case Intrinsic::ppc_altivec_vcmpgtud_p: 13289 Known.Zero = ~1U; // All bits but the low one are known to be zero. 13290 break; 13291 } 13292 } 13293 } 13294 } 13295 13296 unsigned PPCTargetLowering::getPrefLoopAlignment(MachineLoop *ML) const { 13297 switch (Subtarget.getDarwinDirective()) { 13298 default: break; 13299 case PPC::DIR_970: 13300 case PPC::DIR_PWR4: 13301 case PPC::DIR_PWR5: 13302 case PPC::DIR_PWR5X: 13303 case PPC::DIR_PWR6: 13304 case PPC::DIR_PWR6X: 13305 case PPC::DIR_PWR7: 13306 case PPC::DIR_PWR8: 13307 case PPC::DIR_PWR9: { 13308 if (!ML) 13309 break; 13310 13311 const PPCInstrInfo *TII = Subtarget.getInstrInfo(); 13312 13313 // For small loops (between 5 and 8 instructions), align to a 32-byte 13314 // boundary so that the entire loop fits in one instruction-cache line. 13315 uint64_t LoopSize = 0; 13316 for (auto I = ML->block_begin(), IE = ML->block_end(); I != IE; ++I) 13317 for (auto J = (*I)->begin(), JE = (*I)->end(); J != JE; ++J) { 13318 LoopSize += TII->getInstSizeInBytes(*J); 13319 if (LoopSize > 32) 13320 break; 13321 } 13322 13323 if (LoopSize > 16 && LoopSize <= 32) 13324 return 5; 13325 13326 break; 13327 } 13328 } 13329 13330 return TargetLowering::getPrefLoopAlignment(ML); 13331 } 13332 13333 /// getConstraintType - Given a constraint, return the type of 13334 /// constraint it is for this target. 13335 PPCTargetLowering::ConstraintType 13336 PPCTargetLowering::getConstraintType(StringRef Constraint) const { 13337 if (Constraint.size() == 1) { 13338 switch (Constraint[0]) { 13339 default: break; 13340 case 'b': 13341 case 'r': 13342 case 'f': 13343 case 'd': 13344 case 'v': 13345 case 'y': 13346 return C_RegisterClass; 13347 case 'Z': 13348 // FIXME: While Z does indicate a memory constraint, it specifically 13349 // indicates an r+r address (used in conjunction with the 'y' modifier 13350 // in the replacement string). Currently, we're forcing the base 13351 // register to be r0 in the asm printer (which is interpreted as zero) 13352 // and forming the complete address in the second register. This is 13353 // suboptimal. 13354 return C_Memory; 13355 } 13356 } else if (Constraint == "wc") { // individual CR bits. 13357 return C_RegisterClass; 13358 } else if (Constraint == "wa" || Constraint == "wd" || 13359 Constraint == "wf" || Constraint == "ws" || 13360 Constraint == "wi") { 13361 return C_RegisterClass; // VSX registers. 13362 } 13363 return TargetLowering::getConstraintType(Constraint); 13364 } 13365 13366 /// Examine constraint type and operand type and determine a weight value. 13367 /// This object must already have been set up with the operand type 13368 /// and the current alternative constraint selected. 13369 TargetLowering::ConstraintWeight 13370 PPCTargetLowering::getSingleConstraintMatchWeight( 13371 AsmOperandInfo &info, const char *constraint) const { 13372 ConstraintWeight weight = CW_Invalid; 13373 Value *CallOperandVal = info.CallOperandVal; 13374 // If we don't have a value, we can't do a match, 13375 // but allow it at the lowest weight. 13376 if (!CallOperandVal) 13377 return CW_Default; 13378 Type *type = CallOperandVal->getType(); 13379 13380 // Look at the constraint type. 13381 if (StringRef(constraint) == "wc" && type->isIntegerTy(1)) 13382 return CW_Register; // an individual CR bit. 13383 else if ((StringRef(constraint) == "wa" || 13384 StringRef(constraint) == "wd" || 13385 StringRef(constraint) == "wf") && 13386 type->isVectorTy()) 13387 return CW_Register; 13388 else if (StringRef(constraint) == "ws" && type->isDoubleTy()) 13389 return CW_Register; 13390 else if (StringRef(constraint) == "wi" && type->isIntegerTy(64)) 13391 return CW_Register; // just hold 64-bit integers data. 13392 13393 switch (*constraint) { 13394 default: 13395 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint); 13396 break; 13397 case 'b': 13398 if (type->isIntegerTy()) 13399 weight = CW_Register; 13400 break; 13401 case 'f': 13402 if (type->isFloatTy()) 13403 weight = CW_Register; 13404 break; 13405 case 'd': 13406 if (type->isDoubleTy()) 13407 weight = CW_Register; 13408 break; 13409 case 'v': 13410 if (type->isVectorTy()) 13411 weight = CW_Register; 13412 break; 13413 case 'y': 13414 weight = CW_Register; 13415 break; 13416 case 'Z': 13417 weight = CW_Memory; 13418 break; 13419 } 13420 return weight; 13421 } 13422 13423 std::pair<unsigned, const TargetRegisterClass *> 13424 PPCTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, 13425 StringRef Constraint, 13426 MVT VT) const { 13427 if (Constraint.size() == 1) { 13428 // GCC RS6000 Constraint Letters 13429 switch (Constraint[0]) { 13430 case 'b': // R1-R31 13431 if (VT == MVT::i64 && Subtarget.isPPC64()) 13432 return std::make_pair(0U, &PPC::G8RC_NOX0RegClass); 13433 return std::make_pair(0U, &PPC::GPRC_NOR0RegClass); 13434 case 'r': // R0-R31 13435 if (VT == MVT::i64 && Subtarget.isPPC64()) 13436 return std::make_pair(0U, &PPC::G8RCRegClass); 13437 return std::make_pair(0U, &PPC::GPRCRegClass); 13438 // 'd' and 'f' constraints are both defined to be "the floating point 13439 // registers", where one is for 32-bit and the other for 64-bit. We don't 13440 // really care overly much here so just give them all the same reg classes. 13441 case 'd': 13442 case 'f': 13443 if (Subtarget.hasSPE()) { 13444 if (VT == MVT::f32 || VT == MVT::i32) 13445 return std::make_pair(0U, &PPC::SPE4RCRegClass); 13446 if (VT == MVT::f64 || VT == MVT::i64) 13447 return std::make_pair(0U, &PPC::SPERCRegClass); 13448 } else { 13449 if (VT == MVT::f32 || VT == MVT::i32) 13450 return std::make_pair(0U, &PPC::F4RCRegClass); 13451 if (VT == MVT::f64 || VT == MVT::i64) 13452 return std::make_pair(0U, &PPC::F8RCRegClass); 13453 if (VT == MVT::v4f64 && Subtarget.hasQPX()) 13454 return std::make_pair(0U, &PPC::QFRCRegClass); 13455 if (VT == MVT::v4f32 && Subtarget.hasQPX()) 13456 return std::make_pair(0U, &PPC::QSRCRegClass); 13457 } 13458 break; 13459 case 'v': 13460 if (VT == MVT::v4f64 && Subtarget.hasQPX()) 13461 return std::make_pair(0U, &PPC::QFRCRegClass); 13462 if (VT == MVT::v4f32 && Subtarget.hasQPX()) 13463 return std::make_pair(0U, &PPC::QSRCRegClass); 13464 if (Subtarget.hasAltivec()) 13465 return std::make_pair(0U, &PPC::VRRCRegClass); 13466 break; 13467 case 'y': // crrc 13468 return std::make_pair(0U, &PPC::CRRCRegClass); 13469 } 13470 } else if (Constraint == "wc" && Subtarget.useCRBits()) { 13471 // An individual CR bit. 13472 return std::make_pair(0U, &PPC::CRBITRCRegClass); 13473 } else if ((Constraint == "wa" || Constraint == "wd" || 13474 Constraint == "wf" || Constraint == "wi") && 13475 Subtarget.hasVSX()) { 13476 return std::make_pair(0U, &PPC::VSRCRegClass); 13477 } else if (Constraint == "ws" && Subtarget.hasVSX()) { 13478 if (VT == MVT::f32 && Subtarget.hasP8Vector()) 13479 return std::make_pair(0U, &PPC::VSSRCRegClass); 13480 else 13481 return std::make_pair(0U, &PPC::VSFRCRegClass); 13482 } 13483 13484 std::pair<unsigned, const TargetRegisterClass *> R = 13485 TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 13486 13487 // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers 13488 // (which we call X[0-9]+). If a 64-bit value has been requested, and a 13489 // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent 13490 // register. 13491 // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use 13492 // the AsmName field from *RegisterInfo.td, then this would not be necessary. 13493 if (R.first && VT == MVT::i64 && Subtarget.isPPC64() && 13494 PPC::GPRCRegClass.contains(R.first)) 13495 return std::make_pair(TRI->getMatchingSuperReg(R.first, 13496 PPC::sub_32, &PPC::G8RCRegClass), 13497 &PPC::G8RCRegClass); 13498 13499 // GCC accepts 'cc' as an alias for 'cr0', and we need to do the same. 13500 if (!R.second && StringRef("{cc}").equals_lower(Constraint)) { 13501 R.first = PPC::CR0; 13502 R.second = &PPC::CRRCRegClass; 13503 } 13504 13505 return R; 13506 } 13507 13508 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops 13509 /// vector. If it is invalid, don't add anything to Ops. 13510 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op, 13511 std::string &Constraint, 13512 std::vector<SDValue>&Ops, 13513 SelectionDAG &DAG) const { 13514 SDValue Result; 13515 13516 // Only support length 1 constraints. 13517 if (Constraint.length() > 1) return; 13518 13519 char Letter = Constraint[0]; 13520 switch (Letter) { 13521 default: break; 13522 case 'I': 13523 case 'J': 13524 case 'K': 13525 case 'L': 13526 case 'M': 13527 case 'N': 13528 case 'O': 13529 case 'P': { 13530 ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op); 13531 if (!CST) return; // Must be an immediate to match. 13532 SDLoc dl(Op); 13533 int64_t Value = CST->getSExtValue(); 13534 EVT TCVT = MVT::i64; // All constants taken to be 64 bits so that negative 13535 // numbers are printed as such. 13536 switch (Letter) { 13537 default: llvm_unreachable("Unknown constraint letter!"); 13538 case 'I': // "I" is a signed 16-bit constant. 13539 if (isInt<16>(Value)) 13540 Result = DAG.getTargetConstant(Value, dl, TCVT); 13541 break; 13542 case 'J': // "J" is a constant with only the high-order 16 bits nonzero. 13543 if (isShiftedUInt<16, 16>(Value)) 13544 Result = DAG.getTargetConstant(Value, dl, TCVT); 13545 break; 13546 case 'L': // "L" is a signed 16-bit constant shifted left 16 bits. 13547 if (isShiftedInt<16, 16>(Value)) 13548 Result = DAG.getTargetConstant(Value, dl, TCVT); 13549 break; 13550 case 'K': // "K" is a constant with only the low-order 16 bits nonzero. 13551 if (isUInt<16>(Value)) 13552 Result = DAG.getTargetConstant(Value, dl, TCVT); 13553 break; 13554 case 'M': // "M" is a constant that is greater than 31. 13555 if (Value > 31) 13556 Result = DAG.getTargetConstant(Value, dl, TCVT); 13557 break; 13558 case 'N': // "N" is a positive constant that is an exact power of two. 13559 if (Value > 0 && isPowerOf2_64(Value)) 13560 Result = DAG.getTargetConstant(Value, dl, TCVT); 13561 break; 13562 case 'O': // "O" is the constant zero. 13563 if (Value == 0) 13564 Result = DAG.getTargetConstant(Value, dl, TCVT); 13565 break; 13566 case 'P': // "P" is a constant whose negation is a signed 16-bit constant. 13567 if (isInt<16>(-Value)) 13568 Result = DAG.getTargetConstant(Value, dl, TCVT); 13569 break; 13570 } 13571 break; 13572 } 13573 } 13574 13575 if (Result.getNode()) { 13576 Ops.push_back(Result); 13577 return; 13578 } 13579 13580 // Handle standard constraint letters. 13581 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 13582 } 13583 13584 // isLegalAddressingMode - Return true if the addressing mode represented 13585 // by AM is legal for this target, for a load/store of the specified type. 13586 bool PPCTargetLowering::isLegalAddressingMode(const DataLayout &DL, 13587 const AddrMode &AM, Type *Ty, 13588 unsigned AS, Instruction *I) const { 13589 // PPC does not allow r+i addressing modes for vectors! 13590 if (Ty->isVectorTy() && AM.BaseOffs != 0) 13591 return false; 13592 13593 // PPC allows a sign-extended 16-bit immediate field. 13594 if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1) 13595 return false; 13596 13597 // No global is ever allowed as a base. 13598 if (AM.BaseGV) 13599 return false; 13600 13601 // PPC only support r+r, 13602 switch (AM.Scale) { 13603 case 0: // "r+i" or just "i", depending on HasBaseReg. 13604 break; 13605 case 1: 13606 if (AM.HasBaseReg && AM.BaseOffs) // "r+r+i" is not allowed. 13607 return false; 13608 // Otherwise we have r+r or r+i. 13609 break; 13610 case 2: 13611 if (AM.HasBaseReg || AM.BaseOffs) // 2*r+r or 2*r+i is not allowed. 13612 return false; 13613 // Allow 2*r as r+r. 13614 break; 13615 default: 13616 // No other scales are supported. 13617 return false; 13618 } 13619 13620 return true; 13621 } 13622 13623 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op, 13624 SelectionDAG &DAG) const { 13625 MachineFunction &MF = DAG.getMachineFunction(); 13626 MachineFrameInfo &MFI = MF.getFrameInfo(); 13627 MFI.setReturnAddressIsTaken(true); 13628 13629 if (verifyReturnAddressArgumentIsConstant(Op, DAG)) 13630 return SDValue(); 13631 13632 SDLoc dl(Op); 13633 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 13634 13635 // Make sure the function does not optimize away the store of the RA to 13636 // the stack. 13637 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 13638 FuncInfo->setLRStoreRequired(); 13639 bool isPPC64 = Subtarget.isPPC64(); 13640 auto PtrVT = getPointerTy(MF.getDataLayout()); 13641 13642 if (Depth > 0) { 13643 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG); 13644 SDValue Offset = 13645 DAG.getConstant(Subtarget.getFrameLowering()->getReturnSaveOffset(), dl, 13646 isPPC64 ? MVT::i64 : MVT::i32); 13647 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), 13648 DAG.getNode(ISD::ADD, dl, PtrVT, FrameAddr, Offset), 13649 MachinePointerInfo()); 13650 } 13651 13652 // Just load the return address off the stack. 13653 SDValue RetAddrFI = getReturnAddrFrameIndex(DAG); 13654 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), RetAddrFI, 13655 MachinePointerInfo()); 13656 } 13657 13658 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op, 13659 SelectionDAG &DAG) const { 13660 SDLoc dl(Op); 13661 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 13662 13663 MachineFunction &MF = DAG.getMachineFunction(); 13664 MachineFrameInfo &MFI = MF.getFrameInfo(); 13665 MFI.setFrameAddressIsTaken(true); 13666 13667 EVT PtrVT = getPointerTy(MF.getDataLayout()); 13668 bool isPPC64 = PtrVT == MVT::i64; 13669 13670 // Naked functions never have a frame pointer, and so we use r1. For all 13671 // other functions, this decision must be delayed until during PEI. 13672 unsigned FrameReg; 13673 if (MF.getFunction().hasFnAttribute(Attribute::Naked)) 13674 FrameReg = isPPC64 ? PPC::X1 : PPC::R1; 13675 else 13676 FrameReg = isPPC64 ? PPC::FP8 : PPC::FP; 13677 13678 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, 13679 PtrVT); 13680 while (Depth--) 13681 FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(), 13682 FrameAddr, MachinePointerInfo()); 13683 return FrameAddr; 13684 } 13685 13686 // FIXME? Maybe this could be a TableGen attribute on some registers and 13687 // this table could be generated automatically from RegInfo. 13688 unsigned PPCTargetLowering::getRegisterByName(const char* RegName, EVT VT, 13689 SelectionDAG &DAG) const { 13690 bool isPPC64 = Subtarget.isPPC64(); 13691 bool isDarwinABI = Subtarget.isDarwinABI(); 13692 13693 if ((isPPC64 && VT != MVT::i64 && VT != MVT::i32) || 13694 (!isPPC64 && VT != MVT::i32)) 13695 report_fatal_error("Invalid register global variable type"); 13696 13697 bool is64Bit = isPPC64 && VT == MVT::i64; 13698 unsigned Reg = StringSwitch<unsigned>(RegName) 13699 .Case("r1", is64Bit ? PPC::X1 : PPC::R1) 13700 .Case("r2", (isDarwinABI || isPPC64) ? 0 : PPC::R2) 13701 .Case("r13", (!isPPC64 && isDarwinABI) ? 0 : 13702 (is64Bit ? PPC::X13 : PPC::R13)) 13703 .Default(0); 13704 13705 if (Reg) 13706 return Reg; 13707 report_fatal_error("Invalid register name global variable"); 13708 } 13709 13710 bool 13711 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 13712 // The PowerPC target isn't yet aware of offsets. 13713 return false; 13714 } 13715 13716 bool PPCTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 13717 const CallInst &I, 13718 MachineFunction &MF, 13719 unsigned Intrinsic) const { 13720 switch (Intrinsic) { 13721 case Intrinsic::ppc_qpx_qvlfd: 13722 case Intrinsic::ppc_qpx_qvlfs: 13723 case Intrinsic::ppc_qpx_qvlfcd: 13724 case Intrinsic::ppc_qpx_qvlfcs: 13725 case Intrinsic::ppc_qpx_qvlfiwa: 13726 case Intrinsic::ppc_qpx_qvlfiwz: 13727 case Intrinsic::ppc_altivec_lvx: 13728 case Intrinsic::ppc_altivec_lvxl: 13729 case Intrinsic::ppc_altivec_lvebx: 13730 case Intrinsic::ppc_altivec_lvehx: 13731 case Intrinsic::ppc_altivec_lvewx: 13732 case Intrinsic::ppc_vsx_lxvd2x: 13733 case Intrinsic::ppc_vsx_lxvw4x: { 13734 EVT VT; 13735 switch (Intrinsic) { 13736 case Intrinsic::ppc_altivec_lvebx: 13737 VT = MVT::i8; 13738 break; 13739 case Intrinsic::ppc_altivec_lvehx: 13740 VT = MVT::i16; 13741 break; 13742 case Intrinsic::ppc_altivec_lvewx: 13743 VT = MVT::i32; 13744 break; 13745 case Intrinsic::ppc_vsx_lxvd2x: 13746 VT = MVT::v2f64; 13747 break; 13748 case Intrinsic::ppc_qpx_qvlfd: 13749 VT = MVT::v4f64; 13750 break; 13751 case Intrinsic::ppc_qpx_qvlfs: 13752 VT = MVT::v4f32; 13753 break; 13754 case Intrinsic::ppc_qpx_qvlfcd: 13755 VT = MVT::v2f64; 13756 break; 13757 case Intrinsic::ppc_qpx_qvlfcs: 13758 VT = MVT::v2f32; 13759 break; 13760 default: 13761 VT = MVT::v4i32; 13762 break; 13763 } 13764 13765 Info.opc = ISD::INTRINSIC_W_CHAIN; 13766 Info.memVT = VT; 13767 Info.ptrVal = I.getArgOperand(0); 13768 Info.offset = -VT.getStoreSize()+1; 13769 Info.size = 2*VT.getStoreSize()-1; 13770 Info.align = 1; 13771 Info.flags = MachineMemOperand::MOLoad; 13772 return true; 13773 } 13774 case Intrinsic::ppc_qpx_qvlfda: 13775 case Intrinsic::ppc_qpx_qvlfsa: 13776 case Intrinsic::ppc_qpx_qvlfcda: 13777 case Intrinsic::ppc_qpx_qvlfcsa: 13778 case Intrinsic::ppc_qpx_qvlfiwaa: 13779 case Intrinsic::ppc_qpx_qvlfiwza: { 13780 EVT VT; 13781 switch (Intrinsic) { 13782 case Intrinsic::ppc_qpx_qvlfda: 13783 VT = MVT::v4f64; 13784 break; 13785 case Intrinsic::ppc_qpx_qvlfsa: 13786 VT = MVT::v4f32; 13787 break; 13788 case Intrinsic::ppc_qpx_qvlfcda: 13789 VT = MVT::v2f64; 13790 break; 13791 case Intrinsic::ppc_qpx_qvlfcsa: 13792 VT = MVT::v2f32; 13793 break; 13794 default: 13795 VT = MVT::v4i32; 13796 break; 13797 } 13798 13799 Info.opc = ISD::INTRINSIC_W_CHAIN; 13800 Info.memVT = VT; 13801 Info.ptrVal = I.getArgOperand(0); 13802 Info.offset = 0; 13803 Info.size = VT.getStoreSize(); 13804 Info.align = 1; 13805 Info.flags = MachineMemOperand::MOLoad; 13806 return true; 13807 } 13808 case Intrinsic::ppc_qpx_qvstfd: 13809 case Intrinsic::ppc_qpx_qvstfs: 13810 case Intrinsic::ppc_qpx_qvstfcd: 13811 case Intrinsic::ppc_qpx_qvstfcs: 13812 case Intrinsic::ppc_qpx_qvstfiw: 13813 case Intrinsic::ppc_altivec_stvx: 13814 case Intrinsic::ppc_altivec_stvxl: 13815 case Intrinsic::ppc_altivec_stvebx: 13816 case Intrinsic::ppc_altivec_stvehx: 13817 case Intrinsic::ppc_altivec_stvewx: 13818 case Intrinsic::ppc_vsx_stxvd2x: 13819 case Intrinsic::ppc_vsx_stxvw4x: { 13820 EVT VT; 13821 switch (Intrinsic) { 13822 case Intrinsic::ppc_altivec_stvebx: 13823 VT = MVT::i8; 13824 break; 13825 case Intrinsic::ppc_altivec_stvehx: 13826 VT = MVT::i16; 13827 break; 13828 case Intrinsic::ppc_altivec_stvewx: 13829 VT = MVT::i32; 13830 break; 13831 case Intrinsic::ppc_vsx_stxvd2x: 13832 VT = MVT::v2f64; 13833 break; 13834 case Intrinsic::ppc_qpx_qvstfd: 13835 VT = MVT::v4f64; 13836 break; 13837 case Intrinsic::ppc_qpx_qvstfs: 13838 VT = MVT::v4f32; 13839 break; 13840 case Intrinsic::ppc_qpx_qvstfcd: 13841 VT = MVT::v2f64; 13842 break; 13843 case Intrinsic::ppc_qpx_qvstfcs: 13844 VT = MVT::v2f32; 13845 break; 13846 default: 13847 VT = MVT::v4i32; 13848 break; 13849 } 13850 13851 Info.opc = ISD::INTRINSIC_VOID; 13852 Info.memVT = VT; 13853 Info.ptrVal = I.getArgOperand(1); 13854 Info.offset = -VT.getStoreSize()+1; 13855 Info.size = 2*VT.getStoreSize()-1; 13856 Info.align = 1; 13857 Info.flags = MachineMemOperand::MOStore; 13858 return true; 13859 } 13860 case Intrinsic::ppc_qpx_qvstfda: 13861 case Intrinsic::ppc_qpx_qvstfsa: 13862 case Intrinsic::ppc_qpx_qvstfcda: 13863 case Intrinsic::ppc_qpx_qvstfcsa: 13864 case Intrinsic::ppc_qpx_qvstfiwa: { 13865 EVT VT; 13866 switch (Intrinsic) { 13867 case Intrinsic::ppc_qpx_qvstfda: 13868 VT = MVT::v4f64; 13869 break; 13870 case Intrinsic::ppc_qpx_qvstfsa: 13871 VT = MVT::v4f32; 13872 break; 13873 case Intrinsic::ppc_qpx_qvstfcda: 13874 VT = MVT::v2f64; 13875 break; 13876 case Intrinsic::ppc_qpx_qvstfcsa: 13877 VT = MVT::v2f32; 13878 break; 13879 default: 13880 VT = MVT::v4i32; 13881 break; 13882 } 13883 13884 Info.opc = ISD::INTRINSIC_VOID; 13885 Info.memVT = VT; 13886 Info.ptrVal = I.getArgOperand(1); 13887 Info.offset = 0; 13888 Info.size = VT.getStoreSize(); 13889 Info.align = 1; 13890 Info.flags = MachineMemOperand::MOStore; 13891 return true; 13892 } 13893 default: 13894 break; 13895 } 13896 13897 return false; 13898 } 13899 13900 /// getOptimalMemOpType - Returns the target specific optimal type for load 13901 /// and store operations as a result of memset, memcpy, and memmove 13902 /// lowering. If DstAlign is zero that means it's safe to destination 13903 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it 13904 /// means there isn't a need to check it against alignment requirement, 13905 /// probably because the source does not need to be loaded. If 'IsMemset' is 13906 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that 13907 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy 13908 /// source is constant so it does not need to be loaded. 13909 /// It returns EVT::Other if the type should be determined using generic 13910 /// target-independent logic. 13911 EVT PPCTargetLowering::getOptimalMemOpType(uint64_t Size, 13912 unsigned DstAlign, unsigned SrcAlign, 13913 bool IsMemset, bool ZeroMemset, 13914 bool MemcpyStrSrc, 13915 MachineFunction &MF) const { 13916 if (getTargetMachine().getOptLevel() != CodeGenOpt::None) { 13917 const Function &F = MF.getFunction(); 13918 // When expanding a memset, require at least two QPX instructions to cover 13919 // the cost of loading the value to be stored from the constant pool. 13920 if (Subtarget.hasQPX() && Size >= 32 && (!IsMemset || Size >= 64) && 13921 (!SrcAlign || SrcAlign >= 32) && (!DstAlign || DstAlign >= 32) && 13922 !F.hasFnAttribute(Attribute::NoImplicitFloat)) { 13923 return MVT::v4f64; 13924 } 13925 13926 // We should use Altivec/VSX loads and stores when available. For unaligned 13927 // addresses, unaligned VSX loads are only fast starting with the P8. 13928 if (Subtarget.hasAltivec() && Size >= 16 && 13929 (((!SrcAlign || SrcAlign >= 16) && (!DstAlign || DstAlign >= 16)) || 13930 ((IsMemset && Subtarget.hasVSX()) || Subtarget.hasP8Vector()))) 13931 return MVT::v4i32; 13932 } 13933 13934 if (Subtarget.isPPC64()) { 13935 return MVT::i64; 13936 } 13937 13938 return MVT::i32; 13939 } 13940 13941 /// Returns true if it is beneficial to convert a load of a constant 13942 /// to just the constant itself. 13943 bool PPCTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 13944 Type *Ty) const { 13945 assert(Ty->isIntegerTy()); 13946 13947 unsigned BitSize = Ty->getPrimitiveSizeInBits(); 13948 return !(BitSize == 0 || BitSize > 64); 13949 } 13950 13951 bool PPCTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const { 13952 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy()) 13953 return false; 13954 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits(); 13955 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits(); 13956 return NumBits1 == 64 && NumBits2 == 32; 13957 } 13958 13959 bool PPCTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const { 13960 if (!VT1.isInteger() || !VT2.isInteger()) 13961 return false; 13962 unsigned NumBits1 = VT1.getSizeInBits(); 13963 unsigned NumBits2 = VT2.getSizeInBits(); 13964 return NumBits1 == 64 && NumBits2 == 32; 13965 } 13966 13967 bool PPCTargetLowering::isZExtFree(SDValue Val, EVT VT2) const { 13968 // Generally speaking, zexts are not free, but they are free when they can be 13969 // folded with other operations. 13970 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Val)) { 13971 EVT MemVT = LD->getMemoryVT(); 13972 if ((MemVT == MVT::i1 || MemVT == MVT::i8 || MemVT == MVT::i16 || 13973 (Subtarget.isPPC64() && MemVT == MVT::i32)) && 13974 (LD->getExtensionType() == ISD::NON_EXTLOAD || 13975 LD->getExtensionType() == ISD::ZEXTLOAD)) 13976 return true; 13977 } 13978 13979 // FIXME: Add other cases... 13980 // - 32-bit shifts with a zext to i64 13981 // - zext after ctlz, bswap, etc. 13982 // - zext after and by a constant mask 13983 13984 return TargetLowering::isZExtFree(Val, VT2); 13985 } 13986 13987 bool PPCTargetLowering::isFPExtFree(EVT DestVT, EVT SrcVT) const { 13988 assert(DestVT.isFloatingPoint() && SrcVT.isFloatingPoint() && 13989 "invalid fpext types"); 13990 // Extending to float128 is not free. 13991 if (DestVT == MVT::f128) 13992 return false; 13993 return true; 13994 } 13995 13996 bool PPCTargetLowering::isLegalICmpImmediate(int64_t Imm) const { 13997 return isInt<16>(Imm) || isUInt<16>(Imm); 13998 } 13999 14000 bool PPCTargetLowering::isLegalAddImmediate(int64_t Imm) const { 14001 return isInt<16>(Imm) || isUInt<16>(Imm); 14002 } 14003 14004 bool PPCTargetLowering::allowsMisalignedMemoryAccesses(EVT VT, 14005 unsigned, 14006 unsigned, 14007 bool *Fast) const { 14008 if (DisablePPCUnaligned) 14009 return false; 14010 14011 // PowerPC supports unaligned memory access for simple non-vector types. 14012 // Although accessing unaligned addresses is not as efficient as accessing 14013 // aligned addresses, it is generally more efficient than manual expansion, 14014 // and generally only traps for software emulation when crossing page 14015 // boundaries. 14016 14017 if (!VT.isSimple()) 14018 return false; 14019 14020 if (VT.getSimpleVT().isVector()) { 14021 if (Subtarget.hasVSX()) { 14022 if (VT != MVT::v2f64 && VT != MVT::v2i64 && 14023 VT != MVT::v4f32 && VT != MVT::v4i32) 14024 return false; 14025 } else { 14026 return false; 14027 } 14028 } 14029 14030 if (VT == MVT::ppcf128) 14031 return false; 14032 14033 if (Fast) 14034 *Fast = true; 14035 14036 return true; 14037 } 14038 14039 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const { 14040 VT = VT.getScalarType(); 14041 14042 if (!VT.isSimple()) 14043 return false; 14044 14045 switch (VT.getSimpleVT().SimpleTy) { 14046 case MVT::f32: 14047 case MVT::f64: 14048 return true; 14049 case MVT::f128: 14050 return (EnableQuadPrecision && Subtarget.hasP9Vector()); 14051 default: 14052 break; 14053 } 14054 14055 return false; 14056 } 14057 14058 const MCPhysReg * 14059 PPCTargetLowering::getScratchRegisters(CallingConv::ID) const { 14060 // LR is a callee-save register, but we must treat it as clobbered by any call 14061 // site. Hence we include LR in the scratch registers, which are in turn added 14062 // as implicit-defs for stackmaps and patchpoints. The same reasoning applies 14063 // to CTR, which is used by any indirect call. 14064 static const MCPhysReg ScratchRegs[] = { 14065 PPC::X12, PPC::LR8, PPC::CTR8, 0 14066 }; 14067 14068 return ScratchRegs; 14069 } 14070 14071 unsigned PPCTargetLowering::getExceptionPointerRegister( 14072 const Constant *PersonalityFn) const { 14073 return Subtarget.isPPC64() ? PPC::X3 : PPC::R3; 14074 } 14075 14076 unsigned PPCTargetLowering::getExceptionSelectorRegister( 14077 const Constant *PersonalityFn) const { 14078 return Subtarget.isPPC64() ? PPC::X4 : PPC::R4; 14079 } 14080 14081 bool 14082 PPCTargetLowering::shouldExpandBuildVectorWithShuffles( 14083 EVT VT , unsigned DefinedValues) const { 14084 if (VT == MVT::v2i64) 14085 return Subtarget.hasDirectMove(); // Don't need stack ops with direct moves 14086 14087 if (Subtarget.hasVSX() || Subtarget.hasQPX()) 14088 return true; 14089 14090 return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues); 14091 } 14092 14093 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const { 14094 if (DisableILPPref || Subtarget.enableMachineScheduler()) 14095 return TargetLowering::getSchedulingPreference(N); 14096 14097 return Sched::ILP; 14098 } 14099 14100 // Create a fast isel object. 14101 FastISel * 14102 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo, 14103 const TargetLibraryInfo *LibInfo) const { 14104 return PPC::createFastISel(FuncInfo, LibInfo); 14105 } 14106 14107 void PPCTargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const { 14108 if (Subtarget.isDarwinABI()) return; 14109 if (!Subtarget.isPPC64()) return; 14110 14111 // Update IsSplitCSR in PPCFunctionInfo 14112 PPCFunctionInfo *PFI = Entry->getParent()->getInfo<PPCFunctionInfo>(); 14113 PFI->setIsSplitCSR(true); 14114 } 14115 14116 void PPCTargetLowering::insertCopiesSplitCSR( 14117 MachineBasicBlock *Entry, 14118 const SmallVectorImpl<MachineBasicBlock *> &Exits) const { 14119 const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo(); 14120 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent()); 14121 if (!IStart) 14122 return; 14123 14124 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 14125 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo(); 14126 MachineBasicBlock::iterator MBBI = Entry->begin(); 14127 for (const MCPhysReg *I = IStart; *I; ++I) { 14128 const TargetRegisterClass *RC = nullptr; 14129 if (PPC::G8RCRegClass.contains(*I)) 14130 RC = &PPC::G8RCRegClass; 14131 else if (PPC::F8RCRegClass.contains(*I)) 14132 RC = &PPC::F8RCRegClass; 14133 else if (PPC::CRRCRegClass.contains(*I)) 14134 RC = &PPC::CRRCRegClass; 14135 else if (PPC::VRRCRegClass.contains(*I)) 14136 RC = &PPC::VRRCRegClass; 14137 else 14138 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 14139 14140 unsigned NewVR = MRI->createVirtualRegister(RC); 14141 // Create copy from CSR to a virtual register. 14142 // FIXME: this currently does not emit CFI pseudo-instructions, it works 14143 // fine for CXX_FAST_TLS since the C++-style TLS access functions should be 14144 // nounwind. If we want to generalize this later, we may need to emit 14145 // CFI pseudo-instructions. 14146 assert(Entry->getParent()->getFunction().hasFnAttribute( 14147 Attribute::NoUnwind) && 14148 "Function should be nounwind in insertCopiesSplitCSR!"); 14149 Entry->addLiveIn(*I); 14150 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR) 14151 .addReg(*I); 14152 14153 // Insert the copy-back instructions right before the terminator 14154 for (auto *Exit : Exits) 14155 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(), 14156 TII->get(TargetOpcode::COPY), *I) 14157 .addReg(NewVR); 14158 } 14159 } 14160 14161 // Override to enable LOAD_STACK_GUARD lowering on Linux. 14162 bool PPCTargetLowering::useLoadStackGuardNode() const { 14163 if (!Subtarget.isTargetLinux()) 14164 return TargetLowering::useLoadStackGuardNode(); 14165 return true; 14166 } 14167 14168 // Override to disable global variable loading on Linux. 14169 void PPCTargetLowering::insertSSPDeclarations(Module &M) const { 14170 if (!Subtarget.isTargetLinux()) 14171 return TargetLowering::insertSSPDeclarations(M); 14172 } 14173 14174 bool PPCTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const { 14175 if (!VT.isSimple() || !Subtarget.hasVSX()) 14176 return false; 14177 14178 switch(VT.getSimpleVT().SimpleTy) { 14179 default: 14180 // For FP types that are currently not supported by PPC backend, return 14181 // false. Examples: f16, f80. 14182 return false; 14183 case MVT::f32: 14184 case MVT::f64: 14185 case MVT::ppcf128: 14186 return Imm.isPosZero(); 14187 } 14188 } 14189 14190 // For vector shift operation op, fold 14191 // (op x, (and y, ((1 << numbits(x)) - 1))) -> (target op x, y) 14192 static SDValue stripModuloOnShift(const TargetLowering &TLI, SDNode *N, 14193 SelectionDAG &DAG) { 14194 SDValue N0 = N->getOperand(0); 14195 SDValue N1 = N->getOperand(1); 14196 EVT VT = N0.getValueType(); 14197 unsigned OpSizeInBits = VT.getScalarSizeInBits(); 14198 unsigned Opcode = N->getOpcode(); 14199 unsigned TargetOpcode; 14200 14201 switch (Opcode) { 14202 default: 14203 llvm_unreachable("Unexpected shift operation"); 14204 case ISD::SHL: 14205 TargetOpcode = PPCISD::SHL; 14206 break; 14207 case ISD::SRL: 14208 TargetOpcode = PPCISD::SRL; 14209 break; 14210 case ISD::SRA: 14211 TargetOpcode = PPCISD::SRA; 14212 break; 14213 } 14214 14215 if (VT.isVector() && TLI.isOperationLegal(Opcode, VT) && 14216 N1->getOpcode() == ISD::AND) 14217 if (ConstantSDNode *Mask = isConstOrConstSplat(N1->getOperand(1))) 14218 if (Mask->getZExtValue() == OpSizeInBits - 1) 14219 return DAG.getNode(TargetOpcode, SDLoc(N), VT, N0, N1->getOperand(0)); 14220 14221 return SDValue(); 14222 } 14223 14224 SDValue PPCTargetLowering::combineSHL(SDNode *N, DAGCombinerInfo &DCI) const { 14225 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG)) 14226 return Value; 14227 14228 SDValue N0 = N->getOperand(0); 14229 ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N->getOperand(1)); 14230 if (!Subtarget.isISA3_0() || 14231 N0.getOpcode() != ISD::SIGN_EXTEND || 14232 N0.getOperand(0).getValueType() != MVT::i32 || 14233 CN1 == nullptr || N->getValueType(0) != MVT::i64) 14234 return SDValue(); 14235 14236 // We can't save an operation here if the value is already extended, and 14237 // the existing shift is easier to combine. 14238 SDValue ExtsSrc = N0.getOperand(0); 14239 if (ExtsSrc.getOpcode() == ISD::TRUNCATE && 14240 ExtsSrc.getOperand(0).getOpcode() == ISD::AssertSext) 14241 return SDValue(); 14242 14243 SDLoc DL(N0); 14244 SDValue ShiftBy = SDValue(CN1, 0); 14245 // We want the shift amount to be i32 on the extswli, but the shift could 14246 // have an i64. 14247 if (ShiftBy.getValueType() == MVT::i64) 14248 ShiftBy = DCI.DAG.getConstant(CN1->getZExtValue(), DL, MVT::i32); 14249 14250 return DCI.DAG.getNode(PPCISD::EXTSWSLI, DL, MVT::i64, N0->getOperand(0), 14251 ShiftBy); 14252 } 14253 14254 SDValue PPCTargetLowering::combineSRA(SDNode *N, DAGCombinerInfo &DCI) const { 14255 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG)) 14256 return Value; 14257 14258 return SDValue(); 14259 } 14260 14261 SDValue PPCTargetLowering::combineSRL(SDNode *N, DAGCombinerInfo &DCI) const { 14262 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG)) 14263 return Value; 14264 14265 return SDValue(); 14266 } 14267 14268 // Transform (add X, (zext(setne Z, C))) -> (addze X, (addic (addi Z, -C), -1)) 14269 // Transform (add X, (zext(sete Z, C))) -> (addze X, (subfic (addi Z, -C), 0)) 14270 // When C is zero, the equation (addi Z, -C) can be simplified to Z 14271 // Requirement: -C in [-32768, 32767], X and Z are MVT::i64 types 14272 static SDValue combineADDToADDZE(SDNode *N, SelectionDAG &DAG, 14273 const PPCSubtarget &Subtarget) { 14274 if (!Subtarget.isPPC64()) 14275 return SDValue(); 14276 14277 SDValue LHS = N->getOperand(0); 14278 SDValue RHS = N->getOperand(1); 14279 14280 auto isZextOfCompareWithConstant = [](SDValue Op) { 14281 if (Op.getOpcode() != ISD::ZERO_EXTEND || !Op.hasOneUse() || 14282 Op.getValueType() != MVT::i64) 14283 return false; 14284 14285 SDValue Cmp = Op.getOperand(0); 14286 if (Cmp.getOpcode() != ISD::SETCC || !Cmp.hasOneUse() || 14287 Cmp.getOperand(0).getValueType() != MVT::i64) 14288 return false; 14289 14290 if (auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1))) { 14291 int64_t NegConstant = 0 - Constant->getSExtValue(); 14292 // Due to the limitations of the addi instruction, 14293 // -C is required to be [-32768, 32767]. 14294 return isInt<16>(NegConstant); 14295 } 14296 14297 return false; 14298 }; 14299 14300 bool LHSHasPattern = isZextOfCompareWithConstant(LHS); 14301 bool RHSHasPattern = isZextOfCompareWithConstant(RHS); 14302 14303 // If there is a pattern, canonicalize a zext operand to the RHS. 14304 if (LHSHasPattern && !RHSHasPattern) 14305 std::swap(LHS, RHS); 14306 else if (!LHSHasPattern && !RHSHasPattern) 14307 return SDValue(); 14308 14309 SDLoc DL(N); 14310 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i64); 14311 SDValue Cmp = RHS.getOperand(0); 14312 SDValue Z = Cmp.getOperand(0); 14313 auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1)); 14314 14315 assert(Constant && "Constant Should not be a null pointer."); 14316 int64_t NegConstant = 0 - Constant->getSExtValue(); 14317 14318 switch(cast<CondCodeSDNode>(Cmp.getOperand(2))->get()) { 14319 default: break; 14320 case ISD::SETNE: { 14321 // when C == 0 14322 // --> addze X, (addic Z, -1).carry 14323 // / 14324 // add X, (zext(setne Z, C))-- 14325 // \ when -32768 <= -C <= 32767 && C != 0 14326 // --> addze X, (addic (addi Z, -C), -1).carry 14327 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z, 14328 DAG.getConstant(NegConstant, DL, MVT::i64)); 14329 SDValue AddOrZ = NegConstant != 0 ? Add : Z; 14330 SDValue Addc = DAG.getNode(ISD::ADDC, DL, DAG.getVTList(MVT::i64, MVT::Glue), 14331 AddOrZ, DAG.getConstant(-1ULL, DL, MVT::i64)); 14332 return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64), 14333 SDValue(Addc.getNode(), 1)); 14334 } 14335 case ISD::SETEQ: { 14336 // when C == 0 14337 // --> addze X, (subfic Z, 0).carry 14338 // / 14339 // add X, (zext(sete Z, C))-- 14340 // \ when -32768 <= -C <= 32767 && C != 0 14341 // --> addze X, (subfic (addi Z, -C), 0).carry 14342 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z, 14343 DAG.getConstant(NegConstant, DL, MVT::i64)); 14344 SDValue AddOrZ = NegConstant != 0 ? Add : Z; 14345 SDValue Subc = DAG.getNode(ISD::SUBC, DL, DAG.getVTList(MVT::i64, MVT::Glue), 14346 DAG.getConstant(0, DL, MVT::i64), AddOrZ); 14347 return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64), 14348 SDValue(Subc.getNode(), 1)); 14349 } 14350 } 14351 14352 return SDValue(); 14353 } 14354 14355 SDValue PPCTargetLowering::combineADD(SDNode *N, DAGCombinerInfo &DCI) const { 14356 if (auto Value = combineADDToADDZE(N, DCI.DAG, Subtarget)) 14357 return Value; 14358 14359 return SDValue(); 14360 } 14361 14362 // Detect TRUNCATE operations on bitcasts of float128 values. 14363 // What we are looking for here is the situtation where we extract a subset 14364 // of bits from a 128 bit float. 14365 // This can be of two forms: 14366 // 1) BITCAST of f128 feeding TRUNCATE 14367 // 2) BITCAST of f128 feeding SRL (a shift) feeding TRUNCATE 14368 // The reason this is required is because we do not have a legal i128 type 14369 // and so we want to prevent having to store the f128 and then reload part 14370 // of it. 14371 SDValue PPCTargetLowering::combineTRUNCATE(SDNode *N, 14372 DAGCombinerInfo &DCI) const { 14373 // If we are using CRBits then try that first. 14374 if (Subtarget.useCRBits()) { 14375 // Check if CRBits did anything and return that if it did. 14376 if (SDValue CRTruncValue = DAGCombineTruncBoolExt(N, DCI)) 14377 return CRTruncValue; 14378 } 14379 14380 SDLoc dl(N); 14381 SDValue Op0 = N->getOperand(0); 14382 14383 // Looking for a truncate of i128 to i64. 14384 if (Op0.getValueType() != MVT::i128 || N->getValueType(0) != MVT::i64) 14385 return SDValue(); 14386 14387 int EltToExtract = DCI.DAG.getDataLayout().isBigEndian() ? 1 : 0; 14388 14389 // SRL feeding TRUNCATE. 14390 if (Op0.getOpcode() == ISD::SRL) { 14391 ConstantSDNode *ConstNode = dyn_cast<ConstantSDNode>(Op0.getOperand(1)); 14392 // The right shift has to be by 64 bits. 14393 if (!ConstNode || ConstNode->getZExtValue() != 64) 14394 return SDValue(); 14395 14396 // Switch the element number to extract. 14397 EltToExtract = EltToExtract ? 0 : 1; 14398 // Update Op0 past the SRL. 14399 Op0 = Op0.getOperand(0); 14400 } 14401 14402 // BITCAST feeding a TRUNCATE possibly via SRL. 14403 if (Op0.getOpcode() == ISD::BITCAST && 14404 Op0.getValueType() == MVT::i128 && 14405 Op0.getOperand(0).getValueType() == MVT::f128) { 14406 SDValue Bitcast = DCI.DAG.getBitcast(MVT::v2i64, Op0.getOperand(0)); 14407 return DCI.DAG.getNode( 14408 ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Bitcast, 14409 DCI.DAG.getTargetConstant(EltToExtract, dl, MVT::i32)); 14410 } 14411 return SDValue(); 14412 } 14413 14414 bool PPCTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 14415 // Only duplicate to increase tail-calls for the 64bit SysV ABIs. 14416 if (!Subtarget.isSVR4ABI() || !Subtarget.isPPC64()) 14417 return false; 14418 14419 // If not a tail call then no need to proceed. 14420 if (!CI->isTailCall()) 14421 return false; 14422 14423 // If tail calls are disabled for the caller then we are done. 14424 const Function *Caller = CI->getParent()->getParent(); 14425 auto Attr = Caller->getFnAttribute("disable-tail-calls"); 14426 if (Attr.getValueAsString() == "true") 14427 return false; 14428 14429 // If sibling calls have been disabled and tail-calls aren't guaranteed 14430 // there is no reason to duplicate. 14431 auto &TM = getTargetMachine(); 14432 if (!TM.Options.GuaranteedTailCallOpt && DisableSCO) 14433 return false; 14434 14435 // Can't tail call a function called indirectly, or if it has variadic args. 14436 const Function *Callee = CI->getCalledFunction(); 14437 if (!Callee || Callee->isVarArg()) 14438 return false; 14439 14440 // Make sure the callee and caller calling conventions are eligible for tco. 14441 if (!areCallingConvEligibleForTCO_64SVR4(Caller->getCallingConv(), 14442 CI->getCallingConv())) 14443 return false; 14444 14445 // If the function is local then we have a good chance at tail-calling it 14446 return getTargetMachine().shouldAssumeDSOLocal(*Caller->getParent(), Callee); 14447 } 14448 14449 bool PPCTargetLowering::hasBitPreservingFPLogic(EVT VT) const { 14450 if (!Subtarget.hasVSX()) 14451 return false; 14452 if (Subtarget.hasP9Vector() && VT == MVT::f128) 14453 return true; 14454 return VT == MVT::f32 || VT == MVT::f64 || 14455 VT == MVT::v4f32 || VT == MVT::v2f64; 14456 } 14457 14458 bool PPCTargetLowering:: 14459 isMaskAndCmp0FoldingBeneficial(const Instruction &AndI) const { 14460 const Value *Mask = AndI.getOperand(1); 14461 // If the mask is suitable for andi. or andis. we should sink the and. 14462 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Mask)) { 14463 // Can't handle constants wider than 64-bits. 14464 if (CI->getBitWidth() > 64) 14465 return false; 14466 int64_t ConstVal = CI->getZExtValue(); 14467 return isUInt<16>(ConstVal) || 14468 (isUInt<16>(ConstVal >> 16) && !(ConstVal & 0xFFFF)); 14469 } 14470 14471 // For non-constant masks, we can always use the record-form and. 14472 return true; 14473 } 14474