1 //===-- PPCISelLowering.cpp - PPC DAG Lowering Implementation -------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements the PPCISelLowering class. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "PPCISelLowering.h" 14 #include "MCTargetDesc/PPCPredicates.h" 15 #include "PPC.h" 16 #include "PPCCCState.h" 17 #include "PPCCallingConv.h" 18 #include "PPCFrameLowering.h" 19 #include "PPCInstrInfo.h" 20 #include "PPCMachineFunctionInfo.h" 21 #include "PPCPerfectShuffle.h" 22 #include "PPCRegisterInfo.h" 23 #include "PPCSubtarget.h" 24 #include "PPCTargetMachine.h" 25 #include "llvm/ADT/APFloat.h" 26 #include "llvm/ADT/APInt.h" 27 #include "llvm/ADT/ArrayRef.h" 28 #include "llvm/ADT/DenseMap.h" 29 #include "llvm/ADT/None.h" 30 #include "llvm/ADT/STLExtras.h" 31 #include "llvm/ADT/SmallPtrSet.h" 32 #include "llvm/ADT/SmallSet.h" 33 #include "llvm/ADT/SmallVector.h" 34 #include "llvm/ADT/Statistic.h" 35 #include "llvm/ADT/StringRef.h" 36 #include "llvm/ADT/StringSwitch.h" 37 #include "llvm/CodeGen/CallingConvLower.h" 38 #include "llvm/CodeGen/ISDOpcodes.h" 39 #include "llvm/CodeGen/MachineBasicBlock.h" 40 #include "llvm/CodeGen/MachineFrameInfo.h" 41 #include "llvm/CodeGen/MachineFunction.h" 42 #include "llvm/CodeGen/MachineInstr.h" 43 #include "llvm/CodeGen/MachineInstrBuilder.h" 44 #include "llvm/CodeGen/MachineJumpTableInfo.h" 45 #include "llvm/CodeGen/MachineLoopInfo.h" 46 #include "llvm/CodeGen/MachineMemOperand.h" 47 #include "llvm/CodeGen/MachineModuleInfo.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/MCContext.h" 74 #include "llvm/MC/MCExpr.h" 75 #include "llvm/MC/MCRegisterInfo.h" 76 #include "llvm/MC/MCSymbolXCOFF.h" 77 #include "llvm/Support/AtomicOrdering.h" 78 #include "llvm/Support/BranchProbability.h" 79 #include "llvm/Support/Casting.h" 80 #include "llvm/Support/CodeGen.h" 81 #include "llvm/Support/CommandLine.h" 82 #include "llvm/Support/Compiler.h" 83 #include "llvm/Support/Debug.h" 84 #include "llvm/Support/ErrorHandling.h" 85 #include "llvm/Support/Format.h" 86 #include "llvm/Support/KnownBits.h" 87 #include "llvm/Support/MachineValueType.h" 88 #include "llvm/Support/MathExtras.h" 89 #include "llvm/Support/raw_ostream.h" 90 #include "llvm/Target/TargetMachine.h" 91 #include "llvm/Target/TargetOptions.h" 92 #include <algorithm> 93 #include <cassert> 94 #include <cstdint> 95 #include <iterator> 96 #include <list> 97 #include <utility> 98 #include <vector> 99 100 using namespace llvm; 101 102 #define DEBUG_TYPE "ppc-lowering" 103 104 static cl::opt<bool> DisablePPCPreinc("disable-ppc-preinc", 105 cl::desc("disable preincrement load/store generation on PPC"), cl::Hidden); 106 107 static cl::opt<bool> DisableILPPref("disable-ppc-ilp-pref", 108 cl::desc("disable setting the node scheduling preference to ILP on PPC"), cl::Hidden); 109 110 static cl::opt<bool> DisablePPCUnaligned("disable-ppc-unaligned", 111 cl::desc("disable unaligned load/store generation on PPC"), cl::Hidden); 112 113 static cl::opt<bool> DisableSCO("disable-ppc-sco", 114 cl::desc("disable sibling call optimization on ppc"), cl::Hidden); 115 116 static cl::opt<bool> DisableInnermostLoopAlign32("disable-ppc-innermost-loop-align32", 117 cl::desc("don't always align innermost loop to 32 bytes on ppc"), cl::Hidden); 118 119 static cl::opt<bool> EnableQuadPrecision("enable-ppc-quad-precision", 120 cl::desc("enable quad precision float support on ppc"), cl::Hidden); 121 122 STATISTIC(NumTailCalls, "Number of tail calls"); 123 STATISTIC(NumSiblingCalls, "Number of sibling calls"); 124 125 static bool isNByteElemShuffleMask(ShuffleVectorSDNode *, unsigned, int); 126 127 static SDValue widenVec(SelectionDAG &DAG, SDValue Vec, const SDLoc &dl); 128 129 // FIXME: Remove this once the bug has been fixed! 130 extern cl::opt<bool> ANDIGlueBug; 131 132 PPCTargetLowering::PPCTargetLowering(const PPCTargetMachine &TM, 133 const PPCSubtarget &STI) 134 : TargetLowering(TM), Subtarget(STI) { 135 // Use _setjmp/_longjmp instead of setjmp/longjmp. 136 setUseUnderscoreSetJmp(true); 137 setUseUnderscoreLongJmp(true); 138 139 // On PPC32/64, arguments smaller than 4/8 bytes are extended, so all 140 // arguments are at least 4/8 bytes aligned. 141 bool isPPC64 = Subtarget.isPPC64(); 142 setMinStackArgumentAlignment(isPPC64 ? 8:4); 143 144 // Set up the register classes. 145 addRegisterClass(MVT::i32, &PPC::GPRCRegClass); 146 if (!useSoftFloat()) { 147 if (hasSPE()) { 148 addRegisterClass(MVT::f32, &PPC::SPE4RCRegClass); 149 addRegisterClass(MVT::f64, &PPC::SPERCRegClass); 150 } else { 151 addRegisterClass(MVT::f32, &PPC::F4RCRegClass); 152 addRegisterClass(MVT::f64, &PPC::F8RCRegClass); 153 } 154 } 155 156 // Match BITREVERSE to customized fast code sequence in the td file. 157 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal); 158 setOperationAction(ISD::BITREVERSE, MVT::i64, Legal); 159 160 // Sub-word ATOMIC_CMP_SWAP need to ensure that the input is zero-extended. 161 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom); 162 163 // PowerPC has an i16 but no i8 (or i1) SEXTLOAD. 164 for (MVT VT : MVT::integer_valuetypes()) { 165 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote); 166 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i8, Expand); 167 } 168 169 setTruncStoreAction(MVT::f64, MVT::f32, Expand); 170 171 // PowerPC has pre-inc load and store's. 172 setIndexedLoadAction(ISD::PRE_INC, MVT::i1, Legal); 173 setIndexedLoadAction(ISD::PRE_INC, MVT::i8, Legal); 174 setIndexedLoadAction(ISD::PRE_INC, MVT::i16, Legal); 175 setIndexedLoadAction(ISD::PRE_INC, MVT::i32, Legal); 176 setIndexedLoadAction(ISD::PRE_INC, MVT::i64, Legal); 177 setIndexedStoreAction(ISD::PRE_INC, MVT::i1, Legal); 178 setIndexedStoreAction(ISD::PRE_INC, MVT::i8, Legal); 179 setIndexedStoreAction(ISD::PRE_INC, MVT::i16, Legal); 180 setIndexedStoreAction(ISD::PRE_INC, MVT::i32, Legal); 181 setIndexedStoreAction(ISD::PRE_INC, MVT::i64, Legal); 182 if (!Subtarget.hasSPE()) { 183 setIndexedLoadAction(ISD::PRE_INC, MVT::f32, Legal); 184 setIndexedLoadAction(ISD::PRE_INC, MVT::f64, Legal); 185 setIndexedStoreAction(ISD::PRE_INC, MVT::f32, Legal); 186 setIndexedStoreAction(ISD::PRE_INC, MVT::f64, Legal); 187 } 188 189 // PowerPC uses ADDC/ADDE/SUBC/SUBE to propagate carry. 190 const MVT ScalarIntVTs[] = { MVT::i32, MVT::i64 }; 191 for (MVT VT : ScalarIntVTs) { 192 setOperationAction(ISD::ADDC, VT, Legal); 193 setOperationAction(ISD::ADDE, VT, Legal); 194 setOperationAction(ISD::SUBC, VT, Legal); 195 setOperationAction(ISD::SUBE, VT, Legal); 196 } 197 198 if (Subtarget.useCRBits()) { 199 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); 200 201 if (isPPC64 || Subtarget.hasFPCVT()) { 202 setOperationAction(ISD::SINT_TO_FP, MVT::i1, Promote); 203 AddPromotedToType (ISD::SINT_TO_FP, MVT::i1, 204 isPPC64 ? MVT::i64 : MVT::i32); 205 setOperationAction(ISD::UINT_TO_FP, MVT::i1, Promote); 206 AddPromotedToType(ISD::UINT_TO_FP, MVT::i1, 207 isPPC64 ? MVT::i64 : MVT::i32); 208 } else { 209 setOperationAction(ISD::SINT_TO_FP, MVT::i1, Custom); 210 setOperationAction(ISD::UINT_TO_FP, MVT::i1, Custom); 211 } 212 213 // PowerPC does not support direct load/store of condition registers. 214 setOperationAction(ISD::LOAD, MVT::i1, Custom); 215 setOperationAction(ISD::STORE, MVT::i1, Custom); 216 217 // FIXME: Remove this once the ANDI glue bug is fixed: 218 if (ANDIGlueBug) 219 setOperationAction(ISD::TRUNCATE, MVT::i1, Custom); 220 221 for (MVT VT : MVT::integer_valuetypes()) { 222 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote); 223 setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote); 224 setTruncStoreAction(VT, MVT::i1, Expand); 225 } 226 227 addRegisterClass(MVT::i1, &PPC::CRBITRCRegClass); 228 } 229 230 // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on 231 // PPC (the libcall is not available). 232 setOperationAction(ISD::FP_TO_SINT, MVT::ppcf128, Custom); 233 setOperationAction(ISD::FP_TO_UINT, MVT::ppcf128, Custom); 234 235 // We do not currently implement these libm ops for PowerPC. 236 setOperationAction(ISD::FFLOOR, MVT::ppcf128, Expand); 237 setOperationAction(ISD::FCEIL, MVT::ppcf128, Expand); 238 setOperationAction(ISD::FTRUNC, MVT::ppcf128, Expand); 239 setOperationAction(ISD::FRINT, MVT::ppcf128, Expand); 240 setOperationAction(ISD::FNEARBYINT, MVT::ppcf128, Expand); 241 setOperationAction(ISD::FREM, MVT::ppcf128, Expand); 242 243 // PowerPC has no SREM/UREM instructions unless we are on P9 244 // On P9 we may use a hardware instruction to compute the remainder. 245 // The instructions are not legalized directly because in the cases where the 246 // result of both the remainder and the division is required it is more 247 // efficient to compute the remainder from the result of the division rather 248 // than use the remainder instruction. 249 if (Subtarget.isISA3_0()) { 250 setOperationAction(ISD::SREM, MVT::i32, Custom); 251 setOperationAction(ISD::UREM, MVT::i32, Custom); 252 setOperationAction(ISD::SREM, MVT::i64, Custom); 253 setOperationAction(ISD::UREM, MVT::i64, Custom); 254 } else { 255 setOperationAction(ISD::SREM, MVT::i32, Expand); 256 setOperationAction(ISD::UREM, MVT::i32, Expand); 257 setOperationAction(ISD::SREM, MVT::i64, Expand); 258 setOperationAction(ISD::UREM, MVT::i64, Expand); 259 } 260 261 // Don't use SMUL_LOHI/UMUL_LOHI or SDIVREM/UDIVREM to lower SREM/UREM. 262 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand); 263 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand); 264 setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand); 265 setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand); 266 setOperationAction(ISD::UDIVREM, MVT::i32, Expand); 267 setOperationAction(ISD::SDIVREM, MVT::i32, Expand); 268 setOperationAction(ISD::UDIVREM, MVT::i64, Expand); 269 setOperationAction(ISD::SDIVREM, MVT::i64, Expand); 270 271 // We don't support sin/cos/sqrt/fmod/pow 272 setOperationAction(ISD::FSIN , MVT::f64, Expand); 273 setOperationAction(ISD::FCOS , MVT::f64, Expand); 274 setOperationAction(ISD::FSINCOS, MVT::f64, Expand); 275 setOperationAction(ISD::FREM , MVT::f64, Expand); 276 setOperationAction(ISD::FPOW , MVT::f64, Expand); 277 setOperationAction(ISD::FSIN , MVT::f32, Expand); 278 setOperationAction(ISD::FCOS , MVT::f32, Expand); 279 setOperationAction(ISD::FSINCOS, MVT::f32, Expand); 280 setOperationAction(ISD::FREM , MVT::f32, Expand); 281 setOperationAction(ISD::FPOW , MVT::f32, Expand); 282 if (Subtarget.hasSPE()) { 283 setOperationAction(ISD::FMA , MVT::f64, Expand); 284 setOperationAction(ISD::FMA , MVT::f32, Expand); 285 } else { 286 setOperationAction(ISD::FMA , MVT::f64, Legal); 287 setOperationAction(ISD::FMA , MVT::f32, Legal); 288 } 289 290 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom); 291 292 // If we're enabling GP optimizations, use hardware square root 293 if (!Subtarget.hasFSQRT() && 294 !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTE() && 295 Subtarget.hasFRE())) 296 setOperationAction(ISD::FSQRT, MVT::f64, Expand); 297 298 if (!Subtarget.hasFSQRT() && 299 !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTES() && 300 Subtarget.hasFRES())) 301 setOperationAction(ISD::FSQRT, MVT::f32, Expand); 302 303 if (Subtarget.hasFCPSGN()) { 304 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Legal); 305 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Legal); 306 } else { 307 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand); 308 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand); 309 } 310 311 if (Subtarget.hasFPRND()) { 312 setOperationAction(ISD::FFLOOR, MVT::f64, Legal); 313 setOperationAction(ISD::FCEIL, MVT::f64, Legal); 314 setOperationAction(ISD::FTRUNC, MVT::f64, Legal); 315 setOperationAction(ISD::FROUND, MVT::f64, Legal); 316 317 setOperationAction(ISD::FFLOOR, MVT::f32, Legal); 318 setOperationAction(ISD::FCEIL, MVT::f32, Legal); 319 setOperationAction(ISD::FTRUNC, MVT::f32, Legal); 320 setOperationAction(ISD::FROUND, MVT::f32, Legal); 321 } 322 323 // PowerPC does not have BSWAP, but we can use vector BSWAP instruction xxbrd 324 // to speed up scalar BSWAP64. 325 // CTPOP or CTTZ were introduced in P8/P9 respectively 326 setOperationAction(ISD::BSWAP, MVT::i32 , Expand); 327 if (Subtarget.hasP9Vector()) 328 setOperationAction(ISD::BSWAP, MVT::i64 , Custom); 329 else 330 setOperationAction(ISD::BSWAP, MVT::i64 , Expand); 331 if (Subtarget.isISA3_0()) { 332 setOperationAction(ISD::CTTZ , MVT::i32 , Legal); 333 setOperationAction(ISD::CTTZ , MVT::i64 , Legal); 334 } else { 335 setOperationAction(ISD::CTTZ , MVT::i32 , Expand); 336 setOperationAction(ISD::CTTZ , MVT::i64 , Expand); 337 } 338 339 if (Subtarget.hasPOPCNTD() == PPCSubtarget::POPCNTD_Fast) { 340 setOperationAction(ISD::CTPOP, MVT::i32 , Legal); 341 setOperationAction(ISD::CTPOP, MVT::i64 , Legal); 342 } else { 343 setOperationAction(ISD::CTPOP, MVT::i32 , Expand); 344 setOperationAction(ISD::CTPOP, MVT::i64 , Expand); 345 } 346 347 // PowerPC does not have ROTR 348 setOperationAction(ISD::ROTR, MVT::i32 , Expand); 349 setOperationAction(ISD::ROTR, MVT::i64 , Expand); 350 351 if (!Subtarget.useCRBits()) { 352 // PowerPC does not have Select 353 setOperationAction(ISD::SELECT, MVT::i32, Expand); 354 setOperationAction(ISD::SELECT, MVT::i64, Expand); 355 setOperationAction(ISD::SELECT, MVT::f32, Expand); 356 setOperationAction(ISD::SELECT, MVT::f64, Expand); 357 } 358 359 // PowerPC wants to turn select_cc of FP into fsel when possible. 360 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom); 361 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom); 362 363 // PowerPC wants to optimize integer setcc a bit 364 if (!Subtarget.useCRBits()) 365 setOperationAction(ISD::SETCC, MVT::i32, Custom); 366 367 // PowerPC does not have BRCOND which requires SetCC 368 if (!Subtarget.useCRBits()) 369 setOperationAction(ISD::BRCOND, MVT::Other, Expand); 370 371 setOperationAction(ISD::BR_JT, MVT::Other, Expand); 372 373 if (Subtarget.hasSPE()) { 374 // SPE has built-in conversions 375 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Legal); 376 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Legal); 377 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Legal); 378 } else { 379 // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores. 380 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 381 382 // PowerPC does not have [U|S]INT_TO_FP 383 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Expand); 384 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand); 385 } 386 387 if (Subtarget.hasDirectMove() && isPPC64) { 388 setOperationAction(ISD::BITCAST, MVT::f32, Legal); 389 setOperationAction(ISD::BITCAST, MVT::i32, Legal); 390 setOperationAction(ISD::BITCAST, MVT::i64, Legal); 391 setOperationAction(ISD::BITCAST, MVT::f64, Legal); 392 } else { 393 setOperationAction(ISD::BITCAST, MVT::f32, Expand); 394 setOperationAction(ISD::BITCAST, MVT::i32, Expand); 395 setOperationAction(ISD::BITCAST, MVT::i64, Expand); 396 setOperationAction(ISD::BITCAST, MVT::f64, Expand); 397 } 398 399 // We cannot sextinreg(i1). Expand to shifts. 400 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); 401 402 // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support 403 // SjLj exception handling but a light-weight setjmp/longjmp replacement to 404 // support continuation, user-level threading, and etc.. As a result, no 405 // other SjLj exception interfaces are implemented and please don't build 406 // your own exception handling based on them. 407 // LLVM/Clang supports zero-cost DWARF exception handling. 408 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom); 409 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom); 410 411 // We want to legalize GlobalAddress and ConstantPool nodes into the 412 // appropriate instructions to materialize the address. 413 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom); 414 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom); 415 setOperationAction(ISD::BlockAddress, MVT::i32, Custom); 416 setOperationAction(ISD::ConstantPool, MVT::i32, Custom); 417 setOperationAction(ISD::JumpTable, MVT::i32, Custom); 418 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom); 419 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom); 420 setOperationAction(ISD::BlockAddress, MVT::i64, Custom); 421 setOperationAction(ISD::ConstantPool, MVT::i64, Custom); 422 setOperationAction(ISD::JumpTable, MVT::i64, Custom); 423 424 // TRAP is legal. 425 setOperationAction(ISD::TRAP, MVT::Other, Legal); 426 427 // TRAMPOLINE is custom lowered. 428 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom); 429 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom); 430 431 // VASTART needs to be custom lowered to use the VarArgsFrameIndex 432 setOperationAction(ISD::VASTART , MVT::Other, Custom); 433 434 if (Subtarget.isSVR4ABI()) { 435 if (isPPC64) { 436 // VAARG always uses double-word chunks, so promote anything smaller. 437 setOperationAction(ISD::VAARG, MVT::i1, Promote); 438 AddPromotedToType (ISD::VAARG, MVT::i1, MVT::i64); 439 setOperationAction(ISD::VAARG, MVT::i8, Promote); 440 AddPromotedToType (ISD::VAARG, MVT::i8, MVT::i64); 441 setOperationAction(ISD::VAARG, MVT::i16, Promote); 442 AddPromotedToType (ISD::VAARG, MVT::i16, MVT::i64); 443 setOperationAction(ISD::VAARG, MVT::i32, Promote); 444 AddPromotedToType (ISD::VAARG, MVT::i32, MVT::i64); 445 setOperationAction(ISD::VAARG, MVT::Other, Expand); 446 } else { 447 // VAARG is custom lowered with the 32-bit SVR4 ABI. 448 setOperationAction(ISD::VAARG, MVT::Other, Custom); 449 setOperationAction(ISD::VAARG, MVT::i64, Custom); 450 } 451 } else 452 setOperationAction(ISD::VAARG, MVT::Other, Expand); 453 454 if (Subtarget.isSVR4ABI() && !isPPC64) 455 // VACOPY is custom lowered with the 32-bit SVR4 ABI. 456 setOperationAction(ISD::VACOPY , MVT::Other, Custom); 457 else 458 setOperationAction(ISD::VACOPY , MVT::Other, Expand); 459 460 // Use the default implementation. 461 setOperationAction(ISD::VAEND , MVT::Other, Expand); 462 setOperationAction(ISD::STACKSAVE , MVT::Other, Expand); 463 setOperationAction(ISD::STACKRESTORE , MVT::Other, Custom); 464 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32 , Custom); 465 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64 , Custom); 466 setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i32, Custom); 467 setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i64, Custom); 468 setOperationAction(ISD::EH_DWARF_CFA, MVT::i32, Custom); 469 setOperationAction(ISD::EH_DWARF_CFA, MVT::i64, Custom); 470 471 // We want to custom lower some of our intrinsics. 472 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 473 474 // To handle counter-based loop conditions. 475 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i1, Custom); 476 477 setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom); 478 setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom); 479 setOperationAction(ISD::INTRINSIC_VOID, MVT::i32, Custom); 480 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom); 481 482 // Comparisons that require checking two conditions. 483 if (Subtarget.hasSPE()) { 484 setCondCodeAction(ISD::SETO, MVT::f32, Expand); 485 setCondCodeAction(ISD::SETO, MVT::f64, Expand); 486 setCondCodeAction(ISD::SETUO, MVT::f32, Expand); 487 setCondCodeAction(ISD::SETUO, MVT::f64, Expand); 488 } 489 setCondCodeAction(ISD::SETULT, MVT::f32, Expand); 490 setCondCodeAction(ISD::SETULT, MVT::f64, Expand); 491 setCondCodeAction(ISD::SETUGT, MVT::f32, Expand); 492 setCondCodeAction(ISD::SETUGT, MVT::f64, Expand); 493 setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand); 494 setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand); 495 setCondCodeAction(ISD::SETOGE, MVT::f32, Expand); 496 setCondCodeAction(ISD::SETOGE, MVT::f64, Expand); 497 setCondCodeAction(ISD::SETOLE, MVT::f32, Expand); 498 setCondCodeAction(ISD::SETOLE, MVT::f64, Expand); 499 setCondCodeAction(ISD::SETONE, MVT::f32, Expand); 500 setCondCodeAction(ISD::SETONE, MVT::f64, Expand); 501 502 if (Subtarget.has64BitSupport()) { 503 // They also have instructions for converting between i64 and fp. 504 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom); 505 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand); 506 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom); 507 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand); 508 // This is just the low 32 bits of a (signed) fp->i64 conversion. 509 // We cannot do this with Promote because i64 is not a legal type. 510 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 511 512 if (Subtarget.hasLFIWAX() || Subtarget.isPPC64()) 513 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom); 514 } else { 515 // PowerPC does not have FP_TO_UINT on 32-bit implementations. 516 if (Subtarget.hasSPE()) 517 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Legal); 518 else 519 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand); 520 } 521 522 // With the instructions enabled under FPCVT, we can do everything. 523 if (Subtarget.hasFPCVT()) { 524 if (Subtarget.has64BitSupport()) { 525 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom); 526 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom); 527 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom); 528 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom); 529 } 530 531 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 532 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 533 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom); 534 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom); 535 } 536 537 if (Subtarget.use64BitRegs()) { 538 // 64-bit PowerPC implementations can support i64 types directly 539 addRegisterClass(MVT::i64, &PPC::G8RCRegClass); 540 // BUILD_PAIR can't be handled natively, and should be expanded to shl/or 541 setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand); 542 // 64-bit PowerPC wants to expand i128 shifts itself. 543 setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom); 544 setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom); 545 setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom); 546 } else { 547 // 32-bit PowerPC wants to expand i64 shifts itself. 548 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom); 549 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom); 550 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom); 551 } 552 553 if (Subtarget.hasAltivec()) { 554 // First set operation action for all vector types to expand. Then we 555 // will selectively turn on ones that can be effectively codegen'd. 556 for (MVT VT : MVT::vector_valuetypes()) { 557 // add/sub are legal for all supported vector VT's. 558 setOperationAction(ISD::ADD, VT, Legal); 559 setOperationAction(ISD::SUB, VT, Legal); 560 561 // For v2i64, these are only valid with P8Vector. This is corrected after 562 // the loop. 563 setOperationAction(ISD::SMAX, VT, Legal); 564 setOperationAction(ISD::SMIN, VT, Legal); 565 setOperationAction(ISD::UMAX, VT, Legal); 566 setOperationAction(ISD::UMIN, VT, Legal); 567 568 if (Subtarget.hasVSX()) { 569 setOperationAction(ISD::FMAXNUM, VT, Legal); 570 setOperationAction(ISD::FMINNUM, VT, Legal); 571 } 572 573 // Vector instructions introduced in P8 574 if (Subtarget.hasP8Altivec() && (VT.SimpleTy != MVT::v1i128)) { 575 setOperationAction(ISD::CTPOP, VT, Legal); 576 setOperationAction(ISD::CTLZ, VT, Legal); 577 } 578 else { 579 setOperationAction(ISD::CTPOP, VT, Expand); 580 setOperationAction(ISD::CTLZ, VT, Expand); 581 } 582 583 // Vector instructions introduced in P9 584 if (Subtarget.hasP9Altivec() && (VT.SimpleTy != MVT::v1i128)) 585 setOperationAction(ISD::CTTZ, VT, Legal); 586 else 587 setOperationAction(ISD::CTTZ, VT, Expand); 588 589 // We promote all shuffles to v16i8. 590 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Promote); 591 AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8); 592 593 // We promote all non-typed operations to v4i32. 594 setOperationAction(ISD::AND , VT, Promote); 595 AddPromotedToType (ISD::AND , VT, MVT::v4i32); 596 setOperationAction(ISD::OR , VT, Promote); 597 AddPromotedToType (ISD::OR , VT, MVT::v4i32); 598 setOperationAction(ISD::XOR , VT, Promote); 599 AddPromotedToType (ISD::XOR , VT, MVT::v4i32); 600 setOperationAction(ISD::LOAD , VT, Promote); 601 AddPromotedToType (ISD::LOAD , VT, MVT::v4i32); 602 setOperationAction(ISD::SELECT, VT, Promote); 603 AddPromotedToType (ISD::SELECT, VT, MVT::v4i32); 604 setOperationAction(ISD::VSELECT, VT, Legal); 605 setOperationAction(ISD::SELECT_CC, VT, Promote); 606 AddPromotedToType (ISD::SELECT_CC, VT, MVT::v4i32); 607 setOperationAction(ISD::STORE, VT, Promote); 608 AddPromotedToType (ISD::STORE, VT, MVT::v4i32); 609 610 // No other operations are legal. 611 setOperationAction(ISD::MUL , VT, Expand); 612 setOperationAction(ISD::SDIV, VT, Expand); 613 setOperationAction(ISD::SREM, VT, Expand); 614 setOperationAction(ISD::UDIV, VT, Expand); 615 setOperationAction(ISD::UREM, VT, Expand); 616 setOperationAction(ISD::FDIV, VT, Expand); 617 setOperationAction(ISD::FREM, VT, Expand); 618 setOperationAction(ISD::FNEG, VT, Expand); 619 setOperationAction(ISD::FSQRT, VT, Expand); 620 setOperationAction(ISD::FLOG, VT, Expand); 621 setOperationAction(ISD::FLOG10, VT, Expand); 622 setOperationAction(ISD::FLOG2, VT, Expand); 623 setOperationAction(ISD::FEXP, VT, Expand); 624 setOperationAction(ISD::FEXP2, VT, Expand); 625 setOperationAction(ISD::FSIN, VT, Expand); 626 setOperationAction(ISD::FCOS, VT, Expand); 627 setOperationAction(ISD::FABS, VT, Expand); 628 setOperationAction(ISD::FFLOOR, VT, Expand); 629 setOperationAction(ISD::FCEIL, VT, Expand); 630 setOperationAction(ISD::FTRUNC, VT, Expand); 631 setOperationAction(ISD::FRINT, VT, Expand); 632 setOperationAction(ISD::FNEARBYINT, VT, Expand); 633 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand); 634 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand); 635 setOperationAction(ISD::BUILD_VECTOR, VT, Expand); 636 setOperationAction(ISD::MULHU, VT, Expand); 637 setOperationAction(ISD::MULHS, VT, Expand); 638 setOperationAction(ISD::UMUL_LOHI, VT, Expand); 639 setOperationAction(ISD::SMUL_LOHI, VT, Expand); 640 setOperationAction(ISD::UDIVREM, VT, Expand); 641 setOperationAction(ISD::SDIVREM, VT, Expand); 642 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand); 643 setOperationAction(ISD::FPOW, VT, Expand); 644 setOperationAction(ISD::BSWAP, VT, Expand); 645 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand); 646 setOperationAction(ISD::ROTL, VT, Expand); 647 setOperationAction(ISD::ROTR, VT, Expand); 648 649 for (MVT InnerVT : MVT::vector_valuetypes()) { 650 setTruncStoreAction(VT, InnerVT, Expand); 651 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand); 652 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand); 653 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand); 654 } 655 } 656 if (!Subtarget.hasP8Vector()) { 657 setOperationAction(ISD::SMAX, MVT::v2i64, Expand); 658 setOperationAction(ISD::SMIN, MVT::v2i64, Expand); 659 setOperationAction(ISD::UMAX, MVT::v2i64, Expand); 660 setOperationAction(ISD::UMIN, MVT::v2i64, Expand); 661 } 662 663 for (auto VT : {MVT::v2i64, MVT::v4i32, MVT::v8i16, MVT::v16i8}) 664 setOperationAction(ISD::ABS, VT, Custom); 665 666 // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle 667 // with merges, splats, etc. 668 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom); 669 670 // Vector truncates to sub-word integer that fit in an Altivec/VSX register 671 // are cheap, so handle them before they get expanded to scalar. 672 setOperationAction(ISD::TRUNCATE, MVT::v8i8, Custom); 673 setOperationAction(ISD::TRUNCATE, MVT::v4i8, Custom); 674 setOperationAction(ISD::TRUNCATE, MVT::v2i8, Custom); 675 setOperationAction(ISD::TRUNCATE, MVT::v4i16, Custom); 676 setOperationAction(ISD::TRUNCATE, MVT::v2i16, Custom); 677 678 setOperationAction(ISD::AND , MVT::v4i32, Legal); 679 setOperationAction(ISD::OR , MVT::v4i32, Legal); 680 setOperationAction(ISD::XOR , MVT::v4i32, Legal); 681 setOperationAction(ISD::LOAD , MVT::v4i32, Legal); 682 setOperationAction(ISD::SELECT, MVT::v4i32, 683 Subtarget.useCRBits() ? Legal : Expand); 684 setOperationAction(ISD::STORE , MVT::v4i32, Legal); 685 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal); 686 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal); 687 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal); 688 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal); 689 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal); 690 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal); 691 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal); 692 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal); 693 694 // Without hasP8Altivec set, v2i64 SMAX isn't available. 695 // But ABS custom lowering requires SMAX support. 696 if (!Subtarget.hasP8Altivec()) 697 setOperationAction(ISD::ABS, MVT::v2i64, Expand); 698 699 addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass); 700 addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass); 701 addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass); 702 addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass); 703 704 setOperationAction(ISD::MUL, MVT::v4f32, Legal); 705 setOperationAction(ISD::FMA, MVT::v4f32, Legal); 706 707 if (TM.Options.UnsafeFPMath || Subtarget.hasVSX()) { 708 setOperationAction(ISD::FDIV, MVT::v4f32, Legal); 709 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal); 710 } 711 712 if (Subtarget.hasP8Altivec()) 713 setOperationAction(ISD::MUL, MVT::v4i32, Legal); 714 else 715 setOperationAction(ISD::MUL, MVT::v4i32, Custom); 716 717 setOperationAction(ISD::MUL, MVT::v8i16, Custom); 718 setOperationAction(ISD::MUL, MVT::v16i8, Custom); 719 720 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom); 721 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom); 722 723 setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom); 724 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom); 725 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom); 726 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom); 727 728 // Altivec does not contain unordered floating-point compare instructions 729 setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand); 730 setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand); 731 setCondCodeAction(ISD::SETO, MVT::v4f32, Expand); 732 setCondCodeAction(ISD::SETONE, MVT::v4f32, Expand); 733 734 if (Subtarget.hasVSX()) { 735 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal); 736 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal); 737 if (Subtarget.hasP8Vector()) { 738 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal); 739 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Legal); 740 } 741 if (Subtarget.hasDirectMove() && isPPC64) { 742 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Legal); 743 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Legal); 744 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Legal); 745 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i64, Legal); 746 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Legal); 747 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Legal); 748 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Legal); 749 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal); 750 } 751 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal); 752 753 setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal); 754 setOperationAction(ISD::FCEIL, MVT::v2f64, Legal); 755 setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal); 756 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal); 757 setOperationAction(ISD::FROUND, MVT::v2f64, Legal); 758 759 setOperationAction(ISD::FROUND, MVT::v4f32, Legal); 760 761 setOperationAction(ISD::MUL, MVT::v2f64, Legal); 762 setOperationAction(ISD::FMA, MVT::v2f64, Legal); 763 764 setOperationAction(ISD::FDIV, MVT::v2f64, Legal); 765 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal); 766 767 // Share the Altivec comparison restrictions. 768 setCondCodeAction(ISD::SETUO, MVT::v2f64, Expand); 769 setCondCodeAction(ISD::SETUEQ, MVT::v2f64, Expand); 770 setCondCodeAction(ISD::SETO, MVT::v2f64, Expand); 771 setCondCodeAction(ISD::SETONE, MVT::v2f64, Expand); 772 773 setOperationAction(ISD::LOAD, MVT::v2f64, Legal); 774 setOperationAction(ISD::STORE, MVT::v2f64, Legal); 775 776 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Legal); 777 778 if (Subtarget.hasP8Vector()) 779 addRegisterClass(MVT::f32, &PPC::VSSRCRegClass); 780 781 addRegisterClass(MVT::f64, &PPC::VSFRCRegClass); 782 783 addRegisterClass(MVT::v4i32, &PPC::VSRCRegClass); 784 addRegisterClass(MVT::v4f32, &PPC::VSRCRegClass); 785 addRegisterClass(MVT::v2f64, &PPC::VSRCRegClass); 786 787 if (Subtarget.hasP8Altivec()) { 788 setOperationAction(ISD::SHL, MVT::v2i64, Legal); 789 setOperationAction(ISD::SRA, MVT::v2i64, Legal); 790 setOperationAction(ISD::SRL, MVT::v2i64, Legal); 791 792 // 128 bit shifts can be accomplished via 3 instructions for SHL and 793 // SRL, but not for SRA because of the instructions available: 794 // VS{RL} and VS{RL}O. However due to direct move costs, it's not worth 795 // doing 796 setOperationAction(ISD::SHL, MVT::v1i128, Expand); 797 setOperationAction(ISD::SRL, MVT::v1i128, Expand); 798 setOperationAction(ISD::SRA, MVT::v1i128, Expand); 799 800 setOperationAction(ISD::SETCC, MVT::v2i64, Legal); 801 } 802 else { 803 setOperationAction(ISD::SHL, MVT::v2i64, Expand); 804 setOperationAction(ISD::SRA, MVT::v2i64, Expand); 805 setOperationAction(ISD::SRL, MVT::v2i64, Expand); 806 807 setOperationAction(ISD::SETCC, MVT::v2i64, Custom); 808 809 // VSX v2i64 only supports non-arithmetic operations. 810 setOperationAction(ISD::ADD, MVT::v2i64, Expand); 811 setOperationAction(ISD::SUB, MVT::v2i64, Expand); 812 } 813 814 setOperationAction(ISD::LOAD, MVT::v2i64, Promote); 815 AddPromotedToType (ISD::LOAD, MVT::v2i64, MVT::v2f64); 816 setOperationAction(ISD::STORE, MVT::v2i64, Promote); 817 AddPromotedToType (ISD::STORE, MVT::v2i64, MVT::v2f64); 818 819 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Legal); 820 821 setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal); 822 setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal); 823 setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal); 824 setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal); 825 826 // Custom handling for partial vectors of integers converted to 827 // floating point. We already have optimal handling for v2i32 through 828 // the DAG combine, so those aren't necessary. 829 setOperationAction(ISD::UINT_TO_FP, MVT::v2i8, Custom); 830 setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Custom); 831 setOperationAction(ISD::UINT_TO_FP, MVT::v2i16, Custom); 832 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom); 833 setOperationAction(ISD::SINT_TO_FP, MVT::v2i8, Custom); 834 setOperationAction(ISD::SINT_TO_FP, MVT::v4i8, Custom); 835 setOperationAction(ISD::SINT_TO_FP, MVT::v2i16, Custom); 836 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom); 837 838 setOperationAction(ISD::FNEG, MVT::v4f32, Legal); 839 setOperationAction(ISD::FNEG, MVT::v2f64, Legal); 840 setOperationAction(ISD::FABS, MVT::v4f32, Legal); 841 setOperationAction(ISD::FABS, MVT::v2f64, Legal); 842 setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Legal); 843 setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Legal); 844 845 if (Subtarget.hasDirectMove()) 846 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom); 847 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom); 848 849 addRegisterClass(MVT::v2i64, &PPC::VSRCRegClass); 850 } 851 852 if (Subtarget.hasP8Altivec()) { 853 addRegisterClass(MVT::v2i64, &PPC::VRRCRegClass); 854 addRegisterClass(MVT::v1i128, &PPC::VRRCRegClass); 855 } 856 857 if (Subtarget.hasP9Vector()) { 858 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom); 859 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom); 860 861 // 128 bit shifts can be accomplished via 3 instructions for SHL and 862 // SRL, but not for SRA because of the instructions available: 863 // VS{RL} and VS{RL}O. 864 setOperationAction(ISD::SHL, MVT::v1i128, Legal); 865 setOperationAction(ISD::SRL, MVT::v1i128, Legal); 866 setOperationAction(ISD::SRA, MVT::v1i128, Expand); 867 868 if (EnableQuadPrecision) { 869 addRegisterClass(MVT::f128, &PPC::VRRCRegClass); 870 setOperationAction(ISD::FADD, MVT::f128, Legal); 871 setOperationAction(ISD::FSUB, MVT::f128, Legal); 872 setOperationAction(ISD::FDIV, MVT::f128, Legal); 873 setOperationAction(ISD::FMUL, MVT::f128, Legal); 874 setOperationAction(ISD::FP_EXTEND, MVT::f128, Legal); 875 // No extending loads to f128 on PPC. 876 for (MVT FPT : MVT::fp_valuetypes()) 877 setLoadExtAction(ISD::EXTLOAD, MVT::f128, FPT, Expand); 878 setOperationAction(ISD::FMA, MVT::f128, Legal); 879 setCondCodeAction(ISD::SETULT, MVT::f128, Expand); 880 setCondCodeAction(ISD::SETUGT, MVT::f128, Expand); 881 setCondCodeAction(ISD::SETUEQ, MVT::f128, Expand); 882 setCondCodeAction(ISD::SETOGE, MVT::f128, Expand); 883 setCondCodeAction(ISD::SETOLE, MVT::f128, Expand); 884 setCondCodeAction(ISD::SETONE, MVT::f128, Expand); 885 886 setOperationAction(ISD::FTRUNC, MVT::f128, Legal); 887 setOperationAction(ISD::FRINT, MVT::f128, Legal); 888 setOperationAction(ISD::FFLOOR, MVT::f128, Legal); 889 setOperationAction(ISD::FCEIL, MVT::f128, Legal); 890 setOperationAction(ISD::FNEARBYINT, MVT::f128, Legal); 891 setOperationAction(ISD::FROUND, MVT::f128, Legal); 892 893 setOperationAction(ISD::SELECT, MVT::f128, Expand); 894 setOperationAction(ISD::FP_ROUND, MVT::f64, Legal); 895 setOperationAction(ISD::FP_ROUND, MVT::f32, Legal); 896 setTruncStoreAction(MVT::f128, MVT::f64, Expand); 897 setTruncStoreAction(MVT::f128, MVT::f32, Expand); 898 setOperationAction(ISD::BITCAST, MVT::i128, Custom); 899 // No implementation for these ops for PowerPC. 900 setOperationAction(ISD::FSIN , MVT::f128, Expand); 901 setOperationAction(ISD::FCOS , MVT::f128, Expand); 902 setOperationAction(ISD::FPOW, MVT::f128, Expand); 903 setOperationAction(ISD::FPOWI, MVT::f128, Expand); 904 setOperationAction(ISD::FREM, MVT::f128, Expand); 905 } 906 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom); 907 908 } 909 910 if (Subtarget.hasP9Altivec()) { 911 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom); 912 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom); 913 } 914 } 915 916 if (Subtarget.hasQPX()) { 917 setOperationAction(ISD::FADD, MVT::v4f64, Legal); 918 setOperationAction(ISD::FSUB, MVT::v4f64, Legal); 919 setOperationAction(ISD::FMUL, MVT::v4f64, Legal); 920 setOperationAction(ISD::FREM, MVT::v4f64, Expand); 921 922 setOperationAction(ISD::FCOPYSIGN, MVT::v4f64, Legal); 923 setOperationAction(ISD::FGETSIGN, MVT::v4f64, Expand); 924 925 setOperationAction(ISD::LOAD , MVT::v4f64, Custom); 926 setOperationAction(ISD::STORE , MVT::v4f64, Custom); 927 928 setTruncStoreAction(MVT::v4f64, MVT::v4f32, Custom); 929 setLoadExtAction(ISD::EXTLOAD, MVT::v4f64, MVT::v4f32, Custom); 930 931 if (!Subtarget.useCRBits()) 932 setOperationAction(ISD::SELECT, MVT::v4f64, Expand); 933 setOperationAction(ISD::VSELECT, MVT::v4f64, Legal); 934 935 setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f64, Legal); 936 setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f64, Expand); 937 setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f64, Expand); 938 setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f64, Expand); 939 setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f64, Custom); 940 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f64, Legal); 941 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f64, Custom); 942 943 setOperationAction(ISD::FP_TO_SINT , MVT::v4f64, Legal); 944 setOperationAction(ISD::FP_TO_UINT , MVT::v4f64, Expand); 945 946 setOperationAction(ISD::FP_ROUND , MVT::v4f32, Legal); 947 setOperationAction(ISD::FP_ROUND_INREG , MVT::v4f32, Expand); 948 setOperationAction(ISD::FP_EXTEND, MVT::v4f64, Legal); 949 950 setOperationAction(ISD::FNEG , MVT::v4f64, Legal); 951 setOperationAction(ISD::FABS , MVT::v4f64, Legal); 952 setOperationAction(ISD::FSIN , MVT::v4f64, Expand); 953 setOperationAction(ISD::FCOS , MVT::v4f64, Expand); 954 setOperationAction(ISD::FPOW , MVT::v4f64, Expand); 955 setOperationAction(ISD::FLOG , MVT::v4f64, Expand); 956 setOperationAction(ISD::FLOG2 , MVT::v4f64, Expand); 957 setOperationAction(ISD::FLOG10 , MVT::v4f64, Expand); 958 setOperationAction(ISD::FEXP , MVT::v4f64, Expand); 959 setOperationAction(ISD::FEXP2 , MVT::v4f64, Expand); 960 961 setOperationAction(ISD::FMINNUM, MVT::v4f64, Legal); 962 setOperationAction(ISD::FMAXNUM, MVT::v4f64, Legal); 963 964 setIndexedLoadAction(ISD::PRE_INC, MVT::v4f64, Legal); 965 setIndexedStoreAction(ISD::PRE_INC, MVT::v4f64, Legal); 966 967 addRegisterClass(MVT::v4f64, &PPC::QFRCRegClass); 968 969 setOperationAction(ISD::FADD, MVT::v4f32, Legal); 970 setOperationAction(ISD::FSUB, MVT::v4f32, Legal); 971 setOperationAction(ISD::FMUL, MVT::v4f32, Legal); 972 setOperationAction(ISD::FREM, MVT::v4f32, Expand); 973 974 setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Legal); 975 setOperationAction(ISD::FGETSIGN, MVT::v4f32, Expand); 976 977 setOperationAction(ISD::LOAD , MVT::v4f32, Custom); 978 setOperationAction(ISD::STORE , MVT::v4f32, Custom); 979 980 if (!Subtarget.useCRBits()) 981 setOperationAction(ISD::SELECT, MVT::v4f32, Expand); 982 setOperationAction(ISD::VSELECT, MVT::v4f32, Legal); 983 984 setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f32, Legal); 985 setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f32, Expand); 986 setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f32, Expand); 987 setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f32, Expand); 988 setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f32, Custom); 989 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal); 990 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom); 991 992 setOperationAction(ISD::FP_TO_SINT , MVT::v4f32, Legal); 993 setOperationAction(ISD::FP_TO_UINT , MVT::v4f32, Expand); 994 995 setOperationAction(ISD::FNEG , MVT::v4f32, Legal); 996 setOperationAction(ISD::FABS , MVT::v4f32, Legal); 997 setOperationAction(ISD::FSIN , MVT::v4f32, Expand); 998 setOperationAction(ISD::FCOS , MVT::v4f32, Expand); 999 setOperationAction(ISD::FPOW , MVT::v4f32, Expand); 1000 setOperationAction(ISD::FLOG , MVT::v4f32, Expand); 1001 setOperationAction(ISD::FLOG2 , MVT::v4f32, Expand); 1002 setOperationAction(ISD::FLOG10 , MVT::v4f32, Expand); 1003 setOperationAction(ISD::FEXP , MVT::v4f32, Expand); 1004 setOperationAction(ISD::FEXP2 , MVT::v4f32, Expand); 1005 1006 setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal); 1007 setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal); 1008 1009 setIndexedLoadAction(ISD::PRE_INC, MVT::v4f32, Legal); 1010 setIndexedStoreAction(ISD::PRE_INC, MVT::v4f32, Legal); 1011 1012 addRegisterClass(MVT::v4f32, &PPC::QSRCRegClass); 1013 1014 setOperationAction(ISD::AND , MVT::v4i1, Legal); 1015 setOperationAction(ISD::OR , MVT::v4i1, Legal); 1016 setOperationAction(ISD::XOR , MVT::v4i1, Legal); 1017 1018 if (!Subtarget.useCRBits()) 1019 setOperationAction(ISD::SELECT, MVT::v4i1, Expand); 1020 setOperationAction(ISD::VSELECT, MVT::v4i1, Legal); 1021 1022 setOperationAction(ISD::LOAD , MVT::v4i1, Custom); 1023 setOperationAction(ISD::STORE , MVT::v4i1, Custom); 1024 1025 setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4i1, Custom); 1026 setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4i1, Expand); 1027 setOperationAction(ISD::CONCAT_VECTORS , MVT::v4i1, Expand); 1028 setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4i1, Expand); 1029 setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4i1, Custom); 1030 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i1, Expand); 1031 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i1, Custom); 1032 1033 setOperationAction(ISD::SINT_TO_FP, MVT::v4i1, Custom); 1034 setOperationAction(ISD::UINT_TO_FP, MVT::v4i1, Custom); 1035 1036 addRegisterClass(MVT::v4i1, &PPC::QBRCRegClass); 1037 1038 setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal); 1039 setOperationAction(ISD::FCEIL, MVT::v4f64, Legal); 1040 setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal); 1041 setOperationAction(ISD::FROUND, MVT::v4f64, Legal); 1042 1043 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal); 1044 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal); 1045 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal); 1046 setOperationAction(ISD::FROUND, MVT::v4f32, Legal); 1047 1048 setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Expand); 1049 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand); 1050 1051 // These need to set FE_INEXACT, and so cannot be vectorized here. 1052 setOperationAction(ISD::FRINT, MVT::v4f64, Expand); 1053 setOperationAction(ISD::FRINT, MVT::v4f32, Expand); 1054 1055 if (TM.Options.UnsafeFPMath) { 1056 setOperationAction(ISD::FDIV, MVT::v4f64, Legal); 1057 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal); 1058 1059 setOperationAction(ISD::FDIV, MVT::v4f32, Legal); 1060 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal); 1061 } else { 1062 setOperationAction(ISD::FDIV, MVT::v4f64, Expand); 1063 setOperationAction(ISD::FSQRT, MVT::v4f64, Expand); 1064 1065 setOperationAction(ISD::FDIV, MVT::v4f32, Expand); 1066 setOperationAction(ISD::FSQRT, MVT::v4f32, Expand); 1067 } 1068 } 1069 1070 if (Subtarget.has64BitSupport()) 1071 setOperationAction(ISD::PREFETCH, MVT::Other, Legal); 1072 1073 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, isPPC64 ? Legal : Custom); 1074 1075 if (!isPPC64) { 1076 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Expand); 1077 setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand); 1078 } 1079 1080 setBooleanContents(ZeroOrOneBooleanContent); 1081 1082 if (Subtarget.hasAltivec()) { 1083 // Altivec instructions set fields to all zeros or all ones. 1084 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent); 1085 } 1086 1087 if (!isPPC64) { 1088 // These libcalls are not available in 32-bit. 1089 setLibcallName(RTLIB::SHL_I128, nullptr); 1090 setLibcallName(RTLIB::SRL_I128, nullptr); 1091 setLibcallName(RTLIB::SRA_I128, nullptr); 1092 } 1093 1094 setStackPointerRegisterToSaveRestore(isPPC64 ? PPC::X1 : PPC::R1); 1095 1096 // We have target-specific dag combine patterns for the following nodes: 1097 setTargetDAGCombine(ISD::ADD); 1098 setTargetDAGCombine(ISD::SHL); 1099 setTargetDAGCombine(ISD::SRA); 1100 setTargetDAGCombine(ISD::SRL); 1101 setTargetDAGCombine(ISD::MUL); 1102 setTargetDAGCombine(ISD::SINT_TO_FP); 1103 setTargetDAGCombine(ISD::BUILD_VECTOR); 1104 if (Subtarget.hasFPCVT()) 1105 setTargetDAGCombine(ISD::UINT_TO_FP); 1106 setTargetDAGCombine(ISD::LOAD); 1107 setTargetDAGCombine(ISD::STORE); 1108 setTargetDAGCombine(ISD::BR_CC); 1109 if (Subtarget.useCRBits()) 1110 setTargetDAGCombine(ISD::BRCOND); 1111 setTargetDAGCombine(ISD::BSWAP); 1112 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN); 1113 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN); 1114 setTargetDAGCombine(ISD::INTRINSIC_VOID); 1115 1116 setTargetDAGCombine(ISD::SIGN_EXTEND); 1117 setTargetDAGCombine(ISD::ZERO_EXTEND); 1118 setTargetDAGCombine(ISD::ANY_EXTEND); 1119 1120 setTargetDAGCombine(ISD::TRUNCATE); 1121 1122 if (Subtarget.useCRBits()) { 1123 setTargetDAGCombine(ISD::TRUNCATE); 1124 setTargetDAGCombine(ISD::SETCC); 1125 setTargetDAGCombine(ISD::SELECT_CC); 1126 } 1127 1128 // Use reciprocal estimates. 1129 if (TM.Options.UnsafeFPMath) { 1130 setTargetDAGCombine(ISD::FDIV); 1131 setTargetDAGCombine(ISD::FSQRT); 1132 } 1133 1134 if (Subtarget.hasP9Altivec()) { 1135 setTargetDAGCombine(ISD::ABS); 1136 setTargetDAGCombine(ISD::VSELECT); 1137 } 1138 1139 // Darwin long double math library functions have $LDBL128 appended. 1140 if (Subtarget.isDarwin()) { 1141 setLibcallName(RTLIB::COS_PPCF128, "cosl$LDBL128"); 1142 setLibcallName(RTLIB::POW_PPCF128, "powl$LDBL128"); 1143 setLibcallName(RTLIB::REM_PPCF128, "fmodl$LDBL128"); 1144 setLibcallName(RTLIB::SIN_PPCF128, "sinl$LDBL128"); 1145 setLibcallName(RTLIB::SQRT_PPCF128, "sqrtl$LDBL128"); 1146 setLibcallName(RTLIB::LOG_PPCF128, "logl$LDBL128"); 1147 setLibcallName(RTLIB::LOG2_PPCF128, "log2l$LDBL128"); 1148 setLibcallName(RTLIB::LOG10_PPCF128, "log10l$LDBL128"); 1149 setLibcallName(RTLIB::EXP_PPCF128, "expl$LDBL128"); 1150 setLibcallName(RTLIB::EXP2_PPCF128, "exp2l$LDBL128"); 1151 } 1152 1153 if (EnableQuadPrecision) { 1154 setLibcallName(RTLIB::LOG_F128, "logf128"); 1155 setLibcallName(RTLIB::LOG2_F128, "log2f128"); 1156 setLibcallName(RTLIB::LOG10_F128, "log10f128"); 1157 setLibcallName(RTLIB::EXP_F128, "expf128"); 1158 setLibcallName(RTLIB::EXP2_F128, "exp2f128"); 1159 setLibcallName(RTLIB::SIN_F128, "sinf128"); 1160 setLibcallName(RTLIB::COS_F128, "cosf128"); 1161 setLibcallName(RTLIB::POW_F128, "powf128"); 1162 setLibcallName(RTLIB::FMIN_F128, "fminf128"); 1163 setLibcallName(RTLIB::FMAX_F128, "fmaxf128"); 1164 setLibcallName(RTLIB::POWI_F128, "__powikf2"); 1165 setLibcallName(RTLIB::REM_F128, "fmodf128"); 1166 } 1167 1168 // With 32 condition bits, we don't need to sink (and duplicate) compares 1169 // aggressively in CodeGenPrep. 1170 if (Subtarget.useCRBits()) { 1171 setHasMultipleConditionRegisters(); 1172 setJumpIsExpensive(); 1173 } 1174 1175 setMinFunctionAlignment(2); 1176 if (Subtarget.isDarwin()) 1177 setPrefFunctionAlignment(4); 1178 1179 switch (Subtarget.getDarwinDirective()) { 1180 default: break; 1181 case PPC::DIR_970: 1182 case PPC::DIR_A2: 1183 case PPC::DIR_E500: 1184 case PPC::DIR_E500mc: 1185 case PPC::DIR_E5500: 1186 case PPC::DIR_PWR4: 1187 case PPC::DIR_PWR5: 1188 case PPC::DIR_PWR5X: 1189 case PPC::DIR_PWR6: 1190 case PPC::DIR_PWR6X: 1191 case PPC::DIR_PWR7: 1192 case PPC::DIR_PWR8: 1193 case PPC::DIR_PWR9: 1194 setPrefFunctionAlignment(4); 1195 setPrefLoopAlignment(4); 1196 break; 1197 } 1198 1199 if (Subtarget.enableMachineScheduler()) 1200 setSchedulingPreference(Sched::Source); 1201 else 1202 setSchedulingPreference(Sched::Hybrid); 1203 1204 computeRegisterProperties(STI.getRegisterInfo()); 1205 1206 // The Freescale cores do better with aggressive inlining of memcpy and 1207 // friends. GCC uses same threshold of 128 bytes (= 32 word stores). 1208 if (Subtarget.getDarwinDirective() == PPC::DIR_E500mc || 1209 Subtarget.getDarwinDirective() == PPC::DIR_E5500) { 1210 MaxStoresPerMemset = 32; 1211 MaxStoresPerMemsetOptSize = 16; 1212 MaxStoresPerMemcpy = 32; 1213 MaxStoresPerMemcpyOptSize = 8; 1214 MaxStoresPerMemmove = 32; 1215 MaxStoresPerMemmoveOptSize = 8; 1216 } else if (Subtarget.getDarwinDirective() == PPC::DIR_A2) { 1217 // The A2 also benefits from (very) aggressive inlining of memcpy and 1218 // friends. The overhead of a the function call, even when warm, can be 1219 // over one hundred cycles. 1220 MaxStoresPerMemset = 128; 1221 MaxStoresPerMemcpy = 128; 1222 MaxStoresPerMemmove = 128; 1223 MaxLoadsPerMemcmp = 128; 1224 } else { 1225 MaxLoadsPerMemcmp = 8; 1226 MaxLoadsPerMemcmpOptSize = 4; 1227 } 1228 } 1229 1230 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine 1231 /// the desired ByVal argument alignment. 1232 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign, 1233 unsigned MaxMaxAlign) { 1234 if (MaxAlign == MaxMaxAlign) 1235 return; 1236 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) { 1237 if (MaxMaxAlign >= 32 && VTy->getBitWidth() >= 256) 1238 MaxAlign = 32; 1239 else if (VTy->getBitWidth() >= 128 && MaxAlign < 16) 1240 MaxAlign = 16; 1241 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) { 1242 unsigned EltAlign = 0; 1243 getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign); 1244 if (EltAlign > MaxAlign) 1245 MaxAlign = EltAlign; 1246 } else if (StructType *STy = dyn_cast<StructType>(Ty)) { 1247 for (auto *EltTy : STy->elements()) { 1248 unsigned EltAlign = 0; 1249 getMaxByValAlign(EltTy, EltAlign, MaxMaxAlign); 1250 if (EltAlign > MaxAlign) 1251 MaxAlign = EltAlign; 1252 if (MaxAlign == MaxMaxAlign) 1253 break; 1254 } 1255 } 1256 } 1257 1258 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate 1259 /// function arguments in the caller parameter area. 1260 unsigned PPCTargetLowering::getByValTypeAlignment(Type *Ty, 1261 const DataLayout &DL) const { 1262 // Darwin passes everything on 4 byte boundary. 1263 if (Subtarget.isDarwin()) 1264 return 4; 1265 1266 // 16byte and wider vectors are passed on 16byte boundary. 1267 // The rest is 8 on PPC64 and 4 on PPC32 boundary. 1268 unsigned Align = Subtarget.isPPC64() ? 8 : 4; 1269 if (Subtarget.hasAltivec() || Subtarget.hasQPX()) 1270 getMaxByValAlign(Ty, Align, Subtarget.hasQPX() ? 32 : 16); 1271 return Align; 1272 } 1273 1274 bool PPCTargetLowering::useSoftFloat() const { 1275 return Subtarget.useSoftFloat(); 1276 } 1277 1278 bool PPCTargetLowering::hasSPE() const { 1279 return Subtarget.hasSPE(); 1280 } 1281 1282 bool PPCTargetLowering::preferIncOfAddToSubOfNot(EVT VT) const { 1283 return VT.isScalarInteger(); 1284 } 1285 1286 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const { 1287 switch ((PPCISD::NodeType)Opcode) { 1288 case PPCISD::FIRST_NUMBER: break; 1289 case PPCISD::FSEL: return "PPCISD::FSEL"; 1290 case PPCISD::FCFID: return "PPCISD::FCFID"; 1291 case PPCISD::FCFIDU: return "PPCISD::FCFIDU"; 1292 case PPCISD::FCFIDS: return "PPCISD::FCFIDS"; 1293 case PPCISD::FCFIDUS: return "PPCISD::FCFIDUS"; 1294 case PPCISD::FCTIDZ: return "PPCISD::FCTIDZ"; 1295 case PPCISD::FCTIWZ: return "PPCISD::FCTIWZ"; 1296 case PPCISD::FCTIDUZ: return "PPCISD::FCTIDUZ"; 1297 case PPCISD::FCTIWUZ: return "PPCISD::FCTIWUZ"; 1298 case PPCISD::FP_TO_UINT_IN_VSR: 1299 return "PPCISD::FP_TO_UINT_IN_VSR,"; 1300 case PPCISD::FP_TO_SINT_IN_VSR: 1301 return "PPCISD::FP_TO_SINT_IN_VSR"; 1302 case PPCISD::FRE: return "PPCISD::FRE"; 1303 case PPCISD::FRSQRTE: return "PPCISD::FRSQRTE"; 1304 case PPCISD::STFIWX: return "PPCISD::STFIWX"; 1305 case PPCISD::VMADDFP: return "PPCISD::VMADDFP"; 1306 case PPCISD::VNMSUBFP: return "PPCISD::VNMSUBFP"; 1307 case PPCISD::VPERM: return "PPCISD::VPERM"; 1308 case PPCISD::XXSPLT: return "PPCISD::XXSPLT"; 1309 case PPCISD::VECINSERT: return "PPCISD::VECINSERT"; 1310 case PPCISD::XXREVERSE: return "PPCISD::XXREVERSE"; 1311 case PPCISD::XXPERMDI: return "PPCISD::XXPERMDI"; 1312 case PPCISD::VECSHL: return "PPCISD::VECSHL"; 1313 case PPCISD::CMPB: return "PPCISD::CMPB"; 1314 case PPCISD::Hi: return "PPCISD::Hi"; 1315 case PPCISD::Lo: return "PPCISD::Lo"; 1316 case PPCISD::TOC_ENTRY: return "PPCISD::TOC_ENTRY"; 1317 case PPCISD::ATOMIC_CMP_SWAP_8: return "PPCISD::ATOMIC_CMP_SWAP_8"; 1318 case PPCISD::ATOMIC_CMP_SWAP_16: return "PPCISD::ATOMIC_CMP_SWAP_16"; 1319 case PPCISD::DYNALLOC: return "PPCISD::DYNALLOC"; 1320 case PPCISD::DYNAREAOFFSET: return "PPCISD::DYNAREAOFFSET"; 1321 case PPCISD::GlobalBaseReg: return "PPCISD::GlobalBaseReg"; 1322 case PPCISD::SRL: return "PPCISD::SRL"; 1323 case PPCISD::SRA: return "PPCISD::SRA"; 1324 case PPCISD::SHL: return "PPCISD::SHL"; 1325 case PPCISD::SRA_ADDZE: return "PPCISD::SRA_ADDZE"; 1326 case PPCISD::CALL: return "PPCISD::CALL"; 1327 case PPCISD::CALL_NOP: return "PPCISD::CALL_NOP"; 1328 case PPCISD::MTCTR: return "PPCISD::MTCTR"; 1329 case PPCISD::BCTRL: return "PPCISD::BCTRL"; 1330 case PPCISD::BCTRL_LOAD_TOC: return "PPCISD::BCTRL_LOAD_TOC"; 1331 case PPCISD::RET_FLAG: return "PPCISD::RET_FLAG"; 1332 case PPCISD::READ_TIME_BASE: return "PPCISD::READ_TIME_BASE"; 1333 case PPCISD::EH_SJLJ_SETJMP: return "PPCISD::EH_SJLJ_SETJMP"; 1334 case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP"; 1335 case PPCISD::MFOCRF: return "PPCISD::MFOCRF"; 1336 case PPCISD::MFVSR: return "PPCISD::MFVSR"; 1337 case PPCISD::MTVSRA: return "PPCISD::MTVSRA"; 1338 case PPCISD::MTVSRZ: return "PPCISD::MTVSRZ"; 1339 case PPCISD::SINT_VEC_TO_FP: return "PPCISD::SINT_VEC_TO_FP"; 1340 case PPCISD::UINT_VEC_TO_FP: return "PPCISD::UINT_VEC_TO_FP"; 1341 case PPCISD::ANDIo_1_EQ_BIT: return "PPCISD::ANDIo_1_EQ_BIT"; 1342 case PPCISD::ANDIo_1_GT_BIT: return "PPCISD::ANDIo_1_GT_BIT"; 1343 case PPCISD::VCMP: return "PPCISD::VCMP"; 1344 case PPCISD::VCMPo: return "PPCISD::VCMPo"; 1345 case PPCISD::LBRX: return "PPCISD::LBRX"; 1346 case PPCISD::STBRX: return "PPCISD::STBRX"; 1347 case PPCISD::LFIWAX: return "PPCISD::LFIWAX"; 1348 case PPCISD::LFIWZX: return "PPCISD::LFIWZX"; 1349 case PPCISD::LXSIZX: return "PPCISD::LXSIZX"; 1350 case PPCISD::STXSIX: return "PPCISD::STXSIX"; 1351 case PPCISD::VEXTS: return "PPCISD::VEXTS"; 1352 case PPCISD::SExtVElems: return "PPCISD::SExtVElems"; 1353 case PPCISD::LXVD2X: return "PPCISD::LXVD2X"; 1354 case PPCISD::STXVD2X: return "PPCISD::STXVD2X"; 1355 case PPCISD::ST_VSR_SCAL_INT: 1356 return "PPCISD::ST_VSR_SCAL_INT"; 1357 case PPCISD::COND_BRANCH: return "PPCISD::COND_BRANCH"; 1358 case PPCISD::BDNZ: return "PPCISD::BDNZ"; 1359 case PPCISD::BDZ: return "PPCISD::BDZ"; 1360 case PPCISD::MFFS: return "PPCISD::MFFS"; 1361 case PPCISD::FADDRTZ: return "PPCISD::FADDRTZ"; 1362 case PPCISD::TC_RETURN: return "PPCISD::TC_RETURN"; 1363 case PPCISD::CR6SET: return "PPCISD::CR6SET"; 1364 case PPCISD::CR6UNSET: return "PPCISD::CR6UNSET"; 1365 case PPCISD::PPC32_GOT: return "PPCISD::PPC32_GOT"; 1366 case PPCISD::PPC32_PICGOT: return "PPCISD::PPC32_PICGOT"; 1367 case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA"; 1368 case PPCISD::LD_GOT_TPREL_L: return "PPCISD::LD_GOT_TPREL_L"; 1369 case PPCISD::ADD_TLS: return "PPCISD::ADD_TLS"; 1370 case PPCISD::ADDIS_TLSGD_HA: return "PPCISD::ADDIS_TLSGD_HA"; 1371 case PPCISD::ADDI_TLSGD_L: return "PPCISD::ADDI_TLSGD_L"; 1372 case PPCISD::GET_TLS_ADDR: return "PPCISD::GET_TLS_ADDR"; 1373 case PPCISD::ADDI_TLSGD_L_ADDR: return "PPCISD::ADDI_TLSGD_L_ADDR"; 1374 case PPCISD::ADDIS_TLSLD_HA: return "PPCISD::ADDIS_TLSLD_HA"; 1375 case PPCISD::ADDI_TLSLD_L: return "PPCISD::ADDI_TLSLD_L"; 1376 case PPCISD::GET_TLSLD_ADDR: return "PPCISD::GET_TLSLD_ADDR"; 1377 case PPCISD::ADDI_TLSLD_L_ADDR: return "PPCISD::ADDI_TLSLD_L_ADDR"; 1378 case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA"; 1379 case PPCISD::ADDI_DTPREL_L: return "PPCISD::ADDI_DTPREL_L"; 1380 case PPCISD::VADD_SPLAT: return "PPCISD::VADD_SPLAT"; 1381 case PPCISD::SC: return "PPCISD::SC"; 1382 case PPCISD::CLRBHRB: return "PPCISD::CLRBHRB"; 1383 case PPCISD::MFBHRBE: return "PPCISD::MFBHRBE"; 1384 case PPCISD::RFEBB: return "PPCISD::RFEBB"; 1385 case PPCISD::XXSWAPD: return "PPCISD::XXSWAPD"; 1386 case PPCISD::SWAP_NO_CHAIN: return "PPCISD::SWAP_NO_CHAIN"; 1387 case PPCISD::VABSD: return "PPCISD::VABSD"; 1388 case PPCISD::QVFPERM: return "PPCISD::QVFPERM"; 1389 case PPCISD::QVGPCI: return "PPCISD::QVGPCI"; 1390 case PPCISD::QVALIGNI: return "PPCISD::QVALIGNI"; 1391 case PPCISD::QVESPLATI: return "PPCISD::QVESPLATI"; 1392 case PPCISD::QBFLT: return "PPCISD::QBFLT"; 1393 case PPCISD::QVLFSb: return "PPCISD::QVLFSb"; 1394 case PPCISD::BUILD_FP128: return "PPCISD::BUILD_FP128"; 1395 case PPCISD::BUILD_SPE64: return "PPCISD::BUILD_SPE64"; 1396 case PPCISD::EXTRACT_SPE: return "PPCISD::EXTRACT_SPE"; 1397 case PPCISD::EXTSWSLI: return "PPCISD::EXTSWSLI"; 1398 case PPCISD::LD_VSX_LH: return "PPCISD::LD_VSX_LH"; 1399 case PPCISD::FP_EXTEND_LH: return "PPCISD::FP_EXTEND_LH"; 1400 } 1401 return nullptr; 1402 } 1403 1404 EVT PPCTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &C, 1405 EVT VT) const { 1406 if (!VT.isVector()) 1407 return Subtarget.useCRBits() ? MVT::i1 : MVT::i32; 1408 1409 if (Subtarget.hasQPX()) 1410 return EVT::getVectorVT(C, MVT::i1, VT.getVectorNumElements()); 1411 1412 return VT.changeVectorElementTypeToInteger(); 1413 } 1414 1415 bool PPCTargetLowering::enableAggressiveFMAFusion(EVT VT) const { 1416 assert(VT.isFloatingPoint() && "Non-floating-point FMA?"); 1417 return true; 1418 } 1419 1420 //===----------------------------------------------------------------------===// 1421 // Node matching predicates, for use by the tblgen matching code. 1422 //===----------------------------------------------------------------------===// 1423 1424 /// isFloatingPointZero - Return true if this is 0.0 or -0.0. 1425 static bool isFloatingPointZero(SDValue Op) { 1426 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) 1427 return CFP->getValueAPF().isZero(); 1428 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) { 1429 // Maybe this has already been legalized into the constant pool? 1430 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1))) 1431 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal())) 1432 return CFP->getValueAPF().isZero(); 1433 } 1434 return false; 1435 } 1436 1437 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode. Return 1438 /// true if Op is undef or if it matches the specified value. 1439 static bool isConstantOrUndef(int Op, int Val) { 1440 return Op < 0 || Op == Val; 1441 } 1442 1443 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a 1444 /// VPKUHUM instruction. 1445 /// The ShuffleKind distinguishes between big-endian operations with 1446 /// two different inputs (0), either-endian operations with two identical 1447 /// inputs (1), and little-endian operations with two different inputs (2). 1448 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td). 1449 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind, 1450 SelectionDAG &DAG) { 1451 bool IsLE = DAG.getDataLayout().isLittleEndian(); 1452 if (ShuffleKind == 0) { 1453 if (IsLE) 1454 return false; 1455 for (unsigned i = 0; i != 16; ++i) 1456 if (!isConstantOrUndef(N->getMaskElt(i), i*2+1)) 1457 return false; 1458 } else if (ShuffleKind == 2) { 1459 if (!IsLE) 1460 return false; 1461 for (unsigned i = 0; i != 16; ++i) 1462 if (!isConstantOrUndef(N->getMaskElt(i), i*2)) 1463 return false; 1464 } else if (ShuffleKind == 1) { 1465 unsigned j = IsLE ? 0 : 1; 1466 for (unsigned i = 0; i != 8; ++i) 1467 if (!isConstantOrUndef(N->getMaskElt(i), i*2+j) || 1468 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j)) 1469 return false; 1470 } 1471 return true; 1472 } 1473 1474 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a 1475 /// VPKUWUM instruction. 1476 /// The ShuffleKind distinguishes between big-endian operations with 1477 /// two different inputs (0), either-endian operations with two identical 1478 /// inputs (1), and little-endian operations with two different inputs (2). 1479 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td). 1480 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind, 1481 SelectionDAG &DAG) { 1482 bool IsLE = DAG.getDataLayout().isLittleEndian(); 1483 if (ShuffleKind == 0) { 1484 if (IsLE) 1485 return false; 1486 for (unsigned i = 0; i != 16; i += 2) 1487 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+2) || 1488 !isConstantOrUndef(N->getMaskElt(i+1), i*2+3)) 1489 return false; 1490 } else if (ShuffleKind == 2) { 1491 if (!IsLE) 1492 return false; 1493 for (unsigned i = 0; i != 16; i += 2) 1494 if (!isConstantOrUndef(N->getMaskElt(i ), i*2) || 1495 !isConstantOrUndef(N->getMaskElt(i+1), i*2+1)) 1496 return false; 1497 } else if (ShuffleKind == 1) { 1498 unsigned j = IsLE ? 0 : 2; 1499 for (unsigned i = 0; i != 8; i += 2) 1500 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+j) || 1501 !isConstantOrUndef(N->getMaskElt(i+1), i*2+j+1) || 1502 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j) || 1503 !isConstantOrUndef(N->getMaskElt(i+9), i*2+j+1)) 1504 return false; 1505 } 1506 return true; 1507 } 1508 1509 /// isVPKUDUMShuffleMask - Return true if this is the shuffle mask for a 1510 /// VPKUDUM instruction, AND the VPKUDUM instruction exists for the 1511 /// current subtarget. 1512 /// 1513 /// The ShuffleKind distinguishes between big-endian operations with 1514 /// two different inputs (0), either-endian operations with two identical 1515 /// inputs (1), and little-endian operations with two different inputs (2). 1516 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td). 1517 bool PPC::isVPKUDUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind, 1518 SelectionDAG &DAG) { 1519 const PPCSubtarget& Subtarget = 1520 static_cast<const PPCSubtarget&>(DAG.getSubtarget()); 1521 if (!Subtarget.hasP8Vector()) 1522 return false; 1523 1524 bool IsLE = DAG.getDataLayout().isLittleEndian(); 1525 if (ShuffleKind == 0) { 1526 if (IsLE) 1527 return false; 1528 for (unsigned i = 0; i != 16; i += 4) 1529 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+4) || 1530 !isConstantOrUndef(N->getMaskElt(i+1), i*2+5) || 1531 !isConstantOrUndef(N->getMaskElt(i+2), i*2+6) || 1532 !isConstantOrUndef(N->getMaskElt(i+3), i*2+7)) 1533 return false; 1534 } else if (ShuffleKind == 2) { 1535 if (!IsLE) 1536 return false; 1537 for (unsigned i = 0; i != 16; i += 4) 1538 if (!isConstantOrUndef(N->getMaskElt(i ), i*2) || 1539 !isConstantOrUndef(N->getMaskElt(i+1), i*2+1) || 1540 !isConstantOrUndef(N->getMaskElt(i+2), i*2+2) || 1541 !isConstantOrUndef(N->getMaskElt(i+3), i*2+3)) 1542 return false; 1543 } else if (ShuffleKind == 1) { 1544 unsigned j = IsLE ? 0 : 4; 1545 for (unsigned i = 0; i != 8; i += 4) 1546 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+j) || 1547 !isConstantOrUndef(N->getMaskElt(i+1), i*2+j+1) || 1548 !isConstantOrUndef(N->getMaskElt(i+2), i*2+j+2) || 1549 !isConstantOrUndef(N->getMaskElt(i+3), i*2+j+3) || 1550 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j) || 1551 !isConstantOrUndef(N->getMaskElt(i+9), i*2+j+1) || 1552 !isConstantOrUndef(N->getMaskElt(i+10), i*2+j+2) || 1553 !isConstantOrUndef(N->getMaskElt(i+11), i*2+j+3)) 1554 return false; 1555 } 1556 return true; 1557 } 1558 1559 /// isVMerge - Common function, used to match vmrg* shuffles. 1560 /// 1561 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize, 1562 unsigned LHSStart, unsigned RHSStart) { 1563 if (N->getValueType(0) != MVT::v16i8) 1564 return false; 1565 assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) && 1566 "Unsupported merge size!"); 1567 1568 for (unsigned i = 0; i != 8/UnitSize; ++i) // Step over units 1569 for (unsigned j = 0; j != UnitSize; ++j) { // Step over bytes within unit 1570 if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j), 1571 LHSStart+j+i*UnitSize) || 1572 !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j), 1573 RHSStart+j+i*UnitSize)) 1574 return false; 1575 } 1576 return true; 1577 } 1578 1579 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for 1580 /// a VMRGL* instruction with the specified unit size (1,2 or 4 bytes). 1581 /// The ShuffleKind distinguishes between big-endian merges with two 1582 /// different inputs (0), either-endian merges with two identical inputs (1), 1583 /// and little-endian merges with two different inputs (2). For the latter, 1584 /// the input operands are swapped (see PPCInstrAltivec.td). 1585 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize, 1586 unsigned ShuffleKind, SelectionDAG &DAG) { 1587 if (DAG.getDataLayout().isLittleEndian()) { 1588 if (ShuffleKind == 1) // unary 1589 return isVMerge(N, UnitSize, 0, 0); 1590 else if (ShuffleKind == 2) // swapped 1591 return isVMerge(N, UnitSize, 0, 16); 1592 else 1593 return false; 1594 } else { 1595 if (ShuffleKind == 1) // unary 1596 return isVMerge(N, UnitSize, 8, 8); 1597 else if (ShuffleKind == 0) // normal 1598 return isVMerge(N, UnitSize, 8, 24); 1599 else 1600 return false; 1601 } 1602 } 1603 1604 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for 1605 /// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes). 1606 /// The ShuffleKind distinguishes between big-endian merges with two 1607 /// different inputs (0), either-endian merges with two identical inputs (1), 1608 /// and little-endian merges with two different inputs (2). For the latter, 1609 /// the input operands are swapped (see PPCInstrAltivec.td). 1610 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize, 1611 unsigned ShuffleKind, SelectionDAG &DAG) { 1612 if (DAG.getDataLayout().isLittleEndian()) { 1613 if (ShuffleKind == 1) // unary 1614 return isVMerge(N, UnitSize, 8, 8); 1615 else if (ShuffleKind == 2) // swapped 1616 return isVMerge(N, UnitSize, 8, 24); 1617 else 1618 return false; 1619 } else { 1620 if (ShuffleKind == 1) // unary 1621 return isVMerge(N, UnitSize, 0, 0); 1622 else if (ShuffleKind == 0) // normal 1623 return isVMerge(N, UnitSize, 0, 16); 1624 else 1625 return false; 1626 } 1627 } 1628 1629 /** 1630 * Common function used to match vmrgew and vmrgow shuffles 1631 * 1632 * The indexOffset determines whether to look for even or odd words in 1633 * the shuffle mask. This is based on the of the endianness of the target 1634 * machine. 1635 * - Little Endian: 1636 * - Use offset of 0 to check for odd elements 1637 * - Use offset of 4 to check for even elements 1638 * - Big Endian: 1639 * - Use offset of 0 to check for even elements 1640 * - Use offset of 4 to check for odd elements 1641 * A detailed description of the vector element ordering for little endian and 1642 * big endian can be found at 1643 * http://www.ibm.com/developerworks/library/l-ibm-xl-c-cpp-compiler/index.html 1644 * Targeting your applications - what little endian and big endian IBM XL C/C++ 1645 * compiler differences mean to you 1646 * 1647 * The mask to the shuffle vector instruction specifies the indices of the 1648 * elements from the two input vectors to place in the result. The elements are 1649 * numbered in array-access order, starting with the first vector. These vectors 1650 * are always of type v16i8, thus each vector will contain 16 elements of size 1651 * 8. More info on the shuffle vector can be found in the 1652 * http://llvm.org/docs/LangRef.html#shufflevector-instruction 1653 * Language Reference. 1654 * 1655 * The RHSStartValue indicates whether the same input vectors are used (unary) 1656 * or two different input vectors are used, based on the following: 1657 * - If the instruction uses the same vector for both inputs, the range of the 1658 * indices will be 0 to 15. In this case, the RHSStart value passed should 1659 * be 0. 1660 * - If the instruction has two different vectors then the range of the 1661 * indices will be 0 to 31. In this case, the RHSStart value passed should 1662 * be 16 (indices 0-15 specify elements in the first vector while indices 16 1663 * to 31 specify elements in the second vector). 1664 * 1665 * \param[in] N The shuffle vector SD Node to analyze 1666 * \param[in] IndexOffset Specifies whether to look for even or odd elements 1667 * \param[in] RHSStartValue Specifies the starting index for the righthand input 1668 * vector to the shuffle_vector instruction 1669 * \return true iff this shuffle vector represents an even or odd word merge 1670 */ 1671 static bool isVMerge(ShuffleVectorSDNode *N, unsigned IndexOffset, 1672 unsigned RHSStartValue) { 1673 if (N->getValueType(0) != MVT::v16i8) 1674 return false; 1675 1676 for (unsigned i = 0; i < 2; ++i) 1677 for (unsigned j = 0; j < 4; ++j) 1678 if (!isConstantOrUndef(N->getMaskElt(i*4+j), 1679 i*RHSStartValue+j+IndexOffset) || 1680 !isConstantOrUndef(N->getMaskElt(i*4+j+8), 1681 i*RHSStartValue+j+IndexOffset+8)) 1682 return false; 1683 return true; 1684 } 1685 1686 /** 1687 * Determine if the specified shuffle mask is suitable for the vmrgew or 1688 * vmrgow instructions. 1689 * 1690 * \param[in] N The shuffle vector SD Node to analyze 1691 * \param[in] CheckEven Check for an even merge (true) or an odd merge (false) 1692 * \param[in] ShuffleKind Identify the type of merge: 1693 * - 0 = big-endian merge with two different inputs; 1694 * - 1 = either-endian merge with two identical inputs; 1695 * - 2 = little-endian merge with two different inputs (inputs are swapped for 1696 * little-endian merges). 1697 * \param[in] DAG The current SelectionDAG 1698 * \return true iff this shuffle mask 1699 */ 1700 bool PPC::isVMRGEOShuffleMask(ShuffleVectorSDNode *N, bool CheckEven, 1701 unsigned ShuffleKind, SelectionDAG &DAG) { 1702 if (DAG.getDataLayout().isLittleEndian()) { 1703 unsigned indexOffset = CheckEven ? 4 : 0; 1704 if (ShuffleKind == 1) // Unary 1705 return isVMerge(N, indexOffset, 0); 1706 else if (ShuffleKind == 2) // swapped 1707 return isVMerge(N, indexOffset, 16); 1708 else 1709 return false; 1710 } 1711 else { 1712 unsigned indexOffset = CheckEven ? 0 : 4; 1713 if (ShuffleKind == 1) // Unary 1714 return isVMerge(N, indexOffset, 0); 1715 else if (ShuffleKind == 0) // Normal 1716 return isVMerge(N, indexOffset, 16); 1717 else 1718 return false; 1719 } 1720 return false; 1721 } 1722 1723 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift 1724 /// amount, otherwise return -1. 1725 /// The ShuffleKind distinguishes between big-endian operations with two 1726 /// different inputs (0), either-endian operations with two identical inputs 1727 /// (1), and little-endian operations with two different inputs (2). For the 1728 /// latter, the input operands are swapped (see PPCInstrAltivec.td). 1729 int PPC::isVSLDOIShuffleMask(SDNode *N, unsigned ShuffleKind, 1730 SelectionDAG &DAG) { 1731 if (N->getValueType(0) != MVT::v16i8) 1732 return -1; 1733 1734 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 1735 1736 // Find the first non-undef value in the shuffle mask. 1737 unsigned i; 1738 for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i) 1739 /*search*/; 1740 1741 if (i == 16) return -1; // all undef. 1742 1743 // Otherwise, check to see if the rest of the elements are consecutively 1744 // numbered from this value. 1745 unsigned ShiftAmt = SVOp->getMaskElt(i); 1746 if (ShiftAmt < i) return -1; 1747 1748 ShiftAmt -= i; 1749 bool isLE = DAG.getDataLayout().isLittleEndian(); 1750 1751 if ((ShuffleKind == 0 && !isLE) || (ShuffleKind == 2 && isLE)) { 1752 // Check the rest of the elements to see if they are consecutive. 1753 for (++i; i != 16; ++i) 1754 if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i)) 1755 return -1; 1756 } else if (ShuffleKind == 1) { 1757 // Check the rest of the elements to see if they are consecutive. 1758 for (++i; i != 16; ++i) 1759 if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15)) 1760 return -1; 1761 } else 1762 return -1; 1763 1764 if (isLE) 1765 ShiftAmt = 16 - ShiftAmt; 1766 1767 return ShiftAmt; 1768 } 1769 1770 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand 1771 /// specifies a splat of a single element that is suitable for input to 1772 /// VSPLTB/VSPLTH/VSPLTW. 1773 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) { 1774 assert(N->getValueType(0) == MVT::v16i8 && 1775 (EltSize == 1 || EltSize == 2 || EltSize == 4)); 1776 1777 // The consecutive indices need to specify an element, not part of two 1778 // different elements. So abandon ship early if this isn't the case. 1779 if (N->getMaskElt(0) % EltSize != 0) 1780 return false; 1781 1782 // This is a splat operation if each element of the permute is the same, and 1783 // if the value doesn't reference the second vector. 1784 unsigned ElementBase = N->getMaskElt(0); 1785 1786 // FIXME: Handle UNDEF elements too! 1787 if (ElementBase >= 16) 1788 return false; 1789 1790 // Check that the indices are consecutive, in the case of a multi-byte element 1791 // splatted with a v16i8 mask. 1792 for (unsigned i = 1; i != EltSize; ++i) 1793 if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase)) 1794 return false; 1795 1796 for (unsigned i = EltSize, e = 16; i != e; i += EltSize) { 1797 if (N->getMaskElt(i) < 0) continue; 1798 for (unsigned j = 0; j != EltSize; ++j) 1799 if (N->getMaskElt(i+j) != N->getMaskElt(j)) 1800 return false; 1801 } 1802 return true; 1803 } 1804 1805 /// Check that the mask is shuffling N byte elements. Within each N byte 1806 /// element of the mask, the indices could be either in increasing or 1807 /// decreasing order as long as they are consecutive. 1808 /// \param[in] N the shuffle vector SD Node to analyze 1809 /// \param[in] Width the element width in bytes, could be 2/4/8/16 (HalfWord/ 1810 /// Word/DoubleWord/QuadWord). 1811 /// \param[in] StepLen the delta indices number among the N byte element, if 1812 /// the mask is in increasing/decreasing order then it is 1/-1. 1813 /// \return true iff the mask is shuffling N byte elements. 1814 static bool isNByteElemShuffleMask(ShuffleVectorSDNode *N, unsigned Width, 1815 int StepLen) { 1816 assert((Width == 2 || Width == 4 || Width == 8 || Width == 16) && 1817 "Unexpected element width."); 1818 assert((StepLen == 1 || StepLen == -1) && "Unexpected element width."); 1819 1820 unsigned NumOfElem = 16 / Width; 1821 unsigned MaskVal[16]; // Width is never greater than 16 1822 for (unsigned i = 0; i < NumOfElem; ++i) { 1823 MaskVal[0] = N->getMaskElt(i * Width); 1824 if ((StepLen == 1) && (MaskVal[0] % Width)) { 1825 return false; 1826 } else if ((StepLen == -1) && ((MaskVal[0] + 1) % Width)) { 1827 return false; 1828 } 1829 1830 for (unsigned int j = 1; j < Width; ++j) { 1831 MaskVal[j] = N->getMaskElt(i * Width + j); 1832 if (MaskVal[j] != MaskVal[j-1] + StepLen) { 1833 return false; 1834 } 1835 } 1836 } 1837 1838 return true; 1839 } 1840 1841 bool PPC::isXXINSERTWMask(ShuffleVectorSDNode *N, unsigned &ShiftElts, 1842 unsigned &InsertAtByte, bool &Swap, bool IsLE) { 1843 if (!isNByteElemShuffleMask(N, 4, 1)) 1844 return false; 1845 1846 // Now we look at mask elements 0,4,8,12 1847 unsigned M0 = N->getMaskElt(0) / 4; 1848 unsigned M1 = N->getMaskElt(4) / 4; 1849 unsigned M2 = N->getMaskElt(8) / 4; 1850 unsigned M3 = N->getMaskElt(12) / 4; 1851 unsigned LittleEndianShifts[] = { 2, 1, 0, 3 }; 1852 unsigned BigEndianShifts[] = { 3, 0, 1, 2 }; 1853 1854 // Below, let H and L be arbitrary elements of the shuffle mask 1855 // where H is in the range [4,7] and L is in the range [0,3]. 1856 // H, 1, 2, 3 or L, 5, 6, 7 1857 if ((M0 > 3 && M1 == 1 && M2 == 2 && M3 == 3) || 1858 (M0 < 4 && M1 == 5 && M2 == 6 && M3 == 7)) { 1859 ShiftElts = IsLE ? LittleEndianShifts[M0 & 0x3] : BigEndianShifts[M0 & 0x3]; 1860 InsertAtByte = IsLE ? 12 : 0; 1861 Swap = M0 < 4; 1862 return true; 1863 } 1864 // 0, H, 2, 3 or 4, L, 6, 7 1865 if ((M1 > 3 && M0 == 0 && M2 == 2 && M3 == 3) || 1866 (M1 < 4 && M0 == 4 && M2 == 6 && M3 == 7)) { 1867 ShiftElts = IsLE ? LittleEndianShifts[M1 & 0x3] : BigEndianShifts[M1 & 0x3]; 1868 InsertAtByte = IsLE ? 8 : 4; 1869 Swap = M1 < 4; 1870 return true; 1871 } 1872 // 0, 1, H, 3 or 4, 5, L, 7 1873 if ((M2 > 3 && M0 == 0 && M1 == 1 && M3 == 3) || 1874 (M2 < 4 && M0 == 4 && M1 == 5 && M3 == 7)) { 1875 ShiftElts = IsLE ? LittleEndianShifts[M2 & 0x3] : BigEndianShifts[M2 & 0x3]; 1876 InsertAtByte = IsLE ? 4 : 8; 1877 Swap = M2 < 4; 1878 return true; 1879 } 1880 // 0, 1, 2, H or 4, 5, 6, L 1881 if ((M3 > 3 && M0 == 0 && M1 == 1 && M2 == 2) || 1882 (M3 < 4 && M0 == 4 && M1 == 5 && M2 == 6)) { 1883 ShiftElts = IsLE ? LittleEndianShifts[M3 & 0x3] : BigEndianShifts[M3 & 0x3]; 1884 InsertAtByte = IsLE ? 0 : 12; 1885 Swap = M3 < 4; 1886 return true; 1887 } 1888 1889 // If both vector operands for the shuffle are the same vector, the mask will 1890 // contain only elements from the first one and the second one will be undef. 1891 if (N->getOperand(1).isUndef()) { 1892 ShiftElts = 0; 1893 Swap = true; 1894 unsigned XXINSERTWSrcElem = IsLE ? 2 : 1; 1895 if (M0 == XXINSERTWSrcElem && M1 == 1 && M2 == 2 && M3 == 3) { 1896 InsertAtByte = IsLE ? 12 : 0; 1897 return true; 1898 } 1899 if (M0 == 0 && M1 == XXINSERTWSrcElem && M2 == 2 && M3 == 3) { 1900 InsertAtByte = IsLE ? 8 : 4; 1901 return true; 1902 } 1903 if (M0 == 0 && M1 == 1 && M2 == XXINSERTWSrcElem && M3 == 3) { 1904 InsertAtByte = IsLE ? 4 : 8; 1905 return true; 1906 } 1907 if (M0 == 0 && M1 == 1 && M2 == 2 && M3 == XXINSERTWSrcElem) { 1908 InsertAtByte = IsLE ? 0 : 12; 1909 return true; 1910 } 1911 } 1912 1913 return false; 1914 } 1915 1916 bool PPC::isXXSLDWIShuffleMask(ShuffleVectorSDNode *N, unsigned &ShiftElts, 1917 bool &Swap, bool IsLE) { 1918 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8"); 1919 // Ensure each byte index of the word is consecutive. 1920 if (!isNByteElemShuffleMask(N, 4, 1)) 1921 return false; 1922 1923 // Now we look at mask elements 0,4,8,12, which are the beginning of words. 1924 unsigned M0 = N->getMaskElt(0) / 4; 1925 unsigned M1 = N->getMaskElt(4) / 4; 1926 unsigned M2 = N->getMaskElt(8) / 4; 1927 unsigned M3 = N->getMaskElt(12) / 4; 1928 1929 // If both vector operands for the shuffle are the same vector, the mask will 1930 // contain only elements from the first one and the second one will be undef. 1931 if (N->getOperand(1).isUndef()) { 1932 assert(M0 < 4 && "Indexing into an undef vector?"); 1933 if (M1 != (M0 + 1) % 4 || M2 != (M1 + 1) % 4 || M3 != (M2 + 1) % 4) 1934 return false; 1935 1936 ShiftElts = IsLE ? (4 - M0) % 4 : M0; 1937 Swap = false; 1938 return true; 1939 } 1940 1941 // Ensure each word index of the ShuffleVector Mask is consecutive. 1942 if (M1 != (M0 + 1) % 8 || M2 != (M1 + 1) % 8 || M3 != (M2 + 1) % 8) 1943 return false; 1944 1945 if (IsLE) { 1946 if (M0 == 0 || M0 == 7 || M0 == 6 || M0 == 5) { 1947 // Input vectors don't need to be swapped if the leading element 1948 // of the result is one of the 3 left elements of the second vector 1949 // (or if there is no shift to be done at all). 1950 Swap = false; 1951 ShiftElts = (8 - M0) % 8; 1952 } else if (M0 == 4 || M0 == 3 || M0 == 2 || M0 == 1) { 1953 // Input vectors need to be swapped if the leading element 1954 // of the result is one of the 3 left elements of the first vector 1955 // (or if we're shifting by 4 - thereby simply swapping the vectors). 1956 Swap = true; 1957 ShiftElts = (4 - M0) % 4; 1958 } 1959 1960 return true; 1961 } else { // BE 1962 if (M0 == 0 || M0 == 1 || M0 == 2 || M0 == 3) { 1963 // Input vectors don't need to be swapped if the leading element 1964 // of the result is one of the 4 elements of the first vector. 1965 Swap = false; 1966 ShiftElts = M0; 1967 } else if (M0 == 4 || M0 == 5 || M0 == 6 || M0 == 7) { 1968 // Input vectors need to be swapped if the leading element 1969 // of the result is one of the 4 elements of the right vector. 1970 Swap = true; 1971 ShiftElts = M0 - 4; 1972 } 1973 1974 return true; 1975 } 1976 } 1977 1978 bool static isXXBRShuffleMaskHelper(ShuffleVectorSDNode *N, int Width) { 1979 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8"); 1980 1981 if (!isNByteElemShuffleMask(N, Width, -1)) 1982 return false; 1983 1984 for (int i = 0; i < 16; i += Width) 1985 if (N->getMaskElt(i) != i + Width - 1) 1986 return false; 1987 1988 return true; 1989 } 1990 1991 bool PPC::isXXBRHShuffleMask(ShuffleVectorSDNode *N) { 1992 return isXXBRShuffleMaskHelper(N, 2); 1993 } 1994 1995 bool PPC::isXXBRWShuffleMask(ShuffleVectorSDNode *N) { 1996 return isXXBRShuffleMaskHelper(N, 4); 1997 } 1998 1999 bool PPC::isXXBRDShuffleMask(ShuffleVectorSDNode *N) { 2000 return isXXBRShuffleMaskHelper(N, 8); 2001 } 2002 2003 bool PPC::isXXBRQShuffleMask(ShuffleVectorSDNode *N) { 2004 return isXXBRShuffleMaskHelper(N, 16); 2005 } 2006 2007 /// Can node \p N be lowered to an XXPERMDI instruction? If so, set \p Swap 2008 /// if the inputs to the instruction should be swapped and set \p DM to the 2009 /// value for the immediate. 2010 /// Specifically, set \p Swap to true only if \p N can be lowered to XXPERMDI 2011 /// AND element 0 of the result comes from the first input (LE) or second input 2012 /// (BE). Set \p DM to the calculated result (0-3) only if \p N can be lowered. 2013 /// \return true iff the given mask of shuffle node \p N is a XXPERMDI shuffle 2014 /// mask. 2015 bool PPC::isXXPERMDIShuffleMask(ShuffleVectorSDNode *N, unsigned &DM, 2016 bool &Swap, bool IsLE) { 2017 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8"); 2018 2019 // Ensure each byte index of the double word is consecutive. 2020 if (!isNByteElemShuffleMask(N, 8, 1)) 2021 return false; 2022 2023 unsigned M0 = N->getMaskElt(0) / 8; 2024 unsigned M1 = N->getMaskElt(8) / 8; 2025 assert(((M0 | M1) < 4) && "A mask element out of bounds?"); 2026 2027 // If both vector operands for the shuffle are the same vector, the mask will 2028 // contain only elements from the first one and the second one will be undef. 2029 if (N->getOperand(1).isUndef()) { 2030 if ((M0 | M1) < 2) { 2031 DM = IsLE ? (((~M1) & 1) << 1) + ((~M0) & 1) : (M0 << 1) + (M1 & 1); 2032 Swap = false; 2033 return true; 2034 } else 2035 return false; 2036 } 2037 2038 if (IsLE) { 2039 if (M0 > 1 && M1 < 2) { 2040 Swap = false; 2041 } else if (M0 < 2 && M1 > 1) { 2042 M0 = (M0 + 2) % 4; 2043 M1 = (M1 + 2) % 4; 2044 Swap = true; 2045 } else 2046 return false; 2047 2048 // Note: if control flow comes here that means Swap is already set above 2049 DM = (((~M1) & 1) << 1) + ((~M0) & 1); 2050 return true; 2051 } else { // BE 2052 if (M0 < 2 && M1 > 1) { 2053 Swap = false; 2054 } else if (M0 > 1 && M1 < 2) { 2055 M0 = (M0 + 2) % 4; 2056 M1 = (M1 + 2) % 4; 2057 Swap = true; 2058 } else 2059 return false; 2060 2061 // Note: if control flow comes here that means Swap is already set above 2062 DM = (M0 << 1) + (M1 & 1); 2063 return true; 2064 } 2065 } 2066 2067 2068 /// getVSPLTImmediate - Return the appropriate VSPLT* immediate to splat the 2069 /// specified isSplatShuffleMask VECTOR_SHUFFLE mask. 2070 unsigned PPC::getVSPLTImmediate(SDNode *N, unsigned EltSize, 2071 SelectionDAG &DAG) { 2072 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 2073 assert(isSplatShuffleMask(SVOp, EltSize)); 2074 if (DAG.getDataLayout().isLittleEndian()) 2075 return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize); 2076 else 2077 return SVOp->getMaskElt(0) / EltSize; 2078 } 2079 2080 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed 2081 /// by using a vspltis[bhw] instruction of the specified element size, return 2082 /// the constant being splatted. The ByteSize field indicates the number of 2083 /// bytes of each element [124] -> [bhw]. 2084 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) { 2085 SDValue OpVal(nullptr, 0); 2086 2087 // If ByteSize of the splat is bigger than the element size of the 2088 // build_vector, then we have a case where we are checking for a splat where 2089 // multiple elements of the buildvector are folded together into a single 2090 // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8). 2091 unsigned EltSize = 16/N->getNumOperands(); 2092 if (EltSize < ByteSize) { 2093 unsigned Multiple = ByteSize/EltSize; // Number of BV entries per spltval. 2094 SDValue UniquedVals[4]; 2095 assert(Multiple > 1 && Multiple <= 4 && "How can this happen?"); 2096 2097 // See if all of the elements in the buildvector agree across. 2098 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 2099 if (N->getOperand(i).isUndef()) continue; 2100 // If the element isn't a constant, bail fully out. 2101 if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue(); 2102 2103 if (!UniquedVals[i&(Multiple-1)].getNode()) 2104 UniquedVals[i&(Multiple-1)] = N->getOperand(i); 2105 else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i)) 2106 return SDValue(); // no match. 2107 } 2108 2109 // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains 2110 // either constant or undef values that are identical for each chunk. See 2111 // if these chunks can form into a larger vspltis*. 2112 2113 // Check to see if all of the leading entries are either 0 or -1. If 2114 // neither, then this won't fit into the immediate field. 2115 bool LeadingZero = true; 2116 bool LeadingOnes = true; 2117 for (unsigned i = 0; i != Multiple-1; ++i) { 2118 if (!UniquedVals[i].getNode()) continue; // Must have been undefs. 2119 2120 LeadingZero &= isNullConstant(UniquedVals[i]); 2121 LeadingOnes &= isAllOnesConstant(UniquedVals[i]); 2122 } 2123 // Finally, check the least significant entry. 2124 if (LeadingZero) { 2125 if (!UniquedVals[Multiple-1].getNode()) 2126 return DAG.getTargetConstant(0, SDLoc(N), MVT::i32); // 0,0,0,undef 2127 int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue(); 2128 if (Val < 16) // 0,0,0,4 -> vspltisw(4) 2129 return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32); 2130 } 2131 if (LeadingOnes) { 2132 if (!UniquedVals[Multiple-1].getNode()) 2133 return DAG.getTargetConstant(~0U, SDLoc(N), MVT::i32); // -1,-1,-1,undef 2134 int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue(); 2135 if (Val >= -16) // -1,-1,-1,-2 -> vspltisw(-2) 2136 return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32); 2137 } 2138 2139 return SDValue(); 2140 } 2141 2142 // Check to see if this buildvec has a single non-undef value in its elements. 2143 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 2144 if (N->getOperand(i).isUndef()) continue; 2145 if (!OpVal.getNode()) 2146 OpVal = N->getOperand(i); 2147 else if (OpVal != N->getOperand(i)) 2148 return SDValue(); 2149 } 2150 2151 if (!OpVal.getNode()) return SDValue(); // All UNDEF: use implicit def. 2152 2153 unsigned ValSizeInBytes = EltSize; 2154 uint64_t Value = 0; 2155 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) { 2156 Value = CN->getZExtValue(); 2157 } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) { 2158 assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!"); 2159 Value = FloatToBits(CN->getValueAPF().convertToFloat()); 2160 } 2161 2162 // If the splat value is larger than the element value, then we can never do 2163 // this splat. The only case that we could fit the replicated bits into our 2164 // immediate field for would be zero, and we prefer to use vxor for it. 2165 if (ValSizeInBytes < ByteSize) return SDValue(); 2166 2167 // If the element value is larger than the splat value, check if it consists 2168 // of a repeated bit pattern of size ByteSize. 2169 if (!APInt(ValSizeInBytes * 8, Value).isSplat(ByteSize * 8)) 2170 return SDValue(); 2171 2172 // Properly sign extend the value. 2173 int MaskVal = SignExtend32(Value, ByteSize * 8); 2174 2175 // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros. 2176 if (MaskVal == 0) return SDValue(); 2177 2178 // Finally, if this value fits in a 5 bit sext field, return it 2179 if (SignExtend32<5>(MaskVal) == MaskVal) 2180 return DAG.getTargetConstant(MaskVal, SDLoc(N), MVT::i32); 2181 return SDValue(); 2182 } 2183 2184 /// isQVALIGNIShuffleMask - If this is a qvaligni shuffle mask, return the shift 2185 /// amount, otherwise return -1. 2186 int PPC::isQVALIGNIShuffleMask(SDNode *N) { 2187 EVT VT = N->getValueType(0); 2188 if (VT != MVT::v4f64 && VT != MVT::v4f32 && VT != MVT::v4i1) 2189 return -1; 2190 2191 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 2192 2193 // Find the first non-undef value in the shuffle mask. 2194 unsigned i; 2195 for (i = 0; i != 4 && SVOp->getMaskElt(i) < 0; ++i) 2196 /*search*/; 2197 2198 if (i == 4) return -1; // all undef. 2199 2200 // Otherwise, check to see if the rest of the elements are consecutively 2201 // numbered from this value. 2202 unsigned ShiftAmt = SVOp->getMaskElt(i); 2203 if (ShiftAmt < i) return -1; 2204 ShiftAmt -= i; 2205 2206 // Check the rest of the elements to see if they are consecutive. 2207 for (++i; i != 4; ++i) 2208 if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i)) 2209 return -1; 2210 2211 return ShiftAmt; 2212 } 2213 2214 //===----------------------------------------------------------------------===// 2215 // Addressing Mode Selection 2216 //===----------------------------------------------------------------------===// 2217 2218 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit 2219 /// or 64-bit immediate, and if the value can be accurately represented as a 2220 /// sign extension from a 16-bit value. If so, this returns true and the 2221 /// immediate. 2222 bool llvm::isIntS16Immediate(SDNode *N, int16_t &Imm) { 2223 if (!isa<ConstantSDNode>(N)) 2224 return false; 2225 2226 Imm = (int16_t)cast<ConstantSDNode>(N)->getZExtValue(); 2227 if (N->getValueType(0) == MVT::i32) 2228 return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue(); 2229 else 2230 return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue(); 2231 } 2232 bool llvm::isIntS16Immediate(SDValue Op, int16_t &Imm) { 2233 return isIntS16Immediate(Op.getNode(), Imm); 2234 } 2235 2236 /// SelectAddressRegReg - Given the specified addressed, check to see if it 2237 /// can be represented as an indexed [r+r] operation. Returns false if it 2238 /// can be more efficiently represented as [r+imm]. If \p EncodingAlignment is 2239 /// non-zero and N can be represented by a base register plus a signed 16-bit 2240 /// displacement, make a more precise judgement by checking (displacement % \p 2241 /// EncodingAlignment). 2242 bool PPCTargetLowering::SelectAddressRegReg(SDValue N, SDValue &Base, 2243 SDValue &Index, SelectionDAG &DAG, 2244 unsigned EncodingAlignment) const { 2245 int16_t imm = 0; 2246 if (N.getOpcode() == ISD::ADD) { 2247 if (isIntS16Immediate(N.getOperand(1), imm) && 2248 (!EncodingAlignment || !(imm % EncodingAlignment))) 2249 return false; // r+i 2250 if (N.getOperand(1).getOpcode() == PPCISD::Lo) 2251 return false; // r+i 2252 2253 Base = N.getOperand(0); 2254 Index = N.getOperand(1); 2255 return true; 2256 } else if (N.getOpcode() == ISD::OR) { 2257 if (isIntS16Immediate(N.getOperand(1), imm) && 2258 (!EncodingAlignment || !(imm % EncodingAlignment))) 2259 return false; // r+i can fold it if we can. 2260 2261 // If this is an or of disjoint bitfields, we can codegen this as an add 2262 // (for better address arithmetic) if the LHS and RHS of the OR are provably 2263 // disjoint. 2264 KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0)); 2265 2266 if (LHSKnown.Zero.getBoolValue()) { 2267 KnownBits RHSKnown = DAG.computeKnownBits(N.getOperand(1)); 2268 // If all of the bits are known zero on the LHS or RHS, the add won't 2269 // carry. 2270 if (~(LHSKnown.Zero | RHSKnown.Zero) == 0) { 2271 Base = N.getOperand(0); 2272 Index = N.getOperand(1); 2273 return true; 2274 } 2275 } 2276 } 2277 2278 return false; 2279 } 2280 2281 // If we happen to be doing an i64 load or store into a stack slot that has 2282 // less than a 4-byte alignment, then the frame-index elimination may need to 2283 // use an indexed load or store instruction (because the offset may not be a 2284 // multiple of 4). The extra register needed to hold the offset comes from the 2285 // register scavenger, and it is possible that the scavenger will need to use 2286 // an emergency spill slot. As a result, we need to make sure that a spill slot 2287 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned 2288 // stack slot. 2289 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) { 2290 // FIXME: This does not handle the LWA case. 2291 if (VT != MVT::i64) 2292 return; 2293 2294 // NOTE: We'll exclude negative FIs here, which come from argument 2295 // lowering, because there are no known test cases triggering this problem 2296 // using packed structures (or similar). We can remove this exclusion if 2297 // we find such a test case. The reason why this is so test-case driven is 2298 // because this entire 'fixup' is only to prevent crashes (from the 2299 // register scavenger) on not-really-valid inputs. For example, if we have: 2300 // %a = alloca i1 2301 // %b = bitcast i1* %a to i64* 2302 // store i64* a, i64 b 2303 // then the store should really be marked as 'align 1', but is not. If it 2304 // were marked as 'align 1' then the indexed form would have been 2305 // instruction-selected initially, and the problem this 'fixup' is preventing 2306 // won't happen regardless. 2307 if (FrameIdx < 0) 2308 return; 2309 2310 MachineFunction &MF = DAG.getMachineFunction(); 2311 MachineFrameInfo &MFI = MF.getFrameInfo(); 2312 2313 unsigned Align = MFI.getObjectAlignment(FrameIdx); 2314 if (Align >= 4) 2315 return; 2316 2317 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 2318 FuncInfo->setHasNonRISpills(); 2319 } 2320 2321 /// Returns true if the address N can be represented by a base register plus 2322 /// a signed 16-bit displacement [r+imm], and if it is not better 2323 /// represented as reg+reg. If \p EncodingAlignment is non-zero, only accept 2324 /// displacements that are multiples of that value. 2325 bool PPCTargetLowering::SelectAddressRegImm(SDValue N, SDValue &Disp, 2326 SDValue &Base, 2327 SelectionDAG &DAG, 2328 unsigned EncodingAlignment) const { 2329 // FIXME dl should come from parent load or store, not from address 2330 SDLoc dl(N); 2331 // If this can be more profitably realized as r+r, fail. 2332 if (SelectAddressRegReg(N, Disp, Base, DAG, EncodingAlignment)) 2333 return false; 2334 2335 if (N.getOpcode() == ISD::ADD) { 2336 int16_t imm = 0; 2337 if (isIntS16Immediate(N.getOperand(1), imm) && 2338 (!EncodingAlignment || (imm % EncodingAlignment) == 0)) { 2339 Disp = DAG.getTargetConstant(imm, dl, N.getValueType()); 2340 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) { 2341 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2342 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 2343 } else { 2344 Base = N.getOperand(0); 2345 } 2346 return true; // [r+i] 2347 } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) { 2348 // Match LOAD (ADD (X, Lo(G))). 2349 assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue() 2350 && "Cannot handle constant offsets yet!"); 2351 Disp = N.getOperand(1).getOperand(0); // The global address. 2352 assert(Disp.getOpcode() == ISD::TargetGlobalAddress || 2353 Disp.getOpcode() == ISD::TargetGlobalTLSAddress || 2354 Disp.getOpcode() == ISD::TargetConstantPool || 2355 Disp.getOpcode() == ISD::TargetJumpTable); 2356 Base = N.getOperand(0); 2357 return true; // [&g+r] 2358 } 2359 } else if (N.getOpcode() == ISD::OR) { 2360 int16_t imm = 0; 2361 if (isIntS16Immediate(N.getOperand(1), imm) && 2362 (!EncodingAlignment || (imm % EncodingAlignment) == 0)) { 2363 // If this is an or of disjoint bitfields, we can codegen this as an add 2364 // (for better address arithmetic) if the LHS and RHS of the OR are 2365 // provably disjoint. 2366 KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0)); 2367 2368 if ((LHSKnown.Zero.getZExtValue()|~(uint64_t)imm) == ~0ULL) { 2369 // If all of the bits are known zero on the LHS or RHS, the add won't 2370 // carry. 2371 if (FrameIndexSDNode *FI = 2372 dyn_cast<FrameIndexSDNode>(N.getOperand(0))) { 2373 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2374 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 2375 } else { 2376 Base = N.getOperand(0); 2377 } 2378 Disp = DAG.getTargetConstant(imm, dl, N.getValueType()); 2379 return true; 2380 } 2381 } 2382 } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) { 2383 // Loading from a constant address. 2384 2385 // If this address fits entirely in a 16-bit sext immediate field, codegen 2386 // this as "d, 0" 2387 int16_t Imm; 2388 if (isIntS16Immediate(CN, Imm) && 2389 (!EncodingAlignment || (Imm % EncodingAlignment) == 0)) { 2390 Disp = DAG.getTargetConstant(Imm, dl, CN->getValueType(0)); 2391 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO, 2392 CN->getValueType(0)); 2393 return true; 2394 } 2395 2396 // Handle 32-bit sext immediates with LIS + addr mode. 2397 if ((CN->getValueType(0) == MVT::i32 || 2398 (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) && 2399 (!EncodingAlignment || (CN->getZExtValue() % EncodingAlignment) == 0)) { 2400 int Addr = (int)CN->getZExtValue(); 2401 2402 // Otherwise, break this down into an LIS + disp. 2403 Disp = DAG.getTargetConstant((short)Addr, dl, MVT::i32); 2404 2405 Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, dl, 2406 MVT::i32); 2407 unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8; 2408 Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0); 2409 return true; 2410 } 2411 } 2412 2413 Disp = DAG.getTargetConstant(0, dl, getPointerTy(DAG.getDataLayout())); 2414 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) { 2415 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2416 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 2417 } else 2418 Base = N; 2419 return true; // [r+0] 2420 } 2421 2422 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be 2423 /// represented as an indexed [r+r] operation. 2424 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base, 2425 SDValue &Index, 2426 SelectionDAG &DAG) const { 2427 // Check to see if we can easily represent this as an [r+r] address. This 2428 // will fail if it thinks that the address is more profitably represented as 2429 // reg+imm, e.g. where imm = 0. 2430 if (SelectAddressRegReg(N, Base, Index, DAG)) 2431 return true; 2432 2433 // If the address is the result of an add, we will utilize the fact that the 2434 // address calculation includes an implicit add. However, we can reduce 2435 // register pressure if we do not materialize a constant just for use as the 2436 // index register. We only get rid of the add if it is not an add of a 2437 // value and a 16-bit signed constant and both have a single use. 2438 int16_t imm = 0; 2439 if (N.getOpcode() == ISD::ADD && 2440 (!isIntS16Immediate(N.getOperand(1), imm) || 2441 !N.getOperand(1).hasOneUse() || !N.getOperand(0).hasOneUse())) { 2442 Base = N.getOperand(0); 2443 Index = N.getOperand(1); 2444 return true; 2445 } 2446 2447 // Otherwise, do it the hard way, using R0 as the base register. 2448 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO, 2449 N.getValueType()); 2450 Index = N; 2451 return true; 2452 } 2453 2454 /// Returns true if we should use a direct load into vector instruction 2455 /// (such as lxsd or lfd), instead of a load into gpr + direct move sequence. 2456 static bool usePartialVectorLoads(SDNode *N, const PPCSubtarget& ST) { 2457 2458 // If there are any other uses other than scalar to vector, then we should 2459 // keep it as a scalar load -> direct move pattern to prevent multiple 2460 // loads. 2461 LoadSDNode *LD = dyn_cast<LoadSDNode>(N); 2462 if (!LD) 2463 return false; 2464 2465 EVT MemVT = LD->getMemoryVT(); 2466 if (!MemVT.isSimple()) 2467 return false; 2468 switch(MemVT.getSimpleVT().SimpleTy) { 2469 case MVT::i64: 2470 break; 2471 case MVT::i32: 2472 if (!ST.hasP8Vector()) 2473 return false; 2474 break; 2475 case MVT::i16: 2476 case MVT::i8: 2477 if (!ST.hasP9Vector()) 2478 return false; 2479 break; 2480 default: 2481 return false; 2482 } 2483 2484 SDValue LoadedVal(N, 0); 2485 if (!LoadedVal.hasOneUse()) 2486 return false; 2487 2488 for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end(); 2489 UI != UE; ++UI) 2490 if (UI.getUse().get().getResNo() == 0 && 2491 UI->getOpcode() != ISD::SCALAR_TO_VECTOR) 2492 return false; 2493 2494 return true; 2495 } 2496 2497 /// getPreIndexedAddressParts - returns true by value, base pointer and 2498 /// offset pointer and addressing mode by reference if the node's address 2499 /// can be legally represented as pre-indexed load / store address. 2500 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base, 2501 SDValue &Offset, 2502 ISD::MemIndexedMode &AM, 2503 SelectionDAG &DAG) const { 2504 if (DisablePPCPreinc) return false; 2505 2506 bool isLoad = true; 2507 SDValue Ptr; 2508 EVT VT; 2509 unsigned Alignment; 2510 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 2511 Ptr = LD->getBasePtr(); 2512 VT = LD->getMemoryVT(); 2513 Alignment = LD->getAlignment(); 2514 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 2515 Ptr = ST->getBasePtr(); 2516 VT = ST->getMemoryVT(); 2517 Alignment = ST->getAlignment(); 2518 isLoad = false; 2519 } else 2520 return false; 2521 2522 // Do not generate pre-inc forms for specific loads that feed scalar_to_vector 2523 // instructions because we can fold these into a more efficient instruction 2524 // instead, (such as LXSD). 2525 if (isLoad && usePartialVectorLoads(N, Subtarget)) { 2526 return false; 2527 } 2528 2529 // PowerPC doesn't have preinc load/store instructions for vectors (except 2530 // for QPX, which does have preinc r+r forms). 2531 if (VT.isVector()) { 2532 if (!Subtarget.hasQPX() || (VT != MVT::v4f64 && VT != MVT::v4f32)) { 2533 return false; 2534 } else if (SelectAddressRegRegOnly(Ptr, Offset, Base, DAG)) { 2535 AM = ISD::PRE_INC; 2536 return true; 2537 } 2538 } 2539 2540 if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) { 2541 // Common code will reject creating a pre-inc form if the base pointer 2542 // is a frame index, or if N is a store and the base pointer is either 2543 // the same as or a predecessor of the value being stored. Check for 2544 // those situations here, and try with swapped Base/Offset instead. 2545 bool Swap = false; 2546 2547 if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base)) 2548 Swap = true; 2549 else if (!isLoad) { 2550 SDValue Val = cast<StoreSDNode>(N)->getValue(); 2551 if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode())) 2552 Swap = true; 2553 } 2554 2555 if (Swap) 2556 std::swap(Base, Offset); 2557 2558 AM = ISD::PRE_INC; 2559 return true; 2560 } 2561 2562 // LDU/STU can only handle immediates that are a multiple of 4. 2563 if (VT != MVT::i64) { 2564 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, 0)) 2565 return false; 2566 } else { 2567 // LDU/STU need an address with at least 4-byte alignment. 2568 if (Alignment < 4) 2569 return false; 2570 2571 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, 4)) 2572 return false; 2573 } 2574 2575 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 2576 // PPC64 doesn't have lwau, but it does have lwaux. Reject preinc load of 2577 // sext i32 to i64 when addr mode is r+i. 2578 if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 && 2579 LD->getExtensionType() == ISD::SEXTLOAD && 2580 isa<ConstantSDNode>(Offset)) 2581 return false; 2582 } 2583 2584 AM = ISD::PRE_INC; 2585 return true; 2586 } 2587 2588 //===----------------------------------------------------------------------===// 2589 // LowerOperation implementation 2590 //===----------------------------------------------------------------------===// 2591 2592 /// Return true if we should reference labels using a PICBase, set the HiOpFlags 2593 /// and LoOpFlags to the target MO flags. 2594 static void getLabelAccessInfo(bool IsPIC, const PPCSubtarget &Subtarget, 2595 unsigned &HiOpFlags, unsigned &LoOpFlags, 2596 const GlobalValue *GV = nullptr) { 2597 HiOpFlags = PPCII::MO_HA; 2598 LoOpFlags = PPCII::MO_LO; 2599 2600 // Don't use the pic base if not in PIC relocation model. 2601 if (IsPIC) { 2602 HiOpFlags |= PPCII::MO_PIC_FLAG; 2603 LoOpFlags |= PPCII::MO_PIC_FLAG; 2604 } 2605 2606 // If this is a reference to a global value that requires a non-lazy-ptr, make 2607 // sure that instruction lowering adds it. 2608 if (GV && Subtarget.hasLazyResolverStub(GV)) { 2609 HiOpFlags |= PPCII::MO_NLP_FLAG; 2610 LoOpFlags |= PPCII::MO_NLP_FLAG; 2611 2612 if (GV->hasHiddenVisibility()) { 2613 HiOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG; 2614 LoOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG; 2615 } 2616 } 2617 } 2618 2619 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC, 2620 SelectionDAG &DAG) { 2621 SDLoc DL(HiPart); 2622 EVT PtrVT = HiPart.getValueType(); 2623 SDValue Zero = DAG.getConstant(0, DL, PtrVT); 2624 2625 SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero); 2626 SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero); 2627 2628 // With PIC, the first instruction is actually "GR+hi(&G)". 2629 if (isPIC) 2630 Hi = DAG.getNode(ISD::ADD, DL, PtrVT, 2631 DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi); 2632 2633 // Generate non-pic code that has direct accesses to the constant pool. 2634 // The address of the global is just (hi(&g)+lo(&g)). 2635 return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo); 2636 } 2637 2638 static void setUsesTOCBasePtr(MachineFunction &MF) { 2639 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 2640 FuncInfo->setUsesTOCBasePtr(); 2641 } 2642 2643 static void setUsesTOCBasePtr(SelectionDAG &DAG) { 2644 setUsesTOCBasePtr(DAG.getMachineFunction()); 2645 } 2646 2647 static SDValue getTOCEntry(SelectionDAG &DAG, const SDLoc &dl, bool Is64Bit, 2648 SDValue GA) { 2649 EVT VT = Is64Bit ? MVT::i64 : MVT::i32; 2650 SDValue Reg = Is64Bit ? DAG.getRegister(PPC::X2, VT) : 2651 DAG.getNode(PPCISD::GlobalBaseReg, dl, VT); 2652 2653 SDValue Ops[] = { GA, Reg }; 2654 return DAG.getMemIntrinsicNode( 2655 PPCISD::TOC_ENTRY, dl, DAG.getVTList(VT, MVT::Other), Ops, VT, 2656 MachinePointerInfo::getGOT(DAG.getMachineFunction()), 0, 2657 MachineMemOperand::MOLoad); 2658 } 2659 2660 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op, 2661 SelectionDAG &DAG) const { 2662 EVT PtrVT = Op.getValueType(); 2663 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op); 2664 const Constant *C = CP->getConstVal(); 2665 2666 // 64-bit SVR4 ABI code is always position-independent. 2667 // The actual address of the GlobalValue is stored in the TOC. 2668 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) { 2669 setUsesTOCBasePtr(DAG); 2670 SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0); 2671 return getTOCEntry(DAG, SDLoc(CP), true, GA); 2672 } 2673 2674 unsigned MOHiFlag, MOLoFlag; 2675 bool IsPIC = isPositionIndependent(); 2676 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag); 2677 2678 if (IsPIC && Subtarget.isSVR4ABI()) { 2679 SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 2680 PPCII::MO_PIC_FLAG); 2681 return getTOCEntry(DAG, SDLoc(CP), false, GA); 2682 } 2683 2684 SDValue CPIHi = 2685 DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOHiFlag); 2686 SDValue CPILo = 2687 DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOLoFlag); 2688 return LowerLabelRef(CPIHi, CPILo, IsPIC, DAG); 2689 } 2690 2691 // For 64-bit PowerPC, prefer the more compact relative encodings. 2692 // This trades 32 bits per jump table entry for one or two instructions 2693 // on the jump site. 2694 unsigned PPCTargetLowering::getJumpTableEncoding() const { 2695 if (isJumpTableRelative()) 2696 return MachineJumpTableInfo::EK_LabelDifference32; 2697 2698 return TargetLowering::getJumpTableEncoding(); 2699 } 2700 2701 bool PPCTargetLowering::isJumpTableRelative() const { 2702 if (Subtarget.isPPC64()) 2703 return true; 2704 return TargetLowering::isJumpTableRelative(); 2705 } 2706 2707 SDValue PPCTargetLowering::getPICJumpTableRelocBase(SDValue Table, 2708 SelectionDAG &DAG) const { 2709 if (!Subtarget.isPPC64()) 2710 return TargetLowering::getPICJumpTableRelocBase(Table, DAG); 2711 2712 switch (getTargetMachine().getCodeModel()) { 2713 case CodeModel::Small: 2714 case CodeModel::Medium: 2715 return TargetLowering::getPICJumpTableRelocBase(Table, DAG); 2716 default: 2717 return DAG.getNode(PPCISD::GlobalBaseReg, SDLoc(), 2718 getPointerTy(DAG.getDataLayout())); 2719 } 2720 } 2721 2722 const MCExpr * 2723 PPCTargetLowering::getPICJumpTableRelocBaseExpr(const MachineFunction *MF, 2724 unsigned JTI, 2725 MCContext &Ctx) const { 2726 if (!Subtarget.isPPC64()) 2727 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx); 2728 2729 switch (getTargetMachine().getCodeModel()) { 2730 case CodeModel::Small: 2731 case CodeModel::Medium: 2732 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx); 2733 default: 2734 return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx); 2735 } 2736 } 2737 2738 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const { 2739 EVT PtrVT = Op.getValueType(); 2740 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op); 2741 2742 // 64-bit SVR4 ABI code is always position-independent. 2743 // The actual address of the GlobalValue is stored in the TOC. 2744 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) { 2745 setUsesTOCBasePtr(DAG); 2746 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT); 2747 return getTOCEntry(DAG, SDLoc(JT), true, GA); 2748 } 2749 2750 unsigned MOHiFlag, MOLoFlag; 2751 bool IsPIC = isPositionIndependent(); 2752 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag); 2753 2754 if (IsPIC && Subtarget.isSVR4ABI()) { 2755 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, 2756 PPCII::MO_PIC_FLAG); 2757 return getTOCEntry(DAG, SDLoc(GA), false, GA); 2758 } 2759 2760 SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag); 2761 SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag); 2762 return LowerLabelRef(JTIHi, JTILo, IsPIC, DAG); 2763 } 2764 2765 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op, 2766 SelectionDAG &DAG) const { 2767 EVT PtrVT = Op.getValueType(); 2768 BlockAddressSDNode *BASDN = cast<BlockAddressSDNode>(Op); 2769 const BlockAddress *BA = BASDN->getBlockAddress(); 2770 2771 // 64-bit SVR4 ABI code is always position-independent. 2772 // The actual BlockAddress is stored in the TOC. 2773 if (Subtarget.isSVR4ABI() && 2774 (Subtarget.isPPC64() || isPositionIndependent())) { 2775 if (Subtarget.isPPC64()) 2776 setUsesTOCBasePtr(DAG); 2777 SDValue GA = DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset()); 2778 return getTOCEntry(DAG, SDLoc(BASDN), Subtarget.isPPC64(), GA); 2779 } 2780 2781 unsigned MOHiFlag, MOLoFlag; 2782 bool IsPIC = isPositionIndependent(); 2783 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag); 2784 SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag); 2785 SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag); 2786 return LowerLabelRef(TgtBAHi, TgtBALo, IsPIC, DAG); 2787 } 2788 2789 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op, 2790 SelectionDAG &DAG) const { 2791 // FIXME: TLS addresses currently use medium model code sequences, 2792 // which is the most useful form. Eventually support for small and 2793 // large models could be added if users need it, at the cost of 2794 // additional complexity. 2795 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op); 2796 if (DAG.getTarget().useEmulatedTLS()) 2797 return LowerToTLSEmulatedModel(GA, DAG); 2798 2799 SDLoc dl(GA); 2800 const GlobalValue *GV = GA->getGlobal(); 2801 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2802 bool is64bit = Subtarget.isPPC64(); 2803 const Module *M = DAG.getMachineFunction().getFunction().getParent(); 2804 PICLevel::Level picLevel = M->getPICLevel(); 2805 2806 const TargetMachine &TM = getTargetMachine(); 2807 TLSModel::Model Model = TM.getTLSModel(GV); 2808 2809 if (Model == TLSModel::LocalExec) { 2810 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 2811 PPCII::MO_TPREL_HA); 2812 SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 2813 PPCII::MO_TPREL_LO); 2814 SDValue TLSReg = is64bit ? DAG.getRegister(PPC::X13, MVT::i64) 2815 : DAG.getRegister(PPC::R2, MVT::i32); 2816 2817 SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg); 2818 return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi); 2819 } 2820 2821 if (Model == TLSModel::InitialExec) { 2822 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0); 2823 SDValue TGATLS = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 2824 PPCII::MO_TLS); 2825 SDValue GOTPtr; 2826 if (is64bit) { 2827 setUsesTOCBasePtr(DAG); 2828 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64); 2829 GOTPtr = DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl, 2830 PtrVT, GOTReg, TGA); 2831 } else { 2832 if (!TM.isPositionIndependent()) 2833 GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT); 2834 else if (picLevel == PICLevel::SmallPIC) 2835 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT); 2836 else 2837 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT); 2838 } 2839 SDValue TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl, 2840 PtrVT, TGA, GOTPtr); 2841 return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS); 2842 } 2843 2844 if (Model == TLSModel::GeneralDynamic) { 2845 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0); 2846 SDValue GOTPtr; 2847 if (is64bit) { 2848 setUsesTOCBasePtr(DAG); 2849 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64); 2850 GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT, 2851 GOTReg, TGA); 2852 } else { 2853 if (picLevel == PICLevel::SmallPIC) 2854 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT); 2855 else 2856 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT); 2857 } 2858 return DAG.getNode(PPCISD::ADDI_TLSGD_L_ADDR, dl, PtrVT, 2859 GOTPtr, TGA, TGA); 2860 } 2861 2862 if (Model == TLSModel::LocalDynamic) { 2863 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0); 2864 SDValue GOTPtr; 2865 if (is64bit) { 2866 setUsesTOCBasePtr(DAG); 2867 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64); 2868 GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT, 2869 GOTReg, TGA); 2870 } else { 2871 if (picLevel == PICLevel::SmallPIC) 2872 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT); 2873 else 2874 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT); 2875 } 2876 SDValue TLSAddr = DAG.getNode(PPCISD::ADDI_TLSLD_L_ADDR, dl, 2877 PtrVT, GOTPtr, TGA, TGA); 2878 SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl, 2879 PtrVT, TLSAddr, TGA); 2880 return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA); 2881 } 2882 2883 llvm_unreachable("Unknown TLS model!"); 2884 } 2885 2886 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op, 2887 SelectionDAG &DAG) const { 2888 EVT PtrVT = Op.getValueType(); 2889 GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op); 2890 SDLoc DL(GSDN); 2891 const GlobalValue *GV = GSDN->getGlobal(); 2892 2893 // 64-bit SVR4 ABI code is always position-independent. 2894 // The actual address of the GlobalValue is stored in the TOC. 2895 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) { 2896 setUsesTOCBasePtr(DAG); 2897 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset()); 2898 return getTOCEntry(DAG, DL, true, GA); 2899 } 2900 2901 unsigned MOHiFlag, MOLoFlag; 2902 bool IsPIC = isPositionIndependent(); 2903 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag, GV); 2904 2905 if (IsPIC && Subtarget.isSVR4ABI()) { 2906 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 2907 GSDN->getOffset(), 2908 PPCII::MO_PIC_FLAG); 2909 return getTOCEntry(DAG, DL, false, GA); 2910 } 2911 2912 SDValue GAHi = 2913 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag); 2914 SDValue GALo = 2915 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag); 2916 2917 SDValue Ptr = LowerLabelRef(GAHi, GALo, IsPIC, DAG); 2918 2919 // If the global reference is actually to a non-lazy-pointer, we have to do an 2920 // extra load to get the address of the global. 2921 if (MOHiFlag & PPCII::MO_NLP_FLAG) 2922 Ptr = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo()); 2923 return Ptr; 2924 } 2925 2926 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const { 2927 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get(); 2928 SDLoc dl(Op); 2929 2930 if (Op.getValueType() == MVT::v2i64) { 2931 // When the operands themselves are v2i64 values, we need to do something 2932 // special because VSX has no underlying comparison operations for these. 2933 if (Op.getOperand(0).getValueType() == MVT::v2i64) { 2934 // Equality can be handled by casting to the legal type for Altivec 2935 // comparisons, everything else needs to be expanded. 2936 if (CC == ISD::SETEQ || CC == ISD::SETNE) { 2937 return DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, 2938 DAG.getSetCC(dl, MVT::v4i32, 2939 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0)), 2940 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(1)), 2941 CC)); 2942 } 2943 2944 return SDValue(); 2945 } 2946 2947 // We handle most of these in the usual way. 2948 return Op; 2949 } 2950 2951 // If we're comparing for equality to zero, expose the fact that this is 2952 // implemented as a ctlz/srl pair on ppc, so that the dag combiner can 2953 // fold the new nodes. 2954 if (SDValue V = lowerCmpEqZeroToCtlzSrl(Op, DAG)) 2955 return V; 2956 2957 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 2958 // Leave comparisons against 0 and -1 alone for now, since they're usually 2959 // optimized. FIXME: revisit this when we can custom lower all setcc 2960 // optimizations. 2961 if (C->isAllOnesValue() || C->isNullValue()) 2962 return SDValue(); 2963 } 2964 2965 // If we have an integer seteq/setne, turn it into a compare against zero 2966 // by xor'ing the rhs with the lhs, which is faster than setting a 2967 // condition register, reading it back out, and masking the correct bit. The 2968 // normal approach here uses sub to do this instead of xor. Using xor exposes 2969 // the result to other bit-twiddling opportunities. 2970 EVT LHSVT = Op.getOperand(0).getValueType(); 2971 if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) { 2972 EVT VT = Op.getValueType(); 2973 SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0), 2974 Op.getOperand(1)); 2975 return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, dl, LHSVT), CC); 2976 } 2977 return SDValue(); 2978 } 2979 2980 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const { 2981 SDNode *Node = Op.getNode(); 2982 EVT VT = Node->getValueType(0); 2983 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2984 SDValue InChain = Node->getOperand(0); 2985 SDValue VAListPtr = Node->getOperand(1); 2986 const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue(); 2987 SDLoc dl(Node); 2988 2989 assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only"); 2990 2991 // gpr_index 2992 SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain, 2993 VAListPtr, MachinePointerInfo(SV), MVT::i8); 2994 InChain = GprIndex.getValue(1); 2995 2996 if (VT == MVT::i64) { 2997 // Check if GprIndex is even 2998 SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex, 2999 DAG.getConstant(1, dl, MVT::i32)); 3000 SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd, 3001 DAG.getConstant(0, dl, MVT::i32), ISD::SETNE); 3002 SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex, 3003 DAG.getConstant(1, dl, MVT::i32)); 3004 // Align GprIndex to be even if it isn't 3005 GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne, 3006 GprIndex); 3007 } 3008 3009 // fpr index is 1 byte after gpr 3010 SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, 3011 DAG.getConstant(1, dl, MVT::i32)); 3012 3013 // fpr 3014 SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain, 3015 FprPtr, MachinePointerInfo(SV), MVT::i8); 3016 InChain = FprIndex.getValue(1); 3017 3018 SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, 3019 DAG.getConstant(8, dl, MVT::i32)); 3020 3021 SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, 3022 DAG.getConstant(4, dl, MVT::i32)); 3023 3024 // areas 3025 SDValue OverflowArea = 3026 DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr, MachinePointerInfo()); 3027 InChain = OverflowArea.getValue(1); 3028 3029 SDValue RegSaveArea = 3030 DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr, MachinePointerInfo()); 3031 InChain = RegSaveArea.getValue(1); 3032 3033 // select overflow_area if index > 8 3034 SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex, 3035 DAG.getConstant(8, dl, MVT::i32), ISD::SETLT); 3036 3037 // adjustment constant gpr_index * 4/8 3038 SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32, 3039 VT.isInteger() ? GprIndex : FprIndex, 3040 DAG.getConstant(VT.isInteger() ? 4 : 8, dl, 3041 MVT::i32)); 3042 3043 // OurReg = RegSaveArea + RegConstant 3044 SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea, 3045 RegConstant); 3046 3047 // Floating types are 32 bytes into RegSaveArea 3048 if (VT.isFloatingPoint()) 3049 OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg, 3050 DAG.getConstant(32, dl, MVT::i32)); 3051 3052 // increase {f,g}pr_index by 1 (or 2 if VT is i64) 3053 SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32, 3054 VT.isInteger() ? GprIndex : FprIndex, 3055 DAG.getConstant(VT == MVT::i64 ? 2 : 1, dl, 3056 MVT::i32)); 3057 3058 InChain = DAG.getTruncStore(InChain, dl, IndexPlus1, 3059 VT.isInteger() ? VAListPtr : FprPtr, 3060 MachinePointerInfo(SV), MVT::i8); 3061 3062 // determine if we should load from reg_save_area or overflow_area 3063 SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea); 3064 3065 // increase overflow_area by 4/8 if gpr/fpr > 8 3066 SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea, 3067 DAG.getConstant(VT.isInteger() ? 4 : 8, 3068 dl, MVT::i32)); 3069 3070 OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea, 3071 OverflowAreaPlusN); 3072 3073 InChain = DAG.getTruncStore(InChain, dl, OverflowArea, OverflowAreaPtr, 3074 MachinePointerInfo(), MVT::i32); 3075 3076 return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo()); 3077 } 3078 3079 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const { 3080 assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only"); 3081 3082 // We have to copy the entire va_list struct: 3083 // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte 3084 return DAG.getMemcpy(Op.getOperand(0), Op, 3085 Op.getOperand(1), Op.getOperand(2), 3086 DAG.getConstant(12, SDLoc(Op), MVT::i32), 8, false, true, 3087 false, MachinePointerInfo(), MachinePointerInfo()); 3088 } 3089 3090 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op, 3091 SelectionDAG &DAG) const { 3092 return Op.getOperand(0); 3093 } 3094 3095 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op, 3096 SelectionDAG &DAG) const { 3097 SDValue Chain = Op.getOperand(0); 3098 SDValue Trmp = Op.getOperand(1); // trampoline 3099 SDValue FPtr = Op.getOperand(2); // nested function 3100 SDValue Nest = Op.getOperand(3); // 'nest' parameter value 3101 SDLoc dl(Op); 3102 3103 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3104 bool isPPC64 = (PtrVT == MVT::i64); 3105 Type *IntPtrTy = DAG.getDataLayout().getIntPtrType(*DAG.getContext()); 3106 3107 TargetLowering::ArgListTy Args; 3108 TargetLowering::ArgListEntry Entry; 3109 3110 Entry.Ty = IntPtrTy; 3111 Entry.Node = Trmp; Args.push_back(Entry); 3112 3113 // TrampSize == (isPPC64 ? 48 : 40); 3114 Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40, dl, 3115 isPPC64 ? MVT::i64 : MVT::i32); 3116 Args.push_back(Entry); 3117 3118 Entry.Node = FPtr; Args.push_back(Entry); 3119 Entry.Node = Nest; Args.push_back(Entry); 3120 3121 // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg) 3122 TargetLowering::CallLoweringInfo CLI(DAG); 3123 CLI.setDebugLoc(dl).setChain(Chain).setLibCallee( 3124 CallingConv::C, Type::getVoidTy(*DAG.getContext()), 3125 DAG.getExternalSymbol("__trampoline_setup", PtrVT), std::move(Args)); 3126 3127 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 3128 return CallResult.second; 3129 } 3130 3131 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const { 3132 MachineFunction &MF = DAG.getMachineFunction(); 3133 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 3134 EVT PtrVT = getPointerTy(MF.getDataLayout()); 3135 3136 SDLoc dl(Op); 3137 3138 if (Subtarget.isDarwinABI() || Subtarget.isPPC64()) { 3139 // vastart just stores the address of the VarArgsFrameIndex slot into the 3140 // memory location argument. 3141 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 3142 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 3143 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1), 3144 MachinePointerInfo(SV)); 3145 } 3146 3147 // For the 32-bit SVR4 ABI we follow the layout of the va_list struct. 3148 // We suppose the given va_list is already allocated. 3149 // 3150 // typedef struct { 3151 // char gpr; /* index into the array of 8 GPRs 3152 // * stored in the register save area 3153 // * gpr=0 corresponds to r3, 3154 // * gpr=1 to r4, etc. 3155 // */ 3156 // char fpr; /* index into the array of 8 FPRs 3157 // * stored in the register save area 3158 // * fpr=0 corresponds to f1, 3159 // * fpr=1 to f2, etc. 3160 // */ 3161 // char *overflow_arg_area; 3162 // /* location on stack that holds 3163 // * the next overflow argument 3164 // */ 3165 // char *reg_save_area; 3166 // /* where r3:r10 and f1:f8 (if saved) 3167 // * are stored 3168 // */ 3169 // } va_list[1]; 3170 3171 SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), dl, MVT::i32); 3172 SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), dl, MVT::i32); 3173 SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(), 3174 PtrVT); 3175 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), 3176 PtrVT); 3177 3178 uint64_t FrameOffset = PtrVT.getSizeInBits()/8; 3179 SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, dl, PtrVT); 3180 3181 uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1; 3182 SDValue ConstStackOffset = DAG.getConstant(StackOffset, dl, PtrVT); 3183 3184 uint64_t FPROffset = 1; 3185 SDValue ConstFPROffset = DAG.getConstant(FPROffset, dl, PtrVT); 3186 3187 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 3188 3189 // Store first byte : number of int regs 3190 SDValue firstStore = 3191 DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR, Op.getOperand(1), 3192 MachinePointerInfo(SV), MVT::i8); 3193 uint64_t nextOffset = FPROffset; 3194 SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1), 3195 ConstFPROffset); 3196 3197 // Store second byte : number of float regs 3198 SDValue secondStore = 3199 DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr, 3200 MachinePointerInfo(SV, nextOffset), MVT::i8); 3201 nextOffset += StackOffset; 3202 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset); 3203 3204 // Store second word : arguments given on stack 3205 SDValue thirdStore = DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr, 3206 MachinePointerInfo(SV, nextOffset)); 3207 nextOffset += FrameOffset; 3208 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset); 3209 3210 // Store third word : arguments given in registers 3211 return DAG.getStore(thirdStore, dl, FR, nextPtr, 3212 MachinePointerInfo(SV, nextOffset)); 3213 } 3214 3215 /// FPR - The set of FP registers that should be allocated for arguments, 3216 /// on Darwin. 3217 static const MCPhysReg FPR[] = {PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, 3218 PPC::F6, PPC::F7, PPC::F8, PPC::F9, PPC::F10, 3219 PPC::F11, PPC::F12, PPC::F13}; 3220 3221 /// QFPR - The set of QPX registers that should be allocated for arguments. 3222 static const MCPhysReg QFPR[] = { 3223 PPC::QF1, PPC::QF2, PPC::QF3, PPC::QF4, PPC::QF5, PPC::QF6, PPC::QF7, 3224 PPC::QF8, PPC::QF9, PPC::QF10, PPC::QF11, PPC::QF12, PPC::QF13}; 3225 3226 /// CalculateStackSlotSize - Calculates the size reserved for this argument on 3227 /// the stack. 3228 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags, 3229 unsigned PtrByteSize) { 3230 unsigned ArgSize = ArgVT.getStoreSize(); 3231 if (Flags.isByVal()) 3232 ArgSize = Flags.getByValSize(); 3233 3234 // Round up to multiples of the pointer size, except for array members, 3235 // which are always packed. 3236 if (!Flags.isInConsecutiveRegs()) 3237 ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3238 3239 return ArgSize; 3240 } 3241 3242 /// CalculateStackSlotAlignment - Calculates the alignment of this argument 3243 /// on the stack. 3244 static unsigned CalculateStackSlotAlignment(EVT ArgVT, EVT OrigVT, 3245 ISD::ArgFlagsTy Flags, 3246 unsigned PtrByteSize) { 3247 unsigned Align = PtrByteSize; 3248 3249 // Altivec parameters are padded to a 16 byte boundary. 3250 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 || 3251 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 || 3252 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 || 3253 ArgVT == MVT::v1i128 || ArgVT == MVT::f128) 3254 Align = 16; 3255 // QPX vector types stored in double-precision are padded to a 32 byte 3256 // boundary. 3257 else if (ArgVT == MVT::v4f64 || ArgVT == MVT::v4i1) 3258 Align = 32; 3259 3260 // ByVal parameters are aligned as requested. 3261 if (Flags.isByVal()) { 3262 unsigned BVAlign = Flags.getByValAlign(); 3263 if (BVAlign > PtrByteSize) { 3264 if (BVAlign % PtrByteSize != 0) 3265 llvm_unreachable( 3266 "ByVal alignment is not a multiple of the pointer size"); 3267 3268 Align = BVAlign; 3269 } 3270 } 3271 3272 // Array members are always packed to their original alignment. 3273 if (Flags.isInConsecutiveRegs()) { 3274 // If the array member was split into multiple registers, the first 3275 // needs to be aligned to the size of the full type. (Except for 3276 // ppcf128, which is only aligned as its f64 components.) 3277 if (Flags.isSplit() && OrigVT != MVT::ppcf128) 3278 Align = OrigVT.getStoreSize(); 3279 else 3280 Align = ArgVT.getStoreSize(); 3281 } 3282 3283 return Align; 3284 } 3285 3286 /// CalculateStackSlotUsed - Return whether this argument will use its 3287 /// stack slot (instead of being passed in registers). ArgOffset, 3288 /// AvailableFPRs, and AvailableVRs must hold the current argument 3289 /// position, and will be updated to account for this argument. 3290 static bool CalculateStackSlotUsed(EVT ArgVT, EVT OrigVT, 3291 ISD::ArgFlagsTy Flags, 3292 unsigned PtrByteSize, 3293 unsigned LinkageSize, 3294 unsigned ParamAreaSize, 3295 unsigned &ArgOffset, 3296 unsigned &AvailableFPRs, 3297 unsigned &AvailableVRs, bool HasQPX) { 3298 bool UseMemory = false; 3299 3300 // Respect alignment of argument on the stack. 3301 unsigned Align = 3302 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize); 3303 ArgOffset = ((ArgOffset + Align - 1) / Align) * Align; 3304 // If there's no space left in the argument save area, we must 3305 // use memory (this check also catches zero-sized arguments). 3306 if (ArgOffset >= LinkageSize + ParamAreaSize) 3307 UseMemory = true; 3308 3309 // Allocate argument on the stack. 3310 ArgOffset += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize); 3311 if (Flags.isInConsecutiveRegsLast()) 3312 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3313 // If we overran the argument save area, we must use memory 3314 // (this check catches arguments passed partially in memory) 3315 if (ArgOffset > LinkageSize + ParamAreaSize) 3316 UseMemory = true; 3317 3318 // However, if the argument is actually passed in an FPR or a VR, 3319 // we don't use memory after all. 3320 if (!Flags.isByVal()) { 3321 if (ArgVT == MVT::f32 || ArgVT == MVT::f64 || 3322 // QPX registers overlap with the scalar FP registers. 3323 (HasQPX && (ArgVT == MVT::v4f32 || 3324 ArgVT == MVT::v4f64 || 3325 ArgVT == MVT::v4i1))) 3326 if (AvailableFPRs > 0) { 3327 --AvailableFPRs; 3328 return false; 3329 } 3330 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 || 3331 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 || 3332 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 || 3333 ArgVT == MVT::v1i128 || ArgVT == MVT::f128) 3334 if (AvailableVRs > 0) { 3335 --AvailableVRs; 3336 return false; 3337 } 3338 } 3339 3340 return UseMemory; 3341 } 3342 3343 /// EnsureStackAlignment - Round stack frame size up from NumBytes to 3344 /// ensure minimum alignment required for target. 3345 static unsigned EnsureStackAlignment(const PPCFrameLowering *Lowering, 3346 unsigned NumBytes) { 3347 unsigned TargetAlign = Lowering->getStackAlignment(); 3348 unsigned AlignMask = TargetAlign - 1; 3349 NumBytes = (NumBytes + AlignMask) & ~AlignMask; 3350 return NumBytes; 3351 } 3352 3353 SDValue PPCTargetLowering::LowerFormalArguments( 3354 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3355 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3356 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3357 if (Subtarget.isSVR4ABI()) { 3358 if (Subtarget.isPPC64()) 3359 return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins, 3360 dl, DAG, InVals); 3361 else 3362 return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins, 3363 dl, DAG, InVals); 3364 } else { 3365 return LowerFormalArguments_Darwin(Chain, CallConv, isVarArg, Ins, 3366 dl, DAG, InVals); 3367 } 3368 } 3369 3370 SDValue PPCTargetLowering::LowerFormalArguments_32SVR4( 3371 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3372 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3373 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3374 3375 // 32-bit SVR4 ABI Stack Frame Layout: 3376 // +-----------------------------------+ 3377 // +--> | Back chain | 3378 // | +-----------------------------------+ 3379 // | | Floating-point register save area | 3380 // | +-----------------------------------+ 3381 // | | General register save area | 3382 // | +-----------------------------------+ 3383 // | | CR save word | 3384 // | +-----------------------------------+ 3385 // | | VRSAVE save word | 3386 // | +-----------------------------------+ 3387 // | | Alignment padding | 3388 // | +-----------------------------------+ 3389 // | | Vector register save area | 3390 // | +-----------------------------------+ 3391 // | | Local variable space | 3392 // | +-----------------------------------+ 3393 // | | Parameter list area | 3394 // | +-----------------------------------+ 3395 // | | LR save word | 3396 // | +-----------------------------------+ 3397 // SP--> +--- | Back chain | 3398 // +-----------------------------------+ 3399 // 3400 // Specifications: 3401 // System V Application Binary Interface PowerPC Processor Supplement 3402 // AltiVec Technology Programming Interface Manual 3403 3404 MachineFunction &MF = DAG.getMachineFunction(); 3405 MachineFrameInfo &MFI = MF.getFrameInfo(); 3406 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 3407 3408 EVT PtrVT = getPointerTy(MF.getDataLayout()); 3409 // Potential tail calls could cause overwriting of argument stack slots. 3410 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt && 3411 (CallConv == CallingConv::Fast)); 3412 unsigned PtrByteSize = 4; 3413 3414 // Assign locations to all of the incoming arguments. 3415 SmallVector<CCValAssign, 16> ArgLocs; 3416 PPCCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 3417 *DAG.getContext()); 3418 3419 // Reserve space for the linkage area on the stack. 3420 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 3421 CCInfo.AllocateStack(LinkageSize, PtrByteSize); 3422 if (useSoftFloat()) 3423 CCInfo.PreAnalyzeFormalArguments(Ins); 3424 3425 CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4); 3426 CCInfo.clearWasPPCF128(); 3427 3428 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 3429 CCValAssign &VA = ArgLocs[i]; 3430 3431 // Arguments stored in registers. 3432 if (VA.isRegLoc()) { 3433 const TargetRegisterClass *RC; 3434 EVT ValVT = VA.getValVT(); 3435 3436 switch (ValVT.getSimpleVT().SimpleTy) { 3437 default: 3438 llvm_unreachable("ValVT not supported by formal arguments Lowering"); 3439 case MVT::i1: 3440 case MVT::i32: 3441 RC = &PPC::GPRCRegClass; 3442 break; 3443 case MVT::f32: 3444 if (Subtarget.hasP8Vector()) 3445 RC = &PPC::VSSRCRegClass; 3446 else if (Subtarget.hasSPE()) 3447 RC = &PPC::SPE4RCRegClass; 3448 else 3449 RC = &PPC::F4RCRegClass; 3450 break; 3451 case MVT::f64: 3452 if (Subtarget.hasVSX()) 3453 RC = &PPC::VSFRCRegClass; 3454 else if (Subtarget.hasSPE()) 3455 // SPE passes doubles in GPR pairs. 3456 RC = &PPC::GPRCRegClass; 3457 else 3458 RC = &PPC::F8RCRegClass; 3459 break; 3460 case MVT::v16i8: 3461 case MVT::v8i16: 3462 case MVT::v4i32: 3463 RC = &PPC::VRRCRegClass; 3464 break; 3465 case MVT::v4f32: 3466 RC = Subtarget.hasQPX() ? &PPC::QSRCRegClass : &PPC::VRRCRegClass; 3467 break; 3468 case MVT::v2f64: 3469 case MVT::v2i64: 3470 RC = &PPC::VRRCRegClass; 3471 break; 3472 case MVT::v4f64: 3473 RC = &PPC::QFRCRegClass; 3474 break; 3475 case MVT::v4i1: 3476 RC = &PPC::QBRCRegClass; 3477 break; 3478 } 3479 3480 SDValue ArgValue; 3481 // Transform the arguments stored in physical registers into 3482 // virtual ones. 3483 if (VA.getLocVT() == MVT::f64 && Subtarget.hasSPE()) { 3484 assert(i + 1 < e && "No second half of double precision argument"); 3485 unsigned RegLo = MF.addLiveIn(VA.getLocReg(), RC); 3486 unsigned RegHi = MF.addLiveIn(ArgLocs[++i].getLocReg(), RC); 3487 SDValue ArgValueLo = DAG.getCopyFromReg(Chain, dl, RegLo, MVT::i32); 3488 SDValue ArgValueHi = DAG.getCopyFromReg(Chain, dl, RegHi, MVT::i32); 3489 if (!Subtarget.isLittleEndian()) 3490 std::swap (ArgValueLo, ArgValueHi); 3491 ArgValue = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, ArgValueLo, 3492 ArgValueHi); 3493 } else { 3494 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC); 3495 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, 3496 ValVT == MVT::i1 ? MVT::i32 : ValVT); 3497 if (ValVT == MVT::i1) 3498 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue); 3499 } 3500 3501 InVals.push_back(ArgValue); 3502 } else { 3503 // Argument stored in memory. 3504 assert(VA.isMemLoc()); 3505 3506 // Get the extended size of the argument type in stack 3507 unsigned ArgSize = VA.getLocVT().getStoreSize(); 3508 // Get the actual size of the argument type 3509 unsigned ObjSize = VA.getValVT().getStoreSize(); 3510 unsigned ArgOffset = VA.getLocMemOffset(); 3511 // Stack objects in PPC32 are right justified. 3512 ArgOffset += ArgSize - ObjSize; 3513 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, isImmutable); 3514 3515 // Create load nodes to retrieve arguments from the stack. 3516 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3517 InVals.push_back( 3518 DAG.getLoad(VA.getValVT(), dl, Chain, FIN, MachinePointerInfo())); 3519 } 3520 } 3521 3522 // Assign locations to all of the incoming aggregate by value arguments. 3523 // Aggregates passed by value are stored in the local variable space of the 3524 // caller's stack frame, right above the parameter list area. 3525 SmallVector<CCValAssign, 16> ByValArgLocs; 3526 CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(), 3527 ByValArgLocs, *DAG.getContext()); 3528 3529 // Reserve stack space for the allocations in CCInfo. 3530 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize); 3531 3532 CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal); 3533 3534 // Area that is at least reserved in the caller of this function. 3535 unsigned MinReservedArea = CCByValInfo.getNextStackOffset(); 3536 MinReservedArea = std::max(MinReservedArea, LinkageSize); 3537 3538 // Set the size that is at least reserved in caller of this function. Tail 3539 // call optimized function's reserved stack space needs to be aligned so that 3540 // taking the difference between two stack areas will result in an aligned 3541 // stack. 3542 MinReservedArea = 3543 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea); 3544 FuncInfo->setMinReservedArea(MinReservedArea); 3545 3546 SmallVector<SDValue, 8> MemOps; 3547 3548 // If the function takes variable number of arguments, make a frame index for 3549 // the start of the first vararg value... for expansion of llvm.va_start. 3550 if (isVarArg) { 3551 static const MCPhysReg GPArgRegs[] = { 3552 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 3553 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 3554 }; 3555 const unsigned NumGPArgRegs = array_lengthof(GPArgRegs); 3556 3557 static const MCPhysReg FPArgRegs[] = { 3558 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7, 3559 PPC::F8 3560 }; 3561 unsigned NumFPArgRegs = array_lengthof(FPArgRegs); 3562 3563 if (useSoftFloat() || hasSPE()) 3564 NumFPArgRegs = 0; 3565 3566 FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs)); 3567 FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs)); 3568 3569 // Make room for NumGPArgRegs and NumFPArgRegs. 3570 int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 + 3571 NumFPArgRegs * MVT(MVT::f64).getSizeInBits()/8; 3572 3573 FuncInfo->setVarArgsStackOffset( 3574 MFI.CreateFixedObject(PtrVT.getSizeInBits()/8, 3575 CCInfo.getNextStackOffset(), true)); 3576 3577 FuncInfo->setVarArgsFrameIndex(MFI.CreateStackObject(Depth, 8, false)); 3578 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 3579 3580 // The fixed integer arguments of a variadic function are stored to the 3581 // VarArgsFrameIndex on the stack so that they may be loaded by 3582 // dereferencing the result of va_next. 3583 for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) { 3584 // Get an existing live-in vreg, or add a new one. 3585 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]); 3586 if (!VReg) 3587 VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass); 3588 3589 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 3590 SDValue Store = 3591 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 3592 MemOps.push_back(Store); 3593 // Increment the address by four for the next argument to store 3594 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT); 3595 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 3596 } 3597 3598 // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6 3599 // is set. 3600 // The double arguments are stored to the VarArgsFrameIndex 3601 // on the stack. 3602 for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) { 3603 // Get an existing live-in vreg, or add a new one. 3604 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]); 3605 if (!VReg) 3606 VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass); 3607 3608 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64); 3609 SDValue Store = 3610 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 3611 MemOps.push_back(Store); 3612 // Increment the address by eight for the next argument to store 3613 SDValue PtrOff = DAG.getConstant(MVT(MVT::f64).getSizeInBits()/8, dl, 3614 PtrVT); 3615 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 3616 } 3617 } 3618 3619 if (!MemOps.empty()) 3620 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 3621 3622 return Chain; 3623 } 3624 3625 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote 3626 // value to MVT::i64 and then truncate to the correct register size. 3627 SDValue PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags, 3628 EVT ObjectVT, SelectionDAG &DAG, 3629 SDValue ArgVal, 3630 const SDLoc &dl) const { 3631 if (Flags.isSExt()) 3632 ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal, 3633 DAG.getValueType(ObjectVT)); 3634 else if (Flags.isZExt()) 3635 ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal, 3636 DAG.getValueType(ObjectVT)); 3637 3638 return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal); 3639 } 3640 3641 SDValue PPCTargetLowering::LowerFormalArguments_64SVR4( 3642 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3643 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3644 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3645 // TODO: add description of PPC stack frame format, or at least some docs. 3646 // 3647 bool isELFv2ABI = Subtarget.isELFv2ABI(); 3648 bool isLittleEndian = Subtarget.isLittleEndian(); 3649 MachineFunction &MF = DAG.getMachineFunction(); 3650 MachineFrameInfo &MFI = MF.getFrameInfo(); 3651 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 3652 3653 assert(!(CallConv == CallingConv::Fast && isVarArg) && 3654 "fastcc not supported on varargs functions"); 3655 3656 EVT PtrVT = getPointerTy(MF.getDataLayout()); 3657 // Potential tail calls could cause overwriting of argument stack slots. 3658 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt && 3659 (CallConv == CallingConv::Fast)); 3660 unsigned PtrByteSize = 8; 3661 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 3662 3663 static const MCPhysReg GPR[] = { 3664 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 3665 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 3666 }; 3667 static const MCPhysReg VR[] = { 3668 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 3669 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 3670 }; 3671 3672 const unsigned Num_GPR_Regs = array_lengthof(GPR); 3673 const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13; 3674 const unsigned Num_VR_Regs = array_lengthof(VR); 3675 const unsigned Num_QFPR_Regs = Num_FPR_Regs; 3676 3677 // Do a first pass over the arguments to determine whether the ABI 3678 // guarantees that our caller has allocated the parameter save area 3679 // on its stack frame. In the ELFv1 ABI, this is always the case; 3680 // in the ELFv2 ABI, it is true if this is a vararg function or if 3681 // any parameter is located in a stack slot. 3682 3683 bool HasParameterArea = !isELFv2ABI || isVarArg; 3684 unsigned ParamAreaSize = Num_GPR_Regs * PtrByteSize; 3685 unsigned NumBytes = LinkageSize; 3686 unsigned AvailableFPRs = Num_FPR_Regs; 3687 unsigned AvailableVRs = Num_VR_Regs; 3688 for (unsigned i = 0, e = Ins.size(); i != e; ++i) { 3689 if (Ins[i].Flags.isNest()) 3690 continue; 3691 3692 if (CalculateStackSlotUsed(Ins[i].VT, Ins[i].ArgVT, Ins[i].Flags, 3693 PtrByteSize, LinkageSize, ParamAreaSize, 3694 NumBytes, AvailableFPRs, AvailableVRs, 3695 Subtarget.hasQPX())) 3696 HasParameterArea = true; 3697 } 3698 3699 // Add DAG nodes to load the arguments or copy them out of registers. On 3700 // entry to a function on PPC, the arguments start after the linkage area, 3701 // although the first ones are often in registers. 3702 3703 unsigned ArgOffset = LinkageSize; 3704 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 3705 unsigned &QFPR_idx = FPR_idx; 3706 SmallVector<SDValue, 8> MemOps; 3707 Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin(); 3708 unsigned CurArgIdx = 0; 3709 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) { 3710 SDValue ArgVal; 3711 bool needsLoad = false; 3712 EVT ObjectVT = Ins[ArgNo].VT; 3713 EVT OrigVT = Ins[ArgNo].ArgVT; 3714 unsigned ObjSize = ObjectVT.getStoreSize(); 3715 unsigned ArgSize = ObjSize; 3716 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags; 3717 if (Ins[ArgNo].isOrigArg()) { 3718 std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx); 3719 CurArgIdx = Ins[ArgNo].getOrigArgIndex(); 3720 } 3721 // We re-align the argument offset for each argument, except when using the 3722 // fast calling convention, when we need to make sure we do that only when 3723 // we'll actually use a stack slot. 3724 unsigned CurArgOffset, Align; 3725 auto ComputeArgOffset = [&]() { 3726 /* Respect alignment of argument on the stack. */ 3727 Align = CalculateStackSlotAlignment(ObjectVT, OrigVT, Flags, PtrByteSize); 3728 ArgOffset = ((ArgOffset + Align - 1) / Align) * Align; 3729 CurArgOffset = ArgOffset; 3730 }; 3731 3732 if (CallConv != CallingConv::Fast) { 3733 ComputeArgOffset(); 3734 3735 /* Compute GPR index associated with argument offset. */ 3736 GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize; 3737 GPR_idx = std::min(GPR_idx, Num_GPR_Regs); 3738 } 3739 3740 // FIXME the codegen can be much improved in some cases. 3741 // We do not have to keep everything in memory. 3742 if (Flags.isByVal()) { 3743 assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit"); 3744 3745 if (CallConv == CallingConv::Fast) 3746 ComputeArgOffset(); 3747 3748 // ObjSize is the true size, ArgSize rounded up to multiple of registers. 3749 ObjSize = Flags.getByValSize(); 3750 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3751 // Empty aggregate parameters do not take up registers. Examples: 3752 // struct { } a; 3753 // union { } b; 3754 // int c[0]; 3755 // etc. However, we have to provide a place-holder in InVals, so 3756 // pretend we have an 8-byte item at the current address for that 3757 // purpose. 3758 if (!ObjSize) { 3759 int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true); 3760 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3761 InVals.push_back(FIN); 3762 continue; 3763 } 3764 3765 // Create a stack object covering all stack doublewords occupied 3766 // by the argument. If the argument is (fully or partially) on 3767 // the stack, or if the argument is fully in registers but the 3768 // caller has allocated the parameter save anyway, we can refer 3769 // directly to the caller's stack frame. Otherwise, create a 3770 // local copy in our own frame. 3771 int FI; 3772 if (HasParameterArea || 3773 ArgSize + ArgOffset > LinkageSize + Num_GPR_Regs * PtrByteSize) 3774 FI = MFI.CreateFixedObject(ArgSize, ArgOffset, false, true); 3775 else 3776 FI = MFI.CreateStackObject(ArgSize, Align, false); 3777 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3778 3779 // Handle aggregates smaller than 8 bytes. 3780 if (ObjSize < PtrByteSize) { 3781 // The value of the object is its address, which differs from the 3782 // address of the enclosing doubleword on big-endian systems. 3783 SDValue Arg = FIN; 3784 if (!isLittleEndian) { 3785 SDValue ArgOff = DAG.getConstant(PtrByteSize - ObjSize, dl, PtrVT); 3786 Arg = DAG.getNode(ISD::ADD, dl, ArgOff.getValueType(), Arg, ArgOff); 3787 } 3788 InVals.push_back(Arg); 3789 3790 if (GPR_idx != Num_GPR_Regs) { 3791 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass); 3792 FuncInfo->addLiveInAttr(VReg, Flags); 3793 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 3794 SDValue Store; 3795 3796 if (ObjSize==1 || ObjSize==2 || ObjSize==4) { 3797 EVT ObjType = (ObjSize == 1 ? MVT::i8 : 3798 (ObjSize == 2 ? MVT::i16 : MVT::i32)); 3799 Store = DAG.getTruncStore(Val.getValue(1), dl, Val, Arg, 3800 MachinePointerInfo(&*FuncArg), ObjType); 3801 } else { 3802 // For sizes that don't fit a truncating store (3, 5, 6, 7), 3803 // store the whole register as-is to the parameter save area 3804 // slot. 3805 Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, 3806 MachinePointerInfo(&*FuncArg)); 3807 } 3808 3809 MemOps.push_back(Store); 3810 } 3811 // Whether we copied from a register or not, advance the offset 3812 // into the parameter save area by a full doubleword. 3813 ArgOffset += PtrByteSize; 3814 continue; 3815 } 3816 3817 // The value of the object is its address, which is the address of 3818 // its first stack doubleword. 3819 InVals.push_back(FIN); 3820 3821 // Store whatever pieces of the object are in registers to memory. 3822 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) { 3823 if (GPR_idx == Num_GPR_Regs) 3824 break; 3825 3826 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 3827 FuncInfo->addLiveInAttr(VReg, Flags); 3828 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 3829 SDValue Addr = FIN; 3830 if (j) { 3831 SDValue Off = DAG.getConstant(j, dl, PtrVT); 3832 Addr = DAG.getNode(ISD::ADD, dl, Off.getValueType(), Addr, Off); 3833 } 3834 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, Addr, 3835 MachinePointerInfo(&*FuncArg, j)); 3836 MemOps.push_back(Store); 3837 ++GPR_idx; 3838 } 3839 ArgOffset += ArgSize; 3840 continue; 3841 } 3842 3843 switch (ObjectVT.getSimpleVT().SimpleTy) { 3844 default: llvm_unreachable("Unhandled argument type!"); 3845 case MVT::i1: 3846 case MVT::i32: 3847 case MVT::i64: 3848 if (Flags.isNest()) { 3849 // The 'nest' parameter, if any, is passed in R11. 3850 unsigned VReg = MF.addLiveIn(PPC::X11, &PPC::G8RCRegClass); 3851 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 3852 3853 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1) 3854 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl); 3855 3856 break; 3857 } 3858 3859 // These can be scalar arguments or elements of an integer array type 3860 // passed directly. Clang may use those instead of "byval" aggregate 3861 // types to avoid forcing arguments to memory unnecessarily. 3862 if (GPR_idx != Num_GPR_Regs) { 3863 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass); 3864 FuncInfo->addLiveInAttr(VReg, Flags); 3865 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 3866 3867 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1) 3868 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote 3869 // value to MVT::i64 and then truncate to the correct register size. 3870 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl); 3871 } else { 3872 if (CallConv == CallingConv::Fast) 3873 ComputeArgOffset(); 3874 3875 needsLoad = true; 3876 ArgSize = PtrByteSize; 3877 } 3878 if (CallConv != CallingConv::Fast || needsLoad) 3879 ArgOffset += 8; 3880 break; 3881 3882 case MVT::f32: 3883 case MVT::f64: 3884 // These can be scalar arguments or elements of a float array type 3885 // passed directly. The latter are used to implement ELFv2 homogenous 3886 // float aggregates. 3887 if (FPR_idx != Num_FPR_Regs) { 3888 unsigned VReg; 3889 3890 if (ObjectVT == MVT::f32) 3891 VReg = MF.addLiveIn(FPR[FPR_idx], 3892 Subtarget.hasP8Vector() 3893 ? &PPC::VSSRCRegClass 3894 : &PPC::F4RCRegClass); 3895 else 3896 VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX() 3897 ? &PPC::VSFRCRegClass 3898 : &PPC::F8RCRegClass); 3899 3900 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 3901 ++FPR_idx; 3902 } else if (GPR_idx != Num_GPR_Regs && CallConv != CallingConv::Fast) { 3903 // FIXME: We may want to re-enable this for CallingConv::Fast on the P8 3904 // once we support fp <-> gpr moves. 3905 3906 // This can only ever happen in the presence of f32 array types, 3907 // since otherwise we never run out of FPRs before running out 3908 // of GPRs. 3909 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass); 3910 FuncInfo->addLiveInAttr(VReg, Flags); 3911 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 3912 3913 if (ObjectVT == MVT::f32) { 3914 if ((ArgOffset % PtrByteSize) == (isLittleEndian ? 4 : 0)) 3915 ArgVal = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgVal, 3916 DAG.getConstant(32, dl, MVT::i32)); 3917 ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal); 3918 } 3919 3920 ArgVal = DAG.getNode(ISD::BITCAST, dl, ObjectVT, ArgVal); 3921 } else { 3922 if (CallConv == CallingConv::Fast) 3923 ComputeArgOffset(); 3924 3925 needsLoad = true; 3926 } 3927 3928 // When passing an array of floats, the array occupies consecutive 3929 // space in the argument area; only round up to the next doubleword 3930 // at the end of the array. Otherwise, each float takes 8 bytes. 3931 if (CallConv != CallingConv::Fast || needsLoad) { 3932 ArgSize = Flags.isInConsecutiveRegs() ? ObjSize : PtrByteSize; 3933 ArgOffset += ArgSize; 3934 if (Flags.isInConsecutiveRegsLast()) 3935 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3936 } 3937 break; 3938 case MVT::v4f32: 3939 case MVT::v4i32: 3940 case MVT::v8i16: 3941 case MVT::v16i8: 3942 case MVT::v2f64: 3943 case MVT::v2i64: 3944 case MVT::v1i128: 3945 case MVT::f128: 3946 if (!Subtarget.hasQPX()) { 3947 // These can be scalar arguments or elements of a vector array type 3948 // passed directly. The latter are used to implement ELFv2 homogenous 3949 // vector aggregates. 3950 if (VR_idx != Num_VR_Regs) { 3951 unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass); 3952 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 3953 ++VR_idx; 3954 } else { 3955 if (CallConv == CallingConv::Fast) 3956 ComputeArgOffset(); 3957 needsLoad = true; 3958 } 3959 if (CallConv != CallingConv::Fast || needsLoad) 3960 ArgOffset += 16; 3961 break; 3962 } // not QPX 3963 3964 assert(ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 && 3965 "Invalid QPX parameter type"); 3966 LLVM_FALLTHROUGH; 3967 3968 case MVT::v4f64: 3969 case MVT::v4i1: 3970 // QPX vectors are treated like their scalar floating-point subregisters 3971 // (except that they're larger). 3972 unsigned Sz = ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 ? 16 : 32; 3973 if (QFPR_idx != Num_QFPR_Regs) { 3974 const TargetRegisterClass *RC; 3975 switch (ObjectVT.getSimpleVT().SimpleTy) { 3976 case MVT::v4f64: RC = &PPC::QFRCRegClass; break; 3977 case MVT::v4f32: RC = &PPC::QSRCRegClass; break; 3978 default: RC = &PPC::QBRCRegClass; break; 3979 } 3980 3981 unsigned VReg = MF.addLiveIn(QFPR[QFPR_idx], RC); 3982 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 3983 ++QFPR_idx; 3984 } else { 3985 if (CallConv == CallingConv::Fast) 3986 ComputeArgOffset(); 3987 needsLoad = true; 3988 } 3989 if (CallConv != CallingConv::Fast || needsLoad) 3990 ArgOffset += Sz; 3991 break; 3992 } 3993 3994 // We need to load the argument to a virtual register if we determined 3995 // above that we ran out of physical registers of the appropriate type. 3996 if (needsLoad) { 3997 if (ObjSize < ArgSize && !isLittleEndian) 3998 CurArgOffset += ArgSize - ObjSize; 3999 int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, isImmutable); 4000 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4001 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo()); 4002 } 4003 4004 InVals.push_back(ArgVal); 4005 } 4006 4007 // Area that is at least reserved in the caller of this function. 4008 unsigned MinReservedArea; 4009 if (HasParameterArea) 4010 MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize); 4011 else 4012 MinReservedArea = LinkageSize; 4013 4014 // Set the size that is at least reserved in caller of this function. Tail 4015 // call optimized functions' reserved stack space needs to be aligned so that 4016 // taking the difference between two stack areas will result in an aligned 4017 // stack. 4018 MinReservedArea = 4019 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea); 4020 FuncInfo->setMinReservedArea(MinReservedArea); 4021 4022 // If the function takes variable number of arguments, make a frame index for 4023 // the start of the first vararg value... for expansion of llvm.va_start. 4024 if (isVarArg) { 4025 int Depth = ArgOffset; 4026 4027 FuncInfo->setVarArgsFrameIndex( 4028 MFI.CreateFixedObject(PtrByteSize, Depth, true)); 4029 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 4030 4031 // If this function is vararg, store any remaining integer argument regs 4032 // to their spots on the stack so that they may be loaded by dereferencing 4033 // the result of va_next. 4034 for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize; 4035 GPR_idx < Num_GPR_Regs; ++GPR_idx) { 4036 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4037 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4038 SDValue Store = 4039 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 4040 MemOps.push_back(Store); 4041 // Increment the address by four for the next argument to store 4042 SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT); 4043 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 4044 } 4045 } 4046 4047 if (!MemOps.empty()) 4048 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 4049 4050 return Chain; 4051 } 4052 4053 SDValue PPCTargetLowering::LowerFormalArguments_Darwin( 4054 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 4055 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 4056 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 4057 // TODO: add description of PPC stack frame format, or at least some docs. 4058 // 4059 MachineFunction &MF = DAG.getMachineFunction(); 4060 MachineFrameInfo &MFI = MF.getFrameInfo(); 4061 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 4062 4063 EVT PtrVT = getPointerTy(MF.getDataLayout()); 4064 bool isPPC64 = PtrVT == MVT::i64; 4065 // Potential tail calls could cause overwriting of argument stack slots. 4066 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt && 4067 (CallConv == CallingConv::Fast)); 4068 unsigned PtrByteSize = isPPC64 ? 8 : 4; 4069 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 4070 unsigned ArgOffset = LinkageSize; 4071 // Area that is at least reserved in caller of this function. 4072 unsigned MinReservedArea = ArgOffset; 4073 4074 static const MCPhysReg GPR_32[] = { // 32-bit registers. 4075 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 4076 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 4077 }; 4078 static const MCPhysReg GPR_64[] = { // 64-bit registers. 4079 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 4080 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 4081 }; 4082 static const MCPhysReg VR[] = { 4083 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 4084 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 4085 }; 4086 4087 const unsigned Num_GPR_Regs = array_lengthof(GPR_32); 4088 const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13; 4089 const unsigned Num_VR_Regs = array_lengthof( VR); 4090 4091 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 4092 4093 const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32; 4094 4095 // In 32-bit non-varargs functions, the stack space for vectors is after the 4096 // stack space for non-vectors. We do not use this space unless we have 4097 // too many vectors to fit in registers, something that only occurs in 4098 // constructed examples:), but we have to walk the arglist to figure 4099 // that out...for the pathological case, compute VecArgOffset as the 4100 // start of the vector parameter area. Computing VecArgOffset is the 4101 // entire point of the following loop. 4102 unsigned VecArgOffset = ArgOffset; 4103 if (!isVarArg && !isPPC64) { 4104 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; 4105 ++ArgNo) { 4106 EVT ObjectVT = Ins[ArgNo].VT; 4107 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags; 4108 4109 if (Flags.isByVal()) { 4110 // ObjSize is the true size, ArgSize rounded up to multiple of regs. 4111 unsigned ObjSize = Flags.getByValSize(); 4112 unsigned ArgSize = 4113 ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 4114 VecArgOffset += ArgSize; 4115 continue; 4116 } 4117 4118 switch(ObjectVT.getSimpleVT().SimpleTy) { 4119 default: llvm_unreachable("Unhandled argument type!"); 4120 case MVT::i1: 4121 case MVT::i32: 4122 case MVT::f32: 4123 VecArgOffset += 4; 4124 break; 4125 case MVT::i64: // PPC64 4126 case MVT::f64: 4127 // FIXME: We are guaranteed to be !isPPC64 at this point. 4128 // Does MVT::i64 apply? 4129 VecArgOffset += 8; 4130 break; 4131 case MVT::v4f32: 4132 case MVT::v4i32: 4133 case MVT::v8i16: 4134 case MVT::v16i8: 4135 // Nothing to do, we're only looking at Nonvector args here. 4136 break; 4137 } 4138 } 4139 } 4140 // We've found where the vector parameter area in memory is. Skip the 4141 // first 12 parameters; these don't use that memory. 4142 VecArgOffset = ((VecArgOffset+15)/16)*16; 4143 VecArgOffset += 12*16; 4144 4145 // Add DAG nodes to load the arguments or copy them out of registers. On 4146 // entry to a function on PPC, the arguments start after the linkage area, 4147 // although the first ones are often in registers. 4148 4149 SmallVector<SDValue, 8> MemOps; 4150 unsigned nAltivecParamsAtEnd = 0; 4151 Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin(); 4152 unsigned CurArgIdx = 0; 4153 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) { 4154 SDValue ArgVal; 4155 bool needsLoad = false; 4156 EVT ObjectVT = Ins[ArgNo].VT; 4157 unsigned ObjSize = ObjectVT.getSizeInBits()/8; 4158 unsigned ArgSize = ObjSize; 4159 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags; 4160 if (Ins[ArgNo].isOrigArg()) { 4161 std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx); 4162 CurArgIdx = Ins[ArgNo].getOrigArgIndex(); 4163 } 4164 unsigned CurArgOffset = ArgOffset; 4165 4166 // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary. 4167 if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 || 4168 ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) { 4169 if (isVarArg || isPPC64) { 4170 MinReservedArea = ((MinReservedArea+15)/16)*16; 4171 MinReservedArea += CalculateStackSlotSize(ObjectVT, 4172 Flags, 4173 PtrByteSize); 4174 } else nAltivecParamsAtEnd++; 4175 } else 4176 // Calculate min reserved area. 4177 MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT, 4178 Flags, 4179 PtrByteSize); 4180 4181 // FIXME the codegen can be much improved in some cases. 4182 // We do not have to keep everything in memory. 4183 if (Flags.isByVal()) { 4184 assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit"); 4185 4186 // ObjSize is the true size, ArgSize rounded up to multiple of registers. 4187 ObjSize = Flags.getByValSize(); 4188 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 4189 // Objects of size 1 and 2 are right justified, everything else is 4190 // left justified. This means the memory address is adjusted forwards. 4191 if (ObjSize==1 || ObjSize==2) { 4192 CurArgOffset = CurArgOffset + (4 - ObjSize); 4193 } 4194 // The value of the object is its address. 4195 int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, false, true); 4196 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4197 InVals.push_back(FIN); 4198 if (ObjSize==1 || ObjSize==2) { 4199 if (GPR_idx != Num_GPR_Regs) { 4200 unsigned VReg; 4201 if (isPPC64) 4202 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4203 else 4204 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 4205 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4206 EVT ObjType = ObjSize == 1 ? MVT::i8 : MVT::i16; 4207 SDValue Store = 4208 DAG.getTruncStore(Val.getValue(1), dl, Val, FIN, 4209 MachinePointerInfo(&*FuncArg), ObjType); 4210 MemOps.push_back(Store); 4211 ++GPR_idx; 4212 } 4213 4214 ArgOffset += PtrByteSize; 4215 4216 continue; 4217 } 4218 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) { 4219 // Store whatever pieces of the object are in registers 4220 // to memory. ArgOffset will be the address of the beginning 4221 // of the object. 4222 if (GPR_idx != Num_GPR_Regs) { 4223 unsigned VReg; 4224 if (isPPC64) 4225 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4226 else 4227 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 4228 int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true); 4229 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4230 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4231 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, 4232 MachinePointerInfo(&*FuncArg, j)); 4233 MemOps.push_back(Store); 4234 ++GPR_idx; 4235 ArgOffset += PtrByteSize; 4236 } else { 4237 ArgOffset += ArgSize - (ArgOffset-CurArgOffset); 4238 break; 4239 } 4240 } 4241 continue; 4242 } 4243 4244 switch (ObjectVT.getSimpleVT().SimpleTy) { 4245 default: llvm_unreachable("Unhandled argument type!"); 4246 case MVT::i1: 4247 case MVT::i32: 4248 if (!isPPC64) { 4249 if (GPR_idx != Num_GPR_Regs) { 4250 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 4251 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32); 4252 4253 if (ObjectVT == MVT::i1) 4254 ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgVal); 4255 4256 ++GPR_idx; 4257 } else { 4258 needsLoad = true; 4259 ArgSize = PtrByteSize; 4260 } 4261 // All int arguments reserve stack space in the Darwin ABI. 4262 ArgOffset += PtrByteSize; 4263 break; 4264 } 4265 LLVM_FALLTHROUGH; 4266 case MVT::i64: // PPC64 4267 if (GPR_idx != Num_GPR_Regs) { 4268 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4269 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 4270 4271 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1) 4272 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote 4273 // value to MVT::i64 and then truncate to the correct register size. 4274 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl); 4275 4276 ++GPR_idx; 4277 } else { 4278 needsLoad = true; 4279 ArgSize = PtrByteSize; 4280 } 4281 // All int arguments reserve stack space in the Darwin ABI. 4282 ArgOffset += 8; 4283 break; 4284 4285 case MVT::f32: 4286 case MVT::f64: 4287 // Every 4 bytes of argument space consumes one of the GPRs available for 4288 // argument passing. 4289 if (GPR_idx != Num_GPR_Regs) { 4290 ++GPR_idx; 4291 if (ObjSize == 8 && GPR_idx != Num_GPR_Regs && !isPPC64) 4292 ++GPR_idx; 4293 } 4294 if (FPR_idx != Num_FPR_Regs) { 4295 unsigned VReg; 4296 4297 if (ObjectVT == MVT::f32) 4298 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass); 4299 else 4300 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass); 4301 4302 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 4303 ++FPR_idx; 4304 } else { 4305 needsLoad = true; 4306 } 4307 4308 // All FP arguments reserve stack space in the Darwin ABI. 4309 ArgOffset += isPPC64 ? 8 : ObjSize; 4310 break; 4311 case MVT::v4f32: 4312 case MVT::v4i32: 4313 case MVT::v8i16: 4314 case MVT::v16i8: 4315 // Note that vector arguments in registers don't reserve stack space, 4316 // except in varargs functions. 4317 if (VR_idx != Num_VR_Regs) { 4318 unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass); 4319 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 4320 if (isVarArg) { 4321 while ((ArgOffset % 16) != 0) { 4322 ArgOffset += PtrByteSize; 4323 if (GPR_idx != Num_GPR_Regs) 4324 GPR_idx++; 4325 } 4326 ArgOffset += 16; 4327 GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64? 4328 } 4329 ++VR_idx; 4330 } else { 4331 if (!isVarArg && !isPPC64) { 4332 // Vectors go after all the nonvectors. 4333 CurArgOffset = VecArgOffset; 4334 VecArgOffset += 16; 4335 } else { 4336 // Vectors are aligned. 4337 ArgOffset = ((ArgOffset+15)/16)*16; 4338 CurArgOffset = ArgOffset; 4339 ArgOffset += 16; 4340 } 4341 needsLoad = true; 4342 } 4343 break; 4344 } 4345 4346 // We need to load the argument to a virtual register if we determined above 4347 // that we ran out of physical registers of the appropriate type. 4348 if (needsLoad) { 4349 int FI = MFI.CreateFixedObject(ObjSize, 4350 CurArgOffset + (ArgSize - ObjSize), 4351 isImmutable); 4352 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4353 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo()); 4354 } 4355 4356 InVals.push_back(ArgVal); 4357 } 4358 4359 // Allow for Altivec parameters at the end, if needed. 4360 if (nAltivecParamsAtEnd) { 4361 MinReservedArea = ((MinReservedArea+15)/16)*16; 4362 MinReservedArea += 16*nAltivecParamsAtEnd; 4363 } 4364 4365 // Area that is at least reserved in the caller of this function. 4366 MinReservedArea = std::max(MinReservedArea, LinkageSize + 8 * PtrByteSize); 4367 4368 // Set the size that is at least reserved in caller of this function. Tail 4369 // call optimized functions' reserved stack space needs to be aligned so that 4370 // taking the difference between two stack areas will result in an aligned 4371 // stack. 4372 MinReservedArea = 4373 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea); 4374 FuncInfo->setMinReservedArea(MinReservedArea); 4375 4376 // If the function takes variable number of arguments, make a frame index for 4377 // the start of the first vararg value... for expansion of llvm.va_start. 4378 if (isVarArg) { 4379 int Depth = ArgOffset; 4380 4381 FuncInfo->setVarArgsFrameIndex( 4382 MFI.CreateFixedObject(PtrVT.getSizeInBits()/8, 4383 Depth, true)); 4384 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 4385 4386 // If this function is vararg, store any remaining integer argument regs 4387 // to their spots on the stack so that they may be loaded by dereferencing 4388 // the result of va_next. 4389 for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) { 4390 unsigned VReg; 4391 4392 if (isPPC64) 4393 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4394 else 4395 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 4396 4397 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4398 SDValue Store = 4399 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 4400 MemOps.push_back(Store); 4401 // Increment the address by four for the next argument to store 4402 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT); 4403 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 4404 } 4405 } 4406 4407 if (!MemOps.empty()) 4408 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 4409 4410 return Chain; 4411 } 4412 4413 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be 4414 /// adjusted to accommodate the arguments for the tailcall. 4415 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall, 4416 unsigned ParamSize) { 4417 4418 if (!isTailCall) return 0; 4419 4420 PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>(); 4421 unsigned CallerMinReservedArea = FI->getMinReservedArea(); 4422 int SPDiff = (int)CallerMinReservedArea - (int)ParamSize; 4423 // Remember only if the new adjustment is bigger. 4424 if (SPDiff < FI->getTailCallSPDelta()) 4425 FI->setTailCallSPDelta(SPDiff); 4426 4427 return SPDiff; 4428 } 4429 4430 static bool isFunctionGlobalAddress(SDValue Callee); 4431 4432 static bool 4433 callsShareTOCBase(const Function *Caller, SDValue Callee, 4434 const TargetMachine &TM) { 4435 // Callee is either a GlobalAddress or an ExternalSymbol. ExternalSymbols 4436 // don't have enough information to determine if the caller and calle share 4437 // the same TOC base, so we have to pessimistically assume they don't for 4438 // correctness. 4439 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee); 4440 if (!G) 4441 return false; 4442 4443 const GlobalValue *GV = G->getGlobal(); 4444 // The medium and large code models are expected to provide a sufficiently 4445 // large TOC to provide all data addressing needs of a module with a 4446 // single TOC. Since each module will be addressed with a single TOC then we 4447 // only need to check that caller and callee don't cross dso boundaries. 4448 if (CodeModel::Medium == TM.getCodeModel() || 4449 CodeModel::Large == TM.getCodeModel()) 4450 return TM.shouldAssumeDSOLocal(*Caller->getParent(), GV); 4451 4452 // Otherwise we need to ensure callee and caller are in the same section, 4453 // since the linker may allocate multiple TOCs, and we don't know which 4454 // sections will belong to the same TOC base. 4455 4456 if (!GV->isStrongDefinitionForLinker()) 4457 return false; 4458 4459 // Any explicitly-specified sections and section prefixes must also match. 4460 // Also, if we're using -ffunction-sections, then each function is always in 4461 // a different section (the same is true for COMDAT functions). 4462 if (TM.getFunctionSections() || GV->hasComdat() || Caller->hasComdat() || 4463 GV->getSection() != Caller->getSection()) 4464 return false; 4465 if (const auto *F = dyn_cast<Function>(GV)) { 4466 if (F->getSectionPrefix() != Caller->getSectionPrefix()) 4467 return false; 4468 } 4469 4470 // If the callee might be interposed, then we can't assume the ultimate call 4471 // target will be in the same section. Even in cases where we can assume that 4472 // interposition won't happen, in any case where the linker might insert a 4473 // stub to allow for interposition, we must generate code as though 4474 // interposition might occur. To understand why this matters, consider a 4475 // situation where: a -> b -> c where the arrows indicate calls. b and c are 4476 // in the same section, but a is in a different module (i.e. has a different 4477 // TOC base pointer). If the linker allows for interposition between b and c, 4478 // then it will generate a stub for the call edge between b and c which will 4479 // save the TOC pointer into the designated stack slot allocated by b. If we 4480 // return true here, and therefore allow a tail call between b and c, that 4481 // stack slot won't exist and the b -> c stub will end up saving b'c TOC base 4482 // pointer into the stack slot allocated by a (where the a -> b stub saved 4483 // a's TOC base pointer). If we're not considering a tail call, but rather, 4484 // whether a nop is needed after the call instruction in b, because the linker 4485 // will insert a stub, it might complain about a missing nop if we omit it 4486 // (although many don't complain in this case). 4487 if (!TM.shouldAssumeDSOLocal(*Caller->getParent(), GV)) 4488 return false; 4489 4490 return true; 4491 } 4492 4493 static bool 4494 needStackSlotPassParameters(const PPCSubtarget &Subtarget, 4495 const SmallVectorImpl<ISD::OutputArg> &Outs) { 4496 assert(Subtarget.isSVR4ABI() && Subtarget.isPPC64()); 4497 4498 const unsigned PtrByteSize = 8; 4499 const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 4500 4501 static const MCPhysReg GPR[] = { 4502 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 4503 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 4504 }; 4505 static const MCPhysReg VR[] = { 4506 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 4507 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 4508 }; 4509 4510 const unsigned NumGPRs = array_lengthof(GPR); 4511 const unsigned NumFPRs = 13; 4512 const unsigned NumVRs = array_lengthof(VR); 4513 const unsigned ParamAreaSize = NumGPRs * PtrByteSize; 4514 4515 unsigned NumBytes = LinkageSize; 4516 unsigned AvailableFPRs = NumFPRs; 4517 unsigned AvailableVRs = NumVRs; 4518 4519 for (const ISD::OutputArg& Param : Outs) { 4520 if (Param.Flags.isNest()) continue; 4521 4522 if (CalculateStackSlotUsed(Param.VT, Param.ArgVT, Param.Flags, 4523 PtrByteSize, LinkageSize, ParamAreaSize, 4524 NumBytes, AvailableFPRs, AvailableVRs, 4525 Subtarget.hasQPX())) 4526 return true; 4527 } 4528 return false; 4529 } 4530 4531 static bool 4532 hasSameArgumentList(const Function *CallerFn, ImmutableCallSite CS) { 4533 if (CS.arg_size() != CallerFn->arg_size()) 4534 return false; 4535 4536 ImmutableCallSite::arg_iterator CalleeArgIter = CS.arg_begin(); 4537 ImmutableCallSite::arg_iterator CalleeArgEnd = CS.arg_end(); 4538 Function::const_arg_iterator CallerArgIter = CallerFn->arg_begin(); 4539 4540 for (; CalleeArgIter != CalleeArgEnd; ++CalleeArgIter, ++CallerArgIter) { 4541 const Value* CalleeArg = *CalleeArgIter; 4542 const Value* CallerArg = &(*CallerArgIter); 4543 if (CalleeArg == CallerArg) 4544 continue; 4545 4546 // e.g. @caller([4 x i64] %a, [4 x i64] %b) { 4547 // tail call @callee([4 x i64] undef, [4 x i64] %b) 4548 // } 4549 // 1st argument of callee is undef and has the same type as caller. 4550 if (CalleeArg->getType() == CallerArg->getType() && 4551 isa<UndefValue>(CalleeArg)) 4552 continue; 4553 4554 return false; 4555 } 4556 4557 return true; 4558 } 4559 4560 // Returns true if TCO is possible between the callers and callees 4561 // calling conventions. 4562 static bool 4563 areCallingConvEligibleForTCO_64SVR4(CallingConv::ID CallerCC, 4564 CallingConv::ID CalleeCC) { 4565 // Tail calls are possible with fastcc and ccc. 4566 auto isTailCallableCC = [] (CallingConv::ID CC){ 4567 return CC == CallingConv::C || CC == CallingConv::Fast; 4568 }; 4569 if (!isTailCallableCC(CallerCC) || !isTailCallableCC(CalleeCC)) 4570 return false; 4571 4572 // We can safely tail call both fastcc and ccc callees from a c calling 4573 // convention caller. If the caller is fastcc, we may have less stack space 4574 // than a non-fastcc caller with the same signature so disable tail-calls in 4575 // that case. 4576 return CallerCC == CallingConv::C || CallerCC == CalleeCC; 4577 } 4578 4579 bool 4580 PPCTargetLowering::IsEligibleForTailCallOptimization_64SVR4( 4581 SDValue Callee, 4582 CallingConv::ID CalleeCC, 4583 ImmutableCallSite CS, 4584 bool isVarArg, 4585 const SmallVectorImpl<ISD::OutputArg> &Outs, 4586 const SmallVectorImpl<ISD::InputArg> &Ins, 4587 SelectionDAG& DAG) const { 4588 bool TailCallOpt = getTargetMachine().Options.GuaranteedTailCallOpt; 4589 4590 if (DisableSCO && !TailCallOpt) return false; 4591 4592 // Variadic argument functions are not supported. 4593 if (isVarArg) return false; 4594 4595 auto &Caller = DAG.getMachineFunction().getFunction(); 4596 // Check that the calling conventions are compatible for tco. 4597 if (!areCallingConvEligibleForTCO_64SVR4(Caller.getCallingConv(), CalleeCC)) 4598 return false; 4599 4600 // Caller contains any byval parameter is not supported. 4601 if (any_of(Ins, [](const ISD::InputArg &IA) { return IA.Flags.isByVal(); })) 4602 return false; 4603 4604 // Callee contains any byval parameter is not supported, too. 4605 // Note: This is a quick work around, because in some cases, e.g. 4606 // caller's stack size > callee's stack size, we are still able to apply 4607 // sibling call optimization. For example, gcc is able to do SCO for caller1 4608 // in the following example, but not for caller2. 4609 // struct test { 4610 // long int a; 4611 // char ary[56]; 4612 // } gTest; 4613 // __attribute__((noinline)) int callee(struct test v, struct test *b) { 4614 // b->a = v.a; 4615 // return 0; 4616 // } 4617 // void caller1(struct test a, struct test c, struct test *b) { 4618 // callee(gTest, b); } 4619 // void caller2(struct test *b) { callee(gTest, b); } 4620 if (any_of(Outs, [](const ISD::OutputArg& OA) { return OA.Flags.isByVal(); })) 4621 return false; 4622 4623 // If callee and caller use different calling conventions, we cannot pass 4624 // parameters on stack since offsets for the parameter area may be different. 4625 if (Caller.getCallingConv() != CalleeCC && 4626 needStackSlotPassParameters(Subtarget, Outs)) 4627 return false; 4628 4629 // No TCO/SCO on indirect call because Caller have to restore its TOC 4630 if (!isFunctionGlobalAddress(Callee) && 4631 !isa<ExternalSymbolSDNode>(Callee)) 4632 return false; 4633 4634 // If the caller and callee potentially have different TOC bases then we 4635 // cannot tail call since we need to restore the TOC pointer after the call. 4636 // ref: https://bugzilla.mozilla.org/show_bug.cgi?id=973977 4637 if (!callsShareTOCBase(&Caller, Callee, getTargetMachine())) 4638 return false; 4639 4640 // TCO allows altering callee ABI, so we don't have to check further. 4641 if (CalleeCC == CallingConv::Fast && TailCallOpt) 4642 return true; 4643 4644 if (DisableSCO) return false; 4645 4646 // If callee use the same argument list that caller is using, then we can 4647 // apply SCO on this case. If it is not, then we need to check if callee needs 4648 // stack for passing arguments. 4649 if (!hasSameArgumentList(&Caller, CS) && 4650 needStackSlotPassParameters(Subtarget, Outs)) { 4651 return false; 4652 } 4653 4654 return true; 4655 } 4656 4657 /// IsEligibleForTailCallOptimization - Check whether the call is eligible 4658 /// for tail call optimization. Targets which want to do tail call 4659 /// optimization should implement this function. 4660 bool 4661 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee, 4662 CallingConv::ID CalleeCC, 4663 bool isVarArg, 4664 const SmallVectorImpl<ISD::InputArg> &Ins, 4665 SelectionDAG& DAG) const { 4666 if (!getTargetMachine().Options.GuaranteedTailCallOpt) 4667 return false; 4668 4669 // Variable argument functions are not supported. 4670 if (isVarArg) 4671 return false; 4672 4673 MachineFunction &MF = DAG.getMachineFunction(); 4674 CallingConv::ID CallerCC = MF.getFunction().getCallingConv(); 4675 if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) { 4676 // Functions containing by val parameters are not supported. 4677 for (unsigned i = 0; i != Ins.size(); i++) { 4678 ISD::ArgFlagsTy Flags = Ins[i].Flags; 4679 if (Flags.isByVal()) return false; 4680 } 4681 4682 // Non-PIC/GOT tail calls are supported. 4683 if (getTargetMachine().getRelocationModel() != Reloc::PIC_) 4684 return true; 4685 4686 // At the moment we can only do local tail calls (in same module, hidden 4687 // or protected) if we are generating PIC. 4688 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) 4689 return G->getGlobal()->hasHiddenVisibility() 4690 || G->getGlobal()->hasProtectedVisibility(); 4691 } 4692 4693 return false; 4694 } 4695 4696 /// isCallCompatibleAddress - Return the immediate to use if the specified 4697 /// 32-bit value is representable in the immediate field of a BxA instruction. 4698 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) { 4699 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op); 4700 if (!C) return nullptr; 4701 4702 int Addr = C->getZExtValue(); 4703 if ((Addr & 3) != 0 || // Low 2 bits are implicitly zero. 4704 SignExtend32<26>(Addr) != Addr) 4705 return nullptr; // Top 6 bits have to be sext of immediate. 4706 4707 return DAG 4708 .getConstant( 4709 (int)C->getZExtValue() >> 2, SDLoc(Op), 4710 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout())) 4711 .getNode(); 4712 } 4713 4714 namespace { 4715 4716 struct TailCallArgumentInfo { 4717 SDValue Arg; 4718 SDValue FrameIdxOp; 4719 int FrameIdx = 0; 4720 4721 TailCallArgumentInfo() = default; 4722 }; 4723 4724 } // end anonymous namespace 4725 4726 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot. 4727 static void StoreTailCallArgumentsToStackSlot( 4728 SelectionDAG &DAG, SDValue Chain, 4729 const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs, 4730 SmallVectorImpl<SDValue> &MemOpChains, const SDLoc &dl) { 4731 for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) { 4732 SDValue Arg = TailCallArgs[i].Arg; 4733 SDValue FIN = TailCallArgs[i].FrameIdxOp; 4734 int FI = TailCallArgs[i].FrameIdx; 4735 // Store relative to framepointer. 4736 MemOpChains.push_back(DAG.getStore( 4737 Chain, dl, Arg, FIN, 4738 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI))); 4739 } 4740 } 4741 4742 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to 4743 /// the appropriate stack slot for the tail call optimized function call. 4744 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG, SDValue Chain, 4745 SDValue OldRetAddr, SDValue OldFP, 4746 int SPDiff, const SDLoc &dl) { 4747 if (SPDiff) { 4748 // Calculate the new stack slot for the return address. 4749 MachineFunction &MF = DAG.getMachineFunction(); 4750 const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>(); 4751 const PPCFrameLowering *FL = Subtarget.getFrameLowering(); 4752 bool isPPC64 = Subtarget.isPPC64(); 4753 int SlotSize = isPPC64 ? 8 : 4; 4754 int NewRetAddrLoc = SPDiff + FL->getReturnSaveOffset(); 4755 int NewRetAddr = MF.getFrameInfo().CreateFixedObject(SlotSize, 4756 NewRetAddrLoc, true); 4757 EVT VT = isPPC64 ? MVT::i64 : MVT::i32; 4758 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT); 4759 Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx, 4760 MachinePointerInfo::getFixedStack(MF, NewRetAddr)); 4761 4762 // When using the 32/64-bit SVR4 ABI there is no need to move the FP stack 4763 // slot as the FP is never overwritten. 4764 if (Subtarget.isDarwinABI()) { 4765 int NewFPLoc = SPDiff + FL->getFramePointerSaveOffset(); 4766 int NewFPIdx = MF.getFrameInfo().CreateFixedObject(SlotSize, NewFPLoc, 4767 true); 4768 SDValue NewFramePtrIdx = DAG.getFrameIndex(NewFPIdx, VT); 4769 Chain = DAG.getStore(Chain, dl, OldFP, NewFramePtrIdx, 4770 MachinePointerInfo::getFixedStack( 4771 DAG.getMachineFunction(), NewFPIdx)); 4772 } 4773 } 4774 return Chain; 4775 } 4776 4777 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate 4778 /// the position of the argument. 4779 static void 4780 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64, 4781 SDValue Arg, int SPDiff, unsigned ArgOffset, 4782 SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) { 4783 int Offset = ArgOffset + SPDiff; 4784 uint32_t OpSize = (Arg.getValueSizeInBits() + 7) / 8; 4785 int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true); 4786 EVT VT = isPPC64 ? MVT::i64 : MVT::i32; 4787 SDValue FIN = DAG.getFrameIndex(FI, VT); 4788 TailCallArgumentInfo Info; 4789 Info.Arg = Arg; 4790 Info.FrameIdxOp = FIN; 4791 Info.FrameIdx = FI; 4792 TailCallArguments.push_back(Info); 4793 } 4794 4795 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address 4796 /// stack slot. Returns the chain as result and the loaded frame pointers in 4797 /// LROpOut/FPOpout. Used when tail calling. 4798 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr( 4799 SelectionDAG &DAG, int SPDiff, SDValue Chain, SDValue &LROpOut, 4800 SDValue &FPOpOut, const SDLoc &dl) const { 4801 if (SPDiff) { 4802 // Load the LR and FP stack slot for later adjusting. 4803 EVT VT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32; 4804 LROpOut = getReturnAddrFrameIndex(DAG); 4805 LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo()); 4806 Chain = SDValue(LROpOut.getNode(), 1); 4807 4808 // When using the 32/64-bit SVR4 ABI there is no need to load the FP stack 4809 // slot as the FP is never overwritten. 4810 if (Subtarget.isDarwinABI()) { 4811 FPOpOut = getFramePointerFrameIndex(DAG); 4812 FPOpOut = DAG.getLoad(VT, dl, Chain, FPOpOut, MachinePointerInfo()); 4813 Chain = SDValue(FPOpOut.getNode(), 1); 4814 } 4815 } 4816 return Chain; 4817 } 4818 4819 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified 4820 /// by "Src" to address "Dst" of size "Size". Alignment information is 4821 /// specified by the specific parameter attribute. The copy will be passed as 4822 /// a byval function parameter. 4823 /// Sometimes what we are copying is the end of a larger object, the part that 4824 /// does not fit in registers. 4825 static SDValue CreateCopyOfByValArgument(SDValue Src, SDValue Dst, 4826 SDValue Chain, ISD::ArgFlagsTy Flags, 4827 SelectionDAG &DAG, const SDLoc &dl) { 4828 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32); 4829 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(), 4830 false, false, false, MachinePointerInfo(), 4831 MachinePointerInfo()); 4832 } 4833 4834 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of 4835 /// tail calls. 4836 static void LowerMemOpCallTo( 4837 SelectionDAG &DAG, MachineFunction &MF, SDValue Chain, SDValue Arg, 4838 SDValue PtrOff, int SPDiff, unsigned ArgOffset, bool isPPC64, 4839 bool isTailCall, bool isVector, SmallVectorImpl<SDValue> &MemOpChains, 4840 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments, const SDLoc &dl) { 4841 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 4842 if (!isTailCall) { 4843 if (isVector) { 4844 SDValue StackPtr; 4845 if (isPPC64) 4846 StackPtr = DAG.getRegister(PPC::X1, MVT::i64); 4847 else 4848 StackPtr = DAG.getRegister(PPC::R1, MVT::i32); 4849 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, 4850 DAG.getConstant(ArgOffset, dl, PtrVT)); 4851 } 4852 MemOpChains.push_back( 4853 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo())); 4854 // Calculate and remember argument location. 4855 } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset, 4856 TailCallArguments); 4857 } 4858 4859 static void 4860 PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain, 4861 const SDLoc &dl, int SPDiff, unsigned NumBytes, SDValue LROp, 4862 SDValue FPOp, 4863 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) { 4864 // Emit a sequence of copyto/copyfrom virtual registers for arguments that 4865 // might overwrite each other in case of tail call optimization. 4866 SmallVector<SDValue, 8> MemOpChains2; 4867 // Do not flag preceding copytoreg stuff together with the following stuff. 4868 InFlag = SDValue(); 4869 StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments, 4870 MemOpChains2, dl); 4871 if (!MemOpChains2.empty()) 4872 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2); 4873 4874 // Store the return address to the appropriate stack slot. 4875 Chain = EmitTailCallStoreFPAndRetAddr(DAG, Chain, LROp, FPOp, SPDiff, dl); 4876 4877 // Emit callseq_end just before tailcall node. 4878 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true), 4879 DAG.getIntPtrConstant(0, dl, true), InFlag, dl); 4880 InFlag = Chain.getValue(1); 4881 } 4882 4883 // Is this global address that of a function that can be called by name? (as 4884 // opposed to something that must hold a descriptor for an indirect call). 4885 static bool isFunctionGlobalAddress(SDValue Callee) { 4886 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 4887 if (Callee.getOpcode() == ISD::GlobalTLSAddress || 4888 Callee.getOpcode() == ISD::TargetGlobalTLSAddress) 4889 return false; 4890 4891 return G->getGlobal()->getValueType()->isFunctionTy(); 4892 } 4893 4894 return false; 4895 } 4896 4897 static unsigned 4898 PrepareCall(SelectionDAG &DAG, SDValue &Callee, SDValue &InFlag, SDValue &Chain, 4899 SDValue CallSeqStart, const SDLoc &dl, int SPDiff, bool isTailCall, 4900 bool isPatchPoint, bool hasNest, 4901 SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass, 4902 SmallVectorImpl<SDValue> &Ops, std::vector<EVT> &NodeTys, 4903 ImmutableCallSite CS, const PPCSubtarget &Subtarget) { 4904 bool isPPC64 = Subtarget.isPPC64(); 4905 bool isSVR4ABI = Subtarget.isSVR4ABI(); 4906 bool isELFv2ABI = Subtarget.isELFv2ABI(); 4907 bool isAIXABI = Subtarget.isAIXABI(); 4908 4909 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 4910 NodeTys.push_back(MVT::Other); // Returns a chain 4911 NodeTys.push_back(MVT::Glue); // Returns a flag for retval copy to use. 4912 4913 unsigned CallOpc = PPCISD::CALL; 4914 4915 bool needIndirectCall = true; 4916 if (!isSVR4ABI || !isPPC64) 4917 if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG)) { 4918 // If this is an absolute destination address, use the munged value. 4919 Callee = SDValue(Dest, 0); 4920 needIndirectCall = false; 4921 } 4922 4923 // PC-relative references to external symbols should go through $stub, unless 4924 // we're building with the leopard linker or later, which automatically 4925 // synthesizes these stubs. 4926 const TargetMachine &TM = DAG.getTarget(); 4927 const Module *Mod = DAG.getMachineFunction().getFunction().getParent(); 4928 const GlobalValue *GV = nullptr; 4929 if (auto *G = dyn_cast<GlobalAddressSDNode>(Callee)) 4930 GV = G->getGlobal(); 4931 bool Local = TM.shouldAssumeDSOLocal(*Mod, GV); 4932 bool UsePlt = !Local && Subtarget.isTargetELF() && !isPPC64; 4933 4934 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, 4935 // every direct call is) turn it into a TargetGlobalAddress / 4936 // TargetExternalSymbol node so that legalize doesn't hack it. 4937 if (isFunctionGlobalAddress(Callee)) { 4938 GlobalAddressSDNode *G = cast<GlobalAddressSDNode>(Callee); 4939 4940 // A call to a TLS address is actually an indirect call to a 4941 // thread-specific pointer. 4942 unsigned OpFlags = 0; 4943 if (UsePlt) 4944 OpFlags = PPCII::MO_PLT; 4945 4946 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl, 4947 Callee.getValueType(), 0, OpFlags); 4948 needIndirectCall = false; 4949 } 4950 4951 if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) { 4952 unsigned char OpFlags = 0; 4953 4954 if (UsePlt) 4955 OpFlags = PPCII::MO_PLT; 4956 4957 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), Callee.getValueType(), 4958 OpFlags); 4959 needIndirectCall = false; 4960 } 4961 4962 if (isPatchPoint) { 4963 // We'll form an invalid direct call when lowering a patchpoint; the full 4964 // sequence for an indirect call is complicated, and many of the 4965 // instructions introduced might have side effects (and, thus, can't be 4966 // removed later). The call itself will be removed as soon as the 4967 // argument/return lowering is complete, so the fact that it has the wrong 4968 // kind of operands should not really matter. 4969 needIndirectCall = false; 4970 } 4971 4972 if (needIndirectCall) { 4973 // Otherwise, this is an indirect call. We have to use a MTCTR/BCTRL pair 4974 // to do the call, we can't use PPCISD::CALL. 4975 SDValue MTCTROps[] = {Chain, Callee, InFlag}; 4976 4977 if (isSVR4ABI && isPPC64 && !isELFv2ABI) { 4978 // Function pointers in the 64-bit SVR4 ABI do not point to the function 4979 // entry point, but to the function descriptor (the function entry point 4980 // address is part of the function descriptor though). 4981 // The function descriptor is a three doubleword structure with the 4982 // following fields: function entry point, TOC base address and 4983 // environment pointer. 4984 // Thus for a call through a function pointer, the following actions need 4985 // to be performed: 4986 // 1. Save the TOC of the caller in the TOC save area of its stack 4987 // frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()). 4988 // 2. Load the address of the function entry point from the function 4989 // descriptor. 4990 // 3. Load the TOC of the callee from the function descriptor into r2. 4991 // 4. Load the environment pointer from the function descriptor into 4992 // r11. 4993 // 5. Branch to the function entry point address. 4994 // 6. On return of the callee, the TOC of the caller needs to be 4995 // restored (this is done in FinishCall()). 4996 // 4997 // The loads are scheduled at the beginning of the call sequence, and the 4998 // register copies are flagged together to ensure that no other 4999 // operations can be scheduled in between. E.g. without flagging the 5000 // copies together, a TOC access in the caller could be scheduled between 5001 // the assignment of the callee TOC and the branch to the callee, which 5002 // results in the TOC access going through the TOC of the callee instead 5003 // of going through the TOC of the caller, which leads to incorrect code. 5004 5005 // Load the address of the function entry point from the function 5006 // descriptor. 5007 SDValue LDChain = CallSeqStart.getValue(CallSeqStart->getNumValues()-1); 5008 if (LDChain.getValueType() == MVT::Glue) 5009 LDChain = CallSeqStart.getValue(CallSeqStart->getNumValues()-2); 5010 5011 auto MMOFlags = Subtarget.hasInvariantFunctionDescriptors() 5012 ? (MachineMemOperand::MODereferenceable | 5013 MachineMemOperand::MOInvariant) 5014 : MachineMemOperand::MONone; 5015 5016 MachinePointerInfo MPI(CS ? CS.getCalledValue() : nullptr); 5017 SDValue LoadFuncPtr = DAG.getLoad(MVT::i64, dl, LDChain, Callee, MPI, 5018 /* Alignment = */ 8, MMOFlags); 5019 5020 // Load environment pointer into r11. 5021 SDValue PtrOff = DAG.getIntPtrConstant(16, dl); 5022 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, PtrOff); 5023 SDValue LoadEnvPtr = 5024 DAG.getLoad(MVT::i64, dl, LDChain, AddPtr, MPI.getWithOffset(16), 5025 /* Alignment = */ 8, MMOFlags); 5026 5027 SDValue TOCOff = DAG.getIntPtrConstant(8, dl); 5028 SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, TOCOff); 5029 SDValue TOCPtr = 5030 DAG.getLoad(MVT::i64, dl, LDChain, AddTOC, MPI.getWithOffset(8), 5031 /* Alignment = */ 8, MMOFlags); 5032 5033 setUsesTOCBasePtr(DAG); 5034 SDValue TOCVal = DAG.getCopyToReg(Chain, dl, PPC::X2, TOCPtr, 5035 InFlag); 5036 Chain = TOCVal.getValue(0); 5037 InFlag = TOCVal.getValue(1); 5038 5039 // If the function call has an explicit 'nest' parameter, it takes the 5040 // place of the environment pointer. 5041 if (!hasNest) { 5042 SDValue EnvVal = DAG.getCopyToReg(Chain, dl, PPC::X11, LoadEnvPtr, 5043 InFlag); 5044 5045 Chain = EnvVal.getValue(0); 5046 InFlag = EnvVal.getValue(1); 5047 } 5048 5049 MTCTROps[0] = Chain; 5050 MTCTROps[1] = LoadFuncPtr; 5051 MTCTROps[2] = InFlag; 5052 } 5053 5054 Chain = DAG.getNode(PPCISD::MTCTR, dl, NodeTys, 5055 makeArrayRef(MTCTROps, InFlag.getNode() ? 3 : 2)); 5056 InFlag = Chain.getValue(1); 5057 5058 NodeTys.clear(); 5059 NodeTys.push_back(MVT::Other); 5060 NodeTys.push_back(MVT::Glue); 5061 Ops.push_back(Chain); 5062 CallOpc = PPCISD::BCTRL; 5063 Callee.setNode(nullptr); 5064 // Add use of X11 (holding environment pointer) 5065 if (isSVR4ABI && isPPC64 && !isELFv2ABI && !hasNest) 5066 Ops.push_back(DAG.getRegister(PPC::X11, PtrVT)); 5067 // Add CTR register as callee so a bctr can be emitted later. 5068 if (isTailCall) 5069 Ops.push_back(DAG.getRegister(isPPC64 ? PPC::CTR8 : PPC::CTR, PtrVT)); 5070 } 5071 5072 // If this is a direct call, pass the chain and the callee. 5073 if (Callee.getNode()) { 5074 Ops.push_back(Chain); 5075 Ops.push_back(Callee); 5076 } 5077 // If this is a tail call add stack pointer delta. 5078 if (isTailCall) 5079 Ops.push_back(DAG.getConstant(SPDiff, dl, MVT::i32)); 5080 5081 // Add argument registers to the end of the list so that they are known live 5082 // into the call. 5083 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) 5084 Ops.push_back(DAG.getRegister(RegsToPass[i].first, 5085 RegsToPass[i].second.getValueType())); 5086 5087 // All calls, in the AIX ABI and 64-bit ELF ABIs, need the TOC register 5088 // live into the call. 5089 // We do need to reserve R2/X2 to appease the verifier for the PATCHPOINT. 5090 if ((isSVR4ABI && isPPC64) || isAIXABI) { 5091 setUsesTOCBasePtr(DAG); 5092 5093 // We cannot add R2/X2 as an operand here for PATCHPOINT, because there is 5094 // no way to mark dependencies as implicit here. 5095 // We will add the R2/X2 dependency in EmitInstrWithCustomInserter. 5096 if (!isPatchPoint) 5097 Ops.push_back(DAG.getRegister(isPPC64 ? PPC::X2 5098 : PPC::R2, PtrVT)); 5099 } 5100 5101 return CallOpc; 5102 } 5103 5104 SDValue PPCTargetLowering::LowerCallResult( 5105 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg, 5106 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 5107 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 5108 SmallVector<CCValAssign, 16> RVLocs; 5109 CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 5110 *DAG.getContext()); 5111 5112 CCRetInfo.AnalyzeCallResult( 5113 Ins, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold) 5114 ? RetCC_PPC_Cold 5115 : RetCC_PPC); 5116 5117 // Copy all of the result registers out of their specified physreg. 5118 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) { 5119 CCValAssign &VA = RVLocs[i]; 5120 assert(VA.isRegLoc() && "Can only return in registers!"); 5121 5122 SDValue Val; 5123 5124 if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) { 5125 SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, 5126 InFlag); 5127 Chain = Lo.getValue(1); 5128 InFlag = Lo.getValue(2); 5129 VA = RVLocs[++i]; // skip ahead to next loc 5130 SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, 5131 InFlag); 5132 Chain = Hi.getValue(1); 5133 InFlag = Hi.getValue(2); 5134 if (!Subtarget.isLittleEndian()) 5135 std::swap (Lo, Hi); 5136 Val = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, Lo, Hi); 5137 } else { 5138 Val = DAG.getCopyFromReg(Chain, dl, 5139 VA.getLocReg(), VA.getLocVT(), InFlag); 5140 Chain = Val.getValue(1); 5141 InFlag = Val.getValue(2); 5142 } 5143 5144 switch (VA.getLocInfo()) { 5145 default: llvm_unreachable("Unknown loc info!"); 5146 case CCValAssign::Full: break; 5147 case CCValAssign::AExt: 5148 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val); 5149 break; 5150 case CCValAssign::ZExt: 5151 Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val, 5152 DAG.getValueType(VA.getValVT())); 5153 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val); 5154 break; 5155 case CCValAssign::SExt: 5156 Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val, 5157 DAG.getValueType(VA.getValVT())); 5158 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val); 5159 break; 5160 } 5161 5162 InVals.push_back(Val); 5163 } 5164 5165 return Chain; 5166 } 5167 5168 SDValue PPCTargetLowering::FinishCall( 5169 CallingConv::ID CallConv, const SDLoc &dl, bool isTailCall, bool isVarArg, 5170 bool isPatchPoint, bool hasNest, SelectionDAG &DAG, 5171 SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, SDValue InFlag, 5172 SDValue Chain, SDValue CallSeqStart, SDValue &Callee, int SPDiff, 5173 unsigned NumBytes, const SmallVectorImpl<ISD::InputArg> &Ins, 5174 SmallVectorImpl<SDValue> &InVals, ImmutableCallSite CS) const { 5175 std::vector<EVT> NodeTys; 5176 SmallVector<SDValue, 8> Ops; 5177 unsigned CallOpc = PrepareCall(DAG, Callee, InFlag, Chain, CallSeqStart, dl, 5178 SPDiff, isTailCall, isPatchPoint, hasNest, 5179 RegsToPass, Ops, NodeTys, CS, Subtarget); 5180 5181 // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls 5182 if (isVarArg && Subtarget.isSVR4ABI() && !Subtarget.isPPC64()) 5183 Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32)); 5184 5185 // When performing tail call optimization the callee pops its arguments off 5186 // the stack. Account for this here so these bytes can be pushed back on in 5187 // PPCFrameLowering::eliminateCallFramePseudoInstr. 5188 int BytesCalleePops = 5189 (CallConv == CallingConv::Fast && 5190 getTargetMachine().Options.GuaranteedTailCallOpt) ? NumBytes : 0; 5191 5192 // Add a register mask operand representing the call-preserved registers. 5193 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo(); 5194 const uint32_t *Mask = 5195 TRI->getCallPreservedMask(DAG.getMachineFunction(), CallConv); 5196 assert(Mask && "Missing call preserved mask for calling convention"); 5197 Ops.push_back(DAG.getRegisterMask(Mask)); 5198 5199 if (InFlag.getNode()) 5200 Ops.push_back(InFlag); 5201 5202 // Emit tail call. 5203 if (isTailCall) { 5204 assert(((Callee.getOpcode() == ISD::Register && 5205 cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) || 5206 Callee.getOpcode() == ISD::TargetExternalSymbol || 5207 Callee.getOpcode() == ISD::TargetGlobalAddress || 5208 isa<ConstantSDNode>(Callee)) && 5209 "Expecting an global address, external symbol, absolute value or register"); 5210 5211 DAG.getMachineFunction().getFrameInfo().setHasTailCall(); 5212 return DAG.getNode(PPCISD::TC_RETURN, dl, MVT::Other, Ops); 5213 } 5214 5215 // Add a NOP immediately after the branch instruction when using the 64-bit 5216 // SVR4 or the AIX ABI. 5217 // At link time, if caller and callee are in a different module and 5218 // thus have a different TOC, the call will be replaced with a call to a stub 5219 // function which saves the current TOC, loads the TOC of the callee and 5220 // branches to the callee. The NOP will be replaced with a load instruction 5221 // which restores the TOC of the caller from the TOC save slot of the current 5222 // stack frame. If caller and callee belong to the same module (and have the 5223 // same TOC), the NOP will remain unchanged, or become some other NOP. 5224 5225 MachineFunction &MF = DAG.getMachineFunction(); 5226 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 5227 if (!isTailCall && !isPatchPoint && 5228 ((Subtarget.isSVR4ABI() && Subtarget.isPPC64()) || 5229 Subtarget.isAIXABI())) { 5230 if (CallOpc == PPCISD::BCTRL) { 5231 if (Subtarget.isAIXABI()) 5232 report_fatal_error("Indirect call on AIX is not implemented."); 5233 5234 // This is a call through a function pointer. 5235 // Restore the caller TOC from the save area into R2. 5236 // See PrepareCall() for more information about calls through function 5237 // pointers in the 64-bit SVR4 ABI. 5238 // We are using a target-specific load with r2 hard coded, because the 5239 // result of a target-independent load would never go directly into r2, 5240 // since r2 is a reserved register (which prevents the register allocator 5241 // from allocating it), resulting in an additional register being 5242 // allocated and an unnecessary move instruction being generated. 5243 CallOpc = PPCISD::BCTRL_LOAD_TOC; 5244 5245 SDValue StackPtr = DAG.getRegister(PPC::X1, PtrVT); 5246 unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset(); 5247 SDValue TOCOff = DAG.getIntPtrConstant(TOCSaveOffset, dl); 5248 SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, StackPtr, TOCOff); 5249 5250 // The address needs to go after the chain input but before the flag (or 5251 // any other variadic arguments). 5252 Ops.insert(std::next(Ops.begin()), AddTOC); 5253 } else if (CallOpc == PPCISD::CALL && 5254 !callsShareTOCBase(&MF.getFunction(), Callee, DAG.getTarget())) { 5255 // Otherwise insert NOP for non-local calls. 5256 CallOpc = PPCISD::CALL_NOP; 5257 } 5258 } 5259 5260 if (Subtarget.isAIXABI() && isFunctionGlobalAddress(Callee)) { 5261 // On AIX, direct function calls reference the symbol for the function's 5262 // entry point, which is named by inserting a "." before the function's 5263 // C-linkage name. 5264 GlobalAddressSDNode *G = cast<GlobalAddressSDNode>(Callee); 5265 auto &Context = DAG.getMachineFunction().getMMI().getContext(); 5266 MCSymbol *S = Context.getOrCreateSymbol(Twine(".") + 5267 Twine(G->getGlobal()->getName())); 5268 Callee = DAG.getMCSymbol(S, PtrVT); 5269 // Replace the GlobalAddressSDNode Callee with the MCSymbolSDNode. 5270 Ops[1] = Callee; 5271 } 5272 5273 Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops); 5274 InFlag = Chain.getValue(1); 5275 5276 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true), 5277 DAG.getIntPtrConstant(BytesCalleePops, dl, true), 5278 InFlag, dl); 5279 if (!Ins.empty()) 5280 InFlag = Chain.getValue(1); 5281 5282 return LowerCallResult(Chain, InFlag, CallConv, isVarArg, 5283 Ins, dl, DAG, InVals); 5284 } 5285 5286 SDValue 5287 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI, 5288 SmallVectorImpl<SDValue> &InVals) const { 5289 SelectionDAG &DAG = CLI.DAG; 5290 SDLoc &dl = CLI.DL; 5291 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs; 5292 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals; 5293 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins; 5294 SDValue Chain = CLI.Chain; 5295 SDValue Callee = CLI.Callee; 5296 bool &isTailCall = CLI.IsTailCall; 5297 CallingConv::ID CallConv = CLI.CallConv; 5298 bool isVarArg = CLI.IsVarArg; 5299 bool isPatchPoint = CLI.IsPatchPoint; 5300 ImmutableCallSite CS = CLI.CS; 5301 5302 if (isTailCall) { 5303 if (Subtarget.useLongCalls() && !(CS && CS.isMustTailCall())) 5304 isTailCall = false; 5305 else if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) 5306 isTailCall = 5307 IsEligibleForTailCallOptimization_64SVR4(Callee, CallConv, CS, 5308 isVarArg, Outs, Ins, DAG); 5309 else 5310 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg, 5311 Ins, DAG); 5312 if (isTailCall) { 5313 ++NumTailCalls; 5314 if (!getTargetMachine().Options.GuaranteedTailCallOpt) 5315 ++NumSiblingCalls; 5316 5317 assert(isa<GlobalAddressSDNode>(Callee) && 5318 "Callee should be an llvm::Function object."); 5319 LLVM_DEBUG( 5320 const GlobalValue *GV = 5321 cast<GlobalAddressSDNode>(Callee)->getGlobal(); 5322 const unsigned Width = 5323 80 - strlen("TCO caller: ") - strlen(", callee linkage: 0, 0"); 5324 dbgs() << "TCO caller: " 5325 << left_justify(DAG.getMachineFunction().getName(), Width) 5326 << ", callee linkage: " << GV->getVisibility() << ", " 5327 << GV->getLinkage() << "\n"); 5328 } 5329 } 5330 5331 if (!isTailCall && CS && CS.isMustTailCall()) 5332 report_fatal_error("failed to perform tail call elimination on a call " 5333 "site marked musttail"); 5334 5335 // When long calls (i.e. indirect calls) are always used, calls are always 5336 // made via function pointer. If we have a function name, first translate it 5337 // into a pointer. 5338 if (Subtarget.useLongCalls() && isa<GlobalAddressSDNode>(Callee) && 5339 !isTailCall) 5340 Callee = LowerGlobalAddress(Callee, DAG); 5341 5342 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) 5343 return LowerCall_64SVR4(Chain, Callee, CallConv, isVarArg, 5344 isTailCall, isPatchPoint, Outs, OutVals, Ins, 5345 dl, DAG, InVals, CS); 5346 5347 if (Subtarget.isSVR4ABI()) 5348 return LowerCall_32SVR4(Chain, Callee, CallConv, isVarArg, 5349 isTailCall, isPatchPoint, Outs, OutVals, Ins, 5350 dl, DAG, InVals, CS); 5351 5352 if (Subtarget.isAIXABI()) 5353 return LowerCall_AIX(Chain, Callee, CallConv, isVarArg, 5354 isTailCall, isPatchPoint, Outs, OutVals, Ins, 5355 dl, DAG, InVals, CS); 5356 5357 return LowerCall_Darwin(Chain, Callee, CallConv, isVarArg, 5358 isTailCall, isPatchPoint, Outs, OutVals, Ins, 5359 dl, DAG, InVals, CS); 5360 } 5361 5362 SDValue PPCTargetLowering::LowerCall_32SVR4( 5363 SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg, 5364 bool isTailCall, bool isPatchPoint, 5365 const SmallVectorImpl<ISD::OutputArg> &Outs, 5366 const SmallVectorImpl<SDValue> &OutVals, 5367 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 5368 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 5369 ImmutableCallSite CS) const { 5370 // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description 5371 // of the 32-bit SVR4 ABI stack frame layout. 5372 5373 assert((CallConv == CallingConv::C || 5374 CallConv == CallingConv::Cold || 5375 CallConv == CallingConv::Fast) && "Unknown calling convention!"); 5376 5377 unsigned PtrByteSize = 4; 5378 5379 MachineFunction &MF = DAG.getMachineFunction(); 5380 5381 // Mark this function as potentially containing a function that contains a 5382 // tail call. As a consequence the frame pointer will be used for dynamicalloc 5383 // and restoring the callers stack pointer in this functions epilog. This is 5384 // done because by tail calling the called function might overwrite the value 5385 // in this function's (MF) stack pointer stack slot 0(SP). 5386 if (getTargetMachine().Options.GuaranteedTailCallOpt && 5387 CallConv == CallingConv::Fast) 5388 MF.getInfo<PPCFunctionInfo>()->setHasFastCall(); 5389 5390 // Count how many bytes are to be pushed on the stack, including the linkage 5391 // area, parameter list area and the part of the local variable space which 5392 // contains copies of aggregates which are passed by value. 5393 5394 // Assign locations to all of the outgoing arguments. 5395 SmallVector<CCValAssign, 16> ArgLocs; 5396 PPCCCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext()); 5397 5398 // Reserve space for the linkage area on the stack. 5399 CCInfo.AllocateStack(Subtarget.getFrameLowering()->getLinkageSize(), 5400 PtrByteSize); 5401 if (useSoftFloat()) 5402 CCInfo.PreAnalyzeCallOperands(Outs); 5403 5404 if (isVarArg) { 5405 // Handle fixed and variable vector arguments differently. 5406 // Fixed vector arguments go into registers as long as registers are 5407 // available. Variable vector arguments always go into memory. 5408 unsigned NumArgs = Outs.size(); 5409 5410 for (unsigned i = 0; i != NumArgs; ++i) { 5411 MVT ArgVT = Outs[i].VT; 5412 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 5413 bool Result; 5414 5415 if (Outs[i].IsFixed) { 5416 Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, 5417 CCInfo); 5418 } else { 5419 Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full, 5420 ArgFlags, CCInfo); 5421 } 5422 5423 if (Result) { 5424 #ifndef NDEBUG 5425 errs() << "Call operand #" << i << " has unhandled type " 5426 << EVT(ArgVT).getEVTString() << "\n"; 5427 #endif 5428 llvm_unreachable(nullptr); 5429 } 5430 } 5431 } else { 5432 // All arguments are treated the same. 5433 CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4); 5434 } 5435 CCInfo.clearWasPPCF128(); 5436 5437 // Assign locations to all of the outgoing aggregate by value arguments. 5438 SmallVector<CCValAssign, 16> ByValArgLocs; 5439 CCState CCByValInfo(CallConv, isVarArg, MF, ByValArgLocs, *DAG.getContext()); 5440 5441 // Reserve stack space for the allocations in CCInfo. 5442 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize); 5443 5444 CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal); 5445 5446 // Size of the linkage area, parameter list area and the part of the local 5447 // space variable where copies of aggregates which are passed by value are 5448 // stored. 5449 unsigned NumBytes = CCByValInfo.getNextStackOffset(); 5450 5451 // Calculate by how many bytes the stack has to be adjusted in case of tail 5452 // call optimization. 5453 int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes); 5454 5455 // Adjust the stack pointer for the new arguments... 5456 // These operations are automatically eliminated by the prolog/epilog pass 5457 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 5458 SDValue CallSeqStart = Chain; 5459 5460 // Load the return address and frame pointer so it can be moved somewhere else 5461 // later. 5462 SDValue LROp, FPOp; 5463 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl); 5464 5465 // Set up a copy of the stack pointer for use loading and storing any 5466 // arguments that may not fit in the registers available for argument 5467 // passing. 5468 SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32); 5469 5470 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 5471 SmallVector<TailCallArgumentInfo, 8> TailCallArguments; 5472 SmallVector<SDValue, 8> MemOpChains; 5473 5474 bool seenFloatArg = false; 5475 // Walk the register/memloc assignments, inserting copies/loads. 5476 // i - Tracks the index into the list of registers allocated for the call 5477 // RealArgIdx - Tracks the index into the list of actual function arguments 5478 // j - Tracks the index into the list of byval arguments 5479 for (unsigned i = 0, RealArgIdx = 0, j = 0, e = ArgLocs.size(); 5480 i != e; 5481 ++i, ++RealArgIdx) { 5482 CCValAssign &VA = ArgLocs[i]; 5483 SDValue Arg = OutVals[RealArgIdx]; 5484 ISD::ArgFlagsTy Flags = Outs[RealArgIdx].Flags; 5485 5486 if (Flags.isByVal()) { 5487 // Argument is an aggregate which is passed by value, thus we need to 5488 // create a copy of it in the local variable space of the current stack 5489 // frame (which is the stack frame of the caller) and pass the address of 5490 // this copy to the callee. 5491 assert((j < ByValArgLocs.size()) && "Index out of bounds!"); 5492 CCValAssign &ByValVA = ByValArgLocs[j++]; 5493 assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!"); 5494 5495 // Memory reserved in the local variable space of the callers stack frame. 5496 unsigned LocMemOffset = ByValVA.getLocMemOffset(); 5497 5498 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 5499 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()), 5500 StackPtr, PtrOff); 5501 5502 // Create a copy of the argument in the local area of the current 5503 // stack frame. 5504 SDValue MemcpyCall = 5505 CreateCopyOfByValArgument(Arg, PtrOff, 5506 CallSeqStart.getNode()->getOperand(0), 5507 Flags, DAG, dl); 5508 5509 // This must go outside the CALLSEQ_START..END. 5510 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, NumBytes, 0, 5511 SDLoc(MemcpyCall)); 5512 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(), 5513 NewCallSeqStart.getNode()); 5514 Chain = CallSeqStart = NewCallSeqStart; 5515 5516 // Pass the address of the aggregate copy on the stack either in a 5517 // physical register or in the parameter list area of the current stack 5518 // frame to the callee. 5519 Arg = PtrOff; 5520 } 5521 5522 // When useCRBits() is true, there can be i1 arguments. 5523 // It is because getRegisterType(MVT::i1) => MVT::i1, 5524 // and for other integer types getRegisterType() => MVT::i32. 5525 // Extend i1 and ensure callee will get i32. 5526 if (Arg.getValueType() == MVT::i1) 5527 Arg = DAG.getNode(Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, 5528 dl, MVT::i32, Arg); 5529 5530 if (VA.isRegLoc()) { 5531 seenFloatArg |= VA.getLocVT().isFloatingPoint(); 5532 // Put argument in a physical register. 5533 if (Subtarget.hasSPE() && Arg.getValueType() == MVT::f64) { 5534 bool IsLE = Subtarget.isLittleEndian(); 5535 SDValue SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg, 5536 DAG.getIntPtrConstant(IsLE ? 0 : 1, dl)); 5537 RegsToPass.push_back(std::make_pair(VA.getLocReg(), SVal.getValue(0))); 5538 SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg, 5539 DAG.getIntPtrConstant(IsLE ? 1 : 0, dl)); 5540 RegsToPass.push_back(std::make_pair(ArgLocs[++i].getLocReg(), 5541 SVal.getValue(0))); 5542 } else 5543 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 5544 } else { 5545 // Put argument in the parameter list area of the current stack frame. 5546 assert(VA.isMemLoc()); 5547 unsigned LocMemOffset = VA.getLocMemOffset(); 5548 5549 if (!isTailCall) { 5550 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 5551 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()), 5552 StackPtr, PtrOff); 5553 5554 MemOpChains.push_back( 5555 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo())); 5556 } else { 5557 // Calculate and remember argument location. 5558 CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset, 5559 TailCallArguments); 5560 } 5561 } 5562 } 5563 5564 if (!MemOpChains.empty()) 5565 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 5566 5567 // Build a sequence of copy-to-reg nodes chained together with token chain 5568 // and flag operands which copy the outgoing args into the appropriate regs. 5569 SDValue InFlag; 5570 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 5571 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 5572 RegsToPass[i].second, InFlag); 5573 InFlag = Chain.getValue(1); 5574 } 5575 5576 // Set CR bit 6 to true if this is a vararg call with floating args passed in 5577 // registers. 5578 if (isVarArg) { 5579 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue); 5580 SDValue Ops[] = { Chain, InFlag }; 5581 5582 Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET, 5583 dl, VTs, makeArrayRef(Ops, InFlag.getNode() ? 2 : 1)); 5584 5585 InFlag = Chain.getValue(1); 5586 } 5587 5588 if (isTailCall) 5589 PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp, 5590 TailCallArguments); 5591 5592 return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint, 5593 /* unused except on PPC64 ELFv1 */ false, DAG, 5594 RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff, 5595 NumBytes, Ins, InVals, CS); 5596 } 5597 5598 // Copy an argument into memory, being careful to do this outside the 5599 // call sequence for the call to which the argument belongs. 5600 SDValue PPCTargetLowering::createMemcpyOutsideCallSeq( 5601 SDValue Arg, SDValue PtrOff, SDValue CallSeqStart, ISD::ArgFlagsTy Flags, 5602 SelectionDAG &DAG, const SDLoc &dl) const { 5603 SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff, 5604 CallSeqStart.getNode()->getOperand(0), 5605 Flags, DAG, dl); 5606 // The MEMCPY must go outside the CALLSEQ_START..END. 5607 int64_t FrameSize = CallSeqStart.getConstantOperandVal(1); 5608 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, FrameSize, 0, 5609 SDLoc(MemcpyCall)); 5610 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(), 5611 NewCallSeqStart.getNode()); 5612 return NewCallSeqStart; 5613 } 5614 5615 SDValue PPCTargetLowering::LowerCall_64SVR4( 5616 SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg, 5617 bool isTailCall, bool isPatchPoint, 5618 const SmallVectorImpl<ISD::OutputArg> &Outs, 5619 const SmallVectorImpl<SDValue> &OutVals, 5620 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 5621 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 5622 ImmutableCallSite CS) const { 5623 bool isELFv2ABI = Subtarget.isELFv2ABI(); 5624 bool isLittleEndian = Subtarget.isLittleEndian(); 5625 unsigned NumOps = Outs.size(); 5626 bool hasNest = false; 5627 bool IsSibCall = false; 5628 5629 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 5630 unsigned PtrByteSize = 8; 5631 5632 MachineFunction &MF = DAG.getMachineFunction(); 5633 5634 if (isTailCall && !getTargetMachine().Options.GuaranteedTailCallOpt) 5635 IsSibCall = true; 5636 5637 // Mark this function as potentially containing a function that contains a 5638 // tail call. As a consequence the frame pointer will be used for dynamicalloc 5639 // and restoring the callers stack pointer in this functions epilog. This is 5640 // done because by tail calling the called function might overwrite the value 5641 // in this function's (MF) stack pointer stack slot 0(SP). 5642 if (getTargetMachine().Options.GuaranteedTailCallOpt && 5643 CallConv == CallingConv::Fast) 5644 MF.getInfo<PPCFunctionInfo>()->setHasFastCall(); 5645 5646 assert(!(CallConv == CallingConv::Fast && isVarArg) && 5647 "fastcc not supported on varargs functions"); 5648 5649 // Count how many bytes are to be pushed on the stack, including the linkage 5650 // area, and parameter passing area. On ELFv1, the linkage area is 48 bytes 5651 // reserved space for [SP][CR][LR][2 x unused][TOC]; on ELFv2, the linkage 5652 // area is 32 bytes reserved space for [SP][CR][LR][TOC]. 5653 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 5654 unsigned NumBytes = LinkageSize; 5655 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 5656 unsigned &QFPR_idx = FPR_idx; 5657 5658 static const MCPhysReg GPR[] = { 5659 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 5660 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 5661 }; 5662 static const MCPhysReg VR[] = { 5663 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 5664 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 5665 }; 5666 5667 const unsigned NumGPRs = array_lengthof(GPR); 5668 const unsigned NumFPRs = useSoftFloat() ? 0 : 13; 5669 const unsigned NumVRs = array_lengthof(VR); 5670 const unsigned NumQFPRs = NumFPRs; 5671 5672 // On ELFv2, we can avoid allocating the parameter area if all the arguments 5673 // can be passed to the callee in registers. 5674 // For the fast calling convention, there is another check below. 5675 // Note: We should keep consistent with LowerFormalArguments_64SVR4() 5676 bool HasParameterArea = !isELFv2ABI || isVarArg || CallConv == CallingConv::Fast; 5677 if (!HasParameterArea) { 5678 unsigned ParamAreaSize = NumGPRs * PtrByteSize; 5679 unsigned AvailableFPRs = NumFPRs; 5680 unsigned AvailableVRs = NumVRs; 5681 unsigned NumBytesTmp = NumBytes; 5682 for (unsigned i = 0; i != NumOps; ++i) { 5683 if (Outs[i].Flags.isNest()) continue; 5684 if (CalculateStackSlotUsed(Outs[i].VT, Outs[i].ArgVT, Outs[i].Flags, 5685 PtrByteSize, LinkageSize, ParamAreaSize, 5686 NumBytesTmp, AvailableFPRs, AvailableVRs, 5687 Subtarget.hasQPX())) 5688 HasParameterArea = true; 5689 } 5690 } 5691 5692 // When using the fast calling convention, we don't provide backing for 5693 // arguments that will be in registers. 5694 unsigned NumGPRsUsed = 0, NumFPRsUsed = 0, NumVRsUsed = 0; 5695 5696 // Avoid allocating parameter area for fastcc functions if all the arguments 5697 // can be passed in the registers. 5698 if (CallConv == CallingConv::Fast) 5699 HasParameterArea = false; 5700 5701 // Add up all the space actually used. 5702 for (unsigned i = 0; i != NumOps; ++i) { 5703 ISD::ArgFlagsTy Flags = Outs[i].Flags; 5704 EVT ArgVT = Outs[i].VT; 5705 EVT OrigVT = Outs[i].ArgVT; 5706 5707 if (Flags.isNest()) 5708 continue; 5709 5710 if (CallConv == CallingConv::Fast) { 5711 if (Flags.isByVal()) { 5712 NumGPRsUsed += (Flags.getByValSize()+7)/8; 5713 if (NumGPRsUsed > NumGPRs) 5714 HasParameterArea = true; 5715 } else { 5716 switch (ArgVT.getSimpleVT().SimpleTy) { 5717 default: llvm_unreachable("Unexpected ValueType for argument!"); 5718 case MVT::i1: 5719 case MVT::i32: 5720 case MVT::i64: 5721 if (++NumGPRsUsed <= NumGPRs) 5722 continue; 5723 break; 5724 case MVT::v4i32: 5725 case MVT::v8i16: 5726 case MVT::v16i8: 5727 case MVT::v2f64: 5728 case MVT::v2i64: 5729 case MVT::v1i128: 5730 case MVT::f128: 5731 if (++NumVRsUsed <= NumVRs) 5732 continue; 5733 break; 5734 case MVT::v4f32: 5735 // When using QPX, this is handled like a FP register, otherwise, it 5736 // is an Altivec register. 5737 if (Subtarget.hasQPX()) { 5738 if (++NumFPRsUsed <= NumFPRs) 5739 continue; 5740 } else { 5741 if (++NumVRsUsed <= NumVRs) 5742 continue; 5743 } 5744 break; 5745 case MVT::f32: 5746 case MVT::f64: 5747 case MVT::v4f64: // QPX 5748 case MVT::v4i1: // QPX 5749 if (++NumFPRsUsed <= NumFPRs) 5750 continue; 5751 break; 5752 } 5753 HasParameterArea = true; 5754 } 5755 } 5756 5757 /* Respect alignment of argument on the stack. */ 5758 unsigned Align = 5759 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize); 5760 NumBytes = ((NumBytes + Align - 1) / Align) * Align; 5761 5762 NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize); 5763 if (Flags.isInConsecutiveRegsLast()) 5764 NumBytes = ((NumBytes + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 5765 } 5766 5767 unsigned NumBytesActuallyUsed = NumBytes; 5768 5769 // In the old ELFv1 ABI, 5770 // the prolog code of the callee may store up to 8 GPR argument registers to 5771 // the stack, allowing va_start to index over them in memory if its varargs. 5772 // Because we cannot tell if this is needed on the caller side, we have to 5773 // conservatively assume that it is needed. As such, make sure we have at 5774 // least enough stack space for the caller to store the 8 GPRs. 5775 // In the ELFv2 ABI, we allocate the parameter area iff a callee 5776 // really requires memory operands, e.g. a vararg function. 5777 if (HasParameterArea) 5778 NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize); 5779 else 5780 NumBytes = LinkageSize; 5781 5782 // Tail call needs the stack to be aligned. 5783 if (getTargetMachine().Options.GuaranteedTailCallOpt && 5784 CallConv == CallingConv::Fast) 5785 NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes); 5786 5787 int SPDiff = 0; 5788 5789 // Calculate by how many bytes the stack has to be adjusted in case of tail 5790 // call optimization. 5791 if (!IsSibCall) 5792 SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes); 5793 5794 // To protect arguments on the stack from being clobbered in a tail call, 5795 // force all the loads to happen before doing any other lowering. 5796 if (isTailCall) 5797 Chain = DAG.getStackArgumentTokenFactor(Chain); 5798 5799 // Adjust the stack pointer for the new arguments... 5800 // These operations are automatically eliminated by the prolog/epilog pass 5801 if (!IsSibCall) 5802 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 5803 SDValue CallSeqStart = Chain; 5804 5805 // Load the return address and frame pointer so it can be move somewhere else 5806 // later. 5807 SDValue LROp, FPOp; 5808 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl); 5809 5810 // Set up a copy of the stack pointer for use loading and storing any 5811 // arguments that may not fit in the registers available for argument 5812 // passing. 5813 SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64); 5814 5815 // Figure out which arguments are going to go in registers, and which in 5816 // memory. Also, if this is a vararg function, floating point operations 5817 // must be stored to our stack, and loaded into integer regs as well, if 5818 // any integer regs are available for argument passing. 5819 unsigned ArgOffset = LinkageSize; 5820 5821 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 5822 SmallVector<TailCallArgumentInfo, 8> TailCallArguments; 5823 5824 SmallVector<SDValue, 8> MemOpChains; 5825 for (unsigned i = 0; i != NumOps; ++i) { 5826 SDValue Arg = OutVals[i]; 5827 ISD::ArgFlagsTy Flags = Outs[i].Flags; 5828 EVT ArgVT = Outs[i].VT; 5829 EVT OrigVT = Outs[i].ArgVT; 5830 5831 // PtrOff will be used to store the current argument to the stack if a 5832 // register cannot be found for it. 5833 SDValue PtrOff; 5834 5835 // We re-align the argument offset for each argument, except when using the 5836 // fast calling convention, when we need to make sure we do that only when 5837 // we'll actually use a stack slot. 5838 auto ComputePtrOff = [&]() { 5839 /* Respect alignment of argument on the stack. */ 5840 unsigned Align = 5841 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize); 5842 ArgOffset = ((ArgOffset + Align - 1) / Align) * Align; 5843 5844 PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType()); 5845 5846 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 5847 }; 5848 5849 if (CallConv != CallingConv::Fast) { 5850 ComputePtrOff(); 5851 5852 /* Compute GPR index associated with argument offset. */ 5853 GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize; 5854 GPR_idx = std::min(GPR_idx, NumGPRs); 5855 } 5856 5857 // Promote integers to 64-bit values. 5858 if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) { 5859 // FIXME: Should this use ANY_EXTEND if neither sext nor zext? 5860 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 5861 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg); 5862 } 5863 5864 // FIXME memcpy is used way more than necessary. Correctness first. 5865 // Note: "by value" is code for passing a structure by value, not 5866 // basic types. 5867 if (Flags.isByVal()) { 5868 // Note: Size includes alignment padding, so 5869 // struct x { short a; char b; } 5870 // will have Size = 4. With #pragma pack(1), it will have Size = 3. 5871 // These are the proper values we need for right-justifying the 5872 // aggregate in a parameter register. 5873 unsigned Size = Flags.getByValSize(); 5874 5875 // An empty aggregate parameter takes up no storage and no 5876 // registers. 5877 if (Size == 0) 5878 continue; 5879 5880 if (CallConv == CallingConv::Fast) 5881 ComputePtrOff(); 5882 5883 // All aggregates smaller than 8 bytes must be passed right-justified. 5884 if (Size==1 || Size==2 || Size==4) { 5885 EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32); 5886 if (GPR_idx != NumGPRs) { 5887 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg, 5888 MachinePointerInfo(), VT); 5889 MemOpChains.push_back(Load.getValue(1)); 5890 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 5891 5892 ArgOffset += PtrByteSize; 5893 continue; 5894 } 5895 } 5896 5897 if (GPR_idx == NumGPRs && Size < 8) { 5898 SDValue AddPtr = PtrOff; 5899 if (!isLittleEndian) { 5900 SDValue Const = DAG.getConstant(PtrByteSize - Size, dl, 5901 PtrOff.getValueType()); 5902 AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const); 5903 } 5904 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr, 5905 CallSeqStart, 5906 Flags, DAG, dl); 5907 ArgOffset += PtrByteSize; 5908 continue; 5909 } 5910 // Copy entire object into memory. There are cases where gcc-generated 5911 // code assumes it is there, even if it could be put entirely into 5912 // registers. (This is not what the doc says.) 5913 5914 // FIXME: The above statement is likely due to a misunderstanding of the 5915 // documents. All arguments must be copied into the parameter area BY 5916 // THE CALLEE in the event that the callee takes the address of any 5917 // formal argument. That has not yet been implemented. However, it is 5918 // reasonable to use the stack area as a staging area for the register 5919 // load. 5920 5921 // Skip this for small aggregates, as we will use the same slot for a 5922 // right-justified copy, below. 5923 if (Size >= 8) 5924 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff, 5925 CallSeqStart, 5926 Flags, DAG, dl); 5927 5928 // When a register is available, pass a small aggregate right-justified. 5929 if (Size < 8 && GPR_idx != NumGPRs) { 5930 // The easiest way to get this right-justified in a register 5931 // is to copy the structure into the rightmost portion of a 5932 // local variable slot, then load the whole slot into the 5933 // register. 5934 // FIXME: The memcpy seems to produce pretty awful code for 5935 // small aggregates, particularly for packed ones. 5936 // FIXME: It would be preferable to use the slot in the 5937 // parameter save area instead of a new local variable. 5938 SDValue AddPtr = PtrOff; 5939 if (!isLittleEndian) { 5940 SDValue Const = DAG.getConstant(8 - Size, dl, PtrOff.getValueType()); 5941 AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const); 5942 } 5943 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr, 5944 CallSeqStart, 5945 Flags, DAG, dl); 5946 5947 // Load the slot into the register. 5948 SDValue Load = 5949 DAG.getLoad(PtrVT, dl, Chain, PtrOff, MachinePointerInfo()); 5950 MemOpChains.push_back(Load.getValue(1)); 5951 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 5952 5953 // Done with this argument. 5954 ArgOffset += PtrByteSize; 5955 continue; 5956 } 5957 5958 // For aggregates larger than PtrByteSize, copy the pieces of the 5959 // object that fit into registers from the parameter save area. 5960 for (unsigned j=0; j<Size; j+=PtrByteSize) { 5961 SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType()); 5962 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const); 5963 if (GPR_idx != NumGPRs) { 5964 SDValue Load = 5965 DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo()); 5966 MemOpChains.push_back(Load.getValue(1)); 5967 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 5968 ArgOffset += PtrByteSize; 5969 } else { 5970 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize; 5971 break; 5972 } 5973 } 5974 continue; 5975 } 5976 5977 switch (Arg.getSimpleValueType().SimpleTy) { 5978 default: llvm_unreachable("Unexpected ValueType for argument!"); 5979 case MVT::i1: 5980 case MVT::i32: 5981 case MVT::i64: 5982 if (Flags.isNest()) { 5983 // The 'nest' parameter, if any, is passed in R11. 5984 RegsToPass.push_back(std::make_pair(PPC::X11, Arg)); 5985 hasNest = true; 5986 break; 5987 } 5988 5989 // These can be scalar arguments or elements of an integer array type 5990 // passed directly. Clang may use those instead of "byval" aggregate 5991 // types to avoid forcing arguments to memory unnecessarily. 5992 if (GPR_idx != NumGPRs) { 5993 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg)); 5994 } else { 5995 if (CallConv == CallingConv::Fast) 5996 ComputePtrOff(); 5997 5998 assert(HasParameterArea && 5999 "Parameter area must exist to pass an argument in memory."); 6000 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6001 true, isTailCall, false, MemOpChains, 6002 TailCallArguments, dl); 6003 if (CallConv == CallingConv::Fast) 6004 ArgOffset += PtrByteSize; 6005 } 6006 if (CallConv != CallingConv::Fast) 6007 ArgOffset += PtrByteSize; 6008 break; 6009 case MVT::f32: 6010 case MVT::f64: { 6011 // These can be scalar arguments or elements of a float array type 6012 // passed directly. The latter are used to implement ELFv2 homogenous 6013 // float aggregates. 6014 6015 // Named arguments go into FPRs first, and once they overflow, the 6016 // remaining arguments go into GPRs and then the parameter save area. 6017 // Unnamed arguments for vararg functions always go to GPRs and 6018 // then the parameter save area. For now, put all arguments to vararg 6019 // routines always in both locations (FPR *and* GPR or stack slot). 6020 bool NeedGPROrStack = isVarArg || FPR_idx == NumFPRs; 6021 bool NeededLoad = false; 6022 6023 // First load the argument into the next available FPR. 6024 if (FPR_idx != NumFPRs) 6025 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg)); 6026 6027 // Next, load the argument into GPR or stack slot if needed. 6028 if (!NeedGPROrStack) 6029 ; 6030 else if (GPR_idx != NumGPRs && CallConv != CallingConv::Fast) { 6031 // FIXME: We may want to re-enable this for CallingConv::Fast on the P8 6032 // once we support fp <-> gpr moves. 6033 6034 // In the non-vararg case, this can only ever happen in the 6035 // presence of f32 array types, since otherwise we never run 6036 // out of FPRs before running out of GPRs. 6037 SDValue ArgVal; 6038 6039 // Double values are always passed in a single GPR. 6040 if (Arg.getValueType() != MVT::f32) { 6041 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg); 6042 6043 // Non-array float values are extended and passed in a GPR. 6044 } else if (!Flags.isInConsecutiveRegs()) { 6045 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg); 6046 ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal); 6047 6048 // If we have an array of floats, we collect every odd element 6049 // together with its predecessor into one GPR. 6050 } else if (ArgOffset % PtrByteSize != 0) { 6051 SDValue Lo, Hi; 6052 Lo = DAG.getNode(ISD::BITCAST, dl, MVT::i32, OutVals[i - 1]); 6053 Hi = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg); 6054 if (!isLittleEndian) 6055 std::swap(Lo, Hi); 6056 ArgVal = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi); 6057 6058 // The final element, if even, goes into the first half of a GPR. 6059 } else if (Flags.isInConsecutiveRegsLast()) { 6060 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg); 6061 ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal); 6062 if (!isLittleEndian) 6063 ArgVal = DAG.getNode(ISD::SHL, dl, MVT::i64, ArgVal, 6064 DAG.getConstant(32, dl, MVT::i32)); 6065 6066 // Non-final even elements are skipped; they will be handled 6067 // together the with subsequent argument on the next go-around. 6068 } else 6069 ArgVal = SDValue(); 6070 6071 if (ArgVal.getNode()) 6072 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], ArgVal)); 6073 } else { 6074 if (CallConv == CallingConv::Fast) 6075 ComputePtrOff(); 6076 6077 // Single-precision floating-point values are mapped to the 6078 // second (rightmost) word of the stack doubleword. 6079 if (Arg.getValueType() == MVT::f32 && 6080 !isLittleEndian && !Flags.isInConsecutiveRegs()) { 6081 SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType()); 6082 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour); 6083 } 6084 6085 assert(HasParameterArea && 6086 "Parameter area must exist to pass an argument in memory."); 6087 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6088 true, isTailCall, false, MemOpChains, 6089 TailCallArguments, dl); 6090 6091 NeededLoad = true; 6092 } 6093 // When passing an array of floats, the array occupies consecutive 6094 // space in the argument area; only round up to the next doubleword 6095 // at the end of the array. Otherwise, each float takes 8 bytes. 6096 if (CallConv != CallingConv::Fast || NeededLoad) { 6097 ArgOffset += (Arg.getValueType() == MVT::f32 && 6098 Flags.isInConsecutiveRegs()) ? 4 : 8; 6099 if (Flags.isInConsecutiveRegsLast()) 6100 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 6101 } 6102 break; 6103 } 6104 case MVT::v4f32: 6105 case MVT::v4i32: 6106 case MVT::v8i16: 6107 case MVT::v16i8: 6108 case MVT::v2f64: 6109 case MVT::v2i64: 6110 case MVT::v1i128: 6111 case MVT::f128: 6112 if (!Subtarget.hasQPX()) { 6113 // These can be scalar arguments or elements of a vector array type 6114 // passed directly. The latter are used to implement ELFv2 homogenous 6115 // vector aggregates. 6116 6117 // For a varargs call, named arguments go into VRs or on the stack as 6118 // usual; unnamed arguments always go to the stack or the corresponding 6119 // GPRs when within range. For now, we always put the value in both 6120 // locations (or even all three). 6121 if (isVarArg) { 6122 assert(HasParameterArea && 6123 "Parameter area must exist if we have a varargs call."); 6124 // We could elide this store in the case where the object fits 6125 // entirely in R registers. Maybe later. 6126 SDValue Store = 6127 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 6128 MemOpChains.push_back(Store); 6129 if (VR_idx != NumVRs) { 6130 SDValue Load = 6131 DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo()); 6132 MemOpChains.push_back(Load.getValue(1)); 6133 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load)); 6134 } 6135 ArgOffset += 16; 6136 for (unsigned i=0; i<16; i+=PtrByteSize) { 6137 if (GPR_idx == NumGPRs) 6138 break; 6139 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, 6140 DAG.getConstant(i, dl, PtrVT)); 6141 SDValue Load = 6142 DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo()); 6143 MemOpChains.push_back(Load.getValue(1)); 6144 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6145 } 6146 break; 6147 } 6148 6149 // Non-varargs Altivec params go into VRs or on the stack. 6150 if (VR_idx != NumVRs) { 6151 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg)); 6152 } else { 6153 if (CallConv == CallingConv::Fast) 6154 ComputePtrOff(); 6155 6156 assert(HasParameterArea && 6157 "Parameter area must exist to pass an argument in memory."); 6158 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6159 true, isTailCall, true, MemOpChains, 6160 TailCallArguments, dl); 6161 if (CallConv == CallingConv::Fast) 6162 ArgOffset += 16; 6163 } 6164 6165 if (CallConv != CallingConv::Fast) 6166 ArgOffset += 16; 6167 break; 6168 } // not QPX 6169 6170 assert(Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32 && 6171 "Invalid QPX parameter type"); 6172 6173 LLVM_FALLTHROUGH; 6174 case MVT::v4f64: 6175 case MVT::v4i1: { 6176 bool IsF32 = Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32; 6177 if (isVarArg) { 6178 assert(HasParameterArea && 6179 "Parameter area must exist if we have a varargs call."); 6180 // We could elide this store in the case where the object fits 6181 // entirely in R registers. Maybe later. 6182 SDValue Store = 6183 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 6184 MemOpChains.push_back(Store); 6185 if (QFPR_idx != NumQFPRs) { 6186 SDValue Load = DAG.getLoad(IsF32 ? MVT::v4f32 : MVT::v4f64, dl, Store, 6187 PtrOff, MachinePointerInfo()); 6188 MemOpChains.push_back(Load.getValue(1)); 6189 RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Load)); 6190 } 6191 ArgOffset += (IsF32 ? 16 : 32); 6192 for (unsigned i = 0; i < (IsF32 ? 16U : 32U); i += PtrByteSize) { 6193 if (GPR_idx == NumGPRs) 6194 break; 6195 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, 6196 DAG.getConstant(i, dl, PtrVT)); 6197 SDValue Load = 6198 DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo()); 6199 MemOpChains.push_back(Load.getValue(1)); 6200 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6201 } 6202 break; 6203 } 6204 6205 // Non-varargs QPX params go into registers or on the stack. 6206 if (QFPR_idx != NumQFPRs) { 6207 RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Arg)); 6208 } else { 6209 if (CallConv == CallingConv::Fast) 6210 ComputePtrOff(); 6211 6212 assert(HasParameterArea && 6213 "Parameter area must exist to pass an argument in memory."); 6214 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6215 true, isTailCall, true, MemOpChains, 6216 TailCallArguments, dl); 6217 if (CallConv == CallingConv::Fast) 6218 ArgOffset += (IsF32 ? 16 : 32); 6219 } 6220 6221 if (CallConv != CallingConv::Fast) 6222 ArgOffset += (IsF32 ? 16 : 32); 6223 break; 6224 } 6225 } 6226 } 6227 6228 assert((!HasParameterArea || NumBytesActuallyUsed == ArgOffset) && 6229 "mismatch in size of parameter area"); 6230 (void)NumBytesActuallyUsed; 6231 6232 if (!MemOpChains.empty()) 6233 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 6234 6235 // Check if this is an indirect call (MTCTR/BCTRL). 6236 // See PrepareCall() for more information about calls through function 6237 // pointers in the 64-bit SVR4 ABI. 6238 if (!isTailCall && !isPatchPoint && 6239 !isFunctionGlobalAddress(Callee) && 6240 !isa<ExternalSymbolSDNode>(Callee)) { 6241 // Load r2 into a virtual register and store it to the TOC save area. 6242 setUsesTOCBasePtr(DAG); 6243 SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64); 6244 // TOC save area offset. 6245 unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset(); 6246 SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl); 6247 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 6248 Chain = DAG.getStore( 6249 Val.getValue(1), dl, Val, AddPtr, 6250 MachinePointerInfo::getStack(DAG.getMachineFunction(), TOCSaveOffset)); 6251 // In the ELFv2 ABI, R12 must contain the address of an indirect callee. 6252 // This does not mean the MTCTR instruction must use R12; it's easier 6253 // to model this as an extra parameter, so do that. 6254 if (isELFv2ABI && !isPatchPoint) 6255 RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee)); 6256 } 6257 6258 // Build a sequence of copy-to-reg nodes chained together with token chain 6259 // and flag operands which copy the outgoing args into the appropriate regs. 6260 SDValue InFlag; 6261 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 6262 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 6263 RegsToPass[i].second, InFlag); 6264 InFlag = Chain.getValue(1); 6265 } 6266 6267 if (isTailCall && !IsSibCall) 6268 PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp, 6269 TailCallArguments); 6270 6271 return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint, hasNest, 6272 DAG, RegsToPass, InFlag, Chain, CallSeqStart, Callee, 6273 SPDiff, NumBytes, Ins, InVals, CS); 6274 } 6275 6276 SDValue PPCTargetLowering::LowerCall_Darwin( 6277 SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg, 6278 bool isTailCall, bool isPatchPoint, 6279 const SmallVectorImpl<ISD::OutputArg> &Outs, 6280 const SmallVectorImpl<SDValue> &OutVals, 6281 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 6282 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 6283 ImmutableCallSite CS) const { 6284 unsigned NumOps = Outs.size(); 6285 6286 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 6287 bool isPPC64 = PtrVT == MVT::i64; 6288 unsigned PtrByteSize = isPPC64 ? 8 : 4; 6289 6290 MachineFunction &MF = DAG.getMachineFunction(); 6291 6292 // Mark this function as potentially containing a function that contains a 6293 // tail call. As a consequence the frame pointer will be used for dynamicalloc 6294 // and restoring the callers stack pointer in this functions epilog. This is 6295 // done because by tail calling the called function might overwrite the value 6296 // in this function's (MF) stack pointer stack slot 0(SP). 6297 if (getTargetMachine().Options.GuaranteedTailCallOpt && 6298 CallConv == CallingConv::Fast) 6299 MF.getInfo<PPCFunctionInfo>()->setHasFastCall(); 6300 6301 // Count how many bytes are to be pushed on the stack, including the linkage 6302 // area, and parameter passing area. We start with 24/48 bytes, which is 6303 // prereserved space for [SP][CR][LR][3 x unused]. 6304 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 6305 unsigned NumBytes = LinkageSize; 6306 6307 // Add up all the space actually used. 6308 // In 32-bit non-varargs calls, Altivec parameters all go at the end; usually 6309 // they all go in registers, but we must reserve stack space for them for 6310 // possible use by the caller. In varargs or 64-bit calls, parameters are 6311 // assigned stack space in order, with padding so Altivec parameters are 6312 // 16-byte aligned. 6313 unsigned nAltivecParamsAtEnd = 0; 6314 for (unsigned i = 0; i != NumOps; ++i) { 6315 ISD::ArgFlagsTy Flags = Outs[i].Flags; 6316 EVT ArgVT = Outs[i].VT; 6317 // Varargs Altivec parameters are padded to a 16 byte boundary. 6318 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 || 6319 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 || 6320 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64) { 6321 if (!isVarArg && !isPPC64) { 6322 // Non-varargs Altivec parameters go after all the non-Altivec 6323 // parameters; handle those later so we know how much padding we need. 6324 nAltivecParamsAtEnd++; 6325 continue; 6326 } 6327 // Varargs and 64-bit Altivec parameters are padded to 16 byte boundary. 6328 NumBytes = ((NumBytes+15)/16)*16; 6329 } 6330 NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize); 6331 } 6332 6333 // Allow for Altivec parameters at the end, if needed. 6334 if (nAltivecParamsAtEnd) { 6335 NumBytes = ((NumBytes+15)/16)*16; 6336 NumBytes += 16*nAltivecParamsAtEnd; 6337 } 6338 6339 // The prolog code of the callee may store up to 8 GPR argument registers to 6340 // the stack, allowing va_start to index over them in memory if its varargs. 6341 // Because we cannot tell if this is needed on the caller side, we have to 6342 // conservatively assume that it is needed. As such, make sure we have at 6343 // least enough stack space for the caller to store the 8 GPRs. 6344 NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize); 6345 6346 // Tail call needs the stack to be aligned. 6347 if (getTargetMachine().Options.GuaranteedTailCallOpt && 6348 CallConv == CallingConv::Fast) 6349 NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes); 6350 6351 // Calculate by how many bytes the stack has to be adjusted in case of tail 6352 // call optimization. 6353 int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes); 6354 6355 // To protect arguments on the stack from being clobbered in a tail call, 6356 // force all the loads to happen before doing any other lowering. 6357 if (isTailCall) 6358 Chain = DAG.getStackArgumentTokenFactor(Chain); 6359 6360 // Adjust the stack pointer for the new arguments... 6361 // These operations are automatically eliminated by the prolog/epilog pass 6362 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 6363 SDValue CallSeqStart = Chain; 6364 6365 // Load the return address and frame pointer so it can be move somewhere else 6366 // later. 6367 SDValue LROp, FPOp; 6368 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl); 6369 6370 // Set up a copy of the stack pointer for use loading and storing any 6371 // arguments that may not fit in the registers available for argument 6372 // passing. 6373 SDValue StackPtr; 6374 if (isPPC64) 6375 StackPtr = DAG.getRegister(PPC::X1, MVT::i64); 6376 else 6377 StackPtr = DAG.getRegister(PPC::R1, MVT::i32); 6378 6379 // Figure out which arguments are going to go in registers, and which in 6380 // memory. Also, if this is a vararg function, floating point operations 6381 // must be stored to our stack, and loaded into integer regs as well, if 6382 // any integer regs are available for argument passing. 6383 unsigned ArgOffset = LinkageSize; 6384 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 6385 6386 static const MCPhysReg GPR_32[] = { // 32-bit registers. 6387 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 6388 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 6389 }; 6390 static const MCPhysReg GPR_64[] = { // 64-bit registers. 6391 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 6392 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 6393 }; 6394 static const MCPhysReg VR[] = { 6395 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 6396 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 6397 }; 6398 const unsigned NumGPRs = array_lengthof(GPR_32); 6399 const unsigned NumFPRs = 13; 6400 const unsigned NumVRs = array_lengthof(VR); 6401 6402 const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32; 6403 6404 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 6405 SmallVector<TailCallArgumentInfo, 8> TailCallArguments; 6406 6407 SmallVector<SDValue, 8> MemOpChains; 6408 for (unsigned i = 0; i != NumOps; ++i) { 6409 SDValue Arg = OutVals[i]; 6410 ISD::ArgFlagsTy Flags = Outs[i].Flags; 6411 6412 // PtrOff will be used to store the current argument to the stack if a 6413 // register cannot be found for it. 6414 SDValue PtrOff; 6415 6416 PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType()); 6417 6418 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 6419 6420 // On PPC64, promote integers to 64-bit values. 6421 if (isPPC64 && Arg.getValueType() == MVT::i32) { 6422 // FIXME: Should this use ANY_EXTEND if neither sext nor zext? 6423 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 6424 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg); 6425 } 6426 6427 // FIXME memcpy is used way more than necessary. Correctness first. 6428 // Note: "by value" is code for passing a structure by value, not 6429 // basic types. 6430 if (Flags.isByVal()) { 6431 unsigned Size = Flags.getByValSize(); 6432 // Very small objects are passed right-justified. Everything else is 6433 // passed left-justified. 6434 if (Size==1 || Size==2) { 6435 EVT VT = (Size==1) ? MVT::i8 : MVT::i16; 6436 if (GPR_idx != NumGPRs) { 6437 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg, 6438 MachinePointerInfo(), VT); 6439 MemOpChains.push_back(Load.getValue(1)); 6440 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6441 6442 ArgOffset += PtrByteSize; 6443 } else { 6444 SDValue Const = DAG.getConstant(PtrByteSize - Size, dl, 6445 PtrOff.getValueType()); 6446 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const); 6447 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr, 6448 CallSeqStart, 6449 Flags, DAG, dl); 6450 ArgOffset += PtrByteSize; 6451 } 6452 continue; 6453 } 6454 // Copy entire object into memory. There are cases where gcc-generated 6455 // code assumes it is there, even if it could be put entirely into 6456 // registers. (This is not what the doc says.) 6457 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff, 6458 CallSeqStart, 6459 Flags, DAG, dl); 6460 6461 // For small aggregates (Darwin only) and aggregates >= PtrByteSize, 6462 // copy the pieces of the object that fit into registers from the 6463 // parameter save area. 6464 for (unsigned j=0; j<Size; j+=PtrByteSize) { 6465 SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType()); 6466 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const); 6467 if (GPR_idx != NumGPRs) { 6468 SDValue Load = 6469 DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo()); 6470 MemOpChains.push_back(Load.getValue(1)); 6471 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6472 ArgOffset += PtrByteSize; 6473 } else { 6474 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize; 6475 break; 6476 } 6477 } 6478 continue; 6479 } 6480 6481 switch (Arg.getSimpleValueType().SimpleTy) { 6482 default: llvm_unreachable("Unexpected ValueType for argument!"); 6483 case MVT::i1: 6484 case MVT::i32: 6485 case MVT::i64: 6486 if (GPR_idx != NumGPRs) { 6487 if (Arg.getValueType() == MVT::i1) 6488 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, PtrVT, Arg); 6489 6490 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg)); 6491 } else { 6492 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6493 isPPC64, isTailCall, false, MemOpChains, 6494 TailCallArguments, dl); 6495 } 6496 ArgOffset += PtrByteSize; 6497 break; 6498 case MVT::f32: 6499 case MVT::f64: 6500 if (FPR_idx != NumFPRs) { 6501 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg)); 6502 6503 if (isVarArg) { 6504 SDValue Store = 6505 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 6506 MemOpChains.push_back(Store); 6507 6508 // Float varargs are always shadowed in available integer registers 6509 if (GPR_idx != NumGPRs) { 6510 SDValue Load = 6511 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo()); 6512 MemOpChains.push_back(Load.getValue(1)); 6513 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6514 } 6515 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && !isPPC64){ 6516 SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType()); 6517 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour); 6518 SDValue Load = 6519 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo()); 6520 MemOpChains.push_back(Load.getValue(1)); 6521 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6522 } 6523 } else { 6524 // If we have any FPRs remaining, we may also have GPRs remaining. 6525 // Args passed in FPRs consume either 1 (f32) or 2 (f64) available 6526 // GPRs. 6527 if (GPR_idx != NumGPRs) 6528 ++GPR_idx; 6529 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && 6530 !isPPC64) // PPC64 has 64-bit GPR's obviously :) 6531 ++GPR_idx; 6532 } 6533 } else 6534 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6535 isPPC64, isTailCall, false, MemOpChains, 6536 TailCallArguments, dl); 6537 if (isPPC64) 6538 ArgOffset += 8; 6539 else 6540 ArgOffset += Arg.getValueType() == MVT::f32 ? 4 : 8; 6541 break; 6542 case MVT::v4f32: 6543 case MVT::v4i32: 6544 case MVT::v8i16: 6545 case MVT::v16i8: 6546 if (isVarArg) { 6547 // These go aligned on the stack, or in the corresponding R registers 6548 // when within range. The Darwin PPC ABI doc claims they also go in 6549 // V registers; in fact gcc does this only for arguments that are 6550 // prototyped, not for those that match the ... We do it for all 6551 // arguments, seems to work. 6552 while (ArgOffset % 16 !=0) { 6553 ArgOffset += PtrByteSize; 6554 if (GPR_idx != NumGPRs) 6555 GPR_idx++; 6556 } 6557 // We could elide this store in the case where the object fits 6558 // entirely in R registers. Maybe later. 6559 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, 6560 DAG.getConstant(ArgOffset, dl, PtrVT)); 6561 SDValue Store = 6562 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 6563 MemOpChains.push_back(Store); 6564 if (VR_idx != NumVRs) { 6565 SDValue Load = 6566 DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo()); 6567 MemOpChains.push_back(Load.getValue(1)); 6568 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load)); 6569 } 6570 ArgOffset += 16; 6571 for (unsigned i=0; i<16; i+=PtrByteSize) { 6572 if (GPR_idx == NumGPRs) 6573 break; 6574 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, 6575 DAG.getConstant(i, dl, PtrVT)); 6576 SDValue Load = 6577 DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo()); 6578 MemOpChains.push_back(Load.getValue(1)); 6579 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6580 } 6581 break; 6582 } 6583 6584 // Non-varargs Altivec params generally go in registers, but have 6585 // stack space allocated at the end. 6586 if (VR_idx != NumVRs) { 6587 // Doesn't have GPR space allocated. 6588 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg)); 6589 } else if (nAltivecParamsAtEnd==0) { 6590 // We are emitting Altivec params in order. 6591 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6592 isPPC64, isTailCall, true, MemOpChains, 6593 TailCallArguments, dl); 6594 ArgOffset += 16; 6595 } 6596 break; 6597 } 6598 } 6599 // If all Altivec parameters fit in registers, as they usually do, 6600 // they get stack space following the non-Altivec parameters. We 6601 // don't track this here because nobody below needs it. 6602 // If there are more Altivec parameters than fit in registers emit 6603 // the stores here. 6604 if (!isVarArg && nAltivecParamsAtEnd > NumVRs) { 6605 unsigned j = 0; 6606 // Offset is aligned; skip 1st 12 params which go in V registers. 6607 ArgOffset = ((ArgOffset+15)/16)*16; 6608 ArgOffset += 12*16; 6609 for (unsigned i = 0; i != NumOps; ++i) { 6610 SDValue Arg = OutVals[i]; 6611 EVT ArgType = Outs[i].VT; 6612 if (ArgType==MVT::v4f32 || ArgType==MVT::v4i32 || 6613 ArgType==MVT::v8i16 || ArgType==MVT::v16i8) { 6614 if (++j > NumVRs) { 6615 SDValue PtrOff; 6616 // We are emitting Altivec params in order. 6617 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6618 isPPC64, isTailCall, true, MemOpChains, 6619 TailCallArguments, dl); 6620 ArgOffset += 16; 6621 } 6622 } 6623 } 6624 } 6625 6626 if (!MemOpChains.empty()) 6627 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 6628 6629 // On Darwin, R12 must contain the address of an indirect callee. This does 6630 // not mean the MTCTR instruction must use R12; it's easier to model this as 6631 // an extra parameter, so do that. 6632 if (!isTailCall && 6633 !isFunctionGlobalAddress(Callee) && 6634 !isa<ExternalSymbolSDNode>(Callee) && 6635 !isBLACompatibleAddress(Callee, DAG)) 6636 RegsToPass.push_back(std::make_pair((unsigned)(isPPC64 ? PPC::X12 : 6637 PPC::R12), Callee)); 6638 6639 // Build a sequence of copy-to-reg nodes chained together with token chain 6640 // and flag operands which copy the outgoing args into the appropriate regs. 6641 SDValue InFlag; 6642 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 6643 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 6644 RegsToPass[i].second, InFlag); 6645 InFlag = Chain.getValue(1); 6646 } 6647 6648 if (isTailCall) 6649 PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp, 6650 TailCallArguments); 6651 6652 return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint, 6653 /* unused except on PPC64 ELFv1 */ false, DAG, 6654 RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff, 6655 NumBytes, Ins, InVals, CS); 6656 } 6657 6658 6659 SDValue PPCTargetLowering::LowerCall_AIX( 6660 SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg, 6661 bool isTailCall, bool isPatchPoint, 6662 const SmallVectorImpl<ISD::OutputArg> &Outs, 6663 const SmallVectorImpl<SDValue> &OutVals, 6664 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 6665 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 6666 ImmutableCallSite CS) const { 6667 6668 assert((CallConv == CallingConv::C || CallConv == CallingConv::Fast) && 6669 "Unimplemented calling convention!"); 6670 if (isVarArg || isPatchPoint) 6671 report_fatal_error("This call type is unimplemented on AIX."); 6672 6673 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 6674 bool isPPC64 = PtrVT == MVT::i64; 6675 unsigned PtrByteSize = isPPC64 ? 8 : 4; 6676 unsigned NumOps = Outs.size(); 6677 6678 6679 // Count how many bytes are to be pushed on the stack, including the linkage 6680 // area, parameter list area. 6681 // On XCOFF, we start with 24/48, which is reserved space for 6682 // [SP][CR][LR][2 x reserved][TOC]. 6683 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 6684 6685 // The prolog code of the callee may store up to 8 GPR argument registers to 6686 // the stack, allowing va_start to index over them in memory if the callee 6687 // is variadic. 6688 // Because we cannot tell if this is needed on the caller side, we have to 6689 // conservatively assume that it is needed. As such, make sure we have at 6690 // least enough stack space for the caller to store the 8 GPRs. 6691 unsigned NumBytes = LinkageSize + 8 * PtrByteSize; 6692 6693 // Adjust the stack pointer for the new arguments... 6694 // These operations are automatically eliminated by the prolog/epilog 6695 // inserter pass. 6696 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 6697 SDValue CallSeqStart = Chain; 6698 6699 static const MCPhysReg GPR_32[] = { // 32-bit registers. 6700 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 6701 PPC::R7, PPC::R8, PPC::R9, PPC::R10 6702 }; 6703 static const MCPhysReg GPR_64[] = { // 64-bit registers. 6704 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 6705 PPC::X7, PPC::X8, PPC::X9, PPC::X10 6706 }; 6707 6708 const unsigned NumGPRs = isPPC64 ? array_lengthof(GPR_64) 6709 : array_lengthof(GPR_32); 6710 const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32; 6711 unsigned GPR_idx = 0; 6712 6713 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 6714 6715 if (isTailCall) 6716 report_fatal_error("Handling of tail call is unimplemented!"); 6717 int SPDiff = 0; 6718 6719 for (unsigned i = 0; i != NumOps; ++i) { 6720 SDValue Arg = OutVals[i]; 6721 ISD::ArgFlagsTy Flags = Outs[i].Flags; 6722 6723 // Promote integers if needed. 6724 if (Arg.getValueType() == MVT::i1 || 6725 (isPPC64 && Arg.getValueType() == MVT::i32)) { 6726 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 6727 Arg = DAG.getNode(ExtOp, dl, PtrVT, Arg); 6728 } 6729 6730 // Note: "by value" is code for passing a structure by value, not 6731 // basic types. 6732 if (Flags.isByVal()) 6733 report_fatal_error("Passing structure by value is unimplemented!"); 6734 6735 switch (Arg.getSimpleValueType().SimpleTy) { 6736 default: llvm_unreachable("Unexpected ValueType for argument!"); 6737 case MVT::i1: 6738 case MVT::i32: 6739 case MVT::i64: 6740 if (GPR_idx != NumGPRs) 6741 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg)); 6742 else 6743 report_fatal_error("Handling of placing parameters on the stack is " 6744 "unimplemented!"); 6745 break; 6746 case MVT::f32: 6747 case MVT::f64: 6748 case MVT::v4f32: 6749 case MVT::v4i32: 6750 case MVT::v8i16: 6751 case MVT::v16i8: 6752 case MVT::v2f64: 6753 case MVT::v2i64: 6754 case MVT::v1i128: 6755 case MVT::f128: 6756 case MVT::v4f64: 6757 case MVT::v4i1: 6758 report_fatal_error("Handling of this parameter type is unimplemented!"); 6759 } 6760 } 6761 6762 if (!isFunctionGlobalAddress(Callee) && 6763 !isa<ExternalSymbolSDNode>(Callee)) 6764 report_fatal_error("Handling of indirect call is unimplemented!"); 6765 6766 // Build a sequence of copy-to-reg nodes chained together with token chain 6767 // and flag operands which copy the outgoing args into the appropriate regs. 6768 SDValue InFlag; 6769 for (auto Reg : RegsToPass) { 6770 Chain = DAG.getCopyToReg(Chain, dl, Reg.first, Reg.second, InFlag); 6771 InFlag = Chain.getValue(1); 6772 } 6773 6774 return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint, 6775 /* unused except on PPC64 ELFv1 */ false, DAG, 6776 RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff, 6777 NumBytes, Ins, InVals, CS); 6778 } 6779 6780 bool 6781 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv, 6782 MachineFunction &MF, bool isVarArg, 6783 const SmallVectorImpl<ISD::OutputArg> &Outs, 6784 LLVMContext &Context) const { 6785 SmallVector<CCValAssign, 16> RVLocs; 6786 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context); 6787 return CCInfo.CheckReturn( 6788 Outs, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold) 6789 ? RetCC_PPC_Cold 6790 : RetCC_PPC); 6791 } 6792 6793 SDValue 6794 PPCTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 6795 bool isVarArg, 6796 const SmallVectorImpl<ISD::OutputArg> &Outs, 6797 const SmallVectorImpl<SDValue> &OutVals, 6798 const SDLoc &dl, SelectionDAG &DAG) const { 6799 SmallVector<CCValAssign, 16> RVLocs; 6800 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 6801 *DAG.getContext()); 6802 CCInfo.AnalyzeReturn(Outs, 6803 (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold) 6804 ? RetCC_PPC_Cold 6805 : RetCC_PPC); 6806 6807 SDValue Flag; 6808 SmallVector<SDValue, 4> RetOps(1, Chain); 6809 6810 // Copy the result values into the output registers. 6811 for (unsigned i = 0, RealResIdx = 0; i != RVLocs.size(); ++i, ++RealResIdx) { 6812 CCValAssign &VA = RVLocs[i]; 6813 assert(VA.isRegLoc() && "Can only return in registers!"); 6814 6815 SDValue Arg = OutVals[RealResIdx]; 6816 6817 switch (VA.getLocInfo()) { 6818 default: llvm_unreachable("Unknown loc info!"); 6819 case CCValAssign::Full: break; 6820 case CCValAssign::AExt: 6821 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg); 6822 break; 6823 case CCValAssign::ZExt: 6824 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg); 6825 break; 6826 case CCValAssign::SExt: 6827 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg); 6828 break; 6829 } 6830 if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) { 6831 bool isLittleEndian = Subtarget.isLittleEndian(); 6832 // Legalize ret f64 -> ret 2 x i32. 6833 SDValue SVal = 6834 DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg, 6835 DAG.getIntPtrConstant(isLittleEndian ? 0 : 1, dl)); 6836 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Flag); 6837 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 6838 SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg, 6839 DAG.getIntPtrConstant(isLittleEndian ? 1 : 0, dl)); 6840 Flag = Chain.getValue(1); 6841 VA = RVLocs[++i]; // skip ahead to next loc 6842 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Flag); 6843 } else 6844 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag); 6845 Flag = Chain.getValue(1); 6846 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 6847 } 6848 6849 const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo(); 6850 const MCPhysReg *I = 6851 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction()); 6852 if (I) { 6853 for (; *I; ++I) { 6854 6855 if (PPC::G8RCRegClass.contains(*I)) 6856 RetOps.push_back(DAG.getRegister(*I, MVT::i64)); 6857 else if (PPC::F8RCRegClass.contains(*I)) 6858 RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64))); 6859 else if (PPC::CRRCRegClass.contains(*I)) 6860 RetOps.push_back(DAG.getRegister(*I, MVT::i1)); 6861 else if (PPC::VRRCRegClass.contains(*I)) 6862 RetOps.push_back(DAG.getRegister(*I, MVT::Other)); 6863 else 6864 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 6865 } 6866 } 6867 6868 RetOps[0] = Chain; // Update chain. 6869 6870 // Add the flag if we have it. 6871 if (Flag.getNode()) 6872 RetOps.push_back(Flag); 6873 6874 return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, RetOps); 6875 } 6876 6877 SDValue 6878 PPCTargetLowering::LowerGET_DYNAMIC_AREA_OFFSET(SDValue Op, 6879 SelectionDAG &DAG) const { 6880 SDLoc dl(Op); 6881 6882 // Get the correct type for integers. 6883 EVT IntVT = Op.getValueType(); 6884 6885 // Get the inputs. 6886 SDValue Chain = Op.getOperand(0); 6887 SDValue FPSIdx = getFramePointerFrameIndex(DAG); 6888 // Build a DYNAREAOFFSET node. 6889 SDValue Ops[2] = {Chain, FPSIdx}; 6890 SDVTList VTs = DAG.getVTList(IntVT); 6891 return DAG.getNode(PPCISD::DYNAREAOFFSET, dl, VTs, Ops); 6892 } 6893 6894 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op, 6895 SelectionDAG &DAG) const { 6896 // When we pop the dynamic allocation we need to restore the SP link. 6897 SDLoc dl(Op); 6898 6899 // Get the correct type for pointers. 6900 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 6901 6902 // Construct the stack pointer operand. 6903 bool isPPC64 = Subtarget.isPPC64(); 6904 unsigned SP = isPPC64 ? PPC::X1 : PPC::R1; 6905 SDValue StackPtr = DAG.getRegister(SP, PtrVT); 6906 6907 // Get the operands for the STACKRESTORE. 6908 SDValue Chain = Op.getOperand(0); 6909 SDValue SaveSP = Op.getOperand(1); 6910 6911 // Load the old link SP. 6912 SDValue LoadLinkSP = 6913 DAG.getLoad(PtrVT, dl, Chain, StackPtr, MachinePointerInfo()); 6914 6915 // Restore the stack pointer. 6916 Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP); 6917 6918 // Store the old link SP. 6919 return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo()); 6920 } 6921 6922 SDValue PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG &DAG) const { 6923 MachineFunction &MF = DAG.getMachineFunction(); 6924 bool isPPC64 = Subtarget.isPPC64(); 6925 EVT PtrVT = getPointerTy(MF.getDataLayout()); 6926 6927 // Get current frame pointer save index. The users of this index will be 6928 // primarily DYNALLOC instructions. 6929 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>(); 6930 int RASI = FI->getReturnAddrSaveIndex(); 6931 6932 // If the frame pointer save index hasn't been defined yet. 6933 if (!RASI) { 6934 // Find out what the fix offset of the frame pointer save area. 6935 int LROffset = Subtarget.getFrameLowering()->getReturnSaveOffset(); 6936 // Allocate the frame index for frame pointer save area. 6937 RASI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, LROffset, false); 6938 // Save the result. 6939 FI->setReturnAddrSaveIndex(RASI); 6940 } 6941 return DAG.getFrameIndex(RASI, PtrVT); 6942 } 6943 6944 SDValue 6945 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const { 6946 MachineFunction &MF = DAG.getMachineFunction(); 6947 bool isPPC64 = Subtarget.isPPC64(); 6948 EVT PtrVT = getPointerTy(MF.getDataLayout()); 6949 6950 // Get current frame pointer save index. The users of this index will be 6951 // primarily DYNALLOC instructions. 6952 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>(); 6953 int FPSI = FI->getFramePointerSaveIndex(); 6954 6955 // If the frame pointer save index hasn't been defined yet. 6956 if (!FPSI) { 6957 // Find out what the fix offset of the frame pointer save area. 6958 int FPOffset = Subtarget.getFrameLowering()->getFramePointerSaveOffset(); 6959 // Allocate the frame index for frame pointer save area. 6960 FPSI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, FPOffset, true); 6961 // Save the result. 6962 FI->setFramePointerSaveIndex(FPSI); 6963 } 6964 return DAG.getFrameIndex(FPSI, PtrVT); 6965 } 6966 6967 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, 6968 SelectionDAG &DAG) const { 6969 // Get the inputs. 6970 SDValue Chain = Op.getOperand(0); 6971 SDValue Size = Op.getOperand(1); 6972 SDLoc dl(Op); 6973 6974 // Get the correct type for pointers. 6975 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 6976 // Negate the size. 6977 SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT, 6978 DAG.getConstant(0, dl, PtrVT), Size); 6979 // Construct a node for the frame pointer save index. 6980 SDValue FPSIdx = getFramePointerFrameIndex(DAG); 6981 // Build a DYNALLOC node. 6982 SDValue Ops[3] = { Chain, NegSize, FPSIdx }; 6983 SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other); 6984 return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops); 6985 } 6986 6987 SDValue PPCTargetLowering::LowerEH_DWARF_CFA(SDValue Op, 6988 SelectionDAG &DAG) const { 6989 MachineFunction &MF = DAG.getMachineFunction(); 6990 6991 bool isPPC64 = Subtarget.isPPC64(); 6992 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 6993 6994 int FI = MF.getFrameInfo().CreateFixedObject(isPPC64 ? 8 : 4, 0, false); 6995 return DAG.getFrameIndex(FI, PtrVT); 6996 } 6997 6998 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op, 6999 SelectionDAG &DAG) const { 7000 SDLoc DL(Op); 7001 return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL, 7002 DAG.getVTList(MVT::i32, MVT::Other), 7003 Op.getOperand(0), Op.getOperand(1)); 7004 } 7005 7006 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op, 7007 SelectionDAG &DAG) const { 7008 SDLoc DL(Op); 7009 return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other, 7010 Op.getOperand(0), Op.getOperand(1)); 7011 } 7012 7013 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const { 7014 if (Op.getValueType().isVector()) 7015 return LowerVectorLoad(Op, DAG); 7016 7017 assert(Op.getValueType() == MVT::i1 && 7018 "Custom lowering only for i1 loads"); 7019 7020 // First, load 8 bits into 32 bits, then truncate to 1 bit. 7021 7022 SDLoc dl(Op); 7023 LoadSDNode *LD = cast<LoadSDNode>(Op); 7024 7025 SDValue Chain = LD->getChain(); 7026 SDValue BasePtr = LD->getBasePtr(); 7027 MachineMemOperand *MMO = LD->getMemOperand(); 7028 7029 SDValue NewLD = 7030 DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(DAG.getDataLayout()), Chain, 7031 BasePtr, MVT::i8, MMO); 7032 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD); 7033 7034 SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) }; 7035 return DAG.getMergeValues(Ops, dl); 7036 } 7037 7038 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const { 7039 if (Op.getOperand(1).getValueType().isVector()) 7040 return LowerVectorStore(Op, DAG); 7041 7042 assert(Op.getOperand(1).getValueType() == MVT::i1 && 7043 "Custom lowering only for i1 stores"); 7044 7045 // First, zero extend to 32 bits, then use a truncating store to 8 bits. 7046 7047 SDLoc dl(Op); 7048 StoreSDNode *ST = cast<StoreSDNode>(Op); 7049 7050 SDValue Chain = ST->getChain(); 7051 SDValue BasePtr = ST->getBasePtr(); 7052 SDValue Value = ST->getValue(); 7053 MachineMemOperand *MMO = ST->getMemOperand(); 7054 7055 Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(DAG.getDataLayout()), 7056 Value); 7057 return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO); 7058 } 7059 7060 // FIXME: Remove this once the ANDI glue bug is fixed: 7061 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const { 7062 assert(Op.getValueType() == MVT::i1 && 7063 "Custom lowering only for i1 results"); 7064 7065 SDLoc DL(Op); 7066 return DAG.getNode(PPCISD::ANDIo_1_GT_BIT, DL, MVT::i1, 7067 Op.getOperand(0)); 7068 } 7069 7070 SDValue PPCTargetLowering::LowerTRUNCATEVector(SDValue Op, 7071 SelectionDAG &DAG) const { 7072 7073 // Implements a vector truncate that fits in a vector register as a shuffle. 7074 // We want to legalize vector truncates down to where the source fits in 7075 // a vector register (and target is therefore smaller than vector register 7076 // size). At that point legalization will try to custom lower the sub-legal 7077 // result and get here - where we can contain the truncate as a single target 7078 // operation. 7079 7080 // For example a trunc <2 x i16> to <2 x i8> could be visualized as follows: 7081 // <MSB1|LSB1, MSB2|LSB2> to <LSB1, LSB2> 7082 // 7083 // We will implement it for big-endian ordering as this (where x denotes 7084 // undefined): 7085 // < MSB1|LSB1, MSB2|LSB2, uu, uu, uu, uu, uu, uu> to 7086 // < LSB1, LSB2, u, u, u, u, u, u, u, u, u, u, u, u, u, u> 7087 // 7088 // The same operation in little-endian ordering will be: 7089 // <uu, uu, uu, uu, uu, uu, LSB2|MSB2, LSB1|MSB1> to 7090 // <u, u, u, u, u, u, u, u, u, u, u, u, u, u, LSB2, LSB1> 7091 7092 assert(Op.getValueType().isVector() && "Vector type expected."); 7093 7094 SDLoc DL(Op); 7095 SDValue N1 = Op.getOperand(0); 7096 unsigned SrcSize = N1.getValueType().getSizeInBits(); 7097 assert(SrcSize <= 128 && "Source must fit in an Altivec/VSX vector"); 7098 SDValue WideSrc = SrcSize == 128 ? N1 : widenVec(DAG, N1, DL); 7099 7100 EVT TrgVT = Op.getValueType(); 7101 unsigned TrgNumElts = TrgVT.getVectorNumElements(); 7102 EVT EltVT = TrgVT.getVectorElementType(); 7103 unsigned WideNumElts = 128 / EltVT.getSizeInBits(); 7104 EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts); 7105 7106 // First list the elements we want to keep. 7107 unsigned SizeMult = SrcSize / TrgVT.getSizeInBits(); 7108 SmallVector<int, 16> ShuffV; 7109 if (Subtarget.isLittleEndian()) 7110 for (unsigned i = 0; i < TrgNumElts; ++i) 7111 ShuffV.push_back(i * SizeMult); 7112 else 7113 for (unsigned i = 1; i <= TrgNumElts; ++i) 7114 ShuffV.push_back(i * SizeMult - 1); 7115 7116 // Populate the remaining elements with undefs. 7117 for (unsigned i = TrgNumElts; i < WideNumElts; ++i) 7118 // ShuffV.push_back(i + WideNumElts); 7119 ShuffV.push_back(WideNumElts + 1); 7120 7121 SDValue Conv = DAG.getNode(ISD::BITCAST, DL, WideVT, WideSrc); 7122 return DAG.getVectorShuffle(WideVT, DL, Conv, DAG.getUNDEF(WideVT), ShuffV); 7123 } 7124 7125 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when 7126 /// possible. 7127 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const { 7128 // Not FP? Not a fsel. 7129 if (!Op.getOperand(0).getValueType().isFloatingPoint() || 7130 !Op.getOperand(2).getValueType().isFloatingPoint()) 7131 return Op; 7132 7133 // We might be able to do better than this under some circumstances, but in 7134 // general, fsel-based lowering of select is a finite-math-only optimization. 7135 // For more information, see section F.3 of the 2.06 ISA specification. 7136 if (!DAG.getTarget().Options.NoInfsFPMath || 7137 !DAG.getTarget().Options.NoNaNsFPMath) 7138 return Op; 7139 // TODO: Propagate flags from the select rather than global settings. 7140 SDNodeFlags Flags; 7141 Flags.setNoInfs(true); 7142 Flags.setNoNaNs(true); 7143 7144 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get(); 7145 7146 EVT ResVT = Op.getValueType(); 7147 EVT CmpVT = Op.getOperand(0).getValueType(); 7148 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 7149 SDValue TV = Op.getOperand(2), FV = Op.getOperand(3); 7150 SDLoc dl(Op); 7151 7152 // If the RHS of the comparison is a 0.0, we don't need to do the 7153 // subtraction at all. 7154 SDValue Sel1; 7155 if (isFloatingPointZero(RHS)) 7156 switch (CC) { 7157 default: break; // SETUO etc aren't handled by fsel. 7158 case ISD::SETNE: 7159 std::swap(TV, FV); 7160 LLVM_FALLTHROUGH; 7161 case ISD::SETEQ: 7162 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits 7163 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); 7164 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV); 7165 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits 7166 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1); 7167 return DAG.getNode(PPCISD::FSEL, dl, ResVT, 7168 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV); 7169 case ISD::SETULT: 7170 case ISD::SETLT: 7171 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt 7172 LLVM_FALLTHROUGH; 7173 case ISD::SETOGE: 7174 case ISD::SETGE: 7175 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits 7176 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); 7177 return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV); 7178 case ISD::SETUGT: 7179 case ISD::SETGT: 7180 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt 7181 LLVM_FALLTHROUGH; 7182 case ISD::SETOLE: 7183 case ISD::SETLE: 7184 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits 7185 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); 7186 return DAG.getNode(PPCISD::FSEL, dl, ResVT, 7187 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV); 7188 } 7189 7190 SDValue Cmp; 7191 switch (CC) { 7192 default: break; // SETUO etc aren't handled by fsel. 7193 case ISD::SETNE: 7194 std::swap(TV, FV); 7195 LLVM_FALLTHROUGH; 7196 case ISD::SETEQ: 7197 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags); 7198 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 7199 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 7200 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); 7201 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits 7202 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1); 7203 return DAG.getNode(PPCISD::FSEL, dl, ResVT, 7204 DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV); 7205 case ISD::SETULT: 7206 case ISD::SETLT: 7207 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags); 7208 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 7209 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 7210 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV); 7211 case ISD::SETOGE: 7212 case ISD::SETGE: 7213 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags); 7214 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 7215 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 7216 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); 7217 case ISD::SETUGT: 7218 case ISD::SETGT: 7219 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags); 7220 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 7221 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 7222 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV); 7223 case ISD::SETOLE: 7224 case ISD::SETLE: 7225 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags); 7226 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 7227 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 7228 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); 7229 } 7230 return Op; 7231 } 7232 7233 void PPCTargetLowering::LowerFP_TO_INTForReuse(SDValue Op, ReuseLoadInfo &RLI, 7234 SelectionDAG &DAG, 7235 const SDLoc &dl) const { 7236 assert(Op.getOperand(0).getValueType().isFloatingPoint()); 7237 SDValue Src = Op.getOperand(0); 7238 if (Src.getValueType() == MVT::f32) 7239 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src); 7240 7241 SDValue Tmp; 7242 switch (Op.getSimpleValueType().SimpleTy) { 7243 default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!"); 7244 case MVT::i32: 7245 Tmp = DAG.getNode( 7246 Op.getOpcode() == ISD::FP_TO_SINT 7247 ? PPCISD::FCTIWZ 7248 : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ), 7249 dl, MVT::f64, Src); 7250 break; 7251 case MVT::i64: 7252 assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) && 7253 "i64 FP_TO_UINT is supported only with FPCVT"); 7254 Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ : 7255 PPCISD::FCTIDUZ, 7256 dl, MVT::f64, Src); 7257 break; 7258 } 7259 7260 // Convert the FP value to an int value through memory. 7261 bool i32Stack = Op.getValueType() == MVT::i32 && Subtarget.hasSTFIWX() && 7262 (Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()); 7263 SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64); 7264 int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex(); 7265 MachinePointerInfo MPI = 7266 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI); 7267 7268 // Emit a store to the stack slot. 7269 SDValue Chain; 7270 if (i32Stack) { 7271 MachineFunction &MF = DAG.getMachineFunction(); 7272 MachineMemOperand *MMO = 7273 MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, 4); 7274 SDValue Ops[] = { DAG.getEntryNode(), Tmp, FIPtr }; 7275 Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl, 7276 DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO); 7277 } else 7278 Chain = DAG.getStore(DAG.getEntryNode(), dl, Tmp, FIPtr, MPI); 7279 7280 // Result is a load from the stack slot. If loading 4 bytes, make sure to 7281 // add in a bias on big endian. 7282 if (Op.getValueType() == MVT::i32 && !i32Stack) { 7283 FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr, 7284 DAG.getConstant(4, dl, FIPtr.getValueType())); 7285 MPI = MPI.getWithOffset(Subtarget.isLittleEndian() ? 0 : 4); 7286 } 7287 7288 RLI.Chain = Chain; 7289 RLI.Ptr = FIPtr; 7290 RLI.MPI = MPI; 7291 } 7292 7293 /// Custom lowers floating point to integer conversions to use 7294 /// the direct move instructions available in ISA 2.07 to avoid the 7295 /// need for load/store combinations. 7296 SDValue PPCTargetLowering::LowerFP_TO_INTDirectMove(SDValue Op, 7297 SelectionDAG &DAG, 7298 const SDLoc &dl) const { 7299 assert(Op.getOperand(0).getValueType().isFloatingPoint()); 7300 SDValue Src = Op.getOperand(0); 7301 7302 if (Src.getValueType() == MVT::f32) 7303 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src); 7304 7305 SDValue Tmp; 7306 switch (Op.getSimpleValueType().SimpleTy) { 7307 default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!"); 7308 case MVT::i32: 7309 Tmp = DAG.getNode( 7310 Op.getOpcode() == ISD::FP_TO_SINT 7311 ? PPCISD::FCTIWZ 7312 : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ), 7313 dl, MVT::f64, Src); 7314 Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i32, Tmp); 7315 break; 7316 case MVT::i64: 7317 assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) && 7318 "i64 FP_TO_UINT is supported only with FPCVT"); 7319 Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ : 7320 PPCISD::FCTIDUZ, 7321 dl, MVT::f64, Src); 7322 Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i64, Tmp); 7323 break; 7324 } 7325 return Tmp; 7326 } 7327 7328 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG, 7329 const SDLoc &dl) const { 7330 7331 // FP to INT conversions are legal for f128. 7332 if (EnableQuadPrecision && (Op->getOperand(0).getValueType() == MVT::f128)) 7333 return Op; 7334 7335 // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on 7336 // PPC (the libcall is not available). 7337 if (Op.getOperand(0).getValueType() == MVT::ppcf128) { 7338 if (Op.getValueType() == MVT::i32) { 7339 if (Op.getOpcode() == ISD::FP_TO_SINT) { 7340 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, 7341 MVT::f64, Op.getOperand(0), 7342 DAG.getIntPtrConstant(0, dl)); 7343 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, 7344 MVT::f64, Op.getOperand(0), 7345 DAG.getIntPtrConstant(1, dl)); 7346 7347 // Add the two halves of the long double in round-to-zero mode. 7348 SDValue Res = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi); 7349 7350 // Now use a smaller FP_TO_SINT. 7351 return DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Res); 7352 } 7353 if (Op.getOpcode() == ISD::FP_TO_UINT) { 7354 const uint64_t TwoE31[] = {0x41e0000000000000LL, 0}; 7355 APFloat APF = APFloat(APFloat::PPCDoubleDouble(), APInt(128, TwoE31)); 7356 SDValue Tmp = DAG.getConstantFP(APF, dl, MVT::ppcf128); 7357 // X>=2^31 ? (int)(X-2^31)+0x80000000 : (int)X 7358 // FIXME: generated code sucks. 7359 // TODO: Are there fast-math-flags to propagate to this FSUB? 7360 SDValue True = DAG.getNode(ISD::FSUB, dl, MVT::ppcf128, 7361 Op.getOperand(0), Tmp); 7362 True = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, True); 7363 True = DAG.getNode(ISD::ADD, dl, MVT::i32, True, 7364 DAG.getConstant(0x80000000, dl, MVT::i32)); 7365 SDValue False = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, 7366 Op.getOperand(0)); 7367 return DAG.getSelectCC(dl, Op.getOperand(0), Tmp, True, False, 7368 ISD::SETGE); 7369 } 7370 } 7371 7372 return SDValue(); 7373 } 7374 7375 if (Subtarget.hasDirectMove() && Subtarget.isPPC64()) 7376 return LowerFP_TO_INTDirectMove(Op, DAG, dl); 7377 7378 ReuseLoadInfo RLI; 7379 LowerFP_TO_INTForReuse(Op, RLI, DAG, dl); 7380 7381 return DAG.getLoad(Op.getValueType(), dl, RLI.Chain, RLI.Ptr, RLI.MPI, 7382 RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges); 7383 } 7384 7385 // We're trying to insert a regular store, S, and then a load, L. If the 7386 // incoming value, O, is a load, we might just be able to have our load use the 7387 // address used by O. However, we don't know if anything else will store to 7388 // that address before we can load from it. To prevent this situation, we need 7389 // to insert our load, L, into the chain as a peer of O. To do this, we give L 7390 // the same chain operand as O, we create a token factor from the chain results 7391 // of O and L, and we replace all uses of O's chain result with that token 7392 // factor (see spliceIntoChain below for this last part). 7393 bool PPCTargetLowering::canReuseLoadAddress(SDValue Op, EVT MemVT, 7394 ReuseLoadInfo &RLI, 7395 SelectionDAG &DAG, 7396 ISD::LoadExtType ET) const { 7397 SDLoc dl(Op); 7398 if (ET == ISD::NON_EXTLOAD && 7399 (Op.getOpcode() == ISD::FP_TO_UINT || 7400 Op.getOpcode() == ISD::FP_TO_SINT) && 7401 isOperationLegalOrCustom(Op.getOpcode(), 7402 Op.getOperand(0).getValueType())) { 7403 7404 LowerFP_TO_INTForReuse(Op, RLI, DAG, dl); 7405 return true; 7406 } 7407 7408 LoadSDNode *LD = dyn_cast<LoadSDNode>(Op); 7409 if (!LD || LD->getExtensionType() != ET || LD->isVolatile() || 7410 LD->isNonTemporal()) 7411 return false; 7412 if (LD->getMemoryVT() != MemVT) 7413 return false; 7414 7415 RLI.Ptr = LD->getBasePtr(); 7416 if (LD->isIndexed() && !LD->getOffset().isUndef()) { 7417 assert(LD->getAddressingMode() == ISD::PRE_INC && 7418 "Non-pre-inc AM on PPC?"); 7419 RLI.Ptr = DAG.getNode(ISD::ADD, dl, RLI.Ptr.getValueType(), RLI.Ptr, 7420 LD->getOffset()); 7421 } 7422 7423 RLI.Chain = LD->getChain(); 7424 RLI.MPI = LD->getPointerInfo(); 7425 RLI.IsDereferenceable = LD->isDereferenceable(); 7426 RLI.IsInvariant = LD->isInvariant(); 7427 RLI.Alignment = LD->getAlignment(); 7428 RLI.AAInfo = LD->getAAInfo(); 7429 RLI.Ranges = LD->getRanges(); 7430 7431 RLI.ResChain = SDValue(LD, LD->isIndexed() ? 2 : 1); 7432 return true; 7433 } 7434 7435 // Given the head of the old chain, ResChain, insert a token factor containing 7436 // it and NewResChain, and make users of ResChain now be users of that token 7437 // factor. 7438 // TODO: Remove and use DAG::makeEquivalentMemoryOrdering() instead. 7439 void PPCTargetLowering::spliceIntoChain(SDValue ResChain, 7440 SDValue NewResChain, 7441 SelectionDAG &DAG) const { 7442 if (!ResChain) 7443 return; 7444 7445 SDLoc dl(NewResChain); 7446 7447 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 7448 NewResChain, DAG.getUNDEF(MVT::Other)); 7449 assert(TF.getNode() != NewResChain.getNode() && 7450 "A new TF really is required here"); 7451 7452 DAG.ReplaceAllUsesOfValueWith(ResChain, TF); 7453 DAG.UpdateNodeOperands(TF.getNode(), ResChain, NewResChain); 7454 } 7455 7456 /// Analyze profitability of direct move 7457 /// prefer float load to int load plus direct move 7458 /// when there is no integer use of int load 7459 bool PPCTargetLowering::directMoveIsProfitable(const SDValue &Op) const { 7460 SDNode *Origin = Op.getOperand(0).getNode(); 7461 if (Origin->getOpcode() != ISD::LOAD) 7462 return true; 7463 7464 // If there is no LXSIBZX/LXSIHZX, like Power8, 7465 // prefer direct move if the memory size is 1 or 2 bytes. 7466 MachineMemOperand *MMO = cast<LoadSDNode>(Origin)->getMemOperand(); 7467 if (!Subtarget.hasP9Vector() && MMO->getSize() <= 2) 7468 return true; 7469 7470 for (SDNode::use_iterator UI = Origin->use_begin(), 7471 UE = Origin->use_end(); 7472 UI != UE; ++UI) { 7473 7474 // Only look at the users of the loaded value. 7475 if (UI.getUse().get().getResNo() != 0) 7476 continue; 7477 7478 if (UI->getOpcode() != ISD::SINT_TO_FP && 7479 UI->getOpcode() != ISD::UINT_TO_FP) 7480 return true; 7481 } 7482 7483 return false; 7484 } 7485 7486 /// Custom lowers integer to floating point conversions to use 7487 /// the direct move instructions available in ISA 2.07 to avoid the 7488 /// need for load/store combinations. 7489 SDValue PPCTargetLowering::LowerINT_TO_FPDirectMove(SDValue Op, 7490 SelectionDAG &DAG, 7491 const SDLoc &dl) const { 7492 assert((Op.getValueType() == MVT::f32 || 7493 Op.getValueType() == MVT::f64) && 7494 "Invalid floating point type as target of conversion"); 7495 assert(Subtarget.hasFPCVT() && 7496 "Int to FP conversions with direct moves require FPCVT"); 7497 SDValue FP; 7498 SDValue Src = Op.getOperand(0); 7499 bool SinglePrec = Op.getValueType() == MVT::f32; 7500 bool WordInt = Src.getSimpleValueType().SimpleTy == MVT::i32; 7501 bool Signed = Op.getOpcode() == ISD::SINT_TO_FP; 7502 unsigned ConvOp = Signed ? (SinglePrec ? PPCISD::FCFIDS : PPCISD::FCFID) : 7503 (SinglePrec ? PPCISD::FCFIDUS : PPCISD::FCFIDU); 7504 7505 if (WordInt) { 7506 FP = DAG.getNode(Signed ? PPCISD::MTVSRA : PPCISD::MTVSRZ, 7507 dl, MVT::f64, Src); 7508 FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP); 7509 } 7510 else { 7511 FP = DAG.getNode(PPCISD::MTVSRA, dl, MVT::f64, Src); 7512 FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP); 7513 } 7514 7515 return FP; 7516 } 7517 7518 static SDValue widenVec(SelectionDAG &DAG, SDValue Vec, const SDLoc &dl) { 7519 7520 EVT VecVT = Vec.getValueType(); 7521 assert(VecVT.isVector() && "Expected a vector type."); 7522 assert(VecVT.getSizeInBits() < 128 && "Vector is already full width."); 7523 7524 EVT EltVT = VecVT.getVectorElementType(); 7525 unsigned WideNumElts = 128 / EltVT.getSizeInBits(); 7526 EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts); 7527 7528 unsigned NumConcat = WideNumElts / VecVT.getVectorNumElements(); 7529 SmallVector<SDValue, 16> Ops(NumConcat); 7530 Ops[0] = Vec; 7531 SDValue UndefVec = DAG.getUNDEF(VecVT); 7532 for (unsigned i = 1; i < NumConcat; ++i) 7533 Ops[i] = UndefVec; 7534 7535 return DAG.getNode(ISD::CONCAT_VECTORS, dl, WideVT, Ops); 7536 } 7537 7538 SDValue PPCTargetLowering::LowerINT_TO_FPVector(SDValue Op, SelectionDAG &DAG, 7539 const SDLoc &dl) const { 7540 7541 unsigned Opc = Op.getOpcode(); 7542 assert((Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP) && 7543 "Unexpected conversion type"); 7544 assert((Op.getValueType() == MVT::v2f64 || Op.getValueType() == MVT::v4f32) && 7545 "Supports conversions to v2f64/v4f32 only."); 7546 7547 bool SignedConv = Opc == ISD::SINT_TO_FP; 7548 bool FourEltRes = Op.getValueType() == MVT::v4f32; 7549 7550 SDValue Wide = widenVec(DAG, Op.getOperand(0), dl); 7551 EVT WideVT = Wide.getValueType(); 7552 unsigned WideNumElts = WideVT.getVectorNumElements(); 7553 MVT IntermediateVT = FourEltRes ? MVT::v4i32 : MVT::v2i64; 7554 7555 SmallVector<int, 16> ShuffV; 7556 for (unsigned i = 0; i < WideNumElts; ++i) 7557 ShuffV.push_back(i + WideNumElts); 7558 7559 int Stride = FourEltRes ? WideNumElts / 4 : WideNumElts / 2; 7560 int SaveElts = FourEltRes ? 4 : 2; 7561 if (Subtarget.isLittleEndian()) 7562 for (int i = 0; i < SaveElts; i++) 7563 ShuffV[i * Stride] = i; 7564 else 7565 for (int i = 1; i <= SaveElts; i++) 7566 ShuffV[i * Stride - 1] = i - 1; 7567 7568 SDValue ShuffleSrc2 = 7569 SignedConv ? DAG.getUNDEF(WideVT) : DAG.getConstant(0, dl, WideVT); 7570 SDValue Arrange = DAG.getVectorShuffle(WideVT, dl, Wide, ShuffleSrc2, ShuffV); 7571 unsigned ExtendOp = 7572 SignedConv ? (unsigned)PPCISD::SExtVElems : (unsigned)ISD::BITCAST; 7573 7574 SDValue Extend; 7575 if (!Subtarget.hasP9Altivec() && SignedConv) { 7576 Arrange = DAG.getBitcast(IntermediateVT, Arrange); 7577 Extend = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, IntermediateVT, Arrange, 7578 DAG.getValueType(Op.getOperand(0).getValueType())); 7579 } else 7580 Extend = DAG.getNode(ExtendOp, dl, IntermediateVT, Arrange); 7581 7582 return DAG.getNode(Opc, dl, Op.getValueType(), Extend); 7583 } 7584 7585 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op, 7586 SelectionDAG &DAG) const { 7587 SDLoc dl(Op); 7588 7589 EVT InVT = Op.getOperand(0).getValueType(); 7590 EVT OutVT = Op.getValueType(); 7591 if (OutVT.isVector() && OutVT.isFloatingPoint() && 7592 isOperationCustom(Op.getOpcode(), InVT)) 7593 return LowerINT_TO_FPVector(Op, DAG, dl); 7594 7595 // Conversions to f128 are legal. 7596 if (EnableQuadPrecision && (Op.getValueType() == MVT::f128)) 7597 return Op; 7598 7599 if (Subtarget.hasQPX() && Op.getOperand(0).getValueType() == MVT::v4i1) { 7600 if (Op.getValueType() != MVT::v4f32 && Op.getValueType() != MVT::v4f64) 7601 return SDValue(); 7602 7603 SDValue Value = Op.getOperand(0); 7604 // The values are now known to be -1 (false) or 1 (true). To convert this 7605 // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5). 7606 // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5 7607 Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value); 7608 7609 SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64); 7610 7611 Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs); 7612 7613 if (Op.getValueType() != MVT::v4f64) 7614 Value = DAG.getNode(ISD::FP_ROUND, dl, 7615 Op.getValueType(), Value, 7616 DAG.getIntPtrConstant(1, dl)); 7617 return Value; 7618 } 7619 7620 // Don't handle ppc_fp128 here; let it be lowered to a libcall. 7621 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64) 7622 return SDValue(); 7623 7624 if (Op.getOperand(0).getValueType() == MVT::i1) 7625 return DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Op.getOperand(0), 7626 DAG.getConstantFP(1.0, dl, Op.getValueType()), 7627 DAG.getConstantFP(0.0, dl, Op.getValueType())); 7628 7629 // If we have direct moves, we can do all the conversion, skip the store/load 7630 // however, without FPCVT we can't do most conversions. 7631 if (Subtarget.hasDirectMove() && directMoveIsProfitable(Op) && 7632 Subtarget.isPPC64() && Subtarget.hasFPCVT()) 7633 return LowerINT_TO_FPDirectMove(Op, DAG, dl); 7634 7635 assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) && 7636 "UINT_TO_FP is supported only with FPCVT"); 7637 7638 // If we have FCFIDS, then use it when converting to single-precision. 7639 // Otherwise, convert to double-precision and then round. 7640 unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 7641 ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS 7642 : PPCISD::FCFIDS) 7643 : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU 7644 : PPCISD::FCFID); 7645 MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 7646 ? MVT::f32 7647 : MVT::f64; 7648 7649 if (Op.getOperand(0).getValueType() == MVT::i64) { 7650 SDValue SINT = Op.getOperand(0); 7651 // When converting to single-precision, we actually need to convert 7652 // to double-precision first and then round to single-precision. 7653 // To avoid double-rounding effects during that operation, we have 7654 // to prepare the input operand. Bits that might be truncated when 7655 // converting to double-precision are replaced by a bit that won't 7656 // be lost at this stage, but is below the single-precision rounding 7657 // position. 7658 // 7659 // However, if -enable-unsafe-fp-math is in effect, accept double 7660 // rounding to avoid the extra overhead. 7661 if (Op.getValueType() == MVT::f32 && 7662 !Subtarget.hasFPCVT() && 7663 !DAG.getTarget().Options.UnsafeFPMath) { 7664 7665 // Twiddle input to make sure the low 11 bits are zero. (If this 7666 // is the case, we are guaranteed the value will fit into the 53 bit 7667 // mantissa of an IEEE double-precision value without rounding.) 7668 // If any of those low 11 bits were not zero originally, make sure 7669 // bit 12 (value 2048) is set instead, so that the final rounding 7670 // to single-precision gets the correct result. 7671 SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64, 7672 SINT, DAG.getConstant(2047, dl, MVT::i64)); 7673 Round = DAG.getNode(ISD::ADD, dl, MVT::i64, 7674 Round, DAG.getConstant(2047, dl, MVT::i64)); 7675 Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT); 7676 Round = DAG.getNode(ISD::AND, dl, MVT::i64, 7677 Round, DAG.getConstant(-2048, dl, MVT::i64)); 7678 7679 // However, we cannot use that value unconditionally: if the magnitude 7680 // of the input value is small, the bit-twiddling we did above might 7681 // end up visibly changing the output. Fortunately, in that case, we 7682 // don't need to twiddle bits since the original input will convert 7683 // exactly to double-precision floating-point already. Therefore, 7684 // construct a conditional to use the original value if the top 11 7685 // bits are all sign-bit copies, and use the rounded value computed 7686 // above otherwise. 7687 SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64, 7688 SINT, DAG.getConstant(53, dl, MVT::i32)); 7689 Cond = DAG.getNode(ISD::ADD, dl, MVT::i64, 7690 Cond, DAG.getConstant(1, dl, MVT::i64)); 7691 Cond = DAG.getSetCC(dl, MVT::i32, 7692 Cond, DAG.getConstant(1, dl, MVT::i64), ISD::SETUGT); 7693 7694 SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT); 7695 } 7696 7697 ReuseLoadInfo RLI; 7698 SDValue Bits; 7699 7700 MachineFunction &MF = DAG.getMachineFunction(); 7701 if (canReuseLoadAddress(SINT, MVT::i64, RLI, DAG)) { 7702 Bits = DAG.getLoad(MVT::f64, dl, RLI.Chain, RLI.Ptr, RLI.MPI, 7703 RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges); 7704 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG); 7705 } else if (Subtarget.hasLFIWAX() && 7706 canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::SEXTLOAD)) { 7707 MachineMemOperand *MMO = 7708 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 7709 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 7710 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 7711 Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWAX, dl, 7712 DAG.getVTList(MVT::f64, MVT::Other), 7713 Ops, MVT::i32, MMO); 7714 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG); 7715 } else if (Subtarget.hasFPCVT() && 7716 canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::ZEXTLOAD)) { 7717 MachineMemOperand *MMO = 7718 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 7719 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 7720 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 7721 Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWZX, dl, 7722 DAG.getVTList(MVT::f64, MVT::Other), 7723 Ops, MVT::i32, MMO); 7724 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG); 7725 } else if (((Subtarget.hasLFIWAX() && 7726 SINT.getOpcode() == ISD::SIGN_EXTEND) || 7727 (Subtarget.hasFPCVT() && 7728 SINT.getOpcode() == ISD::ZERO_EXTEND)) && 7729 SINT.getOperand(0).getValueType() == MVT::i32) { 7730 MachineFrameInfo &MFI = MF.getFrameInfo(); 7731 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7732 7733 int FrameIdx = MFI.CreateStackObject(4, 4, false); 7734 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 7735 7736 SDValue Store = 7737 DAG.getStore(DAG.getEntryNode(), dl, SINT.getOperand(0), FIdx, 7738 MachinePointerInfo::getFixedStack( 7739 DAG.getMachineFunction(), FrameIdx)); 7740 7741 assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 && 7742 "Expected an i32 store"); 7743 7744 RLI.Ptr = FIdx; 7745 RLI.Chain = Store; 7746 RLI.MPI = 7747 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 7748 RLI.Alignment = 4; 7749 7750 MachineMemOperand *MMO = 7751 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 7752 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 7753 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 7754 Bits = DAG.getMemIntrinsicNode(SINT.getOpcode() == ISD::ZERO_EXTEND ? 7755 PPCISD::LFIWZX : PPCISD::LFIWAX, 7756 dl, DAG.getVTList(MVT::f64, MVT::Other), 7757 Ops, MVT::i32, MMO); 7758 } else 7759 Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT); 7760 7761 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Bits); 7762 7763 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) 7764 FP = DAG.getNode(ISD::FP_ROUND, dl, 7765 MVT::f32, FP, DAG.getIntPtrConstant(0, dl)); 7766 return FP; 7767 } 7768 7769 assert(Op.getOperand(0).getValueType() == MVT::i32 && 7770 "Unhandled INT_TO_FP type in custom expander!"); 7771 // Since we only generate this in 64-bit mode, we can take advantage of 7772 // 64-bit registers. In particular, sign extend the input value into the 7773 // 64-bit register with extsw, store the WHOLE 64-bit value into the stack 7774 // then lfd it and fcfid it. 7775 MachineFunction &MF = DAG.getMachineFunction(); 7776 MachineFrameInfo &MFI = MF.getFrameInfo(); 7777 EVT PtrVT = getPointerTy(MF.getDataLayout()); 7778 7779 SDValue Ld; 7780 if (Subtarget.hasLFIWAX() || Subtarget.hasFPCVT()) { 7781 ReuseLoadInfo RLI; 7782 bool ReusingLoad; 7783 if (!(ReusingLoad = canReuseLoadAddress(Op.getOperand(0), MVT::i32, RLI, 7784 DAG))) { 7785 int FrameIdx = MFI.CreateStackObject(4, 4, false); 7786 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 7787 7788 SDValue Store = 7789 DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx, 7790 MachinePointerInfo::getFixedStack( 7791 DAG.getMachineFunction(), FrameIdx)); 7792 7793 assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 && 7794 "Expected an i32 store"); 7795 7796 RLI.Ptr = FIdx; 7797 RLI.Chain = Store; 7798 RLI.MPI = 7799 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 7800 RLI.Alignment = 4; 7801 } 7802 7803 MachineMemOperand *MMO = 7804 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 7805 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 7806 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 7807 Ld = DAG.getMemIntrinsicNode(Op.getOpcode() == ISD::UINT_TO_FP ? 7808 PPCISD::LFIWZX : PPCISD::LFIWAX, 7809 dl, DAG.getVTList(MVT::f64, MVT::Other), 7810 Ops, MVT::i32, MMO); 7811 if (ReusingLoad) 7812 spliceIntoChain(RLI.ResChain, Ld.getValue(1), DAG); 7813 } else { 7814 assert(Subtarget.isPPC64() && 7815 "i32->FP without LFIWAX supported only on PPC64"); 7816 7817 int FrameIdx = MFI.CreateStackObject(8, 8, false); 7818 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 7819 7820 SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64, 7821 Op.getOperand(0)); 7822 7823 // STD the extended value into the stack slot. 7824 SDValue Store = DAG.getStore( 7825 DAG.getEntryNode(), dl, Ext64, FIdx, 7826 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx)); 7827 7828 // Load the value as a double. 7829 Ld = DAG.getLoad( 7830 MVT::f64, dl, Store, FIdx, 7831 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx)); 7832 } 7833 7834 // FCFID it and return it. 7835 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Ld); 7836 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) 7837 FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP, 7838 DAG.getIntPtrConstant(0, dl)); 7839 return FP; 7840 } 7841 7842 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op, 7843 SelectionDAG &DAG) const { 7844 SDLoc dl(Op); 7845 /* 7846 The rounding mode is in bits 30:31 of FPSR, and has the following 7847 settings: 7848 00 Round to nearest 7849 01 Round to 0 7850 10 Round to +inf 7851 11 Round to -inf 7852 7853 FLT_ROUNDS, on the other hand, expects the following: 7854 -1 Undefined 7855 0 Round to 0 7856 1 Round to nearest 7857 2 Round to +inf 7858 3 Round to -inf 7859 7860 To perform the conversion, we do: 7861 ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1)) 7862 */ 7863 7864 MachineFunction &MF = DAG.getMachineFunction(); 7865 EVT VT = Op.getValueType(); 7866 EVT PtrVT = getPointerTy(MF.getDataLayout()); 7867 7868 // Save FP Control Word to register 7869 EVT NodeTys[] = { 7870 MVT::f64, // return register 7871 MVT::Glue // unused in this context 7872 }; 7873 SDValue Chain = DAG.getNode(PPCISD::MFFS, dl, NodeTys, None); 7874 7875 // Save FP register to stack slot 7876 int SSFI = MF.getFrameInfo().CreateStackObject(8, 8, false); 7877 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT); 7878 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Chain, StackSlot, 7879 MachinePointerInfo()); 7880 7881 // Load FP Control Word from low 32 bits of stack slot. 7882 SDValue Four = DAG.getConstant(4, dl, PtrVT); 7883 SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four); 7884 SDValue CWD = DAG.getLoad(MVT::i32, dl, Store, Addr, MachinePointerInfo()); 7885 7886 // Transform as necessary 7887 SDValue CWD1 = 7888 DAG.getNode(ISD::AND, dl, MVT::i32, 7889 CWD, DAG.getConstant(3, dl, MVT::i32)); 7890 SDValue CWD2 = 7891 DAG.getNode(ISD::SRL, dl, MVT::i32, 7892 DAG.getNode(ISD::AND, dl, MVT::i32, 7893 DAG.getNode(ISD::XOR, dl, MVT::i32, 7894 CWD, DAG.getConstant(3, dl, MVT::i32)), 7895 DAG.getConstant(3, dl, MVT::i32)), 7896 DAG.getConstant(1, dl, MVT::i32)); 7897 7898 SDValue RetVal = 7899 DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2); 7900 7901 return DAG.getNode((VT.getSizeInBits() < 16 ? 7902 ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal); 7903 } 7904 7905 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const { 7906 EVT VT = Op.getValueType(); 7907 unsigned BitWidth = VT.getSizeInBits(); 7908 SDLoc dl(Op); 7909 assert(Op.getNumOperands() == 3 && 7910 VT == Op.getOperand(1).getValueType() && 7911 "Unexpected SHL!"); 7912 7913 // Expand into a bunch of logical ops. Note that these ops 7914 // depend on the PPC behavior for oversized shift amounts. 7915 SDValue Lo = Op.getOperand(0); 7916 SDValue Hi = Op.getOperand(1); 7917 SDValue Amt = Op.getOperand(2); 7918 EVT AmtVT = Amt.getValueType(); 7919 7920 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, 7921 DAG.getConstant(BitWidth, dl, AmtVT), Amt); 7922 SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt); 7923 SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1); 7924 SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3); 7925 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, 7926 DAG.getConstant(-BitWidth, dl, AmtVT)); 7927 SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5); 7928 SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6); 7929 SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt); 7930 SDValue OutOps[] = { OutLo, OutHi }; 7931 return DAG.getMergeValues(OutOps, dl); 7932 } 7933 7934 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const { 7935 EVT VT = Op.getValueType(); 7936 SDLoc dl(Op); 7937 unsigned BitWidth = VT.getSizeInBits(); 7938 assert(Op.getNumOperands() == 3 && 7939 VT == Op.getOperand(1).getValueType() && 7940 "Unexpected SRL!"); 7941 7942 // Expand into a bunch of logical ops. Note that these ops 7943 // depend on the PPC behavior for oversized shift amounts. 7944 SDValue Lo = Op.getOperand(0); 7945 SDValue Hi = Op.getOperand(1); 7946 SDValue Amt = Op.getOperand(2); 7947 EVT AmtVT = Amt.getValueType(); 7948 7949 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, 7950 DAG.getConstant(BitWidth, dl, AmtVT), Amt); 7951 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt); 7952 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1); 7953 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3); 7954 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, 7955 DAG.getConstant(-BitWidth, dl, AmtVT)); 7956 SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5); 7957 SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6); 7958 SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt); 7959 SDValue OutOps[] = { OutLo, OutHi }; 7960 return DAG.getMergeValues(OutOps, dl); 7961 } 7962 7963 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const { 7964 SDLoc dl(Op); 7965 EVT VT = Op.getValueType(); 7966 unsigned BitWidth = VT.getSizeInBits(); 7967 assert(Op.getNumOperands() == 3 && 7968 VT == Op.getOperand(1).getValueType() && 7969 "Unexpected SRA!"); 7970 7971 // Expand into a bunch of logical ops, followed by a select_cc. 7972 SDValue Lo = Op.getOperand(0); 7973 SDValue Hi = Op.getOperand(1); 7974 SDValue Amt = Op.getOperand(2); 7975 EVT AmtVT = Amt.getValueType(); 7976 7977 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, 7978 DAG.getConstant(BitWidth, dl, AmtVT), Amt); 7979 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt); 7980 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1); 7981 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3); 7982 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, 7983 DAG.getConstant(-BitWidth, dl, AmtVT)); 7984 SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5); 7985 SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt); 7986 SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, dl, AmtVT), 7987 Tmp4, Tmp6, ISD::SETLE); 7988 SDValue OutOps[] = { OutLo, OutHi }; 7989 return DAG.getMergeValues(OutOps, dl); 7990 } 7991 7992 //===----------------------------------------------------------------------===// 7993 // Vector related lowering. 7994 // 7995 7996 /// BuildSplatI - Build a canonical splati of Val with an element size of 7997 /// SplatSize. Cast the result to VT. 7998 static SDValue BuildSplatI(int Val, unsigned SplatSize, EVT VT, 7999 SelectionDAG &DAG, const SDLoc &dl) { 8000 assert(Val >= -16 && Val <= 15 && "vsplti is out of range!"); 8001 8002 static const MVT VTys[] = { // canonical VT to use for each size. 8003 MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32 8004 }; 8005 8006 EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1]; 8007 8008 // Force vspltis[hw] -1 to vspltisb -1 to canonicalize. 8009 if (Val == -1) 8010 SplatSize = 1; 8011 8012 EVT CanonicalVT = VTys[SplatSize-1]; 8013 8014 // Build a canonical splat for this value. 8015 return DAG.getBitcast(ReqVT, DAG.getConstant(Val, dl, CanonicalVT)); 8016 } 8017 8018 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the 8019 /// specified intrinsic ID. 8020 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op, SelectionDAG &DAG, 8021 const SDLoc &dl, EVT DestVT = MVT::Other) { 8022 if (DestVT == MVT::Other) DestVT = Op.getValueType(); 8023 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 8024 DAG.getConstant(IID, dl, MVT::i32), Op); 8025 } 8026 8027 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the 8028 /// specified intrinsic ID. 8029 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS, 8030 SelectionDAG &DAG, const SDLoc &dl, 8031 EVT DestVT = MVT::Other) { 8032 if (DestVT == MVT::Other) DestVT = LHS.getValueType(); 8033 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 8034 DAG.getConstant(IID, dl, MVT::i32), LHS, RHS); 8035 } 8036 8037 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the 8038 /// specified intrinsic ID. 8039 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1, 8040 SDValue Op2, SelectionDAG &DAG, const SDLoc &dl, 8041 EVT DestVT = MVT::Other) { 8042 if (DestVT == MVT::Other) DestVT = Op0.getValueType(); 8043 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 8044 DAG.getConstant(IID, dl, MVT::i32), Op0, Op1, Op2); 8045 } 8046 8047 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified 8048 /// amount. The result has the specified value type. 8049 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt, EVT VT, 8050 SelectionDAG &DAG, const SDLoc &dl) { 8051 // Force LHS/RHS to be the right type. 8052 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS); 8053 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS); 8054 8055 int Ops[16]; 8056 for (unsigned i = 0; i != 16; ++i) 8057 Ops[i] = i + Amt; 8058 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops); 8059 return DAG.getNode(ISD::BITCAST, dl, VT, T); 8060 } 8061 8062 /// Do we have an efficient pattern in a .td file for this node? 8063 /// 8064 /// \param V - pointer to the BuildVectorSDNode being matched 8065 /// \param HasDirectMove - does this subtarget have VSR <-> GPR direct moves? 8066 /// 8067 /// There are some patterns where it is beneficial to keep a BUILD_VECTOR 8068 /// node as a BUILD_VECTOR node rather than expanding it. The patterns where 8069 /// the opposite is true (expansion is beneficial) are: 8070 /// - The node builds a vector out of integers that are not 32 or 64-bits 8071 /// - The node builds a vector out of constants 8072 /// - The node is a "load-and-splat" 8073 /// In all other cases, we will choose to keep the BUILD_VECTOR. 8074 static bool haveEfficientBuildVectorPattern(BuildVectorSDNode *V, 8075 bool HasDirectMove, 8076 bool HasP8Vector) { 8077 EVT VecVT = V->getValueType(0); 8078 bool RightType = VecVT == MVT::v2f64 || 8079 (HasP8Vector && VecVT == MVT::v4f32) || 8080 (HasDirectMove && (VecVT == MVT::v2i64 || VecVT == MVT::v4i32)); 8081 if (!RightType) 8082 return false; 8083 8084 bool IsSplat = true; 8085 bool IsLoad = false; 8086 SDValue Op0 = V->getOperand(0); 8087 8088 // This function is called in a block that confirms the node is not a constant 8089 // splat. So a constant BUILD_VECTOR here means the vector is built out of 8090 // different constants. 8091 if (V->isConstant()) 8092 return false; 8093 for (int i = 0, e = V->getNumOperands(); i < e; ++i) { 8094 if (V->getOperand(i).isUndef()) 8095 return false; 8096 // We want to expand nodes that represent load-and-splat even if the 8097 // loaded value is a floating point truncation or conversion to int. 8098 if (V->getOperand(i).getOpcode() == ISD::LOAD || 8099 (V->getOperand(i).getOpcode() == ISD::FP_ROUND && 8100 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) || 8101 (V->getOperand(i).getOpcode() == ISD::FP_TO_SINT && 8102 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) || 8103 (V->getOperand(i).getOpcode() == ISD::FP_TO_UINT && 8104 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD)) 8105 IsLoad = true; 8106 // If the operands are different or the input is not a load and has more 8107 // uses than just this BV node, then it isn't a splat. 8108 if (V->getOperand(i) != Op0 || 8109 (!IsLoad && !V->isOnlyUserOf(V->getOperand(i).getNode()))) 8110 IsSplat = false; 8111 } 8112 return !(IsSplat && IsLoad); 8113 } 8114 8115 // Lower BITCAST(f128, (build_pair i64, i64)) to BUILD_FP128. 8116 SDValue PPCTargetLowering::LowerBITCAST(SDValue Op, SelectionDAG &DAG) const { 8117 8118 SDLoc dl(Op); 8119 SDValue Op0 = Op->getOperand(0); 8120 8121 if (!EnableQuadPrecision || 8122 (Op.getValueType() != MVT::f128 ) || 8123 (Op0.getOpcode() != ISD::BUILD_PAIR) || 8124 (Op0.getOperand(0).getValueType() != MVT::i64) || 8125 (Op0.getOperand(1).getValueType() != MVT::i64)) 8126 return SDValue(); 8127 8128 return DAG.getNode(PPCISD::BUILD_FP128, dl, MVT::f128, Op0.getOperand(0), 8129 Op0.getOperand(1)); 8130 } 8131 8132 // If this is a case we can't handle, return null and let the default 8133 // expansion code take care of it. If we CAN select this case, and if it 8134 // selects to a single instruction, return Op. Otherwise, if we can codegen 8135 // this case more efficiently than a constant pool load, lower it to the 8136 // sequence of ops that should be used. 8137 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op, 8138 SelectionDAG &DAG) const { 8139 SDLoc dl(Op); 8140 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode()); 8141 assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR"); 8142 8143 if (Subtarget.hasQPX() && Op.getValueType() == MVT::v4i1) { 8144 // We first build an i32 vector, load it into a QPX register, 8145 // then convert it to a floating-point vector and compare it 8146 // to a zero vector to get the boolean result. 8147 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 8148 int FrameIdx = MFI.CreateStackObject(16, 16, false); 8149 MachinePointerInfo PtrInfo = 8150 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 8151 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 8152 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 8153 8154 assert(BVN->getNumOperands() == 4 && 8155 "BUILD_VECTOR for v4i1 does not have 4 operands"); 8156 8157 bool IsConst = true; 8158 for (unsigned i = 0; i < 4; ++i) { 8159 if (BVN->getOperand(i).isUndef()) continue; 8160 if (!isa<ConstantSDNode>(BVN->getOperand(i))) { 8161 IsConst = false; 8162 break; 8163 } 8164 } 8165 8166 if (IsConst) { 8167 Constant *One = 8168 ConstantFP::get(Type::getFloatTy(*DAG.getContext()), 1.0); 8169 Constant *NegOne = 8170 ConstantFP::get(Type::getFloatTy(*DAG.getContext()), -1.0); 8171 8172 Constant *CV[4]; 8173 for (unsigned i = 0; i < 4; ++i) { 8174 if (BVN->getOperand(i).isUndef()) 8175 CV[i] = UndefValue::get(Type::getFloatTy(*DAG.getContext())); 8176 else if (isNullConstant(BVN->getOperand(i))) 8177 CV[i] = NegOne; 8178 else 8179 CV[i] = One; 8180 } 8181 8182 Constant *CP = ConstantVector::get(CV); 8183 SDValue CPIdx = DAG.getConstantPool(CP, getPointerTy(DAG.getDataLayout()), 8184 16 /* alignment */); 8185 8186 SDValue Ops[] = {DAG.getEntryNode(), CPIdx}; 8187 SDVTList VTs = DAG.getVTList({MVT::v4i1, /*chain*/ MVT::Other}); 8188 return DAG.getMemIntrinsicNode( 8189 PPCISD::QVLFSb, dl, VTs, Ops, MVT::v4f32, 8190 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 8191 } 8192 8193 SmallVector<SDValue, 4> Stores; 8194 for (unsigned i = 0; i < 4; ++i) { 8195 if (BVN->getOperand(i).isUndef()) continue; 8196 8197 unsigned Offset = 4*i; 8198 SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType()); 8199 Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx); 8200 8201 unsigned StoreSize = BVN->getOperand(i).getValueType().getStoreSize(); 8202 if (StoreSize > 4) { 8203 Stores.push_back( 8204 DAG.getTruncStore(DAG.getEntryNode(), dl, BVN->getOperand(i), Idx, 8205 PtrInfo.getWithOffset(Offset), MVT::i32)); 8206 } else { 8207 SDValue StoreValue = BVN->getOperand(i); 8208 if (StoreSize < 4) 8209 StoreValue = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, StoreValue); 8210 8211 Stores.push_back(DAG.getStore(DAG.getEntryNode(), dl, StoreValue, Idx, 8212 PtrInfo.getWithOffset(Offset))); 8213 } 8214 } 8215 8216 SDValue StoreChain; 8217 if (!Stores.empty()) 8218 StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores); 8219 else 8220 StoreChain = DAG.getEntryNode(); 8221 8222 // Now load from v4i32 into the QPX register; this will extend it to 8223 // v4i64 but not yet convert it to a floating point. Nevertheless, this 8224 // is typed as v4f64 because the QPX register integer states are not 8225 // explicitly represented. 8226 8227 SDValue Ops[] = {StoreChain, 8228 DAG.getConstant(Intrinsic::ppc_qpx_qvlfiwz, dl, MVT::i32), 8229 FIdx}; 8230 SDVTList VTs = DAG.getVTList({MVT::v4f64, /*chain*/ MVT::Other}); 8231 8232 SDValue LoadedVect = DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, 8233 dl, VTs, Ops, MVT::v4i32, PtrInfo); 8234 LoadedVect = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64, 8235 DAG.getConstant(Intrinsic::ppc_qpx_qvfcfidu, dl, MVT::i32), 8236 LoadedVect); 8237 8238 SDValue FPZeros = DAG.getConstantFP(0.0, dl, MVT::v4f64); 8239 8240 return DAG.getSetCC(dl, MVT::v4i1, LoadedVect, FPZeros, ISD::SETEQ); 8241 } 8242 8243 // All other QPX vectors are handled by generic code. 8244 if (Subtarget.hasQPX()) 8245 return SDValue(); 8246 8247 // Check if this is a splat of a constant value. 8248 APInt APSplatBits, APSplatUndef; 8249 unsigned SplatBitSize; 8250 bool HasAnyUndefs; 8251 if (! BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize, 8252 HasAnyUndefs, 0, !Subtarget.isLittleEndian()) || 8253 SplatBitSize > 32) { 8254 // BUILD_VECTOR nodes that are not constant splats of up to 32-bits can be 8255 // lowered to VSX instructions under certain conditions. 8256 // Without VSX, there is no pattern more efficient than expanding the node. 8257 if (Subtarget.hasVSX() && 8258 haveEfficientBuildVectorPattern(BVN, Subtarget.hasDirectMove(), 8259 Subtarget.hasP8Vector())) 8260 return Op; 8261 return SDValue(); 8262 } 8263 8264 unsigned SplatBits = APSplatBits.getZExtValue(); 8265 unsigned SplatUndef = APSplatUndef.getZExtValue(); 8266 unsigned SplatSize = SplatBitSize / 8; 8267 8268 // First, handle single instruction cases. 8269 8270 // All zeros? 8271 if (SplatBits == 0) { 8272 // Canonicalize all zero vectors to be v4i32. 8273 if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) { 8274 SDValue Z = DAG.getConstant(0, dl, MVT::v4i32); 8275 Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z); 8276 } 8277 return Op; 8278 } 8279 8280 // We have XXSPLTIB for constant splats one byte wide 8281 if (Subtarget.hasP9Vector() && SplatSize == 1) { 8282 // This is a splat of 1-byte elements with some elements potentially undef. 8283 // Rather than trying to match undef in the SDAG patterns, ensure that all 8284 // elements are the same constant. 8285 if (HasAnyUndefs || ISD::isBuildVectorAllOnes(BVN)) { 8286 SmallVector<SDValue, 16> Ops(16, DAG.getConstant(SplatBits, 8287 dl, MVT::i32)); 8288 SDValue NewBV = DAG.getBuildVector(MVT::v16i8, dl, Ops); 8289 if (Op.getValueType() != MVT::v16i8) 8290 return DAG.getBitcast(Op.getValueType(), NewBV); 8291 return NewBV; 8292 } 8293 8294 // BuildVectorSDNode::isConstantSplat() is actually pretty smart. It'll 8295 // detect that constant splats like v8i16: 0xABAB are really just splats 8296 // of a 1-byte constant. In this case, we need to convert the node to a 8297 // splat of v16i8 and a bitcast. 8298 if (Op.getValueType() != MVT::v16i8) 8299 return DAG.getBitcast(Op.getValueType(), 8300 DAG.getConstant(SplatBits, dl, MVT::v16i8)); 8301 8302 return Op; 8303 } 8304 8305 // If the sign extended value is in the range [-16,15], use VSPLTI[bhw]. 8306 int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >> 8307 (32-SplatBitSize)); 8308 if (SextVal >= -16 && SextVal <= 15) 8309 return BuildSplatI(SextVal, SplatSize, Op.getValueType(), DAG, dl); 8310 8311 // Two instruction sequences. 8312 8313 // If this value is in the range [-32,30] and is even, use: 8314 // VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2) 8315 // If this value is in the range [17,31] and is odd, use: 8316 // VSPLTI[bhw](val-16) - VSPLTI[bhw](-16) 8317 // If this value is in the range [-31,-17] and is odd, use: 8318 // VSPLTI[bhw](val+16) + VSPLTI[bhw](-16) 8319 // Note the last two are three-instruction sequences. 8320 if (SextVal >= -32 && SextVal <= 31) { 8321 // To avoid having these optimizations undone by constant folding, 8322 // we convert to a pseudo that will be expanded later into one of 8323 // the above forms. 8324 SDValue Elt = DAG.getConstant(SextVal, dl, MVT::i32); 8325 EVT VT = (SplatSize == 1 ? MVT::v16i8 : 8326 (SplatSize == 2 ? MVT::v8i16 : MVT::v4i32)); 8327 SDValue EltSize = DAG.getConstant(SplatSize, dl, MVT::i32); 8328 SDValue RetVal = DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize); 8329 if (VT == Op.getValueType()) 8330 return RetVal; 8331 else 8332 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), RetVal); 8333 } 8334 8335 // If this is 0x8000_0000 x 4, turn into vspltisw + vslw. If it is 8336 // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000). This is important 8337 // for fneg/fabs. 8338 if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) { 8339 // Make -1 and vspltisw -1: 8340 SDValue OnesV = BuildSplatI(-1, 4, MVT::v4i32, DAG, dl); 8341 8342 // Make the VSLW intrinsic, computing 0x8000_0000. 8343 SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV, 8344 OnesV, DAG, dl); 8345 8346 // xor by OnesV to invert it. 8347 Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV); 8348 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 8349 } 8350 8351 // Check to see if this is a wide variety of vsplti*, binop self cases. 8352 static const signed char SplatCsts[] = { 8353 -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7, 8354 -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16 8355 }; 8356 8357 for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) { 8358 // Indirect through the SplatCsts array so that we favor 'vsplti -1' for 8359 // cases which are ambiguous (e.g. formation of 0x8000_0000). 'vsplti -1' 8360 int i = SplatCsts[idx]; 8361 8362 // Figure out what shift amount will be used by altivec if shifted by i in 8363 // this splat size. 8364 unsigned TypeShiftAmt = i & (SplatBitSize-1); 8365 8366 // vsplti + shl self. 8367 if (SextVal == (int)((unsigned)i << TypeShiftAmt)) { 8368 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl); 8369 static const unsigned IIDs[] = { // Intrinsic to use for each size. 8370 Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0, 8371 Intrinsic::ppc_altivec_vslw 8372 }; 8373 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 8374 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 8375 } 8376 8377 // vsplti + srl self. 8378 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) { 8379 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl); 8380 static const unsigned IIDs[] = { // Intrinsic to use for each size. 8381 Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0, 8382 Intrinsic::ppc_altivec_vsrw 8383 }; 8384 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 8385 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 8386 } 8387 8388 // vsplti + sra self. 8389 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) { 8390 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl); 8391 static const unsigned IIDs[] = { // Intrinsic to use for each size. 8392 Intrinsic::ppc_altivec_vsrab, Intrinsic::ppc_altivec_vsrah, 0, 8393 Intrinsic::ppc_altivec_vsraw 8394 }; 8395 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 8396 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 8397 } 8398 8399 // vsplti + rol self. 8400 if (SextVal == (int)(((unsigned)i << TypeShiftAmt) | 8401 ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) { 8402 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl); 8403 static const unsigned IIDs[] = { // Intrinsic to use for each size. 8404 Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0, 8405 Intrinsic::ppc_altivec_vrlw 8406 }; 8407 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 8408 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 8409 } 8410 8411 // t = vsplti c, result = vsldoi t, t, 1 8412 if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) { 8413 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl); 8414 unsigned Amt = Subtarget.isLittleEndian() ? 15 : 1; 8415 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl); 8416 } 8417 // t = vsplti c, result = vsldoi t, t, 2 8418 if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) { 8419 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl); 8420 unsigned Amt = Subtarget.isLittleEndian() ? 14 : 2; 8421 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl); 8422 } 8423 // t = vsplti c, result = vsldoi t, t, 3 8424 if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) { 8425 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl); 8426 unsigned Amt = Subtarget.isLittleEndian() ? 13 : 3; 8427 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl); 8428 } 8429 } 8430 8431 return SDValue(); 8432 } 8433 8434 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit 8435 /// the specified operations to build the shuffle. 8436 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS, 8437 SDValue RHS, SelectionDAG &DAG, 8438 const SDLoc &dl) { 8439 unsigned OpNum = (PFEntry >> 26) & 0x0F; 8440 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1); 8441 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1); 8442 8443 enum { 8444 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3> 8445 OP_VMRGHW, 8446 OP_VMRGLW, 8447 OP_VSPLTISW0, 8448 OP_VSPLTISW1, 8449 OP_VSPLTISW2, 8450 OP_VSPLTISW3, 8451 OP_VSLDOI4, 8452 OP_VSLDOI8, 8453 OP_VSLDOI12 8454 }; 8455 8456 if (OpNum == OP_COPY) { 8457 if (LHSID == (1*9+2)*9+3) return LHS; 8458 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!"); 8459 return RHS; 8460 } 8461 8462 SDValue OpLHS, OpRHS; 8463 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl); 8464 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl); 8465 8466 int ShufIdxs[16]; 8467 switch (OpNum) { 8468 default: llvm_unreachable("Unknown i32 permute!"); 8469 case OP_VMRGHW: 8470 ShufIdxs[ 0] = 0; ShufIdxs[ 1] = 1; ShufIdxs[ 2] = 2; ShufIdxs[ 3] = 3; 8471 ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19; 8472 ShufIdxs[ 8] = 4; ShufIdxs[ 9] = 5; ShufIdxs[10] = 6; ShufIdxs[11] = 7; 8473 ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23; 8474 break; 8475 case OP_VMRGLW: 8476 ShufIdxs[ 0] = 8; ShufIdxs[ 1] = 9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11; 8477 ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27; 8478 ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15; 8479 ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31; 8480 break; 8481 case OP_VSPLTISW0: 8482 for (unsigned i = 0; i != 16; ++i) 8483 ShufIdxs[i] = (i&3)+0; 8484 break; 8485 case OP_VSPLTISW1: 8486 for (unsigned i = 0; i != 16; ++i) 8487 ShufIdxs[i] = (i&3)+4; 8488 break; 8489 case OP_VSPLTISW2: 8490 for (unsigned i = 0; i != 16; ++i) 8491 ShufIdxs[i] = (i&3)+8; 8492 break; 8493 case OP_VSPLTISW3: 8494 for (unsigned i = 0; i != 16; ++i) 8495 ShufIdxs[i] = (i&3)+12; 8496 break; 8497 case OP_VSLDOI4: 8498 return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl); 8499 case OP_VSLDOI8: 8500 return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl); 8501 case OP_VSLDOI12: 8502 return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl); 8503 } 8504 EVT VT = OpLHS.getValueType(); 8505 OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS); 8506 OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS); 8507 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs); 8508 return DAG.getNode(ISD::BITCAST, dl, VT, T); 8509 } 8510 8511 /// lowerToVINSERTB - Return the SDValue if this VECTOR_SHUFFLE can be handled 8512 /// by the VINSERTB instruction introduced in ISA 3.0, else just return default 8513 /// SDValue. 8514 SDValue PPCTargetLowering::lowerToVINSERTB(ShuffleVectorSDNode *N, 8515 SelectionDAG &DAG) const { 8516 const unsigned BytesInVector = 16; 8517 bool IsLE = Subtarget.isLittleEndian(); 8518 SDLoc dl(N); 8519 SDValue V1 = N->getOperand(0); 8520 SDValue V2 = N->getOperand(1); 8521 unsigned ShiftElts = 0, InsertAtByte = 0; 8522 bool Swap = false; 8523 8524 // Shifts required to get the byte we want at element 7. 8525 unsigned LittleEndianShifts[] = {8, 7, 6, 5, 4, 3, 2, 1, 8526 0, 15, 14, 13, 12, 11, 10, 9}; 8527 unsigned BigEndianShifts[] = {9, 10, 11, 12, 13, 14, 15, 0, 8528 1, 2, 3, 4, 5, 6, 7, 8}; 8529 8530 ArrayRef<int> Mask = N->getMask(); 8531 int OriginalOrder[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}; 8532 8533 // For each mask element, find out if we're just inserting something 8534 // from V2 into V1 or vice versa. 8535 // Possible permutations inserting an element from V2 into V1: 8536 // X, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 8537 // 0, X, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 8538 // ... 8539 // 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, X 8540 // Inserting from V1 into V2 will be similar, except mask range will be 8541 // [16,31]. 8542 8543 bool FoundCandidate = false; 8544 // If both vector operands for the shuffle are the same vector, the mask 8545 // will contain only elements from the first one and the second one will be 8546 // undef. 8547 unsigned VINSERTBSrcElem = IsLE ? 8 : 7; 8548 // Go through the mask of half-words to find an element that's being moved 8549 // from one vector to the other. 8550 for (unsigned i = 0; i < BytesInVector; ++i) { 8551 unsigned CurrentElement = Mask[i]; 8552 // If 2nd operand is undefined, we should only look for element 7 in the 8553 // Mask. 8554 if (V2.isUndef() && CurrentElement != VINSERTBSrcElem) 8555 continue; 8556 8557 bool OtherElementsInOrder = true; 8558 // Examine the other elements in the Mask to see if they're in original 8559 // order. 8560 for (unsigned j = 0; j < BytesInVector; ++j) { 8561 if (j == i) 8562 continue; 8563 // If CurrentElement is from V1 [0,15], then we the rest of the Mask to be 8564 // from V2 [16,31] and vice versa. Unless the 2nd operand is undefined, 8565 // in which we always assume we're always picking from the 1st operand. 8566 int MaskOffset = 8567 (!V2.isUndef() && CurrentElement < BytesInVector) ? BytesInVector : 0; 8568 if (Mask[j] != OriginalOrder[j] + MaskOffset) { 8569 OtherElementsInOrder = false; 8570 break; 8571 } 8572 } 8573 // If other elements are in original order, we record the number of shifts 8574 // we need to get the element we want into element 7. Also record which byte 8575 // in the vector we should insert into. 8576 if (OtherElementsInOrder) { 8577 // If 2nd operand is undefined, we assume no shifts and no swapping. 8578 if (V2.isUndef()) { 8579 ShiftElts = 0; 8580 Swap = false; 8581 } else { 8582 // Only need the last 4-bits for shifts because operands will be swapped if CurrentElement is >= 2^4. 8583 ShiftElts = IsLE ? LittleEndianShifts[CurrentElement & 0xF] 8584 : BigEndianShifts[CurrentElement & 0xF]; 8585 Swap = CurrentElement < BytesInVector; 8586 } 8587 InsertAtByte = IsLE ? BytesInVector - (i + 1) : i; 8588 FoundCandidate = true; 8589 break; 8590 } 8591 } 8592 8593 if (!FoundCandidate) 8594 return SDValue(); 8595 8596 // Candidate found, construct the proper SDAG sequence with VINSERTB, 8597 // optionally with VECSHL if shift is required. 8598 if (Swap) 8599 std::swap(V1, V2); 8600 if (V2.isUndef()) 8601 V2 = V1; 8602 if (ShiftElts) { 8603 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2, 8604 DAG.getConstant(ShiftElts, dl, MVT::i32)); 8605 return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, Shl, 8606 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 8607 } 8608 return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, V2, 8609 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 8610 } 8611 8612 /// lowerToVINSERTH - Return the SDValue if this VECTOR_SHUFFLE can be handled 8613 /// by the VINSERTH instruction introduced in ISA 3.0, else just return default 8614 /// SDValue. 8615 SDValue PPCTargetLowering::lowerToVINSERTH(ShuffleVectorSDNode *N, 8616 SelectionDAG &DAG) const { 8617 const unsigned NumHalfWords = 8; 8618 const unsigned BytesInVector = NumHalfWords * 2; 8619 // Check that the shuffle is on half-words. 8620 if (!isNByteElemShuffleMask(N, 2, 1)) 8621 return SDValue(); 8622 8623 bool IsLE = Subtarget.isLittleEndian(); 8624 SDLoc dl(N); 8625 SDValue V1 = N->getOperand(0); 8626 SDValue V2 = N->getOperand(1); 8627 unsigned ShiftElts = 0, InsertAtByte = 0; 8628 bool Swap = false; 8629 8630 // Shifts required to get the half-word we want at element 3. 8631 unsigned LittleEndianShifts[] = {4, 3, 2, 1, 0, 7, 6, 5}; 8632 unsigned BigEndianShifts[] = {5, 6, 7, 0, 1, 2, 3, 4}; 8633 8634 uint32_t Mask = 0; 8635 uint32_t OriginalOrderLow = 0x1234567; 8636 uint32_t OriginalOrderHigh = 0x89ABCDEF; 8637 // Now we look at mask elements 0,2,4,6,8,10,12,14. Pack the mask into a 8638 // 32-bit space, only need 4-bit nibbles per element. 8639 for (unsigned i = 0; i < NumHalfWords; ++i) { 8640 unsigned MaskShift = (NumHalfWords - 1 - i) * 4; 8641 Mask |= ((uint32_t)(N->getMaskElt(i * 2) / 2) << MaskShift); 8642 } 8643 8644 // For each mask element, find out if we're just inserting something 8645 // from V2 into V1 or vice versa. Possible permutations inserting an element 8646 // from V2 into V1: 8647 // X, 1, 2, 3, 4, 5, 6, 7 8648 // 0, X, 2, 3, 4, 5, 6, 7 8649 // 0, 1, X, 3, 4, 5, 6, 7 8650 // 0, 1, 2, X, 4, 5, 6, 7 8651 // 0, 1, 2, 3, X, 5, 6, 7 8652 // 0, 1, 2, 3, 4, X, 6, 7 8653 // 0, 1, 2, 3, 4, 5, X, 7 8654 // 0, 1, 2, 3, 4, 5, 6, X 8655 // Inserting from V1 into V2 will be similar, except mask range will be [8,15]. 8656 8657 bool FoundCandidate = false; 8658 // Go through the mask of half-words to find an element that's being moved 8659 // from one vector to the other. 8660 for (unsigned i = 0; i < NumHalfWords; ++i) { 8661 unsigned MaskShift = (NumHalfWords - 1 - i) * 4; 8662 uint32_t MaskOneElt = (Mask >> MaskShift) & 0xF; 8663 uint32_t MaskOtherElts = ~(0xF << MaskShift); 8664 uint32_t TargetOrder = 0x0; 8665 8666 // If both vector operands for the shuffle are the same vector, the mask 8667 // will contain only elements from the first one and the second one will be 8668 // undef. 8669 if (V2.isUndef()) { 8670 ShiftElts = 0; 8671 unsigned VINSERTHSrcElem = IsLE ? 4 : 3; 8672 TargetOrder = OriginalOrderLow; 8673 Swap = false; 8674 // Skip if not the correct element or mask of other elements don't equal 8675 // to our expected order. 8676 if (MaskOneElt == VINSERTHSrcElem && 8677 (Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) { 8678 InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2; 8679 FoundCandidate = true; 8680 break; 8681 } 8682 } else { // If both operands are defined. 8683 // Target order is [8,15] if the current mask is between [0,7]. 8684 TargetOrder = 8685 (MaskOneElt < NumHalfWords) ? OriginalOrderHigh : OriginalOrderLow; 8686 // Skip if mask of other elements don't equal our expected order. 8687 if ((Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) { 8688 // We only need the last 3 bits for the number of shifts. 8689 ShiftElts = IsLE ? LittleEndianShifts[MaskOneElt & 0x7] 8690 : BigEndianShifts[MaskOneElt & 0x7]; 8691 InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2; 8692 Swap = MaskOneElt < NumHalfWords; 8693 FoundCandidate = true; 8694 break; 8695 } 8696 } 8697 } 8698 8699 if (!FoundCandidate) 8700 return SDValue(); 8701 8702 // Candidate found, construct the proper SDAG sequence with VINSERTH, 8703 // optionally with VECSHL if shift is required. 8704 if (Swap) 8705 std::swap(V1, V2); 8706 if (V2.isUndef()) 8707 V2 = V1; 8708 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1); 8709 if (ShiftElts) { 8710 // Double ShiftElts because we're left shifting on v16i8 type. 8711 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2, 8712 DAG.getConstant(2 * ShiftElts, dl, MVT::i32)); 8713 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, Shl); 8714 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2, 8715 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 8716 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 8717 } 8718 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2); 8719 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2, 8720 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 8721 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 8722 } 8723 8724 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE. If this 8725 /// is a shuffle we can handle in a single instruction, return it. Otherwise, 8726 /// return the code it can be lowered into. Worst case, it can always be 8727 /// lowered into a vperm. 8728 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, 8729 SelectionDAG &DAG) const { 8730 SDLoc dl(Op); 8731 SDValue V1 = Op.getOperand(0); 8732 SDValue V2 = Op.getOperand(1); 8733 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op); 8734 EVT VT = Op.getValueType(); 8735 bool isLittleEndian = Subtarget.isLittleEndian(); 8736 8737 unsigned ShiftElts, InsertAtByte; 8738 bool Swap = false; 8739 if (Subtarget.hasP9Vector() && 8740 PPC::isXXINSERTWMask(SVOp, ShiftElts, InsertAtByte, Swap, 8741 isLittleEndian)) { 8742 if (Swap) 8743 std::swap(V1, V2); 8744 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 8745 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2); 8746 if (ShiftElts) { 8747 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv2, Conv2, 8748 DAG.getConstant(ShiftElts, dl, MVT::i32)); 8749 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Shl, 8750 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 8751 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 8752 } 8753 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Conv2, 8754 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 8755 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 8756 } 8757 8758 if (Subtarget.hasP9Altivec()) { 8759 SDValue NewISDNode; 8760 if ((NewISDNode = lowerToVINSERTH(SVOp, DAG))) 8761 return NewISDNode; 8762 8763 if ((NewISDNode = lowerToVINSERTB(SVOp, DAG))) 8764 return NewISDNode; 8765 } 8766 8767 if (Subtarget.hasVSX() && 8768 PPC::isXXSLDWIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) { 8769 if (Swap) 8770 std::swap(V1, V2); 8771 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 8772 SDValue Conv2 = 8773 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2.isUndef() ? V1 : V2); 8774 8775 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv1, Conv2, 8776 DAG.getConstant(ShiftElts, dl, MVT::i32)); 8777 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Shl); 8778 } 8779 8780 if (Subtarget.hasVSX() && 8781 PPC::isXXPERMDIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) { 8782 if (Swap) 8783 std::swap(V1, V2); 8784 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1); 8785 SDValue Conv2 = 8786 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2.isUndef() ? V1 : V2); 8787 8788 SDValue PermDI = DAG.getNode(PPCISD::XXPERMDI, dl, MVT::v2i64, Conv1, Conv2, 8789 DAG.getConstant(ShiftElts, dl, MVT::i32)); 8790 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, PermDI); 8791 } 8792 8793 if (Subtarget.hasP9Vector()) { 8794 if (PPC::isXXBRHShuffleMask(SVOp)) { 8795 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1); 8796 SDValue ReveHWord = DAG.getNode(PPCISD::XXREVERSE, dl, MVT::v8i16, Conv); 8797 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveHWord); 8798 } else if (PPC::isXXBRWShuffleMask(SVOp)) { 8799 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 8800 SDValue ReveWord = DAG.getNode(PPCISD::XXREVERSE, dl, MVT::v4i32, Conv); 8801 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveWord); 8802 } else if (PPC::isXXBRDShuffleMask(SVOp)) { 8803 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1); 8804 SDValue ReveDWord = DAG.getNode(PPCISD::XXREVERSE, dl, MVT::v2i64, Conv); 8805 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveDWord); 8806 } else if (PPC::isXXBRQShuffleMask(SVOp)) { 8807 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, V1); 8808 SDValue ReveQWord = DAG.getNode(PPCISD::XXREVERSE, dl, MVT::v1i128, Conv); 8809 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveQWord); 8810 } 8811 } 8812 8813 if (Subtarget.hasVSX()) { 8814 if (V2.isUndef() && PPC::isSplatShuffleMask(SVOp, 4)) { 8815 int SplatIdx = PPC::getVSPLTImmediate(SVOp, 4, DAG); 8816 8817 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 8818 SDValue Splat = DAG.getNode(PPCISD::XXSPLT, dl, MVT::v4i32, Conv, 8819 DAG.getConstant(SplatIdx, dl, MVT::i32)); 8820 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Splat); 8821 } 8822 8823 // Left shifts of 8 bytes are actually swaps. Convert accordingly. 8824 if (V2.isUndef() && PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) == 8) { 8825 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1); 8826 SDValue Swap = DAG.getNode(PPCISD::SWAP_NO_CHAIN, dl, MVT::v2f64, Conv); 8827 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Swap); 8828 } 8829 } 8830 8831 if (Subtarget.hasQPX()) { 8832 if (VT.getVectorNumElements() != 4) 8833 return SDValue(); 8834 8835 if (V2.isUndef()) V2 = V1; 8836 8837 int AlignIdx = PPC::isQVALIGNIShuffleMask(SVOp); 8838 if (AlignIdx != -1) { 8839 return DAG.getNode(PPCISD::QVALIGNI, dl, VT, V1, V2, 8840 DAG.getConstant(AlignIdx, dl, MVT::i32)); 8841 } else if (SVOp->isSplat()) { 8842 int SplatIdx = SVOp->getSplatIndex(); 8843 if (SplatIdx >= 4) { 8844 std::swap(V1, V2); 8845 SplatIdx -= 4; 8846 } 8847 8848 return DAG.getNode(PPCISD::QVESPLATI, dl, VT, V1, 8849 DAG.getConstant(SplatIdx, dl, MVT::i32)); 8850 } 8851 8852 // Lower this into a qvgpci/qvfperm pair. 8853 8854 // Compute the qvgpci literal 8855 unsigned idx = 0; 8856 for (unsigned i = 0; i < 4; ++i) { 8857 int m = SVOp->getMaskElt(i); 8858 unsigned mm = m >= 0 ? (unsigned) m : i; 8859 idx |= mm << (3-i)*3; 8860 } 8861 8862 SDValue V3 = DAG.getNode(PPCISD::QVGPCI, dl, MVT::v4f64, 8863 DAG.getConstant(idx, dl, MVT::i32)); 8864 return DAG.getNode(PPCISD::QVFPERM, dl, VT, V1, V2, V3); 8865 } 8866 8867 // Cases that are handled by instructions that take permute immediates 8868 // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be 8869 // selected by the instruction selector. 8870 if (V2.isUndef()) { 8871 if (PPC::isSplatShuffleMask(SVOp, 1) || 8872 PPC::isSplatShuffleMask(SVOp, 2) || 8873 PPC::isSplatShuffleMask(SVOp, 4) || 8874 PPC::isVPKUWUMShuffleMask(SVOp, 1, DAG) || 8875 PPC::isVPKUHUMShuffleMask(SVOp, 1, DAG) || 8876 PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) != -1 || 8877 PPC::isVMRGLShuffleMask(SVOp, 1, 1, DAG) || 8878 PPC::isVMRGLShuffleMask(SVOp, 2, 1, DAG) || 8879 PPC::isVMRGLShuffleMask(SVOp, 4, 1, DAG) || 8880 PPC::isVMRGHShuffleMask(SVOp, 1, 1, DAG) || 8881 PPC::isVMRGHShuffleMask(SVOp, 2, 1, DAG) || 8882 PPC::isVMRGHShuffleMask(SVOp, 4, 1, DAG) || 8883 (Subtarget.hasP8Altivec() && ( 8884 PPC::isVPKUDUMShuffleMask(SVOp, 1, DAG) || 8885 PPC::isVMRGEOShuffleMask(SVOp, true, 1, DAG) || 8886 PPC::isVMRGEOShuffleMask(SVOp, false, 1, DAG)))) { 8887 return Op; 8888 } 8889 } 8890 8891 // Altivec has a variety of "shuffle immediates" that take two vector inputs 8892 // and produce a fixed permutation. If any of these match, do not lower to 8893 // VPERM. 8894 unsigned int ShuffleKind = isLittleEndian ? 2 : 0; 8895 if (PPC::isVPKUWUMShuffleMask(SVOp, ShuffleKind, DAG) || 8896 PPC::isVPKUHUMShuffleMask(SVOp, ShuffleKind, DAG) || 8897 PPC::isVSLDOIShuffleMask(SVOp, ShuffleKind, DAG) != -1 || 8898 PPC::isVMRGLShuffleMask(SVOp, 1, ShuffleKind, DAG) || 8899 PPC::isVMRGLShuffleMask(SVOp, 2, ShuffleKind, DAG) || 8900 PPC::isVMRGLShuffleMask(SVOp, 4, ShuffleKind, DAG) || 8901 PPC::isVMRGHShuffleMask(SVOp, 1, ShuffleKind, DAG) || 8902 PPC::isVMRGHShuffleMask(SVOp, 2, ShuffleKind, DAG) || 8903 PPC::isVMRGHShuffleMask(SVOp, 4, ShuffleKind, DAG) || 8904 (Subtarget.hasP8Altivec() && ( 8905 PPC::isVPKUDUMShuffleMask(SVOp, ShuffleKind, DAG) || 8906 PPC::isVMRGEOShuffleMask(SVOp, true, ShuffleKind, DAG) || 8907 PPC::isVMRGEOShuffleMask(SVOp, false, ShuffleKind, DAG)))) 8908 return Op; 8909 8910 // Check to see if this is a shuffle of 4-byte values. If so, we can use our 8911 // perfect shuffle table to emit an optimal matching sequence. 8912 ArrayRef<int> PermMask = SVOp->getMask(); 8913 8914 unsigned PFIndexes[4]; 8915 bool isFourElementShuffle = true; 8916 for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number 8917 unsigned EltNo = 8; // Start out undef. 8918 for (unsigned j = 0; j != 4; ++j) { // Intra-element byte. 8919 if (PermMask[i*4+j] < 0) 8920 continue; // Undef, ignore it. 8921 8922 unsigned ByteSource = PermMask[i*4+j]; 8923 if ((ByteSource & 3) != j) { 8924 isFourElementShuffle = false; 8925 break; 8926 } 8927 8928 if (EltNo == 8) { 8929 EltNo = ByteSource/4; 8930 } else if (EltNo != ByteSource/4) { 8931 isFourElementShuffle = false; 8932 break; 8933 } 8934 } 8935 PFIndexes[i] = EltNo; 8936 } 8937 8938 // If this shuffle can be expressed as a shuffle of 4-byte elements, use the 8939 // perfect shuffle vector to determine if it is cost effective to do this as 8940 // discrete instructions, or whether we should use a vperm. 8941 // For now, we skip this for little endian until such time as we have a 8942 // little-endian perfect shuffle table. 8943 if (isFourElementShuffle && !isLittleEndian) { 8944 // Compute the index in the perfect shuffle table. 8945 unsigned PFTableIndex = 8946 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3]; 8947 8948 unsigned PFEntry = PerfectShuffleTable[PFTableIndex]; 8949 unsigned Cost = (PFEntry >> 30); 8950 8951 // Determining when to avoid vperm is tricky. Many things affect the cost 8952 // of vperm, particularly how many times the perm mask needs to be computed. 8953 // For example, if the perm mask can be hoisted out of a loop or is already 8954 // used (perhaps because there are multiple permutes with the same shuffle 8955 // mask?) the vperm has a cost of 1. OTOH, hoisting the permute mask out of 8956 // the loop requires an extra register. 8957 // 8958 // As a compromise, we only emit discrete instructions if the shuffle can be 8959 // generated in 3 or fewer operations. When we have loop information 8960 // available, if this block is within a loop, we should avoid using vperm 8961 // for 3-operation perms and use a constant pool load instead. 8962 if (Cost < 3) 8963 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl); 8964 } 8965 8966 // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant 8967 // vector that will get spilled to the constant pool. 8968 if (V2.isUndef()) V2 = V1; 8969 8970 // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except 8971 // that it is in input element units, not in bytes. Convert now. 8972 8973 // For little endian, the order of the input vectors is reversed, and 8974 // the permutation mask is complemented with respect to 31. This is 8975 // necessary to produce proper semantics with the big-endian-biased vperm 8976 // instruction. 8977 EVT EltVT = V1.getValueType().getVectorElementType(); 8978 unsigned BytesPerElement = EltVT.getSizeInBits()/8; 8979 8980 SmallVector<SDValue, 16> ResultMask; 8981 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) { 8982 unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i]; 8983 8984 for (unsigned j = 0; j != BytesPerElement; ++j) 8985 if (isLittleEndian) 8986 ResultMask.push_back(DAG.getConstant(31 - (SrcElt*BytesPerElement + j), 8987 dl, MVT::i32)); 8988 else 8989 ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement + j, dl, 8990 MVT::i32)); 8991 } 8992 8993 SDValue VPermMask = DAG.getBuildVector(MVT::v16i8, dl, ResultMask); 8994 if (isLittleEndian) 8995 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(), 8996 V2, V1, VPermMask); 8997 else 8998 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(), 8999 V1, V2, VPermMask); 9000 } 9001 9002 /// getVectorCompareInfo - Given an intrinsic, return false if it is not a 9003 /// vector comparison. If it is, return true and fill in Opc/isDot with 9004 /// information about the intrinsic. 9005 static bool getVectorCompareInfo(SDValue Intrin, int &CompareOpc, 9006 bool &isDot, const PPCSubtarget &Subtarget) { 9007 unsigned IntrinsicID = 9008 cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue(); 9009 CompareOpc = -1; 9010 isDot = false; 9011 switch (IntrinsicID) { 9012 default: 9013 return false; 9014 // Comparison predicates. 9015 case Intrinsic::ppc_altivec_vcmpbfp_p: 9016 CompareOpc = 966; 9017 isDot = true; 9018 break; 9019 case Intrinsic::ppc_altivec_vcmpeqfp_p: 9020 CompareOpc = 198; 9021 isDot = true; 9022 break; 9023 case Intrinsic::ppc_altivec_vcmpequb_p: 9024 CompareOpc = 6; 9025 isDot = true; 9026 break; 9027 case Intrinsic::ppc_altivec_vcmpequh_p: 9028 CompareOpc = 70; 9029 isDot = true; 9030 break; 9031 case Intrinsic::ppc_altivec_vcmpequw_p: 9032 CompareOpc = 134; 9033 isDot = true; 9034 break; 9035 case Intrinsic::ppc_altivec_vcmpequd_p: 9036 if (Subtarget.hasP8Altivec()) { 9037 CompareOpc = 199; 9038 isDot = true; 9039 } else 9040 return false; 9041 break; 9042 case Intrinsic::ppc_altivec_vcmpneb_p: 9043 case Intrinsic::ppc_altivec_vcmpneh_p: 9044 case Intrinsic::ppc_altivec_vcmpnew_p: 9045 case Intrinsic::ppc_altivec_vcmpnezb_p: 9046 case Intrinsic::ppc_altivec_vcmpnezh_p: 9047 case Intrinsic::ppc_altivec_vcmpnezw_p: 9048 if (Subtarget.hasP9Altivec()) { 9049 switch (IntrinsicID) { 9050 default: 9051 llvm_unreachable("Unknown comparison intrinsic."); 9052 case Intrinsic::ppc_altivec_vcmpneb_p: 9053 CompareOpc = 7; 9054 break; 9055 case Intrinsic::ppc_altivec_vcmpneh_p: 9056 CompareOpc = 71; 9057 break; 9058 case Intrinsic::ppc_altivec_vcmpnew_p: 9059 CompareOpc = 135; 9060 break; 9061 case Intrinsic::ppc_altivec_vcmpnezb_p: 9062 CompareOpc = 263; 9063 break; 9064 case Intrinsic::ppc_altivec_vcmpnezh_p: 9065 CompareOpc = 327; 9066 break; 9067 case Intrinsic::ppc_altivec_vcmpnezw_p: 9068 CompareOpc = 391; 9069 break; 9070 } 9071 isDot = true; 9072 } else 9073 return false; 9074 break; 9075 case Intrinsic::ppc_altivec_vcmpgefp_p: 9076 CompareOpc = 454; 9077 isDot = true; 9078 break; 9079 case Intrinsic::ppc_altivec_vcmpgtfp_p: 9080 CompareOpc = 710; 9081 isDot = true; 9082 break; 9083 case Intrinsic::ppc_altivec_vcmpgtsb_p: 9084 CompareOpc = 774; 9085 isDot = true; 9086 break; 9087 case Intrinsic::ppc_altivec_vcmpgtsh_p: 9088 CompareOpc = 838; 9089 isDot = true; 9090 break; 9091 case Intrinsic::ppc_altivec_vcmpgtsw_p: 9092 CompareOpc = 902; 9093 isDot = true; 9094 break; 9095 case Intrinsic::ppc_altivec_vcmpgtsd_p: 9096 if (Subtarget.hasP8Altivec()) { 9097 CompareOpc = 967; 9098 isDot = true; 9099 } else 9100 return false; 9101 break; 9102 case Intrinsic::ppc_altivec_vcmpgtub_p: 9103 CompareOpc = 518; 9104 isDot = true; 9105 break; 9106 case Intrinsic::ppc_altivec_vcmpgtuh_p: 9107 CompareOpc = 582; 9108 isDot = true; 9109 break; 9110 case Intrinsic::ppc_altivec_vcmpgtuw_p: 9111 CompareOpc = 646; 9112 isDot = true; 9113 break; 9114 case Intrinsic::ppc_altivec_vcmpgtud_p: 9115 if (Subtarget.hasP8Altivec()) { 9116 CompareOpc = 711; 9117 isDot = true; 9118 } else 9119 return false; 9120 break; 9121 9122 // VSX predicate comparisons use the same infrastructure 9123 case Intrinsic::ppc_vsx_xvcmpeqdp_p: 9124 case Intrinsic::ppc_vsx_xvcmpgedp_p: 9125 case Intrinsic::ppc_vsx_xvcmpgtdp_p: 9126 case Intrinsic::ppc_vsx_xvcmpeqsp_p: 9127 case Intrinsic::ppc_vsx_xvcmpgesp_p: 9128 case Intrinsic::ppc_vsx_xvcmpgtsp_p: 9129 if (Subtarget.hasVSX()) { 9130 switch (IntrinsicID) { 9131 case Intrinsic::ppc_vsx_xvcmpeqdp_p: 9132 CompareOpc = 99; 9133 break; 9134 case Intrinsic::ppc_vsx_xvcmpgedp_p: 9135 CompareOpc = 115; 9136 break; 9137 case Intrinsic::ppc_vsx_xvcmpgtdp_p: 9138 CompareOpc = 107; 9139 break; 9140 case Intrinsic::ppc_vsx_xvcmpeqsp_p: 9141 CompareOpc = 67; 9142 break; 9143 case Intrinsic::ppc_vsx_xvcmpgesp_p: 9144 CompareOpc = 83; 9145 break; 9146 case Intrinsic::ppc_vsx_xvcmpgtsp_p: 9147 CompareOpc = 75; 9148 break; 9149 } 9150 isDot = true; 9151 } else 9152 return false; 9153 break; 9154 9155 // Normal Comparisons. 9156 case Intrinsic::ppc_altivec_vcmpbfp: 9157 CompareOpc = 966; 9158 break; 9159 case Intrinsic::ppc_altivec_vcmpeqfp: 9160 CompareOpc = 198; 9161 break; 9162 case Intrinsic::ppc_altivec_vcmpequb: 9163 CompareOpc = 6; 9164 break; 9165 case Intrinsic::ppc_altivec_vcmpequh: 9166 CompareOpc = 70; 9167 break; 9168 case Intrinsic::ppc_altivec_vcmpequw: 9169 CompareOpc = 134; 9170 break; 9171 case Intrinsic::ppc_altivec_vcmpequd: 9172 if (Subtarget.hasP8Altivec()) 9173 CompareOpc = 199; 9174 else 9175 return false; 9176 break; 9177 case Intrinsic::ppc_altivec_vcmpneb: 9178 case Intrinsic::ppc_altivec_vcmpneh: 9179 case Intrinsic::ppc_altivec_vcmpnew: 9180 case Intrinsic::ppc_altivec_vcmpnezb: 9181 case Intrinsic::ppc_altivec_vcmpnezh: 9182 case Intrinsic::ppc_altivec_vcmpnezw: 9183 if (Subtarget.hasP9Altivec()) 9184 switch (IntrinsicID) { 9185 default: 9186 llvm_unreachable("Unknown comparison intrinsic."); 9187 case Intrinsic::ppc_altivec_vcmpneb: 9188 CompareOpc = 7; 9189 break; 9190 case Intrinsic::ppc_altivec_vcmpneh: 9191 CompareOpc = 71; 9192 break; 9193 case Intrinsic::ppc_altivec_vcmpnew: 9194 CompareOpc = 135; 9195 break; 9196 case Intrinsic::ppc_altivec_vcmpnezb: 9197 CompareOpc = 263; 9198 break; 9199 case Intrinsic::ppc_altivec_vcmpnezh: 9200 CompareOpc = 327; 9201 break; 9202 case Intrinsic::ppc_altivec_vcmpnezw: 9203 CompareOpc = 391; 9204 break; 9205 } 9206 else 9207 return false; 9208 break; 9209 case Intrinsic::ppc_altivec_vcmpgefp: 9210 CompareOpc = 454; 9211 break; 9212 case Intrinsic::ppc_altivec_vcmpgtfp: 9213 CompareOpc = 710; 9214 break; 9215 case Intrinsic::ppc_altivec_vcmpgtsb: 9216 CompareOpc = 774; 9217 break; 9218 case Intrinsic::ppc_altivec_vcmpgtsh: 9219 CompareOpc = 838; 9220 break; 9221 case Intrinsic::ppc_altivec_vcmpgtsw: 9222 CompareOpc = 902; 9223 break; 9224 case Intrinsic::ppc_altivec_vcmpgtsd: 9225 if (Subtarget.hasP8Altivec()) 9226 CompareOpc = 967; 9227 else 9228 return false; 9229 break; 9230 case Intrinsic::ppc_altivec_vcmpgtub: 9231 CompareOpc = 518; 9232 break; 9233 case Intrinsic::ppc_altivec_vcmpgtuh: 9234 CompareOpc = 582; 9235 break; 9236 case Intrinsic::ppc_altivec_vcmpgtuw: 9237 CompareOpc = 646; 9238 break; 9239 case Intrinsic::ppc_altivec_vcmpgtud: 9240 if (Subtarget.hasP8Altivec()) 9241 CompareOpc = 711; 9242 else 9243 return false; 9244 break; 9245 } 9246 return true; 9247 } 9248 9249 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom 9250 /// lower, do it, otherwise return null. 9251 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 9252 SelectionDAG &DAG) const { 9253 unsigned IntrinsicID = 9254 cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 9255 9256 SDLoc dl(Op); 9257 9258 if (IntrinsicID == Intrinsic::thread_pointer) { 9259 // Reads the thread pointer register, used for __builtin_thread_pointer. 9260 if (Subtarget.isPPC64()) 9261 return DAG.getRegister(PPC::X13, MVT::i64); 9262 return DAG.getRegister(PPC::R2, MVT::i32); 9263 } 9264 9265 // If this is a lowered altivec predicate compare, CompareOpc is set to the 9266 // opcode number of the comparison. 9267 int CompareOpc; 9268 bool isDot; 9269 if (!getVectorCompareInfo(Op, CompareOpc, isDot, Subtarget)) 9270 return SDValue(); // Don't custom lower most intrinsics. 9271 9272 // If this is a non-dot comparison, make the VCMP node and we are done. 9273 if (!isDot) { 9274 SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(), 9275 Op.getOperand(1), Op.getOperand(2), 9276 DAG.getConstant(CompareOpc, dl, MVT::i32)); 9277 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp); 9278 } 9279 9280 // Create the PPCISD altivec 'dot' comparison node. 9281 SDValue Ops[] = { 9282 Op.getOperand(2), // LHS 9283 Op.getOperand(3), // RHS 9284 DAG.getConstant(CompareOpc, dl, MVT::i32) 9285 }; 9286 EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue }; 9287 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops); 9288 9289 // Now that we have the comparison, emit a copy from the CR to a GPR. 9290 // This is flagged to the above dot comparison. 9291 SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32, 9292 DAG.getRegister(PPC::CR6, MVT::i32), 9293 CompNode.getValue(1)); 9294 9295 // Unpack the result based on how the target uses it. 9296 unsigned BitNo; // Bit # of CR6. 9297 bool InvertBit; // Invert result? 9298 switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) { 9299 default: // Can't happen, don't crash on invalid number though. 9300 case 0: // Return the value of the EQ bit of CR6. 9301 BitNo = 0; InvertBit = false; 9302 break; 9303 case 1: // Return the inverted value of the EQ bit of CR6. 9304 BitNo = 0; InvertBit = true; 9305 break; 9306 case 2: // Return the value of the LT bit of CR6. 9307 BitNo = 2; InvertBit = false; 9308 break; 9309 case 3: // Return the inverted value of the LT bit of CR6. 9310 BitNo = 2; InvertBit = true; 9311 break; 9312 } 9313 9314 // Shift the bit into the low position. 9315 Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags, 9316 DAG.getConstant(8 - (3 - BitNo), dl, MVT::i32)); 9317 // Isolate the bit. 9318 Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags, 9319 DAG.getConstant(1, dl, MVT::i32)); 9320 9321 // If we are supposed to, toggle the bit. 9322 if (InvertBit) 9323 Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags, 9324 DAG.getConstant(1, dl, MVT::i32)); 9325 return Flags; 9326 } 9327 9328 SDValue PPCTargetLowering::LowerINTRINSIC_VOID(SDValue Op, 9329 SelectionDAG &DAG) const { 9330 // SelectionDAGBuilder::visitTargetIntrinsic may insert one extra chain to 9331 // the beginning of the argument list. 9332 int ArgStart = isa<ConstantSDNode>(Op.getOperand(0)) ? 0 : 1; 9333 SDLoc DL(Op); 9334 switch (cast<ConstantSDNode>(Op.getOperand(ArgStart))->getZExtValue()) { 9335 case Intrinsic::ppc_cfence: { 9336 assert(ArgStart == 1 && "llvm.ppc.cfence must carry a chain argument."); 9337 assert(Subtarget.isPPC64() && "Only 64-bit is supported for now."); 9338 return SDValue(DAG.getMachineNode(PPC::CFENCE8, DL, MVT::Other, 9339 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, 9340 Op.getOperand(ArgStart + 1)), 9341 Op.getOperand(0)), 9342 0); 9343 } 9344 default: 9345 break; 9346 } 9347 return SDValue(); 9348 } 9349 9350 SDValue PPCTargetLowering::LowerREM(SDValue Op, SelectionDAG &DAG) const { 9351 // Check for a DIV with the same operands as this REM. 9352 for (auto UI : Op.getOperand(1)->uses()) { 9353 if ((Op.getOpcode() == ISD::SREM && UI->getOpcode() == ISD::SDIV) || 9354 (Op.getOpcode() == ISD::UREM && UI->getOpcode() == ISD::UDIV)) 9355 if (UI->getOperand(0) == Op.getOperand(0) && 9356 UI->getOperand(1) == Op.getOperand(1)) 9357 return SDValue(); 9358 } 9359 return Op; 9360 } 9361 9362 // Lower scalar BSWAP64 to xxbrd. 9363 SDValue PPCTargetLowering::LowerBSWAP(SDValue Op, SelectionDAG &DAG) const { 9364 SDLoc dl(Op); 9365 // MTVSRDD 9366 Op = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i64, Op.getOperand(0), 9367 Op.getOperand(0)); 9368 // XXBRD 9369 Op = DAG.getNode(PPCISD::XXREVERSE, dl, MVT::v2i64, Op); 9370 // MFVSRD 9371 int VectorIndex = 0; 9372 if (Subtarget.isLittleEndian()) 9373 VectorIndex = 1; 9374 Op = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Op, 9375 DAG.getTargetConstant(VectorIndex, dl, MVT::i32)); 9376 return Op; 9377 } 9378 9379 // ATOMIC_CMP_SWAP for i8/i16 needs to zero-extend its input since it will be 9380 // compared to a value that is atomically loaded (atomic loads zero-extend). 9381 SDValue PPCTargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, 9382 SelectionDAG &DAG) const { 9383 assert(Op.getOpcode() == ISD::ATOMIC_CMP_SWAP && 9384 "Expecting an atomic compare-and-swap here."); 9385 SDLoc dl(Op); 9386 auto *AtomicNode = cast<AtomicSDNode>(Op.getNode()); 9387 EVT MemVT = AtomicNode->getMemoryVT(); 9388 if (MemVT.getSizeInBits() >= 32) 9389 return Op; 9390 9391 SDValue CmpOp = Op.getOperand(2); 9392 // If this is already correctly zero-extended, leave it alone. 9393 auto HighBits = APInt::getHighBitsSet(32, 32 - MemVT.getSizeInBits()); 9394 if (DAG.MaskedValueIsZero(CmpOp, HighBits)) 9395 return Op; 9396 9397 // Clear the high bits of the compare operand. 9398 unsigned MaskVal = (1 << MemVT.getSizeInBits()) - 1; 9399 SDValue NewCmpOp = 9400 DAG.getNode(ISD::AND, dl, MVT::i32, CmpOp, 9401 DAG.getConstant(MaskVal, dl, MVT::i32)); 9402 9403 // Replace the existing compare operand with the properly zero-extended one. 9404 SmallVector<SDValue, 4> Ops; 9405 for (int i = 0, e = AtomicNode->getNumOperands(); i < e; i++) 9406 Ops.push_back(AtomicNode->getOperand(i)); 9407 Ops[2] = NewCmpOp; 9408 MachineMemOperand *MMO = AtomicNode->getMemOperand(); 9409 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::Other); 9410 auto NodeTy = 9411 (MemVT == MVT::i8) ? PPCISD::ATOMIC_CMP_SWAP_8 : PPCISD::ATOMIC_CMP_SWAP_16; 9412 return DAG.getMemIntrinsicNode(NodeTy, dl, Tys, Ops, MemVT, MMO); 9413 } 9414 9415 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, 9416 SelectionDAG &DAG) const { 9417 SDLoc dl(Op); 9418 // Create a stack slot that is 16-byte aligned. 9419 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 9420 int FrameIdx = MFI.CreateStackObject(16, 16, false); 9421 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 9422 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 9423 9424 // Store the input value into Value#0 of the stack slot. 9425 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx, 9426 MachinePointerInfo()); 9427 // Load it out. 9428 return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo()); 9429 } 9430 9431 SDValue PPCTargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, 9432 SelectionDAG &DAG) const { 9433 assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && 9434 "Should only be called for ISD::INSERT_VECTOR_ELT"); 9435 9436 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(2)); 9437 // We have legal lowering for constant indices but not for variable ones. 9438 if (!C) 9439 return SDValue(); 9440 9441 EVT VT = Op.getValueType(); 9442 SDLoc dl(Op); 9443 SDValue V1 = Op.getOperand(0); 9444 SDValue V2 = Op.getOperand(1); 9445 // We can use MTVSRZ + VECINSERT for v8i16 and v16i8 types. 9446 if (VT == MVT::v8i16 || VT == MVT::v16i8) { 9447 SDValue Mtvsrz = DAG.getNode(PPCISD::MTVSRZ, dl, VT, V2); 9448 unsigned BytesInEachElement = VT.getVectorElementType().getSizeInBits() / 8; 9449 unsigned InsertAtElement = C->getZExtValue(); 9450 unsigned InsertAtByte = InsertAtElement * BytesInEachElement; 9451 if (Subtarget.isLittleEndian()) { 9452 InsertAtByte = (16 - BytesInEachElement) - InsertAtByte; 9453 } 9454 return DAG.getNode(PPCISD::VECINSERT, dl, VT, V1, Mtvsrz, 9455 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9456 } 9457 return Op; 9458 } 9459 9460 SDValue PPCTargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op, 9461 SelectionDAG &DAG) const { 9462 SDLoc dl(Op); 9463 SDNode *N = Op.getNode(); 9464 9465 assert(N->getOperand(0).getValueType() == MVT::v4i1 && 9466 "Unknown extract_vector_elt type"); 9467 9468 SDValue Value = N->getOperand(0); 9469 9470 // The first part of this is like the store lowering except that we don't 9471 // need to track the chain. 9472 9473 // The values are now known to be -1 (false) or 1 (true). To convert this 9474 // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5). 9475 // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5 9476 Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value); 9477 9478 // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to 9479 // understand how to form the extending load. 9480 SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64); 9481 9482 Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs); 9483 9484 // Now convert to an integer and store. 9485 Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64, 9486 DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32), 9487 Value); 9488 9489 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 9490 int FrameIdx = MFI.CreateStackObject(16, 16, false); 9491 MachinePointerInfo PtrInfo = 9492 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 9493 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 9494 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 9495 9496 SDValue StoreChain = DAG.getEntryNode(); 9497 SDValue Ops[] = {StoreChain, 9498 DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32), 9499 Value, FIdx}; 9500 SDVTList VTs = DAG.getVTList(/*chain*/ MVT::Other); 9501 9502 StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, 9503 dl, VTs, Ops, MVT::v4i32, PtrInfo); 9504 9505 // Extract the value requested. 9506 unsigned Offset = 4*cast<ConstantSDNode>(N->getOperand(1))->getZExtValue(); 9507 SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType()); 9508 Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx); 9509 9510 SDValue IntVal = 9511 DAG.getLoad(MVT::i32, dl, StoreChain, Idx, PtrInfo.getWithOffset(Offset)); 9512 9513 if (!Subtarget.useCRBits()) 9514 return IntVal; 9515 9516 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, IntVal); 9517 } 9518 9519 /// Lowering for QPX v4i1 loads 9520 SDValue PPCTargetLowering::LowerVectorLoad(SDValue Op, 9521 SelectionDAG &DAG) const { 9522 SDLoc dl(Op); 9523 LoadSDNode *LN = cast<LoadSDNode>(Op.getNode()); 9524 SDValue LoadChain = LN->getChain(); 9525 SDValue BasePtr = LN->getBasePtr(); 9526 9527 if (Op.getValueType() == MVT::v4f64 || 9528 Op.getValueType() == MVT::v4f32) { 9529 EVT MemVT = LN->getMemoryVT(); 9530 unsigned Alignment = LN->getAlignment(); 9531 9532 // If this load is properly aligned, then it is legal. 9533 if (Alignment >= MemVT.getStoreSize()) 9534 return Op; 9535 9536 EVT ScalarVT = Op.getValueType().getScalarType(), 9537 ScalarMemVT = MemVT.getScalarType(); 9538 unsigned Stride = ScalarMemVT.getStoreSize(); 9539 9540 SDValue Vals[4], LoadChains[4]; 9541 for (unsigned Idx = 0; Idx < 4; ++Idx) { 9542 SDValue Load; 9543 if (ScalarVT != ScalarMemVT) 9544 Load = DAG.getExtLoad(LN->getExtensionType(), dl, ScalarVT, LoadChain, 9545 BasePtr, 9546 LN->getPointerInfo().getWithOffset(Idx * Stride), 9547 ScalarMemVT, MinAlign(Alignment, Idx * Stride), 9548 LN->getMemOperand()->getFlags(), LN->getAAInfo()); 9549 else 9550 Load = DAG.getLoad(ScalarVT, dl, LoadChain, BasePtr, 9551 LN->getPointerInfo().getWithOffset(Idx * Stride), 9552 MinAlign(Alignment, Idx * Stride), 9553 LN->getMemOperand()->getFlags(), LN->getAAInfo()); 9554 9555 if (Idx == 0 && LN->isIndexed()) { 9556 assert(LN->getAddressingMode() == ISD::PRE_INC && 9557 "Unknown addressing mode on vector load"); 9558 Load = DAG.getIndexedLoad(Load, dl, BasePtr, LN->getOffset(), 9559 LN->getAddressingMode()); 9560 } 9561 9562 Vals[Idx] = Load; 9563 LoadChains[Idx] = Load.getValue(1); 9564 9565 BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, 9566 DAG.getConstant(Stride, dl, 9567 BasePtr.getValueType())); 9568 } 9569 9570 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains); 9571 SDValue Value = DAG.getBuildVector(Op.getValueType(), dl, Vals); 9572 9573 if (LN->isIndexed()) { 9574 SDValue RetOps[] = { Value, Vals[0].getValue(1), TF }; 9575 return DAG.getMergeValues(RetOps, dl); 9576 } 9577 9578 SDValue RetOps[] = { Value, TF }; 9579 return DAG.getMergeValues(RetOps, dl); 9580 } 9581 9582 assert(Op.getValueType() == MVT::v4i1 && "Unknown load to lower"); 9583 assert(LN->isUnindexed() && "Indexed v4i1 loads are not supported"); 9584 9585 // To lower v4i1 from a byte array, we load the byte elements of the 9586 // vector and then reuse the BUILD_VECTOR logic. 9587 9588 SDValue VectElmts[4], VectElmtChains[4]; 9589 for (unsigned i = 0; i < 4; ++i) { 9590 SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType()); 9591 Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx); 9592 9593 VectElmts[i] = DAG.getExtLoad( 9594 ISD::EXTLOAD, dl, MVT::i32, LoadChain, Idx, 9595 LN->getPointerInfo().getWithOffset(i), MVT::i8, 9596 /* Alignment = */ 1, LN->getMemOperand()->getFlags(), LN->getAAInfo()); 9597 VectElmtChains[i] = VectElmts[i].getValue(1); 9598 } 9599 9600 LoadChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, VectElmtChains); 9601 SDValue Value = DAG.getBuildVector(MVT::v4i1, dl, VectElmts); 9602 9603 SDValue RVals[] = { Value, LoadChain }; 9604 return DAG.getMergeValues(RVals, dl); 9605 } 9606 9607 /// Lowering for QPX v4i1 stores 9608 SDValue PPCTargetLowering::LowerVectorStore(SDValue Op, 9609 SelectionDAG &DAG) const { 9610 SDLoc dl(Op); 9611 StoreSDNode *SN = cast<StoreSDNode>(Op.getNode()); 9612 SDValue StoreChain = SN->getChain(); 9613 SDValue BasePtr = SN->getBasePtr(); 9614 SDValue Value = SN->getValue(); 9615 9616 if (Value.getValueType() == MVT::v4f64 || 9617 Value.getValueType() == MVT::v4f32) { 9618 EVT MemVT = SN->getMemoryVT(); 9619 unsigned Alignment = SN->getAlignment(); 9620 9621 // If this store is properly aligned, then it is legal. 9622 if (Alignment >= MemVT.getStoreSize()) 9623 return Op; 9624 9625 EVT ScalarVT = Value.getValueType().getScalarType(), 9626 ScalarMemVT = MemVT.getScalarType(); 9627 unsigned Stride = ScalarMemVT.getStoreSize(); 9628 9629 SDValue Stores[4]; 9630 for (unsigned Idx = 0; Idx < 4; ++Idx) { 9631 SDValue Ex = DAG.getNode( 9632 ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, Value, 9633 DAG.getConstant(Idx, dl, getVectorIdxTy(DAG.getDataLayout()))); 9634 SDValue Store; 9635 if (ScalarVT != ScalarMemVT) 9636 Store = 9637 DAG.getTruncStore(StoreChain, dl, Ex, BasePtr, 9638 SN->getPointerInfo().getWithOffset(Idx * Stride), 9639 ScalarMemVT, MinAlign(Alignment, Idx * Stride), 9640 SN->getMemOperand()->getFlags(), SN->getAAInfo()); 9641 else 9642 Store = DAG.getStore(StoreChain, dl, Ex, BasePtr, 9643 SN->getPointerInfo().getWithOffset(Idx * Stride), 9644 MinAlign(Alignment, Idx * Stride), 9645 SN->getMemOperand()->getFlags(), SN->getAAInfo()); 9646 9647 if (Idx == 0 && SN->isIndexed()) { 9648 assert(SN->getAddressingMode() == ISD::PRE_INC && 9649 "Unknown addressing mode on vector store"); 9650 Store = DAG.getIndexedStore(Store, dl, BasePtr, SN->getOffset(), 9651 SN->getAddressingMode()); 9652 } 9653 9654 BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, 9655 DAG.getConstant(Stride, dl, 9656 BasePtr.getValueType())); 9657 Stores[Idx] = Store; 9658 } 9659 9660 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores); 9661 9662 if (SN->isIndexed()) { 9663 SDValue RetOps[] = { TF, Stores[0].getValue(1) }; 9664 return DAG.getMergeValues(RetOps, dl); 9665 } 9666 9667 return TF; 9668 } 9669 9670 assert(SN->isUnindexed() && "Indexed v4i1 stores are not supported"); 9671 assert(Value.getValueType() == MVT::v4i1 && "Unknown store to lower"); 9672 9673 // The values are now known to be -1 (false) or 1 (true). To convert this 9674 // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5). 9675 // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5 9676 Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value); 9677 9678 // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to 9679 // understand how to form the extending load. 9680 SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64); 9681 9682 Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs); 9683 9684 // Now convert to an integer and store. 9685 Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64, 9686 DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32), 9687 Value); 9688 9689 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 9690 int FrameIdx = MFI.CreateStackObject(16, 16, false); 9691 MachinePointerInfo PtrInfo = 9692 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 9693 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 9694 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 9695 9696 SDValue Ops[] = {StoreChain, 9697 DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32), 9698 Value, FIdx}; 9699 SDVTList VTs = DAG.getVTList(/*chain*/ MVT::Other); 9700 9701 StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, 9702 dl, VTs, Ops, MVT::v4i32, PtrInfo); 9703 9704 // Move data into the byte array. 9705 SDValue Loads[4], LoadChains[4]; 9706 for (unsigned i = 0; i < 4; ++i) { 9707 unsigned Offset = 4*i; 9708 SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType()); 9709 Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx); 9710 9711 Loads[i] = DAG.getLoad(MVT::i32, dl, StoreChain, Idx, 9712 PtrInfo.getWithOffset(Offset)); 9713 LoadChains[i] = Loads[i].getValue(1); 9714 } 9715 9716 StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains); 9717 9718 SDValue Stores[4]; 9719 for (unsigned i = 0; i < 4; ++i) { 9720 SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType()); 9721 Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx); 9722 9723 Stores[i] = DAG.getTruncStore( 9724 StoreChain, dl, Loads[i], Idx, SN->getPointerInfo().getWithOffset(i), 9725 MVT::i8, /* Alignment = */ 1, SN->getMemOperand()->getFlags(), 9726 SN->getAAInfo()); 9727 } 9728 9729 StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores); 9730 9731 return StoreChain; 9732 } 9733 9734 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const { 9735 SDLoc dl(Op); 9736 if (Op.getValueType() == MVT::v4i32) { 9737 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 9738 9739 SDValue Zero = BuildSplatI( 0, 1, MVT::v4i32, DAG, dl); 9740 SDValue Neg16 = BuildSplatI(-16, 4, MVT::v4i32, DAG, dl);//+16 as shift amt. 9741 9742 SDValue RHSSwap = // = vrlw RHS, 16 9743 BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl); 9744 9745 // Shrinkify inputs to v8i16. 9746 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS); 9747 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS); 9748 RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap); 9749 9750 // Low parts multiplied together, generating 32-bit results (we ignore the 9751 // top parts). 9752 SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh, 9753 LHS, RHS, DAG, dl, MVT::v4i32); 9754 9755 SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm, 9756 LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32); 9757 // Shift the high parts up 16 bits. 9758 HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd, 9759 Neg16, DAG, dl); 9760 return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd); 9761 } else if (Op.getValueType() == MVT::v8i16) { 9762 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 9763 9764 SDValue Zero = BuildSplatI(0, 1, MVT::v8i16, DAG, dl); 9765 9766 return BuildIntrinsicOp(Intrinsic::ppc_altivec_vmladduhm, 9767 LHS, RHS, Zero, DAG, dl); 9768 } else if (Op.getValueType() == MVT::v16i8) { 9769 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 9770 bool isLittleEndian = Subtarget.isLittleEndian(); 9771 9772 // Multiply the even 8-bit parts, producing 16-bit sums. 9773 SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub, 9774 LHS, RHS, DAG, dl, MVT::v8i16); 9775 EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts); 9776 9777 // Multiply the odd 8-bit parts, producing 16-bit sums. 9778 SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub, 9779 LHS, RHS, DAG, dl, MVT::v8i16); 9780 OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts); 9781 9782 // Merge the results together. Because vmuleub and vmuloub are 9783 // instructions with a big-endian bias, we must reverse the 9784 // element numbering and reverse the meaning of "odd" and "even" 9785 // when generating little endian code. 9786 int Ops[16]; 9787 for (unsigned i = 0; i != 8; ++i) { 9788 if (isLittleEndian) { 9789 Ops[i*2 ] = 2*i; 9790 Ops[i*2+1] = 2*i+16; 9791 } else { 9792 Ops[i*2 ] = 2*i+1; 9793 Ops[i*2+1] = 2*i+1+16; 9794 } 9795 } 9796 if (isLittleEndian) 9797 return DAG.getVectorShuffle(MVT::v16i8, dl, OddParts, EvenParts, Ops); 9798 else 9799 return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops); 9800 } else { 9801 llvm_unreachable("Unknown mul to lower!"); 9802 } 9803 } 9804 9805 SDValue PPCTargetLowering::LowerABS(SDValue Op, SelectionDAG &DAG) const { 9806 9807 assert(Op.getOpcode() == ISD::ABS && "Should only be called for ISD::ABS"); 9808 9809 EVT VT = Op.getValueType(); 9810 assert(VT.isVector() && 9811 "Only set vector abs as custom, scalar abs shouldn't reach here!"); 9812 assert((VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 || 9813 VT == MVT::v16i8) && 9814 "Unexpected vector element type!"); 9815 assert((VT != MVT::v2i64 || Subtarget.hasP8Altivec()) && 9816 "Current subtarget doesn't support smax v2i64!"); 9817 9818 // For vector abs, it can be lowered to: 9819 // abs x 9820 // ==> 9821 // y = -x 9822 // smax(x, y) 9823 9824 SDLoc dl(Op); 9825 SDValue X = Op.getOperand(0); 9826 SDValue Zero = DAG.getConstant(0, dl, VT); 9827 SDValue Y = DAG.getNode(ISD::SUB, dl, VT, Zero, X); 9828 9829 // SMAX patch https://reviews.llvm.org/D47332 9830 // hasn't landed yet, so use intrinsic first here. 9831 // TODO: Should use SMAX directly once SMAX patch landed 9832 Intrinsic::ID BifID = Intrinsic::ppc_altivec_vmaxsw; 9833 if (VT == MVT::v2i64) 9834 BifID = Intrinsic::ppc_altivec_vmaxsd; 9835 else if (VT == MVT::v8i16) 9836 BifID = Intrinsic::ppc_altivec_vmaxsh; 9837 else if (VT == MVT::v16i8) 9838 BifID = Intrinsic::ppc_altivec_vmaxsb; 9839 9840 return BuildIntrinsicOp(BifID, X, Y, DAG, dl, VT); 9841 } 9842 9843 // Custom lowering for fpext vf32 to v2f64 9844 SDValue PPCTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const { 9845 9846 assert(Op.getOpcode() == ISD::FP_EXTEND && 9847 "Should only be called for ISD::FP_EXTEND"); 9848 9849 // We only want to custom lower an extend from v2f32 to v2f64. 9850 if (Op.getValueType() != MVT::v2f64 || 9851 Op.getOperand(0).getValueType() != MVT::v2f32) 9852 return SDValue(); 9853 9854 SDLoc dl(Op); 9855 SDValue Op0 = Op.getOperand(0); 9856 9857 switch (Op0.getOpcode()) { 9858 default: 9859 return SDValue(); 9860 case ISD::FADD: 9861 case ISD::FMUL: 9862 case ISD::FSUB: { 9863 SDValue NewLoad[2]; 9864 for (unsigned i = 0, ie = Op0.getNumOperands(); i != ie; ++i) { 9865 // Ensure both input are loads. 9866 SDValue LdOp = Op0.getOperand(i); 9867 if (LdOp.getOpcode() != ISD::LOAD) 9868 return SDValue(); 9869 // Generate new load node. 9870 LoadSDNode *LD = cast<LoadSDNode>(LdOp); 9871 SDValue LoadOps[] = { LD->getChain(), LD->getBasePtr() }; 9872 NewLoad[i] = 9873 DAG.getMemIntrinsicNode(PPCISD::LD_VSX_LH, dl, 9874 DAG.getVTList(MVT::v4f32, MVT::Other), 9875 LoadOps, LD->getMemoryVT(), 9876 LD->getMemOperand()); 9877 } 9878 SDValue NewOp = DAG.getNode(Op0.getOpcode(), SDLoc(Op0), MVT::v4f32, 9879 NewLoad[0], NewLoad[1], 9880 Op0.getNode()->getFlags()); 9881 return DAG.getNode(PPCISD::FP_EXTEND_LH, dl, MVT::v2f64, NewOp); 9882 } 9883 case ISD::LOAD: { 9884 LoadSDNode *LD = cast<LoadSDNode>(Op0); 9885 SDValue LoadOps[] = { LD->getChain(), LD->getBasePtr() }; 9886 SDValue NewLd = 9887 DAG.getMemIntrinsicNode(PPCISD::LD_VSX_LH, dl, 9888 DAG.getVTList(MVT::v4f32, MVT::Other), 9889 LoadOps, LD->getMemoryVT(), LD->getMemOperand()); 9890 return DAG.getNode(PPCISD::FP_EXTEND_LH, dl, MVT::v2f64, NewLd); 9891 } 9892 } 9893 llvm_unreachable("ERROR:Should return for all cases within swtich."); 9894 } 9895 9896 /// LowerOperation - Provide custom lowering hooks for some operations. 9897 /// 9898 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 9899 switch (Op.getOpcode()) { 9900 default: llvm_unreachable("Wasn't expecting to be able to lower this!"); 9901 case ISD::ConstantPool: return LowerConstantPool(Op, DAG); 9902 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG); 9903 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG); 9904 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG); 9905 case ISD::JumpTable: return LowerJumpTable(Op, DAG); 9906 case ISD::SETCC: return LowerSETCC(Op, DAG); 9907 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG); 9908 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG); 9909 9910 // Variable argument lowering. 9911 case ISD::VASTART: return LowerVASTART(Op, DAG); 9912 case ISD::VAARG: return LowerVAARG(Op, DAG); 9913 case ISD::VACOPY: return LowerVACOPY(Op, DAG); 9914 9915 case ISD::STACKRESTORE: return LowerSTACKRESTORE(Op, DAG); 9916 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG); 9917 case ISD::GET_DYNAMIC_AREA_OFFSET: 9918 return LowerGET_DYNAMIC_AREA_OFFSET(Op, DAG); 9919 9920 // Exception handling lowering. 9921 case ISD::EH_DWARF_CFA: return LowerEH_DWARF_CFA(Op, DAG); 9922 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG); 9923 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG); 9924 9925 case ISD::LOAD: return LowerLOAD(Op, DAG); 9926 case ISD::STORE: return LowerSTORE(Op, DAG); 9927 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG); 9928 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG); 9929 case ISD::FP_TO_UINT: 9930 case ISD::FP_TO_SINT: return LowerFP_TO_INT(Op, DAG, SDLoc(Op)); 9931 case ISD::UINT_TO_FP: 9932 case ISD::SINT_TO_FP: return LowerINT_TO_FP(Op, DAG); 9933 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG); 9934 9935 // Lower 64-bit shifts. 9936 case ISD::SHL_PARTS: return LowerSHL_PARTS(Op, DAG); 9937 case ISD::SRL_PARTS: return LowerSRL_PARTS(Op, DAG); 9938 case ISD::SRA_PARTS: return LowerSRA_PARTS(Op, DAG); 9939 9940 // Vector-related lowering. 9941 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG); 9942 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG); 9943 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG); 9944 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG); 9945 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG); 9946 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG); 9947 case ISD::MUL: return LowerMUL(Op, DAG); 9948 case ISD::ABS: return LowerABS(Op, DAG); 9949 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG); 9950 9951 // For counter-based loop handling. 9952 case ISD::INTRINSIC_W_CHAIN: return SDValue(); 9953 9954 case ISD::BITCAST: return LowerBITCAST(Op, DAG); 9955 9956 // Frame & Return address. 9957 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG); 9958 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG); 9959 9960 case ISD::INTRINSIC_VOID: 9961 return LowerINTRINSIC_VOID(Op, DAG); 9962 case ISD::SREM: 9963 case ISD::UREM: 9964 return LowerREM(Op, DAG); 9965 case ISD::BSWAP: 9966 return LowerBSWAP(Op, DAG); 9967 case ISD::ATOMIC_CMP_SWAP: 9968 return LowerATOMIC_CMP_SWAP(Op, DAG); 9969 } 9970 } 9971 9972 void PPCTargetLowering::ReplaceNodeResults(SDNode *N, 9973 SmallVectorImpl<SDValue>&Results, 9974 SelectionDAG &DAG) const { 9975 SDLoc dl(N); 9976 switch (N->getOpcode()) { 9977 default: 9978 llvm_unreachable("Do not know how to custom type legalize this operation!"); 9979 case ISD::READCYCLECOUNTER: { 9980 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other); 9981 SDValue RTB = DAG.getNode(PPCISD::READ_TIME_BASE, dl, VTs, N->getOperand(0)); 9982 9983 Results.push_back(RTB); 9984 Results.push_back(RTB.getValue(1)); 9985 Results.push_back(RTB.getValue(2)); 9986 break; 9987 } 9988 case ISD::INTRINSIC_W_CHAIN: { 9989 if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 9990 Intrinsic::loop_decrement) 9991 break; 9992 9993 assert(N->getValueType(0) == MVT::i1 && 9994 "Unexpected result type for CTR decrement intrinsic"); 9995 EVT SVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 9996 N->getValueType(0)); 9997 SDVTList VTs = DAG.getVTList(SVT, MVT::Other); 9998 SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0), 9999 N->getOperand(1)); 10000 10001 Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewInt)); 10002 Results.push_back(NewInt.getValue(1)); 10003 break; 10004 } 10005 case ISD::VAARG: { 10006 if (!Subtarget.isSVR4ABI() || Subtarget.isPPC64()) 10007 return; 10008 10009 EVT VT = N->getValueType(0); 10010 10011 if (VT == MVT::i64) { 10012 SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG); 10013 10014 Results.push_back(NewNode); 10015 Results.push_back(NewNode.getValue(1)); 10016 } 10017 return; 10018 } 10019 case ISD::FP_TO_SINT: 10020 case ISD::FP_TO_UINT: 10021 // LowerFP_TO_INT() can only handle f32 and f64. 10022 if (N->getOperand(0).getValueType() == MVT::ppcf128) 10023 return; 10024 Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl)); 10025 return; 10026 case ISD::TRUNCATE: { 10027 EVT TrgVT = N->getValueType(0); 10028 if (TrgVT.isVector() && 10029 isOperationCustom(N->getOpcode(), TrgVT) && 10030 N->getOperand(0).getValueType().getSizeInBits() <= 128) 10031 Results.push_back(LowerTRUNCATEVector(SDValue(N, 0), DAG)); 10032 return; 10033 } 10034 case ISD::BITCAST: 10035 // Don't handle bitcast here. 10036 return; 10037 } 10038 } 10039 10040 //===----------------------------------------------------------------------===// 10041 // Other Lowering Code 10042 //===----------------------------------------------------------------------===// 10043 10044 static Instruction* callIntrinsic(IRBuilder<> &Builder, Intrinsic::ID Id) { 10045 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 10046 Function *Func = Intrinsic::getDeclaration(M, Id); 10047 return Builder.CreateCall(Func, {}); 10048 } 10049 10050 // The mappings for emitLeading/TrailingFence is taken from 10051 // http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html 10052 Instruction *PPCTargetLowering::emitLeadingFence(IRBuilder<> &Builder, 10053 Instruction *Inst, 10054 AtomicOrdering Ord) const { 10055 if (Ord == AtomicOrdering::SequentiallyConsistent) 10056 return callIntrinsic(Builder, Intrinsic::ppc_sync); 10057 if (isReleaseOrStronger(Ord)) 10058 return callIntrinsic(Builder, Intrinsic::ppc_lwsync); 10059 return nullptr; 10060 } 10061 10062 Instruction *PPCTargetLowering::emitTrailingFence(IRBuilder<> &Builder, 10063 Instruction *Inst, 10064 AtomicOrdering Ord) const { 10065 if (Inst->hasAtomicLoad() && isAcquireOrStronger(Ord)) { 10066 // See http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html and 10067 // http://www.rdrop.com/users/paulmck/scalability/paper/N2745r.2011.03.04a.html 10068 // and http://www.cl.cam.ac.uk/~pes20/cppppc/ for justification. 10069 if (isa<LoadInst>(Inst) && Subtarget.isPPC64()) 10070 return Builder.CreateCall( 10071 Intrinsic::getDeclaration( 10072 Builder.GetInsertBlock()->getParent()->getParent(), 10073 Intrinsic::ppc_cfence, {Inst->getType()}), 10074 {Inst}); 10075 // FIXME: Can use isync for rmw operation. 10076 return callIntrinsic(Builder, Intrinsic::ppc_lwsync); 10077 } 10078 return nullptr; 10079 } 10080 10081 MachineBasicBlock * 10082 PPCTargetLowering::EmitAtomicBinary(MachineInstr &MI, MachineBasicBlock *BB, 10083 unsigned AtomicSize, 10084 unsigned BinOpcode, 10085 unsigned CmpOpcode, 10086 unsigned CmpPred) const { 10087 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0. 10088 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 10089 10090 auto LoadMnemonic = PPC::LDARX; 10091 auto StoreMnemonic = PPC::STDCX; 10092 switch (AtomicSize) { 10093 default: 10094 llvm_unreachable("Unexpected size of atomic entity"); 10095 case 1: 10096 LoadMnemonic = PPC::LBARX; 10097 StoreMnemonic = PPC::STBCX; 10098 assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4"); 10099 break; 10100 case 2: 10101 LoadMnemonic = PPC::LHARX; 10102 StoreMnemonic = PPC::STHCX; 10103 assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4"); 10104 break; 10105 case 4: 10106 LoadMnemonic = PPC::LWARX; 10107 StoreMnemonic = PPC::STWCX; 10108 break; 10109 case 8: 10110 LoadMnemonic = PPC::LDARX; 10111 StoreMnemonic = PPC::STDCX; 10112 break; 10113 } 10114 10115 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 10116 MachineFunction *F = BB->getParent(); 10117 MachineFunction::iterator It = ++BB->getIterator(); 10118 10119 Register dest = MI.getOperand(0).getReg(); 10120 Register ptrA = MI.getOperand(1).getReg(); 10121 Register ptrB = MI.getOperand(2).getReg(); 10122 Register incr = MI.getOperand(3).getReg(); 10123 DebugLoc dl = MI.getDebugLoc(); 10124 10125 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB); 10126 MachineBasicBlock *loop2MBB = 10127 CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr; 10128 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 10129 F->insert(It, loopMBB); 10130 if (CmpOpcode) 10131 F->insert(It, loop2MBB); 10132 F->insert(It, exitMBB); 10133 exitMBB->splice(exitMBB->begin(), BB, 10134 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 10135 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 10136 10137 MachineRegisterInfo &RegInfo = F->getRegInfo(); 10138 Register TmpReg = (!BinOpcode) ? incr : 10139 RegInfo.createVirtualRegister( AtomicSize == 8 ? &PPC::G8RCRegClass 10140 : &PPC::GPRCRegClass); 10141 10142 // thisMBB: 10143 // ... 10144 // fallthrough --> loopMBB 10145 BB->addSuccessor(loopMBB); 10146 10147 // loopMBB: 10148 // l[wd]arx dest, ptr 10149 // add r0, dest, incr 10150 // st[wd]cx. r0, ptr 10151 // bne- loopMBB 10152 // fallthrough --> exitMBB 10153 10154 // For max/min... 10155 // loopMBB: 10156 // l[wd]arx dest, ptr 10157 // cmpl?[wd] incr, dest 10158 // bgt exitMBB 10159 // loop2MBB: 10160 // st[wd]cx. dest, ptr 10161 // bne- loopMBB 10162 // fallthrough --> exitMBB 10163 10164 BB = loopMBB; 10165 BuildMI(BB, dl, TII->get(LoadMnemonic), dest) 10166 .addReg(ptrA).addReg(ptrB); 10167 if (BinOpcode) 10168 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest); 10169 if (CmpOpcode) { 10170 // Signed comparisons of byte or halfword values must be sign-extended. 10171 if (CmpOpcode == PPC::CMPW && AtomicSize < 4) { 10172 unsigned ExtReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass); 10173 BuildMI(BB, dl, TII->get(AtomicSize == 1 ? PPC::EXTSB : PPC::EXTSH), 10174 ExtReg).addReg(dest); 10175 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0) 10176 .addReg(incr).addReg(ExtReg); 10177 } else 10178 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0) 10179 .addReg(incr).addReg(dest); 10180 10181 BuildMI(BB, dl, TII->get(PPC::BCC)) 10182 .addImm(CmpPred).addReg(PPC::CR0).addMBB(exitMBB); 10183 BB->addSuccessor(loop2MBB); 10184 BB->addSuccessor(exitMBB); 10185 BB = loop2MBB; 10186 } 10187 BuildMI(BB, dl, TII->get(StoreMnemonic)) 10188 .addReg(TmpReg).addReg(ptrA).addReg(ptrB); 10189 BuildMI(BB, dl, TII->get(PPC::BCC)) 10190 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB); 10191 BB->addSuccessor(loopMBB); 10192 BB->addSuccessor(exitMBB); 10193 10194 // exitMBB: 10195 // ... 10196 BB = exitMBB; 10197 return BB; 10198 } 10199 10200 MachineBasicBlock *PPCTargetLowering::EmitPartwordAtomicBinary( 10201 MachineInstr &MI, MachineBasicBlock *BB, 10202 bool is8bit, // operation 10203 unsigned BinOpcode, unsigned CmpOpcode, unsigned CmpPred) const { 10204 // If we support part-word atomic mnemonics, just use them 10205 if (Subtarget.hasPartwordAtomics()) 10206 return EmitAtomicBinary(MI, BB, is8bit ? 1 : 2, BinOpcode, CmpOpcode, 10207 CmpPred); 10208 10209 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0. 10210 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 10211 // In 64 bit mode we have to use 64 bits for addresses, even though the 10212 // lwarx/stwcx are 32 bits. With the 32-bit atomics we can use address 10213 // registers without caring whether they're 32 or 64, but here we're 10214 // doing actual arithmetic on the addresses. 10215 bool is64bit = Subtarget.isPPC64(); 10216 bool isLittleEndian = Subtarget.isLittleEndian(); 10217 unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO; 10218 10219 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 10220 MachineFunction *F = BB->getParent(); 10221 MachineFunction::iterator It = ++BB->getIterator(); 10222 10223 unsigned dest = MI.getOperand(0).getReg(); 10224 unsigned ptrA = MI.getOperand(1).getReg(); 10225 unsigned ptrB = MI.getOperand(2).getReg(); 10226 unsigned incr = MI.getOperand(3).getReg(); 10227 DebugLoc dl = MI.getDebugLoc(); 10228 10229 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB); 10230 MachineBasicBlock *loop2MBB = 10231 CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr; 10232 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 10233 F->insert(It, loopMBB); 10234 if (CmpOpcode) 10235 F->insert(It, loop2MBB); 10236 F->insert(It, exitMBB); 10237 exitMBB->splice(exitMBB->begin(), BB, 10238 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 10239 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 10240 10241 MachineRegisterInfo &RegInfo = F->getRegInfo(); 10242 const TargetRegisterClass *RC = 10243 is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 10244 const TargetRegisterClass *GPRC = &PPC::GPRCRegClass; 10245 10246 Register PtrReg = RegInfo.createVirtualRegister(RC); 10247 Register Shift1Reg = RegInfo.createVirtualRegister(GPRC); 10248 Register ShiftReg = 10249 isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC); 10250 Register Incr2Reg = RegInfo.createVirtualRegister(GPRC); 10251 Register MaskReg = RegInfo.createVirtualRegister(GPRC); 10252 Register Mask2Reg = RegInfo.createVirtualRegister(GPRC); 10253 Register Mask3Reg = RegInfo.createVirtualRegister(GPRC); 10254 Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC); 10255 Register Tmp3Reg = RegInfo.createVirtualRegister(GPRC); 10256 Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC); 10257 Register TmpDestReg = RegInfo.createVirtualRegister(GPRC); 10258 Register Ptr1Reg; 10259 Register TmpReg = 10260 (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(GPRC); 10261 10262 // thisMBB: 10263 // ... 10264 // fallthrough --> loopMBB 10265 BB->addSuccessor(loopMBB); 10266 10267 // The 4-byte load must be aligned, while a char or short may be 10268 // anywhere in the word. Hence all this nasty bookkeeping code. 10269 // add ptr1, ptrA, ptrB [copy if ptrA==0] 10270 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27] 10271 // xori shift, shift1, 24 [16] 10272 // rlwinm ptr, ptr1, 0, 0, 29 10273 // slw incr2, incr, shift 10274 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535] 10275 // slw mask, mask2, shift 10276 // loopMBB: 10277 // lwarx tmpDest, ptr 10278 // add tmp, tmpDest, incr2 10279 // andc tmp2, tmpDest, mask 10280 // and tmp3, tmp, mask 10281 // or tmp4, tmp3, tmp2 10282 // stwcx. tmp4, ptr 10283 // bne- loopMBB 10284 // fallthrough --> exitMBB 10285 // srw dest, tmpDest, shift 10286 if (ptrA != ZeroReg) { 10287 Ptr1Reg = RegInfo.createVirtualRegister(RC); 10288 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg) 10289 .addReg(ptrA) 10290 .addReg(ptrB); 10291 } else { 10292 Ptr1Reg = ptrB; 10293 } 10294 // We need use 32-bit subregister to avoid mismatch register class in 64-bit 10295 // mode. 10296 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg) 10297 .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0) 10298 .addImm(3) 10299 .addImm(27) 10300 .addImm(is8bit ? 28 : 27); 10301 if (!isLittleEndian) 10302 BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg) 10303 .addReg(Shift1Reg) 10304 .addImm(is8bit ? 24 : 16); 10305 if (is64bit) 10306 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg) 10307 .addReg(Ptr1Reg) 10308 .addImm(0) 10309 .addImm(61); 10310 else 10311 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg) 10312 .addReg(Ptr1Reg) 10313 .addImm(0) 10314 .addImm(0) 10315 .addImm(29); 10316 BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg).addReg(incr).addReg(ShiftReg); 10317 if (is8bit) 10318 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255); 10319 else { 10320 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0); 10321 BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg) 10322 .addReg(Mask3Reg) 10323 .addImm(65535); 10324 } 10325 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg) 10326 .addReg(Mask2Reg) 10327 .addReg(ShiftReg); 10328 10329 BB = loopMBB; 10330 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg) 10331 .addReg(ZeroReg) 10332 .addReg(PtrReg); 10333 if (BinOpcode) 10334 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg) 10335 .addReg(Incr2Reg) 10336 .addReg(TmpDestReg); 10337 BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg) 10338 .addReg(TmpDestReg) 10339 .addReg(MaskReg); 10340 BuildMI(BB, dl, TII->get(PPC::AND), Tmp3Reg).addReg(TmpReg).addReg(MaskReg); 10341 if (CmpOpcode) { 10342 // For unsigned comparisons, we can directly compare the shifted values. 10343 // For signed comparisons we shift and sign extend. 10344 unsigned SReg = RegInfo.createVirtualRegister(GPRC); 10345 BuildMI(BB, dl, TII->get(PPC::AND), SReg) 10346 .addReg(TmpDestReg) 10347 .addReg(MaskReg); 10348 unsigned ValueReg = SReg; 10349 unsigned CmpReg = Incr2Reg; 10350 if (CmpOpcode == PPC::CMPW) { 10351 ValueReg = RegInfo.createVirtualRegister(GPRC); 10352 BuildMI(BB, dl, TII->get(PPC::SRW), ValueReg) 10353 .addReg(SReg) 10354 .addReg(ShiftReg); 10355 unsigned ValueSReg = RegInfo.createVirtualRegister(GPRC); 10356 BuildMI(BB, dl, TII->get(is8bit ? PPC::EXTSB : PPC::EXTSH), ValueSReg) 10357 .addReg(ValueReg); 10358 ValueReg = ValueSReg; 10359 CmpReg = incr; 10360 } 10361 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0) 10362 .addReg(CmpReg) 10363 .addReg(ValueReg); 10364 BuildMI(BB, dl, TII->get(PPC::BCC)) 10365 .addImm(CmpPred) 10366 .addReg(PPC::CR0) 10367 .addMBB(exitMBB); 10368 BB->addSuccessor(loop2MBB); 10369 BB->addSuccessor(exitMBB); 10370 BB = loop2MBB; 10371 } 10372 BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg).addReg(Tmp3Reg).addReg(Tmp2Reg); 10373 BuildMI(BB, dl, TII->get(PPC::STWCX)) 10374 .addReg(Tmp4Reg) 10375 .addReg(ZeroReg) 10376 .addReg(PtrReg); 10377 BuildMI(BB, dl, TII->get(PPC::BCC)) 10378 .addImm(PPC::PRED_NE) 10379 .addReg(PPC::CR0) 10380 .addMBB(loopMBB); 10381 BB->addSuccessor(loopMBB); 10382 BB->addSuccessor(exitMBB); 10383 10384 // exitMBB: 10385 // ... 10386 BB = exitMBB; 10387 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest) 10388 .addReg(TmpDestReg) 10389 .addReg(ShiftReg); 10390 return BB; 10391 } 10392 10393 llvm::MachineBasicBlock * 10394 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr &MI, 10395 MachineBasicBlock *MBB) const { 10396 DebugLoc DL = MI.getDebugLoc(); 10397 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 10398 const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo(); 10399 10400 MachineFunction *MF = MBB->getParent(); 10401 MachineRegisterInfo &MRI = MF->getRegInfo(); 10402 10403 const BasicBlock *BB = MBB->getBasicBlock(); 10404 MachineFunction::iterator I = ++MBB->getIterator(); 10405 10406 unsigned DstReg = MI.getOperand(0).getReg(); 10407 const TargetRegisterClass *RC = MRI.getRegClass(DstReg); 10408 assert(TRI->isTypeLegalForClass(*RC, MVT::i32) && "Invalid destination!"); 10409 unsigned mainDstReg = MRI.createVirtualRegister(RC); 10410 unsigned restoreDstReg = MRI.createVirtualRegister(RC); 10411 10412 MVT PVT = getPointerTy(MF->getDataLayout()); 10413 assert((PVT == MVT::i64 || PVT == MVT::i32) && 10414 "Invalid Pointer Size!"); 10415 // For v = setjmp(buf), we generate 10416 // 10417 // thisMBB: 10418 // SjLjSetup mainMBB 10419 // bl mainMBB 10420 // v_restore = 1 10421 // b sinkMBB 10422 // 10423 // mainMBB: 10424 // buf[LabelOffset] = LR 10425 // v_main = 0 10426 // 10427 // sinkMBB: 10428 // v = phi(main, restore) 10429 // 10430 10431 MachineBasicBlock *thisMBB = MBB; 10432 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB); 10433 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB); 10434 MF->insert(I, mainMBB); 10435 MF->insert(I, sinkMBB); 10436 10437 MachineInstrBuilder MIB; 10438 10439 // Transfer the remainder of BB and its successor edges to sinkMBB. 10440 sinkMBB->splice(sinkMBB->begin(), MBB, 10441 std::next(MachineBasicBlock::iterator(MI)), MBB->end()); 10442 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB); 10443 10444 // Note that the structure of the jmp_buf used here is not compatible 10445 // with that used by libc, and is not designed to be. Specifically, it 10446 // stores only those 'reserved' registers that LLVM does not otherwise 10447 // understand how to spill. Also, by convention, by the time this 10448 // intrinsic is called, Clang has already stored the frame address in the 10449 // first slot of the buffer and stack address in the third. Following the 10450 // X86 target code, we'll store the jump address in the second slot. We also 10451 // need to save the TOC pointer (R2) to handle jumps between shared 10452 // libraries, and that will be stored in the fourth slot. The thread 10453 // identifier (R13) is not affected. 10454 10455 // thisMBB: 10456 const int64_t LabelOffset = 1 * PVT.getStoreSize(); 10457 const int64_t TOCOffset = 3 * PVT.getStoreSize(); 10458 const int64_t BPOffset = 4 * PVT.getStoreSize(); 10459 10460 // Prepare IP either in reg. 10461 const TargetRegisterClass *PtrRC = getRegClassFor(PVT); 10462 unsigned LabelReg = MRI.createVirtualRegister(PtrRC); 10463 unsigned BufReg = MI.getOperand(1).getReg(); 10464 10465 if (Subtarget.isPPC64() && Subtarget.isSVR4ABI()) { 10466 setUsesTOCBasePtr(*MBB->getParent()); 10467 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD)) 10468 .addReg(PPC::X2) 10469 .addImm(TOCOffset) 10470 .addReg(BufReg) 10471 .cloneMemRefs(MI); 10472 } 10473 10474 // Naked functions never have a base pointer, and so we use r1. For all 10475 // other functions, this decision must be delayed until during PEI. 10476 unsigned BaseReg; 10477 if (MF->getFunction().hasFnAttribute(Attribute::Naked)) 10478 BaseReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1; 10479 else 10480 BaseReg = Subtarget.isPPC64() ? PPC::BP8 : PPC::BP; 10481 10482 MIB = BuildMI(*thisMBB, MI, DL, 10483 TII->get(Subtarget.isPPC64() ? PPC::STD : PPC::STW)) 10484 .addReg(BaseReg) 10485 .addImm(BPOffset) 10486 .addReg(BufReg) 10487 .cloneMemRefs(MI); 10488 10489 // Setup 10490 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB); 10491 MIB.addRegMask(TRI->getNoPreservedMask()); 10492 10493 BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1); 10494 10495 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup)) 10496 .addMBB(mainMBB); 10497 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB); 10498 10499 thisMBB->addSuccessor(mainMBB, BranchProbability::getZero()); 10500 thisMBB->addSuccessor(sinkMBB, BranchProbability::getOne()); 10501 10502 // mainMBB: 10503 // mainDstReg = 0 10504 MIB = 10505 BuildMI(mainMBB, DL, 10506 TII->get(Subtarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg); 10507 10508 // Store IP 10509 if (Subtarget.isPPC64()) { 10510 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD)) 10511 .addReg(LabelReg) 10512 .addImm(LabelOffset) 10513 .addReg(BufReg); 10514 } else { 10515 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW)) 10516 .addReg(LabelReg) 10517 .addImm(LabelOffset) 10518 .addReg(BufReg); 10519 } 10520 MIB.cloneMemRefs(MI); 10521 10522 BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0); 10523 mainMBB->addSuccessor(sinkMBB); 10524 10525 // sinkMBB: 10526 BuildMI(*sinkMBB, sinkMBB->begin(), DL, 10527 TII->get(PPC::PHI), DstReg) 10528 .addReg(mainDstReg).addMBB(mainMBB) 10529 .addReg(restoreDstReg).addMBB(thisMBB); 10530 10531 MI.eraseFromParent(); 10532 return sinkMBB; 10533 } 10534 10535 MachineBasicBlock * 10536 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr &MI, 10537 MachineBasicBlock *MBB) const { 10538 DebugLoc DL = MI.getDebugLoc(); 10539 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 10540 10541 MachineFunction *MF = MBB->getParent(); 10542 MachineRegisterInfo &MRI = MF->getRegInfo(); 10543 10544 MVT PVT = getPointerTy(MF->getDataLayout()); 10545 assert((PVT == MVT::i64 || PVT == MVT::i32) && 10546 "Invalid Pointer Size!"); 10547 10548 const TargetRegisterClass *RC = 10549 (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 10550 unsigned Tmp = MRI.createVirtualRegister(RC); 10551 // Since FP is only updated here but NOT referenced, it's treated as GPR. 10552 unsigned FP = (PVT == MVT::i64) ? PPC::X31 : PPC::R31; 10553 unsigned SP = (PVT == MVT::i64) ? PPC::X1 : PPC::R1; 10554 unsigned BP = 10555 (PVT == MVT::i64) 10556 ? PPC::X30 10557 : (Subtarget.isSVR4ABI() && isPositionIndependent() ? PPC::R29 10558 : PPC::R30); 10559 10560 MachineInstrBuilder MIB; 10561 10562 const int64_t LabelOffset = 1 * PVT.getStoreSize(); 10563 const int64_t SPOffset = 2 * PVT.getStoreSize(); 10564 const int64_t TOCOffset = 3 * PVT.getStoreSize(); 10565 const int64_t BPOffset = 4 * PVT.getStoreSize(); 10566 10567 unsigned BufReg = MI.getOperand(0).getReg(); 10568 10569 // Reload FP (the jumped-to function may not have had a 10570 // frame pointer, and if so, then its r31 will be restored 10571 // as necessary). 10572 if (PVT == MVT::i64) { 10573 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP) 10574 .addImm(0) 10575 .addReg(BufReg); 10576 } else { 10577 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP) 10578 .addImm(0) 10579 .addReg(BufReg); 10580 } 10581 MIB.cloneMemRefs(MI); 10582 10583 // Reload IP 10584 if (PVT == MVT::i64) { 10585 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp) 10586 .addImm(LabelOffset) 10587 .addReg(BufReg); 10588 } else { 10589 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp) 10590 .addImm(LabelOffset) 10591 .addReg(BufReg); 10592 } 10593 MIB.cloneMemRefs(MI); 10594 10595 // Reload SP 10596 if (PVT == MVT::i64) { 10597 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP) 10598 .addImm(SPOffset) 10599 .addReg(BufReg); 10600 } else { 10601 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP) 10602 .addImm(SPOffset) 10603 .addReg(BufReg); 10604 } 10605 MIB.cloneMemRefs(MI); 10606 10607 // Reload BP 10608 if (PVT == MVT::i64) { 10609 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP) 10610 .addImm(BPOffset) 10611 .addReg(BufReg); 10612 } else { 10613 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP) 10614 .addImm(BPOffset) 10615 .addReg(BufReg); 10616 } 10617 MIB.cloneMemRefs(MI); 10618 10619 // Reload TOC 10620 if (PVT == MVT::i64 && Subtarget.isSVR4ABI()) { 10621 setUsesTOCBasePtr(*MBB->getParent()); 10622 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2) 10623 .addImm(TOCOffset) 10624 .addReg(BufReg) 10625 .cloneMemRefs(MI); 10626 } 10627 10628 // Jump 10629 BuildMI(*MBB, MI, DL, 10630 TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp); 10631 BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR)); 10632 10633 MI.eraseFromParent(); 10634 return MBB; 10635 } 10636 10637 MachineBasicBlock * 10638 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI, 10639 MachineBasicBlock *BB) const { 10640 if (MI.getOpcode() == TargetOpcode::STACKMAP || 10641 MI.getOpcode() == TargetOpcode::PATCHPOINT) { 10642 if (Subtarget.isPPC64() && Subtarget.isSVR4ABI() && 10643 MI.getOpcode() == TargetOpcode::PATCHPOINT) { 10644 // Call lowering should have added an r2 operand to indicate a dependence 10645 // on the TOC base pointer value. It can't however, because there is no 10646 // way to mark the dependence as implicit there, and so the stackmap code 10647 // will confuse it with a regular operand. Instead, add the dependence 10648 // here. 10649 MI.addOperand(MachineOperand::CreateReg(PPC::X2, false, true)); 10650 } 10651 10652 return emitPatchPoint(MI, BB); 10653 } 10654 10655 if (MI.getOpcode() == PPC::EH_SjLj_SetJmp32 || 10656 MI.getOpcode() == PPC::EH_SjLj_SetJmp64) { 10657 return emitEHSjLjSetJmp(MI, BB); 10658 } else if (MI.getOpcode() == PPC::EH_SjLj_LongJmp32 || 10659 MI.getOpcode() == PPC::EH_SjLj_LongJmp64) { 10660 return emitEHSjLjLongJmp(MI, BB); 10661 } 10662 10663 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 10664 10665 // To "insert" these instructions we actually have to insert their 10666 // control-flow patterns. 10667 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 10668 MachineFunction::iterator It = ++BB->getIterator(); 10669 10670 MachineFunction *F = BB->getParent(); 10671 10672 if (MI.getOpcode() == PPC::SELECT_CC_I4 || 10673 MI.getOpcode() == PPC::SELECT_CC_I8 || MI.getOpcode() == PPC::SELECT_I4 || 10674 MI.getOpcode() == PPC::SELECT_I8) { 10675 SmallVector<MachineOperand, 2> Cond; 10676 if (MI.getOpcode() == PPC::SELECT_CC_I4 || 10677 MI.getOpcode() == PPC::SELECT_CC_I8) 10678 Cond.push_back(MI.getOperand(4)); 10679 else 10680 Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET)); 10681 Cond.push_back(MI.getOperand(1)); 10682 10683 DebugLoc dl = MI.getDebugLoc(); 10684 TII->insertSelect(*BB, MI, dl, MI.getOperand(0).getReg(), Cond, 10685 MI.getOperand(2).getReg(), MI.getOperand(3).getReg()); 10686 } else if (MI.getOpcode() == PPC::SELECT_CC_I4 || 10687 MI.getOpcode() == PPC::SELECT_CC_I8 || 10688 MI.getOpcode() == PPC::SELECT_CC_F4 || 10689 MI.getOpcode() == PPC::SELECT_CC_F8 || 10690 MI.getOpcode() == PPC::SELECT_CC_F16 || 10691 MI.getOpcode() == PPC::SELECT_CC_QFRC || 10692 MI.getOpcode() == PPC::SELECT_CC_QSRC || 10693 MI.getOpcode() == PPC::SELECT_CC_QBRC || 10694 MI.getOpcode() == PPC::SELECT_CC_VRRC || 10695 MI.getOpcode() == PPC::SELECT_CC_VSFRC || 10696 MI.getOpcode() == PPC::SELECT_CC_VSSRC || 10697 MI.getOpcode() == PPC::SELECT_CC_VSRC || 10698 MI.getOpcode() == PPC::SELECT_CC_SPE4 || 10699 MI.getOpcode() == PPC::SELECT_CC_SPE || 10700 MI.getOpcode() == PPC::SELECT_I4 || 10701 MI.getOpcode() == PPC::SELECT_I8 || 10702 MI.getOpcode() == PPC::SELECT_F4 || 10703 MI.getOpcode() == PPC::SELECT_F8 || 10704 MI.getOpcode() == PPC::SELECT_F16 || 10705 MI.getOpcode() == PPC::SELECT_QFRC || 10706 MI.getOpcode() == PPC::SELECT_QSRC || 10707 MI.getOpcode() == PPC::SELECT_QBRC || 10708 MI.getOpcode() == PPC::SELECT_SPE || 10709 MI.getOpcode() == PPC::SELECT_SPE4 || 10710 MI.getOpcode() == PPC::SELECT_VRRC || 10711 MI.getOpcode() == PPC::SELECT_VSFRC || 10712 MI.getOpcode() == PPC::SELECT_VSSRC || 10713 MI.getOpcode() == PPC::SELECT_VSRC) { 10714 // The incoming instruction knows the destination vreg to set, the 10715 // condition code register to branch on, the true/false values to 10716 // select between, and a branch opcode to use. 10717 10718 // thisMBB: 10719 // ... 10720 // TrueVal = ... 10721 // cmpTY ccX, r1, r2 10722 // bCC copy1MBB 10723 // fallthrough --> copy0MBB 10724 MachineBasicBlock *thisMBB = BB; 10725 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB); 10726 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 10727 DebugLoc dl = MI.getDebugLoc(); 10728 F->insert(It, copy0MBB); 10729 F->insert(It, sinkMBB); 10730 10731 // Transfer the remainder of BB and its successor edges to sinkMBB. 10732 sinkMBB->splice(sinkMBB->begin(), BB, 10733 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 10734 sinkMBB->transferSuccessorsAndUpdatePHIs(BB); 10735 10736 // Next, add the true and fallthrough blocks as its successors. 10737 BB->addSuccessor(copy0MBB); 10738 BB->addSuccessor(sinkMBB); 10739 10740 if (MI.getOpcode() == PPC::SELECT_I4 || MI.getOpcode() == PPC::SELECT_I8 || 10741 MI.getOpcode() == PPC::SELECT_F4 || MI.getOpcode() == PPC::SELECT_F8 || 10742 MI.getOpcode() == PPC::SELECT_F16 || 10743 MI.getOpcode() == PPC::SELECT_SPE4 || 10744 MI.getOpcode() == PPC::SELECT_SPE || 10745 MI.getOpcode() == PPC::SELECT_QFRC || 10746 MI.getOpcode() == PPC::SELECT_QSRC || 10747 MI.getOpcode() == PPC::SELECT_QBRC || 10748 MI.getOpcode() == PPC::SELECT_VRRC || 10749 MI.getOpcode() == PPC::SELECT_VSFRC || 10750 MI.getOpcode() == PPC::SELECT_VSSRC || 10751 MI.getOpcode() == PPC::SELECT_VSRC) { 10752 BuildMI(BB, dl, TII->get(PPC::BC)) 10753 .addReg(MI.getOperand(1).getReg()) 10754 .addMBB(sinkMBB); 10755 } else { 10756 unsigned SelectPred = MI.getOperand(4).getImm(); 10757 BuildMI(BB, dl, TII->get(PPC::BCC)) 10758 .addImm(SelectPred) 10759 .addReg(MI.getOperand(1).getReg()) 10760 .addMBB(sinkMBB); 10761 } 10762 10763 // copy0MBB: 10764 // %FalseValue = ... 10765 // # fallthrough to sinkMBB 10766 BB = copy0MBB; 10767 10768 // Update machine-CFG edges 10769 BB->addSuccessor(sinkMBB); 10770 10771 // sinkMBB: 10772 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ] 10773 // ... 10774 BB = sinkMBB; 10775 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::PHI), MI.getOperand(0).getReg()) 10776 .addReg(MI.getOperand(3).getReg()) 10777 .addMBB(copy0MBB) 10778 .addReg(MI.getOperand(2).getReg()) 10779 .addMBB(thisMBB); 10780 } else if (MI.getOpcode() == PPC::ReadTB) { 10781 // To read the 64-bit time-base register on a 32-bit target, we read the 10782 // two halves. Should the counter have wrapped while it was being read, we 10783 // need to try again. 10784 // ... 10785 // readLoop: 10786 // mfspr Rx,TBU # load from TBU 10787 // mfspr Ry,TB # load from TB 10788 // mfspr Rz,TBU # load from TBU 10789 // cmpw crX,Rx,Rz # check if 'old'='new' 10790 // bne readLoop # branch if they're not equal 10791 // ... 10792 10793 MachineBasicBlock *readMBB = F->CreateMachineBasicBlock(LLVM_BB); 10794 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 10795 DebugLoc dl = MI.getDebugLoc(); 10796 F->insert(It, readMBB); 10797 F->insert(It, sinkMBB); 10798 10799 // Transfer the remainder of BB and its successor edges to sinkMBB. 10800 sinkMBB->splice(sinkMBB->begin(), BB, 10801 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 10802 sinkMBB->transferSuccessorsAndUpdatePHIs(BB); 10803 10804 BB->addSuccessor(readMBB); 10805 BB = readMBB; 10806 10807 MachineRegisterInfo &RegInfo = F->getRegInfo(); 10808 unsigned ReadAgainReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass); 10809 unsigned LoReg = MI.getOperand(0).getReg(); 10810 unsigned HiReg = MI.getOperand(1).getReg(); 10811 10812 BuildMI(BB, dl, TII->get(PPC::MFSPR), HiReg).addImm(269); 10813 BuildMI(BB, dl, TII->get(PPC::MFSPR), LoReg).addImm(268); 10814 BuildMI(BB, dl, TII->get(PPC::MFSPR), ReadAgainReg).addImm(269); 10815 10816 unsigned CmpReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass); 10817 10818 BuildMI(BB, dl, TII->get(PPC::CMPW), CmpReg) 10819 .addReg(HiReg) 10820 .addReg(ReadAgainReg); 10821 BuildMI(BB, dl, TII->get(PPC::BCC)) 10822 .addImm(PPC::PRED_NE) 10823 .addReg(CmpReg) 10824 .addMBB(readMBB); 10825 10826 BB->addSuccessor(readMBB); 10827 BB->addSuccessor(sinkMBB); 10828 } else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I8) 10829 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4); 10830 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I16) 10831 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4); 10832 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I32) 10833 BB = EmitAtomicBinary(MI, BB, 4, PPC::ADD4); 10834 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I64) 10835 BB = EmitAtomicBinary(MI, BB, 8, PPC::ADD8); 10836 10837 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I8) 10838 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND); 10839 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I16) 10840 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND); 10841 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I32) 10842 BB = EmitAtomicBinary(MI, BB, 4, PPC::AND); 10843 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I64) 10844 BB = EmitAtomicBinary(MI, BB, 8, PPC::AND8); 10845 10846 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I8) 10847 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR); 10848 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I16) 10849 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR); 10850 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I32) 10851 BB = EmitAtomicBinary(MI, BB, 4, PPC::OR); 10852 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I64) 10853 BB = EmitAtomicBinary(MI, BB, 8, PPC::OR8); 10854 10855 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I8) 10856 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR); 10857 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I16) 10858 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR); 10859 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I32) 10860 BB = EmitAtomicBinary(MI, BB, 4, PPC::XOR); 10861 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I64) 10862 BB = EmitAtomicBinary(MI, BB, 8, PPC::XOR8); 10863 10864 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I8) 10865 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::NAND); 10866 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I16) 10867 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::NAND); 10868 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I32) 10869 BB = EmitAtomicBinary(MI, BB, 4, PPC::NAND); 10870 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I64) 10871 BB = EmitAtomicBinary(MI, BB, 8, PPC::NAND8); 10872 10873 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I8) 10874 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF); 10875 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I16) 10876 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF); 10877 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I32) 10878 BB = EmitAtomicBinary(MI, BB, 4, PPC::SUBF); 10879 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I64) 10880 BB = EmitAtomicBinary(MI, BB, 8, PPC::SUBF8); 10881 10882 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I8) 10883 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_GE); 10884 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I16) 10885 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_GE); 10886 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I32) 10887 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_GE); 10888 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I64) 10889 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_GE); 10890 10891 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I8) 10892 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_LE); 10893 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I16) 10894 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_LE); 10895 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I32) 10896 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_LE); 10897 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I64) 10898 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_LE); 10899 10900 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I8) 10901 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_GE); 10902 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I16) 10903 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_GE); 10904 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I32) 10905 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_GE); 10906 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I64) 10907 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_GE); 10908 10909 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I8) 10910 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_LE); 10911 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I16) 10912 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_LE); 10913 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I32) 10914 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_LE); 10915 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I64) 10916 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_LE); 10917 10918 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I8) 10919 BB = EmitPartwordAtomicBinary(MI, BB, true, 0); 10920 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I16) 10921 BB = EmitPartwordAtomicBinary(MI, BB, false, 0); 10922 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I32) 10923 BB = EmitAtomicBinary(MI, BB, 4, 0); 10924 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I64) 10925 BB = EmitAtomicBinary(MI, BB, 8, 0); 10926 else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 || 10927 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64 || 10928 (Subtarget.hasPartwordAtomics() && 10929 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8) || 10930 (Subtarget.hasPartwordAtomics() && 10931 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16)) { 10932 bool is64bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64; 10933 10934 auto LoadMnemonic = PPC::LDARX; 10935 auto StoreMnemonic = PPC::STDCX; 10936 switch (MI.getOpcode()) { 10937 default: 10938 llvm_unreachable("Compare and swap of unknown size"); 10939 case PPC::ATOMIC_CMP_SWAP_I8: 10940 LoadMnemonic = PPC::LBARX; 10941 StoreMnemonic = PPC::STBCX; 10942 assert(Subtarget.hasPartwordAtomics() && "No support partword atomics."); 10943 break; 10944 case PPC::ATOMIC_CMP_SWAP_I16: 10945 LoadMnemonic = PPC::LHARX; 10946 StoreMnemonic = PPC::STHCX; 10947 assert(Subtarget.hasPartwordAtomics() && "No support partword atomics."); 10948 break; 10949 case PPC::ATOMIC_CMP_SWAP_I32: 10950 LoadMnemonic = PPC::LWARX; 10951 StoreMnemonic = PPC::STWCX; 10952 break; 10953 case PPC::ATOMIC_CMP_SWAP_I64: 10954 LoadMnemonic = PPC::LDARX; 10955 StoreMnemonic = PPC::STDCX; 10956 break; 10957 } 10958 unsigned dest = MI.getOperand(0).getReg(); 10959 unsigned ptrA = MI.getOperand(1).getReg(); 10960 unsigned ptrB = MI.getOperand(2).getReg(); 10961 unsigned oldval = MI.getOperand(3).getReg(); 10962 unsigned newval = MI.getOperand(4).getReg(); 10963 DebugLoc dl = MI.getDebugLoc(); 10964 10965 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB); 10966 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB); 10967 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB); 10968 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 10969 F->insert(It, loop1MBB); 10970 F->insert(It, loop2MBB); 10971 F->insert(It, midMBB); 10972 F->insert(It, exitMBB); 10973 exitMBB->splice(exitMBB->begin(), BB, 10974 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 10975 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 10976 10977 // thisMBB: 10978 // ... 10979 // fallthrough --> loopMBB 10980 BB->addSuccessor(loop1MBB); 10981 10982 // loop1MBB: 10983 // l[bhwd]arx dest, ptr 10984 // cmp[wd] dest, oldval 10985 // bne- midMBB 10986 // loop2MBB: 10987 // st[bhwd]cx. newval, ptr 10988 // bne- loopMBB 10989 // b exitBB 10990 // midMBB: 10991 // st[bhwd]cx. dest, ptr 10992 // exitBB: 10993 BB = loop1MBB; 10994 BuildMI(BB, dl, TII->get(LoadMnemonic), dest).addReg(ptrA).addReg(ptrB); 10995 BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0) 10996 .addReg(oldval) 10997 .addReg(dest); 10998 BuildMI(BB, dl, TII->get(PPC::BCC)) 10999 .addImm(PPC::PRED_NE) 11000 .addReg(PPC::CR0) 11001 .addMBB(midMBB); 11002 BB->addSuccessor(loop2MBB); 11003 BB->addSuccessor(midMBB); 11004 11005 BB = loop2MBB; 11006 BuildMI(BB, dl, TII->get(StoreMnemonic)) 11007 .addReg(newval) 11008 .addReg(ptrA) 11009 .addReg(ptrB); 11010 BuildMI(BB, dl, TII->get(PPC::BCC)) 11011 .addImm(PPC::PRED_NE) 11012 .addReg(PPC::CR0) 11013 .addMBB(loop1MBB); 11014 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB); 11015 BB->addSuccessor(loop1MBB); 11016 BB->addSuccessor(exitMBB); 11017 11018 BB = midMBB; 11019 BuildMI(BB, dl, TII->get(StoreMnemonic)) 11020 .addReg(dest) 11021 .addReg(ptrA) 11022 .addReg(ptrB); 11023 BB->addSuccessor(exitMBB); 11024 11025 // exitMBB: 11026 // ... 11027 BB = exitMBB; 11028 } else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 || 11029 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) { 11030 // We must use 64-bit registers for addresses when targeting 64-bit, 11031 // since we're actually doing arithmetic on them. Other registers 11032 // can be 32-bit. 11033 bool is64bit = Subtarget.isPPC64(); 11034 bool isLittleEndian = Subtarget.isLittleEndian(); 11035 bool is8bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8; 11036 11037 unsigned dest = MI.getOperand(0).getReg(); 11038 unsigned ptrA = MI.getOperand(1).getReg(); 11039 unsigned ptrB = MI.getOperand(2).getReg(); 11040 unsigned oldval = MI.getOperand(3).getReg(); 11041 unsigned newval = MI.getOperand(4).getReg(); 11042 DebugLoc dl = MI.getDebugLoc(); 11043 11044 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB); 11045 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB); 11046 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB); 11047 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 11048 F->insert(It, loop1MBB); 11049 F->insert(It, loop2MBB); 11050 F->insert(It, midMBB); 11051 F->insert(It, exitMBB); 11052 exitMBB->splice(exitMBB->begin(), BB, 11053 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 11054 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 11055 11056 MachineRegisterInfo &RegInfo = F->getRegInfo(); 11057 const TargetRegisterClass *RC = 11058 is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 11059 const TargetRegisterClass *GPRC = &PPC::GPRCRegClass; 11060 11061 Register PtrReg = RegInfo.createVirtualRegister(RC); 11062 Register Shift1Reg = RegInfo.createVirtualRegister(GPRC); 11063 Register ShiftReg = 11064 isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC); 11065 Register NewVal2Reg = RegInfo.createVirtualRegister(GPRC); 11066 Register NewVal3Reg = RegInfo.createVirtualRegister(GPRC); 11067 Register OldVal2Reg = RegInfo.createVirtualRegister(GPRC); 11068 Register OldVal3Reg = RegInfo.createVirtualRegister(GPRC); 11069 Register MaskReg = RegInfo.createVirtualRegister(GPRC); 11070 Register Mask2Reg = RegInfo.createVirtualRegister(GPRC); 11071 Register Mask3Reg = RegInfo.createVirtualRegister(GPRC); 11072 Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC); 11073 Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC); 11074 Register TmpDestReg = RegInfo.createVirtualRegister(GPRC); 11075 Register Ptr1Reg; 11076 Register TmpReg = RegInfo.createVirtualRegister(GPRC); 11077 Register ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO; 11078 // thisMBB: 11079 // ... 11080 // fallthrough --> loopMBB 11081 BB->addSuccessor(loop1MBB); 11082 11083 // The 4-byte load must be aligned, while a char or short may be 11084 // anywhere in the word. Hence all this nasty bookkeeping code. 11085 // add ptr1, ptrA, ptrB [copy if ptrA==0] 11086 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27] 11087 // xori shift, shift1, 24 [16] 11088 // rlwinm ptr, ptr1, 0, 0, 29 11089 // slw newval2, newval, shift 11090 // slw oldval2, oldval,shift 11091 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535] 11092 // slw mask, mask2, shift 11093 // and newval3, newval2, mask 11094 // and oldval3, oldval2, mask 11095 // loop1MBB: 11096 // lwarx tmpDest, ptr 11097 // and tmp, tmpDest, mask 11098 // cmpw tmp, oldval3 11099 // bne- midMBB 11100 // loop2MBB: 11101 // andc tmp2, tmpDest, mask 11102 // or tmp4, tmp2, newval3 11103 // stwcx. tmp4, ptr 11104 // bne- loop1MBB 11105 // b exitBB 11106 // midMBB: 11107 // stwcx. tmpDest, ptr 11108 // exitBB: 11109 // srw dest, tmpDest, shift 11110 if (ptrA != ZeroReg) { 11111 Ptr1Reg = RegInfo.createVirtualRegister(RC); 11112 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg) 11113 .addReg(ptrA) 11114 .addReg(ptrB); 11115 } else { 11116 Ptr1Reg = ptrB; 11117 } 11118 11119 // We need use 32-bit subregister to avoid mismatch register class in 64-bit 11120 // mode. 11121 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg) 11122 .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0) 11123 .addImm(3) 11124 .addImm(27) 11125 .addImm(is8bit ? 28 : 27); 11126 if (!isLittleEndian) 11127 BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg) 11128 .addReg(Shift1Reg) 11129 .addImm(is8bit ? 24 : 16); 11130 if (is64bit) 11131 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg) 11132 .addReg(Ptr1Reg) 11133 .addImm(0) 11134 .addImm(61); 11135 else 11136 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg) 11137 .addReg(Ptr1Reg) 11138 .addImm(0) 11139 .addImm(0) 11140 .addImm(29); 11141 BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg) 11142 .addReg(newval) 11143 .addReg(ShiftReg); 11144 BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg) 11145 .addReg(oldval) 11146 .addReg(ShiftReg); 11147 if (is8bit) 11148 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255); 11149 else { 11150 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0); 11151 BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg) 11152 .addReg(Mask3Reg) 11153 .addImm(65535); 11154 } 11155 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg) 11156 .addReg(Mask2Reg) 11157 .addReg(ShiftReg); 11158 BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg) 11159 .addReg(NewVal2Reg) 11160 .addReg(MaskReg); 11161 BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg) 11162 .addReg(OldVal2Reg) 11163 .addReg(MaskReg); 11164 11165 BB = loop1MBB; 11166 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg) 11167 .addReg(ZeroReg) 11168 .addReg(PtrReg); 11169 BuildMI(BB, dl, TII->get(PPC::AND), TmpReg) 11170 .addReg(TmpDestReg) 11171 .addReg(MaskReg); 11172 BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0) 11173 .addReg(TmpReg) 11174 .addReg(OldVal3Reg); 11175 BuildMI(BB, dl, TII->get(PPC::BCC)) 11176 .addImm(PPC::PRED_NE) 11177 .addReg(PPC::CR0) 11178 .addMBB(midMBB); 11179 BB->addSuccessor(loop2MBB); 11180 BB->addSuccessor(midMBB); 11181 11182 BB = loop2MBB; 11183 BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg) 11184 .addReg(TmpDestReg) 11185 .addReg(MaskReg); 11186 BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg) 11187 .addReg(Tmp2Reg) 11188 .addReg(NewVal3Reg); 11189 BuildMI(BB, dl, TII->get(PPC::STWCX)) 11190 .addReg(Tmp4Reg) 11191 .addReg(ZeroReg) 11192 .addReg(PtrReg); 11193 BuildMI(BB, dl, TII->get(PPC::BCC)) 11194 .addImm(PPC::PRED_NE) 11195 .addReg(PPC::CR0) 11196 .addMBB(loop1MBB); 11197 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB); 11198 BB->addSuccessor(loop1MBB); 11199 BB->addSuccessor(exitMBB); 11200 11201 BB = midMBB; 11202 BuildMI(BB, dl, TII->get(PPC::STWCX)) 11203 .addReg(TmpDestReg) 11204 .addReg(ZeroReg) 11205 .addReg(PtrReg); 11206 BB->addSuccessor(exitMBB); 11207 11208 // exitMBB: 11209 // ... 11210 BB = exitMBB; 11211 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest) 11212 .addReg(TmpReg) 11213 .addReg(ShiftReg); 11214 } else if (MI.getOpcode() == PPC::FADDrtz) { 11215 // This pseudo performs an FADD with rounding mode temporarily forced 11216 // to round-to-zero. We emit this via custom inserter since the FPSCR 11217 // is not modeled at the SelectionDAG level. 11218 unsigned Dest = MI.getOperand(0).getReg(); 11219 unsigned Src1 = MI.getOperand(1).getReg(); 11220 unsigned Src2 = MI.getOperand(2).getReg(); 11221 DebugLoc dl = MI.getDebugLoc(); 11222 11223 MachineRegisterInfo &RegInfo = F->getRegInfo(); 11224 unsigned MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass); 11225 11226 // Save FPSCR value. 11227 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg); 11228 11229 // Set rounding mode to round-to-zero. 11230 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1)).addImm(31); 11231 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0)).addImm(30); 11232 11233 // Perform addition. 11234 BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest).addReg(Src1).addReg(Src2); 11235 11236 // Restore FPSCR value. 11237 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSFb)).addImm(1).addReg(MFFSReg); 11238 } else if (MI.getOpcode() == PPC::ANDIo_1_EQ_BIT || 11239 MI.getOpcode() == PPC::ANDIo_1_GT_BIT || 11240 MI.getOpcode() == PPC::ANDIo_1_EQ_BIT8 || 11241 MI.getOpcode() == PPC::ANDIo_1_GT_BIT8) { 11242 unsigned Opcode = (MI.getOpcode() == PPC::ANDIo_1_EQ_BIT8 || 11243 MI.getOpcode() == PPC::ANDIo_1_GT_BIT8) 11244 ? PPC::ANDIo8 11245 : PPC::ANDIo; 11246 bool isEQ = (MI.getOpcode() == PPC::ANDIo_1_EQ_BIT || 11247 MI.getOpcode() == PPC::ANDIo_1_EQ_BIT8); 11248 11249 MachineRegisterInfo &RegInfo = F->getRegInfo(); 11250 unsigned Dest = RegInfo.createVirtualRegister( 11251 Opcode == PPC::ANDIo ? &PPC::GPRCRegClass : &PPC::G8RCRegClass); 11252 11253 DebugLoc dl = MI.getDebugLoc(); 11254 BuildMI(*BB, MI, dl, TII->get(Opcode), Dest) 11255 .addReg(MI.getOperand(1).getReg()) 11256 .addImm(1); 11257 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), 11258 MI.getOperand(0).getReg()) 11259 .addReg(isEQ ? PPC::CR0EQ : PPC::CR0GT); 11260 } else if (MI.getOpcode() == PPC::TCHECK_RET) { 11261 DebugLoc Dl = MI.getDebugLoc(); 11262 MachineRegisterInfo &RegInfo = F->getRegInfo(); 11263 unsigned CRReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass); 11264 BuildMI(*BB, MI, Dl, TII->get(PPC::TCHECK), CRReg); 11265 BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY), 11266 MI.getOperand(0).getReg()) 11267 .addReg(CRReg); 11268 } else if (MI.getOpcode() == PPC::TBEGIN_RET) { 11269 DebugLoc Dl = MI.getDebugLoc(); 11270 unsigned Imm = MI.getOperand(1).getImm(); 11271 BuildMI(*BB, MI, Dl, TII->get(PPC::TBEGIN)).addImm(Imm); 11272 BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY), 11273 MI.getOperand(0).getReg()) 11274 .addReg(PPC::CR0EQ); 11275 } else if (MI.getOpcode() == PPC::SETRNDi) { 11276 DebugLoc dl = MI.getDebugLoc(); 11277 unsigned OldFPSCRReg = MI.getOperand(0).getReg(); 11278 11279 // Save FPSCR value. 11280 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg); 11281 11282 // The floating point rounding mode is in the bits 62:63 of FPCSR, and has 11283 // the following settings: 11284 // 00 Round to nearest 11285 // 01 Round to 0 11286 // 10 Round to +inf 11287 // 11 Round to -inf 11288 11289 // When the operand is immediate, using the two least significant bits of 11290 // the immediate to set the bits 62:63 of FPSCR. 11291 unsigned Mode = MI.getOperand(1).getImm(); 11292 BuildMI(*BB, MI, dl, TII->get((Mode & 1) ? PPC::MTFSB1 : PPC::MTFSB0)) 11293 .addImm(31); 11294 11295 BuildMI(*BB, MI, dl, TII->get((Mode & 2) ? PPC::MTFSB1 : PPC::MTFSB0)) 11296 .addImm(30); 11297 } else if (MI.getOpcode() == PPC::SETRND) { 11298 DebugLoc dl = MI.getDebugLoc(); 11299 11300 // Copy register from F8RCRegClass::SrcReg to G8RCRegClass::DestReg 11301 // or copy register from G8RCRegClass::SrcReg to F8RCRegClass::DestReg. 11302 // If the target doesn't have DirectMove, we should use stack to do the 11303 // conversion, because the target doesn't have the instructions like mtvsrd 11304 // or mfvsrd to do this conversion directly. 11305 auto copyRegFromG8RCOrF8RC = [&] (unsigned DestReg, unsigned SrcReg) { 11306 if (Subtarget.hasDirectMove()) { 11307 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), DestReg) 11308 .addReg(SrcReg); 11309 } else { 11310 // Use stack to do the register copy. 11311 unsigned StoreOp = PPC::STD, LoadOp = PPC::LFD; 11312 MachineRegisterInfo &RegInfo = F->getRegInfo(); 11313 const TargetRegisterClass *RC = RegInfo.getRegClass(SrcReg); 11314 if (RC == &PPC::F8RCRegClass) { 11315 // Copy register from F8RCRegClass to G8RCRegclass. 11316 assert((RegInfo.getRegClass(DestReg) == &PPC::G8RCRegClass) && 11317 "Unsupported RegClass."); 11318 11319 StoreOp = PPC::STFD; 11320 LoadOp = PPC::LD; 11321 } else { 11322 // Copy register from G8RCRegClass to F8RCRegclass. 11323 assert((RegInfo.getRegClass(SrcReg) == &PPC::G8RCRegClass) && 11324 (RegInfo.getRegClass(DestReg) == &PPC::F8RCRegClass) && 11325 "Unsupported RegClass."); 11326 } 11327 11328 MachineFrameInfo &MFI = F->getFrameInfo(); 11329 int FrameIdx = MFI.CreateStackObject(8, 8, false); 11330 11331 MachineMemOperand *MMOStore = F->getMachineMemOperand( 11332 MachinePointerInfo::getFixedStack(*F, FrameIdx, 0), 11333 MachineMemOperand::MOStore, MFI.getObjectSize(FrameIdx), 11334 MFI.getObjectAlignment(FrameIdx)); 11335 11336 // Store the SrcReg into the stack. 11337 BuildMI(*BB, MI, dl, TII->get(StoreOp)) 11338 .addReg(SrcReg) 11339 .addImm(0) 11340 .addFrameIndex(FrameIdx) 11341 .addMemOperand(MMOStore); 11342 11343 MachineMemOperand *MMOLoad = F->getMachineMemOperand( 11344 MachinePointerInfo::getFixedStack(*F, FrameIdx, 0), 11345 MachineMemOperand::MOLoad, MFI.getObjectSize(FrameIdx), 11346 MFI.getObjectAlignment(FrameIdx)); 11347 11348 // Load from the stack where SrcReg is stored, and save to DestReg, 11349 // so we have done the RegClass conversion from RegClass::SrcReg to 11350 // RegClass::DestReg. 11351 BuildMI(*BB, MI, dl, TII->get(LoadOp), DestReg) 11352 .addImm(0) 11353 .addFrameIndex(FrameIdx) 11354 .addMemOperand(MMOLoad); 11355 } 11356 }; 11357 11358 unsigned OldFPSCRReg = MI.getOperand(0).getReg(); 11359 11360 // Save FPSCR value. 11361 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg); 11362 11363 // When the operand is gprc register, use two least significant bits of the 11364 // register and mtfsf instruction to set the bits 62:63 of FPSCR. 11365 // 11366 // copy OldFPSCRTmpReg, OldFPSCRReg 11367 // (INSERT_SUBREG ExtSrcReg, (IMPLICIT_DEF ImDefReg), SrcOp, 1) 11368 // rldimi NewFPSCRTmpReg, ExtSrcReg, OldFPSCRReg, 0, 62 11369 // copy NewFPSCRReg, NewFPSCRTmpReg 11370 // mtfsf 255, NewFPSCRReg 11371 MachineOperand SrcOp = MI.getOperand(1); 11372 MachineRegisterInfo &RegInfo = F->getRegInfo(); 11373 unsigned OldFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 11374 11375 copyRegFromG8RCOrF8RC(OldFPSCRTmpReg, OldFPSCRReg); 11376 11377 unsigned ImDefReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 11378 unsigned ExtSrcReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 11379 11380 // The first operand of INSERT_SUBREG should be a register which has 11381 // subregisters, we only care about its RegClass, so we should use an 11382 // IMPLICIT_DEF register. 11383 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::IMPLICIT_DEF), ImDefReg); 11384 BuildMI(*BB, MI, dl, TII->get(PPC::INSERT_SUBREG), ExtSrcReg) 11385 .addReg(ImDefReg) 11386 .add(SrcOp) 11387 .addImm(1); 11388 11389 unsigned NewFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 11390 BuildMI(*BB, MI, dl, TII->get(PPC::RLDIMI), NewFPSCRTmpReg) 11391 .addReg(OldFPSCRTmpReg) 11392 .addReg(ExtSrcReg) 11393 .addImm(0) 11394 .addImm(62); 11395 11396 unsigned NewFPSCRReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass); 11397 copyRegFromG8RCOrF8RC(NewFPSCRReg, NewFPSCRTmpReg); 11398 11399 // The mask 255 means that put the 32:63 bits of NewFPSCRReg to the 32:63 11400 // bits of FPSCR. 11401 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSF)) 11402 .addImm(255) 11403 .addReg(NewFPSCRReg) 11404 .addImm(0) 11405 .addImm(0); 11406 } else { 11407 llvm_unreachable("Unexpected instr type to insert"); 11408 } 11409 11410 MI.eraseFromParent(); // The pseudo instruction is gone now. 11411 return BB; 11412 } 11413 11414 //===----------------------------------------------------------------------===// 11415 // Target Optimization Hooks 11416 //===----------------------------------------------------------------------===// 11417 11418 static int getEstimateRefinementSteps(EVT VT, const PPCSubtarget &Subtarget) { 11419 // For the estimates, convergence is quadratic, so we essentially double the 11420 // number of digits correct after every iteration. For both FRE and FRSQRTE, 11421 // the minimum architected relative accuracy is 2^-5. When hasRecipPrec(), 11422 // this is 2^-14. IEEE float has 23 digits and double has 52 digits. 11423 int RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3; 11424 if (VT.getScalarType() == MVT::f64) 11425 RefinementSteps++; 11426 return RefinementSteps; 11427 } 11428 11429 SDValue PPCTargetLowering::getSqrtEstimate(SDValue Operand, SelectionDAG &DAG, 11430 int Enabled, int &RefinementSteps, 11431 bool &UseOneConstNR, 11432 bool Reciprocal) const { 11433 EVT VT = Operand.getValueType(); 11434 if ((VT == MVT::f32 && Subtarget.hasFRSQRTES()) || 11435 (VT == MVT::f64 && Subtarget.hasFRSQRTE()) || 11436 (VT == MVT::v4f32 && Subtarget.hasAltivec()) || 11437 (VT == MVT::v2f64 && Subtarget.hasVSX()) || 11438 (VT == MVT::v4f32 && Subtarget.hasQPX()) || 11439 (VT == MVT::v4f64 && Subtarget.hasQPX())) { 11440 if (RefinementSteps == ReciprocalEstimate::Unspecified) 11441 RefinementSteps = getEstimateRefinementSteps(VT, Subtarget); 11442 11443 // The Newton-Raphson computation with a single constant does not provide 11444 // enough accuracy on some CPUs. 11445 UseOneConstNR = !Subtarget.needsTwoConstNR(); 11446 return DAG.getNode(PPCISD::FRSQRTE, SDLoc(Operand), VT, Operand); 11447 } 11448 return SDValue(); 11449 } 11450 11451 SDValue PPCTargetLowering::getRecipEstimate(SDValue Operand, SelectionDAG &DAG, 11452 int Enabled, 11453 int &RefinementSteps) const { 11454 EVT VT = Operand.getValueType(); 11455 if ((VT == MVT::f32 && Subtarget.hasFRES()) || 11456 (VT == MVT::f64 && Subtarget.hasFRE()) || 11457 (VT == MVT::v4f32 && Subtarget.hasAltivec()) || 11458 (VT == MVT::v2f64 && Subtarget.hasVSX()) || 11459 (VT == MVT::v4f32 && Subtarget.hasQPX()) || 11460 (VT == MVT::v4f64 && Subtarget.hasQPX())) { 11461 if (RefinementSteps == ReciprocalEstimate::Unspecified) 11462 RefinementSteps = getEstimateRefinementSteps(VT, Subtarget); 11463 return DAG.getNode(PPCISD::FRE, SDLoc(Operand), VT, Operand); 11464 } 11465 return SDValue(); 11466 } 11467 11468 unsigned PPCTargetLowering::combineRepeatedFPDivisors() const { 11469 // Note: This functionality is used only when unsafe-fp-math is enabled, and 11470 // on cores with reciprocal estimates (which are used when unsafe-fp-math is 11471 // enabled for division), this functionality is redundant with the default 11472 // combiner logic (once the division -> reciprocal/multiply transformation 11473 // has taken place). As a result, this matters more for older cores than for 11474 // newer ones. 11475 11476 // Combine multiple FDIVs with the same divisor into multiple FMULs by the 11477 // reciprocal if there are two or more FDIVs (for embedded cores with only 11478 // one FP pipeline) for three or more FDIVs (for generic OOO cores). 11479 switch (Subtarget.getDarwinDirective()) { 11480 default: 11481 return 3; 11482 case PPC::DIR_440: 11483 case PPC::DIR_A2: 11484 case PPC::DIR_E500: 11485 case PPC::DIR_E500mc: 11486 case PPC::DIR_E5500: 11487 return 2; 11488 } 11489 } 11490 11491 // isConsecutiveLSLoc needs to work even if all adds have not yet been 11492 // collapsed, and so we need to look through chains of them. 11493 static void getBaseWithConstantOffset(SDValue Loc, SDValue &Base, 11494 int64_t& Offset, SelectionDAG &DAG) { 11495 if (DAG.isBaseWithConstantOffset(Loc)) { 11496 Base = Loc.getOperand(0); 11497 Offset += cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue(); 11498 11499 // The base might itself be a base plus an offset, and if so, accumulate 11500 // that as well. 11501 getBaseWithConstantOffset(Loc.getOperand(0), Base, Offset, DAG); 11502 } 11503 } 11504 11505 static bool isConsecutiveLSLoc(SDValue Loc, EVT VT, LSBaseSDNode *Base, 11506 unsigned Bytes, int Dist, 11507 SelectionDAG &DAG) { 11508 if (VT.getSizeInBits() / 8 != Bytes) 11509 return false; 11510 11511 SDValue BaseLoc = Base->getBasePtr(); 11512 if (Loc.getOpcode() == ISD::FrameIndex) { 11513 if (BaseLoc.getOpcode() != ISD::FrameIndex) 11514 return false; 11515 const MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 11516 int FI = cast<FrameIndexSDNode>(Loc)->getIndex(); 11517 int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex(); 11518 int FS = MFI.getObjectSize(FI); 11519 int BFS = MFI.getObjectSize(BFI); 11520 if (FS != BFS || FS != (int)Bytes) return false; 11521 return MFI.getObjectOffset(FI) == (MFI.getObjectOffset(BFI) + Dist*Bytes); 11522 } 11523 11524 SDValue Base1 = Loc, Base2 = BaseLoc; 11525 int64_t Offset1 = 0, Offset2 = 0; 11526 getBaseWithConstantOffset(Loc, Base1, Offset1, DAG); 11527 getBaseWithConstantOffset(BaseLoc, Base2, Offset2, DAG); 11528 if (Base1 == Base2 && Offset1 == (Offset2 + Dist * Bytes)) 11529 return true; 11530 11531 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11532 const GlobalValue *GV1 = nullptr; 11533 const GlobalValue *GV2 = nullptr; 11534 Offset1 = 0; 11535 Offset2 = 0; 11536 bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1); 11537 bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2); 11538 if (isGA1 && isGA2 && GV1 == GV2) 11539 return Offset1 == (Offset2 + Dist*Bytes); 11540 return false; 11541 } 11542 11543 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does 11544 // not enforce equality of the chain operands. 11545 static bool isConsecutiveLS(SDNode *N, LSBaseSDNode *Base, 11546 unsigned Bytes, int Dist, 11547 SelectionDAG &DAG) { 11548 if (LSBaseSDNode *LS = dyn_cast<LSBaseSDNode>(N)) { 11549 EVT VT = LS->getMemoryVT(); 11550 SDValue Loc = LS->getBasePtr(); 11551 return isConsecutiveLSLoc(Loc, VT, Base, Bytes, Dist, DAG); 11552 } 11553 11554 if (N->getOpcode() == ISD::INTRINSIC_W_CHAIN) { 11555 EVT VT; 11556 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 11557 default: return false; 11558 case Intrinsic::ppc_qpx_qvlfd: 11559 case Intrinsic::ppc_qpx_qvlfda: 11560 VT = MVT::v4f64; 11561 break; 11562 case Intrinsic::ppc_qpx_qvlfs: 11563 case Intrinsic::ppc_qpx_qvlfsa: 11564 VT = MVT::v4f32; 11565 break; 11566 case Intrinsic::ppc_qpx_qvlfcd: 11567 case Intrinsic::ppc_qpx_qvlfcda: 11568 VT = MVT::v2f64; 11569 break; 11570 case Intrinsic::ppc_qpx_qvlfcs: 11571 case Intrinsic::ppc_qpx_qvlfcsa: 11572 VT = MVT::v2f32; 11573 break; 11574 case Intrinsic::ppc_qpx_qvlfiwa: 11575 case Intrinsic::ppc_qpx_qvlfiwz: 11576 case Intrinsic::ppc_altivec_lvx: 11577 case Intrinsic::ppc_altivec_lvxl: 11578 case Intrinsic::ppc_vsx_lxvw4x: 11579 case Intrinsic::ppc_vsx_lxvw4x_be: 11580 VT = MVT::v4i32; 11581 break; 11582 case Intrinsic::ppc_vsx_lxvd2x: 11583 case Intrinsic::ppc_vsx_lxvd2x_be: 11584 VT = MVT::v2f64; 11585 break; 11586 case Intrinsic::ppc_altivec_lvebx: 11587 VT = MVT::i8; 11588 break; 11589 case Intrinsic::ppc_altivec_lvehx: 11590 VT = MVT::i16; 11591 break; 11592 case Intrinsic::ppc_altivec_lvewx: 11593 VT = MVT::i32; 11594 break; 11595 } 11596 11597 return isConsecutiveLSLoc(N->getOperand(2), VT, Base, Bytes, Dist, DAG); 11598 } 11599 11600 if (N->getOpcode() == ISD::INTRINSIC_VOID) { 11601 EVT VT; 11602 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 11603 default: return false; 11604 case Intrinsic::ppc_qpx_qvstfd: 11605 case Intrinsic::ppc_qpx_qvstfda: 11606 VT = MVT::v4f64; 11607 break; 11608 case Intrinsic::ppc_qpx_qvstfs: 11609 case Intrinsic::ppc_qpx_qvstfsa: 11610 VT = MVT::v4f32; 11611 break; 11612 case Intrinsic::ppc_qpx_qvstfcd: 11613 case Intrinsic::ppc_qpx_qvstfcda: 11614 VT = MVT::v2f64; 11615 break; 11616 case Intrinsic::ppc_qpx_qvstfcs: 11617 case Intrinsic::ppc_qpx_qvstfcsa: 11618 VT = MVT::v2f32; 11619 break; 11620 case Intrinsic::ppc_qpx_qvstfiw: 11621 case Intrinsic::ppc_qpx_qvstfiwa: 11622 case Intrinsic::ppc_altivec_stvx: 11623 case Intrinsic::ppc_altivec_stvxl: 11624 case Intrinsic::ppc_vsx_stxvw4x: 11625 VT = MVT::v4i32; 11626 break; 11627 case Intrinsic::ppc_vsx_stxvd2x: 11628 VT = MVT::v2f64; 11629 break; 11630 case Intrinsic::ppc_vsx_stxvw4x_be: 11631 VT = MVT::v4i32; 11632 break; 11633 case Intrinsic::ppc_vsx_stxvd2x_be: 11634 VT = MVT::v2f64; 11635 break; 11636 case Intrinsic::ppc_altivec_stvebx: 11637 VT = MVT::i8; 11638 break; 11639 case Intrinsic::ppc_altivec_stvehx: 11640 VT = MVT::i16; 11641 break; 11642 case Intrinsic::ppc_altivec_stvewx: 11643 VT = MVT::i32; 11644 break; 11645 } 11646 11647 return isConsecutiveLSLoc(N->getOperand(3), VT, Base, Bytes, Dist, DAG); 11648 } 11649 11650 return false; 11651 } 11652 11653 // Return true is there is a nearyby consecutive load to the one provided 11654 // (regardless of alignment). We search up and down the chain, looking though 11655 // token factors and other loads (but nothing else). As a result, a true result 11656 // indicates that it is safe to create a new consecutive load adjacent to the 11657 // load provided. 11658 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) { 11659 SDValue Chain = LD->getChain(); 11660 EVT VT = LD->getMemoryVT(); 11661 11662 SmallSet<SDNode *, 16> LoadRoots; 11663 SmallVector<SDNode *, 8> Queue(1, Chain.getNode()); 11664 SmallSet<SDNode *, 16> Visited; 11665 11666 // First, search up the chain, branching to follow all token-factor operands. 11667 // If we find a consecutive load, then we're done, otherwise, record all 11668 // nodes just above the top-level loads and token factors. 11669 while (!Queue.empty()) { 11670 SDNode *ChainNext = Queue.pop_back_val(); 11671 if (!Visited.insert(ChainNext).second) 11672 continue; 11673 11674 if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(ChainNext)) { 11675 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG)) 11676 return true; 11677 11678 if (!Visited.count(ChainLD->getChain().getNode())) 11679 Queue.push_back(ChainLD->getChain().getNode()); 11680 } else if (ChainNext->getOpcode() == ISD::TokenFactor) { 11681 for (const SDUse &O : ChainNext->ops()) 11682 if (!Visited.count(O.getNode())) 11683 Queue.push_back(O.getNode()); 11684 } else 11685 LoadRoots.insert(ChainNext); 11686 } 11687 11688 // Second, search down the chain, starting from the top-level nodes recorded 11689 // in the first phase. These top-level nodes are the nodes just above all 11690 // loads and token factors. Starting with their uses, recursively look though 11691 // all loads (just the chain uses) and token factors to find a consecutive 11692 // load. 11693 Visited.clear(); 11694 Queue.clear(); 11695 11696 for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(), 11697 IE = LoadRoots.end(); I != IE; ++I) { 11698 Queue.push_back(*I); 11699 11700 while (!Queue.empty()) { 11701 SDNode *LoadRoot = Queue.pop_back_val(); 11702 if (!Visited.insert(LoadRoot).second) 11703 continue; 11704 11705 if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(LoadRoot)) 11706 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG)) 11707 return true; 11708 11709 for (SDNode::use_iterator UI = LoadRoot->use_begin(), 11710 UE = LoadRoot->use_end(); UI != UE; ++UI) 11711 if (((isa<MemSDNode>(*UI) && 11712 cast<MemSDNode>(*UI)->getChain().getNode() == LoadRoot) || 11713 UI->getOpcode() == ISD::TokenFactor) && !Visited.count(*UI)) 11714 Queue.push_back(*UI); 11715 } 11716 } 11717 11718 return false; 11719 } 11720 11721 /// This function is called when we have proved that a SETCC node can be replaced 11722 /// by subtraction (and other supporting instructions) so that the result of 11723 /// comparison is kept in a GPR instead of CR. This function is purely for 11724 /// codegen purposes and has some flags to guide the codegen process. 11725 static SDValue generateEquivalentSub(SDNode *N, int Size, bool Complement, 11726 bool Swap, SDLoc &DL, SelectionDAG &DAG) { 11727 assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected."); 11728 11729 // Zero extend the operands to the largest legal integer. Originally, they 11730 // must be of a strictly smaller size. 11731 auto Op0 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(0), 11732 DAG.getConstant(Size, DL, MVT::i32)); 11733 auto Op1 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1), 11734 DAG.getConstant(Size, DL, MVT::i32)); 11735 11736 // Swap if needed. Depends on the condition code. 11737 if (Swap) 11738 std::swap(Op0, Op1); 11739 11740 // Subtract extended integers. 11741 auto SubNode = DAG.getNode(ISD::SUB, DL, MVT::i64, Op0, Op1); 11742 11743 // Move the sign bit to the least significant position and zero out the rest. 11744 // Now the least significant bit carries the result of original comparison. 11745 auto Shifted = DAG.getNode(ISD::SRL, DL, MVT::i64, SubNode, 11746 DAG.getConstant(Size - 1, DL, MVT::i32)); 11747 auto Final = Shifted; 11748 11749 // Complement the result if needed. Based on the condition code. 11750 if (Complement) 11751 Final = DAG.getNode(ISD::XOR, DL, MVT::i64, Shifted, 11752 DAG.getConstant(1, DL, MVT::i64)); 11753 11754 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Final); 11755 } 11756 11757 SDValue PPCTargetLowering::ConvertSETCCToSubtract(SDNode *N, 11758 DAGCombinerInfo &DCI) const { 11759 assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected."); 11760 11761 SelectionDAG &DAG = DCI.DAG; 11762 SDLoc DL(N); 11763 11764 // Size of integers being compared has a critical role in the following 11765 // analysis, so we prefer to do this when all types are legal. 11766 if (!DCI.isAfterLegalizeDAG()) 11767 return SDValue(); 11768 11769 // If all users of SETCC extend its value to a legal integer type 11770 // then we replace SETCC with a subtraction 11771 for (SDNode::use_iterator UI = N->use_begin(), 11772 UE = N->use_end(); UI != UE; ++UI) { 11773 if (UI->getOpcode() != ISD::ZERO_EXTEND) 11774 return SDValue(); 11775 } 11776 11777 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 11778 auto OpSize = N->getOperand(0).getValueSizeInBits(); 11779 11780 unsigned Size = DAG.getDataLayout().getLargestLegalIntTypeSizeInBits(); 11781 11782 if (OpSize < Size) { 11783 switch (CC) { 11784 default: break; 11785 case ISD::SETULT: 11786 return generateEquivalentSub(N, Size, false, false, DL, DAG); 11787 case ISD::SETULE: 11788 return generateEquivalentSub(N, Size, true, true, DL, DAG); 11789 case ISD::SETUGT: 11790 return generateEquivalentSub(N, Size, false, true, DL, DAG); 11791 case ISD::SETUGE: 11792 return generateEquivalentSub(N, Size, true, false, DL, DAG); 11793 } 11794 } 11795 11796 return SDValue(); 11797 } 11798 11799 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N, 11800 DAGCombinerInfo &DCI) const { 11801 SelectionDAG &DAG = DCI.DAG; 11802 SDLoc dl(N); 11803 11804 assert(Subtarget.useCRBits() && "Expecting to be tracking CR bits"); 11805 // If we're tracking CR bits, we need to be careful that we don't have: 11806 // trunc(binary-ops(zext(x), zext(y))) 11807 // or 11808 // trunc(binary-ops(binary-ops(zext(x), zext(y)), ...) 11809 // such that we're unnecessarily moving things into GPRs when it would be 11810 // better to keep them in CR bits. 11811 11812 // Note that trunc here can be an actual i1 trunc, or can be the effective 11813 // truncation that comes from a setcc or select_cc. 11814 if (N->getOpcode() == ISD::TRUNCATE && 11815 N->getValueType(0) != MVT::i1) 11816 return SDValue(); 11817 11818 if (N->getOperand(0).getValueType() != MVT::i32 && 11819 N->getOperand(0).getValueType() != MVT::i64) 11820 return SDValue(); 11821 11822 if (N->getOpcode() == ISD::SETCC || 11823 N->getOpcode() == ISD::SELECT_CC) { 11824 // If we're looking at a comparison, then we need to make sure that the 11825 // high bits (all except for the first) don't matter the result. 11826 ISD::CondCode CC = 11827 cast<CondCodeSDNode>(N->getOperand( 11828 N->getOpcode() == ISD::SETCC ? 2 : 4))->get(); 11829 unsigned OpBits = N->getOperand(0).getValueSizeInBits(); 11830 11831 if (ISD::isSignedIntSetCC(CC)) { 11832 if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits || 11833 DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits) 11834 return SDValue(); 11835 } else if (ISD::isUnsignedIntSetCC(CC)) { 11836 if (!DAG.MaskedValueIsZero(N->getOperand(0), 11837 APInt::getHighBitsSet(OpBits, OpBits-1)) || 11838 !DAG.MaskedValueIsZero(N->getOperand(1), 11839 APInt::getHighBitsSet(OpBits, OpBits-1))) 11840 return (N->getOpcode() == ISD::SETCC ? ConvertSETCCToSubtract(N, DCI) 11841 : SDValue()); 11842 } else { 11843 // This is neither a signed nor an unsigned comparison, just make sure 11844 // that the high bits are equal. 11845 KnownBits Op1Known = DAG.computeKnownBits(N->getOperand(0)); 11846 KnownBits Op2Known = DAG.computeKnownBits(N->getOperand(1)); 11847 11848 // We don't really care about what is known about the first bit (if 11849 // anything), so clear it in all masks prior to comparing them. 11850 Op1Known.Zero.clearBit(0); Op1Known.One.clearBit(0); 11851 Op2Known.Zero.clearBit(0); Op2Known.One.clearBit(0); 11852 11853 if (Op1Known.Zero != Op2Known.Zero || Op1Known.One != Op2Known.One) 11854 return SDValue(); 11855 } 11856 } 11857 11858 // We now know that the higher-order bits are irrelevant, we just need to 11859 // make sure that all of the intermediate operations are bit operations, and 11860 // all inputs are extensions. 11861 if (N->getOperand(0).getOpcode() != ISD::AND && 11862 N->getOperand(0).getOpcode() != ISD::OR && 11863 N->getOperand(0).getOpcode() != ISD::XOR && 11864 N->getOperand(0).getOpcode() != ISD::SELECT && 11865 N->getOperand(0).getOpcode() != ISD::SELECT_CC && 11866 N->getOperand(0).getOpcode() != ISD::TRUNCATE && 11867 N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND && 11868 N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND && 11869 N->getOperand(0).getOpcode() != ISD::ANY_EXTEND) 11870 return SDValue(); 11871 11872 if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) && 11873 N->getOperand(1).getOpcode() != ISD::AND && 11874 N->getOperand(1).getOpcode() != ISD::OR && 11875 N->getOperand(1).getOpcode() != ISD::XOR && 11876 N->getOperand(1).getOpcode() != ISD::SELECT && 11877 N->getOperand(1).getOpcode() != ISD::SELECT_CC && 11878 N->getOperand(1).getOpcode() != ISD::TRUNCATE && 11879 N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND && 11880 N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND && 11881 N->getOperand(1).getOpcode() != ISD::ANY_EXTEND) 11882 return SDValue(); 11883 11884 SmallVector<SDValue, 4> Inputs; 11885 SmallVector<SDValue, 8> BinOps, PromOps; 11886 SmallPtrSet<SDNode *, 16> Visited; 11887 11888 for (unsigned i = 0; i < 2; ++i) { 11889 if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND || 11890 N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND || 11891 N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) && 11892 N->getOperand(i).getOperand(0).getValueType() == MVT::i1) || 11893 isa<ConstantSDNode>(N->getOperand(i))) 11894 Inputs.push_back(N->getOperand(i)); 11895 else 11896 BinOps.push_back(N->getOperand(i)); 11897 11898 if (N->getOpcode() == ISD::TRUNCATE) 11899 break; 11900 } 11901 11902 // Visit all inputs, collect all binary operations (and, or, xor and 11903 // select) that are all fed by extensions. 11904 while (!BinOps.empty()) { 11905 SDValue BinOp = BinOps.back(); 11906 BinOps.pop_back(); 11907 11908 if (!Visited.insert(BinOp.getNode()).second) 11909 continue; 11910 11911 PromOps.push_back(BinOp); 11912 11913 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) { 11914 // The condition of the select is not promoted. 11915 if (BinOp.getOpcode() == ISD::SELECT && i == 0) 11916 continue; 11917 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3) 11918 continue; 11919 11920 if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND || 11921 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND || 11922 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) && 11923 BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) || 11924 isa<ConstantSDNode>(BinOp.getOperand(i))) { 11925 Inputs.push_back(BinOp.getOperand(i)); 11926 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND || 11927 BinOp.getOperand(i).getOpcode() == ISD::OR || 11928 BinOp.getOperand(i).getOpcode() == ISD::XOR || 11929 BinOp.getOperand(i).getOpcode() == ISD::SELECT || 11930 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC || 11931 BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE || 11932 BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND || 11933 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND || 11934 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) { 11935 BinOps.push_back(BinOp.getOperand(i)); 11936 } else { 11937 // We have an input that is not an extension or another binary 11938 // operation; we'll abort this transformation. 11939 return SDValue(); 11940 } 11941 } 11942 } 11943 11944 // Make sure that this is a self-contained cluster of operations (which 11945 // is not quite the same thing as saying that everything has only one 11946 // use). 11947 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 11948 if (isa<ConstantSDNode>(Inputs[i])) 11949 continue; 11950 11951 for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(), 11952 UE = Inputs[i].getNode()->use_end(); 11953 UI != UE; ++UI) { 11954 SDNode *User = *UI; 11955 if (User != N && !Visited.count(User)) 11956 return SDValue(); 11957 11958 // Make sure that we're not going to promote the non-output-value 11959 // operand(s) or SELECT or SELECT_CC. 11960 // FIXME: Although we could sometimes handle this, and it does occur in 11961 // practice that one of the condition inputs to the select is also one of 11962 // the outputs, we currently can't deal with this. 11963 if (User->getOpcode() == ISD::SELECT) { 11964 if (User->getOperand(0) == Inputs[i]) 11965 return SDValue(); 11966 } else if (User->getOpcode() == ISD::SELECT_CC) { 11967 if (User->getOperand(0) == Inputs[i] || 11968 User->getOperand(1) == Inputs[i]) 11969 return SDValue(); 11970 } 11971 } 11972 } 11973 11974 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) { 11975 for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(), 11976 UE = PromOps[i].getNode()->use_end(); 11977 UI != UE; ++UI) { 11978 SDNode *User = *UI; 11979 if (User != N && !Visited.count(User)) 11980 return SDValue(); 11981 11982 // Make sure that we're not going to promote the non-output-value 11983 // operand(s) or SELECT or SELECT_CC. 11984 // FIXME: Although we could sometimes handle this, and it does occur in 11985 // practice that one of the condition inputs to the select is also one of 11986 // the outputs, we currently can't deal with this. 11987 if (User->getOpcode() == ISD::SELECT) { 11988 if (User->getOperand(0) == PromOps[i]) 11989 return SDValue(); 11990 } else if (User->getOpcode() == ISD::SELECT_CC) { 11991 if (User->getOperand(0) == PromOps[i] || 11992 User->getOperand(1) == PromOps[i]) 11993 return SDValue(); 11994 } 11995 } 11996 } 11997 11998 // Replace all inputs with the extension operand. 11999 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 12000 // Constants may have users outside the cluster of to-be-promoted nodes, 12001 // and so we need to replace those as we do the promotions. 12002 if (isa<ConstantSDNode>(Inputs[i])) 12003 continue; 12004 else 12005 DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0)); 12006 } 12007 12008 std::list<HandleSDNode> PromOpHandles; 12009 for (auto &PromOp : PromOps) 12010 PromOpHandles.emplace_back(PromOp); 12011 12012 // Replace all operations (these are all the same, but have a different 12013 // (i1) return type). DAG.getNode will validate that the types of 12014 // a binary operator match, so go through the list in reverse so that 12015 // we've likely promoted both operands first. Any intermediate truncations or 12016 // extensions disappear. 12017 while (!PromOpHandles.empty()) { 12018 SDValue PromOp = PromOpHandles.back().getValue(); 12019 PromOpHandles.pop_back(); 12020 12021 if (PromOp.getOpcode() == ISD::TRUNCATE || 12022 PromOp.getOpcode() == ISD::SIGN_EXTEND || 12023 PromOp.getOpcode() == ISD::ZERO_EXTEND || 12024 PromOp.getOpcode() == ISD::ANY_EXTEND) { 12025 if (!isa<ConstantSDNode>(PromOp.getOperand(0)) && 12026 PromOp.getOperand(0).getValueType() != MVT::i1) { 12027 // The operand is not yet ready (see comment below). 12028 PromOpHandles.emplace_front(PromOp); 12029 continue; 12030 } 12031 12032 SDValue RepValue = PromOp.getOperand(0); 12033 if (isa<ConstantSDNode>(RepValue)) 12034 RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue); 12035 12036 DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue); 12037 continue; 12038 } 12039 12040 unsigned C; 12041 switch (PromOp.getOpcode()) { 12042 default: C = 0; break; 12043 case ISD::SELECT: C = 1; break; 12044 case ISD::SELECT_CC: C = 2; break; 12045 } 12046 12047 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) && 12048 PromOp.getOperand(C).getValueType() != MVT::i1) || 12049 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) && 12050 PromOp.getOperand(C+1).getValueType() != MVT::i1)) { 12051 // The to-be-promoted operands of this node have not yet been 12052 // promoted (this should be rare because we're going through the 12053 // list backward, but if one of the operands has several users in 12054 // this cluster of to-be-promoted nodes, it is possible). 12055 PromOpHandles.emplace_front(PromOp); 12056 continue; 12057 } 12058 12059 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(), 12060 PromOp.getNode()->op_end()); 12061 12062 // If there are any constant inputs, make sure they're replaced now. 12063 for (unsigned i = 0; i < 2; ++i) 12064 if (isa<ConstantSDNode>(Ops[C+i])) 12065 Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]); 12066 12067 DAG.ReplaceAllUsesOfValueWith(PromOp, 12068 DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops)); 12069 } 12070 12071 // Now we're left with the initial truncation itself. 12072 if (N->getOpcode() == ISD::TRUNCATE) 12073 return N->getOperand(0); 12074 12075 // Otherwise, this is a comparison. The operands to be compared have just 12076 // changed type (to i1), but everything else is the same. 12077 return SDValue(N, 0); 12078 } 12079 12080 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N, 12081 DAGCombinerInfo &DCI) const { 12082 SelectionDAG &DAG = DCI.DAG; 12083 SDLoc dl(N); 12084 12085 // If we're tracking CR bits, we need to be careful that we don't have: 12086 // zext(binary-ops(trunc(x), trunc(y))) 12087 // or 12088 // zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...) 12089 // such that we're unnecessarily moving things into CR bits that can more 12090 // efficiently stay in GPRs. Note that if we're not certain that the high 12091 // bits are set as required by the final extension, we still may need to do 12092 // some masking to get the proper behavior. 12093 12094 // This same functionality is important on PPC64 when dealing with 12095 // 32-to-64-bit extensions; these occur often when 32-bit values are used as 12096 // the return values of functions. Because it is so similar, it is handled 12097 // here as well. 12098 12099 if (N->getValueType(0) != MVT::i32 && 12100 N->getValueType(0) != MVT::i64) 12101 return SDValue(); 12102 12103 if (!((N->getOperand(0).getValueType() == MVT::i1 && Subtarget.useCRBits()) || 12104 (N->getOperand(0).getValueType() == MVT::i32 && Subtarget.isPPC64()))) 12105 return SDValue(); 12106 12107 if (N->getOperand(0).getOpcode() != ISD::AND && 12108 N->getOperand(0).getOpcode() != ISD::OR && 12109 N->getOperand(0).getOpcode() != ISD::XOR && 12110 N->getOperand(0).getOpcode() != ISD::SELECT && 12111 N->getOperand(0).getOpcode() != ISD::SELECT_CC) 12112 return SDValue(); 12113 12114 SmallVector<SDValue, 4> Inputs; 12115 SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps; 12116 SmallPtrSet<SDNode *, 16> Visited; 12117 12118 // Visit all inputs, collect all binary operations (and, or, xor and 12119 // select) that are all fed by truncations. 12120 while (!BinOps.empty()) { 12121 SDValue BinOp = BinOps.back(); 12122 BinOps.pop_back(); 12123 12124 if (!Visited.insert(BinOp.getNode()).second) 12125 continue; 12126 12127 PromOps.push_back(BinOp); 12128 12129 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) { 12130 // The condition of the select is not promoted. 12131 if (BinOp.getOpcode() == ISD::SELECT && i == 0) 12132 continue; 12133 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3) 12134 continue; 12135 12136 if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE || 12137 isa<ConstantSDNode>(BinOp.getOperand(i))) { 12138 Inputs.push_back(BinOp.getOperand(i)); 12139 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND || 12140 BinOp.getOperand(i).getOpcode() == ISD::OR || 12141 BinOp.getOperand(i).getOpcode() == ISD::XOR || 12142 BinOp.getOperand(i).getOpcode() == ISD::SELECT || 12143 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) { 12144 BinOps.push_back(BinOp.getOperand(i)); 12145 } else { 12146 // We have an input that is not a truncation or another binary 12147 // operation; we'll abort this transformation. 12148 return SDValue(); 12149 } 12150 } 12151 } 12152 12153 // The operands of a select that must be truncated when the select is 12154 // promoted because the operand is actually part of the to-be-promoted set. 12155 DenseMap<SDNode *, EVT> SelectTruncOp[2]; 12156 12157 // Make sure that this is a self-contained cluster of operations (which 12158 // is not quite the same thing as saying that everything has only one 12159 // use). 12160 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 12161 if (isa<ConstantSDNode>(Inputs[i])) 12162 continue; 12163 12164 for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(), 12165 UE = Inputs[i].getNode()->use_end(); 12166 UI != UE; ++UI) { 12167 SDNode *User = *UI; 12168 if (User != N && !Visited.count(User)) 12169 return SDValue(); 12170 12171 // If we're going to promote the non-output-value operand(s) or SELECT or 12172 // SELECT_CC, record them for truncation. 12173 if (User->getOpcode() == ISD::SELECT) { 12174 if (User->getOperand(0) == Inputs[i]) 12175 SelectTruncOp[0].insert(std::make_pair(User, 12176 User->getOperand(0).getValueType())); 12177 } else if (User->getOpcode() == ISD::SELECT_CC) { 12178 if (User->getOperand(0) == Inputs[i]) 12179 SelectTruncOp[0].insert(std::make_pair(User, 12180 User->getOperand(0).getValueType())); 12181 if (User->getOperand(1) == Inputs[i]) 12182 SelectTruncOp[1].insert(std::make_pair(User, 12183 User->getOperand(1).getValueType())); 12184 } 12185 } 12186 } 12187 12188 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) { 12189 for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(), 12190 UE = PromOps[i].getNode()->use_end(); 12191 UI != UE; ++UI) { 12192 SDNode *User = *UI; 12193 if (User != N && !Visited.count(User)) 12194 return SDValue(); 12195 12196 // If we're going to promote the non-output-value operand(s) or SELECT or 12197 // SELECT_CC, record them for truncation. 12198 if (User->getOpcode() == ISD::SELECT) { 12199 if (User->getOperand(0) == PromOps[i]) 12200 SelectTruncOp[0].insert(std::make_pair(User, 12201 User->getOperand(0).getValueType())); 12202 } else if (User->getOpcode() == ISD::SELECT_CC) { 12203 if (User->getOperand(0) == PromOps[i]) 12204 SelectTruncOp[0].insert(std::make_pair(User, 12205 User->getOperand(0).getValueType())); 12206 if (User->getOperand(1) == PromOps[i]) 12207 SelectTruncOp[1].insert(std::make_pair(User, 12208 User->getOperand(1).getValueType())); 12209 } 12210 } 12211 } 12212 12213 unsigned PromBits = N->getOperand(0).getValueSizeInBits(); 12214 bool ReallyNeedsExt = false; 12215 if (N->getOpcode() != ISD::ANY_EXTEND) { 12216 // If all of the inputs are not already sign/zero extended, then 12217 // we'll still need to do that at the end. 12218 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 12219 if (isa<ConstantSDNode>(Inputs[i])) 12220 continue; 12221 12222 unsigned OpBits = 12223 Inputs[i].getOperand(0).getValueSizeInBits(); 12224 assert(PromBits < OpBits && "Truncation not to a smaller bit count?"); 12225 12226 if ((N->getOpcode() == ISD::ZERO_EXTEND && 12227 !DAG.MaskedValueIsZero(Inputs[i].getOperand(0), 12228 APInt::getHighBitsSet(OpBits, 12229 OpBits-PromBits))) || 12230 (N->getOpcode() == ISD::SIGN_EXTEND && 12231 DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) < 12232 (OpBits-(PromBits-1)))) { 12233 ReallyNeedsExt = true; 12234 break; 12235 } 12236 } 12237 } 12238 12239 // Replace all inputs, either with the truncation operand, or a 12240 // truncation or extension to the final output type. 12241 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 12242 // Constant inputs need to be replaced with the to-be-promoted nodes that 12243 // use them because they might have users outside of the cluster of 12244 // promoted nodes. 12245 if (isa<ConstantSDNode>(Inputs[i])) 12246 continue; 12247 12248 SDValue InSrc = Inputs[i].getOperand(0); 12249 if (Inputs[i].getValueType() == N->getValueType(0)) 12250 DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc); 12251 else if (N->getOpcode() == ISD::SIGN_EXTEND) 12252 DAG.ReplaceAllUsesOfValueWith(Inputs[i], 12253 DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0))); 12254 else if (N->getOpcode() == ISD::ZERO_EXTEND) 12255 DAG.ReplaceAllUsesOfValueWith(Inputs[i], 12256 DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0))); 12257 else 12258 DAG.ReplaceAllUsesOfValueWith(Inputs[i], 12259 DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0))); 12260 } 12261 12262 std::list<HandleSDNode> PromOpHandles; 12263 for (auto &PromOp : PromOps) 12264 PromOpHandles.emplace_back(PromOp); 12265 12266 // Replace all operations (these are all the same, but have a different 12267 // (promoted) return type). DAG.getNode will validate that the types of 12268 // a binary operator match, so go through the list in reverse so that 12269 // we've likely promoted both operands first. 12270 while (!PromOpHandles.empty()) { 12271 SDValue PromOp = PromOpHandles.back().getValue(); 12272 PromOpHandles.pop_back(); 12273 12274 unsigned C; 12275 switch (PromOp.getOpcode()) { 12276 default: C = 0; break; 12277 case ISD::SELECT: C = 1; break; 12278 case ISD::SELECT_CC: C = 2; break; 12279 } 12280 12281 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) && 12282 PromOp.getOperand(C).getValueType() != N->getValueType(0)) || 12283 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) && 12284 PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) { 12285 // The to-be-promoted operands of this node have not yet been 12286 // promoted (this should be rare because we're going through the 12287 // list backward, but if one of the operands has several users in 12288 // this cluster of to-be-promoted nodes, it is possible). 12289 PromOpHandles.emplace_front(PromOp); 12290 continue; 12291 } 12292 12293 // For SELECT and SELECT_CC nodes, we do a similar check for any 12294 // to-be-promoted comparison inputs. 12295 if (PromOp.getOpcode() == ISD::SELECT || 12296 PromOp.getOpcode() == ISD::SELECT_CC) { 12297 if ((SelectTruncOp[0].count(PromOp.getNode()) && 12298 PromOp.getOperand(0).getValueType() != N->getValueType(0)) || 12299 (SelectTruncOp[1].count(PromOp.getNode()) && 12300 PromOp.getOperand(1).getValueType() != N->getValueType(0))) { 12301 PromOpHandles.emplace_front(PromOp); 12302 continue; 12303 } 12304 } 12305 12306 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(), 12307 PromOp.getNode()->op_end()); 12308 12309 // If this node has constant inputs, then they'll need to be promoted here. 12310 for (unsigned i = 0; i < 2; ++i) { 12311 if (!isa<ConstantSDNode>(Ops[C+i])) 12312 continue; 12313 if (Ops[C+i].getValueType() == N->getValueType(0)) 12314 continue; 12315 12316 if (N->getOpcode() == ISD::SIGN_EXTEND) 12317 Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); 12318 else if (N->getOpcode() == ISD::ZERO_EXTEND) 12319 Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); 12320 else 12321 Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); 12322 } 12323 12324 // If we've promoted the comparison inputs of a SELECT or SELECT_CC, 12325 // truncate them again to the original value type. 12326 if (PromOp.getOpcode() == ISD::SELECT || 12327 PromOp.getOpcode() == ISD::SELECT_CC) { 12328 auto SI0 = SelectTruncOp[0].find(PromOp.getNode()); 12329 if (SI0 != SelectTruncOp[0].end()) 12330 Ops[0] = DAG.getNode(ISD::TRUNCATE, dl, SI0->second, Ops[0]); 12331 auto SI1 = SelectTruncOp[1].find(PromOp.getNode()); 12332 if (SI1 != SelectTruncOp[1].end()) 12333 Ops[1] = DAG.getNode(ISD::TRUNCATE, dl, SI1->second, Ops[1]); 12334 } 12335 12336 DAG.ReplaceAllUsesOfValueWith(PromOp, 12337 DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops)); 12338 } 12339 12340 // Now we're left with the initial extension itself. 12341 if (!ReallyNeedsExt) 12342 return N->getOperand(0); 12343 12344 // To zero extend, just mask off everything except for the first bit (in the 12345 // i1 case). 12346 if (N->getOpcode() == ISD::ZERO_EXTEND) 12347 return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0), 12348 DAG.getConstant(APInt::getLowBitsSet( 12349 N->getValueSizeInBits(0), PromBits), 12350 dl, N->getValueType(0))); 12351 12352 assert(N->getOpcode() == ISD::SIGN_EXTEND && 12353 "Invalid extension type"); 12354 EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0), DAG.getDataLayout()); 12355 SDValue ShiftCst = 12356 DAG.getConstant(N->getValueSizeInBits(0) - PromBits, dl, ShiftAmountTy); 12357 return DAG.getNode( 12358 ISD::SRA, dl, N->getValueType(0), 12359 DAG.getNode(ISD::SHL, dl, N->getValueType(0), N->getOperand(0), ShiftCst), 12360 ShiftCst); 12361 } 12362 12363 SDValue PPCTargetLowering::combineSetCC(SDNode *N, 12364 DAGCombinerInfo &DCI) const { 12365 assert(N->getOpcode() == ISD::SETCC && 12366 "Should be called with a SETCC node"); 12367 12368 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 12369 if (CC == ISD::SETNE || CC == ISD::SETEQ) { 12370 SDValue LHS = N->getOperand(0); 12371 SDValue RHS = N->getOperand(1); 12372 12373 // If there is a '0 - y' pattern, canonicalize the pattern to the RHS. 12374 if (LHS.getOpcode() == ISD::SUB && isNullConstant(LHS.getOperand(0)) && 12375 LHS.hasOneUse()) 12376 std::swap(LHS, RHS); 12377 12378 // x == 0-y --> x+y == 0 12379 // x != 0-y --> x+y != 0 12380 if (RHS.getOpcode() == ISD::SUB && isNullConstant(RHS.getOperand(0)) && 12381 RHS.hasOneUse()) { 12382 SDLoc DL(N); 12383 SelectionDAG &DAG = DCI.DAG; 12384 EVT VT = N->getValueType(0); 12385 EVT OpVT = LHS.getValueType(); 12386 SDValue Add = DAG.getNode(ISD::ADD, DL, OpVT, LHS, RHS.getOperand(1)); 12387 return DAG.getSetCC(DL, VT, Add, DAG.getConstant(0, DL, OpVT), CC); 12388 } 12389 } 12390 12391 return DAGCombineTruncBoolExt(N, DCI); 12392 } 12393 12394 // Is this an extending load from an f32 to an f64? 12395 static bool isFPExtLoad(SDValue Op) { 12396 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op.getNode())) 12397 return LD->getExtensionType() == ISD::EXTLOAD && 12398 Op.getValueType() == MVT::f64; 12399 return false; 12400 } 12401 12402 /// Reduces the number of fp-to-int conversion when building a vector. 12403 /// 12404 /// If this vector is built out of floating to integer conversions, 12405 /// transform it to a vector built out of floating point values followed by a 12406 /// single floating to integer conversion of the vector. 12407 /// Namely (build_vector (fptosi $A), (fptosi $B), ...) 12408 /// becomes (fptosi (build_vector ($A, $B, ...))) 12409 SDValue PPCTargetLowering:: 12410 combineElementTruncationToVectorTruncation(SDNode *N, 12411 DAGCombinerInfo &DCI) const { 12412 assert(N->getOpcode() == ISD::BUILD_VECTOR && 12413 "Should be called with a BUILD_VECTOR node"); 12414 12415 SelectionDAG &DAG = DCI.DAG; 12416 SDLoc dl(N); 12417 12418 SDValue FirstInput = N->getOperand(0); 12419 assert(FirstInput.getOpcode() == PPCISD::MFVSR && 12420 "The input operand must be an fp-to-int conversion."); 12421 12422 // This combine happens after legalization so the fp_to_[su]i nodes are 12423 // already converted to PPCSISD nodes. 12424 unsigned FirstConversion = FirstInput.getOperand(0).getOpcode(); 12425 if (FirstConversion == PPCISD::FCTIDZ || 12426 FirstConversion == PPCISD::FCTIDUZ || 12427 FirstConversion == PPCISD::FCTIWZ || 12428 FirstConversion == PPCISD::FCTIWUZ) { 12429 bool IsSplat = true; 12430 bool Is32Bit = FirstConversion == PPCISD::FCTIWZ || 12431 FirstConversion == PPCISD::FCTIWUZ; 12432 EVT SrcVT = FirstInput.getOperand(0).getValueType(); 12433 SmallVector<SDValue, 4> Ops; 12434 EVT TargetVT = N->getValueType(0); 12435 for (int i = 0, e = N->getNumOperands(); i < e; ++i) { 12436 SDValue NextOp = N->getOperand(i); 12437 if (NextOp.getOpcode() != PPCISD::MFVSR) 12438 return SDValue(); 12439 unsigned NextConversion = NextOp.getOperand(0).getOpcode(); 12440 if (NextConversion != FirstConversion) 12441 return SDValue(); 12442 // If we are converting to 32-bit integers, we need to add an FP_ROUND. 12443 // This is not valid if the input was originally double precision. It is 12444 // also not profitable to do unless this is an extending load in which 12445 // case doing this combine will allow us to combine consecutive loads. 12446 if (Is32Bit && !isFPExtLoad(NextOp.getOperand(0).getOperand(0))) 12447 return SDValue(); 12448 if (N->getOperand(i) != FirstInput) 12449 IsSplat = false; 12450 } 12451 12452 // If this is a splat, we leave it as-is since there will be only a single 12453 // fp-to-int conversion followed by a splat of the integer. This is better 12454 // for 32-bit and smaller ints and neutral for 64-bit ints. 12455 if (IsSplat) 12456 return SDValue(); 12457 12458 // Now that we know we have the right type of node, get its operands 12459 for (int i = 0, e = N->getNumOperands(); i < e; ++i) { 12460 SDValue In = N->getOperand(i).getOperand(0); 12461 if (Is32Bit) { 12462 // For 32-bit values, we need to add an FP_ROUND node (if we made it 12463 // here, we know that all inputs are extending loads so this is safe). 12464 if (In.isUndef()) 12465 Ops.push_back(DAG.getUNDEF(SrcVT)); 12466 else { 12467 SDValue Trunc = DAG.getNode(ISD::FP_ROUND, dl, 12468 MVT::f32, In.getOperand(0), 12469 DAG.getIntPtrConstant(1, dl)); 12470 Ops.push_back(Trunc); 12471 } 12472 } else 12473 Ops.push_back(In.isUndef() ? DAG.getUNDEF(SrcVT) : In.getOperand(0)); 12474 } 12475 12476 unsigned Opcode; 12477 if (FirstConversion == PPCISD::FCTIDZ || 12478 FirstConversion == PPCISD::FCTIWZ) 12479 Opcode = ISD::FP_TO_SINT; 12480 else 12481 Opcode = ISD::FP_TO_UINT; 12482 12483 EVT NewVT = TargetVT == MVT::v2i64 ? MVT::v2f64 : MVT::v4f32; 12484 SDValue BV = DAG.getBuildVector(NewVT, dl, Ops); 12485 return DAG.getNode(Opcode, dl, TargetVT, BV); 12486 } 12487 return SDValue(); 12488 } 12489 12490 /// Reduce the number of loads when building a vector. 12491 /// 12492 /// Building a vector out of multiple loads can be converted to a load 12493 /// of the vector type if the loads are consecutive. If the loads are 12494 /// consecutive but in descending order, a shuffle is added at the end 12495 /// to reorder the vector. 12496 static SDValue combineBVOfConsecutiveLoads(SDNode *N, SelectionDAG &DAG) { 12497 assert(N->getOpcode() == ISD::BUILD_VECTOR && 12498 "Should be called with a BUILD_VECTOR node"); 12499 12500 SDLoc dl(N); 12501 12502 // Return early for non byte-sized type, as they can't be consecutive. 12503 if (!N->getValueType(0).getVectorElementType().isByteSized()) 12504 return SDValue(); 12505 12506 bool InputsAreConsecutiveLoads = true; 12507 bool InputsAreReverseConsecutive = true; 12508 unsigned ElemSize = N->getValueType(0).getScalarType().getStoreSize(); 12509 SDValue FirstInput = N->getOperand(0); 12510 bool IsRoundOfExtLoad = false; 12511 12512 if (FirstInput.getOpcode() == ISD::FP_ROUND && 12513 FirstInput.getOperand(0).getOpcode() == ISD::LOAD) { 12514 LoadSDNode *LD = dyn_cast<LoadSDNode>(FirstInput.getOperand(0)); 12515 IsRoundOfExtLoad = LD->getExtensionType() == ISD::EXTLOAD; 12516 } 12517 // Not a build vector of (possibly fp_rounded) loads. 12518 if ((!IsRoundOfExtLoad && FirstInput.getOpcode() != ISD::LOAD) || 12519 N->getNumOperands() == 1) 12520 return SDValue(); 12521 12522 for (int i = 1, e = N->getNumOperands(); i < e; ++i) { 12523 // If any inputs are fp_round(extload), they all must be. 12524 if (IsRoundOfExtLoad && N->getOperand(i).getOpcode() != ISD::FP_ROUND) 12525 return SDValue(); 12526 12527 SDValue NextInput = IsRoundOfExtLoad ? N->getOperand(i).getOperand(0) : 12528 N->getOperand(i); 12529 if (NextInput.getOpcode() != ISD::LOAD) 12530 return SDValue(); 12531 12532 SDValue PreviousInput = 12533 IsRoundOfExtLoad ? N->getOperand(i-1).getOperand(0) : N->getOperand(i-1); 12534 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(PreviousInput); 12535 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(NextInput); 12536 12537 // If any inputs are fp_round(extload), they all must be. 12538 if (IsRoundOfExtLoad && LD2->getExtensionType() != ISD::EXTLOAD) 12539 return SDValue(); 12540 12541 if (!isConsecutiveLS(LD2, LD1, ElemSize, 1, DAG)) 12542 InputsAreConsecutiveLoads = false; 12543 if (!isConsecutiveLS(LD1, LD2, ElemSize, 1, DAG)) 12544 InputsAreReverseConsecutive = false; 12545 12546 // Exit early if the loads are neither consecutive nor reverse consecutive. 12547 if (!InputsAreConsecutiveLoads && !InputsAreReverseConsecutive) 12548 return SDValue(); 12549 } 12550 12551 assert(!(InputsAreConsecutiveLoads && InputsAreReverseConsecutive) && 12552 "The loads cannot be both consecutive and reverse consecutive."); 12553 12554 SDValue FirstLoadOp = 12555 IsRoundOfExtLoad ? FirstInput.getOperand(0) : FirstInput; 12556 SDValue LastLoadOp = 12557 IsRoundOfExtLoad ? N->getOperand(N->getNumOperands()-1).getOperand(0) : 12558 N->getOperand(N->getNumOperands()-1); 12559 12560 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(FirstLoadOp); 12561 LoadSDNode *LDL = dyn_cast<LoadSDNode>(LastLoadOp); 12562 if (InputsAreConsecutiveLoads) { 12563 assert(LD1 && "Input needs to be a LoadSDNode."); 12564 return DAG.getLoad(N->getValueType(0), dl, LD1->getChain(), 12565 LD1->getBasePtr(), LD1->getPointerInfo(), 12566 LD1->getAlignment()); 12567 } 12568 if (InputsAreReverseConsecutive) { 12569 assert(LDL && "Input needs to be a LoadSDNode."); 12570 SDValue Load = DAG.getLoad(N->getValueType(0), dl, LDL->getChain(), 12571 LDL->getBasePtr(), LDL->getPointerInfo(), 12572 LDL->getAlignment()); 12573 SmallVector<int, 16> Ops; 12574 for (int i = N->getNumOperands() - 1; i >= 0; i--) 12575 Ops.push_back(i); 12576 12577 return DAG.getVectorShuffle(N->getValueType(0), dl, Load, 12578 DAG.getUNDEF(N->getValueType(0)), Ops); 12579 } 12580 return SDValue(); 12581 } 12582 12583 // This function adds the required vector_shuffle needed to get 12584 // the elements of the vector extract in the correct position 12585 // as specified by the CorrectElems encoding. 12586 static SDValue addShuffleForVecExtend(SDNode *N, SelectionDAG &DAG, 12587 SDValue Input, uint64_t Elems, 12588 uint64_t CorrectElems) { 12589 SDLoc dl(N); 12590 12591 unsigned NumElems = Input.getValueType().getVectorNumElements(); 12592 SmallVector<int, 16> ShuffleMask(NumElems, -1); 12593 12594 // Knowing the element indices being extracted from the original 12595 // vector and the order in which they're being inserted, just put 12596 // them at element indices required for the instruction. 12597 for (unsigned i = 0; i < N->getNumOperands(); i++) { 12598 if (DAG.getDataLayout().isLittleEndian()) 12599 ShuffleMask[CorrectElems & 0xF] = Elems & 0xF; 12600 else 12601 ShuffleMask[(CorrectElems & 0xF0) >> 4] = (Elems & 0xF0) >> 4; 12602 CorrectElems = CorrectElems >> 8; 12603 Elems = Elems >> 8; 12604 } 12605 12606 SDValue Shuffle = 12607 DAG.getVectorShuffle(Input.getValueType(), dl, Input, 12608 DAG.getUNDEF(Input.getValueType()), ShuffleMask); 12609 12610 EVT Ty = N->getValueType(0); 12611 SDValue BV = DAG.getNode(PPCISD::SExtVElems, dl, Ty, Shuffle); 12612 return BV; 12613 } 12614 12615 // Look for build vector patterns where input operands come from sign 12616 // extended vector_extract elements of specific indices. If the correct indices 12617 // aren't used, add a vector shuffle to fix up the indices and create a new 12618 // PPCISD:SExtVElems node which selects the vector sign extend instructions 12619 // during instruction selection. 12620 static SDValue combineBVOfVecSExt(SDNode *N, SelectionDAG &DAG) { 12621 // This array encodes the indices that the vector sign extend instructions 12622 // extract from when extending from one type to another for both BE and LE. 12623 // The right nibble of each byte corresponds to the LE incides. 12624 // and the left nibble of each byte corresponds to the BE incides. 12625 // For example: 0x3074B8FC byte->word 12626 // For LE: the allowed indices are: 0x0,0x4,0x8,0xC 12627 // For BE: the allowed indices are: 0x3,0x7,0xB,0xF 12628 // For example: 0x000070F8 byte->double word 12629 // For LE: the allowed indices are: 0x0,0x8 12630 // For BE: the allowed indices are: 0x7,0xF 12631 uint64_t TargetElems[] = { 12632 0x3074B8FC, // b->w 12633 0x000070F8, // b->d 12634 0x10325476, // h->w 12635 0x00003074, // h->d 12636 0x00001032, // w->d 12637 }; 12638 12639 uint64_t Elems = 0; 12640 int Index; 12641 SDValue Input; 12642 12643 auto isSExtOfVecExtract = [&](SDValue Op) -> bool { 12644 if (!Op) 12645 return false; 12646 if (Op.getOpcode() != ISD::SIGN_EXTEND && 12647 Op.getOpcode() != ISD::SIGN_EXTEND_INREG) 12648 return false; 12649 12650 // A SIGN_EXTEND_INREG might be fed by an ANY_EXTEND to produce a value 12651 // of the right width. 12652 SDValue Extract = Op.getOperand(0); 12653 if (Extract.getOpcode() == ISD::ANY_EXTEND) 12654 Extract = Extract.getOperand(0); 12655 if (Extract.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 12656 return false; 12657 12658 ConstantSDNode *ExtOp = dyn_cast<ConstantSDNode>(Extract.getOperand(1)); 12659 if (!ExtOp) 12660 return false; 12661 12662 Index = ExtOp->getZExtValue(); 12663 if (Input && Input != Extract.getOperand(0)) 12664 return false; 12665 12666 if (!Input) 12667 Input = Extract.getOperand(0); 12668 12669 Elems = Elems << 8; 12670 Index = DAG.getDataLayout().isLittleEndian() ? Index : Index << 4; 12671 Elems |= Index; 12672 12673 return true; 12674 }; 12675 12676 // If the build vector operands aren't sign extended vector extracts, 12677 // of the same input vector, then return. 12678 for (unsigned i = 0; i < N->getNumOperands(); i++) { 12679 if (!isSExtOfVecExtract(N->getOperand(i))) { 12680 return SDValue(); 12681 } 12682 } 12683 12684 // If the vector extract indicies are not correct, add the appropriate 12685 // vector_shuffle. 12686 int TgtElemArrayIdx; 12687 int InputSize = Input.getValueType().getScalarSizeInBits(); 12688 int OutputSize = N->getValueType(0).getScalarSizeInBits(); 12689 if (InputSize + OutputSize == 40) 12690 TgtElemArrayIdx = 0; 12691 else if (InputSize + OutputSize == 72) 12692 TgtElemArrayIdx = 1; 12693 else if (InputSize + OutputSize == 48) 12694 TgtElemArrayIdx = 2; 12695 else if (InputSize + OutputSize == 80) 12696 TgtElemArrayIdx = 3; 12697 else if (InputSize + OutputSize == 96) 12698 TgtElemArrayIdx = 4; 12699 else 12700 return SDValue(); 12701 12702 uint64_t CorrectElems = TargetElems[TgtElemArrayIdx]; 12703 CorrectElems = DAG.getDataLayout().isLittleEndian() 12704 ? CorrectElems & 0x0F0F0F0F0F0F0F0F 12705 : CorrectElems & 0xF0F0F0F0F0F0F0F0; 12706 if (Elems != CorrectElems) { 12707 return addShuffleForVecExtend(N, DAG, Input, Elems, CorrectElems); 12708 } 12709 12710 // Regular lowering will catch cases where a shuffle is not needed. 12711 return SDValue(); 12712 } 12713 12714 SDValue PPCTargetLowering::DAGCombineBuildVector(SDNode *N, 12715 DAGCombinerInfo &DCI) const { 12716 assert(N->getOpcode() == ISD::BUILD_VECTOR && 12717 "Should be called with a BUILD_VECTOR node"); 12718 12719 SelectionDAG &DAG = DCI.DAG; 12720 SDLoc dl(N); 12721 12722 if (!Subtarget.hasVSX()) 12723 return SDValue(); 12724 12725 // The target independent DAG combiner will leave a build_vector of 12726 // float-to-int conversions intact. We can generate MUCH better code for 12727 // a float-to-int conversion of a vector of floats. 12728 SDValue FirstInput = N->getOperand(0); 12729 if (FirstInput.getOpcode() == PPCISD::MFVSR) { 12730 SDValue Reduced = combineElementTruncationToVectorTruncation(N, DCI); 12731 if (Reduced) 12732 return Reduced; 12733 } 12734 12735 // If we're building a vector out of consecutive loads, just load that 12736 // vector type. 12737 SDValue Reduced = combineBVOfConsecutiveLoads(N, DAG); 12738 if (Reduced) 12739 return Reduced; 12740 12741 // If we're building a vector out of extended elements from another vector 12742 // we have P9 vector integer extend instructions. The code assumes legal 12743 // input types (i.e. it can't handle things like v4i16) so do not run before 12744 // legalization. 12745 if (Subtarget.hasP9Altivec() && !DCI.isBeforeLegalize()) { 12746 Reduced = combineBVOfVecSExt(N, DAG); 12747 if (Reduced) 12748 return Reduced; 12749 } 12750 12751 12752 if (N->getValueType(0) != MVT::v2f64) 12753 return SDValue(); 12754 12755 // Looking for: 12756 // (build_vector ([su]int_to_fp (extractelt 0)), [su]int_to_fp (extractelt 1)) 12757 if (FirstInput.getOpcode() != ISD::SINT_TO_FP && 12758 FirstInput.getOpcode() != ISD::UINT_TO_FP) 12759 return SDValue(); 12760 if (N->getOperand(1).getOpcode() != ISD::SINT_TO_FP && 12761 N->getOperand(1).getOpcode() != ISD::UINT_TO_FP) 12762 return SDValue(); 12763 if (FirstInput.getOpcode() != N->getOperand(1).getOpcode()) 12764 return SDValue(); 12765 12766 SDValue Ext1 = FirstInput.getOperand(0); 12767 SDValue Ext2 = N->getOperand(1).getOperand(0); 12768 if(Ext1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 12769 Ext2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 12770 return SDValue(); 12771 12772 ConstantSDNode *Ext1Op = dyn_cast<ConstantSDNode>(Ext1.getOperand(1)); 12773 ConstantSDNode *Ext2Op = dyn_cast<ConstantSDNode>(Ext2.getOperand(1)); 12774 if (!Ext1Op || !Ext2Op) 12775 return SDValue(); 12776 if (Ext1.getOperand(0).getValueType() != MVT::v4i32 || 12777 Ext1.getOperand(0) != Ext2.getOperand(0)) 12778 return SDValue(); 12779 12780 int FirstElem = Ext1Op->getZExtValue(); 12781 int SecondElem = Ext2Op->getZExtValue(); 12782 int SubvecIdx; 12783 if (FirstElem == 0 && SecondElem == 1) 12784 SubvecIdx = Subtarget.isLittleEndian() ? 1 : 0; 12785 else if (FirstElem == 2 && SecondElem == 3) 12786 SubvecIdx = Subtarget.isLittleEndian() ? 0 : 1; 12787 else 12788 return SDValue(); 12789 12790 SDValue SrcVec = Ext1.getOperand(0); 12791 auto NodeType = (N->getOperand(1).getOpcode() == ISD::SINT_TO_FP) ? 12792 PPCISD::SINT_VEC_TO_FP : PPCISD::UINT_VEC_TO_FP; 12793 return DAG.getNode(NodeType, dl, MVT::v2f64, 12794 SrcVec, DAG.getIntPtrConstant(SubvecIdx, dl)); 12795 } 12796 12797 SDValue PPCTargetLowering::combineFPToIntToFP(SDNode *N, 12798 DAGCombinerInfo &DCI) const { 12799 assert((N->getOpcode() == ISD::SINT_TO_FP || 12800 N->getOpcode() == ISD::UINT_TO_FP) && 12801 "Need an int -> FP conversion node here"); 12802 12803 if (useSoftFloat() || !Subtarget.has64BitSupport()) 12804 return SDValue(); 12805 12806 SelectionDAG &DAG = DCI.DAG; 12807 SDLoc dl(N); 12808 SDValue Op(N, 0); 12809 12810 // Don't handle ppc_fp128 here or conversions that are out-of-range capable 12811 // from the hardware. 12812 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64) 12813 return SDValue(); 12814 if (Op.getOperand(0).getValueType().getSimpleVT() <= MVT(MVT::i1) || 12815 Op.getOperand(0).getValueType().getSimpleVT() > MVT(MVT::i64)) 12816 return SDValue(); 12817 12818 SDValue FirstOperand(Op.getOperand(0)); 12819 bool SubWordLoad = FirstOperand.getOpcode() == ISD::LOAD && 12820 (FirstOperand.getValueType() == MVT::i8 || 12821 FirstOperand.getValueType() == MVT::i16); 12822 if (Subtarget.hasP9Vector() && Subtarget.hasP9Altivec() && SubWordLoad) { 12823 bool Signed = N->getOpcode() == ISD::SINT_TO_FP; 12824 bool DstDouble = Op.getValueType() == MVT::f64; 12825 unsigned ConvOp = Signed ? 12826 (DstDouble ? PPCISD::FCFID : PPCISD::FCFIDS) : 12827 (DstDouble ? PPCISD::FCFIDU : PPCISD::FCFIDUS); 12828 SDValue WidthConst = 12829 DAG.getIntPtrConstant(FirstOperand.getValueType() == MVT::i8 ? 1 : 2, 12830 dl, false); 12831 LoadSDNode *LDN = cast<LoadSDNode>(FirstOperand.getNode()); 12832 SDValue Ops[] = { LDN->getChain(), LDN->getBasePtr(), WidthConst }; 12833 SDValue Ld = DAG.getMemIntrinsicNode(PPCISD::LXSIZX, dl, 12834 DAG.getVTList(MVT::f64, MVT::Other), 12835 Ops, MVT::i8, LDN->getMemOperand()); 12836 12837 // For signed conversion, we need to sign-extend the value in the VSR 12838 if (Signed) { 12839 SDValue ExtOps[] = { Ld, WidthConst }; 12840 SDValue Ext = DAG.getNode(PPCISD::VEXTS, dl, MVT::f64, ExtOps); 12841 return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ext); 12842 } else 12843 return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ld); 12844 } 12845 12846 12847 // For i32 intermediate values, unfortunately, the conversion functions 12848 // leave the upper 32 bits of the value are undefined. Within the set of 12849 // scalar instructions, we have no method for zero- or sign-extending the 12850 // value. Thus, we cannot handle i32 intermediate values here. 12851 if (Op.getOperand(0).getValueType() == MVT::i32) 12852 return SDValue(); 12853 12854 assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) && 12855 "UINT_TO_FP is supported only with FPCVT"); 12856 12857 // If we have FCFIDS, then use it when converting to single-precision. 12858 // Otherwise, convert to double-precision and then round. 12859 unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 12860 ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS 12861 : PPCISD::FCFIDS) 12862 : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU 12863 : PPCISD::FCFID); 12864 MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 12865 ? MVT::f32 12866 : MVT::f64; 12867 12868 // If we're converting from a float, to an int, and back to a float again, 12869 // then we don't need the store/load pair at all. 12870 if ((Op.getOperand(0).getOpcode() == ISD::FP_TO_UINT && 12871 Subtarget.hasFPCVT()) || 12872 (Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT)) { 12873 SDValue Src = Op.getOperand(0).getOperand(0); 12874 if (Src.getValueType() == MVT::f32) { 12875 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src); 12876 DCI.AddToWorklist(Src.getNode()); 12877 } else if (Src.getValueType() != MVT::f64) { 12878 // Make sure that we don't pick up a ppc_fp128 source value. 12879 return SDValue(); 12880 } 12881 12882 unsigned FCTOp = 12883 Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT ? PPCISD::FCTIDZ : 12884 PPCISD::FCTIDUZ; 12885 12886 SDValue Tmp = DAG.getNode(FCTOp, dl, MVT::f64, Src); 12887 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Tmp); 12888 12889 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) { 12890 FP = DAG.getNode(ISD::FP_ROUND, dl, 12891 MVT::f32, FP, DAG.getIntPtrConstant(0, dl)); 12892 DCI.AddToWorklist(FP.getNode()); 12893 } 12894 12895 return FP; 12896 } 12897 12898 return SDValue(); 12899 } 12900 12901 // expandVSXLoadForLE - Convert VSX loads (which may be intrinsics for 12902 // builtins) into loads with swaps. 12903 SDValue PPCTargetLowering::expandVSXLoadForLE(SDNode *N, 12904 DAGCombinerInfo &DCI) const { 12905 SelectionDAG &DAG = DCI.DAG; 12906 SDLoc dl(N); 12907 SDValue Chain; 12908 SDValue Base; 12909 MachineMemOperand *MMO; 12910 12911 switch (N->getOpcode()) { 12912 default: 12913 llvm_unreachable("Unexpected opcode for little endian VSX load"); 12914 case ISD::LOAD: { 12915 LoadSDNode *LD = cast<LoadSDNode>(N); 12916 Chain = LD->getChain(); 12917 Base = LD->getBasePtr(); 12918 MMO = LD->getMemOperand(); 12919 // If the MMO suggests this isn't a load of a full vector, leave 12920 // things alone. For a built-in, we have to make the change for 12921 // correctness, so if there is a size problem that will be a bug. 12922 if (MMO->getSize() < 16) 12923 return SDValue(); 12924 break; 12925 } 12926 case ISD::INTRINSIC_W_CHAIN: { 12927 MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N); 12928 Chain = Intrin->getChain(); 12929 // Similarly to the store case below, Intrin->getBasePtr() doesn't get 12930 // us what we want. Get operand 2 instead. 12931 Base = Intrin->getOperand(2); 12932 MMO = Intrin->getMemOperand(); 12933 break; 12934 } 12935 } 12936 12937 MVT VecTy = N->getValueType(0).getSimpleVT(); 12938 12939 // Do not expand to PPCISD::LXVD2X + PPCISD::XXSWAPD when the load is 12940 // aligned and the type is a vector with elements up to 4 bytes 12941 if (Subtarget.needsSwapsForVSXMemOps() && !(MMO->getAlignment()%16) 12942 && VecTy.getScalarSizeInBits() <= 32 ) { 12943 return SDValue(); 12944 } 12945 12946 SDValue LoadOps[] = { Chain, Base }; 12947 SDValue Load = DAG.getMemIntrinsicNode(PPCISD::LXVD2X, dl, 12948 DAG.getVTList(MVT::v2f64, MVT::Other), 12949 LoadOps, MVT::v2f64, MMO); 12950 12951 DCI.AddToWorklist(Load.getNode()); 12952 Chain = Load.getValue(1); 12953 SDValue Swap = DAG.getNode( 12954 PPCISD::XXSWAPD, dl, DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Load); 12955 DCI.AddToWorklist(Swap.getNode()); 12956 12957 // Add a bitcast if the resulting load type doesn't match v2f64. 12958 if (VecTy != MVT::v2f64) { 12959 SDValue N = DAG.getNode(ISD::BITCAST, dl, VecTy, Swap); 12960 DCI.AddToWorklist(N.getNode()); 12961 // Package {bitcast value, swap's chain} to match Load's shape. 12962 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VecTy, MVT::Other), 12963 N, Swap.getValue(1)); 12964 } 12965 12966 return Swap; 12967 } 12968 12969 // expandVSXStoreForLE - Convert VSX stores (which may be intrinsics for 12970 // builtins) into stores with swaps. 12971 SDValue PPCTargetLowering::expandVSXStoreForLE(SDNode *N, 12972 DAGCombinerInfo &DCI) const { 12973 SelectionDAG &DAG = DCI.DAG; 12974 SDLoc dl(N); 12975 SDValue Chain; 12976 SDValue Base; 12977 unsigned SrcOpnd; 12978 MachineMemOperand *MMO; 12979 12980 switch (N->getOpcode()) { 12981 default: 12982 llvm_unreachable("Unexpected opcode for little endian VSX store"); 12983 case ISD::STORE: { 12984 StoreSDNode *ST = cast<StoreSDNode>(N); 12985 Chain = ST->getChain(); 12986 Base = ST->getBasePtr(); 12987 MMO = ST->getMemOperand(); 12988 SrcOpnd = 1; 12989 // If the MMO suggests this isn't a store of a full vector, leave 12990 // things alone. For a built-in, we have to make the change for 12991 // correctness, so if there is a size problem that will be a bug. 12992 if (MMO->getSize() < 16) 12993 return SDValue(); 12994 break; 12995 } 12996 case ISD::INTRINSIC_VOID: { 12997 MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N); 12998 Chain = Intrin->getChain(); 12999 // Intrin->getBasePtr() oddly does not get what we want. 13000 Base = Intrin->getOperand(3); 13001 MMO = Intrin->getMemOperand(); 13002 SrcOpnd = 2; 13003 break; 13004 } 13005 } 13006 13007 SDValue Src = N->getOperand(SrcOpnd); 13008 MVT VecTy = Src.getValueType().getSimpleVT(); 13009 13010 // Do not expand to PPCISD::XXSWAPD and PPCISD::STXVD2X when the load is 13011 // aligned and the type is a vector with elements up to 4 bytes 13012 if (Subtarget.needsSwapsForVSXMemOps() && !(MMO->getAlignment()%16) 13013 && VecTy.getScalarSizeInBits() <= 32 ) { 13014 return SDValue(); 13015 } 13016 13017 // All stores are done as v2f64 and possible bit cast. 13018 if (VecTy != MVT::v2f64) { 13019 Src = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Src); 13020 DCI.AddToWorklist(Src.getNode()); 13021 } 13022 13023 SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl, 13024 DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Src); 13025 DCI.AddToWorklist(Swap.getNode()); 13026 Chain = Swap.getValue(1); 13027 SDValue StoreOps[] = { Chain, Swap, Base }; 13028 SDValue Store = DAG.getMemIntrinsicNode(PPCISD::STXVD2X, dl, 13029 DAG.getVTList(MVT::Other), 13030 StoreOps, VecTy, MMO); 13031 DCI.AddToWorklist(Store.getNode()); 13032 return Store; 13033 } 13034 13035 // Handle DAG combine for STORE (FP_TO_INT F). 13036 SDValue PPCTargetLowering::combineStoreFPToInt(SDNode *N, 13037 DAGCombinerInfo &DCI) const { 13038 13039 SelectionDAG &DAG = DCI.DAG; 13040 SDLoc dl(N); 13041 unsigned Opcode = N->getOperand(1).getOpcode(); 13042 13043 assert((Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT) 13044 && "Not a FP_TO_INT Instruction!"); 13045 13046 SDValue Val = N->getOperand(1).getOperand(0); 13047 EVT Op1VT = N->getOperand(1).getValueType(); 13048 EVT ResVT = Val.getValueType(); 13049 13050 // Floating point types smaller than 32 bits are not legal on Power. 13051 if (ResVT.getScalarSizeInBits() < 32) 13052 return SDValue(); 13053 13054 // Only perform combine for conversion to i64/i32 or power9 i16/i8. 13055 bool ValidTypeForStoreFltAsInt = 13056 (Op1VT == MVT::i32 || Op1VT == MVT::i64 || 13057 (Subtarget.hasP9Vector() && (Op1VT == MVT::i16 || Op1VT == MVT::i8))); 13058 13059 if (ResVT == MVT::ppcf128 || !Subtarget.hasP8Altivec() || 13060 cast<StoreSDNode>(N)->isTruncatingStore() || !ValidTypeForStoreFltAsInt) 13061 return SDValue(); 13062 13063 // Extend f32 values to f64 13064 if (ResVT.getScalarSizeInBits() == 32) { 13065 Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val); 13066 DCI.AddToWorklist(Val.getNode()); 13067 } 13068 13069 // Set signed or unsigned conversion opcode. 13070 unsigned ConvOpcode = (Opcode == ISD::FP_TO_SINT) ? 13071 PPCISD::FP_TO_SINT_IN_VSR : 13072 PPCISD::FP_TO_UINT_IN_VSR; 13073 13074 Val = DAG.getNode(ConvOpcode, 13075 dl, ResVT == MVT::f128 ? MVT::f128 : MVT::f64, Val); 13076 DCI.AddToWorklist(Val.getNode()); 13077 13078 // Set number of bytes being converted. 13079 unsigned ByteSize = Op1VT.getScalarSizeInBits() / 8; 13080 SDValue Ops[] = { N->getOperand(0), Val, N->getOperand(2), 13081 DAG.getIntPtrConstant(ByteSize, dl, false), 13082 DAG.getValueType(Op1VT) }; 13083 13084 Val = DAG.getMemIntrinsicNode(PPCISD::ST_VSR_SCAL_INT, dl, 13085 DAG.getVTList(MVT::Other), Ops, 13086 cast<StoreSDNode>(N)->getMemoryVT(), 13087 cast<StoreSDNode>(N)->getMemOperand()); 13088 13089 DCI.AddToWorklist(Val.getNode()); 13090 return Val; 13091 } 13092 13093 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N, 13094 DAGCombinerInfo &DCI) const { 13095 SelectionDAG &DAG = DCI.DAG; 13096 SDLoc dl(N); 13097 switch (N->getOpcode()) { 13098 default: break; 13099 case ISD::ADD: 13100 return combineADD(N, DCI); 13101 case ISD::SHL: 13102 return combineSHL(N, DCI); 13103 case ISD::SRA: 13104 return combineSRA(N, DCI); 13105 case ISD::SRL: 13106 return combineSRL(N, DCI); 13107 case ISD::MUL: 13108 return combineMUL(N, DCI); 13109 case PPCISD::SHL: 13110 if (isNullConstant(N->getOperand(0))) // 0 << V -> 0. 13111 return N->getOperand(0); 13112 break; 13113 case PPCISD::SRL: 13114 if (isNullConstant(N->getOperand(0))) // 0 >>u V -> 0. 13115 return N->getOperand(0); 13116 break; 13117 case PPCISD::SRA: 13118 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) { 13119 if (C->isNullValue() || // 0 >>s V -> 0. 13120 C->isAllOnesValue()) // -1 >>s V -> -1. 13121 return N->getOperand(0); 13122 } 13123 break; 13124 case ISD::SIGN_EXTEND: 13125 case ISD::ZERO_EXTEND: 13126 case ISD::ANY_EXTEND: 13127 return DAGCombineExtBoolTrunc(N, DCI); 13128 case ISD::TRUNCATE: 13129 return combineTRUNCATE(N, DCI); 13130 case ISD::SETCC: 13131 if (SDValue CSCC = combineSetCC(N, DCI)) 13132 return CSCC; 13133 LLVM_FALLTHROUGH; 13134 case ISD::SELECT_CC: 13135 return DAGCombineTruncBoolExt(N, DCI); 13136 case ISD::SINT_TO_FP: 13137 case ISD::UINT_TO_FP: 13138 return combineFPToIntToFP(N, DCI); 13139 case ISD::STORE: { 13140 13141 EVT Op1VT = N->getOperand(1).getValueType(); 13142 unsigned Opcode = N->getOperand(1).getOpcode(); 13143 13144 if (Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT) { 13145 SDValue Val= combineStoreFPToInt(N, DCI); 13146 if (Val) 13147 return Val; 13148 } 13149 13150 // Turn STORE (BSWAP) -> sthbrx/stwbrx. 13151 if (cast<StoreSDNode>(N)->isUnindexed() && Opcode == ISD::BSWAP && 13152 N->getOperand(1).getNode()->hasOneUse() && 13153 (Op1VT == MVT::i32 || Op1VT == MVT::i16 || 13154 (Subtarget.hasLDBRX() && Subtarget.isPPC64() && Op1VT == MVT::i64))) { 13155 13156 // STBRX can only handle simple types and it makes no sense to store less 13157 // two bytes in byte-reversed order. 13158 EVT mVT = cast<StoreSDNode>(N)->getMemoryVT(); 13159 if (mVT.isExtended() || mVT.getSizeInBits() < 16) 13160 break; 13161 13162 SDValue BSwapOp = N->getOperand(1).getOperand(0); 13163 // Do an any-extend to 32-bits if this is a half-word input. 13164 if (BSwapOp.getValueType() == MVT::i16) 13165 BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp); 13166 13167 // If the type of BSWAP operand is wider than stored memory width 13168 // it need to be shifted to the right side before STBRX. 13169 if (Op1VT.bitsGT(mVT)) { 13170 int Shift = Op1VT.getSizeInBits() - mVT.getSizeInBits(); 13171 BSwapOp = DAG.getNode(ISD::SRL, dl, Op1VT, BSwapOp, 13172 DAG.getConstant(Shift, dl, MVT::i32)); 13173 // Need to truncate if this is a bswap of i64 stored as i32/i16. 13174 if (Op1VT == MVT::i64) 13175 BSwapOp = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BSwapOp); 13176 } 13177 13178 SDValue Ops[] = { 13179 N->getOperand(0), BSwapOp, N->getOperand(2), DAG.getValueType(mVT) 13180 }; 13181 return 13182 DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other), 13183 Ops, cast<StoreSDNode>(N)->getMemoryVT(), 13184 cast<StoreSDNode>(N)->getMemOperand()); 13185 } 13186 13187 // STORE Constant:i32<0> -> STORE<trunc to i32> Constant:i64<0> 13188 // So it can increase the chance of CSE constant construction. 13189 if (Subtarget.isPPC64() && !DCI.isBeforeLegalize() && 13190 isa<ConstantSDNode>(N->getOperand(1)) && Op1VT == MVT::i32) { 13191 // Need to sign-extended to 64-bits to handle negative values. 13192 EVT MemVT = cast<StoreSDNode>(N)->getMemoryVT(); 13193 uint64_t Val64 = SignExtend64(N->getConstantOperandVal(1), 13194 MemVT.getSizeInBits()); 13195 SDValue Const64 = DAG.getConstant(Val64, dl, MVT::i64); 13196 13197 // DAG.getTruncStore() can't be used here because it doesn't accept 13198 // the general (base + offset) addressing mode. 13199 // So we use UpdateNodeOperands and setTruncatingStore instead. 13200 DAG.UpdateNodeOperands(N, N->getOperand(0), Const64, N->getOperand(2), 13201 N->getOperand(3)); 13202 cast<StoreSDNode>(N)->setTruncatingStore(true); 13203 return SDValue(N, 0); 13204 } 13205 13206 // For little endian, VSX stores require generating xxswapd/lxvd2x. 13207 // Not needed on ISA 3.0 based CPUs since we have a non-permuting store. 13208 if (Op1VT.isSimple()) { 13209 MVT StoreVT = Op1VT.getSimpleVT(); 13210 if (Subtarget.needsSwapsForVSXMemOps() && 13211 (StoreVT == MVT::v2f64 || StoreVT == MVT::v2i64 || 13212 StoreVT == MVT::v4f32 || StoreVT == MVT::v4i32)) 13213 return expandVSXStoreForLE(N, DCI); 13214 } 13215 break; 13216 } 13217 case ISD::LOAD: { 13218 LoadSDNode *LD = cast<LoadSDNode>(N); 13219 EVT VT = LD->getValueType(0); 13220 13221 // For little endian, VSX loads require generating lxvd2x/xxswapd. 13222 // Not needed on ISA 3.0 based CPUs since we have a non-permuting load. 13223 if (VT.isSimple()) { 13224 MVT LoadVT = VT.getSimpleVT(); 13225 if (Subtarget.needsSwapsForVSXMemOps() && 13226 (LoadVT == MVT::v2f64 || LoadVT == MVT::v2i64 || 13227 LoadVT == MVT::v4f32 || LoadVT == MVT::v4i32)) 13228 return expandVSXLoadForLE(N, DCI); 13229 } 13230 13231 // We sometimes end up with a 64-bit integer load, from which we extract 13232 // two single-precision floating-point numbers. This happens with 13233 // std::complex<float>, and other similar structures, because of the way we 13234 // canonicalize structure copies. However, if we lack direct moves, 13235 // then the final bitcasts from the extracted integer values to the 13236 // floating-point numbers turn into store/load pairs. Even with direct moves, 13237 // just loading the two floating-point numbers is likely better. 13238 auto ReplaceTwoFloatLoad = [&]() { 13239 if (VT != MVT::i64) 13240 return false; 13241 13242 if (LD->getExtensionType() != ISD::NON_EXTLOAD || 13243 LD->isVolatile()) 13244 return false; 13245 13246 // We're looking for a sequence like this: 13247 // t13: i64,ch = load<LD8[%ref.tmp]> t0, t6, undef:i64 13248 // t16: i64 = srl t13, Constant:i32<32> 13249 // t17: i32 = truncate t16 13250 // t18: f32 = bitcast t17 13251 // t19: i32 = truncate t13 13252 // t20: f32 = bitcast t19 13253 13254 if (!LD->hasNUsesOfValue(2, 0)) 13255 return false; 13256 13257 auto UI = LD->use_begin(); 13258 while (UI.getUse().getResNo() != 0) ++UI; 13259 SDNode *Trunc = *UI++; 13260 while (UI.getUse().getResNo() != 0) ++UI; 13261 SDNode *RightShift = *UI; 13262 if (Trunc->getOpcode() != ISD::TRUNCATE) 13263 std::swap(Trunc, RightShift); 13264 13265 if (Trunc->getOpcode() != ISD::TRUNCATE || 13266 Trunc->getValueType(0) != MVT::i32 || 13267 !Trunc->hasOneUse()) 13268 return false; 13269 if (RightShift->getOpcode() != ISD::SRL || 13270 !isa<ConstantSDNode>(RightShift->getOperand(1)) || 13271 RightShift->getConstantOperandVal(1) != 32 || 13272 !RightShift->hasOneUse()) 13273 return false; 13274 13275 SDNode *Trunc2 = *RightShift->use_begin(); 13276 if (Trunc2->getOpcode() != ISD::TRUNCATE || 13277 Trunc2->getValueType(0) != MVT::i32 || 13278 !Trunc2->hasOneUse()) 13279 return false; 13280 13281 SDNode *Bitcast = *Trunc->use_begin(); 13282 SDNode *Bitcast2 = *Trunc2->use_begin(); 13283 13284 if (Bitcast->getOpcode() != ISD::BITCAST || 13285 Bitcast->getValueType(0) != MVT::f32) 13286 return false; 13287 if (Bitcast2->getOpcode() != ISD::BITCAST || 13288 Bitcast2->getValueType(0) != MVT::f32) 13289 return false; 13290 13291 if (Subtarget.isLittleEndian()) 13292 std::swap(Bitcast, Bitcast2); 13293 13294 // Bitcast has the second float (in memory-layout order) and Bitcast2 13295 // has the first one. 13296 13297 SDValue BasePtr = LD->getBasePtr(); 13298 if (LD->isIndexed()) { 13299 assert(LD->getAddressingMode() == ISD::PRE_INC && 13300 "Non-pre-inc AM on PPC?"); 13301 BasePtr = 13302 DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, 13303 LD->getOffset()); 13304 } 13305 13306 auto MMOFlags = 13307 LD->getMemOperand()->getFlags() & ~MachineMemOperand::MOVolatile; 13308 SDValue FloatLoad = DAG.getLoad(MVT::f32, dl, LD->getChain(), BasePtr, 13309 LD->getPointerInfo(), LD->getAlignment(), 13310 MMOFlags, LD->getAAInfo()); 13311 SDValue AddPtr = 13312 DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), 13313 BasePtr, DAG.getIntPtrConstant(4, dl)); 13314 SDValue FloatLoad2 = DAG.getLoad( 13315 MVT::f32, dl, SDValue(FloatLoad.getNode(), 1), AddPtr, 13316 LD->getPointerInfo().getWithOffset(4), 13317 MinAlign(LD->getAlignment(), 4), MMOFlags, LD->getAAInfo()); 13318 13319 if (LD->isIndexed()) { 13320 // Note that DAGCombine should re-form any pre-increment load(s) from 13321 // what is produced here if that makes sense. 13322 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), BasePtr); 13323 } 13324 13325 DCI.CombineTo(Bitcast2, FloatLoad); 13326 DCI.CombineTo(Bitcast, FloatLoad2); 13327 13328 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, LD->isIndexed() ? 2 : 1), 13329 SDValue(FloatLoad2.getNode(), 1)); 13330 return true; 13331 }; 13332 13333 if (ReplaceTwoFloatLoad()) 13334 return SDValue(N, 0); 13335 13336 EVT MemVT = LD->getMemoryVT(); 13337 Type *Ty = MemVT.getTypeForEVT(*DAG.getContext()); 13338 unsigned ABIAlignment = DAG.getDataLayout().getABITypeAlignment(Ty); 13339 Type *STy = MemVT.getScalarType().getTypeForEVT(*DAG.getContext()); 13340 unsigned ScalarABIAlignment = DAG.getDataLayout().getABITypeAlignment(STy); 13341 if (LD->isUnindexed() && VT.isVector() && 13342 ((Subtarget.hasAltivec() && ISD::isNON_EXTLoad(N) && 13343 // P8 and later hardware should just use LOAD. 13344 !Subtarget.hasP8Vector() && (VT == MVT::v16i8 || VT == MVT::v8i16 || 13345 VT == MVT::v4i32 || VT == MVT::v4f32)) || 13346 (Subtarget.hasQPX() && (VT == MVT::v4f64 || VT == MVT::v4f32) && 13347 LD->getAlignment() >= ScalarABIAlignment)) && 13348 LD->getAlignment() < ABIAlignment) { 13349 // This is a type-legal unaligned Altivec or QPX load. 13350 SDValue Chain = LD->getChain(); 13351 SDValue Ptr = LD->getBasePtr(); 13352 bool isLittleEndian = Subtarget.isLittleEndian(); 13353 13354 // This implements the loading of unaligned vectors as described in 13355 // the venerable Apple Velocity Engine overview. Specifically: 13356 // https://developer.apple.com/hardwaredrivers/ve/alignment.html 13357 // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html 13358 // 13359 // The general idea is to expand a sequence of one or more unaligned 13360 // loads into an alignment-based permutation-control instruction (lvsl 13361 // or lvsr), a series of regular vector loads (which always truncate 13362 // their input address to an aligned address), and a series of 13363 // permutations. The results of these permutations are the requested 13364 // loaded values. The trick is that the last "extra" load is not taken 13365 // from the address you might suspect (sizeof(vector) bytes after the 13366 // last requested load), but rather sizeof(vector) - 1 bytes after the 13367 // last requested vector. The point of this is to avoid a page fault if 13368 // the base address happened to be aligned. This works because if the 13369 // base address is aligned, then adding less than a full vector length 13370 // will cause the last vector in the sequence to be (re)loaded. 13371 // Otherwise, the next vector will be fetched as you might suspect was 13372 // necessary. 13373 13374 // We might be able to reuse the permutation generation from 13375 // a different base address offset from this one by an aligned amount. 13376 // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this 13377 // optimization later. 13378 Intrinsic::ID Intr, IntrLD, IntrPerm; 13379 MVT PermCntlTy, PermTy, LDTy; 13380 if (Subtarget.hasAltivec()) { 13381 Intr = isLittleEndian ? Intrinsic::ppc_altivec_lvsr : 13382 Intrinsic::ppc_altivec_lvsl; 13383 IntrLD = Intrinsic::ppc_altivec_lvx; 13384 IntrPerm = Intrinsic::ppc_altivec_vperm; 13385 PermCntlTy = MVT::v16i8; 13386 PermTy = MVT::v4i32; 13387 LDTy = MVT::v4i32; 13388 } else { 13389 Intr = MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlpcld : 13390 Intrinsic::ppc_qpx_qvlpcls; 13391 IntrLD = MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlfd : 13392 Intrinsic::ppc_qpx_qvlfs; 13393 IntrPerm = Intrinsic::ppc_qpx_qvfperm; 13394 PermCntlTy = MVT::v4f64; 13395 PermTy = MVT::v4f64; 13396 LDTy = MemVT.getSimpleVT(); 13397 } 13398 13399 SDValue PermCntl = BuildIntrinsicOp(Intr, Ptr, DAG, dl, PermCntlTy); 13400 13401 // Create the new MMO for the new base load. It is like the original MMO, 13402 // but represents an area in memory almost twice the vector size centered 13403 // on the original address. If the address is unaligned, we might start 13404 // reading up to (sizeof(vector)-1) bytes below the address of the 13405 // original unaligned load. 13406 MachineFunction &MF = DAG.getMachineFunction(); 13407 MachineMemOperand *BaseMMO = 13408 MF.getMachineMemOperand(LD->getMemOperand(), 13409 -(long)MemVT.getStoreSize()+1, 13410 2*MemVT.getStoreSize()-1); 13411 13412 // Create the new base load. 13413 SDValue LDXIntID = 13414 DAG.getTargetConstant(IntrLD, dl, getPointerTy(MF.getDataLayout())); 13415 SDValue BaseLoadOps[] = { Chain, LDXIntID, Ptr }; 13416 SDValue BaseLoad = 13417 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl, 13418 DAG.getVTList(PermTy, MVT::Other), 13419 BaseLoadOps, LDTy, BaseMMO); 13420 13421 // Note that the value of IncOffset (which is provided to the next 13422 // load's pointer info offset value, and thus used to calculate the 13423 // alignment), and the value of IncValue (which is actually used to 13424 // increment the pointer value) are different! This is because we 13425 // require the next load to appear to be aligned, even though it 13426 // is actually offset from the base pointer by a lesser amount. 13427 int IncOffset = VT.getSizeInBits() / 8; 13428 int IncValue = IncOffset; 13429 13430 // Walk (both up and down) the chain looking for another load at the real 13431 // (aligned) offset (the alignment of the other load does not matter in 13432 // this case). If found, then do not use the offset reduction trick, as 13433 // that will prevent the loads from being later combined (as they would 13434 // otherwise be duplicates). 13435 if (!findConsecutiveLoad(LD, DAG)) 13436 --IncValue; 13437 13438 SDValue Increment = 13439 DAG.getConstant(IncValue, dl, getPointerTy(MF.getDataLayout())); 13440 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment); 13441 13442 MachineMemOperand *ExtraMMO = 13443 MF.getMachineMemOperand(LD->getMemOperand(), 13444 1, 2*MemVT.getStoreSize()-1); 13445 SDValue ExtraLoadOps[] = { Chain, LDXIntID, Ptr }; 13446 SDValue ExtraLoad = 13447 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl, 13448 DAG.getVTList(PermTy, MVT::Other), 13449 ExtraLoadOps, LDTy, ExtraMMO); 13450 13451 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 13452 BaseLoad.getValue(1), ExtraLoad.getValue(1)); 13453 13454 // Because vperm has a big-endian bias, we must reverse the order 13455 // of the input vectors and complement the permute control vector 13456 // when generating little endian code. We have already handled the 13457 // latter by using lvsr instead of lvsl, so just reverse BaseLoad 13458 // and ExtraLoad here. 13459 SDValue Perm; 13460 if (isLittleEndian) 13461 Perm = BuildIntrinsicOp(IntrPerm, 13462 ExtraLoad, BaseLoad, PermCntl, DAG, dl); 13463 else 13464 Perm = BuildIntrinsicOp(IntrPerm, 13465 BaseLoad, ExtraLoad, PermCntl, DAG, dl); 13466 13467 if (VT != PermTy) 13468 Perm = Subtarget.hasAltivec() ? 13469 DAG.getNode(ISD::BITCAST, dl, VT, Perm) : 13470 DAG.getNode(ISD::FP_ROUND, dl, VT, Perm, // QPX 13471 DAG.getTargetConstant(1, dl, MVT::i64)); 13472 // second argument is 1 because this rounding 13473 // is always exact. 13474 13475 // The output of the permutation is our loaded result, the TokenFactor is 13476 // our new chain. 13477 DCI.CombineTo(N, Perm, TF); 13478 return SDValue(N, 0); 13479 } 13480 } 13481 break; 13482 case ISD::INTRINSIC_WO_CHAIN: { 13483 bool isLittleEndian = Subtarget.isLittleEndian(); 13484 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 13485 Intrinsic::ID Intr = (isLittleEndian ? Intrinsic::ppc_altivec_lvsr 13486 : Intrinsic::ppc_altivec_lvsl); 13487 if ((IID == Intr || 13488 IID == Intrinsic::ppc_qpx_qvlpcld || 13489 IID == Intrinsic::ppc_qpx_qvlpcls) && 13490 N->getOperand(1)->getOpcode() == ISD::ADD) { 13491 SDValue Add = N->getOperand(1); 13492 13493 int Bits = IID == Intrinsic::ppc_qpx_qvlpcld ? 13494 5 /* 32 byte alignment */ : 4 /* 16 byte alignment */; 13495 13496 if (DAG.MaskedValueIsZero(Add->getOperand(1), 13497 APInt::getAllOnesValue(Bits /* alignment */) 13498 .zext(Add.getScalarValueSizeInBits()))) { 13499 SDNode *BasePtr = Add->getOperand(0).getNode(); 13500 for (SDNode::use_iterator UI = BasePtr->use_begin(), 13501 UE = BasePtr->use_end(); 13502 UI != UE; ++UI) { 13503 if (UI->getOpcode() == ISD::INTRINSIC_WO_CHAIN && 13504 cast<ConstantSDNode>(UI->getOperand(0))->getZExtValue() == IID) { 13505 // We've found another LVSL/LVSR, and this address is an aligned 13506 // multiple of that one. The results will be the same, so use the 13507 // one we've just found instead. 13508 13509 return SDValue(*UI, 0); 13510 } 13511 } 13512 } 13513 13514 if (isa<ConstantSDNode>(Add->getOperand(1))) { 13515 SDNode *BasePtr = Add->getOperand(0).getNode(); 13516 for (SDNode::use_iterator UI = BasePtr->use_begin(), 13517 UE = BasePtr->use_end(); UI != UE; ++UI) { 13518 if (UI->getOpcode() == ISD::ADD && 13519 isa<ConstantSDNode>(UI->getOperand(1)) && 13520 (cast<ConstantSDNode>(Add->getOperand(1))->getZExtValue() - 13521 cast<ConstantSDNode>(UI->getOperand(1))->getZExtValue()) % 13522 (1ULL << Bits) == 0) { 13523 SDNode *OtherAdd = *UI; 13524 for (SDNode::use_iterator VI = OtherAdd->use_begin(), 13525 VE = OtherAdd->use_end(); VI != VE; ++VI) { 13526 if (VI->getOpcode() == ISD::INTRINSIC_WO_CHAIN && 13527 cast<ConstantSDNode>(VI->getOperand(0))->getZExtValue() == IID) { 13528 return SDValue(*VI, 0); 13529 } 13530 } 13531 } 13532 } 13533 } 13534 } 13535 13536 // Combine vmaxsw/h/b(a, a's negation) to abs(a) 13537 // Expose the vabsduw/h/b opportunity for down stream 13538 if (!DCI.isAfterLegalizeDAG() && Subtarget.hasP9Altivec() && 13539 (IID == Intrinsic::ppc_altivec_vmaxsw || 13540 IID == Intrinsic::ppc_altivec_vmaxsh || 13541 IID == Intrinsic::ppc_altivec_vmaxsb)) { 13542 SDValue V1 = N->getOperand(1); 13543 SDValue V2 = N->getOperand(2); 13544 if ((V1.getSimpleValueType() == MVT::v4i32 || 13545 V1.getSimpleValueType() == MVT::v8i16 || 13546 V1.getSimpleValueType() == MVT::v16i8) && 13547 V1.getSimpleValueType() == V2.getSimpleValueType()) { 13548 // (0-a, a) 13549 if (V1.getOpcode() == ISD::SUB && 13550 ISD::isBuildVectorAllZeros(V1.getOperand(0).getNode()) && 13551 V1.getOperand(1) == V2) { 13552 return DAG.getNode(ISD::ABS, dl, V2.getValueType(), V2); 13553 } 13554 // (a, 0-a) 13555 if (V2.getOpcode() == ISD::SUB && 13556 ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()) && 13557 V2.getOperand(1) == V1) { 13558 return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1); 13559 } 13560 // (x-y, y-x) 13561 if (V1.getOpcode() == ISD::SUB && V2.getOpcode() == ISD::SUB && 13562 V1.getOperand(0) == V2.getOperand(1) && 13563 V1.getOperand(1) == V2.getOperand(0)) { 13564 return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1); 13565 } 13566 } 13567 } 13568 } 13569 13570 break; 13571 case ISD::INTRINSIC_W_CHAIN: 13572 // For little endian, VSX loads require generating lxvd2x/xxswapd. 13573 // Not needed on ISA 3.0 based CPUs since we have a non-permuting load. 13574 if (Subtarget.needsSwapsForVSXMemOps()) { 13575 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 13576 default: 13577 break; 13578 case Intrinsic::ppc_vsx_lxvw4x: 13579 case Intrinsic::ppc_vsx_lxvd2x: 13580 return expandVSXLoadForLE(N, DCI); 13581 } 13582 } 13583 break; 13584 case ISD::INTRINSIC_VOID: 13585 // For little endian, VSX stores require generating xxswapd/stxvd2x. 13586 // Not needed on ISA 3.0 based CPUs since we have a non-permuting store. 13587 if (Subtarget.needsSwapsForVSXMemOps()) { 13588 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 13589 default: 13590 break; 13591 case Intrinsic::ppc_vsx_stxvw4x: 13592 case Intrinsic::ppc_vsx_stxvd2x: 13593 return expandVSXStoreForLE(N, DCI); 13594 } 13595 } 13596 break; 13597 case ISD::BSWAP: 13598 // Turn BSWAP (LOAD) -> lhbrx/lwbrx. 13599 if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) && 13600 N->getOperand(0).hasOneUse() && 13601 (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 || 13602 (Subtarget.hasLDBRX() && Subtarget.isPPC64() && 13603 N->getValueType(0) == MVT::i64))) { 13604 SDValue Load = N->getOperand(0); 13605 LoadSDNode *LD = cast<LoadSDNode>(Load); 13606 // Create the byte-swapping load. 13607 SDValue Ops[] = { 13608 LD->getChain(), // Chain 13609 LD->getBasePtr(), // Ptr 13610 DAG.getValueType(N->getValueType(0)) // VT 13611 }; 13612 SDValue BSLoad = 13613 DAG.getMemIntrinsicNode(PPCISD::LBRX, dl, 13614 DAG.getVTList(N->getValueType(0) == MVT::i64 ? 13615 MVT::i64 : MVT::i32, MVT::Other), 13616 Ops, LD->getMemoryVT(), LD->getMemOperand()); 13617 13618 // If this is an i16 load, insert the truncate. 13619 SDValue ResVal = BSLoad; 13620 if (N->getValueType(0) == MVT::i16) 13621 ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad); 13622 13623 // First, combine the bswap away. This makes the value produced by the 13624 // load dead. 13625 DCI.CombineTo(N, ResVal); 13626 13627 // Next, combine the load away, we give it a bogus result value but a real 13628 // chain result. The result value is dead because the bswap is dead. 13629 DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1)); 13630 13631 // Return N so it doesn't get rechecked! 13632 return SDValue(N, 0); 13633 } 13634 break; 13635 case PPCISD::VCMP: 13636 // If a VCMPo node already exists with exactly the same operands as this 13637 // node, use its result instead of this node (VCMPo computes both a CR6 and 13638 // a normal output). 13639 // 13640 if (!N->getOperand(0).hasOneUse() && 13641 !N->getOperand(1).hasOneUse() && 13642 !N->getOperand(2).hasOneUse()) { 13643 13644 // Scan all of the users of the LHS, looking for VCMPo's that match. 13645 SDNode *VCMPoNode = nullptr; 13646 13647 SDNode *LHSN = N->getOperand(0).getNode(); 13648 for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end(); 13649 UI != E; ++UI) 13650 if (UI->getOpcode() == PPCISD::VCMPo && 13651 UI->getOperand(1) == N->getOperand(1) && 13652 UI->getOperand(2) == N->getOperand(2) && 13653 UI->getOperand(0) == N->getOperand(0)) { 13654 VCMPoNode = *UI; 13655 break; 13656 } 13657 13658 // If there is no VCMPo node, or if the flag value has a single use, don't 13659 // transform this. 13660 if (!VCMPoNode || VCMPoNode->hasNUsesOfValue(0, 1)) 13661 break; 13662 13663 // Look at the (necessarily single) use of the flag value. If it has a 13664 // chain, this transformation is more complex. Note that multiple things 13665 // could use the value result, which we should ignore. 13666 SDNode *FlagUser = nullptr; 13667 for (SDNode::use_iterator UI = VCMPoNode->use_begin(); 13668 FlagUser == nullptr; ++UI) { 13669 assert(UI != VCMPoNode->use_end() && "Didn't find user!"); 13670 SDNode *User = *UI; 13671 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) { 13672 if (User->getOperand(i) == SDValue(VCMPoNode, 1)) { 13673 FlagUser = User; 13674 break; 13675 } 13676 } 13677 } 13678 13679 // If the user is a MFOCRF instruction, we know this is safe. 13680 // Otherwise we give up for right now. 13681 if (FlagUser->getOpcode() == PPCISD::MFOCRF) 13682 return SDValue(VCMPoNode, 0); 13683 } 13684 break; 13685 case ISD::BRCOND: { 13686 SDValue Cond = N->getOperand(1); 13687 SDValue Target = N->getOperand(2); 13688 13689 if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN && 13690 cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() == 13691 Intrinsic::loop_decrement) { 13692 13693 // We now need to make the intrinsic dead (it cannot be instruction 13694 // selected). 13695 DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0)); 13696 assert(Cond.getNode()->hasOneUse() && 13697 "Counter decrement has more than one use"); 13698 13699 return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other, 13700 N->getOperand(0), Target); 13701 } 13702 } 13703 break; 13704 case ISD::BR_CC: { 13705 // If this is a branch on an altivec predicate comparison, lower this so 13706 // that we don't have to do a MFOCRF: instead, branch directly on CR6. This 13707 // lowering is done pre-legalize, because the legalizer lowers the predicate 13708 // compare down to code that is difficult to reassemble. 13709 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get(); 13710 SDValue LHS = N->getOperand(2), RHS = N->getOperand(3); 13711 13712 // Sometimes the promoted value of the intrinsic is ANDed by some non-zero 13713 // value. If so, pass-through the AND to get to the intrinsic. 13714 if (LHS.getOpcode() == ISD::AND && 13715 LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN && 13716 cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() == 13717 Intrinsic::loop_decrement && 13718 isa<ConstantSDNode>(LHS.getOperand(1)) && 13719 !isNullConstant(LHS.getOperand(1))) 13720 LHS = LHS.getOperand(0); 13721 13722 if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN && 13723 cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() == 13724 Intrinsic::loop_decrement && 13725 isa<ConstantSDNode>(RHS)) { 13726 assert((CC == ISD::SETEQ || CC == ISD::SETNE) && 13727 "Counter decrement comparison is not EQ or NE"); 13728 13729 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue(); 13730 bool isBDNZ = (CC == ISD::SETEQ && Val) || 13731 (CC == ISD::SETNE && !Val); 13732 13733 // We now need to make the intrinsic dead (it cannot be instruction 13734 // selected). 13735 DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0)); 13736 assert(LHS.getNode()->hasOneUse() && 13737 "Counter decrement has more than one use"); 13738 13739 return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other, 13740 N->getOperand(0), N->getOperand(4)); 13741 } 13742 13743 int CompareOpc; 13744 bool isDot; 13745 13746 if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN && 13747 isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) && 13748 getVectorCompareInfo(LHS, CompareOpc, isDot, Subtarget)) { 13749 assert(isDot && "Can't compare against a vector result!"); 13750 13751 // If this is a comparison against something other than 0/1, then we know 13752 // that the condition is never/always true. 13753 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue(); 13754 if (Val != 0 && Val != 1) { 13755 if (CC == ISD::SETEQ) // Cond never true, remove branch. 13756 return N->getOperand(0); 13757 // Always !=, turn it into an unconditional branch. 13758 return DAG.getNode(ISD::BR, dl, MVT::Other, 13759 N->getOperand(0), N->getOperand(4)); 13760 } 13761 13762 bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0); 13763 13764 // Create the PPCISD altivec 'dot' comparison node. 13765 SDValue Ops[] = { 13766 LHS.getOperand(2), // LHS of compare 13767 LHS.getOperand(3), // RHS of compare 13768 DAG.getConstant(CompareOpc, dl, MVT::i32) 13769 }; 13770 EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue }; 13771 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops); 13772 13773 // Unpack the result based on how the target uses it. 13774 PPC::Predicate CompOpc; 13775 switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) { 13776 default: // Can't happen, don't crash on invalid number though. 13777 case 0: // Branch on the value of the EQ bit of CR6. 13778 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE; 13779 break; 13780 case 1: // Branch on the inverted value of the EQ bit of CR6. 13781 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ; 13782 break; 13783 case 2: // Branch on the value of the LT bit of CR6. 13784 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE; 13785 break; 13786 case 3: // Branch on the inverted value of the LT bit of CR6. 13787 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT; 13788 break; 13789 } 13790 13791 return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0), 13792 DAG.getConstant(CompOpc, dl, MVT::i32), 13793 DAG.getRegister(PPC::CR6, MVT::i32), 13794 N->getOperand(4), CompNode.getValue(1)); 13795 } 13796 break; 13797 } 13798 case ISD::BUILD_VECTOR: 13799 return DAGCombineBuildVector(N, DCI); 13800 case ISD::ABS: 13801 return combineABS(N, DCI); 13802 case ISD::VSELECT: 13803 return combineVSelect(N, DCI); 13804 } 13805 13806 return SDValue(); 13807 } 13808 13809 SDValue 13810 PPCTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor, 13811 SelectionDAG &DAG, 13812 SmallVectorImpl<SDNode *> &Created) const { 13813 // fold (sdiv X, pow2) 13814 EVT VT = N->getValueType(0); 13815 if (VT == MVT::i64 && !Subtarget.isPPC64()) 13816 return SDValue(); 13817 if ((VT != MVT::i32 && VT != MVT::i64) || 13818 !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2())) 13819 return SDValue(); 13820 13821 SDLoc DL(N); 13822 SDValue N0 = N->getOperand(0); 13823 13824 bool IsNegPow2 = (-Divisor).isPowerOf2(); 13825 unsigned Lg2 = (IsNegPow2 ? -Divisor : Divisor).countTrailingZeros(); 13826 SDValue ShiftAmt = DAG.getConstant(Lg2, DL, VT); 13827 13828 SDValue Op = DAG.getNode(PPCISD::SRA_ADDZE, DL, VT, N0, ShiftAmt); 13829 Created.push_back(Op.getNode()); 13830 13831 if (IsNegPow2) { 13832 Op = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Op); 13833 Created.push_back(Op.getNode()); 13834 } 13835 13836 return Op; 13837 } 13838 13839 //===----------------------------------------------------------------------===// 13840 // Inline Assembly Support 13841 //===----------------------------------------------------------------------===// 13842 13843 void PPCTargetLowering::computeKnownBitsForTargetNode(const SDValue Op, 13844 KnownBits &Known, 13845 const APInt &DemandedElts, 13846 const SelectionDAG &DAG, 13847 unsigned Depth) const { 13848 Known.resetAll(); 13849 switch (Op.getOpcode()) { 13850 default: break; 13851 case PPCISD::LBRX: { 13852 // lhbrx is known to have the top bits cleared out. 13853 if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16) 13854 Known.Zero = 0xFFFF0000; 13855 break; 13856 } 13857 case ISD::INTRINSIC_WO_CHAIN: { 13858 switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) { 13859 default: break; 13860 case Intrinsic::ppc_altivec_vcmpbfp_p: 13861 case Intrinsic::ppc_altivec_vcmpeqfp_p: 13862 case Intrinsic::ppc_altivec_vcmpequb_p: 13863 case Intrinsic::ppc_altivec_vcmpequh_p: 13864 case Intrinsic::ppc_altivec_vcmpequw_p: 13865 case Intrinsic::ppc_altivec_vcmpequd_p: 13866 case Intrinsic::ppc_altivec_vcmpgefp_p: 13867 case Intrinsic::ppc_altivec_vcmpgtfp_p: 13868 case Intrinsic::ppc_altivec_vcmpgtsb_p: 13869 case Intrinsic::ppc_altivec_vcmpgtsh_p: 13870 case Intrinsic::ppc_altivec_vcmpgtsw_p: 13871 case Intrinsic::ppc_altivec_vcmpgtsd_p: 13872 case Intrinsic::ppc_altivec_vcmpgtub_p: 13873 case Intrinsic::ppc_altivec_vcmpgtuh_p: 13874 case Intrinsic::ppc_altivec_vcmpgtuw_p: 13875 case Intrinsic::ppc_altivec_vcmpgtud_p: 13876 Known.Zero = ~1U; // All bits but the low one are known to be zero. 13877 break; 13878 } 13879 } 13880 } 13881 } 13882 13883 unsigned PPCTargetLowering::getPrefLoopAlignment(MachineLoop *ML) const { 13884 switch (Subtarget.getDarwinDirective()) { 13885 default: break; 13886 case PPC::DIR_970: 13887 case PPC::DIR_PWR4: 13888 case PPC::DIR_PWR5: 13889 case PPC::DIR_PWR5X: 13890 case PPC::DIR_PWR6: 13891 case PPC::DIR_PWR6X: 13892 case PPC::DIR_PWR7: 13893 case PPC::DIR_PWR8: 13894 case PPC::DIR_PWR9: { 13895 if (!ML) 13896 break; 13897 13898 if (!DisableInnermostLoopAlign32) { 13899 // If the nested loop is an innermost loop, prefer to a 32-byte alignment, 13900 // so that we can decrease cache misses and branch-prediction misses. 13901 // Actual alignment of the loop will depend on the hotness check and other 13902 // logic in alignBlocks. 13903 if (ML->getLoopDepth() > 1 && ML->getSubLoops().empty()) 13904 return 5; 13905 } 13906 13907 const PPCInstrInfo *TII = Subtarget.getInstrInfo(); 13908 13909 // For small loops (between 5 and 8 instructions), align to a 32-byte 13910 // boundary so that the entire loop fits in one instruction-cache line. 13911 uint64_t LoopSize = 0; 13912 for (auto I = ML->block_begin(), IE = ML->block_end(); I != IE; ++I) 13913 for (auto J = (*I)->begin(), JE = (*I)->end(); J != JE; ++J) { 13914 LoopSize += TII->getInstSizeInBytes(*J); 13915 if (LoopSize > 32) 13916 break; 13917 } 13918 13919 if (LoopSize > 16 && LoopSize <= 32) 13920 return 5; 13921 13922 break; 13923 } 13924 } 13925 13926 return TargetLowering::getPrefLoopAlignment(ML); 13927 } 13928 13929 /// getConstraintType - Given a constraint, return the type of 13930 /// constraint it is for this target. 13931 PPCTargetLowering::ConstraintType 13932 PPCTargetLowering::getConstraintType(StringRef Constraint) const { 13933 if (Constraint.size() == 1) { 13934 switch (Constraint[0]) { 13935 default: break; 13936 case 'b': 13937 case 'r': 13938 case 'f': 13939 case 'd': 13940 case 'v': 13941 case 'y': 13942 return C_RegisterClass; 13943 case 'Z': 13944 // FIXME: While Z does indicate a memory constraint, it specifically 13945 // indicates an r+r address (used in conjunction with the 'y' modifier 13946 // in the replacement string). Currently, we're forcing the base 13947 // register to be r0 in the asm printer (which is interpreted as zero) 13948 // and forming the complete address in the second register. This is 13949 // suboptimal. 13950 return C_Memory; 13951 } 13952 } else if (Constraint == "wc") { // individual CR bits. 13953 return C_RegisterClass; 13954 } else if (Constraint == "wa" || Constraint == "wd" || 13955 Constraint == "wf" || Constraint == "ws" || 13956 Constraint == "wi" || Constraint == "ww") { 13957 return C_RegisterClass; // VSX registers. 13958 } 13959 return TargetLowering::getConstraintType(Constraint); 13960 } 13961 13962 /// Examine constraint type and operand type and determine a weight value. 13963 /// This object must already have been set up with the operand type 13964 /// and the current alternative constraint selected. 13965 TargetLowering::ConstraintWeight 13966 PPCTargetLowering::getSingleConstraintMatchWeight( 13967 AsmOperandInfo &info, const char *constraint) const { 13968 ConstraintWeight weight = CW_Invalid; 13969 Value *CallOperandVal = info.CallOperandVal; 13970 // If we don't have a value, we can't do a match, 13971 // but allow it at the lowest weight. 13972 if (!CallOperandVal) 13973 return CW_Default; 13974 Type *type = CallOperandVal->getType(); 13975 13976 // Look at the constraint type. 13977 if (StringRef(constraint) == "wc" && type->isIntegerTy(1)) 13978 return CW_Register; // an individual CR bit. 13979 else if ((StringRef(constraint) == "wa" || 13980 StringRef(constraint) == "wd" || 13981 StringRef(constraint) == "wf") && 13982 type->isVectorTy()) 13983 return CW_Register; 13984 else if (StringRef(constraint) == "wi" && type->isIntegerTy(64)) 13985 return CW_Register; // just hold 64-bit integers data. 13986 else if (StringRef(constraint) == "ws" && type->isDoubleTy()) 13987 return CW_Register; 13988 else if (StringRef(constraint) == "ww" && type->isFloatTy()) 13989 return CW_Register; 13990 13991 switch (*constraint) { 13992 default: 13993 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint); 13994 break; 13995 case 'b': 13996 if (type->isIntegerTy()) 13997 weight = CW_Register; 13998 break; 13999 case 'f': 14000 if (type->isFloatTy()) 14001 weight = CW_Register; 14002 break; 14003 case 'd': 14004 if (type->isDoubleTy()) 14005 weight = CW_Register; 14006 break; 14007 case 'v': 14008 if (type->isVectorTy()) 14009 weight = CW_Register; 14010 break; 14011 case 'y': 14012 weight = CW_Register; 14013 break; 14014 case 'Z': 14015 weight = CW_Memory; 14016 break; 14017 } 14018 return weight; 14019 } 14020 14021 std::pair<unsigned, const TargetRegisterClass *> 14022 PPCTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, 14023 StringRef Constraint, 14024 MVT VT) const { 14025 if (Constraint.size() == 1) { 14026 // GCC RS6000 Constraint Letters 14027 switch (Constraint[0]) { 14028 case 'b': // R1-R31 14029 if (VT == MVT::i64 && Subtarget.isPPC64()) 14030 return std::make_pair(0U, &PPC::G8RC_NOX0RegClass); 14031 return std::make_pair(0U, &PPC::GPRC_NOR0RegClass); 14032 case 'r': // R0-R31 14033 if (VT == MVT::i64 && Subtarget.isPPC64()) 14034 return std::make_pair(0U, &PPC::G8RCRegClass); 14035 return std::make_pair(0U, &PPC::GPRCRegClass); 14036 // 'd' and 'f' constraints are both defined to be "the floating point 14037 // registers", where one is for 32-bit and the other for 64-bit. We don't 14038 // really care overly much here so just give them all the same reg classes. 14039 case 'd': 14040 case 'f': 14041 if (Subtarget.hasSPE()) { 14042 if (VT == MVT::f32 || VT == MVT::i32) 14043 return std::make_pair(0U, &PPC::SPE4RCRegClass); 14044 if (VT == MVT::f64 || VT == MVT::i64) 14045 return std::make_pair(0U, &PPC::SPERCRegClass); 14046 } else { 14047 if (VT == MVT::f32 || VT == MVT::i32) 14048 return std::make_pair(0U, &PPC::F4RCRegClass); 14049 if (VT == MVT::f64 || VT == MVT::i64) 14050 return std::make_pair(0U, &PPC::F8RCRegClass); 14051 if (VT == MVT::v4f64 && Subtarget.hasQPX()) 14052 return std::make_pair(0U, &PPC::QFRCRegClass); 14053 if (VT == MVT::v4f32 && Subtarget.hasQPX()) 14054 return std::make_pair(0U, &PPC::QSRCRegClass); 14055 } 14056 break; 14057 case 'v': 14058 if (VT == MVT::v4f64 && Subtarget.hasQPX()) 14059 return std::make_pair(0U, &PPC::QFRCRegClass); 14060 if (VT == MVT::v4f32 && Subtarget.hasQPX()) 14061 return std::make_pair(0U, &PPC::QSRCRegClass); 14062 if (Subtarget.hasAltivec()) 14063 return std::make_pair(0U, &PPC::VRRCRegClass); 14064 break; 14065 case 'y': // crrc 14066 return std::make_pair(0U, &PPC::CRRCRegClass); 14067 } 14068 } else if (Constraint == "wc" && Subtarget.useCRBits()) { 14069 // An individual CR bit. 14070 return std::make_pair(0U, &PPC::CRBITRCRegClass); 14071 } else if ((Constraint == "wa" || Constraint == "wd" || 14072 Constraint == "wf" || Constraint == "wi") && 14073 Subtarget.hasVSX()) { 14074 return std::make_pair(0U, &PPC::VSRCRegClass); 14075 } else if ((Constraint == "ws" || Constraint == "ww") && Subtarget.hasVSX()) { 14076 if (VT == MVT::f32 && Subtarget.hasP8Vector()) 14077 return std::make_pair(0U, &PPC::VSSRCRegClass); 14078 else 14079 return std::make_pair(0U, &PPC::VSFRCRegClass); 14080 } 14081 14082 std::pair<unsigned, const TargetRegisterClass *> R = 14083 TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 14084 14085 // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers 14086 // (which we call X[0-9]+). If a 64-bit value has been requested, and a 14087 // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent 14088 // register. 14089 // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use 14090 // the AsmName field from *RegisterInfo.td, then this would not be necessary. 14091 if (R.first && VT == MVT::i64 && Subtarget.isPPC64() && 14092 PPC::GPRCRegClass.contains(R.first)) 14093 return std::make_pair(TRI->getMatchingSuperReg(R.first, 14094 PPC::sub_32, &PPC::G8RCRegClass), 14095 &PPC::G8RCRegClass); 14096 14097 // GCC accepts 'cc' as an alias for 'cr0', and we need to do the same. 14098 if (!R.second && StringRef("{cc}").equals_lower(Constraint)) { 14099 R.first = PPC::CR0; 14100 R.second = &PPC::CRRCRegClass; 14101 } 14102 14103 return R; 14104 } 14105 14106 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops 14107 /// vector. If it is invalid, don't add anything to Ops. 14108 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op, 14109 std::string &Constraint, 14110 std::vector<SDValue>&Ops, 14111 SelectionDAG &DAG) const { 14112 SDValue Result; 14113 14114 // Only support length 1 constraints. 14115 if (Constraint.length() > 1) return; 14116 14117 char Letter = Constraint[0]; 14118 switch (Letter) { 14119 default: break; 14120 case 'I': 14121 case 'J': 14122 case 'K': 14123 case 'L': 14124 case 'M': 14125 case 'N': 14126 case 'O': 14127 case 'P': { 14128 ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op); 14129 if (!CST) return; // Must be an immediate to match. 14130 SDLoc dl(Op); 14131 int64_t Value = CST->getSExtValue(); 14132 EVT TCVT = MVT::i64; // All constants taken to be 64 bits so that negative 14133 // numbers are printed as such. 14134 switch (Letter) { 14135 default: llvm_unreachable("Unknown constraint letter!"); 14136 case 'I': // "I" is a signed 16-bit constant. 14137 if (isInt<16>(Value)) 14138 Result = DAG.getTargetConstant(Value, dl, TCVT); 14139 break; 14140 case 'J': // "J" is a constant with only the high-order 16 bits nonzero. 14141 if (isShiftedUInt<16, 16>(Value)) 14142 Result = DAG.getTargetConstant(Value, dl, TCVT); 14143 break; 14144 case 'L': // "L" is a signed 16-bit constant shifted left 16 bits. 14145 if (isShiftedInt<16, 16>(Value)) 14146 Result = DAG.getTargetConstant(Value, dl, TCVT); 14147 break; 14148 case 'K': // "K" is a constant with only the low-order 16 bits nonzero. 14149 if (isUInt<16>(Value)) 14150 Result = DAG.getTargetConstant(Value, dl, TCVT); 14151 break; 14152 case 'M': // "M" is a constant that is greater than 31. 14153 if (Value > 31) 14154 Result = DAG.getTargetConstant(Value, dl, TCVT); 14155 break; 14156 case 'N': // "N" is a positive constant that is an exact power of two. 14157 if (Value > 0 && isPowerOf2_64(Value)) 14158 Result = DAG.getTargetConstant(Value, dl, TCVT); 14159 break; 14160 case 'O': // "O" is the constant zero. 14161 if (Value == 0) 14162 Result = DAG.getTargetConstant(Value, dl, TCVT); 14163 break; 14164 case 'P': // "P" is a constant whose negation is a signed 16-bit constant. 14165 if (isInt<16>(-Value)) 14166 Result = DAG.getTargetConstant(Value, dl, TCVT); 14167 break; 14168 } 14169 break; 14170 } 14171 } 14172 14173 if (Result.getNode()) { 14174 Ops.push_back(Result); 14175 return; 14176 } 14177 14178 // Handle standard constraint letters. 14179 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 14180 } 14181 14182 // isLegalAddressingMode - Return true if the addressing mode represented 14183 // by AM is legal for this target, for a load/store of the specified type. 14184 bool PPCTargetLowering::isLegalAddressingMode(const DataLayout &DL, 14185 const AddrMode &AM, Type *Ty, 14186 unsigned AS, Instruction *I) const { 14187 // PPC does not allow r+i addressing modes for vectors! 14188 if (Ty->isVectorTy() && AM.BaseOffs != 0) 14189 return false; 14190 14191 // PPC allows a sign-extended 16-bit immediate field. 14192 if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1) 14193 return false; 14194 14195 // No global is ever allowed as a base. 14196 if (AM.BaseGV) 14197 return false; 14198 14199 // PPC only support r+r, 14200 switch (AM.Scale) { 14201 case 0: // "r+i" or just "i", depending on HasBaseReg. 14202 break; 14203 case 1: 14204 if (AM.HasBaseReg && AM.BaseOffs) // "r+r+i" is not allowed. 14205 return false; 14206 // Otherwise we have r+r or r+i. 14207 break; 14208 case 2: 14209 if (AM.HasBaseReg || AM.BaseOffs) // 2*r+r or 2*r+i is not allowed. 14210 return false; 14211 // Allow 2*r as r+r. 14212 break; 14213 default: 14214 // No other scales are supported. 14215 return false; 14216 } 14217 14218 return true; 14219 } 14220 14221 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op, 14222 SelectionDAG &DAG) const { 14223 MachineFunction &MF = DAG.getMachineFunction(); 14224 MachineFrameInfo &MFI = MF.getFrameInfo(); 14225 MFI.setReturnAddressIsTaken(true); 14226 14227 if (verifyReturnAddressArgumentIsConstant(Op, DAG)) 14228 return SDValue(); 14229 14230 SDLoc dl(Op); 14231 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 14232 14233 // Make sure the function does not optimize away the store of the RA to 14234 // the stack. 14235 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 14236 FuncInfo->setLRStoreRequired(); 14237 bool isPPC64 = Subtarget.isPPC64(); 14238 auto PtrVT = getPointerTy(MF.getDataLayout()); 14239 14240 if (Depth > 0) { 14241 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG); 14242 SDValue Offset = 14243 DAG.getConstant(Subtarget.getFrameLowering()->getReturnSaveOffset(), dl, 14244 isPPC64 ? MVT::i64 : MVT::i32); 14245 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), 14246 DAG.getNode(ISD::ADD, dl, PtrVT, FrameAddr, Offset), 14247 MachinePointerInfo()); 14248 } 14249 14250 // Just load the return address off the stack. 14251 SDValue RetAddrFI = getReturnAddrFrameIndex(DAG); 14252 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), RetAddrFI, 14253 MachinePointerInfo()); 14254 } 14255 14256 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op, 14257 SelectionDAG &DAG) const { 14258 SDLoc dl(Op); 14259 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 14260 14261 MachineFunction &MF = DAG.getMachineFunction(); 14262 MachineFrameInfo &MFI = MF.getFrameInfo(); 14263 MFI.setFrameAddressIsTaken(true); 14264 14265 EVT PtrVT = getPointerTy(MF.getDataLayout()); 14266 bool isPPC64 = PtrVT == MVT::i64; 14267 14268 // Naked functions never have a frame pointer, and so we use r1. For all 14269 // other functions, this decision must be delayed until during PEI. 14270 unsigned FrameReg; 14271 if (MF.getFunction().hasFnAttribute(Attribute::Naked)) 14272 FrameReg = isPPC64 ? PPC::X1 : PPC::R1; 14273 else 14274 FrameReg = isPPC64 ? PPC::FP8 : PPC::FP; 14275 14276 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, 14277 PtrVT); 14278 while (Depth--) 14279 FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(), 14280 FrameAddr, MachinePointerInfo()); 14281 return FrameAddr; 14282 } 14283 14284 // FIXME? Maybe this could be a TableGen attribute on some registers and 14285 // this table could be generated automatically from RegInfo. 14286 unsigned PPCTargetLowering::getRegisterByName(const char* RegName, EVT VT, 14287 SelectionDAG &DAG) const { 14288 bool isPPC64 = Subtarget.isPPC64(); 14289 bool isDarwinABI = Subtarget.isDarwinABI(); 14290 14291 if ((isPPC64 && VT != MVT::i64 && VT != MVT::i32) || 14292 (!isPPC64 && VT != MVT::i32)) 14293 report_fatal_error("Invalid register global variable type"); 14294 14295 bool is64Bit = isPPC64 && VT == MVT::i64; 14296 unsigned Reg = StringSwitch<unsigned>(RegName) 14297 .Case("r1", is64Bit ? PPC::X1 : PPC::R1) 14298 .Case("r2", (isDarwinABI || isPPC64) ? 0 : PPC::R2) 14299 .Case("r13", (!isPPC64 && isDarwinABI) ? 0 : 14300 (is64Bit ? PPC::X13 : PPC::R13)) 14301 .Default(0); 14302 14303 if (Reg) 14304 return Reg; 14305 report_fatal_error("Invalid register name global variable"); 14306 } 14307 14308 bool PPCTargetLowering::isAccessedAsGotIndirect(SDValue GA) const { 14309 // 32-bit SVR4 ABI access everything as got-indirect. 14310 if (Subtarget.isSVR4ABI() && !Subtarget.isPPC64()) 14311 return true; 14312 14313 CodeModel::Model CModel = getTargetMachine().getCodeModel(); 14314 // If it is small or large code model, module locals are accessed 14315 // indirectly by loading their address from .toc/.got. The difference 14316 // is that for large code model we have ADDISTocHa + LDtocL and for 14317 // small code model we simply have LDtoc. 14318 if (CModel == CodeModel::Small || CModel == CodeModel::Large) 14319 return true; 14320 14321 // JumpTable and BlockAddress are accessed as got-indirect. 14322 if (isa<JumpTableSDNode>(GA) || isa<BlockAddressSDNode>(GA)) 14323 return true; 14324 14325 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(GA)) { 14326 const GlobalValue *GV = G->getGlobal(); 14327 unsigned char GVFlags = Subtarget.classifyGlobalReference(GV); 14328 // The NLP flag indicates that a global access has to use an 14329 // extra indirection. 14330 if (GVFlags & PPCII::MO_NLP_FLAG) 14331 return true; 14332 } 14333 14334 return false; 14335 } 14336 14337 bool 14338 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 14339 // The PowerPC target isn't yet aware of offsets. 14340 return false; 14341 } 14342 14343 bool PPCTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 14344 const CallInst &I, 14345 MachineFunction &MF, 14346 unsigned Intrinsic) const { 14347 switch (Intrinsic) { 14348 case Intrinsic::ppc_qpx_qvlfd: 14349 case Intrinsic::ppc_qpx_qvlfs: 14350 case Intrinsic::ppc_qpx_qvlfcd: 14351 case Intrinsic::ppc_qpx_qvlfcs: 14352 case Intrinsic::ppc_qpx_qvlfiwa: 14353 case Intrinsic::ppc_qpx_qvlfiwz: 14354 case Intrinsic::ppc_altivec_lvx: 14355 case Intrinsic::ppc_altivec_lvxl: 14356 case Intrinsic::ppc_altivec_lvebx: 14357 case Intrinsic::ppc_altivec_lvehx: 14358 case Intrinsic::ppc_altivec_lvewx: 14359 case Intrinsic::ppc_vsx_lxvd2x: 14360 case Intrinsic::ppc_vsx_lxvw4x: { 14361 EVT VT; 14362 switch (Intrinsic) { 14363 case Intrinsic::ppc_altivec_lvebx: 14364 VT = MVT::i8; 14365 break; 14366 case Intrinsic::ppc_altivec_lvehx: 14367 VT = MVT::i16; 14368 break; 14369 case Intrinsic::ppc_altivec_lvewx: 14370 VT = MVT::i32; 14371 break; 14372 case Intrinsic::ppc_vsx_lxvd2x: 14373 VT = MVT::v2f64; 14374 break; 14375 case Intrinsic::ppc_qpx_qvlfd: 14376 VT = MVT::v4f64; 14377 break; 14378 case Intrinsic::ppc_qpx_qvlfs: 14379 VT = MVT::v4f32; 14380 break; 14381 case Intrinsic::ppc_qpx_qvlfcd: 14382 VT = MVT::v2f64; 14383 break; 14384 case Intrinsic::ppc_qpx_qvlfcs: 14385 VT = MVT::v2f32; 14386 break; 14387 default: 14388 VT = MVT::v4i32; 14389 break; 14390 } 14391 14392 Info.opc = ISD::INTRINSIC_W_CHAIN; 14393 Info.memVT = VT; 14394 Info.ptrVal = I.getArgOperand(0); 14395 Info.offset = -VT.getStoreSize()+1; 14396 Info.size = 2*VT.getStoreSize()-1; 14397 Info.align = 1; 14398 Info.flags = MachineMemOperand::MOLoad; 14399 return true; 14400 } 14401 case Intrinsic::ppc_qpx_qvlfda: 14402 case Intrinsic::ppc_qpx_qvlfsa: 14403 case Intrinsic::ppc_qpx_qvlfcda: 14404 case Intrinsic::ppc_qpx_qvlfcsa: 14405 case Intrinsic::ppc_qpx_qvlfiwaa: 14406 case Intrinsic::ppc_qpx_qvlfiwza: { 14407 EVT VT; 14408 switch (Intrinsic) { 14409 case Intrinsic::ppc_qpx_qvlfda: 14410 VT = MVT::v4f64; 14411 break; 14412 case Intrinsic::ppc_qpx_qvlfsa: 14413 VT = MVT::v4f32; 14414 break; 14415 case Intrinsic::ppc_qpx_qvlfcda: 14416 VT = MVT::v2f64; 14417 break; 14418 case Intrinsic::ppc_qpx_qvlfcsa: 14419 VT = MVT::v2f32; 14420 break; 14421 default: 14422 VT = MVT::v4i32; 14423 break; 14424 } 14425 14426 Info.opc = ISD::INTRINSIC_W_CHAIN; 14427 Info.memVT = VT; 14428 Info.ptrVal = I.getArgOperand(0); 14429 Info.offset = 0; 14430 Info.size = VT.getStoreSize(); 14431 Info.align = 1; 14432 Info.flags = MachineMemOperand::MOLoad; 14433 return true; 14434 } 14435 case Intrinsic::ppc_qpx_qvstfd: 14436 case Intrinsic::ppc_qpx_qvstfs: 14437 case Intrinsic::ppc_qpx_qvstfcd: 14438 case Intrinsic::ppc_qpx_qvstfcs: 14439 case Intrinsic::ppc_qpx_qvstfiw: 14440 case Intrinsic::ppc_altivec_stvx: 14441 case Intrinsic::ppc_altivec_stvxl: 14442 case Intrinsic::ppc_altivec_stvebx: 14443 case Intrinsic::ppc_altivec_stvehx: 14444 case Intrinsic::ppc_altivec_stvewx: 14445 case Intrinsic::ppc_vsx_stxvd2x: 14446 case Intrinsic::ppc_vsx_stxvw4x: { 14447 EVT VT; 14448 switch (Intrinsic) { 14449 case Intrinsic::ppc_altivec_stvebx: 14450 VT = MVT::i8; 14451 break; 14452 case Intrinsic::ppc_altivec_stvehx: 14453 VT = MVT::i16; 14454 break; 14455 case Intrinsic::ppc_altivec_stvewx: 14456 VT = MVT::i32; 14457 break; 14458 case Intrinsic::ppc_vsx_stxvd2x: 14459 VT = MVT::v2f64; 14460 break; 14461 case Intrinsic::ppc_qpx_qvstfd: 14462 VT = MVT::v4f64; 14463 break; 14464 case Intrinsic::ppc_qpx_qvstfs: 14465 VT = MVT::v4f32; 14466 break; 14467 case Intrinsic::ppc_qpx_qvstfcd: 14468 VT = MVT::v2f64; 14469 break; 14470 case Intrinsic::ppc_qpx_qvstfcs: 14471 VT = MVT::v2f32; 14472 break; 14473 default: 14474 VT = MVT::v4i32; 14475 break; 14476 } 14477 14478 Info.opc = ISD::INTRINSIC_VOID; 14479 Info.memVT = VT; 14480 Info.ptrVal = I.getArgOperand(1); 14481 Info.offset = -VT.getStoreSize()+1; 14482 Info.size = 2*VT.getStoreSize()-1; 14483 Info.align = 1; 14484 Info.flags = MachineMemOperand::MOStore; 14485 return true; 14486 } 14487 case Intrinsic::ppc_qpx_qvstfda: 14488 case Intrinsic::ppc_qpx_qvstfsa: 14489 case Intrinsic::ppc_qpx_qvstfcda: 14490 case Intrinsic::ppc_qpx_qvstfcsa: 14491 case Intrinsic::ppc_qpx_qvstfiwa: { 14492 EVT VT; 14493 switch (Intrinsic) { 14494 case Intrinsic::ppc_qpx_qvstfda: 14495 VT = MVT::v4f64; 14496 break; 14497 case Intrinsic::ppc_qpx_qvstfsa: 14498 VT = MVT::v4f32; 14499 break; 14500 case Intrinsic::ppc_qpx_qvstfcda: 14501 VT = MVT::v2f64; 14502 break; 14503 case Intrinsic::ppc_qpx_qvstfcsa: 14504 VT = MVT::v2f32; 14505 break; 14506 default: 14507 VT = MVT::v4i32; 14508 break; 14509 } 14510 14511 Info.opc = ISD::INTRINSIC_VOID; 14512 Info.memVT = VT; 14513 Info.ptrVal = I.getArgOperand(1); 14514 Info.offset = 0; 14515 Info.size = VT.getStoreSize(); 14516 Info.align = 1; 14517 Info.flags = MachineMemOperand::MOStore; 14518 return true; 14519 } 14520 default: 14521 break; 14522 } 14523 14524 return false; 14525 } 14526 14527 /// getOptimalMemOpType - Returns the target specific optimal type for load 14528 /// and store operations as a result of memset, memcpy, and memmove 14529 /// lowering. If DstAlign is zero that means it's safe to destination 14530 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it 14531 /// means there isn't a need to check it against alignment requirement, 14532 /// probably because the source does not need to be loaded. If 'IsMemset' is 14533 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that 14534 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy 14535 /// source is constant so it does not need to be loaded. 14536 /// It returns EVT::Other if the type should be determined using generic 14537 /// target-independent logic. 14538 EVT PPCTargetLowering::getOptimalMemOpType( 14539 uint64_t Size, unsigned DstAlign, unsigned SrcAlign, bool IsMemset, 14540 bool ZeroMemset, bool MemcpyStrSrc, 14541 const AttributeList &FuncAttributes) const { 14542 if (getTargetMachine().getOptLevel() != CodeGenOpt::None) { 14543 // When expanding a memset, require at least two QPX instructions to cover 14544 // the cost of loading the value to be stored from the constant pool. 14545 if (Subtarget.hasQPX() && Size >= 32 && (!IsMemset || Size >= 64) && 14546 (!SrcAlign || SrcAlign >= 32) && (!DstAlign || DstAlign >= 32) && 14547 !FuncAttributes.hasFnAttribute(Attribute::NoImplicitFloat)) { 14548 return MVT::v4f64; 14549 } 14550 14551 // We should use Altivec/VSX loads and stores when available. For unaligned 14552 // addresses, unaligned VSX loads are only fast starting with the P8. 14553 if (Subtarget.hasAltivec() && Size >= 16 && 14554 (((!SrcAlign || SrcAlign >= 16) && (!DstAlign || DstAlign >= 16)) || 14555 ((IsMemset && Subtarget.hasVSX()) || Subtarget.hasP8Vector()))) 14556 return MVT::v4i32; 14557 } 14558 14559 if (Subtarget.isPPC64()) { 14560 return MVT::i64; 14561 } 14562 14563 return MVT::i32; 14564 } 14565 14566 /// Returns true if it is beneficial to convert a load of a constant 14567 /// to just the constant itself. 14568 bool PPCTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 14569 Type *Ty) const { 14570 assert(Ty->isIntegerTy()); 14571 14572 unsigned BitSize = Ty->getPrimitiveSizeInBits(); 14573 return !(BitSize == 0 || BitSize > 64); 14574 } 14575 14576 bool PPCTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const { 14577 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy()) 14578 return false; 14579 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits(); 14580 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits(); 14581 return NumBits1 == 64 && NumBits2 == 32; 14582 } 14583 14584 bool PPCTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const { 14585 if (!VT1.isInteger() || !VT2.isInteger()) 14586 return false; 14587 unsigned NumBits1 = VT1.getSizeInBits(); 14588 unsigned NumBits2 = VT2.getSizeInBits(); 14589 return NumBits1 == 64 && NumBits2 == 32; 14590 } 14591 14592 bool PPCTargetLowering::isZExtFree(SDValue Val, EVT VT2) const { 14593 // Generally speaking, zexts are not free, but they are free when they can be 14594 // folded with other operations. 14595 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Val)) { 14596 EVT MemVT = LD->getMemoryVT(); 14597 if ((MemVT == MVT::i1 || MemVT == MVT::i8 || MemVT == MVT::i16 || 14598 (Subtarget.isPPC64() && MemVT == MVT::i32)) && 14599 (LD->getExtensionType() == ISD::NON_EXTLOAD || 14600 LD->getExtensionType() == ISD::ZEXTLOAD)) 14601 return true; 14602 } 14603 14604 // FIXME: Add other cases... 14605 // - 32-bit shifts with a zext to i64 14606 // - zext after ctlz, bswap, etc. 14607 // - zext after and by a constant mask 14608 14609 return TargetLowering::isZExtFree(Val, VT2); 14610 } 14611 14612 bool PPCTargetLowering::isFPExtFree(EVT DestVT, EVT SrcVT) const { 14613 assert(DestVT.isFloatingPoint() && SrcVT.isFloatingPoint() && 14614 "invalid fpext types"); 14615 // Extending to float128 is not free. 14616 if (DestVT == MVT::f128) 14617 return false; 14618 return true; 14619 } 14620 14621 bool PPCTargetLowering::isLegalICmpImmediate(int64_t Imm) const { 14622 return isInt<16>(Imm) || isUInt<16>(Imm); 14623 } 14624 14625 bool PPCTargetLowering::isLegalAddImmediate(int64_t Imm) const { 14626 return isInt<16>(Imm) || isUInt<16>(Imm); 14627 } 14628 14629 bool PPCTargetLowering::allowsMisalignedMemoryAccesses(EVT VT, 14630 unsigned, 14631 unsigned, 14632 MachineMemOperand::Flags, 14633 bool *Fast) const { 14634 if (DisablePPCUnaligned) 14635 return false; 14636 14637 // PowerPC supports unaligned memory access for simple non-vector types. 14638 // Although accessing unaligned addresses is not as efficient as accessing 14639 // aligned addresses, it is generally more efficient than manual expansion, 14640 // and generally only traps for software emulation when crossing page 14641 // boundaries. 14642 14643 if (!VT.isSimple()) 14644 return false; 14645 14646 if (VT.getSimpleVT().isVector()) { 14647 if (Subtarget.hasVSX()) { 14648 if (VT != MVT::v2f64 && VT != MVT::v2i64 && 14649 VT != MVT::v4f32 && VT != MVT::v4i32) 14650 return false; 14651 } else { 14652 return false; 14653 } 14654 } 14655 14656 if (VT == MVT::ppcf128) 14657 return false; 14658 14659 if (Fast) 14660 *Fast = true; 14661 14662 return true; 14663 } 14664 14665 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const { 14666 VT = VT.getScalarType(); 14667 14668 if (!VT.isSimple()) 14669 return false; 14670 14671 switch (VT.getSimpleVT().SimpleTy) { 14672 case MVT::f32: 14673 case MVT::f64: 14674 return true; 14675 case MVT::f128: 14676 return (EnableQuadPrecision && Subtarget.hasP9Vector()); 14677 default: 14678 break; 14679 } 14680 14681 return false; 14682 } 14683 14684 const MCPhysReg * 14685 PPCTargetLowering::getScratchRegisters(CallingConv::ID) const { 14686 // LR is a callee-save register, but we must treat it as clobbered by any call 14687 // site. Hence we include LR in the scratch registers, which are in turn added 14688 // as implicit-defs for stackmaps and patchpoints. The same reasoning applies 14689 // to CTR, which is used by any indirect call. 14690 static const MCPhysReg ScratchRegs[] = { 14691 PPC::X12, PPC::LR8, PPC::CTR8, 0 14692 }; 14693 14694 return ScratchRegs; 14695 } 14696 14697 unsigned PPCTargetLowering::getExceptionPointerRegister( 14698 const Constant *PersonalityFn) const { 14699 return Subtarget.isPPC64() ? PPC::X3 : PPC::R3; 14700 } 14701 14702 unsigned PPCTargetLowering::getExceptionSelectorRegister( 14703 const Constant *PersonalityFn) const { 14704 return Subtarget.isPPC64() ? PPC::X4 : PPC::R4; 14705 } 14706 14707 bool 14708 PPCTargetLowering::shouldExpandBuildVectorWithShuffles( 14709 EVT VT , unsigned DefinedValues) const { 14710 if (VT == MVT::v2i64) 14711 return Subtarget.hasDirectMove(); // Don't need stack ops with direct moves 14712 14713 if (Subtarget.hasVSX() || Subtarget.hasQPX()) 14714 return true; 14715 14716 return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues); 14717 } 14718 14719 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const { 14720 if (DisableILPPref || Subtarget.enableMachineScheduler()) 14721 return TargetLowering::getSchedulingPreference(N); 14722 14723 return Sched::ILP; 14724 } 14725 14726 // Create a fast isel object. 14727 FastISel * 14728 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo, 14729 const TargetLibraryInfo *LibInfo) const { 14730 return PPC::createFastISel(FuncInfo, LibInfo); 14731 } 14732 14733 void PPCTargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const { 14734 if (Subtarget.isDarwinABI()) return; 14735 if (!Subtarget.isPPC64()) return; 14736 14737 // Update IsSplitCSR in PPCFunctionInfo 14738 PPCFunctionInfo *PFI = Entry->getParent()->getInfo<PPCFunctionInfo>(); 14739 PFI->setIsSplitCSR(true); 14740 } 14741 14742 void PPCTargetLowering::insertCopiesSplitCSR( 14743 MachineBasicBlock *Entry, 14744 const SmallVectorImpl<MachineBasicBlock *> &Exits) const { 14745 const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo(); 14746 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent()); 14747 if (!IStart) 14748 return; 14749 14750 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 14751 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo(); 14752 MachineBasicBlock::iterator MBBI = Entry->begin(); 14753 for (const MCPhysReg *I = IStart; *I; ++I) { 14754 const TargetRegisterClass *RC = nullptr; 14755 if (PPC::G8RCRegClass.contains(*I)) 14756 RC = &PPC::G8RCRegClass; 14757 else if (PPC::F8RCRegClass.contains(*I)) 14758 RC = &PPC::F8RCRegClass; 14759 else if (PPC::CRRCRegClass.contains(*I)) 14760 RC = &PPC::CRRCRegClass; 14761 else if (PPC::VRRCRegClass.contains(*I)) 14762 RC = &PPC::VRRCRegClass; 14763 else 14764 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 14765 14766 unsigned NewVR = MRI->createVirtualRegister(RC); 14767 // Create copy from CSR to a virtual register. 14768 // FIXME: this currently does not emit CFI pseudo-instructions, it works 14769 // fine for CXX_FAST_TLS since the C++-style TLS access functions should be 14770 // nounwind. If we want to generalize this later, we may need to emit 14771 // CFI pseudo-instructions. 14772 assert(Entry->getParent()->getFunction().hasFnAttribute( 14773 Attribute::NoUnwind) && 14774 "Function should be nounwind in insertCopiesSplitCSR!"); 14775 Entry->addLiveIn(*I); 14776 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR) 14777 .addReg(*I); 14778 14779 // Insert the copy-back instructions right before the terminator. 14780 for (auto *Exit : Exits) 14781 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(), 14782 TII->get(TargetOpcode::COPY), *I) 14783 .addReg(NewVR); 14784 } 14785 } 14786 14787 // Override to enable LOAD_STACK_GUARD lowering on Linux. 14788 bool PPCTargetLowering::useLoadStackGuardNode() const { 14789 if (!Subtarget.isTargetLinux()) 14790 return TargetLowering::useLoadStackGuardNode(); 14791 return true; 14792 } 14793 14794 // Override to disable global variable loading on Linux. 14795 void PPCTargetLowering::insertSSPDeclarations(Module &M) const { 14796 if (!Subtarget.isTargetLinux()) 14797 return TargetLowering::insertSSPDeclarations(M); 14798 } 14799 14800 bool PPCTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT, 14801 bool ForCodeSize) const { 14802 if (!VT.isSimple() || !Subtarget.hasVSX()) 14803 return false; 14804 14805 switch(VT.getSimpleVT().SimpleTy) { 14806 default: 14807 // For FP types that are currently not supported by PPC backend, return 14808 // false. Examples: f16, f80. 14809 return false; 14810 case MVT::f32: 14811 case MVT::f64: 14812 case MVT::ppcf128: 14813 return Imm.isPosZero(); 14814 } 14815 } 14816 14817 // For vector shift operation op, fold 14818 // (op x, (and y, ((1 << numbits(x)) - 1))) -> (target op x, y) 14819 static SDValue stripModuloOnShift(const TargetLowering &TLI, SDNode *N, 14820 SelectionDAG &DAG) { 14821 SDValue N0 = N->getOperand(0); 14822 SDValue N1 = N->getOperand(1); 14823 EVT VT = N0.getValueType(); 14824 unsigned OpSizeInBits = VT.getScalarSizeInBits(); 14825 unsigned Opcode = N->getOpcode(); 14826 unsigned TargetOpcode; 14827 14828 switch (Opcode) { 14829 default: 14830 llvm_unreachable("Unexpected shift operation"); 14831 case ISD::SHL: 14832 TargetOpcode = PPCISD::SHL; 14833 break; 14834 case ISD::SRL: 14835 TargetOpcode = PPCISD::SRL; 14836 break; 14837 case ISD::SRA: 14838 TargetOpcode = PPCISD::SRA; 14839 break; 14840 } 14841 14842 if (VT.isVector() && TLI.isOperationLegal(Opcode, VT) && 14843 N1->getOpcode() == ISD::AND) 14844 if (ConstantSDNode *Mask = isConstOrConstSplat(N1->getOperand(1))) 14845 if (Mask->getZExtValue() == OpSizeInBits - 1) 14846 return DAG.getNode(TargetOpcode, SDLoc(N), VT, N0, N1->getOperand(0)); 14847 14848 return SDValue(); 14849 } 14850 14851 SDValue PPCTargetLowering::combineSHL(SDNode *N, DAGCombinerInfo &DCI) const { 14852 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG)) 14853 return Value; 14854 14855 SDValue N0 = N->getOperand(0); 14856 ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N->getOperand(1)); 14857 if (!Subtarget.isISA3_0() || 14858 N0.getOpcode() != ISD::SIGN_EXTEND || 14859 N0.getOperand(0).getValueType() != MVT::i32 || 14860 CN1 == nullptr || N->getValueType(0) != MVT::i64) 14861 return SDValue(); 14862 14863 // We can't save an operation here if the value is already extended, and 14864 // the existing shift is easier to combine. 14865 SDValue ExtsSrc = N0.getOperand(0); 14866 if (ExtsSrc.getOpcode() == ISD::TRUNCATE && 14867 ExtsSrc.getOperand(0).getOpcode() == ISD::AssertSext) 14868 return SDValue(); 14869 14870 SDLoc DL(N0); 14871 SDValue ShiftBy = SDValue(CN1, 0); 14872 // We want the shift amount to be i32 on the extswli, but the shift could 14873 // have an i64. 14874 if (ShiftBy.getValueType() == MVT::i64) 14875 ShiftBy = DCI.DAG.getConstant(CN1->getZExtValue(), DL, MVT::i32); 14876 14877 return DCI.DAG.getNode(PPCISD::EXTSWSLI, DL, MVT::i64, N0->getOperand(0), 14878 ShiftBy); 14879 } 14880 14881 SDValue PPCTargetLowering::combineSRA(SDNode *N, DAGCombinerInfo &DCI) const { 14882 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG)) 14883 return Value; 14884 14885 return SDValue(); 14886 } 14887 14888 SDValue PPCTargetLowering::combineSRL(SDNode *N, DAGCombinerInfo &DCI) const { 14889 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG)) 14890 return Value; 14891 14892 return SDValue(); 14893 } 14894 14895 // Transform (add X, (zext(setne Z, C))) -> (addze X, (addic (addi Z, -C), -1)) 14896 // Transform (add X, (zext(sete Z, C))) -> (addze X, (subfic (addi Z, -C), 0)) 14897 // When C is zero, the equation (addi Z, -C) can be simplified to Z 14898 // Requirement: -C in [-32768, 32767], X and Z are MVT::i64 types 14899 static SDValue combineADDToADDZE(SDNode *N, SelectionDAG &DAG, 14900 const PPCSubtarget &Subtarget) { 14901 if (!Subtarget.isPPC64()) 14902 return SDValue(); 14903 14904 SDValue LHS = N->getOperand(0); 14905 SDValue RHS = N->getOperand(1); 14906 14907 auto isZextOfCompareWithConstant = [](SDValue Op) { 14908 if (Op.getOpcode() != ISD::ZERO_EXTEND || !Op.hasOneUse() || 14909 Op.getValueType() != MVT::i64) 14910 return false; 14911 14912 SDValue Cmp = Op.getOperand(0); 14913 if (Cmp.getOpcode() != ISD::SETCC || !Cmp.hasOneUse() || 14914 Cmp.getOperand(0).getValueType() != MVT::i64) 14915 return false; 14916 14917 if (auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1))) { 14918 int64_t NegConstant = 0 - Constant->getSExtValue(); 14919 // Due to the limitations of the addi instruction, 14920 // -C is required to be [-32768, 32767]. 14921 return isInt<16>(NegConstant); 14922 } 14923 14924 return false; 14925 }; 14926 14927 bool LHSHasPattern = isZextOfCompareWithConstant(LHS); 14928 bool RHSHasPattern = isZextOfCompareWithConstant(RHS); 14929 14930 // If there is a pattern, canonicalize a zext operand to the RHS. 14931 if (LHSHasPattern && !RHSHasPattern) 14932 std::swap(LHS, RHS); 14933 else if (!LHSHasPattern && !RHSHasPattern) 14934 return SDValue(); 14935 14936 SDLoc DL(N); 14937 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Glue); 14938 SDValue Cmp = RHS.getOperand(0); 14939 SDValue Z = Cmp.getOperand(0); 14940 auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1)); 14941 14942 assert(Constant && "Constant Should not be a null pointer."); 14943 int64_t NegConstant = 0 - Constant->getSExtValue(); 14944 14945 switch(cast<CondCodeSDNode>(Cmp.getOperand(2))->get()) { 14946 default: break; 14947 case ISD::SETNE: { 14948 // when C == 0 14949 // --> addze X, (addic Z, -1).carry 14950 // / 14951 // add X, (zext(setne Z, C))-- 14952 // \ when -32768 <= -C <= 32767 && C != 0 14953 // --> addze X, (addic (addi Z, -C), -1).carry 14954 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z, 14955 DAG.getConstant(NegConstant, DL, MVT::i64)); 14956 SDValue AddOrZ = NegConstant != 0 ? Add : Z; 14957 SDValue Addc = DAG.getNode(ISD::ADDC, DL, DAG.getVTList(MVT::i64, MVT::Glue), 14958 AddOrZ, DAG.getConstant(-1ULL, DL, MVT::i64)); 14959 return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64), 14960 SDValue(Addc.getNode(), 1)); 14961 } 14962 case ISD::SETEQ: { 14963 // when C == 0 14964 // --> addze X, (subfic Z, 0).carry 14965 // / 14966 // add X, (zext(sete Z, C))-- 14967 // \ when -32768 <= -C <= 32767 && C != 0 14968 // --> addze X, (subfic (addi Z, -C), 0).carry 14969 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z, 14970 DAG.getConstant(NegConstant, DL, MVT::i64)); 14971 SDValue AddOrZ = NegConstant != 0 ? Add : Z; 14972 SDValue Subc = DAG.getNode(ISD::SUBC, DL, DAG.getVTList(MVT::i64, MVT::Glue), 14973 DAG.getConstant(0, DL, MVT::i64), AddOrZ); 14974 return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64), 14975 SDValue(Subc.getNode(), 1)); 14976 } 14977 } 14978 14979 return SDValue(); 14980 } 14981 14982 SDValue PPCTargetLowering::combineADD(SDNode *N, DAGCombinerInfo &DCI) const { 14983 if (auto Value = combineADDToADDZE(N, DCI.DAG, Subtarget)) 14984 return Value; 14985 14986 return SDValue(); 14987 } 14988 14989 // Detect TRUNCATE operations on bitcasts of float128 values. 14990 // What we are looking for here is the situtation where we extract a subset 14991 // of bits from a 128 bit float. 14992 // This can be of two forms: 14993 // 1) BITCAST of f128 feeding TRUNCATE 14994 // 2) BITCAST of f128 feeding SRL (a shift) feeding TRUNCATE 14995 // The reason this is required is because we do not have a legal i128 type 14996 // and so we want to prevent having to store the f128 and then reload part 14997 // of it. 14998 SDValue PPCTargetLowering::combineTRUNCATE(SDNode *N, 14999 DAGCombinerInfo &DCI) const { 15000 // If we are using CRBits then try that first. 15001 if (Subtarget.useCRBits()) { 15002 // Check if CRBits did anything and return that if it did. 15003 if (SDValue CRTruncValue = DAGCombineTruncBoolExt(N, DCI)) 15004 return CRTruncValue; 15005 } 15006 15007 SDLoc dl(N); 15008 SDValue Op0 = N->getOperand(0); 15009 15010 // Looking for a truncate of i128 to i64. 15011 if (Op0.getValueType() != MVT::i128 || N->getValueType(0) != MVT::i64) 15012 return SDValue(); 15013 15014 int EltToExtract = DCI.DAG.getDataLayout().isBigEndian() ? 1 : 0; 15015 15016 // SRL feeding TRUNCATE. 15017 if (Op0.getOpcode() == ISD::SRL) { 15018 ConstantSDNode *ConstNode = dyn_cast<ConstantSDNode>(Op0.getOperand(1)); 15019 // The right shift has to be by 64 bits. 15020 if (!ConstNode || ConstNode->getZExtValue() != 64) 15021 return SDValue(); 15022 15023 // Switch the element number to extract. 15024 EltToExtract = EltToExtract ? 0 : 1; 15025 // Update Op0 past the SRL. 15026 Op0 = Op0.getOperand(0); 15027 } 15028 15029 // BITCAST feeding a TRUNCATE possibly via SRL. 15030 if (Op0.getOpcode() == ISD::BITCAST && 15031 Op0.getValueType() == MVT::i128 && 15032 Op0.getOperand(0).getValueType() == MVT::f128) { 15033 SDValue Bitcast = DCI.DAG.getBitcast(MVT::v2i64, Op0.getOperand(0)); 15034 return DCI.DAG.getNode( 15035 ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Bitcast, 15036 DCI.DAG.getTargetConstant(EltToExtract, dl, MVT::i32)); 15037 } 15038 return SDValue(); 15039 } 15040 15041 SDValue PPCTargetLowering::combineMUL(SDNode *N, DAGCombinerInfo &DCI) const { 15042 SelectionDAG &DAG = DCI.DAG; 15043 15044 ConstantSDNode *ConstOpOrElement = isConstOrConstSplat(N->getOperand(1)); 15045 if (!ConstOpOrElement) 15046 return SDValue(); 15047 15048 // An imul is usually smaller than the alternative sequence for legal type. 15049 if (DAG.getMachineFunction().getFunction().hasMinSize() && 15050 isOperationLegal(ISD::MUL, N->getValueType(0))) 15051 return SDValue(); 15052 15053 auto IsProfitable = [this](bool IsNeg, bool IsAddOne, EVT VT) -> bool { 15054 switch (this->Subtarget.getDarwinDirective()) { 15055 default: 15056 // TODO: enhance the condition for subtarget before pwr8 15057 return false; 15058 case PPC::DIR_PWR8: 15059 // type mul add shl 15060 // scalar 4 1 1 15061 // vector 7 2 2 15062 return true; 15063 case PPC::DIR_PWR9: 15064 // type mul add shl 15065 // scalar 5 2 2 15066 // vector 7 2 2 15067 15068 // The cycle RATIO of related operations are showed as a table above. 15069 // Because mul is 5(scalar)/7(vector), add/sub/shl are all 2 for both 15070 // scalar and vector type. For 2 instrs patterns, add/sub + shl 15071 // are 4, it is always profitable; but for 3 instrs patterns 15072 // (mul x, -(2^N + 1)) => -(add (shl x, N), x), sub + add + shl are 6. 15073 // So we should only do it for vector type. 15074 return IsAddOne && IsNeg ? VT.isVector() : true; 15075 } 15076 }; 15077 15078 EVT VT = N->getValueType(0); 15079 SDLoc DL(N); 15080 15081 const APInt &MulAmt = ConstOpOrElement->getAPIntValue(); 15082 bool IsNeg = MulAmt.isNegative(); 15083 APInt MulAmtAbs = MulAmt.abs(); 15084 15085 if ((MulAmtAbs - 1).isPowerOf2()) { 15086 // (mul x, 2^N + 1) => (add (shl x, N), x) 15087 // (mul x, -(2^N + 1)) => -(add (shl x, N), x) 15088 15089 if (!IsProfitable(IsNeg, true, VT)) 15090 return SDValue(); 15091 15092 SDValue Op0 = N->getOperand(0); 15093 SDValue Op1 = 15094 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0), 15095 DAG.getConstant((MulAmtAbs - 1).logBase2(), DL, VT)); 15096 SDValue Res = DAG.getNode(ISD::ADD, DL, VT, Op0, Op1); 15097 15098 if (!IsNeg) 15099 return Res; 15100 15101 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Res); 15102 } else if ((MulAmtAbs + 1).isPowerOf2()) { 15103 // (mul x, 2^N - 1) => (sub (shl x, N), x) 15104 // (mul x, -(2^N - 1)) => (sub x, (shl x, N)) 15105 15106 if (!IsProfitable(IsNeg, false, VT)) 15107 return SDValue(); 15108 15109 SDValue Op0 = N->getOperand(0); 15110 SDValue Op1 = 15111 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0), 15112 DAG.getConstant((MulAmtAbs + 1).logBase2(), DL, VT)); 15113 15114 if (!IsNeg) 15115 return DAG.getNode(ISD::SUB, DL, VT, Op1, Op0); 15116 else 15117 return DAG.getNode(ISD::SUB, DL, VT, Op0, Op1); 15118 15119 } else { 15120 return SDValue(); 15121 } 15122 } 15123 15124 bool PPCTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 15125 // Only duplicate to increase tail-calls for the 64bit SysV ABIs. 15126 if (!Subtarget.isSVR4ABI() || !Subtarget.isPPC64()) 15127 return false; 15128 15129 // If not a tail call then no need to proceed. 15130 if (!CI->isTailCall()) 15131 return false; 15132 15133 // If tail calls are disabled for the caller then we are done. 15134 const Function *Caller = CI->getParent()->getParent(); 15135 auto Attr = Caller->getFnAttribute("disable-tail-calls"); 15136 if (Attr.getValueAsString() == "true") 15137 return false; 15138 15139 // If sibling calls have been disabled and tail-calls aren't guaranteed 15140 // there is no reason to duplicate. 15141 auto &TM = getTargetMachine(); 15142 if (!TM.Options.GuaranteedTailCallOpt && DisableSCO) 15143 return false; 15144 15145 // Can't tail call a function called indirectly, or if it has variadic args. 15146 const Function *Callee = CI->getCalledFunction(); 15147 if (!Callee || Callee->isVarArg()) 15148 return false; 15149 15150 // Make sure the callee and caller calling conventions are eligible for tco. 15151 if (!areCallingConvEligibleForTCO_64SVR4(Caller->getCallingConv(), 15152 CI->getCallingConv())) 15153 return false; 15154 15155 // If the function is local then we have a good chance at tail-calling it 15156 return getTargetMachine().shouldAssumeDSOLocal(*Caller->getParent(), Callee); 15157 } 15158 15159 bool PPCTargetLowering::hasBitPreservingFPLogic(EVT VT) const { 15160 if (!Subtarget.hasVSX()) 15161 return false; 15162 if (Subtarget.hasP9Vector() && VT == MVT::f128) 15163 return true; 15164 return VT == MVT::f32 || VT == MVT::f64 || 15165 VT == MVT::v4f32 || VT == MVT::v2f64; 15166 } 15167 15168 bool PPCTargetLowering:: 15169 isMaskAndCmp0FoldingBeneficial(const Instruction &AndI) const { 15170 const Value *Mask = AndI.getOperand(1); 15171 // If the mask is suitable for andi. or andis. we should sink the and. 15172 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Mask)) { 15173 // Can't handle constants wider than 64-bits. 15174 if (CI->getBitWidth() > 64) 15175 return false; 15176 int64_t ConstVal = CI->getZExtValue(); 15177 return isUInt<16>(ConstVal) || 15178 (isUInt<16>(ConstVal >> 16) && !(ConstVal & 0xFFFF)); 15179 } 15180 15181 // For non-constant masks, we can always use the record-form and. 15182 return true; 15183 } 15184 15185 // Transform (abs (sub (zext a), (zext b))) to (vabsd a b 0) 15186 // Transform (abs (sub (zext a), (zext_invec b))) to (vabsd a b 0) 15187 // Transform (abs (sub (zext_invec a), (zext_invec b))) to (vabsd a b 0) 15188 // Transform (abs (sub (zext_invec a), (zext b))) to (vabsd a b 0) 15189 // Transform (abs (sub a, b) to (vabsd a b 1)) if a & b of type v4i32 15190 SDValue PPCTargetLowering::combineABS(SDNode *N, DAGCombinerInfo &DCI) const { 15191 assert((N->getOpcode() == ISD::ABS) && "Need ABS node here"); 15192 assert(Subtarget.hasP9Altivec() && 15193 "Only combine this when P9 altivec supported!"); 15194 EVT VT = N->getValueType(0); 15195 if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8) 15196 return SDValue(); 15197 15198 SelectionDAG &DAG = DCI.DAG; 15199 SDLoc dl(N); 15200 if (N->getOperand(0).getOpcode() == ISD::SUB) { 15201 // Even for signed integers, if it's known to be positive (as signed 15202 // integer) due to zero-extended inputs. 15203 unsigned SubOpcd0 = N->getOperand(0)->getOperand(0).getOpcode(); 15204 unsigned SubOpcd1 = N->getOperand(0)->getOperand(1).getOpcode(); 15205 if ((SubOpcd0 == ISD::ZERO_EXTEND || 15206 SubOpcd0 == ISD::ZERO_EXTEND_VECTOR_INREG) && 15207 (SubOpcd1 == ISD::ZERO_EXTEND || 15208 SubOpcd1 == ISD::ZERO_EXTEND_VECTOR_INREG)) { 15209 return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(), 15210 N->getOperand(0)->getOperand(0), 15211 N->getOperand(0)->getOperand(1), 15212 DAG.getTargetConstant(0, dl, MVT::i32)); 15213 } 15214 15215 // For type v4i32, it can be optimized with xvnegsp + vabsduw 15216 if (N->getOperand(0).getValueType() == MVT::v4i32 && 15217 N->getOperand(0).hasOneUse()) { 15218 return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(), 15219 N->getOperand(0)->getOperand(0), 15220 N->getOperand(0)->getOperand(1), 15221 DAG.getTargetConstant(1, dl, MVT::i32)); 15222 } 15223 } 15224 15225 return SDValue(); 15226 } 15227 15228 // For type v4i32/v8ii16/v16i8, transform 15229 // from (vselect (setcc a, b, setugt), (sub a, b), (sub b, a)) to (vabsd a, b) 15230 // from (vselect (setcc a, b, setuge), (sub a, b), (sub b, a)) to (vabsd a, b) 15231 // from (vselect (setcc a, b, setult), (sub b, a), (sub a, b)) to (vabsd a, b) 15232 // from (vselect (setcc a, b, setule), (sub b, a), (sub a, b)) to (vabsd a, b) 15233 SDValue PPCTargetLowering::combineVSelect(SDNode *N, 15234 DAGCombinerInfo &DCI) const { 15235 assert((N->getOpcode() == ISD::VSELECT) && "Need VSELECT node here"); 15236 assert(Subtarget.hasP9Altivec() && 15237 "Only combine this when P9 altivec supported!"); 15238 15239 SelectionDAG &DAG = DCI.DAG; 15240 SDLoc dl(N); 15241 SDValue Cond = N->getOperand(0); 15242 SDValue TrueOpnd = N->getOperand(1); 15243 SDValue FalseOpnd = N->getOperand(2); 15244 EVT VT = N->getOperand(1).getValueType(); 15245 15246 if (Cond.getOpcode() != ISD::SETCC || TrueOpnd.getOpcode() != ISD::SUB || 15247 FalseOpnd.getOpcode() != ISD::SUB) 15248 return SDValue(); 15249 15250 // ABSD only available for type v4i32/v8i16/v16i8 15251 if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8) 15252 return SDValue(); 15253 15254 // At least to save one more dependent computation 15255 if (!(Cond.hasOneUse() || TrueOpnd.hasOneUse() || FalseOpnd.hasOneUse())) 15256 return SDValue(); 15257 15258 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get(); 15259 15260 // Can only handle unsigned comparison here 15261 switch (CC) { 15262 default: 15263 return SDValue(); 15264 case ISD::SETUGT: 15265 case ISD::SETUGE: 15266 break; 15267 case ISD::SETULT: 15268 case ISD::SETULE: 15269 std::swap(TrueOpnd, FalseOpnd); 15270 break; 15271 } 15272 15273 SDValue CmpOpnd1 = Cond.getOperand(0); 15274 SDValue CmpOpnd2 = Cond.getOperand(1); 15275 15276 // SETCC CmpOpnd1 CmpOpnd2 cond 15277 // TrueOpnd = CmpOpnd1 - CmpOpnd2 15278 // FalseOpnd = CmpOpnd2 - CmpOpnd1 15279 if (TrueOpnd.getOperand(0) == CmpOpnd1 && 15280 TrueOpnd.getOperand(1) == CmpOpnd2 && 15281 FalseOpnd.getOperand(0) == CmpOpnd2 && 15282 FalseOpnd.getOperand(1) == CmpOpnd1) { 15283 return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(1).getValueType(), 15284 CmpOpnd1, CmpOpnd2, 15285 DAG.getTargetConstant(0, dl, MVT::i32)); 15286 } 15287 15288 return SDValue(); 15289 } 15290