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 843 if (Subtarget.hasDirectMove()) 844 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom); 845 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom); 846 847 addRegisterClass(MVT::v2i64, &PPC::VSRCRegClass); 848 } 849 850 if (Subtarget.hasP8Altivec()) { 851 addRegisterClass(MVT::v2i64, &PPC::VRRCRegClass); 852 addRegisterClass(MVT::v1i128, &PPC::VRRCRegClass); 853 } 854 855 if (Subtarget.hasP9Vector()) { 856 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom); 857 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom); 858 859 // 128 bit shifts can be accomplished via 3 instructions for SHL and 860 // SRL, but not for SRA because of the instructions available: 861 // VS{RL} and VS{RL}O. 862 setOperationAction(ISD::SHL, MVT::v1i128, Legal); 863 setOperationAction(ISD::SRL, MVT::v1i128, Legal); 864 setOperationAction(ISD::SRA, MVT::v1i128, Expand); 865 866 if (EnableQuadPrecision) { 867 addRegisterClass(MVT::f128, &PPC::VRRCRegClass); 868 setOperationAction(ISD::FADD, MVT::f128, Legal); 869 setOperationAction(ISD::FSUB, MVT::f128, Legal); 870 setOperationAction(ISD::FDIV, MVT::f128, Legal); 871 setOperationAction(ISD::FMUL, MVT::f128, Legal); 872 setOperationAction(ISD::FP_EXTEND, MVT::f128, Legal); 873 // No extending loads to f128 on PPC. 874 for (MVT FPT : MVT::fp_valuetypes()) 875 setLoadExtAction(ISD::EXTLOAD, MVT::f128, FPT, Expand); 876 setOperationAction(ISD::FMA, MVT::f128, Legal); 877 setCondCodeAction(ISD::SETULT, MVT::f128, Expand); 878 setCondCodeAction(ISD::SETUGT, MVT::f128, Expand); 879 setCondCodeAction(ISD::SETUEQ, MVT::f128, Expand); 880 setCondCodeAction(ISD::SETOGE, MVT::f128, Expand); 881 setCondCodeAction(ISD::SETOLE, MVT::f128, Expand); 882 setCondCodeAction(ISD::SETONE, MVT::f128, Expand); 883 884 setOperationAction(ISD::FTRUNC, MVT::f128, Legal); 885 setOperationAction(ISD::FRINT, MVT::f128, Legal); 886 setOperationAction(ISD::FFLOOR, MVT::f128, Legal); 887 setOperationAction(ISD::FCEIL, MVT::f128, Legal); 888 setOperationAction(ISD::FNEARBYINT, MVT::f128, Legal); 889 setOperationAction(ISD::FROUND, MVT::f128, Legal); 890 891 setOperationAction(ISD::SELECT, MVT::f128, Expand); 892 setOperationAction(ISD::FP_ROUND, MVT::f64, Legal); 893 setOperationAction(ISD::FP_ROUND, MVT::f32, Legal); 894 setTruncStoreAction(MVT::f128, MVT::f64, Expand); 895 setTruncStoreAction(MVT::f128, MVT::f32, Expand); 896 setOperationAction(ISD::BITCAST, MVT::i128, Custom); 897 // No implementation for these ops for PowerPC. 898 setOperationAction(ISD::FSIN , MVT::f128, Expand); 899 setOperationAction(ISD::FCOS , MVT::f128, Expand); 900 setOperationAction(ISD::FPOW, MVT::f128, Expand); 901 setOperationAction(ISD::FPOWI, MVT::f128, Expand); 902 setOperationAction(ISD::FREM, MVT::f128, Expand); 903 } 904 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom); 905 906 } 907 908 if (Subtarget.hasP9Altivec()) { 909 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom); 910 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom); 911 } 912 } 913 914 if (Subtarget.hasQPX()) { 915 setOperationAction(ISD::FADD, MVT::v4f64, Legal); 916 setOperationAction(ISD::FSUB, MVT::v4f64, Legal); 917 setOperationAction(ISD::FMUL, MVT::v4f64, Legal); 918 setOperationAction(ISD::FREM, MVT::v4f64, Expand); 919 920 setOperationAction(ISD::FCOPYSIGN, MVT::v4f64, Legal); 921 setOperationAction(ISD::FGETSIGN, MVT::v4f64, Expand); 922 923 setOperationAction(ISD::LOAD , MVT::v4f64, Custom); 924 setOperationAction(ISD::STORE , MVT::v4f64, Custom); 925 926 setTruncStoreAction(MVT::v4f64, MVT::v4f32, Custom); 927 setLoadExtAction(ISD::EXTLOAD, MVT::v4f64, MVT::v4f32, Custom); 928 929 if (!Subtarget.useCRBits()) 930 setOperationAction(ISD::SELECT, MVT::v4f64, Expand); 931 setOperationAction(ISD::VSELECT, MVT::v4f64, Legal); 932 933 setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f64, Legal); 934 setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f64, Expand); 935 setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f64, Expand); 936 setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f64, Expand); 937 setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f64, Custom); 938 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f64, Legal); 939 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f64, Custom); 940 941 setOperationAction(ISD::FP_TO_SINT , MVT::v4f64, Legal); 942 setOperationAction(ISD::FP_TO_UINT , MVT::v4f64, Expand); 943 944 setOperationAction(ISD::FP_ROUND , MVT::v4f32, Legal); 945 setOperationAction(ISD::FP_ROUND_INREG , MVT::v4f32, Expand); 946 setOperationAction(ISD::FP_EXTEND, MVT::v4f64, Legal); 947 948 setOperationAction(ISD::FNEG , MVT::v4f64, Legal); 949 setOperationAction(ISD::FABS , MVT::v4f64, Legal); 950 setOperationAction(ISD::FSIN , MVT::v4f64, Expand); 951 setOperationAction(ISD::FCOS , MVT::v4f64, Expand); 952 setOperationAction(ISD::FPOW , MVT::v4f64, Expand); 953 setOperationAction(ISD::FLOG , MVT::v4f64, Expand); 954 setOperationAction(ISD::FLOG2 , MVT::v4f64, Expand); 955 setOperationAction(ISD::FLOG10 , MVT::v4f64, Expand); 956 setOperationAction(ISD::FEXP , MVT::v4f64, Expand); 957 setOperationAction(ISD::FEXP2 , MVT::v4f64, Expand); 958 959 setOperationAction(ISD::FMINNUM, MVT::v4f64, Legal); 960 setOperationAction(ISD::FMAXNUM, MVT::v4f64, Legal); 961 962 setIndexedLoadAction(ISD::PRE_INC, MVT::v4f64, Legal); 963 setIndexedStoreAction(ISD::PRE_INC, MVT::v4f64, Legal); 964 965 addRegisterClass(MVT::v4f64, &PPC::QFRCRegClass); 966 967 setOperationAction(ISD::FADD, MVT::v4f32, Legal); 968 setOperationAction(ISD::FSUB, MVT::v4f32, Legal); 969 setOperationAction(ISD::FMUL, MVT::v4f32, Legal); 970 setOperationAction(ISD::FREM, MVT::v4f32, Expand); 971 972 setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Legal); 973 setOperationAction(ISD::FGETSIGN, MVT::v4f32, Expand); 974 975 setOperationAction(ISD::LOAD , MVT::v4f32, Custom); 976 setOperationAction(ISD::STORE , MVT::v4f32, Custom); 977 978 if (!Subtarget.useCRBits()) 979 setOperationAction(ISD::SELECT, MVT::v4f32, Expand); 980 setOperationAction(ISD::VSELECT, MVT::v4f32, Legal); 981 982 setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f32, Legal); 983 setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f32, Expand); 984 setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f32, Expand); 985 setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f32, Expand); 986 setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f32, Custom); 987 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal); 988 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom); 989 990 setOperationAction(ISD::FP_TO_SINT , MVT::v4f32, Legal); 991 setOperationAction(ISD::FP_TO_UINT , MVT::v4f32, Expand); 992 993 setOperationAction(ISD::FNEG , MVT::v4f32, Legal); 994 setOperationAction(ISD::FABS , MVT::v4f32, Legal); 995 setOperationAction(ISD::FSIN , MVT::v4f32, Expand); 996 setOperationAction(ISD::FCOS , MVT::v4f32, Expand); 997 setOperationAction(ISD::FPOW , MVT::v4f32, Expand); 998 setOperationAction(ISD::FLOG , MVT::v4f32, Expand); 999 setOperationAction(ISD::FLOG2 , MVT::v4f32, Expand); 1000 setOperationAction(ISD::FLOG10 , MVT::v4f32, Expand); 1001 setOperationAction(ISD::FEXP , MVT::v4f32, Expand); 1002 setOperationAction(ISD::FEXP2 , MVT::v4f32, Expand); 1003 1004 setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal); 1005 setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal); 1006 1007 setIndexedLoadAction(ISD::PRE_INC, MVT::v4f32, Legal); 1008 setIndexedStoreAction(ISD::PRE_INC, MVT::v4f32, Legal); 1009 1010 addRegisterClass(MVT::v4f32, &PPC::QSRCRegClass); 1011 1012 setOperationAction(ISD::AND , MVT::v4i1, Legal); 1013 setOperationAction(ISD::OR , MVT::v4i1, Legal); 1014 setOperationAction(ISD::XOR , MVT::v4i1, Legal); 1015 1016 if (!Subtarget.useCRBits()) 1017 setOperationAction(ISD::SELECT, MVT::v4i1, Expand); 1018 setOperationAction(ISD::VSELECT, MVT::v4i1, Legal); 1019 1020 setOperationAction(ISD::LOAD , MVT::v4i1, Custom); 1021 setOperationAction(ISD::STORE , MVT::v4i1, Custom); 1022 1023 setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4i1, Custom); 1024 setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4i1, Expand); 1025 setOperationAction(ISD::CONCAT_VECTORS , MVT::v4i1, Expand); 1026 setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4i1, Expand); 1027 setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4i1, Custom); 1028 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i1, Expand); 1029 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i1, Custom); 1030 1031 setOperationAction(ISD::SINT_TO_FP, MVT::v4i1, Custom); 1032 setOperationAction(ISD::UINT_TO_FP, MVT::v4i1, Custom); 1033 1034 addRegisterClass(MVT::v4i1, &PPC::QBRCRegClass); 1035 1036 setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal); 1037 setOperationAction(ISD::FCEIL, MVT::v4f64, Legal); 1038 setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal); 1039 setOperationAction(ISD::FROUND, MVT::v4f64, Legal); 1040 1041 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal); 1042 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal); 1043 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal); 1044 setOperationAction(ISD::FROUND, MVT::v4f32, Legal); 1045 1046 setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Expand); 1047 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand); 1048 1049 // These need to set FE_INEXACT, and so cannot be vectorized here. 1050 setOperationAction(ISD::FRINT, MVT::v4f64, Expand); 1051 setOperationAction(ISD::FRINT, MVT::v4f32, Expand); 1052 1053 if (TM.Options.UnsafeFPMath) { 1054 setOperationAction(ISD::FDIV, MVT::v4f64, Legal); 1055 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal); 1056 1057 setOperationAction(ISD::FDIV, MVT::v4f32, Legal); 1058 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal); 1059 } else { 1060 setOperationAction(ISD::FDIV, MVT::v4f64, Expand); 1061 setOperationAction(ISD::FSQRT, MVT::v4f64, Expand); 1062 1063 setOperationAction(ISD::FDIV, MVT::v4f32, Expand); 1064 setOperationAction(ISD::FSQRT, MVT::v4f32, Expand); 1065 } 1066 } 1067 1068 if (Subtarget.has64BitSupport()) 1069 setOperationAction(ISD::PREFETCH, MVT::Other, Legal); 1070 1071 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, isPPC64 ? Legal : Custom); 1072 1073 if (!isPPC64) { 1074 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Expand); 1075 setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand); 1076 } 1077 1078 setBooleanContents(ZeroOrOneBooleanContent); 1079 1080 if (Subtarget.hasAltivec()) { 1081 // Altivec instructions set fields to all zeros or all ones. 1082 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent); 1083 } 1084 1085 if (!isPPC64) { 1086 // These libcalls are not available in 32-bit. 1087 setLibcallName(RTLIB::SHL_I128, nullptr); 1088 setLibcallName(RTLIB::SRL_I128, nullptr); 1089 setLibcallName(RTLIB::SRA_I128, nullptr); 1090 } 1091 1092 setStackPointerRegisterToSaveRestore(isPPC64 ? PPC::X1 : PPC::R1); 1093 1094 // We have target-specific dag combine patterns for the following nodes: 1095 setTargetDAGCombine(ISD::ADD); 1096 setTargetDAGCombine(ISD::SHL); 1097 setTargetDAGCombine(ISD::SRA); 1098 setTargetDAGCombine(ISD::SRL); 1099 setTargetDAGCombine(ISD::MUL); 1100 setTargetDAGCombine(ISD::SINT_TO_FP); 1101 setTargetDAGCombine(ISD::BUILD_VECTOR); 1102 if (Subtarget.hasFPCVT()) 1103 setTargetDAGCombine(ISD::UINT_TO_FP); 1104 setTargetDAGCombine(ISD::LOAD); 1105 setTargetDAGCombine(ISD::STORE); 1106 setTargetDAGCombine(ISD::BR_CC); 1107 if (Subtarget.useCRBits()) 1108 setTargetDAGCombine(ISD::BRCOND); 1109 setTargetDAGCombine(ISD::BSWAP); 1110 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN); 1111 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN); 1112 setTargetDAGCombine(ISD::INTRINSIC_VOID); 1113 1114 setTargetDAGCombine(ISD::SIGN_EXTEND); 1115 setTargetDAGCombine(ISD::ZERO_EXTEND); 1116 setTargetDAGCombine(ISD::ANY_EXTEND); 1117 1118 setTargetDAGCombine(ISD::TRUNCATE); 1119 1120 if (Subtarget.useCRBits()) { 1121 setTargetDAGCombine(ISD::TRUNCATE); 1122 setTargetDAGCombine(ISD::SETCC); 1123 setTargetDAGCombine(ISD::SELECT_CC); 1124 } 1125 1126 // Use reciprocal estimates. 1127 if (TM.Options.UnsafeFPMath) { 1128 setTargetDAGCombine(ISD::FDIV); 1129 setTargetDAGCombine(ISD::FSQRT); 1130 } 1131 1132 if (Subtarget.hasP9Altivec()) { 1133 setTargetDAGCombine(ISD::ABS); 1134 setTargetDAGCombine(ISD::VSELECT); 1135 } 1136 1137 // Darwin long double math library functions have $LDBL128 appended. 1138 if (Subtarget.isDarwin()) { 1139 setLibcallName(RTLIB::COS_PPCF128, "cosl$LDBL128"); 1140 setLibcallName(RTLIB::POW_PPCF128, "powl$LDBL128"); 1141 setLibcallName(RTLIB::REM_PPCF128, "fmodl$LDBL128"); 1142 setLibcallName(RTLIB::SIN_PPCF128, "sinl$LDBL128"); 1143 setLibcallName(RTLIB::SQRT_PPCF128, "sqrtl$LDBL128"); 1144 setLibcallName(RTLIB::LOG_PPCF128, "logl$LDBL128"); 1145 setLibcallName(RTLIB::LOG2_PPCF128, "log2l$LDBL128"); 1146 setLibcallName(RTLIB::LOG10_PPCF128, "log10l$LDBL128"); 1147 setLibcallName(RTLIB::EXP_PPCF128, "expl$LDBL128"); 1148 setLibcallName(RTLIB::EXP2_PPCF128, "exp2l$LDBL128"); 1149 } 1150 1151 if (EnableQuadPrecision) { 1152 setLibcallName(RTLIB::LOG_F128, "logf128"); 1153 setLibcallName(RTLIB::LOG2_F128, "log2f128"); 1154 setLibcallName(RTLIB::LOG10_F128, "log10f128"); 1155 setLibcallName(RTLIB::EXP_F128, "expf128"); 1156 setLibcallName(RTLIB::EXP2_F128, "exp2f128"); 1157 setLibcallName(RTLIB::SIN_F128, "sinf128"); 1158 setLibcallName(RTLIB::COS_F128, "cosf128"); 1159 setLibcallName(RTLIB::POW_F128, "powf128"); 1160 setLibcallName(RTLIB::FMIN_F128, "fminf128"); 1161 setLibcallName(RTLIB::FMAX_F128, "fmaxf128"); 1162 setLibcallName(RTLIB::POWI_F128, "__powikf2"); 1163 setLibcallName(RTLIB::REM_F128, "fmodf128"); 1164 } 1165 1166 // With 32 condition bits, we don't need to sink (and duplicate) compares 1167 // aggressively in CodeGenPrep. 1168 if (Subtarget.useCRBits()) { 1169 setHasMultipleConditionRegisters(); 1170 setJumpIsExpensive(); 1171 } 1172 1173 setMinFunctionAlignment(2); 1174 if (Subtarget.isDarwin()) 1175 setPrefFunctionAlignment(4); 1176 1177 switch (Subtarget.getDarwinDirective()) { 1178 default: break; 1179 case PPC::DIR_970: 1180 case PPC::DIR_A2: 1181 case PPC::DIR_E500: 1182 case PPC::DIR_E500mc: 1183 case PPC::DIR_E5500: 1184 case PPC::DIR_PWR4: 1185 case PPC::DIR_PWR5: 1186 case PPC::DIR_PWR5X: 1187 case PPC::DIR_PWR6: 1188 case PPC::DIR_PWR6X: 1189 case PPC::DIR_PWR7: 1190 case PPC::DIR_PWR8: 1191 case PPC::DIR_PWR9: 1192 setPrefFunctionAlignment(4); 1193 setPrefLoopAlignment(4); 1194 break; 1195 } 1196 1197 if (Subtarget.enableMachineScheduler()) 1198 setSchedulingPreference(Sched::Source); 1199 else 1200 setSchedulingPreference(Sched::Hybrid); 1201 1202 computeRegisterProperties(STI.getRegisterInfo()); 1203 1204 // The Freescale cores do better with aggressive inlining of memcpy and 1205 // friends. GCC uses same threshold of 128 bytes (= 32 word stores). 1206 if (Subtarget.getDarwinDirective() == PPC::DIR_E500mc || 1207 Subtarget.getDarwinDirective() == PPC::DIR_E5500) { 1208 MaxStoresPerMemset = 32; 1209 MaxStoresPerMemsetOptSize = 16; 1210 MaxStoresPerMemcpy = 32; 1211 MaxStoresPerMemcpyOptSize = 8; 1212 MaxStoresPerMemmove = 32; 1213 MaxStoresPerMemmoveOptSize = 8; 1214 } else if (Subtarget.getDarwinDirective() == PPC::DIR_A2) { 1215 // The A2 also benefits from (very) aggressive inlining of memcpy and 1216 // friends. The overhead of a the function call, even when warm, can be 1217 // over one hundred cycles. 1218 MaxStoresPerMemset = 128; 1219 MaxStoresPerMemcpy = 128; 1220 MaxStoresPerMemmove = 128; 1221 MaxLoadsPerMemcmp = 128; 1222 } else { 1223 MaxLoadsPerMemcmp = 8; 1224 MaxLoadsPerMemcmpOptSize = 4; 1225 } 1226 } 1227 1228 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine 1229 /// the desired ByVal argument alignment. 1230 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign, 1231 unsigned MaxMaxAlign) { 1232 if (MaxAlign == MaxMaxAlign) 1233 return; 1234 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) { 1235 if (MaxMaxAlign >= 32 && VTy->getBitWidth() >= 256) 1236 MaxAlign = 32; 1237 else if (VTy->getBitWidth() >= 128 && MaxAlign < 16) 1238 MaxAlign = 16; 1239 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) { 1240 unsigned EltAlign = 0; 1241 getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign); 1242 if (EltAlign > MaxAlign) 1243 MaxAlign = EltAlign; 1244 } else if (StructType *STy = dyn_cast<StructType>(Ty)) { 1245 for (auto *EltTy : STy->elements()) { 1246 unsigned EltAlign = 0; 1247 getMaxByValAlign(EltTy, EltAlign, MaxMaxAlign); 1248 if (EltAlign > MaxAlign) 1249 MaxAlign = EltAlign; 1250 if (MaxAlign == MaxMaxAlign) 1251 break; 1252 } 1253 } 1254 } 1255 1256 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate 1257 /// function arguments in the caller parameter area. 1258 unsigned PPCTargetLowering::getByValTypeAlignment(Type *Ty, 1259 const DataLayout &DL) const { 1260 // Darwin passes everything on 4 byte boundary. 1261 if (Subtarget.isDarwin()) 1262 return 4; 1263 1264 // 16byte and wider vectors are passed on 16byte boundary. 1265 // The rest is 8 on PPC64 and 4 on PPC32 boundary. 1266 unsigned Align = Subtarget.isPPC64() ? 8 : 4; 1267 if (Subtarget.hasAltivec() || Subtarget.hasQPX()) 1268 getMaxByValAlign(Ty, Align, Subtarget.hasQPX() ? 32 : 16); 1269 return Align; 1270 } 1271 1272 bool PPCTargetLowering::useSoftFloat() const { 1273 return Subtarget.useSoftFloat(); 1274 } 1275 1276 bool PPCTargetLowering::hasSPE() const { 1277 return Subtarget.hasSPE(); 1278 } 1279 1280 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const { 1281 switch ((PPCISD::NodeType)Opcode) { 1282 case PPCISD::FIRST_NUMBER: break; 1283 case PPCISD::FSEL: return "PPCISD::FSEL"; 1284 case PPCISD::FCFID: return "PPCISD::FCFID"; 1285 case PPCISD::FCFIDU: return "PPCISD::FCFIDU"; 1286 case PPCISD::FCFIDS: return "PPCISD::FCFIDS"; 1287 case PPCISD::FCFIDUS: return "PPCISD::FCFIDUS"; 1288 case PPCISD::FCTIDZ: return "PPCISD::FCTIDZ"; 1289 case PPCISD::FCTIWZ: return "PPCISD::FCTIWZ"; 1290 case PPCISD::FCTIDUZ: return "PPCISD::FCTIDUZ"; 1291 case PPCISD::FCTIWUZ: return "PPCISD::FCTIWUZ"; 1292 case PPCISD::FP_TO_UINT_IN_VSR: 1293 return "PPCISD::FP_TO_UINT_IN_VSR,"; 1294 case PPCISD::FP_TO_SINT_IN_VSR: 1295 return "PPCISD::FP_TO_SINT_IN_VSR"; 1296 case PPCISD::FRE: return "PPCISD::FRE"; 1297 case PPCISD::FRSQRTE: return "PPCISD::FRSQRTE"; 1298 case PPCISD::STFIWX: return "PPCISD::STFIWX"; 1299 case PPCISD::VMADDFP: return "PPCISD::VMADDFP"; 1300 case PPCISD::VNMSUBFP: return "PPCISD::VNMSUBFP"; 1301 case PPCISD::VPERM: return "PPCISD::VPERM"; 1302 case PPCISD::XXSPLT: return "PPCISD::XXSPLT"; 1303 case PPCISD::VECINSERT: return "PPCISD::VECINSERT"; 1304 case PPCISD::XXREVERSE: return "PPCISD::XXREVERSE"; 1305 case PPCISD::XXPERMDI: return "PPCISD::XXPERMDI"; 1306 case PPCISD::VECSHL: return "PPCISD::VECSHL"; 1307 case PPCISD::CMPB: return "PPCISD::CMPB"; 1308 case PPCISD::Hi: return "PPCISD::Hi"; 1309 case PPCISD::Lo: return "PPCISD::Lo"; 1310 case PPCISD::TOC_ENTRY: return "PPCISD::TOC_ENTRY"; 1311 case PPCISD::ATOMIC_CMP_SWAP_8: return "PPCISD::ATOMIC_CMP_SWAP_8"; 1312 case PPCISD::ATOMIC_CMP_SWAP_16: return "PPCISD::ATOMIC_CMP_SWAP_16"; 1313 case PPCISD::DYNALLOC: return "PPCISD::DYNALLOC"; 1314 case PPCISD::DYNAREAOFFSET: return "PPCISD::DYNAREAOFFSET"; 1315 case PPCISD::GlobalBaseReg: return "PPCISD::GlobalBaseReg"; 1316 case PPCISD::SRL: return "PPCISD::SRL"; 1317 case PPCISD::SRA: return "PPCISD::SRA"; 1318 case PPCISD::SHL: return "PPCISD::SHL"; 1319 case PPCISD::SRA_ADDZE: return "PPCISD::SRA_ADDZE"; 1320 case PPCISD::CALL: return "PPCISD::CALL"; 1321 case PPCISD::CALL_NOP: return "PPCISD::CALL_NOP"; 1322 case PPCISD::MTCTR: return "PPCISD::MTCTR"; 1323 case PPCISD::BCTRL: return "PPCISD::BCTRL"; 1324 case PPCISD::BCTRL_LOAD_TOC: return "PPCISD::BCTRL_LOAD_TOC"; 1325 case PPCISD::RET_FLAG: return "PPCISD::RET_FLAG"; 1326 case PPCISD::READ_TIME_BASE: return "PPCISD::READ_TIME_BASE"; 1327 case PPCISD::EH_SJLJ_SETJMP: return "PPCISD::EH_SJLJ_SETJMP"; 1328 case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP"; 1329 case PPCISD::MFOCRF: return "PPCISD::MFOCRF"; 1330 case PPCISD::MFVSR: return "PPCISD::MFVSR"; 1331 case PPCISD::MTVSRA: return "PPCISD::MTVSRA"; 1332 case PPCISD::MTVSRZ: return "PPCISD::MTVSRZ"; 1333 case PPCISD::SINT_VEC_TO_FP: return "PPCISD::SINT_VEC_TO_FP"; 1334 case PPCISD::UINT_VEC_TO_FP: return "PPCISD::UINT_VEC_TO_FP"; 1335 case PPCISD::ANDIo_1_EQ_BIT: return "PPCISD::ANDIo_1_EQ_BIT"; 1336 case PPCISD::ANDIo_1_GT_BIT: return "PPCISD::ANDIo_1_GT_BIT"; 1337 case PPCISD::VCMP: return "PPCISD::VCMP"; 1338 case PPCISD::VCMPo: return "PPCISD::VCMPo"; 1339 case PPCISD::LBRX: return "PPCISD::LBRX"; 1340 case PPCISD::STBRX: return "PPCISD::STBRX"; 1341 case PPCISD::LFIWAX: return "PPCISD::LFIWAX"; 1342 case PPCISD::LFIWZX: return "PPCISD::LFIWZX"; 1343 case PPCISD::LXSIZX: return "PPCISD::LXSIZX"; 1344 case PPCISD::STXSIX: return "PPCISD::STXSIX"; 1345 case PPCISD::VEXTS: return "PPCISD::VEXTS"; 1346 case PPCISD::SExtVElems: return "PPCISD::SExtVElems"; 1347 case PPCISD::LXVD2X: return "PPCISD::LXVD2X"; 1348 case PPCISD::STXVD2X: return "PPCISD::STXVD2X"; 1349 case PPCISD::ST_VSR_SCAL_INT: 1350 return "PPCISD::ST_VSR_SCAL_INT"; 1351 case PPCISD::COND_BRANCH: return "PPCISD::COND_BRANCH"; 1352 case PPCISD::BDNZ: return "PPCISD::BDNZ"; 1353 case PPCISD::BDZ: return "PPCISD::BDZ"; 1354 case PPCISD::MFFS: return "PPCISD::MFFS"; 1355 case PPCISD::FADDRTZ: return "PPCISD::FADDRTZ"; 1356 case PPCISD::TC_RETURN: return "PPCISD::TC_RETURN"; 1357 case PPCISD::CR6SET: return "PPCISD::CR6SET"; 1358 case PPCISD::CR6UNSET: return "PPCISD::CR6UNSET"; 1359 case PPCISD::PPC32_GOT: return "PPCISD::PPC32_GOT"; 1360 case PPCISD::PPC32_PICGOT: return "PPCISD::PPC32_PICGOT"; 1361 case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA"; 1362 case PPCISD::LD_GOT_TPREL_L: return "PPCISD::LD_GOT_TPREL_L"; 1363 case PPCISD::ADD_TLS: return "PPCISD::ADD_TLS"; 1364 case PPCISD::ADDIS_TLSGD_HA: return "PPCISD::ADDIS_TLSGD_HA"; 1365 case PPCISD::ADDI_TLSGD_L: return "PPCISD::ADDI_TLSGD_L"; 1366 case PPCISD::GET_TLS_ADDR: return "PPCISD::GET_TLS_ADDR"; 1367 case PPCISD::ADDI_TLSGD_L_ADDR: return "PPCISD::ADDI_TLSGD_L_ADDR"; 1368 case PPCISD::ADDIS_TLSLD_HA: return "PPCISD::ADDIS_TLSLD_HA"; 1369 case PPCISD::ADDI_TLSLD_L: return "PPCISD::ADDI_TLSLD_L"; 1370 case PPCISD::GET_TLSLD_ADDR: return "PPCISD::GET_TLSLD_ADDR"; 1371 case PPCISD::ADDI_TLSLD_L_ADDR: return "PPCISD::ADDI_TLSLD_L_ADDR"; 1372 case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA"; 1373 case PPCISD::ADDI_DTPREL_L: return "PPCISD::ADDI_DTPREL_L"; 1374 case PPCISD::VADD_SPLAT: return "PPCISD::VADD_SPLAT"; 1375 case PPCISD::SC: return "PPCISD::SC"; 1376 case PPCISD::CLRBHRB: return "PPCISD::CLRBHRB"; 1377 case PPCISD::MFBHRBE: return "PPCISD::MFBHRBE"; 1378 case PPCISD::RFEBB: return "PPCISD::RFEBB"; 1379 case PPCISD::XXSWAPD: return "PPCISD::XXSWAPD"; 1380 case PPCISD::SWAP_NO_CHAIN: return "PPCISD::SWAP_NO_CHAIN"; 1381 case PPCISD::VABSD: return "PPCISD::VABSD"; 1382 case PPCISD::QVFPERM: return "PPCISD::QVFPERM"; 1383 case PPCISD::QVGPCI: return "PPCISD::QVGPCI"; 1384 case PPCISD::QVALIGNI: return "PPCISD::QVALIGNI"; 1385 case PPCISD::QVESPLATI: return "PPCISD::QVESPLATI"; 1386 case PPCISD::QBFLT: return "PPCISD::QBFLT"; 1387 case PPCISD::QVLFSb: return "PPCISD::QVLFSb"; 1388 case PPCISD::BUILD_FP128: return "PPCISD::BUILD_FP128"; 1389 case PPCISD::BUILD_SPE64: return "PPCISD::BUILD_SPE64"; 1390 case PPCISD::EXTRACT_SPE: return "PPCISD::EXTRACT_SPE"; 1391 case PPCISD::EXTSWSLI: return "PPCISD::EXTSWSLI"; 1392 case PPCISD::LD_VSX_LH: return "PPCISD::LD_VSX_LH"; 1393 case PPCISD::FP_EXTEND_LH: return "PPCISD::FP_EXTEND_LH"; 1394 } 1395 return nullptr; 1396 } 1397 1398 EVT PPCTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &C, 1399 EVT VT) const { 1400 if (!VT.isVector()) 1401 return Subtarget.useCRBits() ? MVT::i1 : MVT::i32; 1402 1403 if (Subtarget.hasQPX()) 1404 return EVT::getVectorVT(C, MVT::i1, VT.getVectorNumElements()); 1405 1406 return VT.changeVectorElementTypeToInteger(); 1407 } 1408 1409 bool PPCTargetLowering::enableAggressiveFMAFusion(EVT VT) const { 1410 assert(VT.isFloatingPoint() && "Non-floating-point FMA?"); 1411 return true; 1412 } 1413 1414 //===----------------------------------------------------------------------===// 1415 // Node matching predicates, for use by the tblgen matching code. 1416 //===----------------------------------------------------------------------===// 1417 1418 /// isFloatingPointZero - Return true if this is 0.0 or -0.0. 1419 static bool isFloatingPointZero(SDValue Op) { 1420 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) 1421 return CFP->getValueAPF().isZero(); 1422 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) { 1423 // Maybe this has already been legalized into the constant pool? 1424 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1))) 1425 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal())) 1426 return CFP->getValueAPF().isZero(); 1427 } 1428 return false; 1429 } 1430 1431 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode. Return 1432 /// true if Op is undef or if it matches the specified value. 1433 static bool isConstantOrUndef(int Op, int Val) { 1434 return Op < 0 || Op == Val; 1435 } 1436 1437 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a 1438 /// VPKUHUM instruction. 1439 /// The ShuffleKind distinguishes between big-endian operations with 1440 /// two different inputs (0), either-endian operations with two identical 1441 /// inputs (1), and little-endian operations with two different inputs (2). 1442 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td). 1443 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind, 1444 SelectionDAG &DAG) { 1445 bool IsLE = DAG.getDataLayout().isLittleEndian(); 1446 if (ShuffleKind == 0) { 1447 if (IsLE) 1448 return false; 1449 for (unsigned i = 0; i != 16; ++i) 1450 if (!isConstantOrUndef(N->getMaskElt(i), i*2+1)) 1451 return false; 1452 } else if (ShuffleKind == 2) { 1453 if (!IsLE) 1454 return false; 1455 for (unsigned i = 0; i != 16; ++i) 1456 if (!isConstantOrUndef(N->getMaskElt(i), i*2)) 1457 return false; 1458 } else if (ShuffleKind == 1) { 1459 unsigned j = IsLE ? 0 : 1; 1460 for (unsigned i = 0; i != 8; ++i) 1461 if (!isConstantOrUndef(N->getMaskElt(i), i*2+j) || 1462 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j)) 1463 return false; 1464 } 1465 return true; 1466 } 1467 1468 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a 1469 /// VPKUWUM instruction. 1470 /// The ShuffleKind distinguishes between big-endian operations with 1471 /// two different inputs (0), either-endian operations with two identical 1472 /// inputs (1), and little-endian operations with two different inputs (2). 1473 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td). 1474 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind, 1475 SelectionDAG &DAG) { 1476 bool IsLE = DAG.getDataLayout().isLittleEndian(); 1477 if (ShuffleKind == 0) { 1478 if (IsLE) 1479 return false; 1480 for (unsigned i = 0; i != 16; i += 2) 1481 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+2) || 1482 !isConstantOrUndef(N->getMaskElt(i+1), i*2+3)) 1483 return false; 1484 } else if (ShuffleKind == 2) { 1485 if (!IsLE) 1486 return false; 1487 for (unsigned i = 0; i != 16; i += 2) 1488 if (!isConstantOrUndef(N->getMaskElt(i ), i*2) || 1489 !isConstantOrUndef(N->getMaskElt(i+1), i*2+1)) 1490 return false; 1491 } else if (ShuffleKind == 1) { 1492 unsigned j = IsLE ? 0 : 2; 1493 for (unsigned i = 0; i != 8; i += 2) 1494 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+j) || 1495 !isConstantOrUndef(N->getMaskElt(i+1), i*2+j+1) || 1496 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j) || 1497 !isConstantOrUndef(N->getMaskElt(i+9), i*2+j+1)) 1498 return false; 1499 } 1500 return true; 1501 } 1502 1503 /// isVPKUDUMShuffleMask - Return true if this is the shuffle mask for a 1504 /// VPKUDUM instruction, AND the VPKUDUM instruction exists for the 1505 /// current subtarget. 1506 /// 1507 /// The ShuffleKind distinguishes between big-endian operations with 1508 /// two different inputs (0), either-endian operations with two identical 1509 /// inputs (1), and little-endian operations with two different inputs (2). 1510 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td). 1511 bool PPC::isVPKUDUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind, 1512 SelectionDAG &DAG) { 1513 const PPCSubtarget& Subtarget = 1514 static_cast<const PPCSubtarget&>(DAG.getSubtarget()); 1515 if (!Subtarget.hasP8Vector()) 1516 return false; 1517 1518 bool IsLE = DAG.getDataLayout().isLittleEndian(); 1519 if (ShuffleKind == 0) { 1520 if (IsLE) 1521 return false; 1522 for (unsigned i = 0; i != 16; i += 4) 1523 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+4) || 1524 !isConstantOrUndef(N->getMaskElt(i+1), i*2+5) || 1525 !isConstantOrUndef(N->getMaskElt(i+2), i*2+6) || 1526 !isConstantOrUndef(N->getMaskElt(i+3), i*2+7)) 1527 return false; 1528 } else if (ShuffleKind == 2) { 1529 if (!IsLE) 1530 return false; 1531 for (unsigned i = 0; i != 16; i += 4) 1532 if (!isConstantOrUndef(N->getMaskElt(i ), i*2) || 1533 !isConstantOrUndef(N->getMaskElt(i+1), i*2+1) || 1534 !isConstantOrUndef(N->getMaskElt(i+2), i*2+2) || 1535 !isConstantOrUndef(N->getMaskElt(i+3), i*2+3)) 1536 return false; 1537 } else if (ShuffleKind == 1) { 1538 unsigned j = IsLE ? 0 : 4; 1539 for (unsigned i = 0; i != 8; i += 4) 1540 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+j) || 1541 !isConstantOrUndef(N->getMaskElt(i+1), i*2+j+1) || 1542 !isConstantOrUndef(N->getMaskElt(i+2), i*2+j+2) || 1543 !isConstantOrUndef(N->getMaskElt(i+3), i*2+j+3) || 1544 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j) || 1545 !isConstantOrUndef(N->getMaskElt(i+9), i*2+j+1) || 1546 !isConstantOrUndef(N->getMaskElt(i+10), i*2+j+2) || 1547 !isConstantOrUndef(N->getMaskElt(i+11), i*2+j+3)) 1548 return false; 1549 } 1550 return true; 1551 } 1552 1553 /// isVMerge - Common function, used to match vmrg* shuffles. 1554 /// 1555 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize, 1556 unsigned LHSStart, unsigned RHSStart) { 1557 if (N->getValueType(0) != MVT::v16i8) 1558 return false; 1559 assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) && 1560 "Unsupported merge size!"); 1561 1562 for (unsigned i = 0; i != 8/UnitSize; ++i) // Step over units 1563 for (unsigned j = 0; j != UnitSize; ++j) { // Step over bytes within unit 1564 if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j), 1565 LHSStart+j+i*UnitSize) || 1566 !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j), 1567 RHSStart+j+i*UnitSize)) 1568 return false; 1569 } 1570 return true; 1571 } 1572 1573 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for 1574 /// a VMRGL* instruction with the specified unit size (1,2 or 4 bytes). 1575 /// The ShuffleKind distinguishes between big-endian merges with two 1576 /// different inputs (0), either-endian merges with two identical inputs (1), 1577 /// and little-endian merges with two different inputs (2). For the latter, 1578 /// the input operands are swapped (see PPCInstrAltivec.td). 1579 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize, 1580 unsigned ShuffleKind, SelectionDAG &DAG) { 1581 if (DAG.getDataLayout().isLittleEndian()) { 1582 if (ShuffleKind == 1) // unary 1583 return isVMerge(N, UnitSize, 0, 0); 1584 else if (ShuffleKind == 2) // swapped 1585 return isVMerge(N, UnitSize, 0, 16); 1586 else 1587 return false; 1588 } else { 1589 if (ShuffleKind == 1) // unary 1590 return isVMerge(N, UnitSize, 8, 8); 1591 else if (ShuffleKind == 0) // normal 1592 return isVMerge(N, UnitSize, 8, 24); 1593 else 1594 return false; 1595 } 1596 } 1597 1598 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for 1599 /// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes). 1600 /// The ShuffleKind distinguishes between big-endian merges with two 1601 /// different inputs (0), either-endian merges with two identical inputs (1), 1602 /// and little-endian merges with two different inputs (2). For the latter, 1603 /// the input operands are swapped (see PPCInstrAltivec.td). 1604 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize, 1605 unsigned ShuffleKind, SelectionDAG &DAG) { 1606 if (DAG.getDataLayout().isLittleEndian()) { 1607 if (ShuffleKind == 1) // unary 1608 return isVMerge(N, UnitSize, 8, 8); 1609 else if (ShuffleKind == 2) // swapped 1610 return isVMerge(N, UnitSize, 8, 24); 1611 else 1612 return false; 1613 } else { 1614 if (ShuffleKind == 1) // unary 1615 return isVMerge(N, UnitSize, 0, 0); 1616 else if (ShuffleKind == 0) // normal 1617 return isVMerge(N, UnitSize, 0, 16); 1618 else 1619 return false; 1620 } 1621 } 1622 1623 /** 1624 * Common function used to match vmrgew and vmrgow shuffles 1625 * 1626 * The indexOffset determines whether to look for even or odd words in 1627 * the shuffle mask. This is based on the of the endianness of the target 1628 * machine. 1629 * - Little Endian: 1630 * - Use offset of 0 to check for odd elements 1631 * - Use offset of 4 to check for even elements 1632 * - Big Endian: 1633 * - Use offset of 0 to check for even elements 1634 * - Use offset of 4 to check for odd elements 1635 * A detailed description of the vector element ordering for little endian and 1636 * big endian can be found at 1637 * http://www.ibm.com/developerworks/library/l-ibm-xl-c-cpp-compiler/index.html 1638 * Targeting your applications - what little endian and big endian IBM XL C/C++ 1639 * compiler differences mean to you 1640 * 1641 * The mask to the shuffle vector instruction specifies the indices of the 1642 * elements from the two input vectors to place in the result. The elements are 1643 * numbered in array-access order, starting with the first vector. These vectors 1644 * are always of type v16i8, thus each vector will contain 16 elements of size 1645 * 8. More info on the shuffle vector can be found in the 1646 * http://llvm.org/docs/LangRef.html#shufflevector-instruction 1647 * Language Reference. 1648 * 1649 * The RHSStartValue indicates whether the same input vectors are used (unary) 1650 * or two different input vectors are used, based on the following: 1651 * - If the instruction uses the same vector for both inputs, the range of the 1652 * indices will be 0 to 15. In this case, the RHSStart value passed should 1653 * be 0. 1654 * - If the instruction has two different vectors then the range of the 1655 * indices will be 0 to 31. In this case, the RHSStart value passed should 1656 * be 16 (indices 0-15 specify elements in the first vector while indices 16 1657 * to 31 specify elements in the second vector). 1658 * 1659 * \param[in] N The shuffle vector SD Node to analyze 1660 * \param[in] IndexOffset Specifies whether to look for even or odd elements 1661 * \param[in] RHSStartValue Specifies the starting index for the righthand input 1662 * vector to the shuffle_vector instruction 1663 * \return true iff this shuffle vector represents an even or odd word merge 1664 */ 1665 static bool isVMerge(ShuffleVectorSDNode *N, unsigned IndexOffset, 1666 unsigned RHSStartValue) { 1667 if (N->getValueType(0) != MVT::v16i8) 1668 return false; 1669 1670 for (unsigned i = 0; i < 2; ++i) 1671 for (unsigned j = 0; j < 4; ++j) 1672 if (!isConstantOrUndef(N->getMaskElt(i*4+j), 1673 i*RHSStartValue+j+IndexOffset) || 1674 !isConstantOrUndef(N->getMaskElt(i*4+j+8), 1675 i*RHSStartValue+j+IndexOffset+8)) 1676 return false; 1677 return true; 1678 } 1679 1680 /** 1681 * Determine if the specified shuffle mask is suitable for the vmrgew or 1682 * vmrgow instructions. 1683 * 1684 * \param[in] N The shuffle vector SD Node to analyze 1685 * \param[in] CheckEven Check for an even merge (true) or an odd merge (false) 1686 * \param[in] ShuffleKind Identify the type of merge: 1687 * - 0 = big-endian merge with two different inputs; 1688 * - 1 = either-endian merge with two identical inputs; 1689 * - 2 = little-endian merge with two different inputs (inputs are swapped for 1690 * little-endian merges). 1691 * \param[in] DAG The current SelectionDAG 1692 * \return true iff this shuffle mask 1693 */ 1694 bool PPC::isVMRGEOShuffleMask(ShuffleVectorSDNode *N, bool CheckEven, 1695 unsigned ShuffleKind, SelectionDAG &DAG) { 1696 if (DAG.getDataLayout().isLittleEndian()) { 1697 unsigned indexOffset = CheckEven ? 4 : 0; 1698 if (ShuffleKind == 1) // Unary 1699 return isVMerge(N, indexOffset, 0); 1700 else if (ShuffleKind == 2) // swapped 1701 return isVMerge(N, indexOffset, 16); 1702 else 1703 return false; 1704 } 1705 else { 1706 unsigned indexOffset = CheckEven ? 0 : 4; 1707 if (ShuffleKind == 1) // Unary 1708 return isVMerge(N, indexOffset, 0); 1709 else if (ShuffleKind == 0) // Normal 1710 return isVMerge(N, indexOffset, 16); 1711 else 1712 return false; 1713 } 1714 return false; 1715 } 1716 1717 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift 1718 /// amount, otherwise return -1. 1719 /// The ShuffleKind distinguishes between big-endian operations with two 1720 /// different inputs (0), either-endian operations with two identical inputs 1721 /// (1), and little-endian operations with two different inputs (2). For the 1722 /// latter, the input operands are swapped (see PPCInstrAltivec.td). 1723 int PPC::isVSLDOIShuffleMask(SDNode *N, unsigned ShuffleKind, 1724 SelectionDAG &DAG) { 1725 if (N->getValueType(0) != MVT::v16i8) 1726 return -1; 1727 1728 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 1729 1730 // Find the first non-undef value in the shuffle mask. 1731 unsigned i; 1732 for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i) 1733 /*search*/; 1734 1735 if (i == 16) return -1; // all undef. 1736 1737 // Otherwise, check to see if the rest of the elements are consecutively 1738 // numbered from this value. 1739 unsigned ShiftAmt = SVOp->getMaskElt(i); 1740 if (ShiftAmt < i) return -1; 1741 1742 ShiftAmt -= i; 1743 bool isLE = DAG.getDataLayout().isLittleEndian(); 1744 1745 if ((ShuffleKind == 0 && !isLE) || (ShuffleKind == 2 && isLE)) { 1746 // Check the rest of the elements to see if they are consecutive. 1747 for (++i; i != 16; ++i) 1748 if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i)) 1749 return -1; 1750 } else if (ShuffleKind == 1) { 1751 // Check the rest of the elements to see if they are consecutive. 1752 for (++i; i != 16; ++i) 1753 if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15)) 1754 return -1; 1755 } else 1756 return -1; 1757 1758 if (isLE) 1759 ShiftAmt = 16 - ShiftAmt; 1760 1761 return ShiftAmt; 1762 } 1763 1764 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand 1765 /// specifies a splat of a single element that is suitable for input to 1766 /// VSPLTB/VSPLTH/VSPLTW. 1767 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) { 1768 assert(N->getValueType(0) == MVT::v16i8 && 1769 (EltSize == 1 || EltSize == 2 || EltSize == 4)); 1770 1771 // The consecutive indices need to specify an element, not part of two 1772 // different elements. So abandon ship early if this isn't the case. 1773 if (N->getMaskElt(0) % EltSize != 0) 1774 return false; 1775 1776 // This is a splat operation if each element of the permute is the same, and 1777 // if the value doesn't reference the second vector. 1778 unsigned ElementBase = N->getMaskElt(0); 1779 1780 // FIXME: Handle UNDEF elements too! 1781 if (ElementBase >= 16) 1782 return false; 1783 1784 // Check that the indices are consecutive, in the case of a multi-byte element 1785 // splatted with a v16i8 mask. 1786 for (unsigned i = 1; i != EltSize; ++i) 1787 if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase)) 1788 return false; 1789 1790 for (unsigned i = EltSize, e = 16; i != e; i += EltSize) { 1791 if (N->getMaskElt(i) < 0) continue; 1792 for (unsigned j = 0; j != EltSize; ++j) 1793 if (N->getMaskElt(i+j) != N->getMaskElt(j)) 1794 return false; 1795 } 1796 return true; 1797 } 1798 1799 /// Check that the mask is shuffling N byte elements. Within each N byte 1800 /// element of the mask, the indices could be either in increasing or 1801 /// decreasing order as long as they are consecutive. 1802 /// \param[in] N the shuffle vector SD Node to analyze 1803 /// \param[in] Width the element width in bytes, could be 2/4/8/16 (HalfWord/ 1804 /// Word/DoubleWord/QuadWord). 1805 /// \param[in] StepLen the delta indices number among the N byte element, if 1806 /// the mask is in increasing/decreasing order then it is 1/-1. 1807 /// \return true iff the mask is shuffling N byte elements. 1808 static bool isNByteElemShuffleMask(ShuffleVectorSDNode *N, unsigned Width, 1809 int StepLen) { 1810 assert((Width == 2 || Width == 4 || Width == 8 || Width == 16) && 1811 "Unexpected element width."); 1812 assert((StepLen == 1 || StepLen == -1) && "Unexpected element width."); 1813 1814 unsigned NumOfElem = 16 / Width; 1815 unsigned MaskVal[16]; // Width is never greater than 16 1816 for (unsigned i = 0; i < NumOfElem; ++i) { 1817 MaskVal[0] = N->getMaskElt(i * Width); 1818 if ((StepLen == 1) && (MaskVal[0] % Width)) { 1819 return false; 1820 } else if ((StepLen == -1) && ((MaskVal[0] + 1) % Width)) { 1821 return false; 1822 } 1823 1824 for (unsigned int j = 1; j < Width; ++j) { 1825 MaskVal[j] = N->getMaskElt(i * Width + j); 1826 if (MaskVal[j] != MaskVal[j-1] + StepLen) { 1827 return false; 1828 } 1829 } 1830 } 1831 1832 return true; 1833 } 1834 1835 bool PPC::isXXINSERTWMask(ShuffleVectorSDNode *N, unsigned &ShiftElts, 1836 unsigned &InsertAtByte, bool &Swap, bool IsLE) { 1837 if (!isNByteElemShuffleMask(N, 4, 1)) 1838 return false; 1839 1840 // Now we look at mask elements 0,4,8,12 1841 unsigned M0 = N->getMaskElt(0) / 4; 1842 unsigned M1 = N->getMaskElt(4) / 4; 1843 unsigned M2 = N->getMaskElt(8) / 4; 1844 unsigned M3 = N->getMaskElt(12) / 4; 1845 unsigned LittleEndianShifts[] = { 2, 1, 0, 3 }; 1846 unsigned BigEndianShifts[] = { 3, 0, 1, 2 }; 1847 1848 // Below, let H and L be arbitrary elements of the shuffle mask 1849 // where H is in the range [4,7] and L is in the range [0,3]. 1850 // H, 1, 2, 3 or L, 5, 6, 7 1851 if ((M0 > 3 && M1 == 1 && M2 == 2 && M3 == 3) || 1852 (M0 < 4 && M1 == 5 && M2 == 6 && M3 == 7)) { 1853 ShiftElts = IsLE ? LittleEndianShifts[M0 & 0x3] : BigEndianShifts[M0 & 0x3]; 1854 InsertAtByte = IsLE ? 12 : 0; 1855 Swap = M0 < 4; 1856 return true; 1857 } 1858 // 0, H, 2, 3 or 4, L, 6, 7 1859 if ((M1 > 3 && M0 == 0 && M2 == 2 && M3 == 3) || 1860 (M1 < 4 && M0 == 4 && M2 == 6 && M3 == 7)) { 1861 ShiftElts = IsLE ? LittleEndianShifts[M1 & 0x3] : BigEndianShifts[M1 & 0x3]; 1862 InsertAtByte = IsLE ? 8 : 4; 1863 Swap = M1 < 4; 1864 return true; 1865 } 1866 // 0, 1, H, 3 or 4, 5, L, 7 1867 if ((M2 > 3 && M0 == 0 && M1 == 1 && M3 == 3) || 1868 (M2 < 4 && M0 == 4 && M1 == 5 && M3 == 7)) { 1869 ShiftElts = IsLE ? LittleEndianShifts[M2 & 0x3] : BigEndianShifts[M2 & 0x3]; 1870 InsertAtByte = IsLE ? 4 : 8; 1871 Swap = M2 < 4; 1872 return true; 1873 } 1874 // 0, 1, 2, H or 4, 5, 6, L 1875 if ((M3 > 3 && M0 == 0 && M1 == 1 && M2 == 2) || 1876 (M3 < 4 && M0 == 4 && M1 == 5 && M2 == 6)) { 1877 ShiftElts = IsLE ? LittleEndianShifts[M3 & 0x3] : BigEndianShifts[M3 & 0x3]; 1878 InsertAtByte = IsLE ? 0 : 12; 1879 Swap = M3 < 4; 1880 return true; 1881 } 1882 1883 // If both vector operands for the shuffle are the same vector, the mask will 1884 // contain only elements from the first one and the second one will be undef. 1885 if (N->getOperand(1).isUndef()) { 1886 ShiftElts = 0; 1887 Swap = true; 1888 unsigned XXINSERTWSrcElem = IsLE ? 2 : 1; 1889 if (M0 == XXINSERTWSrcElem && M1 == 1 && M2 == 2 && M3 == 3) { 1890 InsertAtByte = IsLE ? 12 : 0; 1891 return true; 1892 } 1893 if (M0 == 0 && M1 == XXINSERTWSrcElem && M2 == 2 && M3 == 3) { 1894 InsertAtByte = IsLE ? 8 : 4; 1895 return true; 1896 } 1897 if (M0 == 0 && M1 == 1 && M2 == XXINSERTWSrcElem && M3 == 3) { 1898 InsertAtByte = IsLE ? 4 : 8; 1899 return true; 1900 } 1901 if (M0 == 0 && M1 == 1 && M2 == 2 && M3 == XXINSERTWSrcElem) { 1902 InsertAtByte = IsLE ? 0 : 12; 1903 return true; 1904 } 1905 } 1906 1907 return false; 1908 } 1909 1910 bool PPC::isXXSLDWIShuffleMask(ShuffleVectorSDNode *N, unsigned &ShiftElts, 1911 bool &Swap, bool IsLE) { 1912 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8"); 1913 // Ensure each byte index of the word is consecutive. 1914 if (!isNByteElemShuffleMask(N, 4, 1)) 1915 return false; 1916 1917 // Now we look at mask elements 0,4,8,12, which are the beginning of words. 1918 unsigned M0 = N->getMaskElt(0) / 4; 1919 unsigned M1 = N->getMaskElt(4) / 4; 1920 unsigned M2 = N->getMaskElt(8) / 4; 1921 unsigned M3 = N->getMaskElt(12) / 4; 1922 1923 // If both vector operands for the shuffle are the same vector, the mask will 1924 // contain only elements from the first one and the second one will be undef. 1925 if (N->getOperand(1).isUndef()) { 1926 assert(M0 < 4 && "Indexing into an undef vector?"); 1927 if (M1 != (M0 + 1) % 4 || M2 != (M1 + 1) % 4 || M3 != (M2 + 1) % 4) 1928 return false; 1929 1930 ShiftElts = IsLE ? (4 - M0) % 4 : M0; 1931 Swap = false; 1932 return true; 1933 } 1934 1935 // Ensure each word index of the ShuffleVector Mask is consecutive. 1936 if (M1 != (M0 + 1) % 8 || M2 != (M1 + 1) % 8 || M3 != (M2 + 1) % 8) 1937 return false; 1938 1939 if (IsLE) { 1940 if (M0 == 0 || M0 == 7 || M0 == 6 || M0 == 5) { 1941 // Input vectors don't need to be swapped if the leading element 1942 // of the result is one of the 3 left elements of the second vector 1943 // (or if there is no shift to be done at all). 1944 Swap = false; 1945 ShiftElts = (8 - M0) % 8; 1946 } else if (M0 == 4 || M0 == 3 || M0 == 2 || M0 == 1) { 1947 // Input vectors need to be swapped if the leading element 1948 // of the result is one of the 3 left elements of the first vector 1949 // (or if we're shifting by 4 - thereby simply swapping the vectors). 1950 Swap = true; 1951 ShiftElts = (4 - M0) % 4; 1952 } 1953 1954 return true; 1955 } else { // BE 1956 if (M0 == 0 || M0 == 1 || M0 == 2 || M0 == 3) { 1957 // Input vectors don't need to be swapped if the leading element 1958 // of the result is one of the 4 elements of the first vector. 1959 Swap = false; 1960 ShiftElts = M0; 1961 } else if (M0 == 4 || M0 == 5 || M0 == 6 || M0 == 7) { 1962 // Input vectors need to be swapped if the leading element 1963 // of the result is one of the 4 elements of the right vector. 1964 Swap = true; 1965 ShiftElts = M0 - 4; 1966 } 1967 1968 return true; 1969 } 1970 } 1971 1972 bool static isXXBRShuffleMaskHelper(ShuffleVectorSDNode *N, int Width) { 1973 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8"); 1974 1975 if (!isNByteElemShuffleMask(N, Width, -1)) 1976 return false; 1977 1978 for (int i = 0; i < 16; i += Width) 1979 if (N->getMaskElt(i) != i + Width - 1) 1980 return false; 1981 1982 return true; 1983 } 1984 1985 bool PPC::isXXBRHShuffleMask(ShuffleVectorSDNode *N) { 1986 return isXXBRShuffleMaskHelper(N, 2); 1987 } 1988 1989 bool PPC::isXXBRWShuffleMask(ShuffleVectorSDNode *N) { 1990 return isXXBRShuffleMaskHelper(N, 4); 1991 } 1992 1993 bool PPC::isXXBRDShuffleMask(ShuffleVectorSDNode *N) { 1994 return isXXBRShuffleMaskHelper(N, 8); 1995 } 1996 1997 bool PPC::isXXBRQShuffleMask(ShuffleVectorSDNode *N) { 1998 return isXXBRShuffleMaskHelper(N, 16); 1999 } 2000 2001 /// Can node \p N be lowered to an XXPERMDI instruction? If so, set \p Swap 2002 /// if the inputs to the instruction should be swapped and set \p DM to the 2003 /// value for the immediate. 2004 /// Specifically, set \p Swap to true only if \p N can be lowered to XXPERMDI 2005 /// AND element 0 of the result comes from the first input (LE) or second input 2006 /// (BE). Set \p DM to the calculated result (0-3) only if \p N can be lowered. 2007 /// \return true iff the given mask of shuffle node \p N is a XXPERMDI shuffle 2008 /// mask. 2009 bool PPC::isXXPERMDIShuffleMask(ShuffleVectorSDNode *N, unsigned &DM, 2010 bool &Swap, bool IsLE) { 2011 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8"); 2012 2013 // Ensure each byte index of the double word is consecutive. 2014 if (!isNByteElemShuffleMask(N, 8, 1)) 2015 return false; 2016 2017 unsigned M0 = N->getMaskElt(0) / 8; 2018 unsigned M1 = N->getMaskElt(8) / 8; 2019 assert(((M0 | M1) < 4) && "A mask element out of bounds?"); 2020 2021 // If both vector operands for the shuffle are the same vector, the mask will 2022 // contain only elements from the first one and the second one will be undef. 2023 if (N->getOperand(1).isUndef()) { 2024 if ((M0 | M1) < 2) { 2025 DM = IsLE ? (((~M1) & 1) << 1) + ((~M0) & 1) : (M0 << 1) + (M1 & 1); 2026 Swap = false; 2027 return true; 2028 } else 2029 return false; 2030 } 2031 2032 if (IsLE) { 2033 if (M0 > 1 && M1 < 2) { 2034 Swap = false; 2035 } else if (M0 < 2 && M1 > 1) { 2036 M0 = (M0 + 2) % 4; 2037 M1 = (M1 + 2) % 4; 2038 Swap = true; 2039 } else 2040 return false; 2041 2042 // Note: if control flow comes here that means Swap is already set above 2043 DM = (((~M1) & 1) << 1) + ((~M0) & 1); 2044 return true; 2045 } else { // BE 2046 if (M0 < 2 && M1 > 1) { 2047 Swap = false; 2048 } else if (M0 > 1 && M1 < 2) { 2049 M0 = (M0 + 2) % 4; 2050 M1 = (M1 + 2) % 4; 2051 Swap = true; 2052 } else 2053 return false; 2054 2055 // Note: if control flow comes here that means Swap is already set above 2056 DM = (M0 << 1) + (M1 & 1); 2057 return true; 2058 } 2059 } 2060 2061 2062 /// getVSPLTImmediate - Return the appropriate VSPLT* immediate to splat the 2063 /// specified isSplatShuffleMask VECTOR_SHUFFLE mask. 2064 unsigned PPC::getVSPLTImmediate(SDNode *N, unsigned EltSize, 2065 SelectionDAG &DAG) { 2066 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 2067 assert(isSplatShuffleMask(SVOp, EltSize)); 2068 if (DAG.getDataLayout().isLittleEndian()) 2069 return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize); 2070 else 2071 return SVOp->getMaskElt(0) / EltSize; 2072 } 2073 2074 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed 2075 /// by using a vspltis[bhw] instruction of the specified element size, return 2076 /// the constant being splatted. The ByteSize field indicates the number of 2077 /// bytes of each element [124] -> [bhw]. 2078 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) { 2079 SDValue OpVal(nullptr, 0); 2080 2081 // If ByteSize of the splat is bigger than the element size of the 2082 // build_vector, then we have a case where we are checking for a splat where 2083 // multiple elements of the buildvector are folded together into a single 2084 // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8). 2085 unsigned EltSize = 16/N->getNumOperands(); 2086 if (EltSize < ByteSize) { 2087 unsigned Multiple = ByteSize/EltSize; // Number of BV entries per spltval. 2088 SDValue UniquedVals[4]; 2089 assert(Multiple > 1 && Multiple <= 4 && "How can this happen?"); 2090 2091 // See if all of the elements in the buildvector agree across. 2092 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 2093 if (N->getOperand(i).isUndef()) continue; 2094 // If the element isn't a constant, bail fully out. 2095 if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue(); 2096 2097 if (!UniquedVals[i&(Multiple-1)].getNode()) 2098 UniquedVals[i&(Multiple-1)] = N->getOperand(i); 2099 else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i)) 2100 return SDValue(); // no match. 2101 } 2102 2103 // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains 2104 // either constant or undef values that are identical for each chunk. See 2105 // if these chunks can form into a larger vspltis*. 2106 2107 // Check to see if all of the leading entries are either 0 or -1. If 2108 // neither, then this won't fit into the immediate field. 2109 bool LeadingZero = true; 2110 bool LeadingOnes = true; 2111 for (unsigned i = 0; i != Multiple-1; ++i) { 2112 if (!UniquedVals[i].getNode()) continue; // Must have been undefs. 2113 2114 LeadingZero &= isNullConstant(UniquedVals[i]); 2115 LeadingOnes &= isAllOnesConstant(UniquedVals[i]); 2116 } 2117 // Finally, check the least significant entry. 2118 if (LeadingZero) { 2119 if (!UniquedVals[Multiple-1].getNode()) 2120 return DAG.getTargetConstant(0, SDLoc(N), MVT::i32); // 0,0,0,undef 2121 int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue(); 2122 if (Val < 16) // 0,0,0,4 -> vspltisw(4) 2123 return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32); 2124 } 2125 if (LeadingOnes) { 2126 if (!UniquedVals[Multiple-1].getNode()) 2127 return DAG.getTargetConstant(~0U, SDLoc(N), MVT::i32); // -1,-1,-1,undef 2128 int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue(); 2129 if (Val >= -16) // -1,-1,-1,-2 -> vspltisw(-2) 2130 return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32); 2131 } 2132 2133 return SDValue(); 2134 } 2135 2136 // Check to see if this buildvec has a single non-undef value in its elements. 2137 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 2138 if (N->getOperand(i).isUndef()) continue; 2139 if (!OpVal.getNode()) 2140 OpVal = N->getOperand(i); 2141 else if (OpVal != N->getOperand(i)) 2142 return SDValue(); 2143 } 2144 2145 if (!OpVal.getNode()) return SDValue(); // All UNDEF: use implicit def. 2146 2147 unsigned ValSizeInBytes = EltSize; 2148 uint64_t Value = 0; 2149 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) { 2150 Value = CN->getZExtValue(); 2151 } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) { 2152 assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!"); 2153 Value = FloatToBits(CN->getValueAPF().convertToFloat()); 2154 } 2155 2156 // If the splat value is larger than the element value, then we can never do 2157 // this splat. The only case that we could fit the replicated bits into our 2158 // immediate field for would be zero, and we prefer to use vxor for it. 2159 if (ValSizeInBytes < ByteSize) return SDValue(); 2160 2161 // If the element value is larger than the splat value, check if it consists 2162 // of a repeated bit pattern of size ByteSize. 2163 if (!APInt(ValSizeInBytes * 8, Value).isSplat(ByteSize * 8)) 2164 return SDValue(); 2165 2166 // Properly sign extend the value. 2167 int MaskVal = SignExtend32(Value, ByteSize * 8); 2168 2169 // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros. 2170 if (MaskVal == 0) return SDValue(); 2171 2172 // Finally, if this value fits in a 5 bit sext field, return it 2173 if (SignExtend32<5>(MaskVal) == MaskVal) 2174 return DAG.getTargetConstant(MaskVal, SDLoc(N), MVT::i32); 2175 return SDValue(); 2176 } 2177 2178 /// isQVALIGNIShuffleMask - If this is a qvaligni shuffle mask, return the shift 2179 /// amount, otherwise return -1. 2180 int PPC::isQVALIGNIShuffleMask(SDNode *N) { 2181 EVT VT = N->getValueType(0); 2182 if (VT != MVT::v4f64 && VT != MVT::v4f32 && VT != MVT::v4i1) 2183 return -1; 2184 2185 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 2186 2187 // Find the first non-undef value in the shuffle mask. 2188 unsigned i; 2189 for (i = 0; i != 4 && SVOp->getMaskElt(i) < 0; ++i) 2190 /*search*/; 2191 2192 if (i == 4) return -1; // all undef. 2193 2194 // Otherwise, check to see if the rest of the elements are consecutively 2195 // numbered from this value. 2196 unsigned ShiftAmt = SVOp->getMaskElt(i); 2197 if (ShiftAmt < i) return -1; 2198 ShiftAmt -= i; 2199 2200 // Check the rest of the elements to see if they are consecutive. 2201 for (++i; i != 4; ++i) 2202 if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i)) 2203 return -1; 2204 2205 return ShiftAmt; 2206 } 2207 2208 //===----------------------------------------------------------------------===// 2209 // Addressing Mode Selection 2210 //===----------------------------------------------------------------------===// 2211 2212 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit 2213 /// or 64-bit immediate, and if the value can be accurately represented as a 2214 /// sign extension from a 16-bit value. If so, this returns true and the 2215 /// immediate. 2216 bool llvm::isIntS16Immediate(SDNode *N, int16_t &Imm) { 2217 if (!isa<ConstantSDNode>(N)) 2218 return false; 2219 2220 Imm = (int16_t)cast<ConstantSDNode>(N)->getZExtValue(); 2221 if (N->getValueType(0) == MVT::i32) 2222 return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue(); 2223 else 2224 return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue(); 2225 } 2226 bool llvm::isIntS16Immediate(SDValue Op, int16_t &Imm) { 2227 return isIntS16Immediate(Op.getNode(), Imm); 2228 } 2229 2230 /// SelectAddressRegReg - Given the specified addressed, check to see if it 2231 /// can be represented as an indexed [r+r] operation. Returns false if it 2232 /// can be more efficiently represented as [r+imm]. If \p EncodingAlignment is 2233 /// non-zero and N can be represented by a base register plus a signed 16-bit 2234 /// displacement, make a more precise judgement by checking (displacement % \p 2235 /// EncodingAlignment). 2236 bool PPCTargetLowering::SelectAddressRegReg(SDValue N, SDValue &Base, 2237 SDValue &Index, SelectionDAG &DAG, 2238 unsigned EncodingAlignment) const { 2239 int16_t imm = 0; 2240 if (N.getOpcode() == ISD::ADD) { 2241 if (isIntS16Immediate(N.getOperand(1), imm) && 2242 (!EncodingAlignment || !(imm % EncodingAlignment))) 2243 return false; // r+i 2244 if (N.getOperand(1).getOpcode() == PPCISD::Lo) 2245 return false; // r+i 2246 2247 Base = N.getOperand(0); 2248 Index = N.getOperand(1); 2249 return true; 2250 } else if (N.getOpcode() == ISD::OR) { 2251 if (isIntS16Immediate(N.getOperand(1), imm) && 2252 (!EncodingAlignment || !(imm % EncodingAlignment))) 2253 return false; // r+i can fold it if we can. 2254 2255 // If this is an or of disjoint bitfields, we can codegen this as an add 2256 // (for better address arithmetic) if the LHS and RHS of the OR are provably 2257 // disjoint. 2258 KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0)); 2259 2260 if (LHSKnown.Zero.getBoolValue()) { 2261 KnownBits RHSKnown = DAG.computeKnownBits(N.getOperand(1)); 2262 // If all of the bits are known zero on the LHS or RHS, the add won't 2263 // carry. 2264 if (~(LHSKnown.Zero | RHSKnown.Zero) == 0) { 2265 Base = N.getOperand(0); 2266 Index = N.getOperand(1); 2267 return true; 2268 } 2269 } 2270 } 2271 2272 return false; 2273 } 2274 2275 // If we happen to be doing an i64 load or store into a stack slot that has 2276 // less than a 4-byte alignment, then the frame-index elimination may need to 2277 // use an indexed load or store instruction (because the offset may not be a 2278 // multiple of 4). The extra register needed to hold the offset comes from the 2279 // register scavenger, and it is possible that the scavenger will need to use 2280 // an emergency spill slot. As a result, we need to make sure that a spill slot 2281 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned 2282 // stack slot. 2283 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) { 2284 // FIXME: This does not handle the LWA case. 2285 if (VT != MVT::i64) 2286 return; 2287 2288 // NOTE: We'll exclude negative FIs here, which come from argument 2289 // lowering, because there are no known test cases triggering this problem 2290 // using packed structures (or similar). We can remove this exclusion if 2291 // we find such a test case. The reason why this is so test-case driven is 2292 // because this entire 'fixup' is only to prevent crashes (from the 2293 // register scavenger) on not-really-valid inputs. For example, if we have: 2294 // %a = alloca i1 2295 // %b = bitcast i1* %a to i64* 2296 // store i64* a, i64 b 2297 // then the store should really be marked as 'align 1', but is not. If it 2298 // were marked as 'align 1' then the indexed form would have been 2299 // instruction-selected initially, and the problem this 'fixup' is preventing 2300 // won't happen regardless. 2301 if (FrameIdx < 0) 2302 return; 2303 2304 MachineFunction &MF = DAG.getMachineFunction(); 2305 MachineFrameInfo &MFI = MF.getFrameInfo(); 2306 2307 unsigned Align = MFI.getObjectAlignment(FrameIdx); 2308 if (Align >= 4) 2309 return; 2310 2311 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 2312 FuncInfo->setHasNonRISpills(); 2313 } 2314 2315 /// Returns true if the address N can be represented by a base register plus 2316 /// a signed 16-bit displacement [r+imm], and if it is not better 2317 /// represented as reg+reg. If \p EncodingAlignment is non-zero, only accept 2318 /// displacements that are multiples of that value. 2319 bool PPCTargetLowering::SelectAddressRegImm(SDValue N, SDValue &Disp, 2320 SDValue &Base, 2321 SelectionDAG &DAG, 2322 unsigned EncodingAlignment) const { 2323 // FIXME dl should come from parent load or store, not from address 2324 SDLoc dl(N); 2325 // If this can be more profitably realized as r+r, fail. 2326 if (SelectAddressRegReg(N, Disp, Base, DAG, EncodingAlignment)) 2327 return false; 2328 2329 if (N.getOpcode() == ISD::ADD) { 2330 int16_t imm = 0; 2331 if (isIntS16Immediate(N.getOperand(1), imm) && 2332 (!EncodingAlignment || (imm % EncodingAlignment) == 0)) { 2333 Disp = DAG.getTargetConstant(imm, dl, N.getValueType()); 2334 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) { 2335 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2336 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 2337 } else { 2338 Base = N.getOperand(0); 2339 } 2340 return true; // [r+i] 2341 } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) { 2342 // Match LOAD (ADD (X, Lo(G))). 2343 assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue() 2344 && "Cannot handle constant offsets yet!"); 2345 Disp = N.getOperand(1).getOperand(0); // The global address. 2346 assert(Disp.getOpcode() == ISD::TargetGlobalAddress || 2347 Disp.getOpcode() == ISD::TargetGlobalTLSAddress || 2348 Disp.getOpcode() == ISD::TargetConstantPool || 2349 Disp.getOpcode() == ISD::TargetJumpTable); 2350 Base = N.getOperand(0); 2351 return true; // [&g+r] 2352 } 2353 } else if (N.getOpcode() == ISD::OR) { 2354 int16_t imm = 0; 2355 if (isIntS16Immediate(N.getOperand(1), imm) && 2356 (!EncodingAlignment || (imm % EncodingAlignment) == 0)) { 2357 // If this is an or of disjoint bitfields, we can codegen this as an add 2358 // (for better address arithmetic) if the LHS and RHS of the OR are 2359 // provably disjoint. 2360 KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0)); 2361 2362 if ((LHSKnown.Zero.getZExtValue()|~(uint64_t)imm) == ~0ULL) { 2363 // If all of the bits are known zero on the LHS or RHS, the add won't 2364 // carry. 2365 if (FrameIndexSDNode *FI = 2366 dyn_cast<FrameIndexSDNode>(N.getOperand(0))) { 2367 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2368 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 2369 } else { 2370 Base = N.getOperand(0); 2371 } 2372 Disp = DAG.getTargetConstant(imm, dl, N.getValueType()); 2373 return true; 2374 } 2375 } 2376 } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) { 2377 // Loading from a constant address. 2378 2379 // If this address fits entirely in a 16-bit sext immediate field, codegen 2380 // this as "d, 0" 2381 int16_t Imm; 2382 if (isIntS16Immediate(CN, Imm) && 2383 (!EncodingAlignment || (Imm % EncodingAlignment) == 0)) { 2384 Disp = DAG.getTargetConstant(Imm, dl, CN->getValueType(0)); 2385 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO, 2386 CN->getValueType(0)); 2387 return true; 2388 } 2389 2390 // Handle 32-bit sext immediates with LIS + addr mode. 2391 if ((CN->getValueType(0) == MVT::i32 || 2392 (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) && 2393 (!EncodingAlignment || (CN->getZExtValue() % EncodingAlignment) == 0)) { 2394 int Addr = (int)CN->getZExtValue(); 2395 2396 // Otherwise, break this down into an LIS + disp. 2397 Disp = DAG.getTargetConstant((short)Addr, dl, MVT::i32); 2398 2399 Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, dl, 2400 MVT::i32); 2401 unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8; 2402 Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0); 2403 return true; 2404 } 2405 } 2406 2407 Disp = DAG.getTargetConstant(0, dl, getPointerTy(DAG.getDataLayout())); 2408 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) { 2409 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2410 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 2411 } else 2412 Base = N; 2413 return true; // [r+0] 2414 } 2415 2416 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be 2417 /// represented as an indexed [r+r] operation. 2418 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base, 2419 SDValue &Index, 2420 SelectionDAG &DAG) const { 2421 // Check to see if we can easily represent this as an [r+r] address. This 2422 // will fail if it thinks that the address is more profitably represented as 2423 // reg+imm, e.g. where imm = 0. 2424 if (SelectAddressRegReg(N, Base, Index, DAG)) 2425 return true; 2426 2427 // If the address is the result of an add, we will utilize the fact that the 2428 // address calculation includes an implicit add. However, we can reduce 2429 // register pressure if we do not materialize a constant just for use as the 2430 // index register. We only get rid of the add if it is not an add of a 2431 // value and a 16-bit signed constant and both have a single use. 2432 int16_t imm = 0; 2433 if (N.getOpcode() == ISD::ADD && 2434 (!isIntS16Immediate(N.getOperand(1), imm) || 2435 !N.getOperand(1).hasOneUse() || !N.getOperand(0).hasOneUse())) { 2436 Base = N.getOperand(0); 2437 Index = N.getOperand(1); 2438 return true; 2439 } 2440 2441 // Otherwise, do it the hard way, using R0 as the base register. 2442 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO, 2443 N.getValueType()); 2444 Index = N; 2445 return true; 2446 } 2447 2448 /// Returns true if we should use a direct load into vector instruction 2449 /// (such as lxsd or lfd), instead of a load into gpr + direct move sequence. 2450 static bool usePartialVectorLoads(SDNode *N, const PPCSubtarget& ST) { 2451 2452 // If there are any other uses other than scalar to vector, then we should 2453 // keep it as a scalar load -> direct move pattern to prevent multiple 2454 // loads. 2455 LoadSDNode *LD = dyn_cast<LoadSDNode>(N); 2456 if (!LD) 2457 return false; 2458 2459 EVT MemVT = LD->getMemoryVT(); 2460 if (!MemVT.isSimple()) 2461 return false; 2462 switch(MemVT.getSimpleVT().SimpleTy) { 2463 case MVT::i64: 2464 break; 2465 case MVT::i32: 2466 if (!ST.hasP8Vector()) 2467 return false; 2468 break; 2469 case MVT::i16: 2470 case MVT::i8: 2471 if (!ST.hasP9Vector()) 2472 return false; 2473 break; 2474 default: 2475 return false; 2476 } 2477 2478 SDValue LoadedVal(N, 0); 2479 if (!LoadedVal.hasOneUse()) 2480 return false; 2481 2482 for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end(); 2483 UI != UE; ++UI) 2484 if (UI.getUse().get().getResNo() == 0 && 2485 UI->getOpcode() != ISD::SCALAR_TO_VECTOR) 2486 return false; 2487 2488 return true; 2489 } 2490 2491 /// getPreIndexedAddressParts - returns true by value, base pointer and 2492 /// offset pointer and addressing mode by reference if the node's address 2493 /// can be legally represented as pre-indexed load / store address. 2494 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base, 2495 SDValue &Offset, 2496 ISD::MemIndexedMode &AM, 2497 SelectionDAG &DAG) const { 2498 if (DisablePPCPreinc) return false; 2499 2500 bool isLoad = true; 2501 SDValue Ptr; 2502 EVT VT; 2503 unsigned Alignment; 2504 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 2505 Ptr = LD->getBasePtr(); 2506 VT = LD->getMemoryVT(); 2507 Alignment = LD->getAlignment(); 2508 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 2509 Ptr = ST->getBasePtr(); 2510 VT = ST->getMemoryVT(); 2511 Alignment = ST->getAlignment(); 2512 isLoad = false; 2513 } else 2514 return false; 2515 2516 // Do not generate pre-inc forms for specific loads that feed scalar_to_vector 2517 // instructions because we can fold these into a more efficient instruction 2518 // instead, (such as LXSD). 2519 if (isLoad && usePartialVectorLoads(N, Subtarget)) { 2520 return false; 2521 } 2522 2523 // PowerPC doesn't have preinc load/store instructions for vectors (except 2524 // for QPX, which does have preinc r+r forms). 2525 if (VT.isVector()) { 2526 if (!Subtarget.hasQPX() || (VT != MVT::v4f64 && VT != MVT::v4f32)) { 2527 return false; 2528 } else if (SelectAddressRegRegOnly(Ptr, Offset, Base, DAG)) { 2529 AM = ISD::PRE_INC; 2530 return true; 2531 } 2532 } 2533 2534 if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) { 2535 // Common code will reject creating a pre-inc form if the base pointer 2536 // is a frame index, or if N is a store and the base pointer is either 2537 // the same as or a predecessor of the value being stored. Check for 2538 // those situations here, and try with swapped Base/Offset instead. 2539 bool Swap = false; 2540 2541 if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base)) 2542 Swap = true; 2543 else if (!isLoad) { 2544 SDValue Val = cast<StoreSDNode>(N)->getValue(); 2545 if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode())) 2546 Swap = true; 2547 } 2548 2549 if (Swap) 2550 std::swap(Base, Offset); 2551 2552 AM = ISD::PRE_INC; 2553 return true; 2554 } 2555 2556 // LDU/STU can only handle immediates that are a multiple of 4. 2557 if (VT != MVT::i64) { 2558 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, 0)) 2559 return false; 2560 } else { 2561 // LDU/STU need an address with at least 4-byte alignment. 2562 if (Alignment < 4) 2563 return false; 2564 2565 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, 4)) 2566 return false; 2567 } 2568 2569 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 2570 // PPC64 doesn't have lwau, but it does have lwaux. Reject preinc load of 2571 // sext i32 to i64 when addr mode is r+i. 2572 if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 && 2573 LD->getExtensionType() == ISD::SEXTLOAD && 2574 isa<ConstantSDNode>(Offset)) 2575 return false; 2576 } 2577 2578 AM = ISD::PRE_INC; 2579 return true; 2580 } 2581 2582 //===----------------------------------------------------------------------===// 2583 // LowerOperation implementation 2584 //===----------------------------------------------------------------------===// 2585 2586 /// Return true if we should reference labels using a PICBase, set the HiOpFlags 2587 /// and LoOpFlags to the target MO flags. 2588 static void getLabelAccessInfo(bool IsPIC, const PPCSubtarget &Subtarget, 2589 unsigned &HiOpFlags, unsigned &LoOpFlags, 2590 const GlobalValue *GV = nullptr) { 2591 HiOpFlags = PPCII::MO_HA; 2592 LoOpFlags = PPCII::MO_LO; 2593 2594 // Don't use the pic base if not in PIC relocation model. 2595 if (IsPIC) { 2596 HiOpFlags |= PPCII::MO_PIC_FLAG; 2597 LoOpFlags |= PPCII::MO_PIC_FLAG; 2598 } 2599 2600 // If this is a reference to a global value that requires a non-lazy-ptr, make 2601 // sure that instruction lowering adds it. 2602 if (GV && Subtarget.hasLazyResolverStub(GV)) { 2603 HiOpFlags |= PPCII::MO_NLP_FLAG; 2604 LoOpFlags |= PPCII::MO_NLP_FLAG; 2605 2606 if (GV->hasHiddenVisibility()) { 2607 HiOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG; 2608 LoOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG; 2609 } 2610 } 2611 } 2612 2613 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC, 2614 SelectionDAG &DAG) { 2615 SDLoc DL(HiPart); 2616 EVT PtrVT = HiPart.getValueType(); 2617 SDValue Zero = DAG.getConstant(0, DL, PtrVT); 2618 2619 SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero); 2620 SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero); 2621 2622 // With PIC, the first instruction is actually "GR+hi(&G)". 2623 if (isPIC) 2624 Hi = DAG.getNode(ISD::ADD, DL, PtrVT, 2625 DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi); 2626 2627 // Generate non-pic code that has direct accesses to the constant pool. 2628 // The address of the global is just (hi(&g)+lo(&g)). 2629 return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo); 2630 } 2631 2632 static void setUsesTOCBasePtr(MachineFunction &MF) { 2633 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 2634 FuncInfo->setUsesTOCBasePtr(); 2635 } 2636 2637 static void setUsesTOCBasePtr(SelectionDAG &DAG) { 2638 setUsesTOCBasePtr(DAG.getMachineFunction()); 2639 } 2640 2641 static SDValue getTOCEntry(SelectionDAG &DAG, const SDLoc &dl, bool Is64Bit, 2642 SDValue GA) { 2643 EVT VT = Is64Bit ? MVT::i64 : MVT::i32; 2644 SDValue Reg = Is64Bit ? DAG.getRegister(PPC::X2, VT) : 2645 DAG.getNode(PPCISD::GlobalBaseReg, dl, VT); 2646 2647 SDValue Ops[] = { GA, Reg }; 2648 return DAG.getMemIntrinsicNode( 2649 PPCISD::TOC_ENTRY, dl, DAG.getVTList(VT, MVT::Other), Ops, VT, 2650 MachinePointerInfo::getGOT(DAG.getMachineFunction()), 0, 2651 MachineMemOperand::MOLoad); 2652 } 2653 2654 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op, 2655 SelectionDAG &DAG) const { 2656 EVT PtrVT = Op.getValueType(); 2657 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op); 2658 const Constant *C = CP->getConstVal(); 2659 2660 // 64-bit SVR4 ABI code is always position-independent. 2661 // The actual address of the GlobalValue is stored in the TOC. 2662 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) { 2663 setUsesTOCBasePtr(DAG); 2664 SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0); 2665 return getTOCEntry(DAG, SDLoc(CP), true, GA); 2666 } 2667 2668 unsigned MOHiFlag, MOLoFlag; 2669 bool IsPIC = isPositionIndependent(); 2670 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag); 2671 2672 if (IsPIC && Subtarget.isSVR4ABI()) { 2673 SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 2674 PPCII::MO_PIC_FLAG); 2675 return getTOCEntry(DAG, SDLoc(CP), false, GA); 2676 } 2677 2678 SDValue CPIHi = 2679 DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOHiFlag); 2680 SDValue CPILo = 2681 DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOLoFlag); 2682 return LowerLabelRef(CPIHi, CPILo, IsPIC, DAG); 2683 } 2684 2685 // For 64-bit PowerPC, prefer the more compact relative encodings. 2686 // This trades 32 bits per jump table entry for one or two instructions 2687 // on the jump site. 2688 unsigned PPCTargetLowering::getJumpTableEncoding() const { 2689 if (isJumpTableRelative()) 2690 return MachineJumpTableInfo::EK_LabelDifference32; 2691 2692 return TargetLowering::getJumpTableEncoding(); 2693 } 2694 2695 bool PPCTargetLowering::isJumpTableRelative() const { 2696 if (Subtarget.isPPC64()) 2697 return true; 2698 return TargetLowering::isJumpTableRelative(); 2699 } 2700 2701 SDValue PPCTargetLowering::getPICJumpTableRelocBase(SDValue Table, 2702 SelectionDAG &DAG) const { 2703 if (!Subtarget.isPPC64()) 2704 return TargetLowering::getPICJumpTableRelocBase(Table, DAG); 2705 2706 switch (getTargetMachine().getCodeModel()) { 2707 case CodeModel::Small: 2708 case CodeModel::Medium: 2709 return TargetLowering::getPICJumpTableRelocBase(Table, DAG); 2710 default: 2711 return DAG.getNode(PPCISD::GlobalBaseReg, SDLoc(), 2712 getPointerTy(DAG.getDataLayout())); 2713 } 2714 } 2715 2716 const MCExpr * 2717 PPCTargetLowering::getPICJumpTableRelocBaseExpr(const MachineFunction *MF, 2718 unsigned JTI, 2719 MCContext &Ctx) const { 2720 if (!Subtarget.isPPC64()) 2721 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx); 2722 2723 switch (getTargetMachine().getCodeModel()) { 2724 case CodeModel::Small: 2725 case CodeModel::Medium: 2726 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx); 2727 default: 2728 return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx); 2729 } 2730 } 2731 2732 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const { 2733 EVT PtrVT = Op.getValueType(); 2734 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op); 2735 2736 // 64-bit SVR4 ABI code is always position-independent. 2737 // The actual address of the GlobalValue is stored in the TOC. 2738 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) { 2739 setUsesTOCBasePtr(DAG); 2740 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT); 2741 return getTOCEntry(DAG, SDLoc(JT), true, GA); 2742 } 2743 2744 unsigned MOHiFlag, MOLoFlag; 2745 bool IsPIC = isPositionIndependent(); 2746 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag); 2747 2748 if (IsPIC && Subtarget.isSVR4ABI()) { 2749 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, 2750 PPCII::MO_PIC_FLAG); 2751 return getTOCEntry(DAG, SDLoc(GA), false, GA); 2752 } 2753 2754 SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag); 2755 SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag); 2756 return LowerLabelRef(JTIHi, JTILo, IsPIC, DAG); 2757 } 2758 2759 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op, 2760 SelectionDAG &DAG) const { 2761 EVT PtrVT = Op.getValueType(); 2762 BlockAddressSDNode *BASDN = cast<BlockAddressSDNode>(Op); 2763 const BlockAddress *BA = BASDN->getBlockAddress(); 2764 2765 // 64-bit SVR4 ABI code is always position-independent. 2766 // The actual BlockAddress is stored in the TOC. 2767 if (Subtarget.isSVR4ABI() && 2768 (Subtarget.isPPC64() || isPositionIndependent())) { 2769 if (Subtarget.isPPC64()) 2770 setUsesTOCBasePtr(DAG); 2771 SDValue GA = DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset()); 2772 return getTOCEntry(DAG, SDLoc(BASDN), Subtarget.isPPC64(), GA); 2773 } 2774 2775 unsigned MOHiFlag, MOLoFlag; 2776 bool IsPIC = isPositionIndependent(); 2777 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag); 2778 SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag); 2779 SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag); 2780 return LowerLabelRef(TgtBAHi, TgtBALo, IsPIC, DAG); 2781 } 2782 2783 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op, 2784 SelectionDAG &DAG) const { 2785 // FIXME: TLS addresses currently use medium model code sequences, 2786 // which is the most useful form. Eventually support for small and 2787 // large models could be added if users need it, at the cost of 2788 // additional complexity. 2789 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op); 2790 if (DAG.getTarget().useEmulatedTLS()) 2791 return LowerToTLSEmulatedModel(GA, DAG); 2792 2793 SDLoc dl(GA); 2794 const GlobalValue *GV = GA->getGlobal(); 2795 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2796 bool is64bit = Subtarget.isPPC64(); 2797 const Module *M = DAG.getMachineFunction().getFunction().getParent(); 2798 PICLevel::Level picLevel = M->getPICLevel(); 2799 2800 const TargetMachine &TM = getTargetMachine(); 2801 TLSModel::Model Model = TM.getTLSModel(GV); 2802 2803 if (Model == TLSModel::LocalExec) { 2804 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 2805 PPCII::MO_TPREL_HA); 2806 SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 2807 PPCII::MO_TPREL_LO); 2808 SDValue TLSReg = is64bit ? DAG.getRegister(PPC::X13, MVT::i64) 2809 : DAG.getRegister(PPC::R2, MVT::i32); 2810 2811 SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg); 2812 return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi); 2813 } 2814 2815 if (Model == TLSModel::InitialExec) { 2816 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0); 2817 SDValue TGATLS = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 2818 PPCII::MO_TLS); 2819 SDValue GOTPtr; 2820 if (is64bit) { 2821 setUsesTOCBasePtr(DAG); 2822 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64); 2823 GOTPtr = DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl, 2824 PtrVT, GOTReg, TGA); 2825 } else { 2826 if (!TM.isPositionIndependent()) 2827 GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT); 2828 else if (picLevel == PICLevel::SmallPIC) 2829 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT); 2830 else 2831 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT); 2832 } 2833 SDValue TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl, 2834 PtrVT, TGA, GOTPtr); 2835 return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS); 2836 } 2837 2838 if (Model == TLSModel::GeneralDynamic) { 2839 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0); 2840 SDValue GOTPtr; 2841 if (is64bit) { 2842 setUsesTOCBasePtr(DAG); 2843 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64); 2844 GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT, 2845 GOTReg, TGA); 2846 } else { 2847 if (picLevel == PICLevel::SmallPIC) 2848 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT); 2849 else 2850 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT); 2851 } 2852 return DAG.getNode(PPCISD::ADDI_TLSGD_L_ADDR, dl, PtrVT, 2853 GOTPtr, TGA, TGA); 2854 } 2855 2856 if (Model == TLSModel::LocalDynamic) { 2857 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0); 2858 SDValue GOTPtr; 2859 if (is64bit) { 2860 setUsesTOCBasePtr(DAG); 2861 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64); 2862 GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT, 2863 GOTReg, TGA); 2864 } else { 2865 if (picLevel == PICLevel::SmallPIC) 2866 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT); 2867 else 2868 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT); 2869 } 2870 SDValue TLSAddr = DAG.getNode(PPCISD::ADDI_TLSLD_L_ADDR, dl, 2871 PtrVT, GOTPtr, TGA, TGA); 2872 SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl, 2873 PtrVT, TLSAddr, TGA); 2874 return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA); 2875 } 2876 2877 llvm_unreachable("Unknown TLS model!"); 2878 } 2879 2880 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op, 2881 SelectionDAG &DAG) const { 2882 EVT PtrVT = Op.getValueType(); 2883 GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op); 2884 SDLoc DL(GSDN); 2885 const GlobalValue *GV = GSDN->getGlobal(); 2886 2887 // 64-bit SVR4 ABI code is always position-independent. 2888 // The actual address of the GlobalValue is stored in the TOC. 2889 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) { 2890 setUsesTOCBasePtr(DAG); 2891 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset()); 2892 return getTOCEntry(DAG, DL, true, GA); 2893 } 2894 2895 unsigned MOHiFlag, MOLoFlag; 2896 bool IsPIC = isPositionIndependent(); 2897 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag, GV); 2898 2899 if (IsPIC && Subtarget.isSVR4ABI()) { 2900 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 2901 GSDN->getOffset(), 2902 PPCII::MO_PIC_FLAG); 2903 return getTOCEntry(DAG, DL, false, GA); 2904 } 2905 2906 SDValue GAHi = 2907 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag); 2908 SDValue GALo = 2909 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag); 2910 2911 SDValue Ptr = LowerLabelRef(GAHi, GALo, IsPIC, DAG); 2912 2913 // If the global reference is actually to a non-lazy-pointer, we have to do an 2914 // extra load to get the address of the global. 2915 if (MOHiFlag & PPCII::MO_NLP_FLAG) 2916 Ptr = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo()); 2917 return Ptr; 2918 } 2919 2920 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const { 2921 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get(); 2922 SDLoc dl(Op); 2923 2924 if (Op.getValueType() == MVT::v2i64) { 2925 // When the operands themselves are v2i64 values, we need to do something 2926 // special because VSX has no underlying comparison operations for these. 2927 if (Op.getOperand(0).getValueType() == MVT::v2i64) { 2928 // Equality can be handled by casting to the legal type for Altivec 2929 // comparisons, everything else needs to be expanded. 2930 if (CC == ISD::SETEQ || CC == ISD::SETNE) { 2931 return DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, 2932 DAG.getSetCC(dl, MVT::v4i32, 2933 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0)), 2934 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(1)), 2935 CC)); 2936 } 2937 2938 return SDValue(); 2939 } 2940 2941 // We handle most of these in the usual way. 2942 return Op; 2943 } 2944 2945 // If we're comparing for equality to zero, expose the fact that this is 2946 // implemented as a ctlz/srl pair on ppc, so that the dag combiner can 2947 // fold the new nodes. 2948 if (SDValue V = lowerCmpEqZeroToCtlzSrl(Op, DAG)) 2949 return V; 2950 2951 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 2952 // Leave comparisons against 0 and -1 alone for now, since they're usually 2953 // optimized. FIXME: revisit this when we can custom lower all setcc 2954 // optimizations. 2955 if (C->isAllOnesValue() || C->isNullValue()) 2956 return SDValue(); 2957 } 2958 2959 // If we have an integer seteq/setne, turn it into a compare against zero 2960 // by xor'ing the rhs with the lhs, which is faster than setting a 2961 // condition register, reading it back out, and masking the correct bit. The 2962 // normal approach here uses sub to do this instead of xor. Using xor exposes 2963 // the result to other bit-twiddling opportunities. 2964 EVT LHSVT = Op.getOperand(0).getValueType(); 2965 if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) { 2966 EVT VT = Op.getValueType(); 2967 SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0), 2968 Op.getOperand(1)); 2969 return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, dl, LHSVT), CC); 2970 } 2971 return SDValue(); 2972 } 2973 2974 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const { 2975 SDNode *Node = Op.getNode(); 2976 EVT VT = Node->getValueType(0); 2977 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2978 SDValue InChain = Node->getOperand(0); 2979 SDValue VAListPtr = Node->getOperand(1); 2980 const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue(); 2981 SDLoc dl(Node); 2982 2983 assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only"); 2984 2985 // gpr_index 2986 SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain, 2987 VAListPtr, MachinePointerInfo(SV), MVT::i8); 2988 InChain = GprIndex.getValue(1); 2989 2990 if (VT == MVT::i64) { 2991 // Check if GprIndex is even 2992 SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex, 2993 DAG.getConstant(1, dl, MVT::i32)); 2994 SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd, 2995 DAG.getConstant(0, dl, MVT::i32), ISD::SETNE); 2996 SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex, 2997 DAG.getConstant(1, dl, MVT::i32)); 2998 // Align GprIndex to be even if it isn't 2999 GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne, 3000 GprIndex); 3001 } 3002 3003 // fpr index is 1 byte after gpr 3004 SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, 3005 DAG.getConstant(1, dl, MVT::i32)); 3006 3007 // fpr 3008 SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain, 3009 FprPtr, MachinePointerInfo(SV), MVT::i8); 3010 InChain = FprIndex.getValue(1); 3011 3012 SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, 3013 DAG.getConstant(8, dl, MVT::i32)); 3014 3015 SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, 3016 DAG.getConstant(4, dl, MVT::i32)); 3017 3018 // areas 3019 SDValue OverflowArea = 3020 DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr, MachinePointerInfo()); 3021 InChain = OverflowArea.getValue(1); 3022 3023 SDValue RegSaveArea = 3024 DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr, MachinePointerInfo()); 3025 InChain = RegSaveArea.getValue(1); 3026 3027 // select overflow_area if index > 8 3028 SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex, 3029 DAG.getConstant(8, dl, MVT::i32), ISD::SETLT); 3030 3031 // adjustment constant gpr_index * 4/8 3032 SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32, 3033 VT.isInteger() ? GprIndex : FprIndex, 3034 DAG.getConstant(VT.isInteger() ? 4 : 8, dl, 3035 MVT::i32)); 3036 3037 // OurReg = RegSaveArea + RegConstant 3038 SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea, 3039 RegConstant); 3040 3041 // Floating types are 32 bytes into RegSaveArea 3042 if (VT.isFloatingPoint()) 3043 OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg, 3044 DAG.getConstant(32, dl, MVT::i32)); 3045 3046 // increase {f,g}pr_index by 1 (or 2 if VT is i64) 3047 SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32, 3048 VT.isInteger() ? GprIndex : FprIndex, 3049 DAG.getConstant(VT == MVT::i64 ? 2 : 1, dl, 3050 MVT::i32)); 3051 3052 InChain = DAG.getTruncStore(InChain, dl, IndexPlus1, 3053 VT.isInteger() ? VAListPtr : FprPtr, 3054 MachinePointerInfo(SV), MVT::i8); 3055 3056 // determine if we should load from reg_save_area or overflow_area 3057 SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea); 3058 3059 // increase overflow_area by 4/8 if gpr/fpr > 8 3060 SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea, 3061 DAG.getConstant(VT.isInteger() ? 4 : 8, 3062 dl, MVT::i32)); 3063 3064 OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea, 3065 OverflowAreaPlusN); 3066 3067 InChain = DAG.getTruncStore(InChain, dl, OverflowArea, OverflowAreaPtr, 3068 MachinePointerInfo(), MVT::i32); 3069 3070 return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo()); 3071 } 3072 3073 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const { 3074 assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only"); 3075 3076 // We have to copy the entire va_list struct: 3077 // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte 3078 return DAG.getMemcpy(Op.getOperand(0), Op, 3079 Op.getOperand(1), Op.getOperand(2), 3080 DAG.getConstant(12, SDLoc(Op), MVT::i32), 8, false, true, 3081 false, MachinePointerInfo(), MachinePointerInfo()); 3082 } 3083 3084 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op, 3085 SelectionDAG &DAG) const { 3086 return Op.getOperand(0); 3087 } 3088 3089 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op, 3090 SelectionDAG &DAG) const { 3091 SDValue Chain = Op.getOperand(0); 3092 SDValue Trmp = Op.getOperand(1); // trampoline 3093 SDValue FPtr = Op.getOperand(2); // nested function 3094 SDValue Nest = Op.getOperand(3); // 'nest' parameter value 3095 SDLoc dl(Op); 3096 3097 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3098 bool isPPC64 = (PtrVT == MVT::i64); 3099 Type *IntPtrTy = DAG.getDataLayout().getIntPtrType(*DAG.getContext()); 3100 3101 TargetLowering::ArgListTy Args; 3102 TargetLowering::ArgListEntry Entry; 3103 3104 Entry.Ty = IntPtrTy; 3105 Entry.Node = Trmp; Args.push_back(Entry); 3106 3107 // TrampSize == (isPPC64 ? 48 : 40); 3108 Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40, dl, 3109 isPPC64 ? MVT::i64 : MVT::i32); 3110 Args.push_back(Entry); 3111 3112 Entry.Node = FPtr; Args.push_back(Entry); 3113 Entry.Node = Nest; Args.push_back(Entry); 3114 3115 // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg) 3116 TargetLowering::CallLoweringInfo CLI(DAG); 3117 CLI.setDebugLoc(dl).setChain(Chain).setLibCallee( 3118 CallingConv::C, Type::getVoidTy(*DAG.getContext()), 3119 DAG.getExternalSymbol("__trampoline_setup", PtrVT), std::move(Args)); 3120 3121 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 3122 return CallResult.second; 3123 } 3124 3125 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const { 3126 MachineFunction &MF = DAG.getMachineFunction(); 3127 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 3128 EVT PtrVT = getPointerTy(MF.getDataLayout()); 3129 3130 SDLoc dl(Op); 3131 3132 if (Subtarget.isDarwinABI() || Subtarget.isPPC64()) { 3133 // vastart just stores the address of the VarArgsFrameIndex slot into the 3134 // memory location argument. 3135 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 3136 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 3137 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1), 3138 MachinePointerInfo(SV)); 3139 } 3140 3141 // For the 32-bit SVR4 ABI we follow the layout of the va_list struct. 3142 // We suppose the given va_list is already allocated. 3143 // 3144 // typedef struct { 3145 // char gpr; /* index into the array of 8 GPRs 3146 // * stored in the register save area 3147 // * gpr=0 corresponds to r3, 3148 // * gpr=1 to r4, etc. 3149 // */ 3150 // char fpr; /* index into the array of 8 FPRs 3151 // * stored in the register save area 3152 // * fpr=0 corresponds to f1, 3153 // * fpr=1 to f2, etc. 3154 // */ 3155 // char *overflow_arg_area; 3156 // /* location on stack that holds 3157 // * the next overflow argument 3158 // */ 3159 // char *reg_save_area; 3160 // /* where r3:r10 and f1:f8 (if saved) 3161 // * are stored 3162 // */ 3163 // } va_list[1]; 3164 3165 SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), dl, MVT::i32); 3166 SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), dl, MVT::i32); 3167 SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(), 3168 PtrVT); 3169 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), 3170 PtrVT); 3171 3172 uint64_t FrameOffset = PtrVT.getSizeInBits()/8; 3173 SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, dl, PtrVT); 3174 3175 uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1; 3176 SDValue ConstStackOffset = DAG.getConstant(StackOffset, dl, PtrVT); 3177 3178 uint64_t FPROffset = 1; 3179 SDValue ConstFPROffset = DAG.getConstant(FPROffset, dl, PtrVT); 3180 3181 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 3182 3183 // Store first byte : number of int regs 3184 SDValue firstStore = 3185 DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR, Op.getOperand(1), 3186 MachinePointerInfo(SV), MVT::i8); 3187 uint64_t nextOffset = FPROffset; 3188 SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1), 3189 ConstFPROffset); 3190 3191 // Store second byte : number of float regs 3192 SDValue secondStore = 3193 DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr, 3194 MachinePointerInfo(SV, nextOffset), MVT::i8); 3195 nextOffset += StackOffset; 3196 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset); 3197 3198 // Store second word : arguments given on stack 3199 SDValue thirdStore = DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr, 3200 MachinePointerInfo(SV, nextOffset)); 3201 nextOffset += FrameOffset; 3202 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset); 3203 3204 // Store third word : arguments given in registers 3205 return DAG.getStore(thirdStore, dl, FR, nextPtr, 3206 MachinePointerInfo(SV, nextOffset)); 3207 } 3208 3209 /// FPR - The set of FP registers that should be allocated for arguments, 3210 /// on Darwin. 3211 static const MCPhysReg FPR[] = {PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, 3212 PPC::F6, PPC::F7, PPC::F8, PPC::F9, PPC::F10, 3213 PPC::F11, PPC::F12, PPC::F13}; 3214 3215 /// QFPR - The set of QPX registers that should be allocated for arguments. 3216 static const MCPhysReg QFPR[] = { 3217 PPC::QF1, PPC::QF2, PPC::QF3, PPC::QF4, PPC::QF5, PPC::QF6, PPC::QF7, 3218 PPC::QF8, PPC::QF9, PPC::QF10, PPC::QF11, PPC::QF12, PPC::QF13}; 3219 3220 /// CalculateStackSlotSize - Calculates the size reserved for this argument on 3221 /// the stack. 3222 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags, 3223 unsigned PtrByteSize) { 3224 unsigned ArgSize = ArgVT.getStoreSize(); 3225 if (Flags.isByVal()) 3226 ArgSize = Flags.getByValSize(); 3227 3228 // Round up to multiples of the pointer size, except for array members, 3229 // which are always packed. 3230 if (!Flags.isInConsecutiveRegs()) 3231 ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3232 3233 return ArgSize; 3234 } 3235 3236 /// CalculateStackSlotAlignment - Calculates the alignment of this argument 3237 /// on the stack. 3238 static unsigned CalculateStackSlotAlignment(EVT ArgVT, EVT OrigVT, 3239 ISD::ArgFlagsTy Flags, 3240 unsigned PtrByteSize) { 3241 unsigned Align = PtrByteSize; 3242 3243 // Altivec parameters are padded to a 16 byte boundary. 3244 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 || 3245 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 || 3246 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 || 3247 ArgVT == MVT::v1i128 || ArgVT == MVT::f128) 3248 Align = 16; 3249 // QPX vector types stored in double-precision are padded to a 32 byte 3250 // boundary. 3251 else if (ArgVT == MVT::v4f64 || ArgVT == MVT::v4i1) 3252 Align = 32; 3253 3254 // ByVal parameters are aligned as requested. 3255 if (Flags.isByVal()) { 3256 unsigned BVAlign = Flags.getByValAlign(); 3257 if (BVAlign > PtrByteSize) { 3258 if (BVAlign % PtrByteSize != 0) 3259 llvm_unreachable( 3260 "ByVal alignment is not a multiple of the pointer size"); 3261 3262 Align = BVAlign; 3263 } 3264 } 3265 3266 // Array members are always packed to their original alignment. 3267 if (Flags.isInConsecutiveRegs()) { 3268 // If the array member was split into multiple registers, the first 3269 // needs to be aligned to the size of the full type. (Except for 3270 // ppcf128, which is only aligned as its f64 components.) 3271 if (Flags.isSplit() && OrigVT != MVT::ppcf128) 3272 Align = OrigVT.getStoreSize(); 3273 else 3274 Align = ArgVT.getStoreSize(); 3275 } 3276 3277 return Align; 3278 } 3279 3280 /// CalculateStackSlotUsed - Return whether this argument will use its 3281 /// stack slot (instead of being passed in registers). ArgOffset, 3282 /// AvailableFPRs, and AvailableVRs must hold the current argument 3283 /// position, and will be updated to account for this argument. 3284 static bool CalculateStackSlotUsed(EVT ArgVT, EVT OrigVT, 3285 ISD::ArgFlagsTy Flags, 3286 unsigned PtrByteSize, 3287 unsigned LinkageSize, 3288 unsigned ParamAreaSize, 3289 unsigned &ArgOffset, 3290 unsigned &AvailableFPRs, 3291 unsigned &AvailableVRs, bool HasQPX) { 3292 bool UseMemory = false; 3293 3294 // Respect alignment of argument on the stack. 3295 unsigned Align = 3296 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize); 3297 ArgOffset = ((ArgOffset + Align - 1) / Align) * Align; 3298 // If there's no space left in the argument save area, we must 3299 // use memory (this check also catches zero-sized arguments). 3300 if (ArgOffset >= LinkageSize + ParamAreaSize) 3301 UseMemory = true; 3302 3303 // Allocate argument on the stack. 3304 ArgOffset += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize); 3305 if (Flags.isInConsecutiveRegsLast()) 3306 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3307 // If we overran the argument save area, we must use memory 3308 // (this check catches arguments passed partially in memory) 3309 if (ArgOffset > LinkageSize + ParamAreaSize) 3310 UseMemory = true; 3311 3312 // However, if the argument is actually passed in an FPR or a VR, 3313 // we don't use memory after all. 3314 if (!Flags.isByVal()) { 3315 if (ArgVT == MVT::f32 || ArgVT == MVT::f64 || 3316 // QPX registers overlap with the scalar FP registers. 3317 (HasQPX && (ArgVT == MVT::v4f32 || 3318 ArgVT == MVT::v4f64 || 3319 ArgVT == MVT::v4i1))) 3320 if (AvailableFPRs > 0) { 3321 --AvailableFPRs; 3322 return false; 3323 } 3324 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 || 3325 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 || 3326 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 || 3327 ArgVT == MVT::v1i128 || ArgVT == MVT::f128) 3328 if (AvailableVRs > 0) { 3329 --AvailableVRs; 3330 return false; 3331 } 3332 } 3333 3334 return UseMemory; 3335 } 3336 3337 /// EnsureStackAlignment - Round stack frame size up from NumBytes to 3338 /// ensure minimum alignment required for target. 3339 static unsigned EnsureStackAlignment(const PPCFrameLowering *Lowering, 3340 unsigned NumBytes) { 3341 unsigned TargetAlign = Lowering->getStackAlignment(); 3342 unsigned AlignMask = TargetAlign - 1; 3343 NumBytes = (NumBytes + AlignMask) & ~AlignMask; 3344 return NumBytes; 3345 } 3346 3347 SDValue PPCTargetLowering::LowerFormalArguments( 3348 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3349 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3350 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3351 if (Subtarget.isSVR4ABI()) { 3352 if (Subtarget.isPPC64()) 3353 return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins, 3354 dl, DAG, InVals); 3355 else 3356 return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins, 3357 dl, DAG, InVals); 3358 } else { 3359 return LowerFormalArguments_Darwin(Chain, CallConv, isVarArg, Ins, 3360 dl, DAG, InVals); 3361 } 3362 } 3363 3364 SDValue PPCTargetLowering::LowerFormalArguments_32SVR4( 3365 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3366 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3367 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3368 3369 // 32-bit SVR4 ABI Stack Frame Layout: 3370 // +-----------------------------------+ 3371 // +--> | Back chain | 3372 // | +-----------------------------------+ 3373 // | | Floating-point register save area | 3374 // | +-----------------------------------+ 3375 // | | General register save area | 3376 // | +-----------------------------------+ 3377 // | | CR save word | 3378 // | +-----------------------------------+ 3379 // | | VRSAVE save word | 3380 // | +-----------------------------------+ 3381 // | | Alignment padding | 3382 // | +-----------------------------------+ 3383 // | | Vector register save area | 3384 // | +-----------------------------------+ 3385 // | | Local variable space | 3386 // | +-----------------------------------+ 3387 // | | Parameter list area | 3388 // | +-----------------------------------+ 3389 // | | LR save word | 3390 // | +-----------------------------------+ 3391 // SP--> +--- | Back chain | 3392 // +-----------------------------------+ 3393 // 3394 // Specifications: 3395 // System V Application Binary Interface PowerPC Processor Supplement 3396 // AltiVec Technology Programming Interface Manual 3397 3398 MachineFunction &MF = DAG.getMachineFunction(); 3399 MachineFrameInfo &MFI = MF.getFrameInfo(); 3400 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 3401 3402 EVT PtrVT = getPointerTy(MF.getDataLayout()); 3403 // Potential tail calls could cause overwriting of argument stack slots. 3404 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt && 3405 (CallConv == CallingConv::Fast)); 3406 unsigned PtrByteSize = 4; 3407 3408 // Assign locations to all of the incoming arguments. 3409 SmallVector<CCValAssign, 16> ArgLocs; 3410 PPCCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 3411 *DAG.getContext()); 3412 3413 // Reserve space for the linkage area on the stack. 3414 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 3415 CCInfo.AllocateStack(LinkageSize, PtrByteSize); 3416 if (useSoftFloat()) 3417 CCInfo.PreAnalyzeFormalArguments(Ins); 3418 3419 CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4); 3420 CCInfo.clearWasPPCF128(); 3421 3422 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 3423 CCValAssign &VA = ArgLocs[i]; 3424 3425 // Arguments stored in registers. 3426 if (VA.isRegLoc()) { 3427 const TargetRegisterClass *RC; 3428 EVT ValVT = VA.getValVT(); 3429 3430 switch (ValVT.getSimpleVT().SimpleTy) { 3431 default: 3432 llvm_unreachable("ValVT not supported by formal arguments Lowering"); 3433 case MVT::i1: 3434 case MVT::i32: 3435 RC = &PPC::GPRCRegClass; 3436 break; 3437 case MVT::f32: 3438 if (Subtarget.hasP8Vector()) 3439 RC = &PPC::VSSRCRegClass; 3440 else if (Subtarget.hasSPE()) 3441 RC = &PPC::SPE4RCRegClass; 3442 else 3443 RC = &PPC::F4RCRegClass; 3444 break; 3445 case MVT::f64: 3446 if (Subtarget.hasVSX()) 3447 RC = &PPC::VSFRCRegClass; 3448 else if (Subtarget.hasSPE()) 3449 // SPE passes doubles in GPR pairs. 3450 RC = &PPC::GPRCRegClass; 3451 else 3452 RC = &PPC::F8RCRegClass; 3453 break; 3454 case MVT::v16i8: 3455 case MVT::v8i16: 3456 case MVT::v4i32: 3457 RC = &PPC::VRRCRegClass; 3458 break; 3459 case MVT::v4f32: 3460 RC = Subtarget.hasQPX() ? &PPC::QSRCRegClass : &PPC::VRRCRegClass; 3461 break; 3462 case MVT::v2f64: 3463 case MVT::v2i64: 3464 RC = &PPC::VRRCRegClass; 3465 break; 3466 case MVT::v4f64: 3467 RC = &PPC::QFRCRegClass; 3468 break; 3469 case MVT::v4i1: 3470 RC = &PPC::QBRCRegClass; 3471 break; 3472 } 3473 3474 SDValue ArgValue; 3475 // Transform the arguments stored in physical registers into 3476 // virtual ones. 3477 if (VA.getLocVT() == MVT::f64 && Subtarget.hasSPE()) { 3478 assert(i + 1 < e && "No second half of double precision argument"); 3479 unsigned RegLo = MF.addLiveIn(VA.getLocReg(), RC); 3480 unsigned RegHi = MF.addLiveIn(ArgLocs[++i].getLocReg(), RC); 3481 SDValue ArgValueLo = DAG.getCopyFromReg(Chain, dl, RegLo, MVT::i32); 3482 SDValue ArgValueHi = DAG.getCopyFromReg(Chain, dl, RegHi, MVT::i32); 3483 if (!Subtarget.isLittleEndian()) 3484 std::swap (ArgValueLo, ArgValueHi); 3485 ArgValue = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, ArgValueLo, 3486 ArgValueHi); 3487 } else { 3488 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC); 3489 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, 3490 ValVT == MVT::i1 ? MVT::i32 : ValVT); 3491 if (ValVT == MVT::i1) 3492 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue); 3493 } 3494 3495 InVals.push_back(ArgValue); 3496 } else { 3497 // Argument stored in memory. 3498 assert(VA.isMemLoc()); 3499 3500 // Get the extended size of the argument type in stack 3501 unsigned ArgSize = VA.getLocVT().getStoreSize(); 3502 // Get the actual size of the argument type 3503 unsigned ObjSize = VA.getValVT().getStoreSize(); 3504 unsigned ArgOffset = VA.getLocMemOffset(); 3505 // Stack objects in PPC32 are right justified. 3506 ArgOffset += ArgSize - ObjSize; 3507 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, isImmutable); 3508 3509 // Create load nodes to retrieve arguments from the stack. 3510 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3511 InVals.push_back( 3512 DAG.getLoad(VA.getValVT(), dl, Chain, FIN, MachinePointerInfo())); 3513 } 3514 } 3515 3516 // Assign locations to all of the incoming aggregate by value arguments. 3517 // Aggregates passed by value are stored in the local variable space of the 3518 // caller's stack frame, right above the parameter list area. 3519 SmallVector<CCValAssign, 16> ByValArgLocs; 3520 CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(), 3521 ByValArgLocs, *DAG.getContext()); 3522 3523 // Reserve stack space for the allocations in CCInfo. 3524 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize); 3525 3526 CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal); 3527 3528 // Area that is at least reserved in the caller of this function. 3529 unsigned MinReservedArea = CCByValInfo.getNextStackOffset(); 3530 MinReservedArea = std::max(MinReservedArea, LinkageSize); 3531 3532 // Set the size that is at least reserved in caller of this function. Tail 3533 // call optimized function's reserved stack space needs to be aligned so that 3534 // taking the difference between two stack areas will result in an aligned 3535 // stack. 3536 MinReservedArea = 3537 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea); 3538 FuncInfo->setMinReservedArea(MinReservedArea); 3539 3540 SmallVector<SDValue, 8> MemOps; 3541 3542 // If the function takes variable number of arguments, make a frame index for 3543 // the start of the first vararg value... for expansion of llvm.va_start. 3544 if (isVarArg) { 3545 static const MCPhysReg GPArgRegs[] = { 3546 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 3547 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 3548 }; 3549 const unsigned NumGPArgRegs = array_lengthof(GPArgRegs); 3550 3551 static const MCPhysReg FPArgRegs[] = { 3552 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7, 3553 PPC::F8 3554 }; 3555 unsigned NumFPArgRegs = array_lengthof(FPArgRegs); 3556 3557 if (useSoftFloat() || hasSPE()) 3558 NumFPArgRegs = 0; 3559 3560 FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs)); 3561 FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs)); 3562 3563 // Make room for NumGPArgRegs and NumFPArgRegs. 3564 int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 + 3565 NumFPArgRegs * MVT(MVT::f64).getSizeInBits()/8; 3566 3567 FuncInfo->setVarArgsStackOffset( 3568 MFI.CreateFixedObject(PtrVT.getSizeInBits()/8, 3569 CCInfo.getNextStackOffset(), true)); 3570 3571 FuncInfo->setVarArgsFrameIndex(MFI.CreateStackObject(Depth, 8, false)); 3572 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 3573 3574 // The fixed integer arguments of a variadic function are stored to the 3575 // VarArgsFrameIndex on the stack so that they may be loaded by 3576 // dereferencing the result of va_next. 3577 for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) { 3578 // Get an existing live-in vreg, or add a new one. 3579 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]); 3580 if (!VReg) 3581 VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass); 3582 3583 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 3584 SDValue Store = 3585 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 3586 MemOps.push_back(Store); 3587 // Increment the address by four for the next argument to store 3588 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT); 3589 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 3590 } 3591 3592 // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6 3593 // is set. 3594 // The double arguments are stored to the VarArgsFrameIndex 3595 // on the stack. 3596 for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) { 3597 // Get an existing live-in vreg, or add a new one. 3598 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]); 3599 if (!VReg) 3600 VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass); 3601 3602 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64); 3603 SDValue Store = 3604 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 3605 MemOps.push_back(Store); 3606 // Increment the address by eight for the next argument to store 3607 SDValue PtrOff = DAG.getConstant(MVT(MVT::f64).getSizeInBits()/8, dl, 3608 PtrVT); 3609 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 3610 } 3611 } 3612 3613 if (!MemOps.empty()) 3614 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 3615 3616 return Chain; 3617 } 3618 3619 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote 3620 // value to MVT::i64 and then truncate to the correct register size. 3621 SDValue PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags, 3622 EVT ObjectVT, SelectionDAG &DAG, 3623 SDValue ArgVal, 3624 const SDLoc &dl) const { 3625 if (Flags.isSExt()) 3626 ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal, 3627 DAG.getValueType(ObjectVT)); 3628 else if (Flags.isZExt()) 3629 ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal, 3630 DAG.getValueType(ObjectVT)); 3631 3632 return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal); 3633 } 3634 3635 SDValue PPCTargetLowering::LowerFormalArguments_64SVR4( 3636 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3637 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3638 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3639 // TODO: add description of PPC stack frame format, or at least some docs. 3640 // 3641 bool isELFv2ABI = Subtarget.isELFv2ABI(); 3642 bool isLittleEndian = Subtarget.isLittleEndian(); 3643 MachineFunction &MF = DAG.getMachineFunction(); 3644 MachineFrameInfo &MFI = MF.getFrameInfo(); 3645 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 3646 3647 assert(!(CallConv == CallingConv::Fast && isVarArg) && 3648 "fastcc not supported on varargs functions"); 3649 3650 EVT PtrVT = getPointerTy(MF.getDataLayout()); 3651 // Potential tail calls could cause overwriting of argument stack slots. 3652 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt && 3653 (CallConv == CallingConv::Fast)); 3654 unsigned PtrByteSize = 8; 3655 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 3656 3657 static const MCPhysReg GPR[] = { 3658 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 3659 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 3660 }; 3661 static const MCPhysReg VR[] = { 3662 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 3663 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 3664 }; 3665 3666 const unsigned Num_GPR_Regs = array_lengthof(GPR); 3667 const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13; 3668 const unsigned Num_VR_Regs = array_lengthof(VR); 3669 const unsigned Num_QFPR_Regs = Num_FPR_Regs; 3670 3671 // Do a first pass over the arguments to determine whether the ABI 3672 // guarantees that our caller has allocated the parameter save area 3673 // on its stack frame. In the ELFv1 ABI, this is always the case; 3674 // in the ELFv2 ABI, it is true if this is a vararg function or if 3675 // any parameter is located in a stack slot. 3676 3677 bool HasParameterArea = !isELFv2ABI || isVarArg; 3678 unsigned ParamAreaSize = Num_GPR_Regs * PtrByteSize; 3679 unsigned NumBytes = LinkageSize; 3680 unsigned AvailableFPRs = Num_FPR_Regs; 3681 unsigned AvailableVRs = Num_VR_Regs; 3682 for (unsigned i = 0, e = Ins.size(); i != e; ++i) { 3683 if (Ins[i].Flags.isNest()) 3684 continue; 3685 3686 if (CalculateStackSlotUsed(Ins[i].VT, Ins[i].ArgVT, Ins[i].Flags, 3687 PtrByteSize, LinkageSize, ParamAreaSize, 3688 NumBytes, AvailableFPRs, AvailableVRs, 3689 Subtarget.hasQPX())) 3690 HasParameterArea = true; 3691 } 3692 3693 // Add DAG nodes to load the arguments or copy them out of registers. On 3694 // entry to a function on PPC, the arguments start after the linkage area, 3695 // although the first ones are often in registers. 3696 3697 unsigned ArgOffset = LinkageSize; 3698 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 3699 unsigned &QFPR_idx = FPR_idx; 3700 SmallVector<SDValue, 8> MemOps; 3701 Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin(); 3702 unsigned CurArgIdx = 0; 3703 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) { 3704 SDValue ArgVal; 3705 bool needsLoad = false; 3706 EVT ObjectVT = Ins[ArgNo].VT; 3707 EVT OrigVT = Ins[ArgNo].ArgVT; 3708 unsigned ObjSize = ObjectVT.getStoreSize(); 3709 unsigned ArgSize = ObjSize; 3710 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags; 3711 if (Ins[ArgNo].isOrigArg()) { 3712 std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx); 3713 CurArgIdx = Ins[ArgNo].getOrigArgIndex(); 3714 } 3715 // We re-align the argument offset for each argument, except when using the 3716 // fast calling convention, when we need to make sure we do that only when 3717 // we'll actually use a stack slot. 3718 unsigned CurArgOffset, Align; 3719 auto ComputeArgOffset = [&]() { 3720 /* Respect alignment of argument on the stack. */ 3721 Align = CalculateStackSlotAlignment(ObjectVT, OrigVT, Flags, PtrByteSize); 3722 ArgOffset = ((ArgOffset + Align - 1) / Align) * Align; 3723 CurArgOffset = ArgOffset; 3724 }; 3725 3726 if (CallConv != CallingConv::Fast) { 3727 ComputeArgOffset(); 3728 3729 /* Compute GPR index associated with argument offset. */ 3730 GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize; 3731 GPR_idx = std::min(GPR_idx, Num_GPR_Regs); 3732 } 3733 3734 // FIXME the codegen can be much improved in some cases. 3735 // We do not have to keep everything in memory. 3736 if (Flags.isByVal()) { 3737 assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit"); 3738 3739 if (CallConv == CallingConv::Fast) 3740 ComputeArgOffset(); 3741 3742 // ObjSize is the true size, ArgSize rounded up to multiple of registers. 3743 ObjSize = Flags.getByValSize(); 3744 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3745 // Empty aggregate parameters do not take up registers. Examples: 3746 // struct { } a; 3747 // union { } b; 3748 // int c[0]; 3749 // etc. However, we have to provide a place-holder in InVals, so 3750 // pretend we have an 8-byte item at the current address for that 3751 // purpose. 3752 if (!ObjSize) { 3753 int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true); 3754 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3755 InVals.push_back(FIN); 3756 continue; 3757 } 3758 3759 // Create a stack object covering all stack doublewords occupied 3760 // by the argument. If the argument is (fully or partially) on 3761 // the stack, or if the argument is fully in registers but the 3762 // caller has allocated the parameter save anyway, we can refer 3763 // directly to the caller's stack frame. Otherwise, create a 3764 // local copy in our own frame. 3765 int FI; 3766 if (HasParameterArea || 3767 ArgSize + ArgOffset > LinkageSize + Num_GPR_Regs * PtrByteSize) 3768 FI = MFI.CreateFixedObject(ArgSize, ArgOffset, false, true); 3769 else 3770 FI = MFI.CreateStackObject(ArgSize, Align, false); 3771 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3772 3773 // Handle aggregates smaller than 8 bytes. 3774 if (ObjSize < PtrByteSize) { 3775 // The value of the object is its address, which differs from the 3776 // address of the enclosing doubleword on big-endian systems. 3777 SDValue Arg = FIN; 3778 if (!isLittleEndian) { 3779 SDValue ArgOff = DAG.getConstant(PtrByteSize - ObjSize, dl, PtrVT); 3780 Arg = DAG.getNode(ISD::ADD, dl, ArgOff.getValueType(), Arg, ArgOff); 3781 } 3782 InVals.push_back(Arg); 3783 3784 if (GPR_idx != Num_GPR_Regs) { 3785 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass); 3786 FuncInfo->addLiveInAttr(VReg, Flags); 3787 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 3788 SDValue Store; 3789 3790 if (ObjSize==1 || ObjSize==2 || ObjSize==4) { 3791 EVT ObjType = (ObjSize == 1 ? MVT::i8 : 3792 (ObjSize == 2 ? MVT::i16 : MVT::i32)); 3793 Store = DAG.getTruncStore(Val.getValue(1), dl, Val, Arg, 3794 MachinePointerInfo(&*FuncArg), ObjType); 3795 } else { 3796 // For sizes that don't fit a truncating store (3, 5, 6, 7), 3797 // store the whole register as-is to the parameter save area 3798 // slot. 3799 Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, 3800 MachinePointerInfo(&*FuncArg)); 3801 } 3802 3803 MemOps.push_back(Store); 3804 } 3805 // Whether we copied from a register or not, advance the offset 3806 // into the parameter save area by a full doubleword. 3807 ArgOffset += PtrByteSize; 3808 continue; 3809 } 3810 3811 // The value of the object is its address, which is the address of 3812 // its first stack doubleword. 3813 InVals.push_back(FIN); 3814 3815 // Store whatever pieces of the object are in registers to memory. 3816 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) { 3817 if (GPR_idx == Num_GPR_Regs) 3818 break; 3819 3820 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 3821 FuncInfo->addLiveInAttr(VReg, Flags); 3822 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 3823 SDValue Addr = FIN; 3824 if (j) { 3825 SDValue Off = DAG.getConstant(j, dl, PtrVT); 3826 Addr = DAG.getNode(ISD::ADD, dl, Off.getValueType(), Addr, Off); 3827 } 3828 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, Addr, 3829 MachinePointerInfo(&*FuncArg, j)); 3830 MemOps.push_back(Store); 3831 ++GPR_idx; 3832 } 3833 ArgOffset += ArgSize; 3834 continue; 3835 } 3836 3837 switch (ObjectVT.getSimpleVT().SimpleTy) { 3838 default: llvm_unreachable("Unhandled argument type!"); 3839 case MVT::i1: 3840 case MVT::i32: 3841 case MVT::i64: 3842 if (Flags.isNest()) { 3843 // The 'nest' parameter, if any, is passed in R11. 3844 unsigned VReg = MF.addLiveIn(PPC::X11, &PPC::G8RCRegClass); 3845 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 3846 3847 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1) 3848 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl); 3849 3850 break; 3851 } 3852 3853 // These can be scalar arguments or elements of an integer array type 3854 // passed directly. Clang may use those instead of "byval" aggregate 3855 // types to avoid forcing arguments to memory unnecessarily. 3856 if (GPR_idx != Num_GPR_Regs) { 3857 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass); 3858 FuncInfo->addLiveInAttr(VReg, Flags); 3859 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 3860 3861 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1) 3862 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote 3863 // value to MVT::i64 and then truncate to the correct register size. 3864 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl); 3865 } else { 3866 if (CallConv == CallingConv::Fast) 3867 ComputeArgOffset(); 3868 3869 needsLoad = true; 3870 ArgSize = PtrByteSize; 3871 } 3872 if (CallConv != CallingConv::Fast || needsLoad) 3873 ArgOffset += 8; 3874 break; 3875 3876 case MVT::f32: 3877 case MVT::f64: 3878 // These can be scalar arguments or elements of a float array type 3879 // passed directly. The latter are used to implement ELFv2 homogenous 3880 // float aggregates. 3881 if (FPR_idx != Num_FPR_Regs) { 3882 unsigned VReg; 3883 3884 if (ObjectVT == MVT::f32) 3885 VReg = MF.addLiveIn(FPR[FPR_idx], 3886 Subtarget.hasP8Vector() 3887 ? &PPC::VSSRCRegClass 3888 : &PPC::F4RCRegClass); 3889 else 3890 VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX() 3891 ? &PPC::VSFRCRegClass 3892 : &PPC::F8RCRegClass); 3893 3894 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 3895 ++FPR_idx; 3896 } else if (GPR_idx != Num_GPR_Regs && CallConv != CallingConv::Fast) { 3897 // FIXME: We may want to re-enable this for CallingConv::Fast on the P8 3898 // once we support fp <-> gpr moves. 3899 3900 // This can only ever happen in the presence of f32 array types, 3901 // since otherwise we never run out of FPRs before running out 3902 // of GPRs. 3903 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass); 3904 FuncInfo->addLiveInAttr(VReg, Flags); 3905 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 3906 3907 if (ObjectVT == MVT::f32) { 3908 if ((ArgOffset % PtrByteSize) == (isLittleEndian ? 4 : 0)) 3909 ArgVal = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgVal, 3910 DAG.getConstant(32, dl, MVT::i32)); 3911 ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal); 3912 } 3913 3914 ArgVal = DAG.getNode(ISD::BITCAST, dl, ObjectVT, ArgVal); 3915 } else { 3916 if (CallConv == CallingConv::Fast) 3917 ComputeArgOffset(); 3918 3919 needsLoad = true; 3920 } 3921 3922 // When passing an array of floats, the array occupies consecutive 3923 // space in the argument area; only round up to the next doubleword 3924 // at the end of the array. Otherwise, each float takes 8 bytes. 3925 if (CallConv != CallingConv::Fast || needsLoad) { 3926 ArgSize = Flags.isInConsecutiveRegs() ? ObjSize : PtrByteSize; 3927 ArgOffset += ArgSize; 3928 if (Flags.isInConsecutiveRegsLast()) 3929 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3930 } 3931 break; 3932 case MVT::v4f32: 3933 case MVT::v4i32: 3934 case MVT::v8i16: 3935 case MVT::v16i8: 3936 case MVT::v2f64: 3937 case MVT::v2i64: 3938 case MVT::v1i128: 3939 case MVT::f128: 3940 if (!Subtarget.hasQPX()) { 3941 // These can be scalar arguments or elements of a vector array type 3942 // passed directly. The latter are used to implement ELFv2 homogenous 3943 // vector aggregates. 3944 if (VR_idx != Num_VR_Regs) { 3945 unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass); 3946 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 3947 ++VR_idx; 3948 } else { 3949 if (CallConv == CallingConv::Fast) 3950 ComputeArgOffset(); 3951 needsLoad = true; 3952 } 3953 if (CallConv != CallingConv::Fast || needsLoad) 3954 ArgOffset += 16; 3955 break; 3956 } // not QPX 3957 3958 assert(ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 && 3959 "Invalid QPX parameter type"); 3960 LLVM_FALLTHROUGH; 3961 3962 case MVT::v4f64: 3963 case MVT::v4i1: 3964 // QPX vectors are treated like their scalar floating-point subregisters 3965 // (except that they're larger). 3966 unsigned Sz = ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 ? 16 : 32; 3967 if (QFPR_idx != Num_QFPR_Regs) { 3968 const TargetRegisterClass *RC; 3969 switch (ObjectVT.getSimpleVT().SimpleTy) { 3970 case MVT::v4f64: RC = &PPC::QFRCRegClass; break; 3971 case MVT::v4f32: RC = &PPC::QSRCRegClass; break; 3972 default: RC = &PPC::QBRCRegClass; break; 3973 } 3974 3975 unsigned VReg = MF.addLiveIn(QFPR[QFPR_idx], RC); 3976 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 3977 ++QFPR_idx; 3978 } else { 3979 if (CallConv == CallingConv::Fast) 3980 ComputeArgOffset(); 3981 needsLoad = true; 3982 } 3983 if (CallConv != CallingConv::Fast || needsLoad) 3984 ArgOffset += Sz; 3985 break; 3986 } 3987 3988 // We need to load the argument to a virtual register if we determined 3989 // above that we ran out of physical registers of the appropriate type. 3990 if (needsLoad) { 3991 if (ObjSize < ArgSize && !isLittleEndian) 3992 CurArgOffset += ArgSize - ObjSize; 3993 int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, isImmutable); 3994 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3995 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo()); 3996 } 3997 3998 InVals.push_back(ArgVal); 3999 } 4000 4001 // Area that is at least reserved in the caller of this function. 4002 unsigned MinReservedArea; 4003 if (HasParameterArea) 4004 MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize); 4005 else 4006 MinReservedArea = LinkageSize; 4007 4008 // Set the size that is at least reserved in caller of this function. Tail 4009 // call optimized functions' reserved stack space needs to be aligned so that 4010 // taking the difference between two stack areas will result in an aligned 4011 // stack. 4012 MinReservedArea = 4013 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea); 4014 FuncInfo->setMinReservedArea(MinReservedArea); 4015 4016 // If the function takes variable number of arguments, make a frame index for 4017 // the start of the first vararg value... for expansion of llvm.va_start. 4018 if (isVarArg) { 4019 int Depth = ArgOffset; 4020 4021 FuncInfo->setVarArgsFrameIndex( 4022 MFI.CreateFixedObject(PtrByteSize, Depth, true)); 4023 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 4024 4025 // If this function is vararg, store any remaining integer argument regs 4026 // to their spots on the stack so that they may be loaded by dereferencing 4027 // the result of va_next. 4028 for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize; 4029 GPR_idx < Num_GPR_Regs; ++GPR_idx) { 4030 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4031 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4032 SDValue Store = 4033 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 4034 MemOps.push_back(Store); 4035 // Increment the address by four for the next argument to store 4036 SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT); 4037 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 4038 } 4039 } 4040 4041 if (!MemOps.empty()) 4042 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 4043 4044 return Chain; 4045 } 4046 4047 SDValue PPCTargetLowering::LowerFormalArguments_Darwin( 4048 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 4049 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 4050 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 4051 // TODO: add description of PPC stack frame format, or at least some docs. 4052 // 4053 MachineFunction &MF = DAG.getMachineFunction(); 4054 MachineFrameInfo &MFI = MF.getFrameInfo(); 4055 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 4056 4057 EVT PtrVT = getPointerTy(MF.getDataLayout()); 4058 bool isPPC64 = PtrVT == MVT::i64; 4059 // Potential tail calls could cause overwriting of argument stack slots. 4060 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt && 4061 (CallConv == CallingConv::Fast)); 4062 unsigned PtrByteSize = isPPC64 ? 8 : 4; 4063 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 4064 unsigned ArgOffset = LinkageSize; 4065 // Area that is at least reserved in caller of this function. 4066 unsigned MinReservedArea = ArgOffset; 4067 4068 static const MCPhysReg GPR_32[] = { // 32-bit registers. 4069 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 4070 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 4071 }; 4072 static const MCPhysReg GPR_64[] = { // 64-bit registers. 4073 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 4074 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 4075 }; 4076 static const MCPhysReg VR[] = { 4077 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 4078 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 4079 }; 4080 4081 const unsigned Num_GPR_Regs = array_lengthof(GPR_32); 4082 const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13; 4083 const unsigned Num_VR_Regs = array_lengthof( VR); 4084 4085 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 4086 4087 const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32; 4088 4089 // In 32-bit non-varargs functions, the stack space for vectors is after the 4090 // stack space for non-vectors. We do not use this space unless we have 4091 // too many vectors to fit in registers, something that only occurs in 4092 // constructed examples:), but we have to walk the arglist to figure 4093 // that out...for the pathological case, compute VecArgOffset as the 4094 // start of the vector parameter area. Computing VecArgOffset is the 4095 // entire point of the following loop. 4096 unsigned VecArgOffset = ArgOffset; 4097 if (!isVarArg && !isPPC64) { 4098 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; 4099 ++ArgNo) { 4100 EVT ObjectVT = Ins[ArgNo].VT; 4101 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags; 4102 4103 if (Flags.isByVal()) { 4104 // ObjSize is the true size, ArgSize rounded up to multiple of regs. 4105 unsigned ObjSize = Flags.getByValSize(); 4106 unsigned ArgSize = 4107 ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 4108 VecArgOffset += ArgSize; 4109 continue; 4110 } 4111 4112 switch(ObjectVT.getSimpleVT().SimpleTy) { 4113 default: llvm_unreachable("Unhandled argument type!"); 4114 case MVT::i1: 4115 case MVT::i32: 4116 case MVT::f32: 4117 VecArgOffset += 4; 4118 break; 4119 case MVT::i64: // PPC64 4120 case MVT::f64: 4121 // FIXME: We are guaranteed to be !isPPC64 at this point. 4122 // Does MVT::i64 apply? 4123 VecArgOffset += 8; 4124 break; 4125 case MVT::v4f32: 4126 case MVT::v4i32: 4127 case MVT::v8i16: 4128 case MVT::v16i8: 4129 // Nothing to do, we're only looking at Nonvector args here. 4130 break; 4131 } 4132 } 4133 } 4134 // We've found where the vector parameter area in memory is. Skip the 4135 // first 12 parameters; these don't use that memory. 4136 VecArgOffset = ((VecArgOffset+15)/16)*16; 4137 VecArgOffset += 12*16; 4138 4139 // Add DAG nodes to load the arguments or copy them out of registers. On 4140 // entry to a function on PPC, the arguments start after the linkage area, 4141 // although the first ones are often in registers. 4142 4143 SmallVector<SDValue, 8> MemOps; 4144 unsigned nAltivecParamsAtEnd = 0; 4145 Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin(); 4146 unsigned CurArgIdx = 0; 4147 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) { 4148 SDValue ArgVal; 4149 bool needsLoad = false; 4150 EVT ObjectVT = Ins[ArgNo].VT; 4151 unsigned ObjSize = ObjectVT.getSizeInBits()/8; 4152 unsigned ArgSize = ObjSize; 4153 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags; 4154 if (Ins[ArgNo].isOrigArg()) { 4155 std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx); 4156 CurArgIdx = Ins[ArgNo].getOrigArgIndex(); 4157 } 4158 unsigned CurArgOffset = ArgOffset; 4159 4160 // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary. 4161 if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 || 4162 ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) { 4163 if (isVarArg || isPPC64) { 4164 MinReservedArea = ((MinReservedArea+15)/16)*16; 4165 MinReservedArea += CalculateStackSlotSize(ObjectVT, 4166 Flags, 4167 PtrByteSize); 4168 } else nAltivecParamsAtEnd++; 4169 } else 4170 // Calculate min reserved area. 4171 MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT, 4172 Flags, 4173 PtrByteSize); 4174 4175 // FIXME the codegen can be much improved in some cases. 4176 // We do not have to keep everything in memory. 4177 if (Flags.isByVal()) { 4178 assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit"); 4179 4180 // ObjSize is the true size, ArgSize rounded up to multiple of registers. 4181 ObjSize = Flags.getByValSize(); 4182 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 4183 // Objects of size 1 and 2 are right justified, everything else is 4184 // left justified. This means the memory address is adjusted forwards. 4185 if (ObjSize==1 || ObjSize==2) { 4186 CurArgOffset = CurArgOffset + (4 - ObjSize); 4187 } 4188 // The value of the object is its address. 4189 int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, false, true); 4190 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4191 InVals.push_back(FIN); 4192 if (ObjSize==1 || ObjSize==2) { 4193 if (GPR_idx != Num_GPR_Regs) { 4194 unsigned VReg; 4195 if (isPPC64) 4196 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4197 else 4198 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 4199 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4200 EVT ObjType = ObjSize == 1 ? MVT::i8 : MVT::i16; 4201 SDValue Store = 4202 DAG.getTruncStore(Val.getValue(1), dl, Val, FIN, 4203 MachinePointerInfo(&*FuncArg), ObjType); 4204 MemOps.push_back(Store); 4205 ++GPR_idx; 4206 } 4207 4208 ArgOffset += PtrByteSize; 4209 4210 continue; 4211 } 4212 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) { 4213 // Store whatever pieces of the object are in registers 4214 // to memory. ArgOffset will be the address of the beginning 4215 // of the object. 4216 if (GPR_idx != Num_GPR_Regs) { 4217 unsigned VReg; 4218 if (isPPC64) 4219 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4220 else 4221 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 4222 int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true); 4223 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4224 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4225 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, 4226 MachinePointerInfo(&*FuncArg, j)); 4227 MemOps.push_back(Store); 4228 ++GPR_idx; 4229 ArgOffset += PtrByteSize; 4230 } else { 4231 ArgOffset += ArgSize - (ArgOffset-CurArgOffset); 4232 break; 4233 } 4234 } 4235 continue; 4236 } 4237 4238 switch (ObjectVT.getSimpleVT().SimpleTy) { 4239 default: llvm_unreachable("Unhandled argument type!"); 4240 case MVT::i1: 4241 case MVT::i32: 4242 if (!isPPC64) { 4243 if (GPR_idx != Num_GPR_Regs) { 4244 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 4245 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32); 4246 4247 if (ObjectVT == MVT::i1) 4248 ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgVal); 4249 4250 ++GPR_idx; 4251 } else { 4252 needsLoad = true; 4253 ArgSize = PtrByteSize; 4254 } 4255 // All int arguments reserve stack space in the Darwin ABI. 4256 ArgOffset += PtrByteSize; 4257 break; 4258 } 4259 LLVM_FALLTHROUGH; 4260 case MVT::i64: // PPC64 4261 if (GPR_idx != Num_GPR_Regs) { 4262 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4263 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 4264 4265 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1) 4266 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote 4267 // value to MVT::i64 and then truncate to the correct register size. 4268 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl); 4269 4270 ++GPR_idx; 4271 } else { 4272 needsLoad = true; 4273 ArgSize = PtrByteSize; 4274 } 4275 // All int arguments reserve stack space in the Darwin ABI. 4276 ArgOffset += 8; 4277 break; 4278 4279 case MVT::f32: 4280 case MVT::f64: 4281 // Every 4 bytes of argument space consumes one of the GPRs available for 4282 // argument passing. 4283 if (GPR_idx != Num_GPR_Regs) { 4284 ++GPR_idx; 4285 if (ObjSize == 8 && GPR_idx != Num_GPR_Regs && !isPPC64) 4286 ++GPR_idx; 4287 } 4288 if (FPR_idx != Num_FPR_Regs) { 4289 unsigned VReg; 4290 4291 if (ObjectVT == MVT::f32) 4292 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass); 4293 else 4294 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass); 4295 4296 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 4297 ++FPR_idx; 4298 } else { 4299 needsLoad = true; 4300 } 4301 4302 // All FP arguments reserve stack space in the Darwin ABI. 4303 ArgOffset += isPPC64 ? 8 : ObjSize; 4304 break; 4305 case MVT::v4f32: 4306 case MVT::v4i32: 4307 case MVT::v8i16: 4308 case MVT::v16i8: 4309 // Note that vector arguments in registers don't reserve stack space, 4310 // except in varargs functions. 4311 if (VR_idx != Num_VR_Regs) { 4312 unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass); 4313 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 4314 if (isVarArg) { 4315 while ((ArgOffset % 16) != 0) { 4316 ArgOffset += PtrByteSize; 4317 if (GPR_idx != Num_GPR_Regs) 4318 GPR_idx++; 4319 } 4320 ArgOffset += 16; 4321 GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64? 4322 } 4323 ++VR_idx; 4324 } else { 4325 if (!isVarArg && !isPPC64) { 4326 // Vectors go after all the nonvectors. 4327 CurArgOffset = VecArgOffset; 4328 VecArgOffset += 16; 4329 } else { 4330 // Vectors are aligned. 4331 ArgOffset = ((ArgOffset+15)/16)*16; 4332 CurArgOffset = ArgOffset; 4333 ArgOffset += 16; 4334 } 4335 needsLoad = true; 4336 } 4337 break; 4338 } 4339 4340 // We need to load the argument to a virtual register if we determined above 4341 // that we ran out of physical registers of the appropriate type. 4342 if (needsLoad) { 4343 int FI = MFI.CreateFixedObject(ObjSize, 4344 CurArgOffset + (ArgSize - ObjSize), 4345 isImmutable); 4346 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4347 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo()); 4348 } 4349 4350 InVals.push_back(ArgVal); 4351 } 4352 4353 // Allow for Altivec parameters at the end, if needed. 4354 if (nAltivecParamsAtEnd) { 4355 MinReservedArea = ((MinReservedArea+15)/16)*16; 4356 MinReservedArea += 16*nAltivecParamsAtEnd; 4357 } 4358 4359 // Area that is at least reserved in the caller of this function. 4360 MinReservedArea = std::max(MinReservedArea, LinkageSize + 8 * PtrByteSize); 4361 4362 // Set the size that is at least reserved in caller of this function. Tail 4363 // call optimized functions' reserved stack space needs to be aligned so that 4364 // taking the difference between two stack areas will result in an aligned 4365 // stack. 4366 MinReservedArea = 4367 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea); 4368 FuncInfo->setMinReservedArea(MinReservedArea); 4369 4370 // If the function takes variable number of arguments, make a frame index for 4371 // the start of the first vararg value... for expansion of llvm.va_start. 4372 if (isVarArg) { 4373 int Depth = ArgOffset; 4374 4375 FuncInfo->setVarArgsFrameIndex( 4376 MFI.CreateFixedObject(PtrVT.getSizeInBits()/8, 4377 Depth, true)); 4378 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 4379 4380 // If this function is vararg, store any remaining integer argument regs 4381 // to their spots on the stack so that they may be loaded by dereferencing 4382 // the result of va_next. 4383 for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) { 4384 unsigned VReg; 4385 4386 if (isPPC64) 4387 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4388 else 4389 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 4390 4391 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4392 SDValue Store = 4393 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 4394 MemOps.push_back(Store); 4395 // Increment the address by four for the next argument to store 4396 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT); 4397 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 4398 } 4399 } 4400 4401 if (!MemOps.empty()) 4402 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 4403 4404 return Chain; 4405 } 4406 4407 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be 4408 /// adjusted to accommodate the arguments for the tailcall. 4409 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall, 4410 unsigned ParamSize) { 4411 4412 if (!isTailCall) return 0; 4413 4414 PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>(); 4415 unsigned CallerMinReservedArea = FI->getMinReservedArea(); 4416 int SPDiff = (int)CallerMinReservedArea - (int)ParamSize; 4417 // Remember only if the new adjustment is bigger. 4418 if (SPDiff < FI->getTailCallSPDelta()) 4419 FI->setTailCallSPDelta(SPDiff); 4420 4421 return SPDiff; 4422 } 4423 4424 static bool isFunctionGlobalAddress(SDValue Callee); 4425 4426 static bool 4427 callsShareTOCBase(const Function *Caller, SDValue Callee, 4428 const TargetMachine &TM) { 4429 // Need a GlobalValue to determine if a Caller and Callee share the same 4430 // TOCBase. 4431 const GlobalValue *GV = nullptr; 4432 4433 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 4434 GV = G->getGlobal(); 4435 } else if (MCSymbolSDNode *M = dyn_cast<MCSymbolSDNode>(Callee)) { 4436 // On AIX only, we replace GlobalAddressSDNode with MCSymbolSDNode for 4437 // the callee of a direct function call. The MCSymbolSDNode contains the 4438 // MCSymbol for the funtion entry point. 4439 const auto *S = cast<MCSymbolXCOFF>(M->getMCSymbol()); 4440 GV = S->getGlobalValue(); 4441 } 4442 4443 // If we failed to get a GlobalValue, then pessimistically assume they do not 4444 // share a TOCBase. 4445 if (!GV) 4446 return false; 4447 4448 // The medium and large code models are expected to provide a sufficiently 4449 // large TOC to provide all data addressing needs of a module with a 4450 // single TOC. Since each module will be addressed with a single TOC then we 4451 // only need to check that caller and callee don't cross dso boundaries. 4452 if (CodeModel::Medium == TM.getCodeModel() || 4453 CodeModel::Large == TM.getCodeModel()) 4454 return TM.shouldAssumeDSOLocal(*Caller->getParent(), GV); 4455 4456 // Otherwise we need to ensure callee and caller are in the same section, 4457 // since the linker may allocate multiple TOCs, and we don't know which 4458 // sections will belong to the same TOC base. 4459 4460 if (!GV->isStrongDefinitionForLinker()) 4461 return false; 4462 4463 // Any explicitly-specified sections and section prefixes must also match. 4464 // Also, if we're using -ffunction-sections, then each function is always in 4465 // a different section (the same is true for COMDAT functions). 4466 if (TM.getFunctionSections() || GV->hasComdat() || Caller->hasComdat() || 4467 GV->getSection() != Caller->getSection()) 4468 return false; 4469 if (const auto *F = dyn_cast<Function>(GV)) { 4470 if (F->getSectionPrefix() != Caller->getSectionPrefix()) 4471 return false; 4472 } 4473 4474 // If the callee might be interposed, then we can't assume the ultimate call 4475 // target will be in the same section. Even in cases where we can assume that 4476 // interposition won't happen, in any case where the linker might insert a 4477 // stub to allow for interposition, we must generate code as though 4478 // interposition might occur. To understand why this matters, consider a 4479 // situation where: a -> b -> c where the arrows indicate calls. b and c are 4480 // in the same section, but a is in a different module (i.e. has a different 4481 // TOC base pointer). If the linker allows for interposition between b and c, 4482 // then it will generate a stub for the call edge between b and c which will 4483 // save the TOC pointer into the designated stack slot allocated by b. If we 4484 // return true here, and therefore allow a tail call between b and c, that 4485 // stack slot won't exist and the b -> c stub will end up saving b'c TOC base 4486 // pointer into the stack slot allocated by a (where the a -> b stub saved 4487 // a's TOC base pointer). If we're not considering a tail call, but rather, 4488 // whether a nop is needed after the call instruction in b, because the linker 4489 // will insert a stub, it might complain about a missing nop if we omit it 4490 // (although many don't complain in this case). 4491 if (!TM.shouldAssumeDSOLocal(*Caller->getParent(), GV)) 4492 return false; 4493 4494 return true; 4495 } 4496 4497 static bool 4498 needStackSlotPassParameters(const PPCSubtarget &Subtarget, 4499 const SmallVectorImpl<ISD::OutputArg> &Outs) { 4500 assert(Subtarget.isSVR4ABI() && Subtarget.isPPC64()); 4501 4502 const unsigned PtrByteSize = 8; 4503 const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 4504 4505 static const MCPhysReg GPR[] = { 4506 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 4507 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 4508 }; 4509 static const MCPhysReg VR[] = { 4510 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 4511 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 4512 }; 4513 4514 const unsigned NumGPRs = array_lengthof(GPR); 4515 const unsigned NumFPRs = 13; 4516 const unsigned NumVRs = array_lengthof(VR); 4517 const unsigned ParamAreaSize = NumGPRs * PtrByteSize; 4518 4519 unsigned NumBytes = LinkageSize; 4520 unsigned AvailableFPRs = NumFPRs; 4521 unsigned AvailableVRs = NumVRs; 4522 4523 for (const ISD::OutputArg& Param : Outs) { 4524 if (Param.Flags.isNest()) continue; 4525 4526 if (CalculateStackSlotUsed(Param.VT, Param.ArgVT, Param.Flags, 4527 PtrByteSize, LinkageSize, ParamAreaSize, 4528 NumBytes, AvailableFPRs, AvailableVRs, 4529 Subtarget.hasQPX())) 4530 return true; 4531 } 4532 return false; 4533 } 4534 4535 static bool 4536 hasSameArgumentList(const Function *CallerFn, ImmutableCallSite CS) { 4537 if (CS.arg_size() != CallerFn->arg_size()) 4538 return false; 4539 4540 ImmutableCallSite::arg_iterator CalleeArgIter = CS.arg_begin(); 4541 ImmutableCallSite::arg_iterator CalleeArgEnd = CS.arg_end(); 4542 Function::const_arg_iterator CallerArgIter = CallerFn->arg_begin(); 4543 4544 for (; CalleeArgIter != CalleeArgEnd; ++CalleeArgIter, ++CallerArgIter) { 4545 const Value* CalleeArg = *CalleeArgIter; 4546 const Value* CallerArg = &(*CallerArgIter); 4547 if (CalleeArg == CallerArg) 4548 continue; 4549 4550 // e.g. @caller([4 x i64] %a, [4 x i64] %b) { 4551 // tail call @callee([4 x i64] undef, [4 x i64] %b) 4552 // } 4553 // 1st argument of callee is undef and has the same type as caller. 4554 if (CalleeArg->getType() == CallerArg->getType() && 4555 isa<UndefValue>(CalleeArg)) 4556 continue; 4557 4558 return false; 4559 } 4560 4561 return true; 4562 } 4563 4564 // Returns true if TCO is possible between the callers and callees 4565 // calling conventions. 4566 static bool 4567 areCallingConvEligibleForTCO_64SVR4(CallingConv::ID CallerCC, 4568 CallingConv::ID CalleeCC) { 4569 // Tail calls are possible with fastcc and ccc. 4570 auto isTailCallableCC = [] (CallingConv::ID CC){ 4571 return CC == CallingConv::C || CC == CallingConv::Fast; 4572 }; 4573 if (!isTailCallableCC(CallerCC) || !isTailCallableCC(CalleeCC)) 4574 return false; 4575 4576 // We can safely tail call both fastcc and ccc callees from a c calling 4577 // convention caller. If the caller is fastcc, we may have less stack space 4578 // than a non-fastcc caller with the same signature so disable tail-calls in 4579 // that case. 4580 return CallerCC == CallingConv::C || CallerCC == CalleeCC; 4581 } 4582 4583 bool 4584 PPCTargetLowering::IsEligibleForTailCallOptimization_64SVR4( 4585 SDValue Callee, 4586 CallingConv::ID CalleeCC, 4587 ImmutableCallSite CS, 4588 bool isVarArg, 4589 const SmallVectorImpl<ISD::OutputArg> &Outs, 4590 const SmallVectorImpl<ISD::InputArg> &Ins, 4591 SelectionDAG& DAG) const { 4592 bool TailCallOpt = getTargetMachine().Options.GuaranteedTailCallOpt; 4593 4594 if (DisableSCO && !TailCallOpt) return false; 4595 4596 // Variadic argument functions are not supported. 4597 if (isVarArg) return false; 4598 4599 auto &Caller = DAG.getMachineFunction().getFunction(); 4600 // Check that the calling conventions are compatible for tco. 4601 if (!areCallingConvEligibleForTCO_64SVR4(Caller.getCallingConv(), CalleeCC)) 4602 return false; 4603 4604 // Caller contains any byval parameter is not supported. 4605 if (any_of(Ins, [](const ISD::InputArg &IA) { return IA.Flags.isByVal(); })) 4606 return false; 4607 4608 // Callee contains any byval parameter is not supported, too. 4609 // Note: This is a quick work around, because in some cases, e.g. 4610 // caller's stack size > callee's stack size, we are still able to apply 4611 // sibling call optimization. For example, gcc is able to do SCO for caller1 4612 // in the following example, but not for caller2. 4613 // struct test { 4614 // long int a; 4615 // char ary[56]; 4616 // } gTest; 4617 // __attribute__((noinline)) int callee(struct test v, struct test *b) { 4618 // b->a = v.a; 4619 // return 0; 4620 // } 4621 // void caller1(struct test a, struct test c, struct test *b) { 4622 // callee(gTest, b); } 4623 // void caller2(struct test *b) { callee(gTest, b); } 4624 if (any_of(Outs, [](const ISD::OutputArg& OA) { return OA.Flags.isByVal(); })) 4625 return false; 4626 4627 // If callee and caller use different calling conventions, we cannot pass 4628 // parameters on stack since offsets for the parameter area may be different. 4629 if (Caller.getCallingConv() != CalleeCC && 4630 needStackSlotPassParameters(Subtarget, Outs)) 4631 return false; 4632 4633 // No TCO/SCO on indirect call because Caller have to restore its TOC 4634 if (!isFunctionGlobalAddress(Callee) && 4635 !isa<ExternalSymbolSDNode>(Callee)) 4636 return false; 4637 4638 // If the caller and callee potentially have different TOC bases then we 4639 // cannot tail call since we need to restore the TOC pointer after the call. 4640 // ref: https://bugzilla.mozilla.org/show_bug.cgi?id=973977 4641 if (!callsShareTOCBase(&Caller, Callee, getTargetMachine())) 4642 return false; 4643 4644 // TCO allows altering callee ABI, so we don't have to check further. 4645 if (CalleeCC == CallingConv::Fast && TailCallOpt) 4646 return true; 4647 4648 if (DisableSCO) return false; 4649 4650 // If callee use the same argument list that caller is using, then we can 4651 // apply SCO on this case. If it is not, then we need to check if callee needs 4652 // stack for passing arguments. 4653 if (!hasSameArgumentList(&Caller, CS) && 4654 needStackSlotPassParameters(Subtarget, Outs)) { 4655 return false; 4656 } 4657 4658 return true; 4659 } 4660 4661 /// IsEligibleForTailCallOptimization - Check whether the call is eligible 4662 /// for tail call optimization. Targets which want to do tail call 4663 /// optimization should implement this function. 4664 bool 4665 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee, 4666 CallingConv::ID CalleeCC, 4667 bool isVarArg, 4668 const SmallVectorImpl<ISD::InputArg> &Ins, 4669 SelectionDAG& DAG) const { 4670 if (!getTargetMachine().Options.GuaranteedTailCallOpt) 4671 return false; 4672 4673 // Variable argument functions are not supported. 4674 if (isVarArg) 4675 return false; 4676 4677 MachineFunction &MF = DAG.getMachineFunction(); 4678 CallingConv::ID CallerCC = MF.getFunction().getCallingConv(); 4679 if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) { 4680 // Functions containing by val parameters are not supported. 4681 for (unsigned i = 0; i != Ins.size(); i++) { 4682 ISD::ArgFlagsTy Flags = Ins[i].Flags; 4683 if (Flags.isByVal()) return false; 4684 } 4685 4686 // Non-PIC/GOT tail calls are supported. 4687 if (getTargetMachine().getRelocationModel() != Reloc::PIC_) 4688 return true; 4689 4690 // At the moment we can only do local tail calls (in same module, hidden 4691 // or protected) if we are generating PIC. 4692 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) 4693 return G->getGlobal()->hasHiddenVisibility() 4694 || G->getGlobal()->hasProtectedVisibility(); 4695 } 4696 4697 return false; 4698 } 4699 4700 /// isCallCompatibleAddress - Return the immediate to use if the specified 4701 /// 32-bit value is representable in the immediate field of a BxA instruction. 4702 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) { 4703 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op); 4704 if (!C) return nullptr; 4705 4706 int Addr = C->getZExtValue(); 4707 if ((Addr & 3) != 0 || // Low 2 bits are implicitly zero. 4708 SignExtend32<26>(Addr) != Addr) 4709 return nullptr; // Top 6 bits have to be sext of immediate. 4710 4711 return DAG 4712 .getConstant( 4713 (int)C->getZExtValue() >> 2, SDLoc(Op), 4714 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout())) 4715 .getNode(); 4716 } 4717 4718 namespace { 4719 4720 struct TailCallArgumentInfo { 4721 SDValue Arg; 4722 SDValue FrameIdxOp; 4723 int FrameIdx = 0; 4724 4725 TailCallArgumentInfo() = default; 4726 }; 4727 4728 } // end anonymous namespace 4729 4730 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot. 4731 static void StoreTailCallArgumentsToStackSlot( 4732 SelectionDAG &DAG, SDValue Chain, 4733 const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs, 4734 SmallVectorImpl<SDValue> &MemOpChains, const SDLoc &dl) { 4735 for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) { 4736 SDValue Arg = TailCallArgs[i].Arg; 4737 SDValue FIN = TailCallArgs[i].FrameIdxOp; 4738 int FI = TailCallArgs[i].FrameIdx; 4739 // Store relative to framepointer. 4740 MemOpChains.push_back(DAG.getStore( 4741 Chain, dl, Arg, FIN, 4742 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI))); 4743 } 4744 } 4745 4746 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to 4747 /// the appropriate stack slot for the tail call optimized function call. 4748 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG, SDValue Chain, 4749 SDValue OldRetAddr, SDValue OldFP, 4750 int SPDiff, const SDLoc &dl) { 4751 if (SPDiff) { 4752 // Calculate the new stack slot for the return address. 4753 MachineFunction &MF = DAG.getMachineFunction(); 4754 const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>(); 4755 const PPCFrameLowering *FL = Subtarget.getFrameLowering(); 4756 bool isPPC64 = Subtarget.isPPC64(); 4757 int SlotSize = isPPC64 ? 8 : 4; 4758 int NewRetAddrLoc = SPDiff + FL->getReturnSaveOffset(); 4759 int NewRetAddr = MF.getFrameInfo().CreateFixedObject(SlotSize, 4760 NewRetAddrLoc, true); 4761 EVT VT = isPPC64 ? MVT::i64 : MVT::i32; 4762 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT); 4763 Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx, 4764 MachinePointerInfo::getFixedStack(MF, NewRetAddr)); 4765 4766 // When using the 32/64-bit SVR4 ABI there is no need to move the FP stack 4767 // slot as the FP is never overwritten. 4768 if (Subtarget.isDarwinABI()) { 4769 int NewFPLoc = SPDiff + FL->getFramePointerSaveOffset(); 4770 int NewFPIdx = MF.getFrameInfo().CreateFixedObject(SlotSize, NewFPLoc, 4771 true); 4772 SDValue NewFramePtrIdx = DAG.getFrameIndex(NewFPIdx, VT); 4773 Chain = DAG.getStore(Chain, dl, OldFP, NewFramePtrIdx, 4774 MachinePointerInfo::getFixedStack( 4775 DAG.getMachineFunction(), NewFPIdx)); 4776 } 4777 } 4778 return Chain; 4779 } 4780 4781 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate 4782 /// the position of the argument. 4783 static void 4784 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64, 4785 SDValue Arg, int SPDiff, unsigned ArgOffset, 4786 SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) { 4787 int Offset = ArgOffset + SPDiff; 4788 uint32_t OpSize = (Arg.getValueSizeInBits() + 7) / 8; 4789 int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true); 4790 EVT VT = isPPC64 ? MVT::i64 : MVT::i32; 4791 SDValue FIN = DAG.getFrameIndex(FI, VT); 4792 TailCallArgumentInfo Info; 4793 Info.Arg = Arg; 4794 Info.FrameIdxOp = FIN; 4795 Info.FrameIdx = FI; 4796 TailCallArguments.push_back(Info); 4797 } 4798 4799 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address 4800 /// stack slot. Returns the chain as result and the loaded frame pointers in 4801 /// LROpOut/FPOpout. Used when tail calling. 4802 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr( 4803 SelectionDAG &DAG, int SPDiff, SDValue Chain, SDValue &LROpOut, 4804 SDValue &FPOpOut, const SDLoc &dl) const { 4805 if (SPDiff) { 4806 // Load the LR and FP stack slot for later adjusting. 4807 EVT VT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32; 4808 LROpOut = getReturnAddrFrameIndex(DAG); 4809 LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo()); 4810 Chain = SDValue(LROpOut.getNode(), 1); 4811 4812 // When using the 32/64-bit SVR4 ABI there is no need to load the FP stack 4813 // slot as the FP is never overwritten. 4814 if (Subtarget.isDarwinABI()) { 4815 FPOpOut = getFramePointerFrameIndex(DAG); 4816 FPOpOut = DAG.getLoad(VT, dl, Chain, FPOpOut, MachinePointerInfo()); 4817 Chain = SDValue(FPOpOut.getNode(), 1); 4818 } 4819 } 4820 return Chain; 4821 } 4822 4823 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified 4824 /// by "Src" to address "Dst" of size "Size". Alignment information is 4825 /// specified by the specific parameter attribute. The copy will be passed as 4826 /// a byval function parameter. 4827 /// Sometimes what we are copying is the end of a larger object, the part that 4828 /// does not fit in registers. 4829 static SDValue CreateCopyOfByValArgument(SDValue Src, SDValue Dst, 4830 SDValue Chain, ISD::ArgFlagsTy Flags, 4831 SelectionDAG &DAG, const SDLoc &dl) { 4832 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32); 4833 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(), 4834 false, false, false, MachinePointerInfo(), 4835 MachinePointerInfo()); 4836 } 4837 4838 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of 4839 /// tail calls. 4840 static void LowerMemOpCallTo( 4841 SelectionDAG &DAG, MachineFunction &MF, SDValue Chain, SDValue Arg, 4842 SDValue PtrOff, int SPDiff, unsigned ArgOffset, bool isPPC64, 4843 bool isTailCall, bool isVector, SmallVectorImpl<SDValue> &MemOpChains, 4844 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments, const SDLoc &dl) { 4845 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 4846 if (!isTailCall) { 4847 if (isVector) { 4848 SDValue StackPtr; 4849 if (isPPC64) 4850 StackPtr = DAG.getRegister(PPC::X1, MVT::i64); 4851 else 4852 StackPtr = DAG.getRegister(PPC::R1, MVT::i32); 4853 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, 4854 DAG.getConstant(ArgOffset, dl, PtrVT)); 4855 } 4856 MemOpChains.push_back( 4857 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo())); 4858 // Calculate and remember argument location. 4859 } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset, 4860 TailCallArguments); 4861 } 4862 4863 static void 4864 PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain, 4865 const SDLoc &dl, int SPDiff, unsigned NumBytes, SDValue LROp, 4866 SDValue FPOp, 4867 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) { 4868 // Emit a sequence of copyto/copyfrom virtual registers for arguments that 4869 // might overwrite each other in case of tail call optimization. 4870 SmallVector<SDValue, 8> MemOpChains2; 4871 // Do not flag preceding copytoreg stuff together with the following stuff. 4872 InFlag = SDValue(); 4873 StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments, 4874 MemOpChains2, dl); 4875 if (!MemOpChains2.empty()) 4876 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2); 4877 4878 // Store the return address to the appropriate stack slot. 4879 Chain = EmitTailCallStoreFPAndRetAddr(DAG, Chain, LROp, FPOp, SPDiff, dl); 4880 4881 // Emit callseq_end just before tailcall node. 4882 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true), 4883 DAG.getIntPtrConstant(0, dl, true), InFlag, dl); 4884 InFlag = Chain.getValue(1); 4885 } 4886 4887 // Is this global address that of a function that can be called by name? (as 4888 // opposed to something that must hold a descriptor for an indirect call). 4889 static bool isFunctionGlobalAddress(SDValue Callee) { 4890 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 4891 if (Callee.getOpcode() == ISD::GlobalTLSAddress || 4892 Callee.getOpcode() == ISD::TargetGlobalTLSAddress) 4893 return false; 4894 4895 return G->getGlobal()->getValueType()->isFunctionTy(); 4896 } 4897 4898 return false; 4899 } 4900 4901 static unsigned 4902 PrepareCall(SelectionDAG &DAG, SDValue &Callee, SDValue &InFlag, SDValue &Chain, 4903 SDValue CallSeqStart, const SDLoc &dl, int SPDiff, bool isTailCall, 4904 bool isPatchPoint, bool hasNest, 4905 SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass, 4906 SmallVectorImpl<SDValue> &Ops, std::vector<EVT> &NodeTys, 4907 ImmutableCallSite CS, const PPCSubtarget &Subtarget) { 4908 bool isPPC64 = Subtarget.isPPC64(); 4909 bool isSVR4ABI = Subtarget.isSVR4ABI(); 4910 bool isELFv2ABI = Subtarget.isELFv2ABI(); 4911 bool isAIXABI = Subtarget.isAIXABI(); 4912 4913 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 4914 NodeTys.push_back(MVT::Other); // Returns a chain 4915 NodeTys.push_back(MVT::Glue); // Returns a flag for retval copy to use. 4916 4917 unsigned CallOpc = PPCISD::CALL; 4918 4919 bool needIndirectCall = true; 4920 if (!isSVR4ABI || !isPPC64) 4921 if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG)) { 4922 // If this is an absolute destination address, use the munged value. 4923 Callee = SDValue(Dest, 0); 4924 needIndirectCall = false; 4925 } 4926 4927 // PC-relative references to external symbols should go through $stub, unless 4928 // we're building with the leopard linker or later, which automatically 4929 // synthesizes these stubs. 4930 const TargetMachine &TM = DAG.getTarget(); 4931 MachineFunction &MF = DAG.getMachineFunction(); 4932 const Module *Mod = MF.getFunction().getParent(); 4933 const GlobalValue *GV = nullptr; 4934 if (auto *G = dyn_cast<GlobalAddressSDNode>(Callee)) 4935 GV = G->getGlobal(); 4936 bool Local = TM.shouldAssumeDSOLocal(*Mod, GV); 4937 bool UsePlt = !Local && Subtarget.isTargetELF() && !isPPC64; 4938 4939 if (isFunctionGlobalAddress(Callee)) { 4940 GlobalAddressSDNode *G = cast<GlobalAddressSDNode>(Callee); 4941 4942 if (TM.getTargetTriple().isOSAIX()) { 4943 // Direct function calls reference the symbol for the function's entry 4944 // point, which is named by inserting a "." before the function's 4945 // C-linkage name. 4946 auto &Context = MF.getMMI().getContext(); 4947 MCSymbol *S = Context.getOrCreateSymbol(Twine(".") + 4948 Twine(G->getGlobal()->getName())); 4949 cast<MCSymbolXCOFF>(S)->setGlobalValue(GV); 4950 Callee = DAG.getMCSymbol(S, PtrVT); 4951 } else { 4952 // A call to a TLS address is actually an indirect call to a 4953 // thread-specific pointer. 4954 unsigned OpFlags = 0; 4955 if (UsePlt) 4956 OpFlags = PPCII::MO_PLT; 4957 4958 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, 4959 // every direct call is) turn it into a TargetGlobalAddress / 4960 // TargetExternalSymbol node so that legalize doesn't hack it. 4961 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl, 4962 Callee.getValueType(), 0, OpFlags); 4963 } 4964 needIndirectCall = false; 4965 } 4966 4967 if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) { 4968 unsigned char OpFlags = 0; 4969 4970 if (UsePlt) 4971 OpFlags = PPCII::MO_PLT; 4972 4973 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), Callee.getValueType(), 4974 OpFlags); 4975 needIndirectCall = false; 4976 } 4977 4978 if (isPatchPoint) { 4979 // We'll form an invalid direct call when lowering a patchpoint; the full 4980 // sequence for an indirect call is complicated, and many of the 4981 // instructions introduced might have side effects (and, thus, can't be 4982 // removed later). The call itself will be removed as soon as the 4983 // argument/return lowering is complete, so the fact that it has the wrong 4984 // kind of operands should not really matter. 4985 needIndirectCall = false; 4986 } 4987 4988 if (needIndirectCall) { 4989 // Otherwise, this is an indirect call. We have to use a MTCTR/BCTRL pair 4990 // to do the call, we can't use PPCISD::CALL. 4991 SDValue MTCTROps[] = {Chain, Callee, InFlag}; 4992 4993 if (isSVR4ABI && isPPC64 && !isELFv2ABI) { 4994 // Function pointers in the 64-bit SVR4 ABI do not point to the function 4995 // entry point, but to the function descriptor (the function entry point 4996 // address is part of the function descriptor though). 4997 // The function descriptor is a three doubleword structure with the 4998 // following fields: function entry point, TOC base address and 4999 // environment pointer. 5000 // Thus for a call through a function pointer, the following actions need 5001 // to be performed: 5002 // 1. Save the TOC of the caller in the TOC save area of its stack 5003 // frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()). 5004 // 2. Load the address of the function entry point from the function 5005 // descriptor. 5006 // 3. Load the TOC of the callee from the function descriptor into r2. 5007 // 4. Load the environment pointer from the function descriptor into 5008 // r11. 5009 // 5. Branch to the function entry point address. 5010 // 6. On return of the callee, the TOC of the caller needs to be 5011 // restored (this is done in FinishCall()). 5012 // 5013 // The loads are scheduled at the beginning of the call sequence, and the 5014 // register copies are flagged together to ensure that no other 5015 // operations can be scheduled in between. E.g. without flagging the 5016 // copies together, a TOC access in the caller could be scheduled between 5017 // the assignment of the callee TOC and the branch to the callee, which 5018 // results in the TOC access going through the TOC of the callee instead 5019 // of going through the TOC of the caller, which leads to incorrect code. 5020 5021 // Load the address of the function entry point from the function 5022 // descriptor. 5023 SDValue LDChain = CallSeqStart.getValue(CallSeqStart->getNumValues()-1); 5024 if (LDChain.getValueType() == MVT::Glue) 5025 LDChain = CallSeqStart.getValue(CallSeqStart->getNumValues()-2); 5026 5027 auto MMOFlags = Subtarget.hasInvariantFunctionDescriptors() 5028 ? (MachineMemOperand::MODereferenceable | 5029 MachineMemOperand::MOInvariant) 5030 : MachineMemOperand::MONone; 5031 5032 MachinePointerInfo MPI(CS ? CS.getCalledValue() : nullptr); 5033 SDValue LoadFuncPtr = DAG.getLoad(MVT::i64, dl, LDChain, Callee, MPI, 5034 /* Alignment = */ 8, MMOFlags); 5035 5036 // Load environment pointer into r11. 5037 SDValue PtrOff = DAG.getIntPtrConstant(16, dl); 5038 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, PtrOff); 5039 SDValue LoadEnvPtr = 5040 DAG.getLoad(MVT::i64, dl, LDChain, AddPtr, MPI.getWithOffset(16), 5041 /* Alignment = */ 8, MMOFlags); 5042 5043 SDValue TOCOff = DAG.getIntPtrConstant(8, dl); 5044 SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, TOCOff); 5045 SDValue TOCPtr = 5046 DAG.getLoad(MVT::i64, dl, LDChain, AddTOC, MPI.getWithOffset(8), 5047 /* Alignment = */ 8, MMOFlags); 5048 5049 setUsesTOCBasePtr(DAG); 5050 SDValue TOCVal = DAG.getCopyToReg(Chain, dl, PPC::X2, TOCPtr, 5051 InFlag); 5052 Chain = TOCVal.getValue(0); 5053 InFlag = TOCVal.getValue(1); 5054 5055 // If the function call has an explicit 'nest' parameter, it takes the 5056 // place of the environment pointer. 5057 if (!hasNest) { 5058 SDValue EnvVal = DAG.getCopyToReg(Chain, dl, PPC::X11, LoadEnvPtr, 5059 InFlag); 5060 5061 Chain = EnvVal.getValue(0); 5062 InFlag = EnvVal.getValue(1); 5063 } 5064 5065 MTCTROps[0] = Chain; 5066 MTCTROps[1] = LoadFuncPtr; 5067 MTCTROps[2] = InFlag; 5068 } 5069 5070 Chain = DAG.getNode(PPCISD::MTCTR, dl, NodeTys, 5071 makeArrayRef(MTCTROps, InFlag.getNode() ? 3 : 2)); 5072 InFlag = Chain.getValue(1); 5073 5074 NodeTys.clear(); 5075 NodeTys.push_back(MVT::Other); 5076 NodeTys.push_back(MVT::Glue); 5077 Ops.push_back(Chain); 5078 CallOpc = PPCISD::BCTRL; 5079 Callee.setNode(nullptr); 5080 // Add use of X11 (holding environment pointer) 5081 if (isSVR4ABI && isPPC64 && !isELFv2ABI && !hasNest) 5082 Ops.push_back(DAG.getRegister(PPC::X11, PtrVT)); 5083 // Add CTR register as callee so a bctr can be emitted later. 5084 if (isTailCall) 5085 Ops.push_back(DAG.getRegister(isPPC64 ? PPC::CTR8 : PPC::CTR, PtrVT)); 5086 } 5087 5088 // If this is a direct call, pass the chain and the callee. 5089 if (Callee.getNode()) { 5090 Ops.push_back(Chain); 5091 Ops.push_back(Callee); 5092 } 5093 // If this is a tail call add stack pointer delta. 5094 if (isTailCall) 5095 Ops.push_back(DAG.getConstant(SPDiff, dl, MVT::i32)); 5096 5097 // Add argument registers to the end of the list so that they are known live 5098 // into the call. 5099 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) 5100 Ops.push_back(DAG.getRegister(RegsToPass[i].first, 5101 RegsToPass[i].second.getValueType())); 5102 5103 // All calls, in the AIX ABI and 64-bit ELF ABIs, need the TOC register 5104 // live into the call. 5105 // We do need to reserve R2/X2 to appease the verifier for the PATCHPOINT. 5106 if ((isSVR4ABI && isPPC64) || isAIXABI) { 5107 setUsesTOCBasePtr(DAG); 5108 5109 // We cannot add R2/X2 as an operand here for PATCHPOINT, because there is 5110 // no way to mark dependencies as implicit here. 5111 // We will add the R2/X2 dependency in EmitInstrWithCustomInserter. 5112 if (!isPatchPoint) 5113 Ops.push_back(DAG.getRegister(isPPC64 ? PPC::X2 5114 : PPC::R2, PtrVT)); 5115 } 5116 5117 return CallOpc; 5118 } 5119 5120 SDValue PPCTargetLowering::LowerCallResult( 5121 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg, 5122 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 5123 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 5124 SmallVector<CCValAssign, 16> RVLocs; 5125 CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 5126 *DAG.getContext()); 5127 5128 CCRetInfo.AnalyzeCallResult( 5129 Ins, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold) 5130 ? RetCC_PPC_Cold 5131 : RetCC_PPC); 5132 5133 // Copy all of the result registers out of their specified physreg. 5134 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) { 5135 CCValAssign &VA = RVLocs[i]; 5136 assert(VA.isRegLoc() && "Can only return in registers!"); 5137 5138 SDValue Val; 5139 5140 if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) { 5141 SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, 5142 InFlag); 5143 Chain = Lo.getValue(1); 5144 InFlag = Lo.getValue(2); 5145 VA = RVLocs[++i]; // skip ahead to next loc 5146 SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, 5147 InFlag); 5148 Chain = Hi.getValue(1); 5149 InFlag = Hi.getValue(2); 5150 if (!Subtarget.isLittleEndian()) 5151 std::swap (Lo, Hi); 5152 Val = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, Lo, Hi); 5153 } else { 5154 Val = DAG.getCopyFromReg(Chain, dl, 5155 VA.getLocReg(), VA.getLocVT(), InFlag); 5156 Chain = Val.getValue(1); 5157 InFlag = Val.getValue(2); 5158 } 5159 5160 switch (VA.getLocInfo()) { 5161 default: llvm_unreachable("Unknown loc info!"); 5162 case CCValAssign::Full: break; 5163 case CCValAssign::AExt: 5164 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val); 5165 break; 5166 case CCValAssign::ZExt: 5167 Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val, 5168 DAG.getValueType(VA.getValVT())); 5169 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val); 5170 break; 5171 case CCValAssign::SExt: 5172 Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val, 5173 DAG.getValueType(VA.getValVT())); 5174 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val); 5175 break; 5176 } 5177 5178 InVals.push_back(Val); 5179 } 5180 5181 return Chain; 5182 } 5183 5184 SDValue PPCTargetLowering::FinishCall( 5185 CallingConv::ID CallConv, const SDLoc &dl, bool isTailCall, bool isVarArg, 5186 bool isPatchPoint, bool hasNest, SelectionDAG &DAG, 5187 SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, SDValue InFlag, 5188 SDValue Chain, SDValue CallSeqStart, SDValue &Callee, int SPDiff, 5189 unsigned NumBytes, const SmallVectorImpl<ISD::InputArg> &Ins, 5190 SmallVectorImpl<SDValue> &InVals, ImmutableCallSite CS) const { 5191 std::vector<EVT> NodeTys; 5192 SmallVector<SDValue, 8> Ops; 5193 unsigned CallOpc = PrepareCall(DAG, Callee, InFlag, Chain, CallSeqStart, dl, 5194 SPDiff, isTailCall, isPatchPoint, hasNest, 5195 RegsToPass, Ops, NodeTys, CS, Subtarget); 5196 5197 // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls 5198 if (isVarArg && Subtarget.isSVR4ABI() && !Subtarget.isPPC64()) 5199 Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32)); 5200 5201 // When performing tail call optimization the callee pops its arguments off 5202 // the stack. Account for this here so these bytes can be pushed back on in 5203 // PPCFrameLowering::eliminateCallFramePseudoInstr. 5204 int BytesCalleePops = 5205 (CallConv == CallingConv::Fast && 5206 getTargetMachine().Options.GuaranteedTailCallOpt) ? NumBytes : 0; 5207 5208 // Add a register mask operand representing the call-preserved registers. 5209 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo(); 5210 const uint32_t *Mask = 5211 TRI->getCallPreservedMask(DAG.getMachineFunction(), CallConv); 5212 assert(Mask && "Missing call preserved mask for calling convention"); 5213 Ops.push_back(DAG.getRegisterMask(Mask)); 5214 5215 if (InFlag.getNode()) 5216 Ops.push_back(InFlag); 5217 5218 // Emit tail call. 5219 if (isTailCall) { 5220 assert(((Callee.getOpcode() == ISD::Register && 5221 cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) || 5222 Callee.getOpcode() == ISD::TargetExternalSymbol || 5223 Callee.getOpcode() == ISD::TargetGlobalAddress || 5224 isa<ConstantSDNode>(Callee)) && 5225 "Expecting an global address, external symbol, absolute value or register"); 5226 5227 DAG.getMachineFunction().getFrameInfo().setHasTailCall(); 5228 return DAG.getNode(PPCISD::TC_RETURN, dl, MVT::Other, Ops); 5229 } 5230 5231 // Add a NOP immediately after the branch instruction when using the 64-bit 5232 // SVR4 or the AIX ABI. 5233 // At link time, if caller and callee are in a different module and 5234 // thus have a different TOC, the call will be replaced with a call to a stub 5235 // function which saves the current TOC, loads the TOC of the callee and 5236 // branches to the callee. The NOP will be replaced with a load instruction 5237 // which restores the TOC of the caller from the TOC save slot of the current 5238 // stack frame. If caller and callee belong to the same module (and have the 5239 // same TOC), the NOP will remain unchanged, or become some other NOP. 5240 5241 MachineFunction &MF = DAG.getMachineFunction(); 5242 if (!isTailCall && !isPatchPoint && 5243 ((Subtarget.isSVR4ABI() && Subtarget.isPPC64()) || 5244 Subtarget.isAIXABI())) { 5245 if (CallOpc == PPCISD::BCTRL) { 5246 if (Subtarget.isAIXABI()) 5247 report_fatal_error("Indirect call on AIX is not implemented."); 5248 5249 // This is a call through a function pointer. 5250 // Restore the caller TOC from the save area into R2. 5251 // See PrepareCall() for more information about calls through function 5252 // pointers in the 64-bit SVR4 ABI. 5253 // We are using a target-specific load with r2 hard coded, because the 5254 // result of a target-independent load would never go directly into r2, 5255 // since r2 is a reserved register (which prevents the register allocator 5256 // from allocating it), resulting in an additional register being 5257 // allocated and an unnecessary move instruction being generated. 5258 CallOpc = PPCISD::BCTRL_LOAD_TOC; 5259 5260 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 5261 SDValue StackPtr = DAG.getRegister(PPC::X1, PtrVT); 5262 unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset(); 5263 SDValue TOCOff = DAG.getIntPtrConstant(TOCSaveOffset, dl); 5264 SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, StackPtr, TOCOff); 5265 5266 // The address needs to go after the chain input but before the flag (or 5267 // any other variadic arguments). 5268 Ops.insert(std::next(Ops.begin()), AddTOC); 5269 } else if (CallOpc == PPCISD::CALL && 5270 !callsShareTOCBase(&MF.getFunction(), Callee, DAG.getTarget())) { 5271 // Otherwise insert NOP for non-local calls. 5272 CallOpc = PPCISD::CALL_NOP; 5273 } 5274 } 5275 5276 Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops); 5277 InFlag = Chain.getValue(1); 5278 5279 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true), 5280 DAG.getIntPtrConstant(BytesCalleePops, dl, true), 5281 InFlag, dl); 5282 if (!Ins.empty()) 5283 InFlag = Chain.getValue(1); 5284 5285 return LowerCallResult(Chain, InFlag, CallConv, isVarArg, 5286 Ins, dl, DAG, InVals); 5287 } 5288 5289 SDValue 5290 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI, 5291 SmallVectorImpl<SDValue> &InVals) const { 5292 SelectionDAG &DAG = CLI.DAG; 5293 SDLoc &dl = CLI.DL; 5294 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs; 5295 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals; 5296 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins; 5297 SDValue Chain = CLI.Chain; 5298 SDValue Callee = CLI.Callee; 5299 bool &isTailCall = CLI.IsTailCall; 5300 CallingConv::ID CallConv = CLI.CallConv; 5301 bool isVarArg = CLI.IsVarArg; 5302 bool isPatchPoint = CLI.IsPatchPoint; 5303 ImmutableCallSite CS = CLI.CS; 5304 5305 if (isTailCall) { 5306 if (Subtarget.useLongCalls() && !(CS && CS.isMustTailCall())) 5307 isTailCall = false; 5308 else if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) 5309 isTailCall = 5310 IsEligibleForTailCallOptimization_64SVR4(Callee, CallConv, CS, 5311 isVarArg, Outs, Ins, DAG); 5312 else 5313 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg, 5314 Ins, DAG); 5315 if (isTailCall) { 5316 ++NumTailCalls; 5317 if (!getTargetMachine().Options.GuaranteedTailCallOpt) 5318 ++NumSiblingCalls; 5319 5320 assert(isa<GlobalAddressSDNode>(Callee) && 5321 "Callee should be an llvm::Function object."); 5322 LLVM_DEBUG( 5323 const GlobalValue *GV = 5324 cast<GlobalAddressSDNode>(Callee)->getGlobal(); 5325 const unsigned Width = 5326 80 - strlen("TCO caller: ") - strlen(", callee linkage: 0, 0"); 5327 dbgs() << "TCO caller: " 5328 << left_justify(DAG.getMachineFunction().getName(), Width) 5329 << ", callee linkage: " << GV->getVisibility() << ", " 5330 << GV->getLinkage() << "\n"); 5331 } 5332 } 5333 5334 if (!isTailCall && CS && CS.isMustTailCall()) 5335 report_fatal_error("failed to perform tail call elimination on a call " 5336 "site marked musttail"); 5337 5338 // When long calls (i.e. indirect calls) are always used, calls are always 5339 // made via function pointer. If we have a function name, first translate it 5340 // into a pointer. 5341 if (Subtarget.useLongCalls() && isa<GlobalAddressSDNode>(Callee) && 5342 !isTailCall) 5343 Callee = LowerGlobalAddress(Callee, DAG); 5344 5345 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) 5346 return LowerCall_64SVR4(Chain, Callee, CallConv, isVarArg, 5347 isTailCall, isPatchPoint, Outs, OutVals, Ins, 5348 dl, DAG, InVals, CS); 5349 5350 if (Subtarget.isSVR4ABI()) 5351 return LowerCall_32SVR4(Chain, Callee, CallConv, isVarArg, 5352 isTailCall, isPatchPoint, Outs, OutVals, Ins, 5353 dl, DAG, InVals, CS); 5354 5355 if (Subtarget.isAIXABI()) 5356 return LowerCall_AIX(Chain, Callee, CallConv, isVarArg, 5357 isTailCall, isPatchPoint, Outs, OutVals, Ins, 5358 dl, DAG, InVals, CS); 5359 5360 return LowerCall_Darwin(Chain, Callee, CallConv, isVarArg, 5361 isTailCall, isPatchPoint, Outs, OutVals, Ins, 5362 dl, DAG, InVals, CS); 5363 } 5364 5365 SDValue PPCTargetLowering::LowerCall_32SVR4( 5366 SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg, 5367 bool isTailCall, bool isPatchPoint, 5368 const SmallVectorImpl<ISD::OutputArg> &Outs, 5369 const SmallVectorImpl<SDValue> &OutVals, 5370 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 5371 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 5372 ImmutableCallSite CS) const { 5373 // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description 5374 // of the 32-bit SVR4 ABI stack frame layout. 5375 5376 assert((CallConv == CallingConv::C || 5377 CallConv == CallingConv::Cold || 5378 CallConv == CallingConv::Fast) && "Unknown calling convention!"); 5379 5380 unsigned PtrByteSize = 4; 5381 5382 MachineFunction &MF = DAG.getMachineFunction(); 5383 5384 // Mark this function as potentially containing a function that contains a 5385 // tail call. As a consequence the frame pointer will be used for dynamicalloc 5386 // and restoring the callers stack pointer in this functions epilog. This is 5387 // done because by tail calling the called function might overwrite the value 5388 // in this function's (MF) stack pointer stack slot 0(SP). 5389 if (getTargetMachine().Options.GuaranteedTailCallOpt && 5390 CallConv == CallingConv::Fast) 5391 MF.getInfo<PPCFunctionInfo>()->setHasFastCall(); 5392 5393 // Count how many bytes are to be pushed on the stack, including the linkage 5394 // area, parameter list area and the part of the local variable space which 5395 // contains copies of aggregates which are passed by value. 5396 5397 // Assign locations to all of the outgoing arguments. 5398 SmallVector<CCValAssign, 16> ArgLocs; 5399 PPCCCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext()); 5400 5401 // Reserve space for the linkage area on the stack. 5402 CCInfo.AllocateStack(Subtarget.getFrameLowering()->getLinkageSize(), 5403 PtrByteSize); 5404 if (useSoftFloat()) 5405 CCInfo.PreAnalyzeCallOperands(Outs); 5406 5407 if (isVarArg) { 5408 // Handle fixed and variable vector arguments differently. 5409 // Fixed vector arguments go into registers as long as registers are 5410 // available. Variable vector arguments always go into memory. 5411 unsigned NumArgs = Outs.size(); 5412 5413 for (unsigned i = 0; i != NumArgs; ++i) { 5414 MVT ArgVT = Outs[i].VT; 5415 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 5416 bool Result; 5417 5418 if (Outs[i].IsFixed) { 5419 Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, 5420 CCInfo); 5421 } else { 5422 Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full, 5423 ArgFlags, CCInfo); 5424 } 5425 5426 if (Result) { 5427 #ifndef NDEBUG 5428 errs() << "Call operand #" << i << " has unhandled type " 5429 << EVT(ArgVT).getEVTString() << "\n"; 5430 #endif 5431 llvm_unreachable(nullptr); 5432 } 5433 } 5434 } else { 5435 // All arguments are treated the same. 5436 CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4); 5437 } 5438 CCInfo.clearWasPPCF128(); 5439 5440 // Assign locations to all of the outgoing aggregate by value arguments. 5441 SmallVector<CCValAssign, 16> ByValArgLocs; 5442 CCState CCByValInfo(CallConv, isVarArg, MF, ByValArgLocs, *DAG.getContext()); 5443 5444 // Reserve stack space for the allocations in CCInfo. 5445 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize); 5446 5447 CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal); 5448 5449 // Size of the linkage area, parameter list area and the part of the local 5450 // space variable where copies of aggregates which are passed by value are 5451 // stored. 5452 unsigned NumBytes = CCByValInfo.getNextStackOffset(); 5453 5454 // Calculate by how many bytes the stack has to be adjusted in case of tail 5455 // call optimization. 5456 int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes); 5457 5458 // Adjust the stack pointer for the new arguments... 5459 // These operations are automatically eliminated by the prolog/epilog pass 5460 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 5461 SDValue CallSeqStart = Chain; 5462 5463 // Load the return address and frame pointer so it can be moved somewhere else 5464 // later. 5465 SDValue LROp, FPOp; 5466 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl); 5467 5468 // Set up a copy of the stack pointer for use loading and storing any 5469 // arguments that may not fit in the registers available for argument 5470 // passing. 5471 SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32); 5472 5473 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 5474 SmallVector<TailCallArgumentInfo, 8> TailCallArguments; 5475 SmallVector<SDValue, 8> MemOpChains; 5476 5477 bool seenFloatArg = false; 5478 // Walk the register/memloc assignments, inserting copies/loads. 5479 // i - Tracks the index into the list of registers allocated for the call 5480 // RealArgIdx - Tracks the index into the list of actual function arguments 5481 // j - Tracks the index into the list of byval arguments 5482 for (unsigned i = 0, RealArgIdx = 0, j = 0, e = ArgLocs.size(); 5483 i != e; 5484 ++i, ++RealArgIdx) { 5485 CCValAssign &VA = ArgLocs[i]; 5486 SDValue Arg = OutVals[RealArgIdx]; 5487 ISD::ArgFlagsTy Flags = Outs[RealArgIdx].Flags; 5488 5489 if (Flags.isByVal()) { 5490 // Argument is an aggregate which is passed by value, thus we need to 5491 // create a copy of it in the local variable space of the current stack 5492 // frame (which is the stack frame of the caller) and pass the address of 5493 // this copy to the callee. 5494 assert((j < ByValArgLocs.size()) && "Index out of bounds!"); 5495 CCValAssign &ByValVA = ByValArgLocs[j++]; 5496 assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!"); 5497 5498 // Memory reserved in the local variable space of the callers stack frame. 5499 unsigned LocMemOffset = ByValVA.getLocMemOffset(); 5500 5501 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 5502 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()), 5503 StackPtr, PtrOff); 5504 5505 // Create a copy of the argument in the local area of the current 5506 // stack frame. 5507 SDValue MemcpyCall = 5508 CreateCopyOfByValArgument(Arg, PtrOff, 5509 CallSeqStart.getNode()->getOperand(0), 5510 Flags, DAG, dl); 5511 5512 // This must go outside the CALLSEQ_START..END. 5513 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, NumBytes, 0, 5514 SDLoc(MemcpyCall)); 5515 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(), 5516 NewCallSeqStart.getNode()); 5517 Chain = CallSeqStart = NewCallSeqStart; 5518 5519 // Pass the address of the aggregate copy on the stack either in a 5520 // physical register or in the parameter list area of the current stack 5521 // frame to the callee. 5522 Arg = PtrOff; 5523 } 5524 5525 // When useCRBits() is true, there can be i1 arguments. 5526 // It is because getRegisterType(MVT::i1) => MVT::i1, 5527 // and for other integer types getRegisterType() => MVT::i32. 5528 // Extend i1 and ensure callee will get i32. 5529 if (Arg.getValueType() == MVT::i1) 5530 Arg = DAG.getNode(Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, 5531 dl, MVT::i32, Arg); 5532 5533 if (VA.isRegLoc()) { 5534 seenFloatArg |= VA.getLocVT().isFloatingPoint(); 5535 // Put argument in a physical register. 5536 if (Subtarget.hasSPE() && Arg.getValueType() == MVT::f64) { 5537 bool IsLE = Subtarget.isLittleEndian(); 5538 SDValue SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg, 5539 DAG.getIntPtrConstant(IsLE ? 0 : 1, dl)); 5540 RegsToPass.push_back(std::make_pair(VA.getLocReg(), SVal.getValue(0))); 5541 SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg, 5542 DAG.getIntPtrConstant(IsLE ? 1 : 0, dl)); 5543 RegsToPass.push_back(std::make_pair(ArgLocs[++i].getLocReg(), 5544 SVal.getValue(0))); 5545 } else 5546 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 5547 } else { 5548 // Put argument in the parameter list area of the current stack frame. 5549 assert(VA.isMemLoc()); 5550 unsigned LocMemOffset = VA.getLocMemOffset(); 5551 5552 if (!isTailCall) { 5553 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 5554 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()), 5555 StackPtr, PtrOff); 5556 5557 MemOpChains.push_back( 5558 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo())); 5559 } else { 5560 // Calculate and remember argument location. 5561 CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset, 5562 TailCallArguments); 5563 } 5564 } 5565 } 5566 5567 if (!MemOpChains.empty()) 5568 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 5569 5570 // Build a sequence of copy-to-reg nodes chained together with token chain 5571 // and flag operands which copy the outgoing args into the appropriate regs. 5572 SDValue InFlag; 5573 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 5574 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 5575 RegsToPass[i].second, InFlag); 5576 InFlag = Chain.getValue(1); 5577 } 5578 5579 // Set CR bit 6 to true if this is a vararg call with floating args passed in 5580 // registers. 5581 if (isVarArg) { 5582 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue); 5583 SDValue Ops[] = { Chain, InFlag }; 5584 5585 Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET, 5586 dl, VTs, makeArrayRef(Ops, InFlag.getNode() ? 2 : 1)); 5587 5588 InFlag = Chain.getValue(1); 5589 } 5590 5591 if (isTailCall) 5592 PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp, 5593 TailCallArguments); 5594 5595 return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint, 5596 /* unused except on PPC64 ELFv1 */ false, DAG, 5597 RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff, 5598 NumBytes, Ins, InVals, CS); 5599 } 5600 5601 // Copy an argument into memory, being careful to do this outside the 5602 // call sequence for the call to which the argument belongs. 5603 SDValue PPCTargetLowering::createMemcpyOutsideCallSeq( 5604 SDValue Arg, SDValue PtrOff, SDValue CallSeqStart, ISD::ArgFlagsTy Flags, 5605 SelectionDAG &DAG, const SDLoc &dl) const { 5606 SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff, 5607 CallSeqStart.getNode()->getOperand(0), 5608 Flags, DAG, dl); 5609 // The MEMCPY must go outside the CALLSEQ_START..END. 5610 int64_t FrameSize = CallSeqStart.getConstantOperandVal(1); 5611 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, FrameSize, 0, 5612 SDLoc(MemcpyCall)); 5613 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(), 5614 NewCallSeqStart.getNode()); 5615 return NewCallSeqStart; 5616 } 5617 5618 SDValue PPCTargetLowering::LowerCall_64SVR4( 5619 SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg, 5620 bool isTailCall, bool isPatchPoint, 5621 const SmallVectorImpl<ISD::OutputArg> &Outs, 5622 const SmallVectorImpl<SDValue> &OutVals, 5623 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 5624 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 5625 ImmutableCallSite CS) const { 5626 bool isELFv2ABI = Subtarget.isELFv2ABI(); 5627 bool isLittleEndian = Subtarget.isLittleEndian(); 5628 unsigned NumOps = Outs.size(); 5629 bool hasNest = false; 5630 bool IsSibCall = false; 5631 5632 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 5633 unsigned PtrByteSize = 8; 5634 5635 MachineFunction &MF = DAG.getMachineFunction(); 5636 5637 if (isTailCall && !getTargetMachine().Options.GuaranteedTailCallOpt) 5638 IsSibCall = true; 5639 5640 // Mark this function as potentially containing a function that contains a 5641 // tail call. As a consequence the frame pointer will be used for dynamicalloc 5642 // and restoring the callers stack pointer in this functions epilog. This is 5643 // done because by tail calling the called function might overwrite the value 5644 // in this function's (MF) stack pointer stack slot 0(SP). 5645 if (getTargetMachine().Options.GuaranteedTailCallOpt && 5646 CallConv == CallingConv::Fast) 5647 MF.getInfo<PPCFunctionInfo>()->setHasFastCall(); 5648 5649 assert(!(CallConv == CallingConv::Fast && isVarArg) && 5650 "fastcc not supported on varargs functions"); 5651 5652 // Count how many bytes are to be pushed on the stack, including the linkage 5653 // area, and parameter passing area. On ELFv1, the linkage area is 48 bytes 5654 // reserved space for [SP][CR][LR][2 x unused][TOC]; on ELFv2, the linkage 5655 // area is 32 bytes reserved space for [SP][CR][LR][TOC]. 5656 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 5657 unsigned NumBytes = LinkageSize; 5658 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 5659 unsigned &QFPR_idx = FPR_idx; 5660 5661 static const MCPhysReg GPR[] = { 5662 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 5663 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 5664 }; 5665 static const MCPhysReg VR[] = { 5666 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 5667 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 5668 }; 5669 5670 const unsigned NumGPRs = array_lengthof(GPR); 5671 const unsigned NumFPRs = useSoftFloat() ? 0 : 13; 5672 const unsigned NumVRs = array_lengthof(VR); 5673 const unsigned NumQFPRs = NumFPRs; 5674 5675 // On ELFv2, we can avoid allocating the parameter area if all the arguments 5676 // can be passed to the callee in registers. 5677 // For the fast calling convention, there is another check below. 5678 // Note: We should keep consistent with LowerFormalArguments_64SVR4() 5679 bool HasParameterArea = !isELFv2ABI || isVarArg || CallConv == CallingConv::Fast; 5680 if (!HasParameterArea) { 5681 unsigned ParamAreaSize = NumGPRs * PtrByteSize; 5682 unsigned AvailableFPRs = NumFPRs; 5683 unsigned AvailableVRs = NumVRs; 5684 unsigned NumBytesTmp = NumBytes; 5685 for (unsigned i = 0; i != NumOps; ++i) { 5686 if (Outs[i].Flags.isNest()) continue; 5687 if (CalculateStackSlotUsed(Outs[i].VT, Outs[i].ArgVT, Outs[i].Flags, 5688 PtrByteSize, LinkageSize, ParamAreaSize, 5689 NumBytesTmp, AvailableFPRs, AvailableVRs, 5690 Subtarget.hasQPX())) 5691 HasParameterArea = true; 5692 } 5693 } 5694 5695 // When using the fast calling convention, we don't provide backing for 5696 // arguments that will be in registers. 5697 unsigned NumGPRsUsed = 0, NumFPRsUsed = 0, NumVRsUsed = 0; 5698 5699 // Avoid allocating parameter area for fastcc functions if all the arguments 5700 // can be passed in the registers. 5701 if (CallConv == CallingConv::Fast) 5702 HasParameterArea = false; 5703 5704 // Add up all the space actually used. 5705 for (unsigned i = 0; i != NumOps; ++i) { 5706 ISD::ArgFlagsTy Flags = Outs[i].Flags; 5707 EVT ArgVT = Outs[i].VT; 5708 EVT OrigVT = Outs[i].ArgVT; 5709 5710 if (Flags.isNest()) 5711 continue; 5712 5713 if (CallConv == CallingConv::Fast) { 5714 if (Flags.isByVal()) { 5715 NumGPRsUsed += (Flags.getByValSize()+7)/8; 5716 if (NumGPRsUsed > NumGPRs) 5717 HasParameterArea = true; 5718 } else { 5719 switch (ArgVT.getSimpleVT().SimpleTy) { 5720 default: llvm_unreachable("Unexpected ValueType for argument!"); 5721 case MVT::i1: 5722 case MVT::i32: 5723 case MVT::i64: 5724 if (++NumGPRsUsed <= NumGPRs) 5725 continue; 5726 break; 5727 case MVT::v4i32: 5728 case MVT::v8i16: 5729 case MVT::v16i8: 5730 case MVT::v2f64: 5731 case MVT::v2i64: 5732 case MVT::v1i128: 5733 case MVT::f128: 5734 if (++NumVRsUsed <= NumVRs) 5735 continue; 5736 break; 5737 case MVT::v4f32: 5738 // When using QPX, this is handled like a FP register, otherwise, it 5739 // is an Altivec register. 5740 if (Subtarget.hasQPX()) { 5741 if (++NumFPRsUsed <= NumFPRs) 5742 continue; 5743 } else { 5744 if (++NumVRsUsed <= NumVRs) 5745 continue; 5746 } 5747 break; 5748 case MVT::f32: 5749 case MVT::f64: 5750 case MVT::v4f64: // QPX 5751 case MVT::v4i1: // QPX 5752 if (++NumFPRsUsed <= NumFPRs) 5753 continue; 5754 break; 5755 } 5756 HasParameterArea = true; 5757 } 5758 } 5759 5760 /* Respect alignment of argument on the stack. */ 5761 unsigned Align = 5762 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize); 5763 NumBytes = ((NumBytes + Align - 1) / Align) * Align; 5764 5765 NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize); 5766 if (Flags.isInConsecutiveRegsLast()) 5767 NumBytes = ((NumBytes + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 5768 } 5769 5770 unsigned NumBytesActuallyUsed = NumBytes; 5771 5772 // In the old ELFv1 ABI, 5773 // the prolog code of the callee may store up to 8 GPR argument registers to 5774 // the stack, allowing va_start to index over them in memory if its varargs. 5775 // Because we cannot tell if this is needed on the caller side, we have to 5776 // conservatively assume that it is needed. As such, make sure we have at 5777 // least enough stack space for the caller to store the 8 GPRs. 5778 // In the ELFv2 ABI, we allocate the parameter area iff a callee 5779 // really requires memory operands, e.g. a vararg function. 5780 if (HasParameterArea) 5781 NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize); 5782 else 5783 NumBytes = LinkageSize; 5784 5785 // Tail call needs the stack to be aligned. 5786 if (getTargetMachine().Options.GuaranteedTailCallOpt && 5787 CallConv == CallingConv::Fast) 5788 NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes); 5789 5790 int SPDiff = 0; 5791 5792 // Calculate by how many bytes the stack has to be adjusted in case of tail 5793 // call optimization. 5794 if (!IsSibCall) 5795 SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes); 5796 5797 // To protect arguments on the stack from being clobbered in a tail call, 5798 // force all the loads to happen before doing any other lowering. 5799 if (isTailCall) 5800 Chain = DAG.getStackArgumentTokenFactor(Chain); 5801 5802 // Adjust the stack pointer for the new arguments... 5803 // These operations are automatically eliminated by the prolog/epilog pass 5804 if (!IsSibCall) 5805 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 5806 SDValue CallSeqStart = Chain; 5807 5808 // Load the return address and frame pointer so it can be move somewhere else 5809 // later. 5810 SDValue LROp, FPOp; 5811 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl); 5812 5813 // Set up a copy of the stack pointer for use loading and storing any 5814 // arguments that may not fit in the registers available for argument 5815 // passing. 5816 SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64); 5817 5818 // Figure out which arguments are going to go in registers, and which in 5819 // memory. Also, if this is a vararg function, floating point operations 5820 // must be stored to our stack, and loaded into integer regs as well, if 5821 // any integer regs are available for argument passing. 5822 unsigned ArgOffset = LinkageSize; 5823 5824 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 5825 SmallVector<TailCallArgumentInfo, 8> TailCallArguments; 5826 5827 SmallVector<SDValue, 8> MemOpChains; 5828 for (unsigned i = 0; i != NumOps; ++i) { 5829 SDValue Arg = OutVals[i]; 5830 ISD::ArgFlagsTy Flags = Outs[i].Flags; 5831 EVT ArgVT = Outs[i].VT; 5832 EVT OrigVT = Outs[i].ArgVT; 5833 5834 // PtrOff will be used to store the current argument to the stack if a 5835 // register cannot be found for it. 5836 SDValue PtrOff; 5837 5838 // We re-align the argument offset for each argument, except when using the 5839 // fast calling convention, when we need to make sure we do that only when 5840 // we'll actually use a stack slot. 5841 auto ComputePtrOff = [&]() { 5842 /* Respect alignment of argument on the stack. */ 5843 unsigned Align = 5844 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize); 5845 ArgOffset = ((ArgOffset + Align - 1) / Align) * Align; 5846 5847 PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType()); 5848 5849 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 5850 }; 5851 5852 if (CallConv != CallingConv::Fast) { 5853 ComputePtrOff(); 5854 5855 /* Compute GPR index associated with argument offset. */ 5856 GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize; 5857 GPR_idx = std::min(GPR_idx, NumGPRs); 5858 } 5859 5860 // Promote integers to 64-bit values. 5861 if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) { 5862 // FIXME: Should this use ANY_EXTEND if neither sext nor zext? 5863 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 5864 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg); 5865 } 5866 5867 // FIXME memcpy is used way more than necessary. Correctness first. 5868 // Note: "by value" is code for passing a structure by value, not 5869 // basic types. 5870 if (Flags.isByVal()) { 5871 // Note: Size includes alignment padding, so 5872 // struct x { short a; char b; } 5873 // will have Size = 4. With #pragma pack(1), it will have Size = 3. 5874 // These are the proper values we need for right-justifying the 5875 // aggregate in a parameter register. 5876 unsigned Size = Flags.getByValSize(); 5877 5878 // An empty aggregate parameter takes up no storage and no 5879 // registers. 5880 if (Size == 0) 5881 continue; 5882 5883 if (CallConv == CallingConv::Fast) 5884 ComputePtrOff(); 5885 5886 // All aggregates smaller than 8 bytes must be passed right-justified. 5887 if (Size==1 || Size==2 || Size==4) { 5888 EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32); 5889 if (GPR_idx != NumGPRs) { 5890 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg, 5891 MachinePointerInfo(), VT); 5892 MemOpChains.push_back(Load.getValue(1)); 5893 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 5894 5895 ArgOffset += PtrByteSize; 5896 continue; 5897 } 5898 } 5899 5900 if (GPR_idx == NumGPRs && Size < 8) { 5901 SDValue AddPtr = PtrOff; 5902 if (!isLittleEndian) { 5903 SDValue Const = DAG.getConstant(PtrByteSize - Size, dl, 5904 PtrOff.getValueType()); 5905 AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const); 5906 } 5907 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr, 5908 CallSeqStart, 5909 Flags, DAG, dl); 5910 ArgOffset += PtrByteSize; 5911 continue; 5912 } 5913 // Copy entire object into memory. There are cases where gcc-generated 5914 // code assumes it is there, even if it could be put entirely into 5915 // registers. (This is not what the doc says.) 5916 5917 // FIXME: The above statement is likely due to a misunderstanding of the 5918 // documents. All arguments must be copied into the parameter area BY 5919 // THE CALLEE in the event that the callee takes the address of any 5920 // formal argument. That has not yet been implemented. However, it is 5921 // reasonable to use the stack area as a staging area for the register 5922 // load. 5923 5924 // Skip this for small aggregates, as we will use the same slot for a 5925 // right-justified copy, below. 5926 if (Size >= 8) 5927 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff, 5928 CallSeqStart, 5929 Flags, DAG, dl); 5930 5931 // When a register is available, pass a small aggregate right-justified. 5932 if (Size < 8 && GPR_idx != NumGPRs) { 5933 // The easiest way to get this right-justified in a register 5934 // is to copy the structure into the rightmost portion of a 5935 // local variable slot, then load the whole slot into the 5936 // register. 5937 // FIXME: The memcpy seems to produce pretty awful code for 5938 // small aggregates, particularly for packed ones. 5939 // FIXME: It would be preferable to use the slot in the 5940 // parameter save area instead of a new local variable. 5941 SDValue AddPtr = PtrOff; 5942 if (!isLittleEndian) { 5943 SDValue Const = DAG.getConstant(8 - Size, dl, PtrOff.getValueType()); 5944 AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const); 5945 } 5946 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr, 5947 CallSeqStart, 5948 Flags, DAG, dl); 5949 5950 // Load the slot into the register. 5951 SDValue Load = 5952 DAG.getLoad(PtrVT, dl, Chain, PtrOff, MachinePointerInfo()); 5953 MemOpChains.push_back(Load.getValue(1)); 5954 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 5955 5956 // Done with this argument. 5957 ArgOffset += PtrByteSize; 5958 continue; 5959 } 5960 5961 // For aggregates larger than PtrByteSize, copy the pieces of the 5962 // object that fit into registers from the parameter save area. 5963 for (unsigned j=0; j<Size; j+=PtrByteSize) { 5964 SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType()); 5965 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const); 5966 if (GPR_idx != NumGPRs) { 5967 SDValue Load = 5968 DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo()); 5969 MemOpChains.push_back(Load.getValue(1)); 5970 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 5971 ArgOffset += PtrByteSize; 5972 } else { 5973 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize; 5974 break; 5975 } 5976 } 5977 continue; 5978 } 5979 5980 switch (Arg.getSimpleValueType().SimpleTy) { 5981 default: llvm_unreachable("Unexpected ValueType for argument!"); 5982 case MVT::i1: 5983 case MVT::i32: 5984 case MVT::i64: 5985 if (Flags.isNest()) { 5986 // The 'nest' parameter, if any, is passed in R11. 5987 RegsToPass.push_back(std::make_pair(PPC::X11, Arg)); 5988 hasNest = true; 5989 break; 5990 } 5991 5992 // These can be scalar arguments or elements of an integer array type 5993 // passed directly. Clang may use those instead of "byval" aggregate 5994 // types to avoid forcing arguments to memory unnecessarily. 5995 if (GPR_idx != NumGPRs) { 5996 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg)); 5997 } else { 5998 if (CallConv == CallingConv::Fast) 5999 ComputePtrOff(); 6000 6001 assert(HasParameterArea && 6002 "Parameter area must exist to pass an argument in memory."); 6003 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6004 true, isTailCall, false, MemOpChains, 6005 TailCallArguments, dl); 6006 if (CallConv == CallingConv::Fast) 6007 ArgOffset += PtrByteSize; 6008 } 6009 if (CallConv != CallingConv::Fast) 6010 ArgOffset += PtrByteSize; 6011 break; 6012 case MVT::f32: 6013 case MVT::f64: { 6014 // These can be scalar arguments or elements of a float array type 6015 // passed directly. The latter are used to implement ELFv2 homogenous 6016 // float aggregates. 6017 6018 // Named arguments go into FPRs first, and once they overflow, the 6019 // remaining arguments go into GPRs and then the parameter save area. 6020 // Unnamed arguments for vararg functions always go to GPRs and 6021 // then the parameter save area. For now, put all arguments to vararg 6022 // routines always in both locations (FPR *and* GPR or stack slot). 6023 bool NeedGPROrStack = isVarArg || FPR_idx == NumFPRs; 6024 bool NeededLoad = false; 6025 6026 // First load the argument into the next available FPR. 6027 if (FPR_idx != NumFPRs) 6028 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg)); 6029 6030 // Next, load the argument into GPR or stack slot if needed. 6031 if (!NeedGPROrStack) 6032 ; 6033 else if (GPR_idx != NumGPRs && CallConv != CallingConv::Fast) { 6034 // FIXME: We may want to re-enable this for CallingConv::Fast on the P8 6035 // once we support fp <-> gpr moves. 6036 6037 // In the non-vararg case, this can only ever happen in the 6038 // presence of f32 array types, since otherwise we never run 6039 // out of FPRs before running out of GPRs. 6040 SDValue ArgVal; 6041 6042 // Double values are always passed in a single GPR. 6043 if (Arg.getValueType() != MVT::f32) { 6044 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg); 6045 6046 // Non-array float values are extended and passed in a GPR. 6047 } else if (!Flags.isInConsecutiveRegs()) { 6048 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg); 6049 ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal); 6050 6051 // If we have an array of floats, we collect every odd element 6052 // together with its predecessor into one GPR. 6053 } else if (ArgOffset % PtrByteSize != 0) { 6054 SDValue Lo, Hi; 6055 Lo = DAG.getNode(ISD::BITCAST, dl, MVT::i32, OutVals[i - 1]); 6056 Hi = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg); 6057 if (!isLittleEndian) 6058 std::swap(Lo, Hi); 6059 ArgVal = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi); 6060 6061 // The final element, if even, goes into the first half of a GPR. 6062 } else if (Flags.isInConsecutiveRegsLast()) { 6063 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg); 6064 ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal); 6065 if (!isLittleEndian) 6066 ArgVal = DAG.getNode(ISD::SHL, dl, MVT::i64, ArgVal, 6067 DAG.getConstant(32, dl, MVT::i32)); 6068 6069 // Non-final even elements are skipped; they will be handled 6070 // together the with subsequent argument on the next go-around. 6071 } else 6072 ArgVal = SDValue(); 6073 6074 if (ArgVal.getNode()) 6075 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], ArgVal)); 6076 } else { 6077 if (CallConv == CallingConv::Fast) 6078 ComputePtrOff(); 6079 6080 // Single-precision floating-point values are mapped to the 6081 // second (rightmost) word of the stack doubleword. 6082 if (Arg.getValueType() == MVT::f32 && 6083 !isLittleEndian && !Flags.isInConsecutiveRegs()) { 6084 SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType()); 6085 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour); 6086 } 6087 6088 assert(HasParameterArea && 6089 "Parameter area must exist to pass an argument in memory."); 6090 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6091 true, isTailCall, false, MemOpChains, 6092 TailCallArguments, dl); 6093 6094 NeededLoad = true; 6095 } 6096 // When passing an array of floats, the array occupies consecutive 6097 // space in the argument area; only round up to the next doubleword 6098 // at the end of the array. Otherwise, each float takes 8 bytes. 6099 if (CallConv != CallingConv::Fast || NeededLoad) { 6100 ArgOffset += (Arg.getValueType() == MVT::f32 && 6101 Flags.isInConsecutiveRegs()) ? 4 : 8; 6102 if (Flags.isInConsecutiveRegsLast()) 6103 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 6104 } 6105 break; 6106 } 6107 case MVT::v4f32: 6108 case MVT::v4i32: 6109 case MVT::v8i16: 6110 case MVT::v16i8: 6111 case MVT::v2f64: 6112 case MVT::v2i64: 6113 case MVT::v1i128: 6114 case MVT::f128: 6115 if (!Subtarget.hasQPX()) { 6116 // These can be scalar arguments or elements of a vector array type 6117 // passed directly. The latter are used to implement ELFv2 homogenous 6118 // vector aggregates. 6119 6120 // For a varargs call, named arguments go into VRs or on the stack as 6121 // usual; unnamed arguments always go to the stack or the corresponding 6122 // GPRs when within range. For now, we always put the value in both 6123 // locations (or even all three). 6124 if (isVarArg) { 6125 assert(HasParameterArea && 6126 "Parameter area must exist if we have a varargs call."); 6127 // We could elide this store in the case where the object fits 6128 // entirely in R registers. Maybe later. 6129 SDValue Store = 6130 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 6131 MemOpChains.push_back(Store); 6132 if (VR_idx != NumVRs) { 6133 SDValue Load = 6134 DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo()); 6135 MemOpChains.push_back(Load.getValue(1)); 6136 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load)); 6137 } 6138 ArgOffset += 16; 6139 for (unsigned i=0; i<16; i+=PtrByteSize) { 6140 if (GPR_idx == NumGPRs) 6141 break; 6142 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, 6143 DAG.getConstant(i, dl, PtrVT)); 6144 SDValue Load = 6145 DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo()); 6146 MemOpChains.push_back(Load.getValue(1)); 6147 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6148 } 6149 break; 6150 } 6151 6152 // Non-varargs Altivec params go into VRs or on the stack. 6153 if (VR_idx != NumVRs) { 6154 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg)); 6155 } else { 6156 if (CallConv == CallingConv::Fast) 6157 ComputePtrOff(); 6158 6159 assert(HasParameterArea && 6160 "Parameter area must exist to pass an argument in memory."); 6161 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6162 true, isTailCall, true, MemOpChains, 6163 TailCallArguments, dl); 6164 if (CallConv == CallingConv::Fast) 6165 ArgOffset += 16; 6166 } 6167 6168 if (CallConv != CallingConv::Fast) 6169 ArgOffset += 16; 6170 break; 6171 } // not QPX 6172 6173 assert(Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32 && 6174 "Invalid QPX parameter type"); 6175 6176 LLVM_FALLTHROUGH; 6177 case MVT::v4f64: 6178 case MVT::v4i1: { 6179 bool IsF32 = Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32; 6180 if (isVarArg) { 6181 assert(HasParameterArea && 6182 "Parameter area must exist if we have a varargs call."); 6183 // We could elide this store in the case where the object fits 6184 // entirely in R registers. Maybe later. 6185 SDValue Store = 6186 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 6187 MemOpChains.push_back(Store); 6188 if (QFPR_idx != NumQFPRs) { 6189 SDValue Load = DAG.getLoad(IsF32 ? MVT::v4f32 : MVT::v4f64, dl, Store, 6190 PtrOff, MachinePointerInfo()); 6191 MemOpChains.push_back(Load.getValue(1)); 6192 RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Load)); 6193 } 6194 ArgOffset += (IsF32 ? 16 : 32); 6195 for (unsigned i = 0; i < (IsF32 ? 16U : 32U); i += PtrByteSize) { 6196 if (GPR_idx == NumGPRs) 6197 break; 6198 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, 6199 DAG.getConstant(i, dl, PtrVT)); 6200 SDValue Load = 6201 DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo()); 6202 MemOpChains.push_back(Load.getValue(1)); 6203 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6204 } 6205 break; 6206 } 6207 6208 // Non-varargs QPX params go into registers or on the stack. 6209 if (QFPR_idx != NumQFPRs) { 6210 RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Arg)); 6211 } else { 6212 if (CallConv == CallingConv::Fast) 6213 ComputePtrOff(); 6214 6215 assert(HasParameterArea && 6216 "Parameter area must exist to pass an argument in memory."); 6217 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6218 true, isTailCall, true, MemOpChains, 6219 TailCallArguments, dl); 6220 if (CallConv == CallingConv::Fast) 6221 ArgOffset += (IsF32 ? 16 : 32); 6222 } 6223 6224 if (CallConv != CallingConv::Fast) 6225 ArgOffset += (IsF32 ? 16 : 32); 6226 break; 6227 } 6228 } 6229 } 6230 6231 assert((!HasParameterArea || NumBytesActuallyUsed == ArgOffset) && 6232 "mismatch in size of parameter area"); 6233 (void)NumBytesActuallyUsed; 6234 6235 if (!MemOpChains.empty()) 6236 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 6237 6238 // Check if this is an indirect call (MTCTR/BCTRL). 6239 // See PrepareCall() for more information about calls through function 6240 // pointers in the 64-bit SVR4 ABI. 6241 if (!isTailCall && !isPatchPoint && 6242 !isFunctionGlobalAddress(Callee) && 6243 !isa<ExternalSymbolSDNode>(Callee)) { 6244 // Load r2 into a virtual register and store it to the TOC save area. 6245 setUsesTOCBasePtr(DAG); 6246 SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64); 6247 // TOC save area offset. 6248 unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset(); 6249 SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl); 6250 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 6251 Chain = DAG.getStore( 6252 Val.getValue(1), dl, Val, AddPtr, 6253 MachinePointerInfo::getStack(DAG.getMachineFunction(), TOCSaveOffset)); 6254 // In the ELFv2 ABI, R12 must contain the address of an indirect callee. 6255 // This does not mean the MTCTR instruction must use R12; it's easier 6256 // to model this as an extra parameter, so do that. 6257 if (isELFv2ABI && !isPatchPoint) 6258 RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee)); 6259 } 6260 6261 // Build a sequence of copy-to-reg nodes chained together with token chain 6262 // and flag operands which copy the outgoing args into the appropriate regs. 6263 SDValue InFlag; 6264 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 6265 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 6266 RegsToPass[i].second, InFlag); 6267 InFlag = Chain.getValue(1); 6268 } 6269 6270 if (isTailCall && !IsSibCall) 6271 PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp, 6272 TailCallArguments); 6273 6274 return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint, hasNest, 6275 DAG, RegsToPass, InFlag, Chain, CallSeqStart, Callee, 6276 SPDiff, NumBytes, Ins, InVals, CS); 6277 } 6278 6279 SDValue PPCTargetLowering::LowerCall_Darwin( 6280 SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg, 6281 bool isTailCall, bool isPatchPoint, 6282 const SmallVectorImpl<ISD::OutputArg> &Outs, 6283 const SmallVectorImpl<SDValue> &OutVals, 6284 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 6285 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 6286 ImmutableCallSite CS) const { 6287 unsigned NumOps = Outs.size(); 6288 6289 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 6290 bool isPPC64 = PtrVT == MVT::i64; 6291 unsigned PtrByteSize = isPPC64 ? 8 : 4; 6292 6293 MachineFunction &MF = DAG.getMachineFunction(); 6294 6295 // Mark this function as potentially containing a function that contains a 6296 // tail call. As a consequence the frame pointer will be used for dynamicalloc 6297 // and restoring the callers stack pointer in this functions epilog. This is 6298 // done because by tail calling the called function might overwrite the value 6299 // in this function's (MF) stack pointer stack slot 0(SP). 6300 if (getTargetMachine().Options.GuaranteedTailCallOpt && 6301 CallConv == CallingConv::Fast) 6302 MF.getInfo<PPCFunctionInfo>()->setHasFastCall(); 6303 6304 // Count how many bytes are to be pushed on the stack, including the linkage 6305 // area, and parameter passing area. We start with 24/48 bytes, which is 6306 // prereserved space for [SP][CR][LR][3 x unused]. 6307 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 6308 unsigned NumBytes = LinkageSize; 6309 6310 // Add up all the space actually used. 6311 // In 32-bit non-varargs calls, Altivec parameters all go at the end; usually 6312 // they all go in registers, but we must reserve stack space for them for 6313 // possible use by the caller. In varargs or 64-bit calls, parameters are 6314 // assigned stack space in order, with padding so Altivec parameters are 6315 // 16-byte aligned. 6316 unsigned nAltivecParamsAtEnd = 0; 6317 for (unsigned i = 0; i != NumOps; ++i) { 6318 ISD::ArgFlagsTy Flags = Outs[i].Flags; 6319 EVT ArgVT = Outs[i].VT; 6320 // Varargs Altivec parameters are padded to a 16 byte boundary. 6321 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 || 6322 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 || 6323 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64) { 6324 if (!isVarArg && !isPPC64) { 6325 // Non-varargs Altivec parameters go after all the non-Altivec 6326 // parameters; handle those later so we know how much padding we need. 6327 nAltivecParamsAtEnd++; 6328 continue; 6329 } 6330 // Varargs and 64-bit Altivec parameters are padded to 16 byte boundary. 6331 NumBytes = ((NumBytes+15)/16)*16; 6332 } 6333 NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize); 6334 } 6335 6336 // Allow for Altivec parameters at the end, if needed. 6337 if (nAltivecParamsAtEnd) { 6338 NumBytes = ((NumBytes+15)/16)*16; 6339 NumBytes += 16*nAltivecParamsAtEnd; 6340 } 6341 6342 // The prolog code of the callee may store up to 8 GPR argument registers to 6343 // the stack, allowing va_start to index over them in memory if its varargs. 6344 // Because we cannot tell if this is needed on the caller side, we have to 6345 // conservatively assume that it is needed. As such, make sure we have at 6346 // least enough stack space for the caller to store the 8 GPRs. 6347 NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize); 6348 6349 // Tail call needs the stack to be aligned. 6350 if (getTargetMachine().Options.GuaranteedTailCallOpt && 6351 CallConv == CallingConv::Fast) 6352 NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes); 6353 6354 // Calculate by how many bytes the stack has to be adjusted in case of tail 6355 // call optimization. 6356 int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes); 6357 6358 // To protect arguments on the stack from being clobbered in a tail call, 6359 // force all the loads to happen before doing any other lowering. 6360 if (isTailCall) 6361 Chain = DAG.getStackArgumentTokenFactor(Chain); 6362 6363 // Adjust the stack pointer for the new arguments... 6364 // These operations are automatically eliminated by the prolog/epilog pass 6365 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 6366 SDValue CallSeqStart = Chain; 6367 6368 // Load the return address and frame pointer so it can be move somewhere else 6369 // later. 6370 SDValue LROp, FPOp; 6371 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl); 6372 6373 // Set up a copy of the stack pointer for use loading and storing any 6374 // arguments that may not fit in the registers available for argument 6375 // passing. 6376 SDValue StackPtr; 6377 if (isPPC64) 6378 StackPtr = DAG.getRegister(PPC::X1, MVT::i64); 6379 else 6380 StackPtr = DAG.getRegister(PPC::R1, MVT::i32); 6381 6382 // Figure out which arguments are going to go in registers, and which in 6383 // memory. Also, if this is a vararg function, floating point operations 6384 // must be stored to our stack, and loaded into integer regs as well, if 6385 // any integer regs are available for argument passing. 6386 unsigned ArgOffset = LinkageSize; 6387 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 6388 6389 static const MCPhysReg GPR_32[] = { // 32-bit registers. 6390 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 6391 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 6392 }; 6393 static const MCPhysReg GPR_64[] = { // 64-bit registers. 6394 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 6395 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 6396 }; 6397 static const MCPhysReg VR[] = { 6398 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 6399 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 6400 }; 6401 const unsigned NumGPRs = array_lengthof(GPR_32); 6402 const unsigned NumFPRs = 13; 6403 const unsigned NumVRs = array_lengthof(VR); 6404 6405 const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32; 6406 6407 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 6408 SmallVector<TailCallArgumentInfo, 8> TailCallArguments; 6409 6410 SmallVector<SDValue, 8> MemOpChains; 6411 for (unsigned i = 0; i != NumOps; ++i) { 6412 SDValue Arg = OutVals[i]; 6413 ISD::ArgFlagsTy Flags = Outs[i].Flags; 6414 6415 // PtrOff will be used to store the current argument to the stack if a 6416 // register cannot be found for it. 6417 SDValue PtrOff; 6418 6419 PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType()); 6420 6421 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 6422 6423 // On PPC64, promote integers to 64-bit values. 6424 if (isPPC64 && Arg.getValueType() == MVT::i32) { 6425 // FIXME: Should this use ANY_EXTEND if neither sext nor zext? 6426 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 6427 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg); 6428 } 6429 6430 // FIXME memcpy is used way more than necessary. Correctness first. 6431 // Note: "by value" is code for passing a structure by value, not 6432 // basic types. 6433 if (Flags.isByVal()) { 6434 unsigned Size = Flags.getByValSize(); 6435 // Very small objects are passed right-justified. Everything else is 6436 // passed left-justified. 6437 if (Size==1 || Size==2) { 6438 EVT VT = (Size==1) ? MVT::i8 : MVT::i16; 6439 if (GPR_idx != NumGPRs) { 6440 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg, 6441 MachinePointerInfo(), VT); 6442 MemOpChains.push_back(Load.getValue(1)); 6443 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6444 6445 ArgOffset += PtrByteSize; 6446 } else { 6447 SDValue Const = DAG.getConstant(PtrByteSize - Size, dl, 6448 PtrOff.getValueType()); 6449 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const); 6450 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr, 6451 CallSeqStart, 6452 Flags, DAG, dl); 6453 ArgOffset += PtrByteSize; 6454 } 6455 continue; 6456 } 6457 // Copy entire object into memory. There are cases where gcc-generated 6458 // code assumes it is there, even if it could be put entirely into 6459 // registers. (This is not what the doc says.) 6460 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff, 6461 CallSeqStart, 6462 Flags, DAG, dl); 6463 6464 // For small aggregates (Darwin only) and aggregates >= PtrByteSize, 6465 // copy the pieces of the object that fit into registers from the 6466 // parameter save area. 6467 for (unsigned j=0; j<Size; j+=PtrByteSize) { 6468 SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType()); 6469 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const); 6470 if (GPR_idx != NumGPRs) { 6471 SDValue Load = 6472 DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo()); 6473 MemOpChains.push_back(Load.getValue(1)); 6474 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6475 ArgOffset += PtrByteSize; 6476 } else { 6477 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize; 6478 break; 6479 } 6480 } 6481 continue; 6482 } 6483 6484 switch (Arg.getSimpleValueType().SimpleTy) { 6485 default: llvm_unreachable("Unexpected ValueType for argument!"); 6486 case MVT::i1: 6487 case MVT::i32: 6488 case MVT::i64: 6489 if (GPR_idx != NumGPRs) { 6490 if (Arg.getValueType() == MVT::i1) 6491 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, PtrVT, Arg); 6492 6493 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg)); 6494 } else { 6495 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6496 isPPC64, isTailCall, false, MemOpChains, 6497 TailCallArguments, dl); 6498 } 6499 ArgOffset += PtrByteSize; 6500 break; 6501 case MVT::f32: 6502 case MVT::f64: 6503 if (FPR_idx != NumFPRs) { 6504 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg)); 6505 6506 if (isVarArg) { 6507 SDValue Store = 6508 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 6509 MemOpChains.push_back(Store); 6510 6511 // Float varargs are always shadowed in available integer registers 6512 if (GPR_idx != NumGPRs) { 6513 SDValue Load = 6514 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo()); 6515 MemOpChains.push_back(Load.getValue(1)); 6516 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6517 } 6518 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && !isPPC64){ 6519 SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType()); 6520 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour); 6521 SDValue Load = 6522 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo()); 6523 MemOpChains.push_back(Load.getValue(1)); 6524 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6525 } 6526 } else { 6527 // If we have any FPRs remaining, we may also have GPRs remaining. 6528 // Args passed in FPRs consume either 1 (f32) or 2 (f64) available 6529 // GPRs. 6530 if (GPR_idx != NumGPRs) 6531 ++GPR_idx; 6532 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && 6533 !isPPC64) // PPC64 has 64-bit GPR's obviously :) 6534 ++GPR_idx; 6535 } 6536 } else 6537 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6538 isPPC64, isTailCall, false, MemOpChains, 6539 TailCallArguments, dl); 6540 if (isPPC64) 6541 ArgOffset += 8; 6542 else 6543 ArgOffset += Arg.getValueType() == MVT::f32 ? 4 : 8; 6544 break; 6545 case MVT::v4f32: 6546 case MVT::v4i32: 6547 case MVT::v8i16: 6548 case MVT::v16i8: 6549 if (isVarArg) { 6550 // These go aligned on the stack, or in the corresponding R registers 6551 // when within range. The Darwin PPC ABI doc claims they also go in 6552 // V registers; in fact gcc does this only for arguments that are 6553 // prototyped, not for those that match the ... We do it for all 6554 // arguments, seems to work. 6555 while (ArgOffset % 16 !=0) { 6556 ArgOffset += PtrByteSize; 6557 if (GPR_idx != NumGPRs) 6558 GPR_idx++; 6559 } 6560 // We could elide this store in the case where the object fits 6561 // entirely in R registers. Maybe later. 6562 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, 6563 DAG.getConstant(ArgOffset, dl, PtrVT)); 6564 SDValue Store = 6565 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 6566 MemOpChains.push_back(Store); 6567 if (VR_idx != NumVRs) { 6568 SDValue Load = 6569 DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo()); 6570 MemOpChains.push_back(Load.getValue(1)); 6571 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load)); 6572 } 6573 ArgOffset += 16; 6574 for (unsigned i=0; i<16; i+=PtrByteSize) { 6575 if (GPR_idx == NumGPRs) 6576 break; 6577 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, 6578 DAG.getConstant(i, dl, PtrVT)); 6579 SDValue Load = 6580 DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo()); 6581 MemOpChains.push_back(Load.getValue(1)); 6582 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6583 } 6584 break; 6585 } 6586 6587 // Non-varargs Altivec params generally go in registers, but have 6588 // stack space allocated at the end. 6589 if (VR_idx != NumVRs) { 6590 // Doesn't have GPR space allocated. 6591 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg)); 6592 } else if (nAltivecParamsAtEnd==0) { 6593 // We are emitting Altivec params in order. 6594 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6595 isPPC64, isTailCall, true, MemOpChains, 6596 TailCallArguments, dl); 6597 ArgOffset += 16; 6598 } 6599 break; 6600 } 6601 } 6602 // If all Altivec parameters fit in registers, as they usually do, 6603 // they get stack space following the non-Altivec parameters. We 6604 // don't track this here because nobody below needs it. 6605 // If there are more Altivec parameters than fit in registers emit 6606 // the stores here. 6607 if (!isVarArg && nAltivecParamsAtEnd > NumVRs) { 6608 unsigned j = 0; 6609 // Offset is aligned; skip 1st 12 params which go in V registers. 6610 ArgOffset = ((ArgOffset+15)/16)*16; 6611 ArgOffset += 12*16; 6612 for (unsigned i = 0; i != NumOps; ++i) { 6613 SDValue Arg = OutVals[i]; 6614 EVT ArgType = Outs[i].VT; 6615 if (ArgType==MVT::v4f32 || ArgType==MVT::v4i32 || 6616 ArgType==MVT::v8i16 || ArgType==MVT::v16i8) { 6617 if (++j > NumVRs) { 6618 SDValue PtrOff; 6619 // We are emitting Altivec params in order. 6620 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6621 isPPC64, isTailCall, true, MemOpChains, 6622 TailCallArguments, dl); 6623 ArgOffset += 16; 6624 } 6625 } 6626 } 6627 } 6628 6629 if (!MemOpChains.empty()) 6630 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 6631 6632 // On Darwin, R12 must contain the address of an indirect callee. This does 6633 // not mean the MTCTR instruction must use R12; it's easier to model this as 6634 // an extra parameter, so do that. 6635 if (!isTailCall && 6636 !isFunctionGlobalAddress(Callee) && 6637 !isa<ExternalSymbolSDNode>(Callee) && 6638 !isBLACompatibleAddress(Callee, DAG)) 6639 RegsToPass.push_back(std::make_pair((unsigned)(isPPC64 ? PPC::X12 : 6640 PPC::R12), Callee)); 6641 6642 // Build a sequence of copy-to-reg nodes chained together with token chain 6643 // and flag operands which copy the outgoing args into the appropriate regs. 6644 SDValue InFlag; 6645 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 6646 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 6647 RegsToPass[i].second, InFlag); 6648 InFlag = Chain.getValue(1); 6649 } 6650 6651 if (isTailCall) 6652 PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp, 6653 TailCallArguments); 6654 6655 return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint, 6656 /* unused except on PPC64 ELFv1 */ false, DAG, 6657 RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff, 6658 NumBytes, Ins, InVals, CS); 6659 } 6660 6661 6662 SDValue PPCTargetLowering::LowerCall_AIX( 6663 SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg, 6664 bool isTailCall, bool isPatchPoint, 6665 const SmallVectorImpl<ISD::OutputArg> &Outs, 6666 const SmallVectorImpl<SDValue> &OutVals, 6667 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 6668 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 6669 ImmutableCallSite CS) const { 6670 6671 assert((CallConv == CallingConv::C || CallConv == CallingConv::Fast) && 6672 "Unimplemented calling convention!"); 6673 if (isVarArg || isPatchPoint) 6674 report_fatal_error("This call type is unimplemented on AIX."); 6675 6676 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 6677 bool isPPC64 = PtrVT == MVT::i64; 6678 unsigned PtrByteSize = isPPC64 ? 8 : 4; 6679 unsigned NumOps = Outs.size(); 6680 6681 6682 // Count how many bytes are to be pushed on the stack, including the linkage 6683 // area, parameter list area. 6684 // On XCOFF, we start with 24/48, which is reserved space for 6685 // [SP][CR][LR][2 x reserved][TOC]. 6686 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 6687 6688 // The prolog code of the callee may store up to 8 GPR argument registers to 6689 // the stack, allowing va_start to index over them in memory if the callee 6690 // is variadic. 6691 // Because we cannot tell if this is needed on the caller side, we have to 6692 // conservatively assume that it is needed. As such, make sure we have at 6693 // least enough stack space for the caller to store the 8 GPRs. 6694 unsigned NumBytes = LinkageSize + 8 * PtrByteSize; 6695 6696 // Adjust the stack pointer for the new arguments... 6697 // These operations are automatically eliminated by the prolog/epilog 6698 // inserter pass. 6699 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 6700 SDValue CallSeqStart = Chain; 6701 6702 static const MCPhysReg GPR_32[] = { // 32-bit registers. 6703 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 6704 PPC::R7, PPC::R8, PPC::R9, PPC::R10 6705 }; 6706 static const MCPhysReg GPR_64[] = { // 64-bit registers. 6707 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 6708 PPC::X7, PPC::X8, PPC::X9, PPC::X10 6709 }; 6710 6711 const unsigned NumGPRs = isPPC64 ? array_lengthof(GPR_64) 6712 : array_lengthof(GPR_32); 6713 const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32; 6714 unsigned GPR_idx = 0; 6715 6716 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 6717 6718 if (isTailCall) 6719 report_fatal_error("Handling of tail call is unimplemented!"); 6720 int SPDiff = 0; 6721 6722 for (unsigned i = 0; i != NumOps; ++i) { 6723 SDValue Arg = OutVals[i]; 6724 ISD::ArgFlagsTy Flags = Outs[i].Flags; 6725 6726 // Promote integers if needed. 6727 if (Arg.getValueType() == MVT::i1 || 6728 (isPPC64 && Arg.getValueType() == MVT::i32)) { 6729 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 6730 Arg = DAG.getNode(ExtOp, dl, PtrVT, Arg); 6731 } 6732 6733 // Note: "by value" is code for passing a structure by value, not 6734 // basic types. 6735 if (Flags.isByVal()) 6736 report_fatal_error("Passing structure by value is unimplemented!"); 6737 6738 switch (Arg.getSimpleValueType().SimpleTy) { 6739 default: llvm_unreachable("Unexpected ValueType for argument!"); 6740 case MVT::i1: 6741 case MVT::i32: 6742 case MVT::i64: 6743 if (GPR_idx != NumGPRs) 6744 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg)); 6745 else 6746 report_fatal_error("Handling of placing parameters on the stack is " 6747 "unimplemented!"); 6748 break; 6749 case MVT::f32: 6750 case MVT::f64: 6751 case MVT::v4f32: 6752 case MVT::v4i32: 6753 case MVT::v8i16: 6754 case MVT::v16i8: 6755 case MVT::v2f64: 6756 case MVT::v2i64: 6757 case MVT::v1i128: 6758 case MVT::f128: 6759 case MVT::v4f64: 6760 case MVT::v4i1: 6761 report_fatal_error("Handling of this parameter type is unimplemented!"); 6762 } 6763 } 6764 6765 if (!isFunctionGlobalAddress(Callee) && 6766 !isa<ExternalSymbolSDNode>(Callee)) 6767 report_fatal_error("Handling of indirect call is unimplemented!"); 6768 6769 // Build a sequence of copy-to-reg nodes chained together with token chain 6770 // and flag operands which copy the outgoing args into the appropriate regs. 6771 SDValue InFlag; 6772 for (auto Reg : RegsToPass) { 6773 Chain = DAG.getCopyToReg(Chain, dl, Reg.first, Reg.second, InFlag); 6774 InFlag = Chain.getValue(1); 6775 } 6776 6777 return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint, 6778 /* unused except on PPC64 ELFv1 */ false, DAG, 6779 RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff, 6780 NumBytes, Ins, InVals, CS); 6781 } 6782 6783 bool 6784 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv, 6785 MachineFunction &MF, bool isVarArg, 6786 const SmallVectorImpl<ISD::OutputArg> &Outs, 6787 LLVMContext &Context) const { 6788 SmallVector<CCValAssign, 16> RVLocs; 6789 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context); 6790 return CCInfo.CheckReturn( 6791 Outs, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold) 6792 ? RetCC_PPC_Cold 6793 : RetCC_PPC); 6794 } 6795 6796 SDValue 6797 PPCTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 6798 bool isVarArg, 6799 const SmallVectorImpl<ISD::OutputArg> &Outs, 6800 const SmallVectorImpl<SDValue> &OutVals, 6801 const SDLoc &dl, SelectionDAG &DAG) const { 6802 SmallVector<CCValAssign, 16> RVLocs; 6803 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 6804 *DAG.getContext()); 6805 CCInfo.AnalyzeReturn(Outs, 6806 (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold) 6807 ? RetCC_PPC_Cold 6808 : RetCC_PPC); 6809 6810 SDValue Flag; 6811 SmallVector<SDValue, 4> RetOps(1, Chain); 6812 6813 // Copy the result values into the output registers. 6814 for (unsigned i = 0, RealResIdx = 0; i != RVLocs.size(); ++i, ++RealResIdx) { 6815 CCValAssign &VA = RVLocs[i]; 6816 assert(VA.isRegLoc() && "Can only return in registers!"); 6817 6818 SDValue Arg = OutVals[RealResIdx]; 6819 6820 switch (VA.getLocInfo()) { 6821 default: llvm_unreachable("Unknown loc info!"); 6822 case CCValAssign::Full: break; 6823 case CCValAssign::AExt: 6824 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg); 6825 break; 6826 case CCValAssign::ZExt: 6827 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg); 6828 break; 6829 case CCValAssign::SExt: 6830 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg); 6831 break; 6832 } 6833 if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) { 6834 bool isLittleEndian = Subtarget.isLittleEndian(); 6835 // Legalize ret f64 -> ret 2 x i32. 6836 SDValue SVal = 6837 DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg, 6838 DAG.getIntPtrConstant(isLittleEndian ? 0 : 1, dl)); 6839 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Flag); 6840 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 6841 SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg, 6842 DAG.getIntPtrConstant(isLittleEndian ? 1 : 0, dl)); 6843 Flag = Chain.getValue(1); 6844 VA = RVLocs[++i]; // skip ahead to next loc 6845 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Flag); 6846 } else 6847 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag); 6848 Flag = Chain.getValue(1); 6849 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 6850 } 6851 6852 const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo(); 6853 const MCPhysReg *I = 6854 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction()); 6855 if (I) { 6856 for (; *I; ++I) { 6857 6858 if (PPC::G8RCRegClass.contains(*I)) 6859 RetOps.push_back(DAG.getRegister(*I, MVT::i64)); 6860 else if (PPC::F8RCRegClass.contains(*I)) 6861 RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64))); 6862 else if (PPC::CRRCRegClass.contains(*I)) 6863 RetOps.push_back(DAG.getRegister(*I, MVT::i1)); 6864 else if (PPC::VRRCRegClass.contains(*I)) 6865 RetOps.push_back(DAG.getRegister(*I, MVT::Other)); 6866 else 6867 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 6868 } 6869 } 6870 6871 RetOps[0] = Chain; // Update chain. 6872 6873 // Add the flag if we have it. 6874 if (Flag.getNode()) 6875 RetOps.push_back(Flag); 6876 6877 return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, RetOps); 6878 } 6879 6880 SDValue 6881 PPCTargetLowering::LowerGET_DYNAMIC_AREA_OFFSET(SDValue Op, 6882 SelectionDAG &DAG) const { 6883 SDLoc dl(Op); 6884 6885 // Get the correct type for integers. 6886 EVT IntVT = Op.getValueType(); 6887 6888 // Get the inputs. 6889 SDValue Chain = Op.getOperand(0); 6890 SDValue FPSIdx = getFramePointerFrameIndex(DAG); 6891 // Build a DYNAREAOFFSET node. 6892 SDValue Ops[2] = {Chain, FPSIdx}; 6893 SDVTList VTs = DAG.getVTList(IntVT); 6894 return DAG.getNode(PPCISD::DYNAREAOFFSET, dl, VTs, Ops); 6895 } 6896 6897 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op, 6898 SelectionDAG &DAG) const { 6899 // When we pop the dynamic allocation we need to restore the SP link. 6900 SDLoc dl(Op); 6901 6902 // Get the correct type for pointers. 6903 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 6904 6905 // Construct the stack pointer operand. 6906 bool isPPC64 = Subtarget.isPPC64(); 6907 unsigned SP = isPPC64 ? PPC::X1 : PPC::R1; 6908 SDValue StackPtr = DAG.getRegister(SP, PtrVT); 6909 6910 // Get the operands for the STACKRESTORE. 6911 SDValue Chain = Op.getOperand(0); 6912 SDValue SaveSP = Op.getOperand(1); 6913 6914 // Load the old link SP. 6915 SDValue LoadLinkSP = 6916 DAG.getLoad(PtrVT, dl, Chain, StackPtr, MachinePointerInfo()); 6917 6918 // Restore the stack pointer. 6919 Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP); 6920 6921 // Store the old link SP. 6922 return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo()); 6923 } 6924 6925 SDValue PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG &DAG) const { 6926 MachineFunction &MF = DAG.getMachineFunction(); 6927 bool isPPC64 = Subtarget.isPPC64(); 6928 EVT PtrVT = getPointerTy(MF.getDataLayout()); 6929 6930 // Get current frame pointer save index. The users of this index will be 6931 // primarily DYNALLOC instructions. 6932 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>(); 6933 int RASI = FI->getReturnAddrSaveIndex(); 6934 6935 // If the frame pointer save index hasn't been defined yet. 6936 if (!RASI) { 6937 // Find out what the fix offset of the frame pointer save area. 6938 int LROffset = Subtarget.getFrameLowering()->getReturnSaveOffset(); 6939 // Allocate the frame index for frame pointer save area. 6940 RASI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, LROffset, false); 6941 // Save the result. 6942 FI->setReturnAddrSaveIndex(RASI); 6943 } 6944 return DAG.getFrameIndex(RASI, PtrVT); 6945 } 6946 6947 SDValue 6948 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const { 6949 MachineFunction &MF = DAG.getMachineFunction(); 6950 bool isPPC64 = Subtarget.isPPC64(); 6951 EVT PtrVT = getPointerTy(MF.getDataLayout()); 6952 6953 // Get current frame pointer save index. The users of this index will be 6954 // primarily DYNALLOC instructions. 6955 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>(); 6956 int FPSI = FI->getFramePointerSaveIndex(); 6957 6958 // If the frame pointer save index hasn't been defined yet. 6959 if (!FPSI) { 6960 // Find out what the fix offset of the frame pointer save area. 6961 int FPOffset = Subtarget.getFrameLowering()->getFramePointerSaveOffset(); 6962 // Allocate the frame index for frame pointer save area. 6963 FPSI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, FPOffset, true); 6964 // Save the result. 6965 FI->setFramePointerSaveIndex(FPSI); 6966 } 6967 return DAG.getFrameIndex(FPSI, PtrVT); 6968 } 6969 6970 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, 6971 SelectionDAG &DAG) const { 6972 // Get the inputs. 6973 SDValue Chain = Op.getOperand(0); 6974 SDValue Size = Op.getOperand(1); 6975 SDLoc dl(Op); 6976 6977 // Get the correct type for pointers. 6978 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 6979 // Negate the size. 6980 SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT, 6981 DAG.getConstant(0, dl, PtrVT), Size); 6982 // Construct a node for the frame pointer save index. 6983 SDValue FPSIdx = getFramePointerFrameIndex(DAG); 6984 // Build a DYNALLOC node. 6985 SDValue Ops[3] = { Chain, NegSize, FPSIdx }; 6986 SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other); 6987 return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops); 6988 } 6989 6990 SDValue PPCTargetLowering::LowerEH_DWARF_CFA(SDValue Op, 6991 SelectionDAG &DAG) const { 6992 MachineFunction &MF = DAG.getMachineFunction(); 6993 6994 bool isPPC64 = Subtarget.isPPC64(); 6995 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 6996 6997 int FI = MF.getFrameInfo().CreateFixedObject(isPPC64 ? 8 : 4, 0, false); 6998 return DAG.getFrameIndex(FI, PtrVT); 6999 } 7000 7001 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op, 7002 SelectionDAG &DAG) const { 7003 SDLoc DL(Op); 7004 return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL, 7005 DAG.getVTList(MVT::i32, MVT::Other), 7006 Op.getOperand(0), Op.getOperand(1)); 7007 } 7008 7009 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op, 7010 SelectionDAG &DAG) const { 7011 SDLoc DL(Op); 7012 return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other, 7013 Op.getOperand(0), Op.getOperand(1)); 7014 } 7015 7016 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const { 7017 if (Op.getValueType().isVector()) 7018 return LowerVectorLoad(Op, DAG); 7019 7020 assert(Op.getValueType() == MVT::i1 && 7021 "Custom lowering only for i1 loads"); 7022 7023 // First, load 8 bits into 32 bits, then truncate to 1 bit. 7024 7025 SDLoc dl(Op); 7026 LoadSDNode *LD = cast<LoadSDNode>(Op); 7027 7028 SDValue Chain = LD->getChain(); 7029 SDValue BasePtr = LD->getBasePtr(); 7030 MachineMemOperand *MMO = LD->getMemOperand(); 7031 7032 SDValue NewLD = 7033 DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(DAG.getDataLayout()), Chain, 7034 BasePtr, MVT::i8, MMO); 7035 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD); 7036 7037 SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) }; 7038 return DAG.getMergeValues(Ops, dl); 7039 } 7040 7041 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const { 7042 if (Op.getOperand(1).getValueType().isVector()) 7043 return LowerVectorStore(Op, DAG); 7044 7045 assert(Op.getOperand(1).getValueType() == MVT::i1 && 7046 "Custom lowering only for i1 stores"); 7047 7048 // First, zero extend to 32 bits, then use a truncating store to 8 bits. 7049 7050 SDLoc dl(Op); 7051 StoreSDNode *ST = cast<StoreSDNode>(Op); 7052 7053 SDValue Chain = ST->getChain(); 7054 SDValue BasePtr = ST->getBasePtr(); 7055 SDValue Value = ST->getValue(); 7056 MachineMemOperand *MMO = ST->getMemOperand(); 7057 7058 Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(DAG.getDataLayout()), 7059 Value); 7060 return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO); 7061 } 7062 7063 // FIXME: Remove this once the ANDI glue bug is fixed: 7064 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const { 7065 assert(Op.getValueType() == MVT::i1 && 7066 "Custom lowering only for i1 results"); 7067 7068 SDLoc DL(Op); 7069 return DAG.getNode(PPCISD::ANDIo_1_GT_BIT, DL, MVT::i1, 7070 Op.getOperand(0)); 7071 } 7072 7073 SDValue PPCTargetLowering::LowerTRUNCATEVector(SDValue Op, 7074 SelectionDAG &DAG) const { 7075 7076 // Implements a vector truncate that fits in a vector register as a shuffle. 7077 // We want to legalize vector truncates down to where the source fits in 7078 // a vector register (and target is therefore smaller than vector register 7079 // size). At that point legalization will try to custom lower the sub-legal 7080 // result and get here - where we can contain the truncate as a single target 7081 // operation. 7082 7083 // For example a trunc <2 x i16> to <2 x i8> could be visualized as follows: 7084 // <MSB1|LSB1, MSB2|LSB2> to <LSB1, LSB2> 7085 // 7086 // We will implement it for big-endian ordering as this (where x denotes 7087 // undefined): 7088 // < MSB1|LSB1, MSB2|LSB2, uu, uu, uu, uu, uu, uu> to 7089 // < LSB1, LSB2, u, u, u, u, u, u, u, u, u, u, u, u, u, u> 7090 // 7091 // The same operation in little-endian ordering will be: 7092 // <uu, uu, uu, uu, uu, uu, LSB2|MSB2, LSB1|MSB1> to 7093 // <u, u, u, u, u, u, u, u, u, u, u, u, u, u, LSB2, LSB1> 7094 7095 assert(Op.getValueType().isVector() && "Vector type expected."); 7096 7097 SDLoc DL(Op); 7098 SDValue N1 = Op.getOperand(0); 7099 unsigned SrcSize = N1.getValueType().getSizeInBits(); 7100 assert(SrcSize <= 128 && "Source must fit in an Altivec/VSX vector"); 7101 SDValue WideSrc = SrcSize == 128 ? N1 : widenVec(DAG, N1, DL); 7102 7103 EVT TrgVT = Op.getValueType(); 7104 unsigned TrgNumElts = TrgVT.getVectorNumElements(); 7105 EVT EltVT = TrgVT.getVectorElementType(); 7106 unsigned WideNumElts = 128 / EltVT.getSizeInBits(); 7107 EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts); 7108 7109 // First list the elements we want to keep. 7110 unsigned SizeMult = SrcSize / TrgVT.getSizeInBits(); 7111 SmallVector<int, 16> ShuffV; 7112 if (Subtarget.isLittleEndian()) 7113 for (unsigned i = 0; i < TrgNumElts; ++i) 7114 ShuffV.push_back(i * SizeMult); 7115 else 7116 for (unsigned i = 1; i <= TrgNumElts; ++i) 7117 ShuffV.push_back(i * SizeMult - 1); 7118 7119 // Populate the remaining elements with undefs. 7120 for (unsigned i = TrgNumElts; i < WideNumElts; ++i) 7121 // ShuffV.push_back(i + WideNumElts); 7122 ShuffV.push_back(WideNumElts + 1); 7123 7124 SDValue Conv = DAG.getNode(ISD::BITCAST, DL, WideVT, WideSrc); 7125 return DAG.getVectorShuffle(WideVT, DL, Conv, DAG.getUNDEF(WideVT), ShuffV); 7126 } 7127 7128 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when 7129 /// possible. 7130 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const { 7131 // Not FP? Not a fsel. 7132 if (!Op.getOperand(0).getValueType().isFloatingPoint() || 7133 !Op.getOperand(2).getValueType().isFloatingPoint()) 7134 return Op; 7135 7136 // We might be able to do better than this under some circumstances, but in 7137 // general, fsel-based lowering of select is a finite-math-only optimization. 7138 // For more information, see section F.3 of the 2.06 ISA specification. 7139 if (!DAG.getTarget().Options.NoInfsFPMath || 7140 !DAG.getTarget().Options.NoNaNsFPMath) 7141 return Op; 7142 // TODO: Propagate flags from the select rather than global settings. 7143 SDNodeFlags Flags; 7144 Flags.setNoInfs(true); 7145 Flags.setNoNaNs(true); 7146 7147 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get(); 7148 7149 EVT ResVT = Op.getValueType(); 7150 EVT CmpVT = Op.getOperand(0).getValueType(); 7151 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 7152 SDValue TV = Op.getOperand(2), FV = Op.getOperand(3); 7153 SDLoc dl(Op); 7154 7155 // If the RHS of the comparison is a 0.0, we don't need to do the 7156 // subtraction at all. 7157 SDValue Sel1; 7158 if (isFloatingPointZero(RHS)) 7159 switch (CC) { 7160 default: break; // SETUO etc aren't handled by fsel. 7161 case ISD::SETNE: 7162 std::swap(TV, FV); 7163 LLVM_FALLTHROUGH; 7164 case ISD::SETEQ: 7165 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits 7166 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); 7167 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV); 7168 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits 7169 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1); 7170 return DAG.getNode(PPCISD::FSEL, dl, ResVT, 7171 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV); 7172 case ISD::SETULT: 7173 case ISD::SETLT: 7174 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt 7175 LLVM_FALLTHROUGH; 7176 case ISD::SETOGE: 7177 case ISD::SETGE: 7178 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits 7179 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); 7180 return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV); 7181 case ISD::SETUGT: 7182 case ISD::SETGT: 7183 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt 7184 LLVM_FALLTHROUGH; 7185 case ISD::SETOLE: 7186 case ISD::SETLE: 7187 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits 7188 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); 7189 return DAG.getNode(PPCISD::FSEL, dl, ResVT, 7190 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV); 7191 } 7192 7193 SDValue Cmp; 7194 switch (CC) { 7195 default: break; // SETUO etc aren't handled by fsel. 7196 case ISD::SETNE: 7197 std::swap(TV, FV); 7198 LLVM_FALLTHROUGH; 7199 case ISD::SETEQ: 7200 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags); 7201 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 7202 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 7203 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); 7204 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits 7205 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1); 7206 return DAG.getNode(PPCISD::FSEL, dl, ResVT, 7207 DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV); 7208 case ISD::SETULT: 7209 case ISD::SETLT: 7210 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags); 7211 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 7212 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 7213 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV); 7214 case ISD::SETOGE: 7215 case ISD::SETGE: 7216 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags); 7217 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 7218 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 7219 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); 7220 case ISD::SETUGT: 7221 case ISD::SETGT: 7222 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags); 7223 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 7224 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 7225 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV); 7226 case ISD::SETOLE: 7227 case ISD::SETLE: 7228 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags); 7229 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 7230 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 7231 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); 7232 } 7233 return Op; 7234 } 7235 7236 void PPCTargetLowering::LowerFP_TO_INTForReuse(SDValue Op, ReuseLoadInfo &RLI, 7237 SelectionDAG &DAG, 7238 const SDLoc &dl) const { 7239 assert(Op.getOperand(0).getValueType().isFloatingPoint()); 7240 SDValue Src = Op.getOperand(0); 7241 if (Src.getValueType() == MVT::f32) 7242 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src); 7243 7244 SDValue Tmp; 7245 switch (Op.getSimpleValueType().SimpleTy) { 7246 default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!"); 7247 case MVT::i32: 7248 Tmp = DAG.getNode( 7249 Op.getOpcode() == ISD::FP_TO_SINT 7250 ? PPCISD::FCTIWZ 7251 : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ), 7252 dl, MVT::f64, Src); 7253 break; 7254 case MVT::i64: 7255 assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) && 7256 "i64 FP_TO_UINT is supported only with FPCVT"); 7257 Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ : 7258 PPCISD::FCTIDUZ, 7259 dl, MVT::f64, Src); 7260 break; 7261 } 7262 7263 // Convert the FP value to an int value through memory. 7264 bool i32Stack = Op.getValueType() == MVT::i32 && Subtarget.hasSTFIWX() && 7265 (Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()); 7266 SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64); 7267 int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex(); 7268 MachinePointerInfo MPI = 7269 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI); 7270 7271 // Emit a store to the stack slot. 7272 SDValue Chain; 7273 if (i32Stack) { 7274 MachineFunction &MF = DAG.getMachineFunction(); 7275 MachineMemOperand *MMO = 7276 MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, 4); 7277 SDValue Ops[] = { DAG.getEntryNode(), Tmp, FIPtr }; 7278 Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl, 7279 DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO); 7280 } else 7281 Chain = DAG.getStore(DAG.getEntryNode(), dl, Tmp, FIPtr, MPI); 7282 7283 // Result is a load from the stack slot. If loading 4 bytes, make sure to 7284 // add in a bias on big endian. 7285 if (Op.getValueType() == MVT::i32 && !i32Stack) { 7286 FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr, 7287 DAG.getConstant(4, dl, FIPtr.getValueType())); 7288 MPI = MPI.getWithOffset(Subtarget.isLittleEndian() ? 0 : 4); 7289 } 7290 7291 RLI.Chain = Chain; 7292 RLI.Ptr = FIPtr; 7293 RLI.MPI = MPI; 7294 } 7295 7296 /// Custom lowers floating point to integer conversions to use 7297 /// the direct move instructions available in ISA 2.07 to avoid the 7298 /// need for load/store combinations. 7299 SDValue PPCTargetLowering::LowerFP_TO_INTDirectMove(SDValue Op, 7300 SelectionDAG &DAG, 7301 const SDLoc &dl) const { 7302 assert(Op.getOperand(0).getValueType().isFloatingPoint()); 7303 SDValue Src = Op.getOperand(0); 7304 7305 if (Src.getValueType() == MVT::f32) 7306 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src); 7307 7308 SDValue Tmp; 7309 switch (Op.getSimpleValueType().SimpleTy) { 7310 default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!"); 7311 case MVT::i32: 7312 Tmp = DAG.getNode( 7313 Op.getOpcode() == ISD::FP_TO_SINT 7314 ? PPCISD::FCTIWZ 7315 : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ), 7316 dl, MVT::f64, Src); 7317 Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i32, Tmp); 7318 break; 7319 case MVT::i64: 7320 assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) && 7321 "i64 FP_TO_UINT is supported only with FPCVT"); 7322 Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ : 7323 PPCISD::FCTIDUZ, 7324 dl, MVT::f64, Src); 7325 Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i64, Tmp); 7326 break; 7327 } 7328 return Tmp; 7329 } 7330 7331 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG, 7332 const SDLoc &dl) const { 7333 7334 // FP to INT conversions are legal for f128. 7335 if (EnableQuadPrecision && (Op->getOperand(0).getValueType() == MVT::f128)) 7336 return Op; 7337 7338 // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on 7339 // PPC (the libcall is not available). 7340 if (Op.getOperand(0).getValueType() == MVT::ppcf128) { 7341 if (Op.getValueType() == MVT::i32) { 7342 if (Op.getOpcode() == ISD::FP_TO_SINT) { 7343 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, 7344 MVT::f64, Op.getOperand(0), 7345 DAG.getIntPtrConstant(0, dl)); 7346 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, 7347 MVT::f64, Op.getOperand(0), 7348 DAG.getIntPtrConstant(1, dl)); 7349 7350 // Add the two halves of the long double in round-to-zero mode. 7351 SDValue Res = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi); 7352 7353 // Now use a smaller FP_TO_SINT. 7354 return DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Res); 7355 } 7356 if (Op.getOpcode() == ISD::FP_TO_UINT) { 7357 const uint64_t TwoE31[] = {0x41e0000000000000LL, 0}; 7358 APFloat APF = APFloat(APFloat::PPCDoubleDouble(), APInt(128, TwoE31)); 7359 SDValue Tmp = DAG.getConstantFP(APF, dl, MVT::ppcf128); 7360 // X>=2^31 ? (int)(X-2^31)+0x80000000 : (int)X 7361 // FIXME: generated code sucks. 7362 // TODO: Are there fast-math-flags to propagate to this FSUB? 7363 SDValue True = DAG.getNode(ISD::FSUB, dl, MVT::ppcf128, 7364 Op.getOperand(0), Tmp); 7365 True = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, True); 7366 True = DAG.getNode(ISD::ADD, dl, MVT::i32, True, 7367 DAG.getConstant(0x80000000, dl, MVT::i32)); 7368 SDValue False = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, 7369 Op.getOperand(0)); 7370 return DAG.getSelectCC(dl, Op.getOperand(0), Tmp, True, False, 7371 ISD::SETGE); 7372 } 7373 } 7374 7375 return SDValue(); 7376 } 7377 7378 if (Subtarget.hasDirectMove() && Subtarget.isPPC64()) 7379 return LowerFP_TO_INTDirectMove(Op, DAG, dl); 7380 7381 ReuseLoadInfo RLI; 7382 LowerFP_TO_INTForReuse(Op, RLI, DAG, dl); 7383 7384 return DAG.getLoad(Op.getValueType(), dl, RLI.Chain, RLI.Ptr, RLI.MPI, 7385 RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges); 7386 } 7387 7388 // We're trying to insert a regular store, S, and then a load, L. If the 7389 // incoming value, O, is a load, we might just be able to have our load use the 7390 // address used by O. However, we don't know if anything else will store to 7391 // that address before we can load from it. To prevent this situation, we need 7392 // to insert our load, L, into the chain as a peer of O. To do this, we give L 7393 // the same chain operand as O, we create a token factor from the chain results 7394 // of O and L, and we replace all uses of O's chain result with that token 7395 // factor (see spliceIntoChain below for this last part). 7396 bool PPCTargetLowering::canReuseLoadAddress(SDValue Op, EVT MemVT, 7397 ReuseLoadInfo &RLI, 7398 SelectionDAG &DAG, 7399 ISD::LoadExtType ET) const { 7400 SDLoc dl(Op); 7401 if (ET == ISD::NON_EXTLOAD && 7402 (Op.getOpcode() == ISD::FP_TO_UINT || 7403 Op.getOpcode() == ISD::FP_TO_SINT) && 7404 isOperationLegalOrCustom(Op.getOpcode(), 7405 Op.getOperand(0).getValueType())) { 7406 7407 LowerFP_TO_INTForReuse(Op, RLI, DAG, dl); 7408 return true; 7409 } 7410 7411 LoadSDNode *LD = dyn_cast<LoadSDNode>(Op); 7412 if (!LD || LD->getExtensionType() != ET || LD->isVolatile() || 7413 LD->isNonTemporal()) 7414 return false; 7415 if (LD->getMemoryVT() != MemVT) 7416 return false; 7417 7418 RLI.Ptr = LD->getBasePtr(); 7419 if (LD->isIndexed() && !LD->getOffset().isUndef()) { 7420 assert(LD->getAddressingMode() == ISD::PRE_INC && 7421 "Non-pre-inc AM on PPC?"); 7422 RLI.Ptr = DAG.getNode(ISD::ADD, dl, RLI.Ptr.getValueType(), RLI.Ptr, 7423 LD->getOffset()); 7424 } 7425 7426 RLI.Chain = LD->getChain(); 7427 RLI.MPI = LD->getPointerInfo(); 7428 RLI.IsDereferenceable = LD->isDereferenceable(); 7429 RLI.IsInvariant = LD->isInvariant(); 7430 RLI.Alignment = LD->getAlignment(); 7431 RLI.AAInfo = LD->getAAInfo(); 7432 RLI.Ranges = LD->getRanges(); 7433 7434 RLI.ResChain = SDValue(LD, LD->isIndexed() ? 2 : 1); 7435 return true; 7436 } 7437 7438 // Given the head of the old chain, ResChain, insert a token factor containing 7439 // it and NewResChain, and make users of ResChain now be users of that token 7440 // factor. 7441 // TODO: Remove and use DAG::makeEquivalentMemoryOrdering() instead. 7442 void PPCTargetLowering::spliceIntoChain(SDValue ResChain, 7443 SDValue NewResChain, 7444 SelectionDAG &DAG) const { 7445 if (!ResChain) 7446 return; 7447 7448 SDLoc dl(NewResChain); 7449 7450 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 7451 NewResChain, DAG.getUNDEF(MVT::Other)); 7452 assert(TF.getNode() != NewResChain.getNode() && 7453 "A new TF really is required here"); 7454 7455 DAG.ReplaceAllUsesOfValueWith(ResChain, TF); 7456 DAG.UpdateNodeOperands(TF.getNode(), ResChain, NewResChain); 7457 } 7458 7459 /// Analyze profitability of direct move 7460 /// prefer float load to int load plus direct move 7461 /// when there is no integer use of int load 7462 bool PPCTargetLowering::directMoveIsProfitable(const SDValue &Op) const { 7463 SDNode *Origin = Op.getOperand(0).getNode(); 7464 if (Origin->getOpcode() != ISD::LOAD) 7465 return true; 7466 7467 // If there is no LXSIBZX/LXSIHZX, like Power8, 7468 // prefer direct move if the memory size is 1 or 2 bytes. 7469 MachineMemOperand *MMO = cast<LoadSDNode>(Origin)->getMemOperand(); 7470 if (!Subtarget.hasP9Vector() && MMO->getSize() <= 2) 7471 return true; 7472 7473 for (SDNode::use_iterator UI = Origin->use_begin(), 7474 UE = Origin->use_end(); 7475 UI != UE; ++UI) { 7476 7477 // Only look at the users of the loaded value. 7478 if (UI.getUse().get().getResNo() != 0) 7479 continue; 7480 7481 if (UI->getOpcode() != ISD::SINT_TO_FP && 7482 UI->getOpcode() != ISD::UINT_TO_FP) 7483 return true; 7484 } 7485 7486 return false; 7487 } 7488 7489 /// Custom lowers integer to floating point conversions to use 7490 /// the direct move instructions available in ISA 2.07 to avoid the 7491 /// need for load/store combinations. 7492 SDValue PPCTargetLowering::LowerINT_TO_FPDirectMove(SDValue Op, 7493 SelectionDAG &DAG, 7494 const SDLoc &dl) const { 7495 assert((Op.getValueType() == MVT::f32 || 7496 Op.getValueType() == MVT::f64) && 7497 "Invalid floating point type as target of conversion"); 7498 assert(Subtarget.hasFPCVT() && 7499 "Int to FP conversions with direct moves require FPCVT"); 7500 SDValue FP; 7501 SDValue Src = Op.getOperand(0); 7502 bool SinglePrec = Op.getValueType() == MVT::f32; 7503 bool WordInt = Src.getSimpleValueType().SimpleTy == MVT::i32; 7504 bool Signed = Op.getOpcode() == ISD::SINT_TO_FP; 7505 unsigned ConvOp = Signed ? (SinglePrec ? PPCISD::FCFIDS : PPCISD::FCFID) : 7506 (SinglePrec ? PPCISD::FCFIDUS : PPCISD::FCFIDU); 7507 7508 if (WordInt) { 7509 FP = DAG.getNode(Signed ? PPCISD::MTVSRA : PPCISD::MTVSRZ, 7510 dl, MVT::f64, Src); 7511 FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP); 7512 } 7513 else { 7514 FP = DAG.getNode(PPCISD::MTVSRA, dl, MVT::f64, Src); 7515 FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP); 7516 } 7517 7518 return FP; 7519 } 7520 7521 static SDValue widenVec(SelectionDAG &DAG, SDValue Vec, const SDLoc &dl) { 7522 7523 EVT VecVT = Vec.getValueType(); 7524 assert(VecVT.isVector() && "Expected a vector type."); 7525 assert(VecVT.getSizeInBits() < 128 && "Vector is already full width."); 7526 7527 EVT EltVT = VecVT.getVectorElementType(); 7528 unsigned WideNumElts = 128 / EltVT.getSizeInBits(); 7529 EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts); 7530 7531 unsigned NumConcat = WideNumElts / VecVT.getVectorNumElements(); 7532 SmallVector<SDValue, 16> Ops(NumConcat); 7533 Ops[0] = Vec; 7534 SDValue UndefVec = DAG.getUNDEF(VecVT); 7535 for (unsigned i = 1; i < NumConcat; ++i) 7536 Ops[i] = UndefVec; 7537 7538 return DAG.getNode(ISD::CONCAT_VECTORS, dl, WideVT, Ops); 7539 } 7540 7541 SDValue PPCTargetLowering::LowerINT_TO_FPVector(SDValue Op, SelectionDAG &DAG, 7542 const SDLoc &dl) const { 7543 7544 unsigned Opc = Op.getOpcode(); 7545 assert((Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP) && 7546 "Unexpected conversion type"); 7547 assert((Op.getValueType() == MVT::v2f64 || Op.getValueType() == MVT::v4f32) && 7548 "Supports conversions to v2f64/v4f32 only."); 7549 7550 bool SignedConv = Opc == ISD::SINT_TO_FP; 7551 bool FourEltRes = Op.getValueType() == MVT::v4f32; 7552 7553 SDValue Wide = widenVec(DAG, Op.getOperand(0), dl); 7554 EVT WideVT = Wide.getValueType(); 7555 unsigned WideNumElts = WideVT.getVectorNumElements(); 7556 MVT IntermediateVT = FourEltRes ? MVT::v4i32 : MVT::v2i64; 7557 7558 SmallVector<int, 16> ShuffV; 7559 for (unsigned i = 0; i < WideNumElts; ++i) 7560 ShuffV.push_back(i + WideNumElts); 7561 7562 int Stride = FourEltRes ? WideNumElts / 4 : WideNumElts / 2; 7563 int SaveElts = FourEltRes ? 4 : 2; 7564 if (Subtarget.isLittleEndian()) 7565 for (int i = 0; i < SaveElts; i++) 7566 ShuffV[i * Stride] = i; 7567 else 7568 for (int i = 1; i <= SaveElts; i++) 7569 ShuffV[i * Stride - 1] = i - 1; 7570 7571 SDValue ShuffleSrc2 = 7572 SignedConv ? DAG.getUNDEF(WideVT) : DAG.getConstant(0, dl, WideVT); 7573 SDValue Arrange = DAG.getVectorShuffle(WideVT, dl, Wide, ShuffleSrc2, ShuffV); 7574 unsigned ExtendOp = 7575 SignedConv ? (unsigned)PPCISD::SExtVElems : (unsigned)ISD::BITCAST; 7576 7577 SDValue Extend; 7578 if (!Subtarget.hasP9Altivec() && SignedConv) { 7579 Arrange = DAG.getBitcast(IntermediateVT, Arrange); 7580 Extend = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, IntermediateVT, Arrange, 7581 DAG.getValueType(Op.getOperand(0).getValueType())); 7582 } else 7583 Extend = DAG.getNode(ExtendOp, dl, IntermediateVT, Arrange); 7584 7585 return DAG.getNode(Opc, dl, Op.getValueType(), Extend); 7586 } 7587 7588 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op, 7589 SelectionDAG &DAG) const { 7590 SDLoc dl(Op); 7591 7592 EVT InVT = Op.getOperand(0).getValueType(); 7593 EVT OutVT = Op.getValueType(); 7594 if (OutVT.isVector() && OutVT.isFloatingPoint() && 7595 isOperationCustom(Op.getOpcode(), InVT)) 7596 return LowerINT_TO_FPVector(Op, DAG, dl); 7597 7598 // Conversions to f128 are legal. 7599 if (EnableQuadPrecision && (Op.getValueType() == MVT::f128)) 7600 return Op; 7601 7602 if (Subtarget.hasQPX() && Op.getOperand(0).getValueType() == MVT::v4i1) { 7603 if (Op.getValueType() != MVT::v4f32 && Op.getValueType() != MVT::v4f64) 7604 return SDValue(); 7605 7606 SDValue Value = Op.getOperand(0); 7607 // The values are now known to be -1 (false) or 1 (true). To convert this 7608 // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5). 7609 // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5 7610 Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value); 7611 7612 SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64); 7613 7614 Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs); 7615 7616 if (Op.getValueType() != MVT::v4f64) 7617 Value = DAG.getNode(ISD::FP_ROUND, dl, 7618 Op.getValueType(), Value, 7619 DAG.getIntPtrConstant(1, dl)); 7620 return Value; 7621 } 7622 7623 // Don't handle ppc_fp128 here; let it be lowered to a libcall. 7624 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64) 7625 return SDValue(); 7626 7627 if (Op.getOperand(0).getValueType() == MVT::i1) 7628 return DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Op.getOperand(0), 7629 DAG.getConstantFP(1.0, dl, Op.getValueType()), 7630 DAG.getConstantFP(0.0, dl, Op.getValueType())); 7631 7632 // If we have direct moves, we can do all the conversion, skip the store/load 7633 // however, without FPCVT we can't do most conversions. 7634 if (Subtarget.hasDirectMove() && directMoveIsProfitable(Op) && 7635 Subtarget.isPPC64() && Subtarget.hasFPCVT()) 7636 return LowerINT_TO_FPDirectMove(Op, DAG, dl); 7637 7638 assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) && 7639 "UINT_TO_FP is supported only with FPCVT"); 7640 7641 // If we have FCFIDS, then use it when converting to single-precision. 7642 // Otherwise, convert to double-precision and then round. 7643 unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 7644 ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS 7645 : PPCISD::FCFIDS) 7646 : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU 7647 : PPCISD::FCFID); 7648 MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 7649 ? MVT::f32 7650 : MVT::f64; 7651 7652 if (Op.getOperand(0).getValueType() == MVT::i64) { 7653 SDValue SINT = Op.getOperand(0); 7654 // When converting to single-precision, we actually need to convert 7655 // to double-precision first and then round to single-precision. 7656 // To avoid double-rounding effects during that operation, we have 7657 // to prepare the input operand. Bits that might be truncated when 7658 // converting to double-precision are replaced by a bit that won't 7659 // be lost at this stage, but is below the single-precision rounding 7660 // position. 7661 // 7662 // However, if -enable-unsafe-fp-math is in effect, accept double 7663 // rounding to avoid the extra overhead. 7664 if (Op.getValueType() == MVT::f32 && 7665 !Subtarget.hasFPCVT() && 7666 !DAG.getTarget().Options.UnsafeFPMath) { 7667 7668 // Twiddle input to make sure the low 11 bits are zero. (If this 7669 // is the case, we are guaranteed the value will fit into the 53 bit 7670 // mantissa of an IEEE double-precision value without rounding.) 7671 // If any of those low 11 bits were not zero originally, make sure 7672 // bit 12 (value 2048) is set instead, so that the final rounding 7673 // to single-precision gets the correct result. 7674 SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64, 7675 SINT, DAG.getConstant(2047, dl, MVT::i64)); 7676 Round = DAG.getNode(ISD::ADD, dl, MVT::i64, 7677 Round, DAG.getConstant(2047, dl, MVT::i64)); 7678 Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT); 7679 Round = DAG.getNode(ISD::AND, dl, MVT::i64, 7680 Round, DAG.getConstant(-2048, dl, MVT::i64)); 7681 7682 // However, we cannot use that value unconditionally: if the magnitude 7683 // of the input value is small, the bit-twiddling we did above might 7684 // end up visibly changing the output. Fortunately, in that case, we 7685 // don't need to twiddle bits since the original input will convert 7686 // exactly to double-precision floating-point already. Therefore, 7687 // construct a conditional to use the original value if the top 11 7688 // bits are all sign-bit copies, and use the rounded value computed 7689 // above otherwise. 7690 SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64, 7691 SINT, DAG.getConstant(53, dl, MVT::i32)); 7692 Cond = DAG.getNode(ISD::ADD, dl, MVT::i64, 7693 Cond, DAG.getConstant(1, dl, MVT::i64)); 7694 Cond = DAG.getSetCC(dl, MVT::i32, 7695 Cond, DAG.getConstant(1, dl, MVT::i64), ISD::SETUGT); 7696 7697 SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT); 7698 } 7699 7700 ReuseLoadInfo RLI; 7701 SDValue Bits; 7702 7703 MachineFunction &MF = DAG.getMachineFunction(); 7704 if (canReuseLoadAddress(SINT, MVT::i64, RLI, DAG)) { 7705 Bits = DAG.getLoad(MVT::f64, dl, RLI.Chain, RLI.Ptr, RLI.MPI, 7706 RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges); 7707 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG); 7708 } else if (Subtarget.hasLFIWAX() && 7709 canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::SEXTLOAD)) { 7710 MachineMemOperand *MMO = 7711 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 7712 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 7713 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 7714 Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWAX, dl, 7715 DAG.getVTList(MVT::f64, MVT::Other), 7716 Ops, MVT::i32, MMO); 7717 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG); 7718 } else if (Subtarget.hasFPCVT() && 7719 canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::ZEXTLOAD)) { 7720 MachineMemOperand *MMO = 7721 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 7722 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 7723 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 7724 Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWZX, dl, 7725 DAG.getVTList(MVT::f64, MVT::Other), 7726 Ops, MVT::i32, MMO); 7727 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG); 7728 } else if (((Subtarget.hasLFIWAX() && 7729 SINT.getOpcode() == ISD::SIGN_EXTEND) || 7730 (Subtarget.hasFPCVT() && 7731 SINT.getOpcode() == ISD::ZERO_EXTEND)) && 7732 SINT.getOperand(0).getValueType() == MVT::i32) { 7733 MachineFrameInfo &MFI = MF.getFrameInfo(); 7734 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7735 7736 int FrameIdx = MFI.CreateStackObject(4, 4, false); 7737 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 7738 7739 SDValue Store = 7740 DAG.getStore(DAG.getEntryNode(), dl, SINT.getOperand(0), FIdx, 7741 MachinePointerInfo::getFixedStack( 7742 DAG.getMachineFunction(), FrameIdx)); 7743 7744 assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 && 7745 "Expected an i32 store"); 7746 7747 RLI.Ptr = FIdx; 7748 RLI.Chain = Store; 7749 RLI.MPI = 7750 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 7751 RLI.Alignment = 4; 7752 7753 MachineMemOperand *MMO = 7754 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 7755 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 7756 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 7757 Bits = DAG.getMemIntrinsicNode(SINT.getOpcode() == ISD::ZERO_EXTEND ? 7758 PPCISD::LFIWZX : PPCISD::LFIWAX, 7759 dl, DAG.getVTList(MVT::f64, MVT::Other), 7760 Ops, MVT::i32, MMO); 7761 } else 7762 Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT); 7763 7764 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Bits); 7765 7766 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) 7767 FP = DAG.getNode(ISD::FP_ROUND, dl, 7768 MVT::f32, FP, DAG.getIntPtrConstant(0, dl)); 7769 return FP; 7770 } 7771 7772 assert(Op.getOperand(0).getValueType() == MVT::i32 && 7773 "Unhandled INT_TO_FP type in custom expander!"); 7774 // Since we only generate this in 64-bit mode, we can take advantage of 7775 // 64-bit registers. In particular, sign extend the input value into the 7776 // 64-bit register with extsw, store the WHOLE 64-bit value into the stack 7777 // then lfd it and fcfid it. 7778 MachineFunction &MF = DAG.getMachineFunction(); 7779 MachineFrameInfo &MFI = MF.getFrameInfo(); 7780 EVT PtrVT = getPointerTy(MF.getDataLayout()); 7781 7782 SDValue Ld; 7783 if (Subtarget.hasLFIWAX() || Subtarget.hasFPCVT()) { 7784 ReuseLoadInfo RLI; 7785 bool ReusingLoad; 7786 if (!(ReusingLoad = canReuseLoadAddress(Op.getOperand(0), MVT::i32, RLI, 7787 DAG))) { 7788 int FrameIdx = MFI.CreateStackObject(4, 4, false); 7789 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 7790 7791 SDValue Store = 7792 DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx, 7793 MachinePointerInfo::getFixedStack( 7794 DAG.getMachineFunction(), FrameIdx)); 7795 7796 assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 && 7797 "Expected an i32 store"); 7798 7799 RLI.Ptr = FIdx; 7800 RLI.Chain = Store; 7801 RLI.MPI = 7802 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 7803 RLI.Alignment = 4; 7804 } 7805 7806 MachineMemOperand *MMO = 7807 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 7808 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 7809 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 7810 Ld = DAG.getMemIntrinsicNode(Op.getOpcode() == ISD::UINT_TO_FP ? 7811 PPCISD::LFIWZX : PPCISD::LFIWAX, 7812 dl, DAG.getVTList(MVT::f64, MVT::Other), 7813 Ops, MVT::i32, MMO); 7814 if (ReusingLoad) 7815 spliceIntoChain(RLI.ResChain, Ld.getValue(1), DAG); 7816 } else { 7817 assert(Subtarget.isPPC64() && 7818 "i32->FP without LFIWAX supported only on PPC64"); 7819 7820 int FrameIdx = MFI.CreateStackObject(8, 8, false); 7821 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 7822 7823 SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64, 7824 Op.getOperand(0)); 7825 7826 // STD the extended value into the stack slot. 7827 SDValue Store = DAG.getStore( 7828 DAG.getEntryNode(), dl, Ext64, FIdx, 7829 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx)); 7830 7831 // Load the value as a double. 7832 Ld = DAG.getLoad( 7833 MVT::f64, dl, Store, FIdx, 7834 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx)); 7835 } 7836 7837 // FCFID it and return it. 7838 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Ld); 7839 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) 7840 FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP, 7841 DAG.getIntPtrConstant(0, dl)); 7842 return FP; 7843 } 7844 7845 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op, 7846 SelectionDAG &DAG) const { 7847 SDLoc dl(Op); 7848 /* 7849 The rounding mode is in bits 30:31 of FPSR, and has the following 7850 settings: 7851 00 Round to nearest 7852 01 Round to 0 7853 10 Round to +inf 7854 11 Round to -inf 7855 7856 FLT_ROUNDS, on the other hand, expects the following: 7857 -1 Undefined 7858 0 Round to 0 7859 1 Round to nearest 7860 2 Round to +inf 7861 3 Round to -inf 7862 7863 To perform the conversion, we do: 7864 ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1)) 7865 */ 7866 7867 MachineFunction &MF = DAG.getMachineFunction(); 7868 EVT VT = Op.getValueType(); 7869 EVT PtrVT = getPointerTy(MF.getDataLayout()); 7870 7871 // Save FP Control Word to register 7872 EVT NodeTys[] = { 7873 MVT::f64, // return register 7874 MVT::Glue // unused in this context 7875 }; 7876 SDValue Chain = DAG.getNode(PPCISD::MFFS, dl, NodeTys, None); 7877 7878 // Save FP register to stack slot 7879 int SSFI = MF.getFrameInfo().CreateStackObject(8, 8, false); 7880 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT); 7881 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Chain, StackSlot, 7882 MachinePointerInfo()); 7883 7884 // Load FP Control Word from low 32 bits of stack slot. 7885 SDValue Four = DAG.getConstant(4, dl, PtrVT); 7886 SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four); 7887 SDValue CWD = DAG.getLoad(MVT::i32, dl, Store, Addr, MachinePointerInfo()); 7888 7889 // Transform as necessary 7890 SDValue CWD1 = 7891 DAG.getNode(ISD::AND, dl, MVT::i32, 7892 CWD, DAG.getConstant(3, dl, MVT::i32)); 7893 SDValue CWD2 = 7894 DAG.getNode(ISD::SRL, dl, MVT::i32, 7895 DAG.getNode(ISD::AND, dl, MVT::i32, 7896 DAG.getNode(ISD::XOR, dl, MVT::i32, 7897 CWD, DAG.getConstant(3, dl, MVT::i32)), 7898 DAG.getConstant(3, dl, MVT::i32)), 7899 DAG.getConstant(1, dl, MVT::i32)); 7900 7901 SDValue RetVal = 7902 DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2); 7903 7904 return DAG.getNode((VT.getSizeInBits() < 16 ? 7905 ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal); 7906 } 7907 7908 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const { 7909 EVT VT = Op.getValueType(); 7910 unsigned BitWidth = VT.getSizeInBits(); 7911 SDLoc dl(Op); 7912 assert(Op.getNumOperands() == 3 && 7913 VT == Op.getOperand(1).getValueType() && 7914 "Unexpected SHL!"); 7915 7916 // Expand into a bunch of logical ops. Note that these ops 7917 // depend on the PPC behavior for oversized shift amounts. 7918 SDValue Lo = Op.getOperand(0); 7919 SDValue Hi = Op.getOperand(1); 7920 SDValue Amt = Op.getOperand(2); 7921 EVT AmtVT = Amt.getValueType(); 7922 7923 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, 7924 DAG.getConstant(BitWidth, dl, AmtVT), Amt); 7925 SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt); 7926 SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1); 7927 SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3); 7928 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, 7929 DAG.getConstant(-BitWidth, dl, AmtVT)); 7930 SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5); 7931 SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6); 7932 SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt); 7933 SDValue OutOps[] = { OutLo, OutHi }; 7934 return DAG.getMergeValues(OutOps, dl); 7935 } 7936 7937 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const { 7938 EVT VT = Op.getValueType(); 7939 SDLoc dl(Op); 7940 unsigned BitWidth = VT.getSizeInBits(); 7941 assert(Op.getNumOperands() == 3 && 7942 VT == Op.getOperand(1).getValueType() && 7943 "Unexpected SRL!"); 7944 7945 // Expand into a bunch of logical ops. Note that these ops 7946 // depend on the PPC behavior for oversized shift amounts. 7947 SDValue Lo = Op.getOperand(0); 7948 SDValue Hi = Op.getOperand(1); 7949 SDValue Amt = Op.getOperand(2); 7950 EVT AmtVT = Amt.getValueType(); 7951 7952 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, 7953 DAG.getConstant(BitWidth, dl, AmtVT), Amt); 7954 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt); 7955 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1); 7956 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3); 7957 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, 7958 DAG.getConstant(-BitWidth, dl, AmtVT)); 7959 SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5); 7960 SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6); 7961 SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt); 7962 SDValue OutOps[] = { OutLo, OutHi }; 7963 return DAG.getMergeValues(OutOps, dl); 7964 } 7965 7966 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const { 7967 SDLoc dl(Op); 7968 EVT VT = Op.getValueType(); 7969 unsigned BitWidth = VT.getSizeInBits(); 7970 assert(Op.getNumOperands() == 3 && 7971 VT == Op.getOperand(1).getValueType() && 7972 "Unexpected SRA!"); 7973 7974 // Expand into a bunch of logical ops, followed by a select_cc. 7975 SDValue Lo = Op.getOperand(0); 7976 SDValue Hi = Op.getOperand(1); 7977 SDValue Amt = Op.getOperand(2); 7978 EVT AmtVT = Amt.getValueType(); 7979 7980 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, 7981 DAG.getConstant(BitWidth, dl, AmtVT), Amt); 7982 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt); 7983 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1); 7984 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3); 7985 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, 7986 DAG.getConstant(-BitWidth, dl, AmtVT)); 7987 SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5); 7988 SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt); 7989 SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, dl, AmtVT), 7990 Tmp4, Tmp6, ISD::SETLE); 7991 SDValue OutOps[] = { OutLo, OutHi }; 7992 return DAG.getMergeValues(OutOps, dl); 7993 } 7994 7995 //===----------------------------------------------------------------------===// 7996 // Vector related lowering. 7997 // 7998 7999 /// BuildSplatI - Build a canonical splati of Val with an element size of 8000 /// SplatSize. Cast the result to VT. 8001 static SDValue BuildSplatI(int Val, unsigned SplatSize, EVT VT, 8002 SelectionDAG &DAG, const SDLoc &dl) { 8003 assert(Val >= -16 && Val <= 15 && "vsplti is out of range!"); 8004 8005 static const MVT VTys[] = { // canonical VT to use for each size. 8006 MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32 8007 }; 8008 8009 EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1]; 8010 8011 // Force vspltis[hw] -1 to vspltisb -1 to canonicalize. 8012 if (Val == -1) 8013 SplatSize = 1; 8014 8015 EVT CanonicalVT = VTys[SplatSize-1]; 8016 8017 // Build a canonical splat for this value. 8018 return DAG.getBitcast(ReqVT, DAG.getConstant(Val, dl, CanonicalVT)); 8019 } 8020 8021 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the 8022 /// specified intrinsic ID. 8023 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op, SelectionDAG &DAG, 8024 const SDLoc &dl, EVT DestVT = MVT::Other) { 8025 if (DestVT == MVT::Other) DestVT = Op.getValueType(); 8026 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 8027 DAG.getConstant(IID, dl, MVT::i32), Op); 8028 } 8029 8030 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the 8031 /// specified intrinsic ID. 8032 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS, 8033 SelectionDAG &DAG, const SDLoc &dl, 8034 EVT DestVT = MVT::Other) { 8035 if (DestVT == MVT::Other) DestVT = LHS.getValueType(); 8036 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 8037 DAG.getConstant(IID, dl, MVT::i32), LHS, RHS); 8038 } 8039 8040 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the 8041 /// specified intrinsic ID. 8042 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1, 8043 SDValue Op2, SelectionDAG &DAG, const SDLoc &dl, 8044 EVT DestVT = MVT::Other) { 8045 if (DestVT == MVT::Other) DestVT = Op0.getValueType(); 8046 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 8047 DAG.getConstant(IID, dl, MVT::i32), Op0, Op1, Op2); 8048 } 8049 8050 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified 8051 /// amount. The result has the specified value type. 8052 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt, EVT VT, 8053 SelectionDAG &DAG, const SDLoc &dl) { 8054 // Force LHS/RHS to be the right type. 8055 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS); 8056 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS); 8057 8058 int Ops[16]; 8059 for (unsigned i = 0; i != 16; ++i) 8060 Ops[i] = i + Amt; 8061 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops); 8062 return DAG.getNode(ISD::BITCAST, dl, VT, T); 8063 } 8064 8065 /// Do we have an efficient pattern in a .td file for this node? 8066 /// 8067 /// \param V - pointer to the BuildVectorSDNode being matched 8068 /// \param HasDirectMove - does this subtarget have VSR <-> GPR direct moves? 8069 /// 8070 /// There are some patterns where it is beneficial to keep a BUILD_VECTOR 8071 /// node as a BUILD_VECTOR node rather than expanding it. The patterns where 8072 /// the opposite is true (expansion is beneficial) are: 8073 /// - The node builds a vector out of integers that are not 32 or 64-bits 8074 /// - The node builds a vector out of constants 8075 /// - The node is a "load-and-splat" 8076 /// In all other cases, we will choose to keep the BUILD_VECTOR. 8077 static bool haveEfficientBuildVectorPattern(BuildVectorSDNode *V, 8078 bool HasDirectMove, 8079 bool HasP8Vector) { 8080 EVT VecVT = V->getValueType(0); 8081 bool RightType = VecVT == MVT::v2f64 || 8082 (HasP8Vector && VecVT == MVT::v4f32) || 8083 (HasDirectMove && (VecVT == MVT::v2i64 || VecVT == MVT::v4i32)); 8084 if (!RightType) 8085 return false; 8086 8087 bool IsSplat = true; 8088 bool IsLoad = false; 8089 SDValue Op0 = V->getOperand(0); 8090 8091 // This function is called in a block that confirms the node is not a constant 8092 // splat. So a constant BUILD_VECTOR here means the vector is built out of 8093 // different constants. 8094 if (V->isConstant()) 8095 return false; 8096 for (int i = 0, e = V->getNumOperands(); i < e; ++i) { 8097 if (V->getOperand(i).isUndef()) 8098 return false; 8099 // We want to expand nodes that represent load-and-splat even if the 8100 // loaded value is a floating point truncation or conversion to int. 8101 if (V->getOperand(i).getOpcode() == ISD::LOAD || 8102 (V->getOperand(i).getOpcode() == ISD::FP_ROUND && 8103 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) || 8104 (V->getOperand(i).getOpcode() == ISD::FP_TO_SINT && 8105 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) || 8106 (V->getOperand(i).getOpcode() == ISD::FP_TO_UINT && 8107 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD)) 8108 IsLoad = true; 8109 // If the operands are different or the input is not a load and has more 8110 // uses than just this BV node, then it isn't a splat. 8111 if (V->getOperand(i) != Op0 || 8112 (!IsLoad && !V->isOnlyUserOf(V->getOperand(i).getNode()))) 8113 IsSplat = false; 8114 } 8115 return !(IsSplat && IsLoad); 8116 } 8117 8118 // Lower BITCAST(f128, (build_pair i64, i64)) to BUILD_FP128. 8119 SDValue PPCTargetLowering::LowerBITCAST(SDValue Op, SelectionDAG &DAG) const { 8120 8121 SDLoc dl(Op); 8122 SDValue Op0 = Op->getOperand(0); 8123 8124 if (!EnableQuadPrecision || 8125 (Op.getValueType() != MVT::f128 ) || 8126 (Op0.getOpcode() != ISD::BUILD_PAIR) || 8127 (Op0.getOperand(0).getValueType() != MVT::i64) || 8128 (Op0.getOperand(1).getValueType() != MVT::i64)) 8129 return SDValue(); 8130 8131 return DAG.getNode(PPCISD::BUILD_FP128, dl, MVT::f128, Op0.getOperand(0), 8132 Op0.getOperand(1)); 8133 } 8134 8135 // If this is a case we can't handle, return null and let the default 8136 // expansion code take care of it. If we CAN select this case, and if it 8137 // selects to a single instruction, return Op. Otherwise, if we can codegen 8138 // this case more efficiently than a constant pool load, lower it to the 8139 // sequence of ops that should be used. 8140 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op, 8141 SelectionDAG &DAG) const { 8142 SDLoc dl(Op); 8143 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode()); 8144 assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR"); 8145 8146 if (Subtarget.hasQPX() && Op.getValueType() == MVT::v4i1) { 8147 // We first build an i32 vector, load it into a QPX register, 8148 // then convert it to a floating-point vector and compare it 8149 // to a zero vector to get the boolean result. 8150 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 8151 int FrameIdx = MFI.CreateStackObject(16, 16, false); 8152 MachinePointerInfo PtrInfo = 8153 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 8154 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 8155 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 8156 8157 assert(BVN->getNumOperands() == 4 && 8158 "BUILD_VECTOR for v4i1 does not have 4 operands"); 8159 8160 bool IsConst = true; 8161 for (unsigned i = 0; i < 4; ++i) { 8162 if (BVN->getOperand(i).isUndef()) continue; 8163 if (!isa<ConstantSDNode>(BVN->getOperand(i))) { 8164 IsConst = false; 8165 break; 8166 } 8167 } 8168 8169 if (IsConst) { 8170 Constant *One = 8171 ConstantFP::get(Type::getFloatTy(*DAG.getContext()), 1.0); 8172 Constant *NegOne = 8173 ConstantFP::get(Type::getFloatTy(*DAG.getContext()), -1.0); 8174 8175 Constant *CV[4]; 8176 for (unsigned i = 0; i < 4; ++i) { 8177 if (BVN->getOperand(i).isUndef()) 8178 CV[i] = UndefValue::get(Type::getFloatTy(*DAG.getContext())); 8179 else if (isNullConstant(BVN->getOperand(i))) 8180 CV[i] = NegOne; 8181 else 8182 CV[i] = One; 8183 } 8184 8185 Constant *CP = ConstantVector::get(CV); 8186 SDValue CPIdx = DAG.getConstantPool(CP, getPointerTy(DAG.getDataLayout()), 8187 16 /* alignment */); 8188 8189 SDValue Ops[] = {DAG.getEntryNode(), CPIdx}; 8190 SDVTList VTs = DAG.getVTList({MVT::v4i1, /*chain*/ MVT::Other}); 8191 return DAG.getMemIntrinsicNode( 8192 PPCISD::QVLFSb, dl, VTs, Ops, MVT::v4f32, 8193 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 8194 } 8195 8196 SmallVector<SDValue, 4> Stores; 8197 for (unsigned i = 0; i < 4; ++i) { 8198 if (BVN->getOperand(i).isUndef()) continue; 8199 8200 unsigned Offset = 4*i; 8201 SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType()); 8202 Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx); 8203 8204 unsigned StoreSize = BVN->getOperand(i).getValueType().getStoreSize(); 8205 if (StoreSize > 4) { 8206 Stores.push_back( 8207 DAG.getTruncStore(DAG.getEntryNode(), dl, BVN->getOperand(i), Idx, 8208 PtrInfo.getWithOffset(Offset), MVT::i32)); 8209 } else { 8210 SDValue StoreValue = BVN->getOperand(i); 8211 if (StoreSize < 4) 8212 StoreValue = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, StoreValue); 8213 8214 Stores.push_back(DAG.getStore(DAG.getEntryNode(), dl, StoreValue, Idx, 8215 PtrInfo.getWithOffset(Offset))); 8216 } 8217 } 8218 8219 SDValue StoreChain; 8220 if (!Stores.empty()) 8221 StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores); 8222 else 8223 StoreChain = DAG.getEntryNode(); 8224 8225 // Now load from v4i32 into the QPX register; this will extend it to 8226 // v4i64 but not yet convert it to a floating point. Nevertheless, this 8227 // is typed as v4f64 because the QPX register integer states are not 8228 // explicitly represented. 8229 8230 SDValue Ops[] = {StoreChain, 8231 DAG.getConstant(Intrinsic::ppc_qpx_qvlfiwz, dl, MVT::i32), 8232 FIdx}; 8233 SDVTList VTs = DAG.getVTList({MVT::v4f64, /*chain*/ MVT::Other}); 8234 8235 SDValue LoadedVect = DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, 8236 dl, VTs, Ops, MVT::v4i32, PtrInfo); 8237 LoadedVect = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64, 8238 DAG.getConstant(Intrinsic::ppc_qpx_qvfcfidu, dl, MVT::i32), 8239 LoadedVect); 8240 8241 SDValue FPZeros = DAG.getConstantFP(0.0, dl, MVT::v4f64); 8242 8243 return DAG.getSetCC(dl, MVT::v4i1, LoadedVect, FPZeros, ISD::SETEQ); 8244 } 8245 8246 // All other QPX vectors are handled by generic code. 8247 if (Subtarget.hasQPX()) 8248 return SDValue(); 8249 8250 // Check if this is a splat of a constant value. 8251 APInt APSplatBits, APSplatUndef; 8252 unsigned SplatBitSize; 8253 bool HasAnyUndefs; 8254 if (! BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize, 8255 HasAnyUndefs, 0, !Subtarget.isLittleEndian()) || 8256 SplatBitSize > 32) { 8257 // BUILD_VECTOR nodes that are not constant splats of up to 32-bits can be 8258 // lowered to VSX instructions under certain conditions. 8259 // Without VSX, there is no pattern more efficient than expanding the node. 8260 if (Subtarget.hasVSX() && 8261 haveEfficientBuildVectorPattern(BVN, Subtarget.hasDirectMove(), 8262 Subtarget.hasP8Vector())) 8263 return Op; 8264 return SDValue(); 8265 } 8266 8267 unsigned SplatBits = APSplatBits.getZExtValue(); 8268 unsigned SplatUndef = APSplatUndef.getZExtValue(); 8269 unsigned SplatSize = SplatBitSize / 8; 8270 8271 // First, handle single instruction cases. 8272 8273 // All zeros? 8274 if (SplatBits == 0) { 8275 // Canonicalize all zero vectors to be v4i32. 8276 if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) { 8277 SDValue Z = DAG.getConstant(0, dl, MVT::v4i32); 8278 Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z); 8279 } 8280 return Op; 8281 } 8282 8283 // We have XXSPLTIB for constant splats one byte wide 8284 if (Subtarget.hasP9Vector() && SplatSize == 1) { 8285 // This is a splat of 1-byte elements with some elements potentially undef. 8286 // Rather than trying to match undef in the SDAG patterns, ensure that all 8287 // elements are the same constant. 8288 if (HasAnyUndefs || ISD::isBuildVectorAllOnes(BVN)) { 8289 SmallVector<SDValue, 16> Ops(16, DAG.getConstant(SplatBits, 8290 dl, MVT::i32)); 8291 SDValue NewBV = DAG.getBuildVector(MVT::v16i8, dl, Ops); 8292 if (Op.getValueType() != MVT::v16i8) 8293 return DAG.getBitcast(Op.getValueType(), NewBV); 8294 return NewBV; 8295 } 8296 8297 // BuildVectorSDNode::isConstantSplat() is actually pretty smart. It'll 8298 // detect that constant splats like v8i16: 0xABAB are really just splats 8299 // of a 1-byte constant. In this case, we need to convert the node to a 8300 // splat of v16i8 and a bitcast. 8301 if (Op.getValueType() != MVT::v16i8) 8302 return DAG.getBitcast(Op.getValueType(), 8303 DAG.getConstant(SplatBits, dl, MVT::v16i8)); 8304 8305 return Op; 8306 } 8307 8308 // If the sign extended value is in the range [-16,15], use VSPLTI[bhw]. 8309 int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >> 8310 (32-SplatBitSize)); 8311 if (SextVal >= -16 && SextVal <= 15) 8312 return BuildSplatI(SextVal, SplatSize, Op.getValueType(), DAG, dl); 8313 8314 // Two instruction sequences. 8315 8316 // If this value is in the range [-32,30] and is even, use: 8317 // VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2) 8318 // If this value is in the range [17,31] and is odd, use: 8319 // VSPLTI[bhw](val-16) - VSPLTI[bhw](-16) 8320 // If this value is in the range [-31,-17] and is odd, use: 8321 // VSPLTI[bhw](val+16) + VSPLTI[bhw](-16) 8322 // Note the last two are three-instruction sequences. 8323 if (SextVal >= -32 && SextVal <= 31) { 8324 // To avoid having these optimizations undone by constant folding, 8325 // we convert to a pseudo that will be expanded later into one of 8326 // the above forms. 8327 SDValue Elt = DAG.getConstant(SextVal, dl, MVT::i32); 8328 EVT VT = (SplatSize == 1 ? MVT::v16i8 : 8329 (SplatSize == 2 ? MVT::v8i16 : MVT::v4i32)); 8330 SDValue EltSize = DAG.getConstant(SplatSize, dl, MVT::i32); 8331 SDValue RetVal = DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize); 8332 if (VT == Op.getValueType()) 8333 return RetVal; 8334 else 8335 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), RetVal); 8336 } 8337 8338 // If this is 0x8000_0000 x 4, turn into vspltisw + vslw. If it is 8339 // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000). This is important 8340 // for fneg/fabs. 8341 if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) { 8342 // Make -1 and vspltisw -1: 8343 SDValue OnesV = BuildSplatI(-1, 4, MVT::v4i32, DAG, dl); 8344 8345 // Make the VSLW intrinsic, computing 0x8000_0000. 8346 SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV, 8347 OnesV, DAG, dl); 8348 8349 // xor by OnesV to invert it. 8350 Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV); 8351 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 8352 } 8353 8354 // Check to see if this is a wide variety of vsplti*, binop self cases. 8355 static const signed char SplatCsts[] = { 8356 -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7, 8357 -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16 8358 }; 8359 8360 for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) { 8361 // Indirect through the SplatCsts array so that we favor 'vsplti -1' for 8362 // cases which are ambiguous (e.g. formation of 0x8000_0000). 'vsplti -1' 8363 int i = SplatCsts[idx]; 8364 8365 // Figure out what shift amount will be used by altivec if shifted by i in 8366 // this splat size. 8367 unsigned TypeShiftAmt = i & (SplatBitSize-1); 8368 8369 // vsplti + shl self. 8370 if (SextVal == (int)((unsigned)i << TypeShiftAmt)) { 8371 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl); 8372 static const unsigned IIDs[] = { // Intrinsic to use for each size. 8373 Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0, 8374 Intrinsic::ppc_altivec_vslw 8375 }; 8376 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 8377 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 8378 } 8379 8380 // vsplti + srl self. 8381 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) { 8382 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl); 8383 static const unsigned IIDs[] = { // Intrinsic to use for each size. 8384 Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0, 8385 Intrinsic::ppc_altivec_vsrw 8386 }; 8387 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 8388 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 8389 } 8390 8391 // vsplti + sra self. 8392 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) { 8393 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl); 8394 static const unsigned IIDs[] = { // Intrinsic to use for each size. 8395 Intrinsic::ppc_altivec_vsrab, Intrinsic::ppc_altivec_vsrah, 0, 8396 Intrinsic::ppc_altivec_vsraw 8397 }; 8398 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 8399 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 8400 } 8401 8402 // vsplti + rol self. 8403 if (SextVal == (int)(((unsigned)i << TypeShiftAmt) | 8404 ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) { 8405 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl); 8406 static const unsigned IIDs[] = { // Intrinsic to use for each size. 8407 Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0, 8408 Intrinsic::ppc_altivec_vrlw 8409 }; 8410 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 8411 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 8412 } 8413 8414 // t = vsplti c, result = vsldoi t, t, 1 8415 if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) { 8416 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl); 8417 unsigned Amt = Subtarget.isLittleEndian() ? 15 : 1; 8418 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl); 8419 } 8420 // t = vsplti c, result = vsldoi t, t, 2 8421 if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) { 8422 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl); 8423 unsigned Amt = Subtarget.isLittleEndian() ? 14 : 2; 8424 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl); 8425 } 8426 // t = vsplti c, result = vsldoi t, t, 3 8427 if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) { 8428 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl); 8429 unsigned Amt = Subtarget.isLittleEndian() ? 13 : 3; 8430 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl); 8431 } 8432 } 8433 8434 return SDValue(); 8435 } 8436 8437 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit 8438 /// the specified operations to build the shuffle. 8439 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS, 8440 SDValue RHS, SelectionDAG &DAG, 8441 const SDLoc &dl) { 8442 unsigned OpNum = (PFEntry >> 26) & 0x0F; 8443 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1); 8444 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1); 8445 8446 enum { 8447 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3> 8448 OP_VMRGHW, 8449 OP_VMRGLW, 8450 OP_VSPLTISW0, 8451 OP_VSPLTISW1, 8452 OP_VSPLTISW2, 8453 OP_VSPLTISW3, 8454 OP_VSLDOI4, 8455 OP_VSLDOI8, 8456 OP_VSLDOI12 8457 }; 8458 8459 if (OpNum == OP_COPY) { 8460 if (LHSID == (1*9+2)*9+3) return LHS; 8461 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!"); 8462 return RHS; 8463 } 8464 8465 SDValue OpLHS, OpRHS; 8466 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl); 8467 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl); 8468 8469 int ShufIdxs[16]; 8470 switch (OpNum) { 8471 default: llvm_unreachable("Unknown i32 permute!"); 8472 case OP_VMRGHW: 8473 ShufIdxs[ 0] = 0; ShufIdxs[ 1] = 1; ShufIdxs[ 2] = 2; ShufIdxs[ 3] = 3; 8474 ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19; 8475 ShufIdxs[ 8] = 4; ShufIdxs[ 9] = 5; ShufIdxs[10] = 6; ShufIdxs[11] = 7; 8476 ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23; 8477 break; 8478 case OP_VMRGLW: 8479 ShufIdxs[ 0] = 8; ShufIdxs[ 1] = 9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11; 8480 ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27; 8481 ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15; 8482 ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31; 8483 break; 8484 case OP_VSPLTISW0: 8485 for (unsigned i = 0; i != 16; ++i) 8486 ShufIdxs[i] = (i&3)+0; 8487 break; 8488 case OP_VSPLTISW1: 8489 for (unsigned i = 0; i != 16; ++i) 8490 ShufIdxs[i] = (i&3)+4; 8491 break; 8492 case OP_VSPLTISW2: 8493 for (unsigned i = 0; i != 16; ++i) 8494 ShufIdxs[i] = (i&3)+8; 8495 break; 8496 case OP_VSPLTISW3: 8497 for (unsigned i = 0; i != 16; ++i) 8498 ShufIdxs[i] = (i&3)+12; 8499 break; 8500 case OP_VSLDOI4: 8501 return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl); 8502 case OP_VSLDOI8: 8503 return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl); 8504 case OP_VSLDOI12: 8505 return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl); 8506 } 8507 EVT VT = OpLHS.getValueType(); 8508 OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS); 8509 OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS); 8510 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs); 8511 return DAG.getNode(ISD::BITCAST, dl, VT, T); 8512 } 8513 8514 /// lowerToVINSERTB - Return the SDValue if this VECTOR_SHUFFLE can be handled 8515 /// by the VINSERTB instruction introduced in ISA 3.0, else just return default 8516 /// SDValue. 8517 SDValue PPCTargetLowering::lowerToVINSERTB(ShuffleVectorSDNode *N, 8518 SelectionDAG &DAG) const { 8519 const unsigned BytesInVector = 16; 8520 bool IsLE = Subtarget.isLittleEndian(); 8521 SDLoc dl(N); 8522 SDValue V1 = N->getOperand(0); 8523 SDValue V2 = N->getOperand(1); 8524 unsigned ShiftElts = 0, InsertAtByte = 0; 8525 bool Swap = false; 8526 8527 // Shifts required to get the byte we want at element 7. 8528 unsigned LittleEndianShifts[] = {8, 7, 6, 5, 4, 3, 2, 1, 8529 0, 15, 14, 13, 12, 11, 10, 9}; 8530 unsigned BigEndianShifts[] = {9, 10, 11, 12, 13, 14, 15, 0, 8531 1, 2, 3, 4, 5, 6, 7, 8}; 8532 8533 ArrayRef<int> Mask = N->getMask(); 8534 int OriginalOrder[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}; 8535 8536 // For each mask element, find out if we're just inserting something 8537 // from V2 into V1 or vice versa. 8538 // Possible permutations inserting an element from V2 into V1: 8539 // X, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 8540 // 0, X, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 8541 // ... 8542 // 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, X 8543 // Inserting from V1 into V2 will be similar, except mask range will be 8544 // [16,31]. 8545 8546 bool FoundCandidate = false; 8547 // If both vector operands for the shuffle are the same vector, the mask 8548 // will contain only elements from the first one and the second one will be 8549 // undef. 8550 unsigned VINSERTBSrcElem = IsLE ? 8 : 7; 8551 // Go through the mask of half-words to find an element that's being moved 8552 // from one vector to the other. 8553 for (unsigned i = 0; i < BytesInVector; ++i) { 8554 unsigned CurrentElement = Mask[i]; 8555 // If 2nd operand is undefined, we should only look for element 7 in the 8556 // Mask. 8557 if (V2.isUndef() && CurrentElement != VINSERTBSrcElem) 8558 continue; 8559 8560 bool OtherElementsInOrder = true; 8561 // Examine the other elements in the Mask to see if they're in original 8562 // order. 8563 for (unsigned j = 0; j < BytesInVector; ++j) { 8564 if (j == i) 8565 continue; 8566 // If CurrentElement is from V1 [0,15], then we the rest of the Mask to be 8567 // from V2 [16,31] and vice versa. Unless the 2nd operand is undefined, 8568 // in which we always assume we're always picking from the 1st operand. 8569 int MaskOffset = 8570 (!V2.isUndef() && CurrentElement < BytesInVector) ? BytesInVector : 0; 8571 if (Mask[j] != OriginalOrder[j] + MaskOffset) { 8572 OtherElementsInOrder = false; 8573 break; 8574 } 8575 } 8576 // If other elements are in original order, we record the number of shifts 8577 // we need to get the element we want into element 7. Also record which byte 8578 // in the vector we should insert into. 8579 if (OtherElementsInOrder) { 8580 // If 2nd operand is undefined, we assume no shifts and no swapping. 8581 if (V2.isUndef()) { 8582 ShiftElts = 0; 8583 Swap = false; 8584 } else { 8585 // Only need the last 4-bits for shifts because operands will be swapped if CurrentElement is >= 2^4. 8586 ShiftElts = IsLE ? LittleEndianShifts[CurrentElement & 0xF] 8587 : BigEndianShifts[CurrentElement & 0xF]; 8588 Swap = CurrentElement < BytesInVector; 8589 } 8590 InsertAtByte = IsLE ? BytesInVector - (i + 1) : i; 8591 FoundCandidate = true; 8592 break; 8593 } 8594 } 8595 8596 if (!FoundCandidate) 8597 return SDValue(); 8598 8599 // Candidate found, construct the proper SDAG sequence with VINSERTB, 8600 // optionally with VECSHL if shift is required. 8601 if (Swap) 8602 std::swap(V1, V2); 8603 if (V2.isUndef()) 8604 V2 = V1; 8605 if (ShiftElts) { 8606 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2, 8607 DAG.getConstant(ShiftElts, dl, MVT::i32)); 8608 return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, Shl, 8609 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 8610 } 8611 return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, V2, 8612 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 8613 } 8614 8615 /// lowerToVINSERTH - Return the SDValue if this VECTOR_SHUFFLE can be handled 8616 /// by the VINSERTH instruction introduced in ISA 3.0, else just return default 8617 /// SDValue. 8618 SDValue PPCTargetLowering::lowerToVINSERTH(ShuffleVectorSDNode *N, 8619 SelectionDAG &DAG) const { 8620 const unsigned NumHalfWords = 8; 8621 const unsigned BytesInVector = NumHalfWords * 2; 8622 // Check that the shuffle is on half-words. 8623 if (!isNByteElemShuffleMask(N, 2, 1)) 8624 return SDValue(); 8625 8626 bool IsLE = Subtarget.isLittleEndian(); 8627 SDLoc dl(N); 8628 SDValue V1 = N->getOperand(0); 8629 SDValue V2 = N->getOperand(1); 8630 unsigned ShiftElts = 0, InsertAtByte = 0; 8631 bool Swap = false; 8632 8633 // Shifts required to get the half-word we want at element 3. 8634 unsigned LittleEndianShifts[] = {4, 3, 2, 1, 0, 7, 6, 5}; 8635 unsigned BigEndianShifts[] = {5, 6, 7, 0, 1, 2, 3, 4}; 8636 8637 uint32_t Mask = 0; 8638 uint32_t OriginalOrderLow = 0x1234567; 8639 uint32_t OriginalOrderHigh = 0x89ABCDEF; 8640 // Now we look at mask elements 0,2,4,6,8,10,12,14. Pack the mask into a 8641 // 32-bit space, only need 4-bit nibbles per element. 8642 for (unsigned i = 0; i < NumHalfWords; ++i) { 8643 unsigned MaskShift = (NumHalfWords - 1 - i) * 4; 8644 Mask |= ((uint32_t)(N->getMaskElt(i * 2) / 2) << MaskShift); 8645 } 8646 8647 // For each mask element, find out if we're just inserting something 8648 // from V2 into V1 or vice versa. Possible permutations inserting an element 8649 // from V2 into V1: 8650 // X, 1, 2, 3, 4, 5, 6, 7 8651 // 0, X, 2, 3, 4, 5, 6, 7 8652 // 0, 1, X, 3, 4, 5, 6, 7 8653 // 0, 1, 2, X, 4, 5, 6, 7 8654 // 0, 1, 2, 3, X, 5, 6, 7 8655 // 0, 1, 2, 3, 4, X, 6, 7 8656 // 0, 1, 2, 3, 4, 5, X, 7 8657 // 0, 1, 2, 3, 4, 5, 6, X 8658 // Inserting from V1 into V2 will be similar, except mask range will be [8,15]. 8659 8660 bool FoundCandidate = false; 8661 // Go through the mask of half-words to find an element that's being moved 8662 // from one vector to the other. 8663 for (unsigned i = 0; i < NumHalfWords; ++i) { 8664 unsigned MaskShift = (NumHalfWords - 1 - i) * 4; 8665 uint32_t MaskOneElt = (Mask >> MaskShift) & 0xF; 8666 uint32_t MaskOtherElts = ~(0xF << MaskShift); 8667 uint32_t TargetOrder = 0x0; 8668 8669 // If both vector operands for the shuffle are the same vector, the mask 8670 // will contain only elements from the first one and the second one will be 8671 // undef. 8672 if (V2.isUndef()) { 8673 ShiftElts = 0; 8674 unsigned VINSERTHSrcElem = IsLE ? 4 : 3; 8675 TargetOrder = OriginalOrderLow; 8676 Swap = false; 8677 // Skip if not the correct element or mask of other elements don't equal 8678 // to our expected order. 8679 if (MaskOneElt == VINSERTHSrcElem && 8680 (Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) { 8681 InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2; 8682 FoundCandidate = true; 8683 break; 8684 } 8685 } else { // If both operands are defined. 8686 // Target order is [8,15] if the current mask is between [0,7]. 8687 TargetOrder = 8688 (MaskOneElt < NumHalfWords) ? OriginalOrderHigh : OriginalOrderLow; 8689 // Skip if mask of other elements don't equal our expected order. 8690 if ((Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) { 8691 // We only need the last 3 bits for the number of shifts. 8692 ShiftElts = IsLE ? LittleEndianShifts[MaskOneElt & 0x7] 8693 : BigEndianShifts[MaskOneElt & 0x7]; 8694 InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2; 8695 Swap = MaskOneElt < NumHalfWords; 8696 FoundCandidate = true; 8697 break; 8698 } 8699 } 8700 } 8701 8702 if (!FoundCandidate) 8703 return SDValue(); 8704 8705 // Candidate found, construct the proper SDAG sequence with VINSERTH, 8706 // optionally with VECSHL if shift is required. 8707 if (Swap) 8708 std::swap(V1, V2); 8709 if (V2.isUndef()) 8710 V2 = V1; 8711 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1); 8712 if (ShiftElts) { 8713 // Double ShiftElts because we're left shifting on v16i8 type. 8714 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2, 8715 DAG.getConstant(2 * ShiftElts, dl, MVT::i32)); 8716 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, Shl); 8717 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2, 8718 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 8719 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 8720 } 8721 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2); 8722 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2, 8723 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 8724 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 8725 } 8726 8727 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE. If this 8728 /// is a shuffle we can handle in a single instruction, return it. Otherwise, 8729 /// return the code it can be lowered into. Worst case, it can always be 8730 /// lowered into a vperm. 8731 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, 8732 SelectionDAG &DAG) const { 8733 SDLoc dl(Op); 8734 SDValue V1 = Op.getOperand(0); 8735 SDValue V2 = Op.getOperand(1); 8736 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op); 8737 EVT VT = Op.getValueType(); 8738 bool isLittleEndian = Subtarget.isLittleEndian(); 8739 8740 unsigned ShiftElts, InsertAtByte; 8741 bool Swap = false; 8742 if (Subtarget.hasP9Vector() && 8743 PPC::isXXINSERTWMask(SVOp, ShiftElts, InsertAtByte, Swap, 8744 isLittleEndian)) { 8745 if (Swap) 8746 std::swap(V1, V2); 8747 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 8748 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2); 8749 if (ShiftElts) { 8750 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv2, Conv2, 8751 DAG.getConstant(ShiftElts, dl, MVT::i32)); 8752 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Shl, 8753 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 8754 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 8755 } 8756 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Conv2, 8757 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 8758 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 8759 } 8760 8761 if (Subtarget.hasP9Altivec()) { 8762 SDValue NewISDNode; 8763 if ((NewISDNode = lowerToVINSERTH(SVOp, DAG))) 8764 return NewISDNode; 8765 8766 if ((NewISDNode = lowerToVINSERTB(SVOp, DAG))) 8767 return NewISDNode; 8768 } 8769 8770 if (Subtarget.hasVSX() && 8771 PPC::isXXSLDWIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) { 8772 if (Swap) 8773 std::swap(V1, V2); 8774 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 8775 SDValue Conv2 = 8776 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2.isUndef() ? V1 : V2); 8777 8778 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv1, Conv2, 8779 DAG.getConstant(ShiftElts, dl, MVT::i32)); 8780 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Shl); 8781 } 8782 8783 if (Subtarget.hasVSX() && 8784 PPC::isXXPERMDIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) { 8785 if (Swap) 8786 std::swap(V1, V2); 8787 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1); 8788 SDValue Conv2 = 8789 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2.isUndef() ? V1 : V2); 8790 8791 SDValue PermDI = DAG.getNode(PPCISD::XXPERMDI, dl, MVT::v2i64, Conv1, Conv2, 8792 DAG.getConstant(ShiftElts, dl, MVT::i32)); 8793 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, PermDI); 8794 } 8795 8796 if (Subtarget.hasP9Vector()) { 8797 if (PPC::isXXBRHShuffleMask(SVOp)) { 8798 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1); 8799 SDValue ReveHWord = DAG.getNode(PPCISD::XXREVERSE, dl, MVT::v8i16, Conv); 8800 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveHWord); 8801 } else if (PPC::isXXBRWShuffleMask(SVOp)) { 8802 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 8803 SDValue ReveWord = DAG.getNode(PPCISD::XXREVERSE, dl, MVT::v4i32, Conv); 8804 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveWord); 8805 } else if (PPC::isXXBRDShuffleMask(SVOp)) { 8806 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1); 8807 SDValue ReveDWord = DAG.getNode(PPCISD::XXREVERSE, dl, MVT::v2i64, Conv); 8808 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveDWord); 8809 } else if (PPC::isXXBRQShuffleMask(SVOp)) { 8810 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, V1); 8811 SDValue ReveQWord = DAG.getNode(PPCISD::XXREVERSE, dl, MVT::v1i128, Conv); 8812 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveQWord); 8813 } 8814 } 8815 8816 if (Subtarget.hasVSX()) { 8817 if (V2.isUndef() && PPC::isSplatShuffleMask(SVOp, 4)) { 8818 int SplatIdx = PPC::getVSPLTImmediate(SVOp, 4, DAG); 8819 8820 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 8821 SDValue Splat = DAG.getNode(PPCISD::XXSPLT, dl, MVT::v4i32, Conv, 8822 DAG.getConstant(SplatIdx, dl, MVT::i32)); 8823 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Splat); 8824 } 8825 8826 // Left shifts of 8 bytes are actually swaps. Convert accordingly. 8827 if (V2.isUndef() && PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) == 8) { 8828 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1); 8829 SDValue Swap = DAG.getNode(PPCISD::SWAP_NO_CHAIN, dl, MVT::v2f64, Conv); 8830 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Swap); 8831 } 8832 } 8833 8834 if (Subtarget.hasQPX()) { 8835 if (VT.getVectorNumElements() != 4) 8836 return SDValue(); 8837 8838 if (V2.isUndef()) V2 = V1; 8839 8840 int AlignIdx = PPC::isQVALIGNIShuffleMask(SVOp); 8841 if (AlignIdx != -1) { 8842 return DAG.getNode(PPCISD::QVALIGNI, dl, VT, V1, V2, 8843 DAG.getConstant(AlignIdx, dl, MVT::i32)); 8844 } else if (SVOp->isSplat()) { 8845 int SplatIdx = SVOp->getSplatIndex(); 8846 if (SplatIdx >= 4) { 8847 std::swap(V1, V2); 8848 SplatIdx -= 4; 8849 } 8850 8851 return DAG.getNode(PPCISD::QVESPLATI, dl, VT, V1, 8852 DAG.getConstant(SplatIdx, dl, MVT::i32)); 8853 } 8854 8855 // Lower this into a qvgpci/qvfperm pair. 8856 8857 // Compute the qvgpci literal 8858 unsigned idx = 0; 8859 for (unsigned i = 0; i < 4; ++i) { 8860 int m = SVOp->getMaskElt(i); 8861 unsigned mm = m >= 0 ? (unsigned) m : i; 8862 idx |= mm << (3-i)*3; 8863 } 8864 8865 SDValue V3 = DAG.getNode(PPCISD::QVGPCI, dl, MVT::v4f64, 8866 DAG.getConstant(idx, dl, MVT::i32)); 8867 return DAG.getNode(PPCISD::QVFPERM, dl, VT, V1, V2, V3); 8868 } 8869 8870 // Cases that are handled by instructions that take permute immediates 8871 // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be 8872 // selected by the instruction selector. 8873 if (V2.isUndef()) { 8874 if (PPC::isSplatShuffleMask(SVOp, 1) || 8875 PPC::isSplatShuffleMask(SVOp, 2) || 8876 PPC::isSplatShuffleMask(SVOp, 4) || 8877 PPC::isVPKUWUMShuffleMask(SVOp, 1, DAG) || 8878 PPC::isVPKUHUMShuffleMask(SVOp, 1, DAG) || 8879 PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) != -1 || 8880 PPC::isVMRGLShuffleMask(SVOp, 1, 1, DAG) || 8881 PPC::isVMRGLShuffleMask(SVOp, 2, 1, DAG) || 8882 PPC::isVMRGLShuffleMask(SVOp, 4, 1, DAG) || 8883 PPC::isVMRGHShuffleMask(SVOp, 1, 1, DAG) || 8884 PPC::isVMRGHShuffleMask(SVOp, 2, 1, DAG) || 8885 PPC::isVMRGHShuffleMask(SVOp, 4, 1, DAG) || 8886 (Subtarget.hasP8Altivec() && ( 8887 PPC::isVPKUDUMShuffleMask(SVOp, 1, DAG) || 8888 PPC::isVMRGEOShuffleMask(SVOp, true, 1, DAG) || 8889 PPC::isVMRGEOShuffleMask(SVOp, false, 1, DAG)))) { 8890 return Op; 8891 } 8892 } 8893 8894 // Altivec has a variety of "shuffle immediates" that take two vector inputs 8895 // and produce a fixed permutation. If any of these match, do not lower to 8896 // VPERM. 8897 unsigned int ShuffleKind = isLittleEndian ? 2 : 0; 8898 if (PPC::isVPKUWUMShuffleMask(SVOp, ShuffleKind, DAG) || 8899 PPC::isVPKUHUMShuffleMask(SVOp, ShuffleKind, DAG) || 8900 PPC::isVSLDOIShuffleMask(SVOp, ShuffleKind, DAG) != -1 || 8901 PPC::isVMRGLShuffleMask(SVOp, 1, ShuffleKind, DAG) || 8902 PPC::isVMRGLShuffleMask(SVOp, 2, ShuffleKind, DAG) || 8903 PPC::isVMRGLShuffleMask(SVOp, 4, ShuffleKind, DAG) || 8904 PPC::isVMRGHShuffleMask(SVOp, 1, ShuffleKind, DAG) || 8905 PPC::isVMRGHShuffleMask(SVOp, 2, ShuffleKind, DAG) || 8906 PPC::isVMRGHShuffleMask(SVOp, 4, ShuffleKind, DAG) || 8907 (Subtarget.hasP8Altivec() && ( 8908 PPC::isVPKUDUMShuffleMask(SVOp, ShuffleKind, DAG) || 8909 PPC::isVMRGEOShuffleMask(SVOp, true, ShuffleKind, DAG) || 8910 PPC::isVMRGEOShuffleMask(SVOp, false, ShuffleKind, DAG)))) 8911 return Op; 8912 8913 // Check to see if this is a shuffle of 4-byte values. If so, we can use our 8914 // perfect shuffle table to emit an optimal matching sequence. 8915 ArrayRef<int> PermMask = SVOp->getMask(); 8916 8917 unsigned PFIndexes[4]; 8918 bool isFourElementShuffle = true; 8919 for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number 8920 unsigned EltNo = 8; // Start out undef. 8921 for (unsigned j = 0; j != 4; ++j) { // Intra-element byte. 8922 if (PermMask[i*4+j] < 0) 8923 continue; // Undef, ignore it. 8924 8925 unsigned ByteSource = PermMask[i*4+j]; 8926 if ((ByteSource & 3) != j) { 8927 isFourElementShuffle = false; 8928 break; 8929 } 8930 8931 if (EltNo == 8) { 8932 EltNo = ByteSource/4; 8933 } else if (EltNo != ByteSource/4) { 8934 isFourElementShuffle = false; 8935 break; 8936 } 8937 } 8938 PFIndexes[i] = EltNo; 8939 } 8940 8941 // If this shuffle can be expressed as a shuffle of 4-byte elements, use the 8942 // perfect shuffle vector to determine if it is cost effective to do this as 8943 // discrete instructions, or whether we should use a vperm. 8944 // For now, we skip this for little endian until such time as we have a 8945 // little-endian perfect shuffle table. 8946 if (isFourElementShuffle && !isLittleEndian) { 8947 // Compute the index in the perfect shuffle table. 8948 unsigned PFTableIndex = 8949 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3]; 8950 8951 unsigned PFEntry = PerfectShuffleTable[PFTableIndex]; 8952 unsigned Cost = (PFEntry >> 30); 8953 8954 // Determining when to avoid vperm is tricky. Many things affect the cost 8955 // of vperm, particularly how many times the perm mask needs to be computed. 8956 // For example, if the perm mask can be hoisted out of a loop or is already 8957 // used (perhaps because there are multiple permutes with the same shuffle 8958 // mask?) the vperm has a cost of 1. OTOH, hoisting the permute mask out of 8959 // the loop requires an extra register. 8960 // 8961 // As a compromise, we only emit discrete instructions if the shuffle can be 8962 // generated in 3 or fewer operations. When we have loop information 8963 // available, if this block is within a loop, we should avoid using vperm 8964 // for 3-operation perms and use a constant pool load instead. 8965 if (Cost < 3) 8966 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl); 8967 } 8968 8969 // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant 8970 // vector that will get spilled to the constant pool. 8971 if (V2.isUndef()) V2 = V1; 8972 8973 // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except 8974 // that it is in input element units, not in bytes. Convert now. 8975 8976 // For little endian, the order of the input vectors is reversed, and 8977 // the permutation mask is complemented with respect to 31. This is 8978 // necessary to produce proper semantics with the big-endian-biased vperm 8979 // instruction. 8980 EVT EltVT = V1.getValueType().getVectorElementType(); 8981 unsigned BytesPerElement = EltVT.getSizeInBits()/8; 8982 8983 SmallVector<SDValue, 16> ResultMask; 8984 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) { 8985 unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i]; 8986 8987 for (unsigned j = 0; j != BytesPerElement; ++j) 8988 if (isLittleEndian) 8989 ResultMask.push_back(DAG.getConstant(31 - (SrcElt*BytesPerElement + j), 8990 dl, MVT::i32)); 8991 else 8992 ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement + j, dl, 8993 MVT::i32)); 8994 } 8995 8996 SDValue VPermMask = DAG.getBuildVector(MVT::v16i8, dl, ResultMask); 8997 if (isLittleEndian) 8998 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(), 8999 V2, V1, VPermMask); 9000 else 9001 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(), 9002 V1, V2, VPermMask); 9003 } 9004 9005 /// getVectorCompareInfo - Given an intrinsic, return false if it is not a 9006 /// vector comparison. If it is, return true and fill in Opc/isDot with 9007 /// information about the intrinsic. 9008 static bool getVectorCompareInfo(SDValue Intrin, int &CompareOpc, 9009 bool &isDot, const PPCSubtarget &Subtarget) { 9010 unsigned IntrinsicID = 9011 cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue(); 9012 CompareOpc = -1; 9013 isDot = false; 9014 switch (IntrinsicID) { 9015 default: 9016 return false; 9017 // Comparison predicates. 9018 case Intrinsic::ppc_altivec_vcmpbfp_p: 9019 CompareOpc = 966; 9020 isDot = true; 9021 break; 9022 case Intrinsic::ppc_altivec_vcmpeqfp_p: 9023 CompareOpc = 198; 9024 isDot = true; 9025 break; 9026 case Intrinsic::ppc_altivec_vcmpequb_p: 9027 CompareOpc = 6; 9028 isDot = true; 9029 break; 9030 case Intrinsic::ppc_altivec_vcmpequh_p: 9031 CompareOpc = 70; 9032 isDot = true; 9033 break; 9034 case Intrinsic::ppc_altivec_vcmpequw_p: 9035 CompareOpc = 134; 9036 isDot = true; 9037 break; 9038 case Intrinsic::ppc_altivec_vcmpequd_p: 9039 if (Subtarget.hasP8Altivec()) { 9040 CompareOpc = 199; 9041 isDot = true; 9042 } else 9043 return false; 9044 break; 9045 case Intrinsic::ppc_altivec_vcmpneb_p: 9046 case Intrinsic::ppc_altivec_vcmpneh_p: 9047 case Intrinsic::ppc_altivec_vcmpnew_p: 9048 case Intrinsic::ppc_altivec_vcmpnezb_p: 9049 case Intrinsic::ppc_altivec_vcmpnezh_p: 9050 case Intrinsic::ppc_altivec_vcmpnezw_p: 9051 if (Subtarget.hasP9Altivec()) { 9052 switch (IntrinsicID) { 9053 default: 9054 llvm_unreachable("Unknown comparison intrinsic."); 9055 case Intrinsic::ppc_altivec_vcmpneb_p: 9056 CompareOpc = 7; 9057 break; 9058 case Intrinsic::ppc_altivec_vcmpneh_p: 9059 CompareOpc = 71; 9060 break; 9061 case Intrinsic::ppc_altivec_vcmpnew_p: 9062 CompareOpc = 135; 9063 break; 9064 case Intrinsic::ppc_altivec_vcmpnezb_p: 9065 CompareOpc = 263; 9066 break; 9067 case Intrinsic::ppc_altivec_vcmpnezh_p: 9068 CompareOpc = 327; 9069 break; 9070 case Intrinsic::ppc_altivec_vcmpnezw_p: 9071 CompareOpc = 391; 9072 break; 9073 } 9074 isDot = true; 9075 } else 9076 return false; 9077 break; 9078 case Intrinsic::ppc_altivec_vcmpgefp_p: 9079 CompareOpc = 454; 9080 isDot = true; 9081 break; 9082 case Intrinsic::ppc_altivec_vcmpgtfp_p: 9083 CompareOpc = 710; 9084 isDot = true; 9085 break; 9086 case Intrinsic::ppc_altivec_vcmpgtsb_p: 9087 CompareOpc = 774; 9088 isDot = true; 9089 break; 9090 case Intrinsic::ppc_altivec_vcmpgtsh_p: 9091 CompareOpc = 838; 9092 isDot = true; 9093 break; 9094 case Intrinsic::ppc_altivec_vcmpgtsw_p: 9095 CompareOpc = 902; 9096 isDot = true; 9097 break; 9098 case Intrinsic::ppc_altivec_vcmpgtsd_p: 9099 if (Subtarget.hasP8Altivec()) { 9100 CompareOpc = 967; 9101 isDot = true; 9102 } else 9103 return false; 9104 break; 9105 case Intrinsic::ppc_altivec_vcmpgtub_p: 9106 CompareOpc = 518; 9107 isDot = true; 9108 break; 9109 case Intrinsic::ppc_altivec_vcmpgtuh_p: 9110 CompareOpc = 582; 9111 isDot = true; 9112 break; 9113 case Intrinsic::ppc_altivec_vcmpgtuw_p: 9114 CompareOpc = 646; 9115 isDot = true; 9116 break; 9117 case Intrinsic::ppc_altivec_vcmpgtud_p: 9118 if (Subtarget.hasP8Altivec()) { 9119 CompareOpc = 711; 9120 isDot = true; 9121 } else 9122 return false; 9123 break; 9124 9125 // VSX predicate comparisons use the same infrastructure 9126 case Intrinsic::ppc_vsx_xvcmpeqdp_p: 9127 case Intrinsic::ppc_vsx_xvcmpgedp_p: 9128 case Intrinsic::ppc_vsx_xvcmpgtdp_p: 9129 case Intrinsic::ppc_vsx_xvcmpeqsp_p: 9130 case Intrinsic::ppc_vsx_xvcmpgesp_p: 9131 case Intrinsic::ppc_vsx_xvcmpgtsp_p: 9132 if (Subtarget.hasVSX()) { 9133 switch (IntrinsicID) { 9134 case Intrinsic::ppc_vsx_xvcmpeqdp_p: 9135 CompareOpc = 99; 9136 break; 9137 case Intrinsic::ppc_vsx_xvcmpgedp_p: 9138 CompareOpc = 115; 9139 break; 9140 case Intrinsic::ppc_vsx_xvcmpgtdp_p: 9141 CompareOpc = 107; 9142 break; 9143 case Intrinsic::ppc_vsx_xvcmpeqsp_p: 9144 CompareOpc = 67; 9145 break; 9146 case Intrinsic::ppc_vsx_xvcmpgesp_p: 9147 CompareOpc = 83; 9148 break; 9149 case Intrinsic::ppc_vsx_xvcmpgtsp_p: 9150 CompareOpc = 75; 9151 break; 9152 } 9153 isDot = true; 9154 } else 9155 return false; 9156 break; 9157 9158 // Normal Comparisons. 9159 case Intrinsic::ppc_altivec_vcmpbfp: 9160 CompareOpc = 966; 9161 break; 9162 case Intrinsic::ppc_altivec_vcmpeqfp: 9163 CompareOpc = 198; 9164 break; 9165 case Intrinsic::ppc_altivec_vcmpequb: 9166 CompareOpc = 6; 9167 break; 9168 case Intrinsic::ppc_altivec_vcmpequh: 9169 CompareOpc = 70; 9170 break; 9171 case Intrinsic::ppc_altivec_vcmpequw: 9172 CompareOpc = 134; 9173 break; 9174 case Intrinsic::ppc_altivec_vcmpequd: 9175 if (Subtarget.hasP8Altivec()) 9176 CompareOpc = 199; 9177 else 9178 return false; 9179 break; 9180 case Intrinsic::ppc_altivec_vcmpneb: 9181 case Intrinsic::ppc_altivec_vcmpneh: 9182 case Intrinsic::ppc_altivec_vcmpnew: 9183 case Intrinsic::ppc_altivec_vcmpnezb: 9184 case Intrinsic::ppc_altivec_vcmpnezh: 9185 case Intrinsic::ppc_altivec_vcmpnezw: 9186 if (Subtarget.hasP9Altivec()) 9187 switch (IntrinsicID) { 9188 default: 9189 llvm_unreachable("Unknown comparison intrinsic."); 9190 case Intrinsic::ppc_altivec_vcmpneb: 9191 CompareOpc = 7; 9192 break; 9193 case Intrinsic::ppc_altivec_vcmpneh: 9194 CompareOpc = 71; 9195 break; 9196 case Intrinsic::ppc_altivec_vcmpnew: 9197 CompareOpc = 135; 9198 break; 9199 case Intrinsic::ppc_altivec_vcmpnezb: 9200 CompareOpc = 263; 9201 break; 9202 case Intrinsic::ppc_altivec_vcmpnezh: 9203 CompareOpc = 327; 9204 break; 9205 case Intrinsic::ppc_altivec_vcmpnezw: 9206 CompareOpc = 391; 9207 break; 9208 } 9209 else 9210 return false; 9211 break; 9212 case Intrinsic::ppc_altivec_vcmpgefp: 9213 CompareOpc = 454; 9214 break; 9215 case Intrinsic::ppc_altivec_vcmpgtfp: 9216 CompareOpc = 710; 9217 break; 9218 case Intrinsic::ppc_altivec_vcmpgtsb: 9219 CompareOpc = 774; 9220 break; 9221 case Intrinsic::ppc_altivec_vcmpgtsh: 9222 CompareOpc = 838; 9223 break; 9224 case Intrinsic::ppc_altivec_vcmpgtsw: 9225 CompareOpc = 902; 9226 break; 9227 case Intrinsic::ppc_altivec_vcmpgtsd: 9228 if (Subtarget.hasP8Altivec()) 9229 CompareOpc = 967; 9230 else 9231 return false; 9232 break; 9233 case Intrinsic::ppc_altivec_vcmpgtub: 9234 CompareOpc = 518; 9235 break; 9236 case Intrinsic::ppc_altivec_vcmpgtuh: 9237 CompareOpc = 582; 9238 break; 9239 case Intrinsic::ppc_altivec_vcmpgtuw: 9240 CompareOpc = 646; 9241 break; 9242 case Intrinsic::ppc_altivec_vcmpgtud: 9243 if (Subtarget.hasP8Altivec()) 9244 CompareOpc = 711; 9245 else 9246 return false; 9247 break; 9248 } 9249 return true; 9250 } 9251 9252 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom 9253 /// lower, do it, otherwise return null. 9254 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 9255 SelectionDAG &DAG) const { 9256 unsigned IntrinsicID = 9257 cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 9258 9259 SDLoc dl(Op); 9260 9261 if (IntrinsicID == Intrinsic::thread_pointer) { 9262 // Reads the thread pointer register, used for __builtin_thread_pointer. 9263 if (Subtarget.isPPC64()) 9264 return DAG.getRegister(PPC::X13, MVT::i64); 9265 return DAG.getRegister(PPC::R2, MVT::i32); 9266 } 9267 9268 // If this is a lowered altivec predicate compare, CompareOpc is set to the 9269 // opcode number of the comparison. 9270 int CompareOpc; 9271 bool isDot; 9272 if (!getVectorCompareInfo(Op, CompareOpc, isDot, Subtarget)) 9273 return SDValue(); // Don't custom lower most intrinsics. 9274 9275 // If this is a non-dot comparison, make the VCMP node and we are done. 9276 if (!isDot) { 9277 SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(), 9278 Op.getOperand(1), Op.getOperand(2), 9279 DAG.getConstant(CompareOpc, dl, MVT::i32)); 9280 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp); 9281 } 9282 9283 // Create the PPCISD altivec 'dot' comparison node. 9284 SDValue Ops[] = { 9285 Op.getOperand(2), // LHS 9286 Op.getOperand(3), // RHS 9287 DAG.getConstant(CompareOpc, dl, MVT::i32) 9288 }; 9289 EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue }; 9290 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops); 9291 9292 // Now that we have the comparison, emit a copy from the CR to a GPR. 9293 // This is flagged to the above dot comparison. 9294 SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32, 9295 DAG.getRegister(PPC::CR6, MVT::i32), 9296 CompNode.getValue(1)); 9297 9298 // Unpack the result based on how the target uses it. 9299 unsigned BitNo; // Bit # of CR6. 9300 bool InvertBit; // Invert result? 9301 switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) { 9302 default: // Can't happen, don't crash on invalid number though. 9303 case 0: // Return the value of the EQ bit of CR6. 9304 BitNo = 0; InvertBit = false; 9305 break; 9306 case 1: // Return the inverted value of the EQ bit of CR6. 9307 BitNo = 0; InvertBit = true; 9308 break; 9309 case 2: // Return the value of the LT bit of CR6. 9310 BitNo = 2; InvertBit = false; 9311 break; 9312 case 3: // Return the inverted value of the LT bit of CR6. 9313 BitNo = 2; InvertBit = true; 9314 break; 9315 } 9316 9317 // Shift the bit into the low position. 9318 Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags, 9319 DAG.getConstant(8 - (3 - BitNo), dl, MVT::i32)); 9320 // Isolate the bit. 9321 Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags, 9322 DAG.getConstant(1, dl, MVT::i32)); 9323 9324 // If we are supposed to, toggle the bit. 9325 if (InvertBit) 9326 Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags, 9327 DAG.getConstant(1, dl, MVT::i32)); 9328 return Flags; 9329 } 9330 9331 SDValue PPCTargetLowering::LowerINTRINSIC_VOID(SDValue Op, 9332 SelectionDAG &DAG) const { 9333 // SelectionDAGBuilder::visitTargetIntrinsic may insert one extra chain to 9334 // the beginning of the argument list. 9335 int ArgStart = isa<ConstantSDNode>(Op.getOperand(0)) ? 0 : 1; 9336 SDLoc DL(Op); 9337 switch (cast<ConstantSDNode>(Op.getOperand(ArgStart))->getZExtValue()) { 9338 case Intrinsic::ppc_cfence: { 9339 assert(ArgStart == 1 && "llvm.ppc.cfence must carry a chain argument."); 9340 assert(Subtarget.isPPC64() && "Only 64-bit is supported for now."); 9341 return SDValue(DAG.getMachineNode(PPC::CFENCE8, DL, MVT::Other, 9342 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, 9343 Op.getOperand(ArgStart + 1)), 9344 Op.getOperand(0)), 9345 0); 9346 } 9347 default: 9348 break; 9349 } 9350 return SDValue(); 9351 } 9352 9353 SDValue PPCTargetLowering::LowerREM(SDValue Op, SelectionDAG &DAG) const { 9354 // Check for a DIV with the same operands as this REM. 9355 for (auto UI : Op.getOperand(1)->uses()) { 9356 if ((Op.getOpcode() == ISD::SREM && UI->getOpcode() == ISD::SDIV) || 9357 (Op.getOpcode() == ISD::UREM && UI->getOpcode() == ISD::UDIV)) 9358 if (UI->getOperand(0) == Op.getOperand(0) && 9359 UI->getOperand(1) == Op.getOperand(1)) 9360 return SDValue(); 9361 } 9362 return Op; 9363 } 9364 9365 // Lower scalar BSWAP64 to xxbrd. 9366 SDValue PPCTargetLowering::LowerBSWAP(SDValue Op, SelectionDAG &DAG) const { 9367 SDLoc dl(Op); 9368 // MTVSRDD 9369 Op = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i64, Op.getOperand(0), 9370 Op.getOperand(0)); 9371 // XXBRD 9372 Op = DAG.getNode(PPCISD::XXREVERSE, dl, MVT::v2i64, Op); 9373 // MFVSRD 9374 int VectorIndex = 0; 9375 if (Subtarget.isLittleEndian()) 9376 VectorIndex = 1; 9377 Op = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Op, 9378 DAG.getTargetConstant(VectorIndex, dl, MVT::i32)); 9379 return Op; 9380 } 9381 9382 // ATOMIC_CMP_SWAP for i8/i16 needs to zero-extend its input since it will be 9383 // compared to a value that is atomically loaded (atomic loads zero-extend). 9384 SDValue PPCTargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, 9385 SelectionDAG &DAG) const { 9386 assert(Op.getOpcode() == ISD::ATOMIC_CMP_SWAP && 9387 "Expecting an atomic compare-and-swap here."); 9388 SDLoc dl(Op); 9389 auto *AtomicNode = cast<AtomicSDNode>(Op.getNode()); 9390 EVT MemVT = AtomicNode->getMemoryVT(); 9391 if (MemVT.getSizeInBits() >= 32) 9392 return Op; 9393 9394 SDValue CmpOp = Op.getOperand(2); 9395 // If this is already correctly zero-extended, leave it alone. 9396 auto HighBits = APInt::getHighBitsSet(32, 32 - MemVT.getSizeInBits()); 9397 if (DAG.MaskedValueIsZero(CmpOp, HighBits)) 9398 return Op; 9399 9400 // Clear the high bits of the compare operand. 9401 unsigned MaskVal = (1 << MemVT.getSizeInBits()) - 1; 9402 SDValue NewCmpOp = 9403 DAG.getNode(ISD::AND, dl, MVT::i32, CmpOp, 9404 DAG.getConstant(MaskVal, dl, MVT::i32)); 9405 9406 // Replace the existing compare operand with the properly zero-extended one. 9407 SmallVector<SDValue, 4> Ops; 9408 for (int i = 0, e = AtomicNode->getNumOperands(); i < e; i++) 9409 Ops.push_back(AtomicNode->getOperand(i)); 9410 Ops[2] = NewCmpOp; 9411 MachineMemOperand *MMO = AtomicNode->getMemOperand(); 9412 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::Other); 9413 auto NodeTy = 9414 (MemVT == MVT::i8) ? PPCISD::ATOMIC_CMP_SWAP_8 : PPCISD::ATOMIC_CMP_SWAP_16; 9415 return DAG.getMemIntrinsicNode(NodeTy, dl, Tys, Ops, MemVT, MMO); 9416 } 9417 9418 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, 9419 SelectionDAG &DAG) const { 9420 SDLoc dl(Op); 9421 // Create a stack slot that is 16-byte aligned. 9422 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 9423 int FrameIdx = MFI.CreateStackObject(16, 16, false); 9424 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 9425 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 9426 9427 // Store the input value into Value#0 of the stack slot. 9428 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx, 9429 MachinePointerInfo()); 9430 // Load it out. 9431 return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo()); 9432 } 9433 9434 SDValue PPCTargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, 9435 SelectionDAG &DAG) const { 9436 assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && 9437 "Should only be called for ISD::INSERT_VECTOR_ELT"); 9438 9439 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(2)); 9440 // We have legal lowering for constant indices but not for variable ones. 9441 if (!C) 9442 return SDValue(); 9443 9444 EVT VT = Op.getValueType(); 9445 SDLoc dl(Op); 9446 SDValue V1 = Op.getOperand(0); 9447 SDValue V2 = Op.getOperand(1); 9448 // We can use MTVSRZ + VECINSERT for v8i16 and v16i8 types. 9449 if (VT == MVT::v8i16 || VT == MVT::v16i8) { 9450 SDValue Mtvsrz = DAG.getNode(PPCISD::MTVSRZ, dl, VT, V2); 9451 unsigned BytesInEachElement = VT.getVectorElementType().getSizeInBits() / 8; 9452 unsigned InsertAtElement = C->getZExtValue(); 9453 unsigned InsertAtByte = InsertAtElement * BytesInEachElement; 9454 if (Subtarget.isLittleEndian()) { 9455 InsertAtByte = (16 - BytesInEachElement) - InsertAtByte; 9456 } 9457 return DAG.getNode(PPCISD::VECINSERT, dl, VT, V1, Mtvsrz, 9458 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9459 } 9460 return Op; 9461 } 9462 9463 SDValue PPCTargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op, 9464 SelectionDAG &DAG) const { 9465 SDLoc dl(Op); 9466 SDNode *N = Op.getNode(); 9467 9468 assert(N->getOperand(0).getValueType() == MVT::v4i1 && 9469 "Unknown extract_vector_elt type"); 9470 9471 SDValue Value = N->getOperand(0); 9472 9473 // The first part of this is like the store lowering except that we don't 9474 // need to track the chain. 9475 9476 // The values are now known to be -1 (false) or 1 (true). To convert this 9477 // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5). 9478 // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5 9479 Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value); 9480 9481 // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to 9482 // understand how to form the extending load. 9483 SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64); 9484 9485 Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs); 9486 9487 // Now convert to an integer and store. 9488 Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64, 9489 DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32), 9490 Value); 9491 9492 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 9493 int FrameIdx = MFI.CreateStackObject(16, 16, false); 9494 MachinePointerInfo PtrInfo = 9495 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 9496 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 9497 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 9498 9499 SDValue StoreChain = DAG.getEntryNode(); 9500 SDValue Ops[] = {StoreChain, 9501 DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32), 9502 Value, FIdx}; 9503 SDVTList VTs = DAG.getVTList(/*chain*/ MVT::Other); 9504 9505 StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, 9506 dl, VTs, Ops, MVT::v4i32, PtrInfo); 9507 9508 // Extract the value requested. 9509 unsigned Offset = 4*cast<ConstantSDNode>(N->getOperand(1))->getZExtValue(); 9510 SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType()); 9511 Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx); 9512 9513 SDValue IntVal = 9514 DAG.getLoad(MVT::i32, dl, StoreChain, Idx, PtrInfo.getWithOffset(Offset)); 9515 9516 if (!Subtarget.useCRBits()) 9517 return IntVal; 9518 9519 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, IntVal); 9520 } 9521 9522 /// Lowering for QPX v4i1 loads 9523 SDValue PPCTargetLowering::LowerVectorLoad(SDValue Op, 9524 SelectionDAG &DAG) const { 9525 SDLoc dl(Op); 9526 LoadSDNode *LN = cast<LoadSDNode>(Op.getNode()); 9527 SDValue LoadChain = LN->getChain(); 9528 SDValue BasePtr = LN->getBasePtr(); 9529 9530 if (Op.getValueType() == MVT::v4f64 || 9531 Op.getValueType() == MVT::v4f32) { 9532 EVT MemVT = LN->getMemoryVT(); 9533 unsigned Alignment = LN->getAlignment(); 9534 9535 // If this load is properly aligned, then it is legal. 9536 if (Alignment >= MemVT.getStoreSize()) 9537 return Op; 9538 9539 EVT ScalarVT = Op.getValueType().getScalarType(), 9540 ScalarMemVT = MemVT.getScalarType(); 9541 unsigned Stride = ScalarMemVT.getStoreSize(); 9542 9543 SDValue Vals[4], LoadChains[4]; 9544 for (unsigned Idx = 0; Idx < 4; ++Idx) { 9545 SDValue Load; 9546 if (ScalarVT != ScalarMemVT) 9547 Load = DAG.getExtLoad(LN->getExtensionType(), dl, ScalarVT, LoadChain, 9548 BasePtr, 9549 LN->getPointerInfo().getWithOffset(Idx * Stride), 9550 ScalarMemVT, MinAlign(Alignment, Idx * Stride), 9551 LN->getMemOperand()->getFlags(), LN->getAAInfo()); 9552 else 9553 Load = DAG.getLoad(ScalarVT, dl, LoadChain, BasePtr, 9554 LN->getPointerInfo().getWithOffset(Idx * Stride), 9555 MinAlign(Alignment, Idx * Stride), 9556 LN->getMemOperand()->getFlags(), LN->getAAInfo()); 9557 9558 if (Idx == 0 && LN->isIndexed()) { 9559 assert(LN->getAddressingMode() == ISD::PRE_INC && 9560 "Unknown addressing mode on vector load"); 9561 Load = DAG.getIndexedLoad(Load, dl, BasePtr, LN->getOffset(), 9562 LN->getAddressingMode()); 9563 } 9564 9565 Vals[Idx] = Load; 9566 LoadChains[Idx] = Load.getValue(1); 9567 9568 BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, 9569 DAG.getConstant(Stride, dl, 9570 BasePtr.getValueType())); 9571 } 9572 9573 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains); 9574 SDValue Value = DAG.getBuildVector(Op.getValueType(), dl, Vals); 9575 9576 if (LN->isIndexed()) { 9577 SDValue RetOps[] = { Value, Vals[0].getValue(1), TF }; 9578 return DAG.getMergeValues(RetOps, dl); 9579 } 9580 9581 SDValue RetOps[] = { Value, TF }; 9582 return DAG.getMergeValues(RetOps, dl); 9583 } 9584 9585 assert(Op.getValueType() == MVT::v4i1 && "Unknown load to lower"); 9586 assert(LN->isUnindexed() && "Indexed v4i1 loads are not supported"); 9587 9588 // To lower v4i1 from a byte array, we load the byte elements of the 9589 // vector and then reuse the BUILD_VECTOR logic. 9590 9591 SDValue VectElmts[4], VectElmtChains[4]; 9592 for (unsigned i = 0; i < 4; ++i) { 9593 SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType()); 9594 Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx); 9595 9596 VectElmts[i] = DAG.getExtLoad( 9597 ISD::EXTLOAD, dl, MVT::i32, LoadChain, Idx, 9598 LN->getPointerInfo().getWithOffset(i), MVT::i8, 9599 /* Alignment = */ 1, LN->getMemOperand()->getFlags(), LN->getAAInfo()); 9600 VectElmtChains[i] = VectElmts[i].getValue(1); 9601 } 9602 9603 LoadChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, VectElmtChains); 9604 SDValue Value = DAG.getBuildVector(MVT::v4i1, dl, VectElmts); 9605 9606 SDValue RVals[] = { Value, LoadChain }; 9607 return DAG.getMergeValues(RVals, dl); 9608 } 9609 9610 /// Lowering for QPX v4i1 stores 9611 SDValue PPCTargetLowering::LowerVectorStore(SDValue Op, 9612 SelectionDAG &DAG) const { 9613 SDLoc dl(Op); 9614 StoreSDNode *SN = cast<StoreSDNode>(Op.getNode()); 9615 SDValue StoreChain = SN->getChain(); 9616 SDValue BasePtr = SN->getBasePtr(); 9617 SDValue Value = SN->getValue(); 9618 9619 if (Value.getValueType() == MVT::v4f64 || 9620 Value.getValueType() == MVT::v4f32) { 9621 EVT MemVT = SN->getMemoryVT(); 9622 unsigned Alignment = SN->getAlignment(); 9623 9624 // If this store is properly aligned, then it is legal. 9625 if (Alignment >= MemVT.getStoreSize()) 9626 return Op; 9627 9628 EVT ScalarVT = Value.getValueType().getScalarType(), 9629 ScalarMemVT = MemVT.getScalarType(); 9630 unsigned Stride = ScalarMemVT.getStoreSize(); 9631 9632 SDValue Stores[4]; 9633 for (unsigned Idx = 0; Idx < 4; ++Idx) { 9634 SDValue Ex = DAG.getNode( 9635 ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, Value, 9636 DAG.getConstant(Idx, dl, getVectorIdxTy(DAG.getDataLayout()))); 9637 SDValue Store; 9638 if (ScalarVT != ScalarMemVT) 9639 Store = 9640 DAG.getTruncStore(StoreChain, dl, Ex, BasePtr, 9641 SN->getPointerInfo().getWithOffset(Idx * Stride), 9642 ScalarMemVT, MinAlign(Alignment, Idx * Stride), 9643 SN->getMemOperand()->getFlags(), SN->getAAInfo()); 9644 else 9645 Store = DAG.getStore(StoreChain, dl, Ex, BasePtr, 9646 SN->getPointerInfo().getWithOffset(Idx * Stride), 9647 MinAlign(Alignment, Idx * Stride), 9648 SN->getMemOperand()->getFlags(), SN->getAAInfo()); 9649 9650 if (Idx == 0 && SN->isIndexed()) { 9651 assert(SN->getAddressingMode() == ISD::PRE_INC && 9652 "Unknown addressing mode on vector store"); 9653 Store = DAG.getIndexedStore(Store, dl, BasePtr, SN->getOffset(), 9654 SN->getAddressingMode()); 9655 } 9656 9657 BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, 9658 DAG.getConstant(Stride, dl, 9659 BasePtr.getValueType())); 9660 Stores[Idx] = Store; 9661 } 9662 9663 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores); 9664 9665 if (SN->isIndexed()) { 9666 SDValue RetOps[] = { TF, Stores[0].getValue(1) }; 9667 return DAG.getMergeValues(RetOps, dl); 9668 } 9669 9670 return TF; 9671 } 9672 9673 assert(SN->isUnindexed() && "Indexed v4i1 stores are not supported"); 9674 assert(Value.getValueType() == MVT::v4i1 && "Unknown store to lower"); 9675 9676 // The values are now known to be -1 (false) or 1 (true). To convert this 9677 // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5). 9678 // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5 9679 Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value); 9680 9681 // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to 9682 // understand how to form the extending load. 9683 SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64); 9684 9685 Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs); 9686 9687 // Now convert to an integer and store. 9688 Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64, 9689 DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32), 9690 Value); 9691 9692 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 9693 int FrameIdx = MFI.CreateStackObject(16, 16, false); 9694 MachinePointerInfo PtrInfo = 9695 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 9696 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 9697 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 9698 9699 SDValue Ops[] = {StoreChain, 9700 DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32), 9701 Value, FIdx}; 9702 SDVTList VTs = DAG.getVTList(/*chain*/ MVT::Other); 9703 9704 StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, 9705 dl, VTs, Ops, MVT::v4i32, PtrInfo); 9706 9707 // Move data into the byte array. 9708 SDValue Loads[4], LoadChains[4]; 9709 for (unsigned i = 0; i < 4; ++i) { 9710 unsigned Offset = 4*i; 9711 SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType()); 9712 Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx); 9713 9714 Loads[i] = DAG.getLoad(MVT::i32, dl, StoreChain, Idx, 9715 PtrInfo.getWithOffset(Offset)); 9716 LoadChains[i] = Loads[i].getValue(1); 9717 } 9718 9719 StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains); 9720 9721 SDValue Stores[4]; 9722 for (unsigned i = 0; i < 4; ++i) { 9723 SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType()); 9724 Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx); 9725 9726 Stores[i] = DAG.getTruncStore( 9727 StoreChain, dl, Loads[i], Idx, SN->getPointerInfo().getWithOffset(i), 9728 MVT::i8, /* Alignment = */ 1, SN->getMemOperand()->getFlags(), 9729 SN->getAAInfo()); 9730 } 9731 9732 StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores); 9733 9734 return StoreChain; 9735 } 9736 9737 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const { 9738 SDLoc dl(Op); 9739 if (Op.getValueType() == MVT::v4i32) { 9740 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 9741 9742 SDValue Zero = BuildSplatI( 0, 1, MVT::v4i32, DAG, dl); 9743 SDValue Neg16 = BuildSplatI(-16, 4, MVT::v4i32, DAG, dl);//+16 as shift amt. 9744 9745 SDValue RHSSwap = // = vrlw RHS, 16 9746 BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl); 9747 9748 // Shrinkify inputs to v8i16. 9749 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS); 9750 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS); 9751 RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap); 9752 9753 // Low parts multiplied together, generating 32-bit results (we ignore the 9754 // top parts). 9755 SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh, 9756 LHS, RHS, DAG, dl, MVT::v4i32); 9757 9758 SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm, 9759 LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32); 9760 // Shift the high parts up 16 bits. 9761 HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd, 9762 Neg16, DAG, dl); 9763 return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd); 9764 } else if (Op.getValueType() == MVT::v8i16) { 9765 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 9766 9767 SDValue Zero = BuildSplatI(0, 1, MVT::v8i16, DAG, dl); 9768 9769 return BuildIntrinsicOp(Intrinsic::ppc_altivec_vmladduhm, 9770 LHS, RHS, Zero, DAG, dl); 9771 } else if (Op.getValueType() == MVT::v16i8) { 9772 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 9773 bool isLittleEndian = Subtarget.isLittleEndian(); 9774 9775 // Multiply the even 8-bit parts, producing 16-bit sums. 9776 SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub, 9777 LHS, RHS, DAG, dl, MVT::v8i16); 9778 EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts); 9779 9780 // Multiply the odd 8-bit parts, producing 16-bit sums. 9781 SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub, 9782 LHS, RHS, DAG, dl, MVT::v8i16); 9783 OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts); 9784 9785 // Merge the results together. Because vmuleub and vmuloub are 9786 // instructions with a big-endian bias, we must reverse the 9787 // element numbering and reverse the meaning of "odd" and "even" 9788 // when generating little endian code. 9789 int Ops[16]; 9790 for (unsigned i = 0; i != 8; ++i) { 9791 if (isLittleEndian) { 9792 Ops[i*2 ] = 2*i; 9793 Ops[i*2+1] = 2*i+16; 9794 } else { 9795 Ops[i*2 ] = 2*i+1; 9796 Ops[i*2+1] = 2*i+1+16; 9797 } 9798 } 9799 if (isLittleEndian) 9800 return DAG.getVectorShuffle(MVT::v16i8, dl, OddParts, EvenParts, Ops); 9801 else 9802 return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops); 9803 } else { 9804 llvm_unreachable("Unknown mul to lower!"); 9805 } 9806 } 9807 9808 SDValue PPCTargetLowering::LowerABS(SDValue Op, SelectionDAG &DAG) const { 9809 9810 assert(Op.getOpcode() == ISD::ABS && "Should only be called for ISD::ABS"); 9811 9812 EVT VT = Op.getValueType(); 9813 assert(VT.isVector() && 9814 "Only set vector abs as custom, scalar abs shouldn't reach here!"); 9815 assert((VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 || 9816 VT == MVT::v16i8) && 9817 "Unexpected vector element type!"); 9818 assert((VT != MVT::v2i64 || Subtarget.hasP8Altivec()) && 9819 "Current subtarget doesn't support smax v2i64!"); 9820 9821 // For vector abs, it can be lowered to: 9822 // abs x 9823 // ==> 9824 // y = -x 9825 // smax(x, y) 9826 9827 SDLoc dl(Op); 9828 SDValue X = Op.getOperand(0); 9829 SDValue Zero = DAG.getConstant(0, dl, VT); 9830 SDValue Y = DAG.getNode(ISD::SUB, dl, VT, Zero, X); 9831 9832 // SMAX patch https://reviews.llvm.org/D47332 9833 // hasn't landed yet, so use intrinsic first here. 9834 // TODO: Should use SMAX directly once SMAX patch landed 9835 Intrinsic::ID BifID = Intrinsic::ppc_altivec_vmaxsw; 9836 if (VT == MVT::v2i64) 9837 BifID = Intrinsic::ppc_altivec_vmaxsd; 9838 else if (VT == MVT::v8i16) 9839 BifID = Intrinsic::ppc_altivec_vmaxsh; 9840 else if (VT == MVT::v16i8) 9841 BifID = Intrinsic::ppc_altivec_vmaxsb; 9842 9843 return BuildIntrinsicOp(BifID, X, Y, DAG, dl, VT); 9844 } 9845 9846 // Custom lowering for fpext vf32 to v2f64 9847 SDValue PPCTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const { 9848 9849 assert(Op.getOpcode() == ISD::FP_EXTEND && 9850 "Should only be called for ISD::FP_EXTEND"); 9851 9852 // We only want to custom lower an extend from v2f32 to v2f64. 9853 if (Op.getValueType() != MVT::v2f64 || 9854 Op.getOperand(0).getValueType() != MVT::v2f32) 9855 return SDValue(); 9856 9857 SDLoc dl(Op); 9858 SDValue Op0 = Op.getOperand(0); 9859 9860 switch (Op0.getOpcode()) { 9861 default: 9862 return SDValue(); 9863 case ISD::FADD: 9864 case ISD::FMUL: 9865 case ISD::FSUB: { 9866 SDValue NewLoad[2]; 9867 for (unsigned i = 0, ie = Op0.getNumOperands(); i != ie; ++i) { 9868 // Ensure both input are loads. 9869 SDValue LdOp = Op0.getOperand(i); 9870 if (LdOp.getOpcode() != ISD::LOAD) 9871 return SDValue(); 9872 // Generate new load node. 9873 LoadSDNode *LD = cast<LoadSDNode>(LdOp); 9874 SDValue LoadOps[] = { LD->getChain(), LD->getBasePtr() }; 9875 NewLoad[i] = 9876 DAG.getMemIntrinsicNode(PPCISD::LD_VSX_LH, dl, 9877 DAG.getVTList(MVT::v4f32, MVT::Other), 9878 LoadOps, LD->getMemoryVT(), 9879 LD->getMemOperand()); 9880 } 9881 SDValue NewOp = DAG.getNode(Op0.getOpcode(), SDLoc(Op0), MVT::v4f32, 9882 NewLoad[0], NewLoad[1], 9883 Op0.getNode()->getFlags()); 9884 return DAG.getNode(PPCISD::FP_EXTEND_LH, dl, MVT::v2f64, NewOp); 9885 } 9886 case ISD::LOAD: { 9887 LoadSDNode *LD = cast<LoadSDNode>(Op0); 9888 SDValue LoadOps[] = { LD->getChain(), LD->getBasePtr() }; 9889 SDValue NewLd = 9890 DAG.getMemIntrinsicNode(PPCISD::LD_VSX_LH, dl, 9891 DAG.getVTList(MVT::v4f32, MVT::Other), 9892 LoadOps, LD->getMemoryVT(), LD->getMemOperand()); 9893 return DAG.getNode(PPCISD::FP_EXTEND_LH, dl, MVT::v2f64, NewLd); 9894 } 9895 } 9896 llvm_unreachable("ERROR:Should return for all cases within swtich."); 9897 } 9898 9899 /// LowerOperation - Provide custom lowering hooks for some operations. 9900 /// 9901 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 9902 switch (Op.getOpcode()) { 9903 default: llvm_unreachable("Wasn't expecting to be able to lower this!"); 9904 case ISD::ConstantPool: return LowerConstantPool(Op, DAG); 9905 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG); 9906 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG); 9907 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG); 9908 case ISD::JumpTable: return LowerJumpTable(Op, DAG); 9909 case ISD::SETCC: return LowerSETCC(Op, DAG); 9910 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG); 9911 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG); 9912 9913 // Variable argument lowering. 9914 case ISD::VASTART: return LowerVASTART(Op, DAG); 9915 case ISD::VAARG: return LowerVAARG(Op, DAG); 9916 case ISD::VACOPY: return LowerVACOPY(Op, DAG); 9917 9918 case ISD::STACKRESTORE: return LowerSTACKRESTORE(Op, DAG); 9919 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG); 9920 case ISD::GET_DYNAMIC_AREA_OFFSET: 9921 return LowerGET_DYNAMIC_AREA_OFFSET(Op, DAG); 9922 9923 // Exception handling lowering. 9924 case ISD::EH_DWARF_CFA: return LowerEH_DWARF_CFA(Op, DAG); 9925 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG); 9926 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG); 9927 9928 case ISD::LOAD: return LowerLOAD(Op, DAG); 9929 case ISD::STORE: return LowerSTORE(Op, DAG); 9930 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG); 9931 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG); 9932 case ISD::FP_TO_UINT: 9933 case ISD::FP_TO_SINT: return LowerFP_TO_INT(Op, DAG, SDLoc(Op)); 9934 case ISD::UINT_TO_FP: 9935 case ISD::SINT_TO_FP: return LowerINT_TO_FP(Op, DAG); 9936 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG); 9937 9938 // Lower 64-bit shifts. 9939 case ISD::SHL_PARTS: return LowerSHL_PARTS(Op, DAG); 9940 case ISD::SRL_PARTS: return LowerSRL_PARTS(Op, DAG); 9941 case ISD::SRA_PARTS: return LowerSRA_PARTS(Op, DAG); 9942 9943 // Vector-related lowering. 9944 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG); 9945 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG); 9946 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG); 9947 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG); 9948 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG); 9949 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG); 9950 case ISD::MUL: return LowerMUL(Op, DAG); 9951 case ISD::ABS: return LowerABS(Op, DAG); 9952 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG); 9953 9954 // For counter-based loop handling. 9955 case ISD::INTRINSIC_W_CHAIN: return SDValue(); 9956 9957 case ISD::BITCAST: return LowerBITCAST(Op, DAG); 9958 9959 // Frame & Return address. 9960 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG); 9961 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG); 9962 9963 case ISD::INTRINSIC_VOID: 9964 return LowerINTRINSIC_VOID(Op, DAG); 9965 case ISD::SREM: 9966 case ISD::UREM: 9967 return LowerREM(Op, DAG); 9968 case ISD::BSWAP: 9969 return LowerBSWAP(Op, DAG); 9970 case ISD::ATOMIC_CMP_SWAP: 9971 return LowerATOMIC_CMP_SWAP(Op, DAG); 9972 } 9973 } 9974 9975 void PPCTargetLowering::ReplaceNodeResults(SDNode *N, 9976 SmallVectorImpl<SDValue>&Results, 9977 SelectionDAG &DAG) const { 9978 SDLoc dl(N); 9979 switch (N->getOpcode()) { 9980 default: 9981 llvm_unreachable("Do not know how to custom type legalize this operation!"); 9982 case ISD::READCYCLECOUNTER: { 9983 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other); 9984 SDValue RTB = DAG.getNode(PPCISD::READ_TIME_BASE, dl, VTs, N->getOperand(0)); 9985 9986 Results.push_back(RTB); 9987 Results.push_back(RTB.getValue(1)); 9988 Results.push_back(RTB.getValue(2)); 9989 break; 9990 } 9991 case ISD::INTRINSIC_W_CHAIN: { 9992 if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 9993 Intrinsic::loop_decrement) 9994 break; 9995 9996 assert(N->getValueType(0) == MVT::i1 && 9997 "Unexpected result type for CTR decrement intrinsic"); 9998 EVT SVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 9999 N->getValueType(0)); 10000 SDVTList VTs = DAG.getVTList(SVT, MVT::Other); 10001 SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0), 10002 N->getOperand(1)); 10003 10004 Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewInt)); 10005 Results.push_back(NewInt.getValue(1)); 10006 break; 10007 } 10008 case ISD::VAARG: { 10009 if (!Subtarget.isSVR4ABI() || Subtarget.isPPC64()) 10010 return; 10011 10012 EVT VT = N->getValueType(0); 10013 10014 if (VT == MVT::i64) { 10015 SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG); 10016 10017 Results.push_back(NewNode); 10018 Results.push_back(NewNode.getValue(1)); 10019 } 10020 return; 10021 } 10022 case ISD::FP_TO_SINT: 10023 case ISD::FP_TO_UINT: 10024 // LowerFP_TO_INT() can only handle f32 and f64. 10025 if (N->getOperand(0).getValueType() == MVT::ppcf128) 10026 return; 10027 Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl)); 10028 return; 10029 case ISD::TRUNCATE: { 10030 EVT TrgVT = N->getValueType(0); 10031 if (TrgVT.isVector() && 10032 isOperationCustom(N->getOpcode(), TrgVT) && 10033 N->getOperand(0).getValueType().getSizeInBits() <= 128) 10034 Results.push_back(LowerTRUNCATEVector(SDValue(N, 0), DAG)); 10035 return; 10036 } 10037 case ISD::BITCAST: 10038 // Don't handle bitcast here. 10039 return; 10040 } 10041 } 10042 10043 //===----------------------------------------------------------------------===// 10044 // Other Lowering Code 10045 //===----------------------------------------------------------------------===// 10046 10047 static Instruction* callIntrinsic(IRBuilder<> &Builder, Intrinsic::ID Id) { 10048 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 10049 Function *Func = Intrinsic::getDeclaration(M, Id); 10050 return Builder.CreateCall(Func, {}); 10051 } 10052 10053 // The mappings for emitLeading/TrailingFence is taken from 10054 // http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html 10055 Instruction *PPCTargetLowering::emitLeadingFence(IRBuilder<> &Builder, 10056 Instruction *Inst, 10057 AtomicOrdering Ord) const { 10058 if (Ord == AtomicOrdering::SequentiallyConsistent) 10059 return callIntrinsic(Builder, Intrinsic::ppc_sync); 10060 if (isReleaseOrStronger(Ord)) 10061 return callIntrinsic(Builder, Intrinsic::ppc_lwsync); 10062 return nullptr; 10063 } 10064 10065 Instruction *PPCTargetLowering::emitTrailingFence(IRBuilder<> &Builder, 10066 Instruction *Inst, 10067 AtomicOrdering Ord) const { 10068 if (Inst->hasAtomicLoad() && isAcquireOrStronger(Ord)) { 10069 // See http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html and 10070 // http://www.rdrop.com/users/paulmck/scalability/paper/N2745r.2011.03.04a.html 10071 // and http://www.cl.cam.ac.uk/~pes20/cppppc/ for justification. 10072 if (isa<LoadInst>(Inst) && Subtarget.isPPC64()) 10073 return Builder.CreateCall( 10074 Intrinsic::getDeclaration( 10075 Builder.GetInsertBlock()->getParent()->getParent(), 10076 Intrinsic::ppc_cfence, {Inst->getType()}), 10077 {Inst}); 10078 // FIXME: Can use isync for rmw operation. 10079 return callIntrinsic(Builder, Intrinsic::ppc_lwsync); 10080 } 10081 return nullptr; 10082 } 10083 10084 MachineBasicBlock * 10085 PPCTargetLowering::EmitAtomicBinary(MachineInstr &MI, MachineBasicBlock *BB, 10086 unsigned AtomicSize, 10087 unsigned BinOpcode, 10088 unsigned CmpOpcode, 10089 unsigned CmpPred) const { 10090 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0. 10091 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 10092 10093 auto LoadMnemonic = PPC::LDARX; 10094 auto StoreMnemonic = PPC::STDCX; 10095 switch (AtomicSize) { 10096 default: 10097 llvm_unreachable("Unexpected size of atomic entity"); 10098 case 1: 10099 LoadMnemonic = PPC::LBARX; 10100 StoreMnemonic = PPC::STBCX; 10101 assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4"); 10102 break; 10103 case 2: 10104 LoadMnemonic = PPC::LHARX; 10105 StoreMnemonic = PPC::STHCX; 10106 assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4"); 10107 break; 10108 case 4: 10109 LoadMnemonic = PPC::LWARX; 10110 StoreMnemonic = PPC::STWCX; 10111 break; 10112 case 8: 10113 LoadMnemonic = PPC::LDARX; 10114 StoreMnemonic = PPC::STDCX; 10115 break; 10116 } 10117 10118 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 10119 MachineFunction *F = BB->getParent(); 10120 MachineFunction::iterator It = ++BB->getIterator(); 10121 10122 unsigned dest = MI.getOperand(0).getReg(); 10123 unsigned ptrA = MI.getOperand(1).getReg(); 10124 unsigned ptrB = MI.getOperand(2).getReg(); 10125 unsigned incr = MI.getOperand(3).getReg(); 10126 DebugLoc dl = MI.getDebugLoc(); 10127 10128 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB); 10129 MachineBasicBlock *loop2MBB = 10130 CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr; 10131 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 10132 F->insert(It, loopMBB); 10133 if (CmpOpcode) 10134 F->insert(It, loop2MBB); 10135 F->insert(It, exitMBB); 10136 exitMBB->splice(exitMBB->begin(), BB, 10137 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 10138 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 10139 10140 MachineRegisterInfo &RegInfo = F->getRegInfo(); 10141 unsigned TmpReg = (!BinOpcode) ? incr : 10142 RegInfo.createVirtualRegister( AtomicSize == 8 ? &PPC::G8RCRegClass 10143 : &PPC::GPRCRegClass); 10144 10145 // thisMBB: 10146 // ... 10147 // fallthrough --> loopMBB 10148 BB->addSuccessor(loopMBB); 10149 10150 // loopMBB: 10151 // l[wd]arx dest, ptr 10152 // add r0, dest, incr 10153 // st[wd]cx. r0, ptr 10154 // bne- loopMBB 10155 // fallthrough --> exitMBB 10156 10157 // For max/min... 10158 // loopMBB: 10159 // l[wd]arx dest, ptr 10160 // cmpl?[wd] incr, dest 10161 // bgt exitMBB 10162 // loop2MBB: 10163 // st[wd]cx. dest, ptr 10164 // bne- loopMBB 10165 // fallthrough --> exitMBB 10166 10167 BB = loopMBB; 10168 BuildMI(BB, dl, TII->get(LoadMnemonic), dest) 10169 .addReg(ptrA).addReg(ptrB); 10170 if (BinOpcode) 10171 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest); 10172 if (CmpOpcode) { 10173 // Signed comparisons of byte or halfword values must be sign-extended. 10174 if (CmpOpcode == PPC::CMPW && AtomicSize < 4) { 10175 unsigned ExtReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass); 10176 BuildMI(BB, dl, TII->get(AtomicSize == 1 ? PPC::EXTSB : PPC::EXTSH), 10177 ExtReg).addReg(dest); 10178 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0) 10179 .addReg(incr).addReg(ExtReg); 10180 } else 10181 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0) 10182 .addReg(incr).addReg(dest); 10183 10184 BuildMI(BB, dl, TII->get(PPC::BCC)) 10185 .addImm(CmpPred).addReg(PPC::CR0).addMBB(exitMBB); 10186 BB->addSuccessor(loop2MBB); 10187 BB->addSuccessor(exitMBB); 10188 BB = loop2MBB; 10189 } 10190 BuildMI(BB, dl, TII->get(StoreMnemonic)) 10191 .addReg(TmpReg).addReg(ptrA).addReg(ptrB); 10192 BuildMI(BB, dl, TII->get(PPC::BCC)) 10193 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB); 10194 BB->addSuccessor(loopMBB); 10195 BB->addSuccessor(exitMBB); 10196 10197 // exitMBB: 10198 // ... 10199 BB = exitMBB; 10200 return BB; 10201 } 10202 10203 MachineBasicBlock *PPCTargetLowering::EmitPartwordAtomicBinary( 10204 MachineInstr &MI, MachineBasicBlock *BB, 10205 bool is8bit, // operation 10206 unsigned BinOpcode, unsigned CmpOpcode, unsigned CmpPred) const { 10207 // If we support part-word atomic mnemonics, just use them 10208 if (Subtarget.hasPartwordAtomics()) 10209 return EmitAtomicBinary(MI, BB, is8bit ? 1 : 2, BinOpcode, CmpOpcode, 10210 CmpPred); 10211 10212 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0. 10213 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 10214 // In 64 bit mode we have to use 64 bits for addresses, even though the 10215 // lwarx/stwcx are 32 bits. With the 32-bit atomics we can use address 10216 // registers without caring whether they're 32 or 64, but here we're 10217 // doing actual arithmetic on the addresses. 10218 bool is64bit = Subtarget.isPPC64(); 10219 bool isLittleEndian = Subtarget.isLittleEndian(); 10220 unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO; 10221 10222 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 10223 MachineFunction *F = BB->getParent(); 10224 MachineFunction::iterator It = ++BB->getIterator(); 10225 10226 unsigned dest = MI.getOperand(0).getReg(); 10227 unsigned ptrA = MI.getOperand(1).getReg(); 10228 unsigned ptrB = MI.getOperand(2).getReg(); 10229 unsigned incr = MI.getOperand(3).getReg(); 10230 DebugLoc dl = MI.getDebugLoc(); 10231 10232 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB); 10233 MachineBasicBlock *loop2MBB = 10234 CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr; 10235 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 10236 F->insert(It, loopMBB); 10237 if (CmpOpcode) 10238 F->insert(It, loop2MBB); 10239 F->insert(It, exitMBB); 10240 exitMBB->splice(exitMBB->begin(), BB, 10241 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 10242 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 10243 10244 MachineRegisterInfo &RegInfo = F->getRegInfo(); 10245 const TargetRegisterClass *RC = 10246 is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 10247 const TargetRegisterClass *GPRC = &PPC::GPRCRegClass; 10248 10249 unsigned PtrReg = RegInfo.createVirtualRegister(RC); 10250 unsigned Shift1Reg = RegInfo.createVirtualRegister(GPRC); 10251 unsigned ShiftReg = 10252 isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC); 10253 unsigned Incr2Reg = RegInfo.createVirtualRegister(GPRC); 10254 unsigned MaskReg = RegInfo.createVirtualRegister(GPRC); 10255 unsigned Mask2Reg = RegInfo.createVirtualRegister(GPRC); 10256 unsigned Mask3Reg = RegInfo.createVirtualRegister(GPRC); 10257 unsigned Tmp2Reg = RegInfo.createVirtualRegister(GPRC); 10258 unsigned Tmp3Reg = RegInfo.createVirtualRegister(GPRC); 10259 unsigned Tmp4Reg = RegInfo.createVirtualRegister(GPRC); 10260 unsigned TmpDestReg = RegInfo.createVirtualRegister(GPRC); 10261 unsigned Ptr1Reg; 10262 unsigned TmpReg = 10263 (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(GPRC); 10264 10265 // thisMBB: 10266 // ... 10267 // fallthrough --> loopMBB 10268 BB->addSuccessor(loopMBB); 10269 10270 // The 4-byte load must be aligned, while a char or short may be 10271 // anywhere in the word. Hence all this nasty bookkeeping code. 10272 // add ptr1, ptrA, ptrB [copy if ptrA==0] 10273 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27] 10274 // xori shift, shift1, 24 [16] 10275 // rlwinm ptr, ptr1, 0, 0, 29 10276 // slw incr2, incr, shift 10277 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535] 10278 // slw mask, mask2, shift 10279 // loopMBB: 10280 // lwarx tmpDest, ptr 10281 // add tmp, tmpDest, incr2 10282 // andc tmp2, tmpDest, mask 10283 // and tmp3, tmp, mask 10284 // or tmp4, tmp3, tmp2 10285 // stwcx. tmp4, ptr 10286 // bne- loopMBB 10287 // fallthrough --> exitMBB 10288 // srw dest, tmpDest, shift 10289 if (ptrA != ZeroReg) { 10290 Ptr1Reg = RegInfo.createVirtualRegister(RC); 10291 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg) 10292 .addReg(ptrA) 10293 .addReg(ptrB); 10294 } else { 10295 Ptr1Reg = ptrB; 10296 } 10297 // We need use 32-bit subregister to avoid mismatch register class in 64-bit 10298 // mode. 10299 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg) 10300 .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0) 10301 .addImm(3) 10302 .addImm(27) 10303 .addImm(is8bit ? 28 : 27); 10304 if (!isLittleEndian) 10305 BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg) 10306 .addReg(Shift1Reg) 10307 .addImm(is8bit ? 24 : 16); 10308 if (is64bit) 10309 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg) 10310 .addReg(Ptr1Reg) 10311 .addImm(0) 10312 .addImm(61); 10313 else 10314 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg) 10315 .addReg(Ptr1Reg) 10316 .addImm(0) 10317 .addImm(0) 10318 .addImm(29); 10319 BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg).addReg(incr).addReg(ShiftReg); 10320 if (is8bit) 10321 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255); 10322 else { 10323 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0); 10324 BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg) 10325 .addReg(Mask3Reg) 10326 .addImm(65535); 10327 } 10328 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg) 10329 .addReg(Mask2Reg) 10330 .addReg(ShiftReg); 10331 10332 BB = loopMBB; 10333 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg) 10334 .addReg(ZeroReg) 10335 .addReg(PtrReg); 10336 if (BinOpcode) 10337 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg) 10338 .addReg(Incr2Reg) 10339 .addReg(TmpDestReg); 10340 BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg) 10341 .addReg(TmpDestReg) 10342 .addReg(MaskReg); 10343 BuildMI(BB, dl, TII->get(PPC::AND), Tmp3Reg).addReg(TmpReg).addReg(MaskReg); 10344 if (CmpOpcode) { 10345 // For unsigned comparisons, we can directly compare the shifted values. 10346 // For signed comparisons we shift and sign extend. 10347 unsigned SReg = RegInfo.createVirtualRegister(GPRC); 10348 BuildMI(BB, dl, TII->get(PPC::AND), SReg) 10349 .addReg(TmpDestReg) 10350 .addReg(MaskReg); 10351 unsigned ValueReg = SReg; 10352 unsigned CmpReg = Incr2Reg; 10353 if (CmpOpcode == PPC::CMPW) { 10354 ValueReg = RegInfo.createVirtualRegister(GPRC); 10355 BuildMI(BB, dl, TII->get(PPC::SRW), ValueReg) 10356 .addReg(SReg) 10357 .addReg(ShiftReg); 10358 unsigned ValueSReg = RegInfo.createVirtualRegister(GPRC); 10359 BuildMI(BB, dl, TII->get(is8bit ? PPC::EXTSB : PPC::EXTSH), ValueSReg) 10360 .addReg(ValueReg); 10361 ValueReg = ValueSReg; 10362 CmpReg = incr; 10363 } 10364 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0) 10365 .addReg(CmpReg) 10366 .addReg(ValueReg); 10367 BuildMI(BB, dl, TII->get(PPC::BCC)) 10368 .addImm(CmpPred) 10369 .addReg(PPC::CR0) 10370 .addMBB(exitMBB); 10371 BB->addSuccessor(loop2MBB); 10372 BB->addSuccessor(exitMBB); 10373 BB = loop2MBB; 10374 } 10375 BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg).addReg(Tmp3Reg).addReg(Tmp2Reg); 10376 BuildMI(BB, dl, TII->get(PPC::STWCX)) 10377 .addReg(Tmp4Reg) 10378 .addReg(ZeroReg) 10379 .addReg(PtrReg); 10380 BuildMI(BB, dl, TII->get(PPC::BCC)) 10381 .addImm(PPC::PRED_NE) 10382 .addReg(PPC::CR0) 10383 .addMBB(loopMBB); 10384 BB->addSuccessor(loopMBB); 10385 BB->addSuccessor(exitMBB); 10386 10387 // exitMBB: 10388 // ... 10389 BB = exitMBB; 10390 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest) 10391 .addReg(TmpDestReg) 10392 .addReg(ShiftReg); 10393 return BB; 10394 } 10395 10396 llvm::MachineBasicBlock * 10397 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr &MI, 10398 MachineBasicBlock *MBB) const { 10399 DebugLoc DL = MI.getDebugLoc(); 10400 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 10401 const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo(); 10402 10403 MachineFunction *MF = MBB->getParent(); 10404 MachineRegisterInfo &MRI = MF->getRegInfo(); 10405 10406 const BasicBlock *BB = MBB->getBasicBlock(); 10407 MachineFunction::iterator I = ++MBB->getIterator(); 10408 10409 unsigned DstReg = MI.getOperand(0).getReg(); 10410 const TargetRegisterClass *RC = MRI.getRegClass(DstReg); 10411 assert(TRI->isTypeLegalForClass(*RC, MVT::i32) && "Invalid destination!"); 10412 unsigned mainDstReg = MRI.createVirtualRegister(RC); 10413 unsigned restoreDstReg = MRI.createVirtualRegister(RC); 10414 10415 MVT PVT = getPointerTy(MF->getDataLayout()); 10416 assert((PVT == MVT::i64 || PVT == MVT::i32) && 10417 "Invalid Pointer Size!"); 10418 // For v = setjmp(buf), we generate 10419 // 10420 // thisMBB: 10421 // SjLjSetup mainMBB 10422 // bl mainMBB 10423 // v_restore = 1 10424 // b sinkMBB 10425 // 10426 // mainMBB: 10427 // buf[LabelOffset] = LR 10428 // v_main = 0 10429 // 10430 // sinkMBB: 10431 // v = phi(main, restore) 10432 // 10433 10434 MachineBasicBlock *thisMBB = MBB; 10435 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB); 10436 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB); 10437 MF->insert(I, mainMBB); 10438 MF->insert(I, sinkMBB); 10439 10440 MachineInstrBuilder MIB; 10441 10442 // Transfer the remainder of BB and its successor edges to sinkMBB. 10443 sinkMBB->splice(sinkMBB->begin(), MBB, 10444 std::next(MachineBasicBlock::iterator(MI)), MBB->end()); 10445 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB); 10446 10447 // Note that the structure of the jmp_buf used here is not compatible 10448 // with that used by libc, and is not designed to be. Specifically, it 10449 // stores only those 'reserved' registers that LLVM does not otherwise 10450 // understand how to spill. Also, by convention, by the time this 10451 // intrinsic is called, Clang has already stored the frame address in the 10452 // first slot of the buffer and stack address in the third. Following the 10453 // X86 target code, we'll store the jump address in the second slot. We also 10454 // need to save the TOC pointer (R2) to handle jumps between shared 10455 // libraries, and that will be stored in the fourth slot. The thread 10456 // identifier (R13) is not affected. 10457 10458 // thisMBB: 10459 const int64_t LabelOffset = 1 * PVT.getStoreSize(); 10460 const int64_t TOCOffset = 3 * PVT.getStoreSize(); 10461 const int64_t BPOffset = 4 * PVT.getStoreSize(); 10462 10463 // Prepare IP either in reg. 10464 const TargetRegisterClass *PtrRC = getRegClassFor(PVT); 10465 unsigned LabelReg = MRI.createVirtualRegister(PtrRC); 10466 unsigned BufReg = MI.getOperand(1).getReg(); 10467 10468 if (Subtarget.isPPC64() && Subtarget.isSVR4ABI()) { 10469 setUsesTOCBasePtr(*MBB->getParent()); 10470 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD)) 10471 .addReg(PPC::X2) 10472 .addImm(TOCOffset) 10473 .addReg(BufReg) 10474 .cloneMemRefs(MI); 10475 } 10476 10477 // Naked functions never have a base pointer, and so we use r1. For all 10478 // other functions, this decision must be delayed until during PEI. 10479 unsigned BaseReg; 10480 if (MF->getFunction().hasFnAttribute(Attribute::Naked)) 10481 BaseReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1; 10482 else 10483 BaseReg = Subtarget.isPPC64() ? PPC::BP8 : PPC::BP; 10484 10485 MIB = BuildMI(*thisMBB, MI, DL, 10486 TII->get(Subtarget.isPPC64() ? PPC::STD : PPC::STW)) 10487 .addReg(BaseReg) 10488 .addImm(BPOffset) 10489 .addReg(BufReg) 10490 .cloneMemRefs(MI); 10491 10492 // Setup 10493 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB); 10494 MIB.addRegMask(TRI->getNoPreservedMask()); 10495 10496 BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1); 10497 10498 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup)) 10499 .addMBB(mainMBB); 10500 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB); 10501 10502 thisMBB->addSuccessor(mainMBB, BranchProbability::getZero()); 10503 thisMBB->addSuccessor(sinkMBB, BranchProbability::getOne()); 10504 10505 // mainMBB: 10506 // mainDstReg = 0 10507 MIB = 10508 BuildMI(mainMBB, DL, 10509 TII->get(Subtarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg); 10510 10511 // Store IP 10512 if (Subtarget.isPPC64()) { 10513 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD)) 10514 .addReg(LabelReg) 10515 .addImm(LabelOffset) 10516 .addReg(BufReg); 10517 } else { 10518 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW)) 10519 .addReg(LabelReg) 10520 .addImm(LabelOffset) 10521 .addReg(BufReg); 10522 } 10523 MIB.cloneMemRefs(MI); 10524 10525 BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0); 10526 mainMBB->addSuccessor(sinkMBB); 10527 10528 // sinkMBB: 10529 BuildMI(*sinkMBB, sinkMBB->begin(), DL, 10530 TII->get(PPC::PHI), DstReg) 10531 .addReg(mainDstReg).addMBB(mainMBB) 10532 .addReg(restoreDstReg).addMBB(thisMBB); 10533 10534 MI.eraseFromParent(); 10535 return sinkMBB; 10536 } 10537 10538 MachineBasicBlock * 10539 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr &MI, 10540 MachineBasicBlock *MBB) const { 10541 DebugLoc DL = MI.getDebugLoc(); 10542 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 10543 10544 MachineFunction *MF = MBB->getParent(); 10545 MachineRegisterInfo &MRI = MF->getRegInfo(); 10546 10547 MVT PVT = getPointerTy(MF->getDataLayout()); 10548 assert((PVT == MVT::i64 || PVT == MVT::i32) && 10549 "Invalid Pointer Size!"); 10550 10551 const TargetRegisterClass *RC = 10552 (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 10553 unsigned Tmp = MRI.createVirtualRegister(RC); 10554 // Since FP is only updated here but NOT referenced, it's treated as GPR. 10555 unsigned FP = (PVT == MVT::i64) ? PPC::X31 : PPC::R31; 10556 unsigned SP = (PVT == MVT::i64) ? PPC::X1 : PPC::R1; 10557 unsigned BP = 10558 (PVT == MVT::i64) 10559 ? PPC::X30 10560 : (Subtarget.isSVR4ABI() && isPositionIndependent() ? PPC::R29 10561 : PPC::R30); 10562 10563 MachineInstrBuilder MIB; 10564 10565 const int64_t LabelOffset = 1 * PVT.getStoreSize(); 10566 const int64_t SPOffset = 2 * PVT.getStoreSize(); 10567 const int64_t TOCOffset = 3 * PVT.getStoreSize(); 10568 const int64_t BPOffset = 4 * PVT.getStoreSize(); 10569 10570 unsigned BufReg = MI.getOperand(0).getReg(); 10571 10572 // Reload FP (the jumped-to function may not have had a 10573 // frame pointer, and if so, then its r31 will be restored 10574 // as necessary). 10575 if (PVT == MVT::i64) { 10576 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP) 10577 .addImm(0) 10578 .addReg(BufReg); 10579 } else { 10580 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP) 10581 .addImm(0) 10582 .addReg(BufReg); 10583 } 10584 MIB.cloneMemRefs(MI); 10585 10586 // Reload IP 10587 if (PVT == MVT::i64) { 10588 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp) 10589 .addImm(LabelOffset) 10590 .addReg(BufReg); 10591 } else { 10592 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp) 10593 .addImm(LabelOffset) 10594 .addReg(BufReg); 10595 } 10596 MIB.cloneMemRefs(MI); 10597 10598 // Reload SP 10599 if (PVT == MVT::i64) { 10600 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP) 10601 .addImm(SPOffset) 10602 .addReg(BufReg); 10603 } else { 10604 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP) 10605 .addImm(SPOffset) 10606 .addReg(BufReg); 10607 } 10608 MIB.cloneMemRefs(MI); 10609 10610 // Reload BP 10611 if (PVT == MVT::i64) { 10612 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP) 10613 .addImm(BPOffset) 10614 .addReg(BufReg); 10615 } else { 10616 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP) 10617 .addImm(BPOffset) 10618 .addReg(BufReg); 10619 } 10620 MIB.cloneMemRefs(MI); 10621 10622 // Reload TOC 10623 if (PVT == MVT::i64 && Subtarget.isSVR4ABI()) { 10624 setUsesTOCBasePtr(*MBB->getParent()); 10625 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2) 10626 .addImm(TOCOffset) 10627 .addReg(BufReg) 10628 .cloneMemRefs(MI); 10629 } 10630 10631 // Jump 10632 BuildMI(*MBB, MI, DL, 10633 TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp); 10634 BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR)); 10635 10636 MI.eraseFromParent(); 10637 return MBB; 10638 } 10639 10640 MachineBasicBlock * 10641 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI, 10642 MachineBasicBlock *BB) const { 10643 if (MI.getOpcode() == TargetOpcode::STACKMAP || 10644 MI.getOpcode() == TargetOpcode::PATCHPOINT) { 10645 if (Subtarget.isPPC64() && Subtarget.isSVR4ABI() && 10646 MI.getOpcode() == TargetOpcode::PATCHPOINT) { 10647 // Call lowering should have added an r2 operand to indicate a dependence 10648 // on the TOC base pointer value. It can't however, because there is no 10649 // way to mark the dependence as implicit there, and so the stackmap code 10650 // will confuse it with a regular operand. Instead, add the dependence 10651 // here. 10652 MI.addOperand(MachineOperand::CreateReg(PPC::X2, false, true)); 10653 } 10654 10655 return emitPatchPoint(MI, BB); 10656 } 10657 10658 if (MI.getOpcode() == PPC::EH_SjLj_SetJmp32 || 10659 MI.getOpcode() == PPC::EH_SjLj_SetJmp64) { 10660 return emitEHSjLjSetJmp(MI, BB); 10661 } else if (MI.getOpcode() == PPC::EH_SjLj_LongJmp32 || 10662 MI.getOpcode() == PPC::EH_SjLj_LongJmp64) { 10663 return emitEHSjLjLongJmp(MI, BB); 10664 } 10665 10666 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 10667 10668 // To "insert" these instructions we actually have to insert their 10669 // control-flow patterns. 10670 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 10671 MachineFunction::iterator It = ++BB->getIterator(); 10672 10673 MachineFunction *F = BB->getParent(); 10674 10675 if (MI.getOpcode() == PPC::SELECT_CC_I4 || 10676 MI.getOpcode() == PPC::SELECT_CC_I8 || MI.getOpcode() == PPC::SELECT_I4 || 10677 MI.getOpcode() == PPC::SELECT_I8) { 10678 SmallVector<MachineOperand, 2> Cond; 10679 if (MI.getOpcode() == PPC::SELECT_CC_I4 || 10680 MI.getOpcode() == PPC::SELECT_CC_I8) 10681 Cond.push_back(MI.getOperand(4)); 10682 else 10683 Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET)); 10684 Cond.push_back(MI.getOperand(1)); 10685 10686 DebugLoc dl = MI.getDebugLoc(); 10687 TII->insertSelect(*BB, MI, dl, MI.getOperand(0).getReg(), Cond, 10688 MI.getOperand(2).getReg(), MI.getOperand(3).getReg()); 10689 } else if (MI.getOpcode() == PPC::SELECT_CC_I4 || 10690 MI.getOpcode() == PPC::SELECT_CC_I8 || 10691 MI.getOpcode() == PPC::SELECT_CC_F4 || 10692 MI.getOpcode() == PPC::SELECT_CC_F8 || 10693 MI.getOpcode() == PPC::SELECT_CC_F16 || 10694 MI.getOpcode() == PPC::SELECT_CC_QFRC || 10695 MI.getOpcode() == PPC::SELECT_CC_QSRC || 10696 MI.getOpcode() == PPC::SELECT_CC_QBRC || 10697 MI.getOpcode() == PPC::SELECT_CC_VRRC || 10698 MI.getOpcode() == PPC::SELECT_CC_VSFRC || 10699 MI.getOpcode() == PPC::SELECT_CC_VSSRC || 10700 MI.getOpcode() == PPC::SELECT_CC_VSRC || 10701 MI.getOpcode() == PPC::SELECT_CC_SPE4 || 10702 MI.getOpcode() == PPC::SELECT_CC_SPE || 10703 MI.getOpcode() == PPC::SELECT_I4 || 10704 MI.getOpcode() == PPC::SELECT_I8 || 10705 MI.getOpcode() == PPC::SELECT_F4 || 10706 MI.getOpcode() == PPC::SELECT_F8 || 10707 MI.getOpcode() == PPC::SELECT_F16 || 10708 MI.getOpcode() == PPC::SELECT_QFRC || 10709 MI.getOpcode() == PPC::SELECT_QSRC || 10710 MI.getOpcode() == PPC::SELECT_QBRC || 10711 MI.getOpcode() == PPC::SELECT_SPE || 10712 MI.getOpcode() == PPC::SELECT_SPE4 || 10713 MI.getOpcode() == PPC::SELECT_VRRC || 10714 MI.getOpcode() == PPC::SELECT_VSFRC || 10715 MI.getOpcode() == PPC::SELECT_VSSRC || 10716 MI.getOpcode() == PPC::SELECT_VSRC) { 10717 // The incoming instruction knows the destination vreg to set, the 10718 // condition code register to branch on, the true/false values to 10719 // select between, and a branch opcode to use. 10720 10721 // thisMBB: 10722 // ... 10723 // TrueVal = ... 10724 // cmpTY ccX, r1, r2 10725 // bCC copy1MBB 10726 // fallthrough --> copy0MBB 10727 MachineBasicBlock *thisMBB = BB; 10728 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB); 10729 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 10730 DebugLoc dl = MI.getDebugLoc(); 10731 F->insert(It, copy0MBB); 10732 F->insert(It, sinkMBB); 10733 10734 // Transfer the remainder of BB and its successor edges to sinkMBB. 10735 sinkMBB->splice(sinkMBB->begin(), BB, 10736 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 10737 sinkMBB->transferSuccessorsAndUpdatePHIs(BB); 10738 10739 // Next, add the true and fallthrough blocks as its successors. 10740 BB->addSuccessor(copy0MBB); 10741 BB->addSuccessor(sinkMBB); 10742 10743 if (MI.getOpcode() == PPC::SELECT_I4 || MI.getOpcode() == PPC::SELECT_I8 || 10744 MI.getOpcode() == PPC::SELECT_F4 || MI.getOpcode() == PPC::SELECT_F8 || 10745 MI.getOpcode() == PPC::SELECT_F16 || 10746 MI.getOpcode() == PPC::SELECT_SPE4 || 10747 MI.getOpcode() == PPC::SELECT_SPE || 10748 MI.getOpcode() == PPC::SELECT_QFRC || 10749 MI.getOpcode() == PPC::SELECT_QSRC || 10750 MI.getOpcode() == PPC::SELECT_QBRC || 10751 MI.getOpcode() == PPC::SELECT_VRRC || 10752 MI.getOpcode() == PPC::SELECT_VSFRC || 10753 MI.getOpcode() == PPC::SELECT_VSSRC || 10754 MI.getOpcode() == PPC::SELECT_VSRC) { 10755 BuildMI(BB, dl, TII->get(PPC::BC)) 10756 .addReg(MI.getOperand(1).getReg()) 10757 .addMBB(sinkMBB); 10758 } else { 10759 unsigned SelectPred = MI.getOperand(4).getImm(); 10760 BuildMI(BB, dl, TII->get(PPC::BCC)) 10761 .addImm(SelectPred) 10762 .addReg(MI.getOperand(1).getReg()) 10763 .addMBB(sinkMBB); 10764 } 10765 10766 // copy0MBB: 10767 // %FalseValue = ... 10768 // # fallthrough to sinkMBB 10769 BB = copy0MBB; 10770 10771 // Update machine-CFG edges 10772 BB->addSuccessor(sinkMBB); 10773 10774 // sinkMBB: 10775 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ] 10776 // ... 10777 BB = sinkMBB; 10778 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::PHI), MI.getOperand(0).getReg()) 10779 .addReg(MI.getOperand(3).getReg()) 10780 .addMBB(copy0MBB) 10781 .addReg(MI.getOperand(2).getReg()) 10782 .addMBB(thisMBB); 10783 } else if (MI.getOpcode() == PPC::ReadTB) { 10784 // To read the 64-bit time-base register on a 32-bit target, we read the 10785 // two halves. Should the counter have wrapped while it was being read, we 10786 // need to try again. 10787 // ... 10788 // readLoop: 10789 // mfspr Rx,TBU # load from TBU 10790 // mfspr Ry,TB # load from TB 10791 // mfspr Rz,TBU # load from TBU 10792 // cmpw crX,Rx,Rz # check if 'old'='new' 10793 // bne readLoop # branch if they're not equal 10794 // ... 10795 10796 MachineBasicBlock *readMBB = F->CreateMachineBasicBlock(LLVM_BB); 10797 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 10798 DebugLoc dl = MI.getDebugLoc(); 10799 F->insert(It, readMBB); 10800 F->insert(It, sinkMBB); 10801 10802 // Transfer the remainder of BB and its successor edges to sinkMBB. 10803 sinkMBB->splice(sinkMBB->begin(), BB, 10804 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 10805 sinkMBB->transferSuccessorsAndUpdatePHIs(BB); 10806 10807 BB->addSuccessor(readMBB); 10808 BB = readMBB; 10809 10810 MachineRegisterInfo &RegInfo = F->getRegInfo(); 10811 unsigned ReadAgainReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass); 10812 unsigned LoReg = MI.getOperand(0).getReg(); 10813 unsigned HiReg = MI.getOperand(1).getReg(); 10814 10815 BuildMI(BB, dl, TII->get(PPC::MFSPR), HiReg).addImm(269); 10816 BuildMI(BB, dl, TII->get(PPC::MFSPR), LoReg).addImm(268); 10817 BuildMI(BB, dl, TII->get(PPC::MFSPR), ReadAgainReg).addImm(269); 10818 10819 unsigned CmpReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass); 10820 10821 BuildMI(BB, dl, TII->get(PPC::CMPW), CmpReg) 10822 .addReg(HiReg) 10823 .addReg(ReadAgainReg); 10824 BuildMI(BB, dl, TII->get(PPC::BCC)) 10825 .addImm(PPC::PRED_NE) 10826 .addReg(CmpReg) 10827 .addMBB(readMBB); 10828 10829 BB->addSuccessor(readMBB); 10830 BB->addSuccessor(sinkMBB); 10831 } else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I8) 10832 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4); 10833 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I16) 10834 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4); 10835 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I32) 10836 BB = EmitAtomicBinary(MI, BB, 4, PPC::ADD4); 10837 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I64) 10838 BB = EmitAtomicBinary(MI, BB, 8, PPC::ADD8); 10839 10840 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I8) 10841 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND); 10842 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I16) 10843 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND); 10844 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I32) 10845 BB = EmitAtomicBinary(MI, BB, 4, PPC::AND); 10846 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I64) 10847 BB = EmitAtomicBinary(MI, BB, 8, PPC::AND8); 10848 10849 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I8) 10850 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR); 10851 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I16) 10852 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR); 10853 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I32) 10854 BB = EmitAtomicBinary(MI, BB, 4, PPC::OR); 10855 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I64) 10856 BB = EmitAtomicBinary(MI, BB, 8, PPC::OR8); 10857 10858 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I8) 10859 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR); 10860 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I16) 10861 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR); 10862 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I32) 10863 BB = EmitAtomicBinary(MI, BB, 4, PPC::XOR); 10864 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I64) 10865 BB = EmitAtomicBinary(MI, BB, 8, PPC::XOR8); 10866 10867 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I8) 10868 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::NAND); 10869 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I16) 10870 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::NAND); 10871 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I32) 10872 BB = EmitAtomicBinary(MI, BB, 4, PPC::NAND); 10873 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I64) 10874 BB = EmitAtomicBinary(MI, BB, 8, PPC::NAND8); 10875 10876 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I8) 10877 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF); 10878 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I16) 10879 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF); 10880 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I32) 10881 BB = EmitAtomicBinary(MI, BB, 4, PPC::SUBF); 10882 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I64) 10883 BB = EmitAtomicBinary(MI, BB, 8, PPC::SUBF8); 10884 10885 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I8) 10886 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_GE); 10887 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I16) 10888 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_GE); 10889 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I32) 10890 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_GE); 10891 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I64) 10892 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_GE); 10893 10894 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I8) 10895 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_LE); 10896 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I16) 10897 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_LE); 10898 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I32) 10899 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_LE); 10900 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I64) 10901 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_LE); 10902 10903 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I8) 10904 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_GE); 10905 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I16) 10906 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_GE); 10907 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I32) 10908 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_GE); 10909 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I64) 10910 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_GE); 10911 10912 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I8) 10913 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_LE); 10914 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I16) 10915 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_LE); 10916 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I32) 10917 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_LE); 10918 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I64) 10919 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_LE); 10920 10921 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I8) 10922 BB = EmitPartwordAtomicBinary(MI, BB, true, 0); 10923 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I16) 10924 BB = EmitPartwordAtomicBinary(MI, BB, false, 0); 10925 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I32) 10926 BB = EmitAtomicBinary(MI, BB, 4, 0); 10927 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I64) 10928 BB = EmitAtomicBinary(MI, BB, 8, 0); 10929 else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 || 10930 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64 || 10931 (Subtarget.hasPartwordAtomics() && 10932 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8) || 10933 (Subtarget.hasPartwordAtomics() && 10934 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16)) { 10935 bool is64bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64; 10936 10937 auto LoadMnemonic = PPC::LDARX; 10938 auto StoreMnemonic = PPC::STDCX; 10939 switch (MI.getOpcode()) { 10940 default: 10941 llvm_unreachable("Compare and swap of unknown size"); 10942 case PPC::ATOMIC_CMP_SWAP_I8: 10943 LoadMnemonic = PPC::LBARX; 10944 StoreMnemonic = PPC::STBCX; 10945 assert(Subtarget.hasPartwordAtomics() && "No support partword atomics."); 10946 break; 10947 case PPC::ATOMIC_CMP_SWAP_I16: 10948 LoadMnemonic = PPC::LHARX; 10949 StoreMnemonic = PPC::STHCX; 10950 assert(Subtarget.hasPartwordAtomics() && "No support partword atomics."); 10951 break; 10952 case PPC::ATOMIC_CMP_SWAP_I32: 10953 LoadMnemonic = PPC::LWARX; 10954 StoreMnemonic = PPC::STWCX; 10955 break; 10956 case PPC::ATOMIC_CMP_SWAP_I64: 10957 LoadMnemonic = PPC::LDARX; 10958 StoreMnemonic = PPC::STDCX; 10959 break; 10960 } 10961 unsigned dest = MI.getOperand(0).getReg(); 10962 unsigned ptrA = MI.getOperand(1).getReg(); 10963 unsigned ptrB = MI.getOperand(2).getReg(); 10964 unsigned oldval = MI.getOperand(3).getReg(); 10965 unsigned newval = MI.getOperand(4).getReg(); 10966 DebugLoc dl = MI.getDebugLoc(); 10967 10968 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB); 10969 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB); 10970 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB); 10971 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 10972 F->insert(It, loop1MBB); 10973 F->insert(It, loop2MBB); 10974 F->insert(It, midMBB); 10975 F->insert(It, exitMBB); 10976 exitMBB->splice(exitMBB->begin(), BB, 10977 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 10978 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 10979 10980 // thisMBB: 10981 // ... 10982 // fallthrough --> loopMBB 10983 BB->addSuccessor(loop1MBB); 10984 10985 // loop1MBB: 10986 // l[bhwd]arx dest, ptr 10987 // cmp[wd] dest, oldval 10988 // bne- midMBB 10989 // loop2MBB: 10990 // st[bhwd]cx. newval, ptr 10991 // bne- loopMBB 10992 // b exitBB 10993 // midMBB: 10994 // st[bhwd]cx. dest, ptr 10995 // exitBB: 10996 BB = loop1MBB; 10997 BuildMI(BB, dl, TII->get(LoadMnemonic), dest).addReg(ptrA).addReg(ptrB); 10998 BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0) 10999 .addReg(oldval) 11000 .addReg(dest); 11001 BuildMI(BB, dl, TII->get(PPC::BCC)) 11002 .addImm(PPC::PRED_NE) 11003 .addReg(PPC::CR0) 11004 .addMBB(midMBB); 11005 BB->addSuccessor(loop2MBB); 11006 BB->addSuccessor(midMBB); 11007 11008 BB = loop2MBB; 11009 BuildMI(BB, dl, TII->get(StoreMnemonic)) 11010 .addReg(newval) 11011 .addReg(ptrA) 11012 .addReg(ptrB); 11013 BuildMI(BB, dl, TII->get(PPC::BCC)) 11014 .addImm(PPC::PRED_NE) 11015 .addReg(PPC::CR0) 11016 .addMBB(loop1MBB); 11017 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB); 11018 BB->addSuccessor(loop1MBB); 11019 BB->addSuccessor(exitMBB); 11020 11021 BB = midMBB; 11022 BuildMI(BB, dl, TII->get(StoreMnemonic)) 11023 .addReg(dest) 11024 .addReg(ptrA) 11025 .addReg(ptrB); 11026 BB->addSuccessor(exitMBB); 11027 11028 // exitMBB: 11029 // ... 11030 BB = exitMBB; 11031 } else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 || 11032 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) { 11033 // We must use 64-bit registers for addresses when targeting 64-bit, 11034 // since we're actually doing arithmetic on them. Other registers 11035 // can be 32-bit. 11036 bool is64bit = Subtarget.isPPC64(); 11037 bool isLittleEndian = Subtarget.isLittleEndian(); 11038 bool is8bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8; 11039 11040 unsigned dest = MI.getOperand(0).getReg(); 11041 unsigned ptrA = MI.getOperand(1).getReg(); 11042 unsigned ptrB = MI.getOperand(2).getReg(); 11043 unsigned oldval = MI.getOperand(3).getReg(); 11044 unsigned newval = MI.getOperand(4).getReg(); 11045 DebugLoc dl = MI.getDebugLoc(); 11046 11047 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB); 11048 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB); 11049 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB); 11050 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 11051 F->insert(It, loop1MBB); 11052 F->insert(It, loop2MBB); 11053 F->insert(It, midMBB); 11054 F->insert(It, exitMBB); 11055 exitMBB->splice(exitMBB->begin(), BB, 11056 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 11057 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 11058 11059 MachineRegisterInfo &RegInfo = F->getRegInfo(); 11060 const TargetRegisterClass *RC = 11061 is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 11062 const TargetRegisterClass *GPRC = &PPC::GPRCRegClass; 11063 11064 unsigned PtrReg = RegInfo.createVirtualRegister(RC); 11065 unsigned Shift1Reg = RegInfo.createVirtualRegister(GPRC); 11066 unsigned ShiftReg = 11067 isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC); 11068 unsigned NewVal2Reg = RegInfo.createVirtualRegister(GPRC); 11069 unsigned NewVal3Reg = RegInfo.createVirtualRegister(GPRC); 11070 unsigned OldVal2Reg = RegInfo.createVirtualRegister(GPRC); 11071 unsigned OldVal3Reg = RegInfo.createVirtualRegister(GPRC); 11072 unsigned MaskReg = RegInfo.createVirtualRegister(GPRC); 11073 unsigned Mask2Reg = RegInfo.createVirtualRegister(GPRC); 11074 unsigned Mask3Reg = RegInfo.createVirtualRegister(GPRC); 11075 unsigned Tmp2Reg = RegInfo.createVirtualRegister(GPRC); 11076 unsigned Tmp4Reg = RegInfo.createVirtualRegister(GPRC); 11077 unsigned TmpDestReg = RegInfo.createVirtualRegister(GPRC); 11078 unsigned Ptr1Reg; 11079 unsigned TmpReg = RegInfo.createVirtualRegister(GPRC); 11080 unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO; 11081 // thisMBB: 11082 // ... 11083 // fallthrough --> loopMBB 11084 BB->addSuccessor(loop1MBB); 11085 11086 // The 4-byte load must be aligned, while a char or short may be 11087 // anywhere in the word. Hence all this nasty bookkeeping code. 11088 // add ptr1, ptrA, ptrB [copy if ptrA==0] 11089 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27] 11090 // xori shift, shift1, 24 [16] 11091 // rlwinm ptr, ptr1, 0, 0, 29 11092 // slw newval2, newval, shift 11093 // slw oldval2, oldval,shift 11094 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535] 11095 // slw mask, mask2, shift 11096 // and newval3, newval2, mask 11097 // and oldval3, oldval2, mask 11098 // loop1MBB: 11099 // lwarx tmpDest, ptr 11100 // and tmp, tmpDest, mask 11101 // cmpw tmp, oldval3 11102 // bne- midMBB 11103 // loop2MBB: 11104 // andc tmp2, tmpDest, mask 11105 // or tmp4, tmp2, newval3 11106 // stwcx. tmp4, ptr 11107 // bne- loop1MBB 11108 // b exitBB 11109 // midMBB: 11110 // stwcx. tmpDest, ptr 11111 // exitBB: 11112 // srw dest, tmpDest, shift 11113 if (ptrA != ZeroReg) { 11114 Ptr1Reg = RegInfo.createVirtualRegister(RC); 11115 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg) 11116 .addReg(ptrA) 11117 .addReg(ptrB); 11118 } else { 11119 Ptr1Reg = ptrB; 11120 } 11121 11122 // We need use 32-bit subregister to avoid mismatch register class in 64-bit 11123 // mode. 11124 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg) 11125 .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0) 11126 .addImm(3) 11127 .addImm(27) 11128 .addImm(is8bit ? 28 : 27); 11129 if (!isLittleEndian) 11130 BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg) 11131 .addReg(Shift1Reg) 11132 .addImm(is8bit ? 24 : 16); 11133 if (is64bit) 11134 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg) 11135 .addReg(Ptr1Reg) 11136 .addImm(0) 11137 .addImm(61); 11138 else 11139 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg) 11140 .addReg(Ptr1Reg) 11141 .addImm(0) 11142 .addImm(0) 11143 .addImm(29); 11144 BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg) 11145 .addReg(newval) 11146 .addReg(ShiftReg); 11147 BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg) 11148 .addReg(oldval) 11149 .addReg(ShiftReg); 11150 if (is8bit) 11151 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255); 11152 else { 11153 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0); 11154 BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg) 11155 .addReg(Mask3Reg) 11156 .addImm(65535); 11157 } 11158 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg) 11159 .addReg(Mask2Reg) 11160 .addReg(ShiftReg); 11161 BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg) 11162 .addReg(NewVal2Reg) 11163 .addReg(MaskReg); 11164 BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg) 11165 .addReg(OldVal2Reg) 11166 .addReg(MaskReg); 11167 11168 BB = loop1MBB; 11169 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg) 11170 .addReg(ZeroReg) 11171 .addReg(PtrReg); 11172 BuildMI(BB, dl, TII->get(PPC::AND), TmpReg) 11173 .addReg(TmpDestReg) 11174 .addReg(MaskReg); 11175 BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0) 11176 .addReg(TmpReg) 11177 .addReg(OldVal3Reg); 11178 BuildMI(BB, dl, TII->get(PPC::BCC)) 11179 .addImm(PPC::PRED_NE) 11180 .addReg(PPC::CR0) 11181 .addMBB(midMBB); 11182 BB->addSuccessor(loop2MBB); 11183 BB->addSuccessor(midMBB); 11184 11185 BB = loop2MBB; 11186 BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg) 11187 .addReg(TmpDestReg) 11188 .addReg(MaskReg); 11189 BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg) 11190 .addReg(Tmp2Reg) 11191 .addReg(NewVal3Reg); 11192 BuildMI(BB, dl, TII->get(PPC::STWCX)) 11193 .addReg(Tmp4Reg) 11194 .addReg(ZeroReg) 11195 .addReg(PtrReg); 11196 BuildMI(BB, dl, TII->get(PPC::BCC)) 11197 .addImm(PPC::PRED_NE) 11198 .addReg(PPC::CR0) 11199 .addMBB(loop1MBB); 11200 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB); 11201 BB->addSuccessor(loop1MBB); 11202 BB->addSuccessor(exitMBB); 11203 11204 BB = midMBB; 11205 BuildMI(BB, dl, TII->get(PPC::STWCX)) 11206 .addReg(TmpDestReg) 11207 .addReg(ZeroReg) 11208 .addReg(PtrReg); 11209 BB->addSuccessor(exitMBB); 11210 11211 // exitMBB: 11212 // ... 11213 BB = exitMBB; 11214 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest) 11215 .addReg(TmpReg) 11216 .addReg(ShiftReg); 11217 } else if (MI.getOpcode() == PPC::FADDrtz) { 11218 // This pseudo performs an FADD with rounding mode temporarily forced 11219 // to round-to-zero. We emit this via custom inserter since the FPSCR 11220 // is not modeled at the SelectionDAG level. 11221 unsigned Dest = MI.getOperand(0).getReg(); 11222 unsigned Src1 = MI.getOperand(1).getReg(); 11223 unsigned Src2 = MI.getOperand(2).getReg(); 11224 DebugLoc dl = MI.getDebugLoc(); 11225 11226 MachineRegisterInfo &RegInfo = F->getRegInfo(); 11227 unsigned MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass); 11228 11229 // Save FPSCR value. 11230 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg); 11231 11232 // Set rounding mode to round-to-zero. 11233 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1)).addImm(31); 11234 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0)).addImm(30); 11235 11236 // Perform addition. 11237 BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest).addReg(Src1).addReg(Src2); 11238 11239 // Restore FPSCR value. 11240 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSFb)).addImm(1).addReg(MFFSReg); 11241 } else if (MI.getOpcode() == PPC::ANDIo_1_EQ_BIT || 11242 MI.getOpcode() == PPC::ANDIo_1_GT_BIT || 11243 MI.getOpcode() == PPC::ANDIo_1_EQ_BIT8 || 11244 MI.getOpcode() == PPC::ANDIo_1_GT_BIT8) { 11245 unsigned Opcode = (MI.getOpcode() == PPC::ANDIo_1_EQ_BIT8 || 11246 MI.getOpcode() == PPC::ANDIo_1_GT_BIT8) 11247 ? PPC::ANDIo8 11248 : PPC::ANDIo; 11249 bool isEQ = (MI.getOpcode() == PPC::ANDIo_1_EQ_BIT || 11250 MI.getOpcode() == PPC::ANDIo_1_EQ_BIT8); 11251 11252 MachineRegisterInfo &RegInfo = F->getRegInfo(); 11253 unsigned Dest = RegInfo.createVirtualRegister( 11254 Opcode == PPC::ANDIo ? &PPC::GPRCRegClass : &PPC::G8RCRegClass); 11255 11256 DebugLoc dl = MI.getDebugLoc(); 11257 BuildMI(*BB, MI, dl, TII->get(Opcode), Dest) 11258 .addReg(MI.getOperand(1).getReg()) 11259 .addImm(1); 11260 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), 11261 MI.getOperand(0).getReg()) 11262 .addReg(isEQ ? PPC::CR0EQ : PPC::CR0GT); 11263 } else if (MI.getOpcode() == PPC::TCHECK_RET) { 11264 DebugLoc Dl = MI.getDebugLoc(); 11265 MachineRegisterInfo &RegInfo = F->getRegInfo(); 11266 unsigned CRReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass); 11267 BuildMI(*BB, MI, Dl, TII->get(PPC::TCHECK), CRReg); 11268 return BB; 11269 } else if (MI.getOpcode() == PPC::SETRNDi) { 11270 DebugLoc dl = MI.getDebugLoc(); 11271 unsigned OldFPSCRReg = MI.getOperand(0).getReg(); 11272 11273 // Save FPSCR value. 11274 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg); 11275 11276 // The floating point rounding mode is in the bits 62:63 of FPCSR, and has 11277 // the following settings: 11278 // 00 Round to nearest 11279 // 01 Round to 0 11280 // 10 Round to +inf 11281 // 11 Round to -inf 11282 11283 // When the operand is immediate, using the two least significant bits of 11284 // the immediate to set the bits 62:63 of FPSCR. 11285 unsigned Mode = MI.getOperand(1).getImm(); 11286 BuildMI(*BB, MI, dl, TII->get((Mode & 1) ? PPC::MTFSB1 : PPC::MTFSB0)) 11287 .addImm(31); 11288 11289 BuildMI(*BB, MI, dl, TII->get((Mode & 2) ? PPC::MTFSB1 : PPC::MTFSB0)) 11290 .addImm(30); 11291 } else if (MI.getOpcode() == PPC::SETRND) { 11292 DebugLoc dl = MI.getDebugLoc(); 11293 11294 // Copy register from F8RCRegClass::SrcReg to G8RCRegClass::DestReg 11295 // or copy register from G8RCRegClass::SrcReg to F8RCRegClass::DestReg. 11296 // If the target doesn't have DirectMove, we should use stack to do the 11297 // conversion, because the target doesn't have the instructions like mtvsrd 11298 // or mfvsrd to do this conversion directly. 11299 auto copyRegFromG8RCOrF8RC = [&] (unsigned DestReg, unsigned SrcReg) { 11300 if (Subtarget.hasDirectMove()) { 11301 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), DestReg) 11302 .addReg(SrcReg); 11303 } else { 11304 // Use stack to do the register copy. 11305 unsigned StoreOp = PPC::STD, LoadOp = PPC::LFD; 11306 MachineRegisterInfo &RegInfo = F->getRegInfo(); 11307 const TargetRegisterClass *RC = RegInfo.getRegClass(SrcReg); 11308 if (RC == &PPC::F8RCRegClass) { 11309 // Copy register from F8RCRegClass to G8RCRegclass. 11310 assert((RegInfo.getRegClass(DestReg) == &PPC::G8RCRegClass) && 11311 "Unsupported RegClass."); 11312 11313 StoreOp = PPC::STFD; 11314 LoadOp = PPC::LD; 11315 } else { 11316 // Copy register from G8RCRegClass to F8RCRegclass. 11317 assert((RegInfo.getRegClass(SrcReg) == &PPC::G8RCRegClass) && 11318 (RegInfo.getRegClass(DestReg) == &PPC::F8RCRegClass) && 11319 "Unsupported RegClass."); 11320 } 11321 11322 MachineFrameInfo &MFI = F->getFrameInfo(); 11323 int FrameIdx = MFI.CreateStackObject(8, 8, false); 11324 11325 MachineMemOperand *MMOStore = F->getMachineMemOperand( 11326 MachinePointerInfo::getFixedStack(*F, FrameIdx, 0), 11327 MachineMemOperand::MOStore, MFI.getObjectSize(FrameIdx), 11328 MFI.getObjectAlignment(FrameIdx)); 11329 11330 // Store the SrcReg into the stack. 11331 BuildMI(*BB, MI, dl, TII->get(StoreOp)) 11332 .addReg(SrcReg) 11333 .addImm(0) 11334 .addFrameIndex(FrameIdx) 11335 .addMemOperand(MMOStore); 11336 11337 MachineMemOperand *MMOLoad = F->getMachineMemOperand( 11338 MachinePointerInfo::getFixedStack(*F, FrameIdx, 0), 11339 MachineMemOperand::MOLoad, MFI.getObjectSize(FrameIdx), 11340 MFI.getObjectAlignment(FrameIdx)); 11341 11342 // Load from the stack where SrcReg is stored, and save to DestReg, 11343 // so we have done the RegClass conversion from RegClass::SrcReg to 11344 // RegClass::DestReg. 11345 BuildMI(*BB, MI, dl, TII->get(LoadOp), DestReg) 11346 .addImm(0) 11347 .addFrameIndex(FrameIdx) 11348 .addMemOperand(MMOLoad); 11349 } 11350 }; 11351 11352 unsigned OldFPSCRReg = MI.getOperand(0).getReg(); 11353 11354 // Save FPSCR value. 11355 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg); 11356 11357 // When the operand is gprc register, use two least significant bits of the 11358 // register and mtfsf instruction to set the bits 62:63 of FPSCR. 11359 // 11360 // copy OldFPSCRTmpReg, OldFPSCRReg 11361 // (INSERT_SUBREG ExtSrcReg, (IMPLICIT_DEF ImDefReg), SrcOp, 1) 11362 // rldimi NewFPSCRTmpReg, ExtSrcReg, OldFPSCRReg, 0, 62 11363 // copy NewFPSCRReg, NewFPSCRTmpReg 11364 // mtfsf 255, NewFPSCRReg 11365 MachineOperand SrcOp = MI.getOperand(1); 11366 MachineRegisterInfo &RegInfo = F->getRegInfo(); 11367 unsigned OldFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 11368 11369 copyRegFromG8RCOrF8RC(OldFPSCRTmpReg, OldFPSCRReg); 11370 11371 unsigned ImDefReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 11372 unsigned ExtSrcReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 11373 11374 // The first operand of INSERT_SUBREG should be a register which has 11375 // subregisters, we only care about its RegClass, so we should use an 11376 // IMPLICIT_DEF register. 11377 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::IMPLICIT_DEF), ImDefReg); 11378 BuildMI(*BB, MI, dl, TII->get(PPC::INSERT_SUBREG), ExtSrcReg) 11379 .addReg(ImDefReg) 11380 .add(SrcOp) 11381 .addImm(1); 11382 11383 unsigned NewFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 11384 BuildMI(*BB, MI, dl, TII->get(PPC::RLDIMI), NewFPSCRTmpReg) 11385 .addReg(OldFPSCRTmpReg) 11386 .addReg(ExtSrcReg) 11387 .addImm(0) 11388 .addImm(62); 11389 11390 unsigned NewFPSCRReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass); 11391 copyRegFromG8RCOrF8RC(NewFPSCRReg, NewFPSCRTmpReg); 11392 11393 // The mask 255 means that put the 32:63 bits of NewFPSCRReg to the 32:63 11394 // bits of FPSCR. 11395 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSF)) 11396 .addImm(255) 11397 .addReg(NewFPSCRReg) 11398 .addImm(0) 11399 .addImm(0); 11400 } else { 11401 llvm_unreachable("Unexpected instr type to insert"); 11402 } 11403 11404 MI.eraseFromParent(); // The pseudo instruction is gone now. 11405 return BB; 11406 } 11407 11408 //===----------------------------------------------------------------------===// 11409 // Target Optimization Hooks 11410 //===----------------------------------------------------------------------===// 11411 11412 static int getEstimateRefinementSteps(EVT VT, const PPCSubtarget &Subtarget) { 11413 // For the estimates, convergence is quadratic, so we essentially double the 11414 // number of digits correct after every iteration. For both FRE and FRSQRTE, 11415 // the minimum architected relative accuracy is 2^-5. When hasRecipPrec(), 11416 // this is 2^-14. IEEE float has 23 digits and double has 52 digits. 11417 int RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3; 11418 if (VT.getScalarType() == MVT::f64) 11419 RefinementSteps++; 11420 return RefinementSteps; 11421 } 11422 11423 SDValue PPCTargetLowering::getSqrtEstimate(SDValue Operand, SelectionDAG &DAG, 11424 int Enabled, int &RefinementSteps, 11425 bool &UseOneConstNR, 11426 bool Reciprocal) const { 11427 EVT VT = Operand.getValueType(); 11428 if ((VT == MVT::f32 && Subtarget.hasFRSQRTES()) || 11429 (VT == MVT::f64 && Subtarget.hasFRSQRTE()) || 11430 (VT == MVT::v4f32 && Subtarget.hasAltivec()) || 11431 (VT == MVT::v2f64 && Subtarget.hasVSX()) || 11432 (VT == MVT::v4f32 && Subtarget.hasQPX()) || 11433 (VT == MVT::v4f64 && Subtarget.hasQPX())) { 11434 if (RefinementSteps == ReciprocalEstimate::Unspecified) 11435 RefinementSteps = getEstimateRefinementSteps(VT, Subtarget); 11436 11437 // The Newton-Raphson computation with a single constant does not provide 11438 // enough accuracy on some CPUs. 11439 UseOneConstNR = !Subtarget.needsTwoConstNR(); 11440 return DAG.getNode(PPCISD::FRSQRTE, SDLoc(Operand), VT, Operand); 11441 } 11442 return SDValue(); 11443 } 11444 11445 SDValue PPCTargetLowering::getRecipEstimate(SDValue Operand, SelectionDAG &DAG, 11446 int Enabled, 11447 int &RefinementSteps) const { 11448 EVT VT = Operand.getValueType(); 11449 if ((VT == MVT::f32 && Subtarget.hasFRES()) || 11450 (VT == MVT::f64 && Subtarget.hasFRE()) || 11451 (VT == MVT::v4f32 && Subtarget.hasAltivec()) || 11452 (VT == MVT::v2f64 && Subtarget.hasVSX()) || 11453 (VT == MVT::v4f32 && Subtarget.hasQPX()) || 11454 (VT == MVT::v4f64 && Subtarget.hasQPX())) { 11455 if (RefinementSteps == ReciprocalEstimate::Unspecified) 11456 RefinementSteps = getEstimateRefinementSteps(VT, Subtarget); 11457 return DAG.getNode(PPCISD::FRE, SDLoc(Operand), VT, Operand); 11458 } 11459 return SDValue(); 11460 } 11461 11462 unsigned PPCTargetLowering::combineRepeatedFPDivisors() const { 11463 // Note: This functionality is used only when unsafe-fp-math is enabled, and 11464 // on cores with reciprocal estimates (which are used when unsafe-fp-math is 11465 // enabled for division), this functionality is redundant with the default 11466 // combiner logic (once the division -> reciprocal/multiply transformation 11467 // has taken place). As a result, this matters more for older cores than for 11468 // newer ones. 11469 11470 // Combine multiple FDIVs with the same divisor into multiple FMULs by the 11471 // reciprocal if there are two or more FDIVs (for embedded cores with only 11472 // one FP pipeline) for three or more FDIVs (for generic OOO cores). 11473 switch (Subtarget.getDarwinDirective()) { 11474 default: 11475 return 3; 11476 case PPC::DIR_440: 11477 case PPC::DIR_A2: 11478 case PPC::DIR_E500: 11479 case PPC::DIR_E500mc: 11480 case PPC::DIR_E5500: 11481 return 2; 11482 } 11483 } 11484 11485 // isConsecutiveLSLoc needs to work even if all adds have not yet been 11486 // collapsed, and so we need to look through chains of them. 11487 static void getBaseWithConstantOffset(SDValue Loc, SDValue &Base, 11488 int64_t& Offset, SelectionDAG &DAG) { 11489 if (DAG.isBaseWithConstantOffset(Loc)) { 11490 Base = Loc.getOperand(0); 11491 Offset += cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue(); 11492 11493 // The base might itself be a base plus an offset, and if so, accumulate 11494 // that as well. 11495 getBaseWithConstantOffset(Loc.getOperand(0), Base, Offset, DAG); 11496 } 11497 } 11498 11499 static bool isConsecutiveLSLoc(SDValue Loc, EVT VT, LSBaseSDNode *Base, 11500 unsigned Bytes, int Dist, 11501 SelectionDAG &DAG) { 11502 if (VT.getSizeInBits() / 8 != Bytes) 11503 return false; 11504 11505 SDValue BaseLoc = Base->getBasePtr(); 11506 if (Loc.getOpcode() == ISD::FrameIndex) { 11507 if (BaseLoc.getOpcode() != ISD::FrameIndex) 11508 return false; 11509 const MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 11510 int FI = cast<FrameIndexSDNode>(Loc)->getIndex(); 11511 int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex(); 11512 int FS = MFI.getObjectSize(FI); 11513 int BFS = MFI.getObjectSize(BFI); 11514 if (FS != BFS || FS != (int)Bytes) return false; 11515 return MFI.getObjectOffset(FI) == (MFI.getObjectOffset(BFI) + Dist*Bytes); 11516 } 11517 11518 SDValue Base1 = Loc, Base2 = BaseLoc; 11519 int64_t Offset1 = 0, Offset2 = 0; 11520 getBaseWithConstantOffset(Loc, Base1, Offset1, DAG); 11521 getBaseWithConstantOffset(BaseLoc, Base2, Offset2, DAG); 11522 if (Base1 == Base2 && Offset1 == (Offset2 + Dist * Bytes)) 11523 return true; 11524 11525 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11526 const GlobalValue *GV1 = nullptr; 11527 const GlobalValue *GV2 = nullptr; 11528 Offset1 = 0; 11529 Offset2 = 0; 11530 bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1); 11531 bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2); 11532 if (isGA1 && isGA2 && GV1 == GV2) 11533 return Offset1 == (Offset2 + Dist*Bytes); 11534 return false; 11535 } 11536 11537 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does 11538 // not enforce equality of the chain operands. 11539 static bool isConsecutiveLS(SDNode *N, LSBaseSDNode *Base, 11540 unsigned Bytes, int Dist, 11541 SelectionDAG &DAG) { 11542 if (LSBaseSDNode *LS = dyn_cast<LSBaseSDNode>(N)) { 11543 EVT VT = LS->getMemoryVT(); 11544 SDValue Loc = LS->getBasePtr(); 11545 return isConsecutiveLSLoc(Loc, VT, Base, Bytes, Dist, DAG); 11546 } 11547 11548 if (N->getOpcode() == ISD::INTRINSIC_W_CHAIN) { 11549 EVT VT; 11550 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 11551 default: return false; 11552 case Intrinsic::ppc_qpx_qvlfd: 11553 case Intrinsic::ppc_qpx_qvlfda: 11554 VT = MVT::v4f64; 11555 break; 11556 case Intrinsic::ppc_qpx_qvlfs: 11557 case Intrinsic::ppc_qpx_qvlfsa: 11558 VT = MVT::v4f32; 11559 break; 11560 case Intrinsic::ppc_qpx_qvlfcd: 11561 case Intrinsic::ppc_qpx_qvlfcda: 11562 VT = MVT::v2f64; 11563 break; 11564 case Intrinsic::ppc_qpx_qvlfcs: 11565 case Intrinsic::ppc_qpx_qvlfcsa: 11566 VT = MVT::v2f32; 11567 break; 11568 case Intrinsic::ppc_qpx_qvlfiwa: 11569 case Intrinsic::ppc_qpx_qvlfiwz: 11570 case Intrinsic::ppc_altivec_lvx: 11571 case Intrinsic::ppc_altivec_lvxl: 11572 case Intrinsic::ppc_vsx_lxvw4x: 11573 case Intrinsic::ppc_vsx_lxvw4x_be: 11574 VT = MVT::v4i32; 11575 break; 11576 case Intrinsic::ppc_vsx_lxvd2x: 11577 case Intrinsic::ppc_vsx_lxvd2x_be: 11578 VT = MVT::v2f64; 11579 break; 11580 case Intrinsic::ppc_altivec_lvebx: 11581 VT = MVT::i8; 11582 break; 11583 case Intrinsic::ppc_altivec_lvehx: 11584 VT = MVT::i16; 11585 break; 11586 case Intrinsic::ppc_altivec_lvewx: 11587 VT = MVT::i32; 11588 break; 11589 } 11590 11591 return isConsecutiveLSLoc(N->getOperand(2), VT, Base, Bytes, Dist, DAG); 11592 } 11593 11594 if (N->getOpcode() == ISD::INTRINSIC_VOID) { 11595 EVT VT; 11596 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 11597 default: return false; 11598 case Intrinsic::ppc_qpx_qvstfd: 11599 case Intrinsic::ppc_qpx_qvstfda: 11600 VT = MVT::v4f64; 11601 break; 11602 case Intrinsic::ppc_qpx_qvstfs: 11603 case Intrinsic::ppc_qpx_qvstfsa: 11604 VT = MVT::v4f32; 11605 break; 11606 case Intrinsic::ppc_qpx_qvstfcd: 11607 case Intrinsic::ppc_qpx_qvstfcda: 11608 VT = MVT::v2f64; 11609 break; 11610 case Intrinsic::ppc_qpx_qvstfcs: 11611 case Intrinsic::ppc_qpx_qvstfcsa: 11612 VT = MVT::v2f32; 11613 break; 11614 case Intrinsic::ppc_qpx_qvstfiw: 11615 case Intrinsic::ppc_qpx_qvstfiwa: 11616 case Intrinsic::ppc_altivec_stvx: 11617 case Intrinsic::ppc_altivec_stvxl: 11618 case Intrinsic::ppc_vsx_stxvw4x: 11619 VT = MVT::v4i32; 11620 break; 11621 case Intrinsic::ppc_vsx_stxvd2x: 11622 VT = MVT::v2f64; 11623 break; 11624 case Intrinsic::ppc_vsx_stxvw4x_be: 11625 VT = MVT::v4i32; 11626 break; 11627 case Intrinsic::ppc_vsx_stxvd2x_be: 11628 VT = MVT::v2f64; 11629 break; 11630 case Intrinsic::ppc_altivec_stvebx: 11631 VT = MVT::i8; 11632 break; 11633 case Intrinsic::ppc_altivec_stvehx: 11634 VT = MVT::i16; 11635 break; 11636 case Intrinsic::ppc_altivec_stvewx: 11637 VT = MVT::i32; 11638 break; 11639 } 11640 11641 return isConsecutiveLSLoc(N->getOperand(3), VT, Base, Bytes, Dist, DAG); 11642 } 11643 11644 return false; 11645 } 11646 11647 // Return true is there is a nearyby consecutive load to the one provided 11648 // (regardless of alignment). We search up and down the chain, looking though 11649 // token factors and other loads (but nothing else). As a result, a true result 11650 // indicates that it is safe to create a new consecutive load adjacent to the 11651 // load provided. 11652 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) { 11653 SDValue Chain = LD->getChain(); 11654 EVT VT = LD->getMemoryVT(); 11655 11656 SmallSet<SDNode *, 16> LoadRoots; 11657 SmallVector<SDNode *, 8> Queue(1, Chain.getNode()); 11658 SmallSet<SDNode *, 16> Visited; 11659 11660 // First, search up the chain, branching to follow all token-factor operands. 11661 // If we find a consecutive load, then we're done, otherwise, record all 11662 // nodes just above the top-level loads and token factors. 11663 while (!Queue.empty()) { 11664 SDNode *ChainNext = Queue.pop_back_val(); 11665 if (!Visited.insert(ChainNext).second) 11666 continue; 11667 11668 if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(ChainNext)) { 11669 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG)) 11670 return true; 11671 11672 if (!Visited.count(ChainLD->getChain().getNode())) 11673 Queue.push_back(ChainLD->getChain().getNode()); 11674 } else if (ChainNext->getOpcode() == ISD::TokenFactor) { 11675 for (const SDUse &O : ChainNext->ops()) 11676 if (!Visited.count(O.getNode())) 11677 Queue.push_back(O.getNode()); 11678 } else 11679 LoadRoots.insert(ChainNext); 11680 } 11681 11682 // Second, search down the chain, starting from the top-level nodes recorded 11683 // in the first phase. These top-level nodes are the nodes just above all 11684 // loads and token factors. Starting with their uses, recursively look though 11685 // all loads (just the chain uses) and token factors to find a consecutive 11686 // load. 11687 Visited.clear(); 11688 Queue.clear(); 11689 11690 for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(), 11691 IE = LoadRoots.end(); I != IE; ++I) { 11692 Queue.push_back(*I); 11693 11694 while (!Queue.empty()) { 11695 SDNode *LoadRoot = Queue.pop_back_val(); 11696 if (!Visited.insert(LoadRoot).second) 11697 continue; 11698 11699 if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(LoadRoot)) 11700 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG)) 11701 return true; 11702 11703 for (SDNode::use_iterator UI = LoadRoot->use_begin(), 11704 UE = LoadRoot->use_end(); UI != UE; ++UI) 11705 if (((isa<MemSDNode>(*UI) && 11706 cast<MemSDNode>(*UI)->getChain().getNode() == LoadRoot) || 11707 UI->getOpcode() == ISD::TokenFactor) && !Visited.count(*UI)) 11708 Queue.push_back(*UI); 11709 } 11710 } 11711 11712 return false; 11713 } 11714 11715 /// This function is called when we have proved that a SETCC node can be replaced 11716 /// by subtraction (and other supporting instructions) so that the result of 11717 /// comparison is kept in a GPR instead of CR. This function is purely for 11718 /// codegen purposes and has some flags to guide the codegen process. 11719 static SDValue generateEquivalentSub(SDNode *N, int Size, bool Complement, 11720 bool Swap, SDLoc &DL, SelectionDAG &DAG) { 11721 assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected."); 11722 11723 // Zero extend the operands to the largest legal integer. Originally, they 11724 // must be of a strictly smaller size. 11725 auto Op0 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(0), 11726 DAG.getConstant(Size, DL, MVT::i32)); 11727 auto Op1 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1), 11728 DAG.getConstant(Size, DL, MVT::i32)); 11729 11730 // Swap if needed. Depends on the condition code. 11731 if (Swap) 11732 std::swap(Op0, Op1); 11733 11734 // Subtract extended integers. 11735 auto SubNode = DAG.getNode(ISD::SUB, DL, MVT::i64, Op0, Op1); 11736 11737 // Move the sign bit to the least significant position and zero out the rest. 11738 // Now the least significant bit carries the result of original comparison. 11739 auto Shifted = DAG.getNode(ISD::SRL, DL, MVT::i64, SubNode, 11740 DAG.getConstant(Size - 1, DL, MVT::i32)); 11741 auto Final = Shifted; 11742 11743 // Complement the result if needed. Based on the condition code. 11744 if (Complement) 11745 Final = DAG.getNode(ISD::XOR, DL, MVT::i64, Shifted, 11746 DAG.getConstant(1, DL, MVT::i64)); 11747 11748 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Final); 11749 } 11750 11751 SDValue PPCTargetLowering::ConvertSETCCToSubtract(SDNode *N, 11752 DAGCombinerInfo &DCI) const { 11753 assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected."); 11754 11755 SelectionDAG &DAG = DCI.DAG; 11756 SDLoc DL(N); 11757 11758 // Size of integers being compared has a critical role in the following 11759 // analysis, so we prefer to do this when all types are legal. 11760 if (!DCI.isAfterLegalizeDAG()) 11761 return SDValue(); 11762 11763 // If all users of SETCC extend its value to a legal integer type 11764 // then we replace SETCC with a subtraction 11765 for (SDNode::use_iterator UI = N->use_begin(), 11766 UE = N->use_end(); UI != UE; ++UI) { 11767 if (UI->getOpcode() != ISD::ZERO_EXTEND) 11768 return SDValue(); 11769 } 11770 11771 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 11772 auto OpSize = N->getOperand(0).getValueSizeInBits(); 11773 11774 unsigned Size = DAG.getDataLayout().getLargestLegalIntTypeSizeInBits(); 11775 11776 if (OpSize < Size) { 11777 switch (CC) { 11778 default: break; 11779 case ISD::SETULT: 11780 return generateEquivalentSub(N, Size, false, false, DL, DAG); 11781 case ISD::SETULE: 11782 return generateEquivalentSub(N, Size, true, true, DL, DAG); 11783 case ISD::SETUGT: 11784 return generateEquivalentSub(N, Size, false, true, DL, DAG); 11785 case ISD::SETUGE: 11786 return generateEquivalentSub(N, Size, true, false, DL, DAG); 11787 } 11788 } 11789 11790 return SDValue(); 11791 } 11792 11793 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N, 11794 DAGCombinerInfo &DCI) const { 11795 SelectionDAG &DAG = DCI.DAG; 11796 SDLoc dl(N); 11797 11798 assert(Subtarget.useCRBits() && "Expecting to be tracking CR bits"); 11799 // If we're tracking CR bits, we need to be careful that we don't have: 11800 // trunc(binary-ops(zext(x), zext(y))) 11801 // or 11802 // trunc(binary-ops(binary-ops(zext(x), zext(y)), ...) 11803 // such that we're unnecessarily moving things into GPRs when it would be 11804 // better to keep them in CR bits. 11805 11806 // Note that trunc here can be an actual i1 trunc, or can be the effective 11807 // truncation that comes from a setcc or select_cc. 11808 if (N->getOpcode() == ISD::TRUNCATE && 11809 N->getValueType(0) != MVT::i1) 11810 return SDValue(); 11811 11812 if (N->getOperand(0).getValueType() != MVT::i32 && 11813 N->getOperand(0).getValueType() != MVT::i64) 11814 return SDValue(); 11815 11816 if (N->getOpcode() == ISD::SETCC || 11817 N->getOpcode() == ISD::SELECT_CC) { 11818 // If we're looking at a comparison, then we need to make sure that the 11819 // high bits (all except for the first) don't matter the result. 11820 ISD::CondCode CC = 11821 cast<CondCodeSDNode>(N->getOperand( 11822 N->getOpcode() == ISD::SETCC ? 2 : 4))->get(); 11823 unsigned OpBits = N->getOperand(0).getValueSizeInBits(); 11824 11825 if (ISD::isSignedIntSetCC(CC)) { 11826 if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits || 11827 DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits) 11828 return SDValue(); 11829 } else if (ISD::isUnsignedIntSetCC(CC)) { 11830 if (!DAG.MaskedValueIsZero(N->getOperand(0), 11831 APInt::getHighBitsSet(OpBits, OpBits-1)) || 11832 !DAG.MaskedValueIsZero(N->getOperand(1), 11833 APInt::getHighBitsSet(OpBits, OpBits-1))) 11834 return (N->getOpcode() == ISD::SETCC ? ConvertSETCCToSubtract(N, DCI) 11835 : SDValue()); 11836 } else { 11837 // This is neither a signed nor an unsigned comparison, just make sure 11838 // that the high bits are equal. 11839 KnownBits Op1Known = DAG.computeKnownBits(N->getOperand(0)); 11840 KnownBits Op2Known = DAG.computeKnownBits(N->getOperand(1)); 11841 11842 // We don't really care about what is known about the first bit (if 11843 // anything), so clear it in all masks prior to comparing them. 11844 Op1Known.Zero.clearBit(0); Op1Known.One.clearBit(0); 11845 Op2Known.Zero.clearBit(0); Op2Known.One.clearBit(0); 11846 11847 if (Op1Known.Zero != Op2Known.Zero || Op1Known.One != Op2Known.One) 11848 return SDValue(); 11849 } 11850 } 11851 11852 // We now know that the higher-order bits are irrelevant, we just need to 11853 // make sure that all of the intermediate operations are bit operations, and 11854 // all inputs are extensions. 11855 if (N->getOperand(0).getOpcode() != ISD::AND && 11856 N->getOperand(0).getOpcode() != ISD::OR && 11857 N->getOperand(0).getOpcode() != ISD::XOR && 11858 N->getOperand(0).getOpcode() != ISD::SELECT && 11859 N->getOperand(0).getOpcode() != ISD::SELECT_CC && 11860 N->getOperand(0).getOpcode() != ISD::TRUNCATE && 11861 N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND && 11862 N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND && 11863 N->getOperand(0).getOpcode() != ISD::ANY_EXTEND) 11864 return SDValue(); 11865 11866 if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) && 11867 N->getOperand(1).getOpcode() != ISD::AND && 11868 N->getOperand(1).getOpcode() != ISD::OR && 11869 N->getOperand(1).getOpcode() != ISD::XOR && 11870 N->getOperand(1).getOpcode() != ISD::SELECT && 11871 N->getOperand(1).getOpcode() != ISD::SELECT_CC && 11872 N->getOperand(1).getOpcode() != ISD::TRUNCATE && 11873 N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND && 11874 N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND && 11875 N->getOperand(1).getOpcode() != ISD::ANY_EXTEND) 11876 return SDValue(); 11877 11878 SmallVector<SDValue, 4> Inputs; 11879 SmallVector<SDValue, 8> BinOps, PromOps; 11880 SmallPtrSet<SDNode *, 16> Visited; 11881 11882 for (unsigned i = 0; i < 2; ++i) { 11883 if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND || 11884 N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND || 11885 N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) && 11886 N->getOperand(i).getOperand(0).getValueType() == MVT::i1) || 11887 isa<ConstantSDNode>(N->getOperand(i))) 11888 Inputs.push_back(N->getOperand(i)); 11889 else 11890 BinOps.push_back(N->getOperand(i)); 11891 11892 if (N->getOpcode() == ISD::TRUNCATE) 11893 break; 11894 } 11895 11896 // Visit all inputs, collect all binary operations (and, or, xor and 11897 // select) that are all fed by extensions. 11898 while (!BinOps.empty()) { 11899 SDValue BinOp = BinOps.back(); 11900 BinOps.pop_back(); 11901 11902 if (!Visited.insert(BinOp.getNode()).second) 11903 continue; 11904 11905 PromOps.push_back(BinOp); 11906 11907 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) { 11908 // The condition of the select is not promoted. 11909 if (BinOp.getOpcode() == ISD::SELECT && i == 0) 11910 continue; 11911 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3) 11912 continue; 11913 11914 if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND || 11915 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND || 11916 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) && 11917 BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) || 11918 isa<ConstantSDNode>(BinOp.getOperand(i))) { 11919 Inputs.push_back(BinOp.getOperand(i)); 11920 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND || 11921 BinOp.getOperand(i).getOpcode() == ISD::OR || 11922 BinOp.getOperand(i).getOpcode() == ISD::XOR || 11923 BinOp.getOperand(i).getOpcode() == ISD::SELECT || 11924 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC || 11925 BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE || 11926 BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND || 11927 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND || 11928 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) { 11929 BinOps.push_back(BinOp.getOperand(i)); 11930 } else { 11931 // We have an input that is not an extension or another binary 11932 // operation; we'll abort this transformation. 11933 return SDValue(); 11934 } 11935 } 11936 } 11937 11938 // Make sure that this is a self-contained cluster of operations (which 11939 // is not quite the same thing as saying that everything has only one 11940 // use). 11941 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 11942 if (isa<ConstantSDNode>(Inputs[i])) 11943 continue; 11944 11945 for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(), 11946 UE = Inputs[i].getNode()->use_end(); 11947 UI != UE; ++UI) { 11948 SDNode *User = *UI; 11949 if (User != N && !Visited.count(User)) 11950 return SDValue(); 11951 11952 // Make sure that we're not going to promote the non-output-value 11953 // operand(s) or SELECT or SELECT_CC. 11954 // FIXME: Although we could sometimes handle this, and it does occur in 11955 // practice that one of the condition inputs to the select is also one of 11956 // the outputs, we currently can't deal with this. 11957 if (User->getOpcode() == ISD::SELECT) { 11958 if (User->getOperand(0) == Inputs[i]) 11959 return SDValue(); 11960 } else if (User->getOpcode() == ISD::SELECT_CC) { 11961 if (User->getOperand(0) == Inputs[i] || 11962 User->getOperand(1) == Inputs[i]) 11963 return SDValue(); 11964 } 11965 } 11966 } 11967 11968 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) { 11969 for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(), 11970 UE = PromOps[i].getNode()->use_end(); 11971 UI != UE; ++UI) { 11972 SDNode *User = *UI; 11973 if (User != N && !Visited.count(User)) 11974 return SDValue(); 11975 11976 // Make sure that we're not going to promote the non-output-value 11977 // operand(s) or SELECT or SELECT_CC. 11978 // FIXME: Although we could sometimes handle this, and it does occur in 11979 // practice that one of the condition inputs to the select is also one of 11980 // the outputs, we currently can't deal with this. 11981 if (User->getOpcode() == ISD::SELECT) { 11982 if (User->getOperand(0) == PromOps[i]) 11983 return SDValue(); 11984 } else if (User->getOpcode() == ISD::SELECT_CC) { 11985 if (User->getOperand(0) == PromOps[i] || 11986 User->getOperand(1) == PromOps[i]) 11987 return SDValue(); 11988 } 11989 } 11990 } 11991 11992 // Replace all inputs with the extension operand. 11993 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 11994 // Constants may have users outside the cluster of to-be-promoted nodes, 11995 // and so we need to replace those as we do the promotions. 11996 if (isa<ConstantSDNode>(Inputs[i])) 11997 continue; 11998 else 11999 DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0)); 12000 } 12001 12002 std::list<HandleSDNode> PromOpHandles; 12003 for (auto &PromOp : PromOps) 12004 PromOpHandles.emplace_back(PromOp); 12005 12006 // Replace all operations (these are all the same, but have a different 12007 // (i1) return type). DAG.getNode will validate that the types of 12008 // a binary operator match, so go through the list in reverse so that 12009 // we've likely promoted both operands first. Any intermediate truncations or 12010 // extensions disappear. 12011 while (!PromOpHandles.empty()) { 12012 SDValue PromOp = PromOpHandles.back().getValue(); 12013 PromOpHandles.pop_back(); 12014 12015 if (PromOp.getOpcode() == ISD::TRUNCATE || 12016 PromOp.getOpcode() == ISD::SIGN_EXTEND || 12017 PromOp.getOpcode() == ISD::ZERO_EXTEND || 12018 PromOp.getOpcode() == ISD::ANY_EXTEND) { 12019 if (!isa<ConstantSDNode>(PromOp.getOperand(0)) && 12020 PromOp.getOperand(0).getValueType() != MVT::i1) { 12021 // The operand is not yet ready (see comment below). 12022 PromOpHandles.emplace_front(PromOp); 12023 continue; 12024 } 12025 12026 SDValue RepValue = PromOp.getOperand(0); 12027 if (isa<ConstantSDNode>(RepValue)) 12028 RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue); 12029 12030 DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue); 12031 continue; 12032 } 12033 12034 unsigned C; 12035 switch (PromOp.getOpcode()) { 12036 default: C = 0; break; 12037 case ISD::SELECT: C = 1; break; 12038 case ISD::SELECT_CC: C = 2; break; 12039 } 12040 12041 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) && 12042 PromOp.getOperand(C).getValueType() != MVT::i1) || 12043 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) && 12044 PromOp.getOperand(C+1).getValueType() != MVT::i1)) { 12045 // The to-be-promoted operands of this node have not yet been 12046 // promoted (this should be rare because we're going through the 12047 // list backward, but if one of the operands has several users in 12048 // this cluster of to-be-promoted nodes, it is possible). 12049 PromOpHandles.emplace_front(PromOp); 12050 continue; 12051 } 12052 12053 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(), 12054 PromOp.getNode()->op_end()); 12055 12056 // If there are any constant inputs, make sure they're replaced now. 12057 for (unsigned i = 0; i < 2; ++i) 12058 if (isa<ConstantSDNode>(Ops[C+i])) 12059 Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]); 12060 12061 DAG.ReplaceAllUsesOfValueWith(PromOp, 12062 DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops)); 12063 } 12064 12065 // Now we're left with the initial truncation itself. 12066 if (N->getOpcode() == ISD::TRUNCATE) 12067 return N->getOperand(0); 12068 12069 // Otherwise, this is a comparison. The operands to be compared have just 12070 // changed type (to i1), but everything else is the same. 12071 return SDValue(N, 0); 12072 } 12073 12074 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N, 12075 DAGCombinerInfo &DCI) const { 12076 SelectionDAG &DAG = DCI.DAG; 12077 SDLoc dl(N); 12078 12079 // If we're tracking CR bits, we need to be careful that we don't have: 12080 // zext(binary-ops(trunc(x), trunc(y))) 12081 // or 12082 // zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...) 12083 // such that we're unnecessarily moving things into CR bits that can more 12084 // efficiently stay in GPRs. Note that if we're not certain that the high 12085 // bits are set as required by the final extension, we still may need to do 12086 // some masking to get the proper behavior. 12087 12088 // This same functionality is important on PPC64 when dealing with 12089 // 32-to-64-bit extensions; these occur often when 32-bit values are used as 12090 // the return values of functions. Because it is so similar, it is handled 12091 // here as well. 12092 12093 if (N->getValueType(0) != MVT::i32 && 12094 N->getValueType(0) != MVT::i64) 12095 return SDValue(); 12096 12097 if (!((N->getOperand(0).getValueType() == MVT::i1 && Subtarget.useCRBits()) || 12098 (N->getOperand(0).getValueType() == MVT::i32 && Subtarget.isPPC64()))) 12099 return SDValue(); 12100 12101 if (N->getOperand(0).getOpcode() != ISD::AND && 12102 N->getOperand(0).getOpcode() != ISD::OR && 12103 N->getOperand(0).getOpcode() != ISD::XOR && 12104 N->getOperand(0).getOpcode() != ISD::SELECT && 12105 N->getOperand(0).getOpcode() != ISD::SELECT_CC) 12106 return SDValue(); 12107 12108 SmallVector<SDValue, 4> Inputs; 12109 SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps; 12110 SmallPtrSet<SDNode *, 16> Visited; 12111 12112 // Visit all inputs, collect all binary operations (and, or, xor and 12113 // select) that are all fed by truncations. 12114 while (!BinOps.empty()) { 12115 SDValue BinOp = BinOps.back(); 12116 BinOps.pop_back(); 12117 12118 if (!Visited.insert(BinOp.getNode()).second) 12119 continue; 12120 12121 PromOps.push_back(BinOp); 12122 12123 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) { 12124 // The condition of the select is not promoted. 12125 if (BinOp.getOpcode() == ISD::SELECT && i == 0) 12126 continue; 12127 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3) 12128 continue; 12129 12130 if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE || 12131 isa<ConstantSDNode>(BinOp.getOperand(i))) { 12132 Inputs.push_back(BinOp.getOperand(i)); 12133 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND || 12134 BinOp.getOperand(i).getOpcode() == ISD::OR || 12135 BinOp.getOperand(i).getOpcode() == ISD::XOR || 12136 BinOp.getOperand(i).getOpcode() == ISD::SELECT || 12137 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) { 12138 BinOps.push_back(BinOp.getOperand(i)); 12139 } else { 12140 // We have an input that is not a truncation or another binary 12141 // operation; we'll abort this transformation. 12142 return SDValue(); 12143 } 12144 } 12145 } 12146 12147 // The operands of a select that must be truncated when the select is 12148 // promoted because the operand is actually part of the to-be-promoted set. 12149 DenseMap<SDNode *, EVT> SelectTruncOp[2]; 12150 12151 // Make sure that this is a self-contained cluster of operations (which 12152 // is not quite the same thing as saying that everything has only one 12153 // use). 12154 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 12155 if (isa<ConstantSDNode>(Inputs[i])) 12156 continue; 12157 12158 for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(), 12159 UE = Inputs[i].getNode()->use_end(); 12160 UI != UE; ++UI) { 12161 SDNode *User = *UI; 12162 if (User != N && !Visited.count(User)) 12163 return SDValue(); 12164 12165 // If we're going to promote the non-output-value operand(s) or SELECT or 12166 // SELECT_CC, record them for truncation. 12167 if (User->getOpcode() == ISD::SELECT) { 12168 if (User->getOperand(0) == Inputs[i]) 12169 SelectTruncOp[0].insert(std::make_pair(User, 12170 User->getOperand(0).getValueType())); 12171 } else if (User->getOpcode() == ISD::SELECT_CC) { 12172 if (User->getOperand(0) == Inputs[i]) 12173 SelectTruncOp[0].insert(std::make_pair(User, 12174 User->getOperand(0).getValueType())); 12175 if (User->getOperand(1) == Inputs[i]) 12176 SelectTruncOp[1].insert(std::make_pair(User, 12177 User->getOperand(1).getValueType())); 12178 } 12179 } 12180 } 12181 12182 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) { 12183 for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(), 12184 UE = PromOps[i].getNode()->use_end(); 12185 UI != UE; ++UI) { 12186 SDNode *User = *UI; 12187 if (User != N && !Visited.count(User)) 12188 return SDValue(); 12189 12190 // If we're going to promote the non-output-value operand(s) or SELECT or 12191 // SELECT_CC, record them for truncation. 12192 if (User->getOpcode() == ISD::SELECT) { 12193 if (User->getOperand(0) == PromOps[i]) 12194 SelectTruncOp[0].insert(std::make_pair(User, 12195 User->getOperand(0).getValueType())); 12196 } else if (User->getOpcode() == ISD::SELECT_CC) { 12197 if (User->getOperand(0) == PromOps[i]) 12198 SelectTruncOp[0].insert(std::make_pair(User, 12199 User->getOperand(0).getValueType())); 12200 if (User->getOperand(1) == PromOps[i]) 12201 SelectTruncOp[1].insert(std::make_pair(User, 12202 User->getOperand(1).getValueType())); 12203 } 12204 } 12205 } 12206 12207 unsigned PromBits = N->getOperand(0).getValueSizeInBits(); 12208 bool ReallyNeedsExt = false; 12209 if (N->getOpcode() != ISD::ANY_EXTEND) { 12210 // If all of the inputs are not already sign/zero extended, then 12211 // we'll still need to do that at the end. 12212 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 12213 if (isa<ConstantSDNode>(Inputs[i])) 12214 continue; 12215 12216 unsigned OpBits = 12217 Inputs[i].getOperand(0).getValueSizeInBits(); 12218 assert(PromBits < OpBits && "Truncation not to a smaller bit count?"); 12219 12220 if ((N->getOpcode() == ISD::ZERO_EXTEND && 12221 !DAG.MaskedValueIsZero(Inputs[i].getOperand(0), 12222 APInt::getHighBitsSet(OpBits, 12223 OpBits-PromBits))) || 12224 (N->getOpcode() == ISD::SIGN_EXTEND && 12225 DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) < 12226 (OpBits-(PromBits-1)))) { 12227 ReallyNeedsExt = true; 12228 break; 12229 } 12230 } 12231 } 12232 12233 // Replace all inputs, either with the truncation operand, or a 12234 // truncation or extension to the final output type. 12235 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 12236 // Constant inputs need to be replaced with the to-be-promoted nodes that 12237 // use them because they might have users outside of the cluster of 12238 // promoted nodes. 12239 if (isa<ConstantSDNode>(Inputs[i])) 12240 continue; 12241 12242 SDValue InSrc = Inputs[i].getOperand(0); 12243 if (Inputs[i].getValueType() == N->getValueType(0)) 12244 DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc); 12245 else if (N->getOpcode() == ISD::SIGN_EXTEND) 12246 DAG.ReplaceAllUsesOfValueWith(Inputs[i], 12247 DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0))); 12248 else if (N->getOpcode() == ISD::ZERO_EXTEND) 12249 DAG.ReplaceAllUsesOfValueWith(Inputs[i], 12250 DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0))); 12251 else 12252 DAG.ReplaceAllUsesOfValueWith(Inputs[i], 12253 DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0))); 12254 } 12255 12256 std::list<HandleSDNode> PromOpHandles; 12257 for (auto &PromOp : PromOps) 12258 PromOpHandles.emplace_back(PromOp); 12259 12260 // Replace all operations (these are all the same, but have a different 12261 // (promoted) return type). DAG.getNode will validate that the types of 12262 // a binary operator match, so go through the list in reverse so that 12263 // we've likely promoted both operands first. 12264 while (!PromOpHandles.empty()) { 12265 SDValue PromOp = PromOpHandles.back().getValue(); 12266 PromOpHandles.pop_back(); 12267 12268 unsigned C; 12269 switch (PromOp.getOpcode()) { 12270 default: C = 0; break; 12271 case ISD::SELECT: C = 1; break; 12272 case ISD::SELECT_CC: C = 2; break; 12273 } 12274 12275 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) && 12276 PromOp.getOperand(C).getValueType() != N->getValueType(0)) || 12277 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) && 12278 PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) { 12279 // The to-be-promoted operands of this node have not yet been 12280 // promoted (this should be rare because we're going through the 12281 // list backward, but if one of the operands has several users in 12282 // this cluster of to-be-promoted nodes, it is possible). 12283 PromOpHandles.emplace_front(PromOp); 12284 continue; 12285 } 12286 12287 // For SELECT and SELECT_CC nodes, we do a similar check for any 12288 // to-be-promoted comparison inputs. 12289 if (PromOp.getOpcode() == ISD::SELECT || 12290 PromOp.getOpcode() == ISD::SELECT_CC) { 12291 if ((SelectTruncOp[0].count(PromOp.getNode()) && 12292 PromOp.getOperand(0).getValueType() != N->getValueType(0)) || 12293 (SelectTruncOp[1].count(PromOp.getNode()) && 12294 PromOp.getOperand(1).getValueType() != N->getValueType(0))) { 12295 PromOpHandles.emplace_front(PromOp); 12296 continue; 12297 } 12298 } 12299 12300 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(), 12301 PromOp.getNode()->op_end()); 12302 12303 // If this node has constant inputs, then they'll need to be promoted here. 12304 for (unsigned i = 0; i < 2; ++i) { 12305 if (!isa<ConstantSDNode>(Ops[C+i])) 12306 continue; 12307 if (Ops[C+i].getValueType() == N->getValueType(0)) 12308 continue; 12309 12310 if (N->getOpcode() == ISD::SIGN_EXTEND) 12311 Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); 12312 else if (N->getOpcode() == ISD::ZERO_EXTEND) 12313 Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); 12314 else 12315 Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); 12316 } 12317 12318 // If we've promoted the comparison inputs of a SELECT or SELECT_CC, 12319 // truncate them again to the original value type. 12320 if (PromOp.getOpcode() == ISD::SELECT || 12321 PromOp.getOpcode() == ISD::SELECT_CC) { 12322 auto SI0 = SelectTruncOp[0].find(PromOp.getNode()); 12323 if (SI0 != SelectTruncOp[0].end()) 12324 Ops[0] = DAG.getNode(ISD::TRUNCATE, dl, SI0->second, Ops[0]); 12325 auto SI1 = SelectTruncOp[1].find(PromOp.getNode()); 12326 if (SI1 != SelectTruncOp[1].end()) 12327 Ops[1] = DAG.getNode(ISD::TRUNCATE, dl, SI1->second, Ops[1]); 12328 } 12329 12330 DAG.ReplaceAllUsesOfValueWith(PromOp, 12331 DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops)); 12332 } 12333 12334 // Now we're left with the initial extension itself. 12335 if (!ReallyNeedsExt) 12336 return N->getOperand(0); 12337 12338 // To zero extend, just mask off everything except for the first bit (in the 12339 // i1 case). 12340 if (N->getOpcode() == ISD::ZERO_EXTEND) 12341 return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0), 12342 DAG.getConstant(APInt::getLowBitsSet( 12343 N->getValueSizeInBits(0), PromBits), 12344 dl, N->getValueType(0))); 12345 12346 assert(N->getOpcode() == ISD::SIGN_EXTEND && 12347 "Invalid extension type"); 12348 EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0), DAG.getDataLayout()); 12349 SDValue ShiftCst = 12350 DAG.getConstant(N->getValueSizeInBits(0) - PromBits, dl, ShiftAmountTy); 12351 return DAG.getNode( 12352 ISD::SRA, dl, N->getValueType(0), 12353 DAG.getNode(ISD::SHL, dl, N->getValueType(0), N->getOperand(0), ShiftCst), 12354 ShiftCst); 12355 } 12356 12357 SDValue PPCTargetLowering::combineSetCC(SDNode *N, 12358 DAGCombinerInfo &DCI) const { 12359 assert(N->getOpcode() == ISD::SETCC && 12360 "Should be called with a SETCC node"); 12361 12362 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 12363 if (CC == ISD::SETNE || CC == ISD::SETEQ) { 12364 SDValue LHS = N->getOperand(0); 12365 SDValue RHS = N->getOperand(1); 12366 12367 // If there is a '0 - y' pattern, canonicalize the pattern to the RHS. 12368 if (LHS.getOpcode() == ISD::SUB && isNullConstant(LHS.getOperand(0)) && 12369 LHS.hasOneUse()) 12370 std::swap(LHS, RHS); 12371 12372 // x == 0-y --> x+y == 0 12373 // x != 0-y --> x+y != 0 12374 if (RHS.getOpcode() == ISD::SUB && isNullConstant(RHS.getOperand(0)) && 12375 RHS.hasOneUse()) { 12376 SDLoc DL(N); 12377 SelectionDAG &DAG = DCI.DAG; 12378 EVT VT = N->getValueType(0); 12379 EVT OpVT = LHS.getValueType(); 12380 SDValue Add = DAG.getNode(ISD::ADD, DL, OpVT, LHS, RHS.getOperand(1)); 12381 return DAG.getSetCC(DL, VT, Add, DAG.getConstant(0, DL, OpVT), CC); 12382 } 12383 } 12384 12385 return DAGCombineTruncBoolExt(N, DCI); 12386 } 12387 12388 // Is this an extending load from an f32 to an f64? 12389 static bool isFPExtLoad(SDValue Op) { 12390 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op.getNode())) 12391 return LD->getExtensionType() == ISD::EXTLOAD && 12392 Op.getValueType() == MVT::f64; 12393 return false; 12394 } 12395 12396 /// Reduces the number of fp-to-int conversion when building a vector. 12397 /// 12398 /// If this vector is built out of floating to integer conversions, 12399 /// transform it to a vector built out of floating point values followed by a 12400 /// single floating to integer conversion of the vector. 12401 /// Namely (build_vector (fptosi $A), (fptosi $B), ...) 12402 /// becomes (fptosi (build_vector ($A, $B, ...))) 12403 SDValue PPCTargetLowering:: 12404 combineElementTruncationToVectorTruncation(SDNode *N, 12405 DAGCombinerInfo &DCI) const { 12406 assert(N->getOpcode() == ISD::BUILD_VECTOR && 12407 "Should be called with a BUILD_VECTOR node"); 12408 12409 SelectionDAG &DAG = DCI.DAG; 12410 SDLoc dl(N); 12411 12412 SDValue FirstInput = N->getOperand(0); 12413 assert(FirstInput.getOpcode() == PPCISD::MFVSR && 12414 "The input operand must be an fp-to-int conversion."); 12415 12416 // This combine happens after legalization so the fp_to_[su]i nodes are 12417 // already converted to PPCSISD nodes. 12418 unsigned FirstConversion = FirstInput.getOperand(0).getOpcode(); 12419 if (FirstConversion == PPCISD::FCTIDZ || 12420 FirstConversion == PPCISD::FCTIDUZ || 12421 FirstConversion == PPCISD::FCTIWZ || 12422 FirstConversion == PPCISD::FCTIWUZ) { 12423 bool IsSplat = true; 12424 bool Is32Bit = FirstConversion == PPCISD::FCTIWZ || 12425 FirstConversion == PPCISD::FCTIWUZ; 12426 EVT SrcVT = FirstInput.getOperand(0).getValueType(); 12427 SmallVector<SDValue, 4> Ops; 12428 EVT TargetVT = N->getValueType(0); 12429 for (int i = 0, e = N->getNumOperands(); i < e; ++i) { 12430 SDValue NextOp = N->getOperand(i); 12431 if (NextOp.getOpcode() != PPCISD::MFVSR) 12432 return SDValue(); 12433 unsigned NextConversion = NextOp.getOperand(0).getOpcode(); 12434 if (NextConversion != FirstConversion) 12435 return SDValue(); 12436 // If we are converting to 32-bit integers, we need to add an FP_ROUND. 12437 // This is not valid if the input was originally double precision. It is 12438 // also not profitable to do unless this is an extending load in which 12439 // case doing this combine will allow us to combine consecutive loads. 12440 if (Is32Bit && !isFPExtLoad(NextOp.getOperand(0).getOperand(0))) 12441 return SDValue(); 12442 if (N->getOperand(i) != FirstInput) 12443 IsSplat = false; 12444 } 12445 12446 // If this is a splat, we leave it as-is since there will be only a single 12447 // fp-to-int conversion followed by a splat of the integer. This is better 12448 // for 32-bit and smaller ints and neutral for 64-bit ints. 12449 if (IsSplat) 12450 return SDValue(); 12451 12452 // Now that we know we have the right type of node, get its operands 12453 for (int i = 0, e = N->getNumOperands(); i < e; ++i) { 12454 SDValue In = N->getOperand(i).getOperand(0); 12455 if (Is32Bit) { 12456 // For 32-bit values, we need to add an FP_ROUND node (if we made it 12457 // here, we know that all inputs are extending loads so this is safe). 12458 if (In.isUndef()) 12459 Ops.push_back(DAG.getUNDEF(SrcVT)); 12460 else { 12461 SDValue Trunc = DAG.getNode(ISD::FP_ROUND, dl, 12462 MVT::f32, In.getOperand(0), 12463 DAG.getIntPtrConstant(1, dl)); 12464 Ops.push_back(Trunc); 12465 } 12466 } else 12467 Ops.push_back(In.isUndef() ? DAG.getUNDEF(SrcVT) : In.getOperand(0)); 12468 } 12469 12470 unsigned Opcode; 12471 if (FirstConversion == PPCISD::FCTIDZ || 12472 FirstConversion == PPCISD::FCTIWZ) 12473 Opcode = ISD::FP_TO_SINT; 12474 else 12475 Opcode = ISD::FP_TO_UINT; 12476 12477 EVT NewVT = TargetVT == MVT::v2i64 ? MVT::v2f64 : MVT::v4f32; 12478 SDValue BV = DAG.getBuildVector(NewVT, dl, Ops); 12479 return DAG.getNode(Opcode, dl, TargetVT, BV); 12480 } 12481 return SDValue(); 12482 } 12483 12484 /// Reduce the number of loads when building a vector. 12485 /// 12486 /// Building a vector out of multiple loads can be converted to a load 12487 /// of the vector type if the loads are consecutive. If the loads are 12488 /// consecutive but in descending order, a shuffle is added at the end 12489 /// to reorder the vector. 12490 static SDValue combineBVOfConsecutiveLoads(SDNode *N, SelectionDAG &DAG) { 12491 assert(N->getOpcode() == ISD::BUILD_VECTOR && 12492 "Should be called with a BUILD_VECTOR node"); 12493 12494 SDLoc dl(N); 12495 12496 // Return early for non byte-sized type, as they can't be consecutive. 12497 if (!N->getValueType(0).getVectorElementType().isByteSized()) 12498 return SDValue(); 12499 12500 bool InputsAreConsecutiveLoads = true; 12501 bool InputsAreReverseConsecutive = true; 12502 unsigned ElemSize = N->getValueType(0).getScalarType().getStoreSize(); 12503 SDValue FirstInput = N->getOperand(0); 12504 bool IsRoundOfExtLoad = false; 12505 12506 if (FirstInput.getOpcode() == ISD::FP_ROUND && 12507 FirstInput.getOperand(0).getOpcode() == ISD::LOAD) { 12508 LoadSDNode *LD = dyn_cast<LoadSDNode>(FirstInput.getOperand(0)); 12509 IsRoundOfExtLoad = LD->getExtensionType() == ISD::EXTLOAD; 12510 } 12511 // Not a build vector of (possibly fp_rounded) loads. 12512 if ((!IsRoundOfExtLoad && FirstInput.getOpcode() != ISD::LOAD) || 12513 N->getNumOperands() == 1) 12514 return SDValue(); 12515 12516 for (int i = 1, e = N->getNumOperands(); i < e; ++i) { 12517 // If any inputs are fp_round(extload), they all must be. 12518 if (IsRoundOfExtLoad && N->getOperand(i).getOpcode() != ISD::FP_ROUND) 12519 return SDValue(); 12520 12521 SDValue NextInput = IsRoundOfExtLoad ? N->getOperand(i).getOperand(0) : 12522 N->getOperand(i); 12523 if (NextInput.getOpcode() != ISD::LOAD) 12524 return SDValue(); 12525 12526 SDValue PreviousInput = 12527 IsRoundOfExtLoad ? N->getOperand(i-1).getOperand(0) : N->getOperand(i-1); 12528 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(PreviousInput); 12529 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(NextInput); 12530 12531 // If any inputs are fp_round(extload), they all must be. 12532 if (IsRoundOfExtLoad && LD2->getExtensionType() != ISD::EXTLOAD) 12533 return SDValue(); 12534 12535 if (!isConsecutiveLS(LD2, LD1, ElemSize, 1, DAG)) 12536 InputsAreConsecutiveLoads = false; 12537 if (!isConsecutiveLS(LD1, LD2, ElemSize, 1, DAG)) 12538 InputsAreReverseConsecutive = false; 12539 12540 // Exit early if the loads are neither consecutive nor reverse consecutive. 12541 if (!InputsAreConsecutiveLoads && !InputsAreReverseConsecutive) 12542 return SDValue(); 12543 } 12544 12545 assert(!(InputsAreConsecutiveLoads && InputsAreReverseConsecutive) && 12546 "The loads cannot be both consecutive and reverse consecutive."); 12547 12548 SDValue FirstLoadOp = 12549 IsRoundOfExtLoad ? FirstInput.getOperand(0) : FirstInput; 12550 SDValue LastLoadOp = 12551 IsRoundOfExtLoad ? N->getOperand(N->getNumOperands()-1).getOperand(0) : 12552 N->getOperand(N->getNumOperands()-1); 12553 12554 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(FirstLoadOp); 12555 LoadSDNode *LDL = dyn_cast<LoadSDNode>(LastLoadOp); 12556 if (InputsAreConsecutiveLoads) { 12557 assert(LD1 && "Input needs to be a LoadSDNode."); 12558 return DAG.getLoad(N->getValueType(0), dl, LD1->getChain(), 12559 LD1->getBasePtr(), LD1->getPointerInfo(), 12560 LD1->getAlignment()); 12561 } 12562 if (InputsAreReverseConsecutive) { 12563 assert(LDL && "Input needs to be a LoadSDNode."); 12564 SDValue Load = DAG.getLoad(N->getValueType(0), dl, LDL->getChain(), 12565 LDL->getBasePtr(), LDL->getPointerInfo(), 12566 LDL->getAlignment()); 12567 SmallVector<int, 16> Ops; 12568 for (int i = N->getNumOperands() - 1; i >= 0; i--) 12569 Ops.push_back(i); 12570 12571 return DAG.getVectorShuffle(N->getValueType(0), dl, Load, 12572 DAG.getUNDEF(N->getValueType(0)), Ops); 12573 } 12574 return SDValue(); 12575 } 12576 12577 // This function adds the required vector_shuffle needed to get 12578 // the elements of the vector extract in the correct position 12579 // as specified by the CorrectElems encoding. 12580 static SDValue addShuffleForVecExtend(SDNode *N, SelectionDAG &DAG, 12581 SDValue Input, uint64_t Elems, 12582 uint64_t CorrectElems) { 12583 SDLoc dl(N); 12584 12585 unsigned NumElems = Input.getValueType().getVectorNumElements(); 12586 SmallVector<int, 16> ShuffleMask(NumElems, -1); 12587 12588 // Knowing the element indices being extracted from the original 12589 // vector and the order in which they're being inserted, just put 12590 // them at element indices required for the instruction. 12591 for (unsigned i = 0; i < N->getNumOperands(); i++) { 12592 if (DAG.getDataLayout().isLittleEndian()) 12593 ShuffleMask[CorrectElems & 0xF] = Elems & 0xF; 12594 else 12595 ShuffleMask[(CorrectElems & 0xF0) >> 4] = (Elems & 0xF0) >> 4; 12596 CorrectElems = CorrectElems >> 8; 12597 Elems = Elems >> 8; 12598 } 12599 12600 SDValue Shuffle = 12601 DAG.getVectorShuffle(Input.getValueType(), dl, Input, 12602 DAG.getUNDEF(Input.getValueType()), ShuffleMask); 12603 12604 EVT Ty = N->getValueType(0); 12605 SDValue BV = DAG.getNode(PPCISD::SExtVElems, dl, Ty, Shuffle); 12606 return BV; 12607 } 12608 12609 // Look for build vector patterns where input operands come from sign 12610 // extended vector_extract elements of specific indices. If the correct indices 12611 // aren't used, add a vector shuffle to fix up the indices and create a new 12612 // PPCISD:SExtVElems node which selects the vector sign extend instructions 12613 // during instruction selection. 12614 static SDValue combineBVOfVecSExt(SDNode *N, SelectionDAG &DAG) { 12615 // This array encodes the indices that the vector sign extend instructions 12616 // extract from when extending from one type to another for both BE and LE. 12617 // The right nibble of each byte corresponds to the LE incides. 12618 // and the left nibble of each byte corresponds to the BE incides. 12619 // For example: 0x3074B8FC byte->word 12620 // For LE: the allowed indices are: 0x0,0x4,0x8,0xC 12621 // For BE: the allowed indices are: 0x3,0x7,0xB,0xF 12622 // For example: 0x000070F8 byte->double word 12623 // For LE: the allowed indices are: 0x0,0x8 12624 // For BE: the allowed indices are: 0x7,0xF 12625 uint64_t TargetElems[] = { 12626 0x3074B8FC, // b->w 12627 0x000070F8, // b->d 12628 0x10325476, // h->w 12629 0x00003074, // h->d 12630 0x00001032, // w->d 12631 }; 12632 12633 uint64_t Elems = 0; 12634 int Index; 12635 SDValue Input; 12636 12637 auto isSExtOfVecExtract = [&](SDValue Op) -> bool { 12638 if (!Op) 12639 return false; 12640 if (Op.getOpcode() != ISD::SIGN_EXTEND && 12641 Op.getOpcode() != ISD::SIGN_EXTEND_INREG) 12642 return false; 12643 12644 // A SIGN_EXTEND_INREG might be fed by an ANY_EXTEND to produce a value 12645 // of the right width. 12646 SDValue Extract = Op.getOperand(0); 12647 if (Extract.getOpcode() == ISD::ANY_EXTEND) 12648 Extract = Extract.getOperand(0); 12649 if (Extract.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 12650 return false; 12651 12652 ConstantSDNode *ExtOp = dyn_cast<ConstantSDNode>(Extract.getOperand(1)); 12653 if (!ExtOp) 12654 return false; 12655 12656 Index = ExtOp->getZExtValue(); 12657 if (Input && Input != Extract.getOperand(0)) 12658 return false; 12659 12660 if (!Input) 12661 Input = Extract.getOperand(0); 12662 12663 Elems = Elems << 8; 12664 Index = DAG.getDataLayout().isLittleEndian() ? Index : Index << 4; 12665 Elems |= Index; 12666 12667 return true; 12668 }; 12669 12670 // If the build vector operands aren't sign extended vector extracts, 12671 // of the same input vector, then return. 12672 for (unsigned i = 0; i < N->getNumOperands(); i++) { 12673 if (!isSExtOfVecExtract(N->getOperand(i))) { 12674 return SDValue(); 12675 } 12676 } 12677 12678 // If the vector extract indicies are not correct, add the appropriate 12679 // vector_shuffle. 12680 int TgtElemArrayIdx; 12681 int InputSize = Input.getValueType().getScalarSizeInBits(); 12682 int OutputSize = N->getValueType(0).getScalarSizeInBits(); 12683 if (InputSize + OutputSize == 40) 12684 TgtElemArrayIdx = 0; 12685 else if (InputSize + OutputSize == 72) 12686 TgtElemArrayIdx = 1; 12687 else if (InputSize + OutputSize == 48) 12688 TgtElemArrayIdx = 2; 12689 else if (InputSize + OutputSize == 80) 12690 TgtElemArrayIdx = 3; 12691 else if (InputSize + OutputSize == 96) 12692 TgtElemArrayIdx = 4; 12693 else 12694 return SDValue(); 12695 12696 uint64_t CorrectElems = TargetElems[TgtElemArrayIdx]; 12697 CorrectElems = DAG.getDataLayout().isLittleEndian() 12698 ? CorrectElems & 0x0F0F0F0F0F0F0F0F 12699 : CorrectElems & 0xF0F0F0F0F0F0F0F0; 12700 if (Elems != CorrectElems) { 12701 return addShuffleForVecExtend(N, DAG, Input, Elems, CorrectElems); 12702 } 12703 12704 // Regular lowering will catch cases where a shuffle is not needed. 12705 return SDValue(); 12706 } 12707 12708 SDValue PPCTargetLowering::DAGCombineBuildVector(SDNode *N, 12709 DAGCombinerInfo &DCI) const { 12710 assert(N->getOpcode() == ISD::BUILD_VECTOR && 12711 "Should be called with a BUILD_VECTOR node"); 12712 12713 SelectionDAG &DAG = DCI.DAG; 12714 SDLoc dl(N); 12715 12716 if (!Subtarget.hasVSX()) 12717 return SDValue(); 12718 12719 // The target independent DAG combiner will leave a build_vector of 12720 // float-to-int conversions intact. We can generate MUCH better code for 12721 // a float-to-int conversion of a vector of floats. 12722 SDValue FirstInput = N->getOperand(0); 12723 if (FirstInput.getOpcode() == PPCISD::MFVSR) { 12724 SDValue Reduced = combineElementTruncationToVectorTruncation(N, DCI); 12725 if (Reduced) 12726 return Reduced; 12727 } 12728 12729 // If we're building a vector out of consecutive loads, just load that 12730 // vector type. 12731 SDValue Reduced = combineBVOfConsecutiveLoads(N, DAG); 12732 if (Reduced) 12733 return Reduced; 12734 12735 // If we're building a vector out of extended elements from another vector 12736 // we have P9 vector integer extend instructions. The code assumes legal 12737 // input types (i.e. it can't handle things like v4i16) so do not run before 12738 // legalization. 12739 if (Subtarget.hasP9Altivec() && !DCI.isBeforeLegalize()) { 12740 Reduced = combineBVOfVecSExt(N, DAG); 12741 if (Reduced) 12742 return Reduced; 12743 } 12744 12745 12746 if (N->getValueType(0) != MVT::v2f64) 12747 return SDValue(); 12748 12749 // Looking for: 12750 // (build_vector ([su]int_to_fp (extractelt 0)), [su]int_to_fp (extractelt 1)) 12751 if (FirstInput.getOpcode() != ISD::SINT_TO_FP && 12752 FirstInput.getOpcode() != ISD::UINT_TO_FP) 12753 return SDValue(); 12754 if (N->getOperand(1).getOpcode() != ISD::SINT_TO_FP && 12755 N->getOperand(1).getOpcode() != ISD::UINT_TO_FP) 12756 return SDValue(); 12757 if (FirstInput.getOpcode() != N->getOperand(1).getOpcode()) 12758 return SDValue(); 12759 12760 SDValue Ext1 = FirstInput.getOperand(0); 12761 SDValue Ext2 = N->getOperand(1).getOperand(0); 12762 if(Ext1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 12763 Ext2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 12764 return SDValue(); 12765 12766 ConstantSDNode *Ext1Op = dyn_cast<ConstantSDNode>(Ext1.getOperand(1)); 12767 ConstantSDNode *Ext2Op = dyn_cast<ConstantSDNode>(Ext2.getOperand(1)); 12768 if (!Ext1Op || !Ext2Op) 12769 return SDValue(); 12770 if (Ext1.getOperand(0).getValueType() != MVT::v4i32 || 12771 Ext1.getOperand(0) != Ext2.getOperand(0)) 12772 return SDValue(); 12773 12774 int FirstElem = Ext1Op->getZExtValue(); 12775 int SecondElem = Ext2Op->getZExtValue(); 12776 int SubvecIdx; 12777 if (FirstElem == 0 && SecondElem == 1) 12778 SubvecIdx = Subtarget.isLittleEndian() ? 1 : 0; 12779 else if (FirstElem == 2 && SecondElem == 3) 12780 SubvecIdx = Subtarget.isLittleEndian() ? 0 : 1; 12781 else 12782 return SDValue(); 12783 12784 SDValue SrcVec = Ext1.getOperand(0); 12785 auto NodeType = (N->getOperand(1).getOpcode() == ISD::SINT_TO_FP) ? 12786 PPCISD::SINT_VEC_TO_FP : PPCISD::UINT_VEC_TO_FP; 12787 return DAG.getNode(NodeType, dl, MVT::v2f64, 12788 SrcVec, DAG.getIntPtrConstant(SubvecIdx, dl)); 12789 } 12790 12791 SDValue PPCTargetLowering::combineFPToIntToFP(SDNode *N, 12792 DAGCombinerInfo &DCI) const { 12793 assert((N->getOpcode() == ISD::SINT_TO_FP || 12794 N->getOpcode() == ISD::UINT_TO_FP) && 12795 "Need an int -> FP conversion node here"); 12796 12797 if (useSoftFloat() || !Subtarget.has64BitSupport()) 12798 return SDValue(); 12799 12800 SelectionDAG &DAG = DCI.DAG; 12801 SDLoc dl(N); 12802 SDValue Op(N, 0); 12803 12804 // Don't handle ppc_fp128 here or conversions that are out-of-range capable 12805 // from the hardware. 12806 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64) 12807 return SDValue(); 12808 if (Op.getOperand(0).getValueType().getSimpleVT() <= MVT(MVT::i1) || 12809 Op.getOperand(0).getValueType().getSimpleVT() > MVT(MVT::i64)) 12810 return SDValue(); 12811 12812 SDValue FirstOperand(Op.getOperand(0)); 12813 bool SubWordLoad = FirstOperand.getOpcode() == ISD::LOAD && 12814 (FirstOperand.getValueType() == MVT::i8 || 12815 FirstOperand.getValueType() == MVT::i16); 12816 if (Subtarget.hasP9Vector() && Subtarget.hasP9Altivec() && SubWordLoad) { 12817 bool Signed = N->getOpcode() == ISD::SINT_TO_FP; 12818 bool DstDouble = Op.getValueType() == MVT::f64; 12819 unsigned ConvOp = Signed ? 12820 (DstDouble ? PPCISD::FCFID : PPCISD::FCFIDS) : 12821 (DstDouble ? PPCISD::FCFIDU : PPCISD::FCFIDUS); 12822 SDValue WidthConst = 12823 DAG.getIntPtrConstant(FirstOperand.getValueType() == MVT::i8 ? 1 : 2, 12824 dl, false); 12825 LoadSDNode *LDN = cast<LoadSDNode>(FirstOperand.getNode()); 12826 SDValue Ops[] = { LDN->getChain(), LDN->getBasePtr(), WidthConst }; 12827 SDValue Ld = DAG.getMemIntrinsicNode(PPCISD::LXSIZX, dl, 12828 DAG.getVTList(MVT::f64, MVT::Other), 12829 Ops, MVT::i8, LDN->getMemOperand()); 12830 12831 // For signed conversion, we need to sign-extend the value in the VSR 12832 if (Signed) { 12833 SDValue ExtOps[] = { Ld, WidthConst }; 12834 SDValue Ext = DAG.getNode(PPCISD::VEXTS, dl, MVT::f64, ExtOps); 12835 return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ext); 12836 } else 12837 return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ld); 12838 } 12839 12840 12841 // For i32 intermediate values, unfortunately, the conversion functions 12842 // leave the upper 32 bits of the value are undefined. Within the set of 12843 // scalar instructions, we have no method for zero- or sign-extending the 12844 // value. Thus, we cannot handle i32 intermediate values here. 12845 if (Op.getOperand(0).getValueType() == MVT::i32) 12846 return SDValue(); 12847 12848 assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) && 12849 "UINT_TO_FP is supported only with FPCVT"); 12850 12851 // If we have FCFIDS, then use it when converting to single-precision. 12852 // Otherwise, convert to double-precision and then round. 12853 unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 12854 ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS 12855 : PPCISD::FCFIDS) 12856 : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU 12857 : PPCISD::FCFID); 12858 MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 12859 ? MVT::f32 12860 : MVT::f64; 12861 12862 // If we're converting from a float, to an int, and back to a float again, 12863 // then we don't need the store/load pair at all. 12864 if ((Op.getOperand(0).getOpcode() == ISD::FP_TO_UINT && 12865 Subtarget.hasFPCVT()) || 12866 (Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT)) { 12867 SDValue Src = Op.getOperand(0).getOperand(0); 12868 if (Src.getValueType() == MVT::f32) { 12869 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src); 12870 DCI.AddToWorklist(Src.getNode()); 12871 } else if (Src.getValueType() != MVT::f64) { 12872 // Make sure that we don't pick up a ppc_fp128 source value. 12873 return SDValue(); 12874 } 12875 12876 unsigned FCTOp = 12877 Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT ? PPCISD::FCTIDZ : 12878 PPCISD::FCTIDUZ; 12879 12880 SDValue Tmp = DAG.getNode(FCTOp, dl, MVT::f64, Src); 12881 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Tmp); 12882 12883 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) { 12884 FP = DAG.getNode(ISD::FP_ROUND, dl, 12885 MVT::f32, FP, DAG.getIntPtrConstant(0, dl)); 12886 DCI.AddToWorklist(FP.getNode()); 12887 } 12888 12889 return FP; 12890 } 12891 12892 return SDValue(); 12893 } 12894 12895 // expandVSXLoadForLE - Convert VSX loads (which may be intrinsics for 12896 // builtins) into loads with swaps. 12897 SDValue PPCTargetLowering::expandVSXLoadForLE(SDNode *N, 12898 DAGCombinerInfo &DCI) const { 12899 SelectionDAG &DAG = DCI.DAG; 12900 SDLoc dl(N); 12901 SDValue Chain; 12902 SDValue Base; 12903 MachineMemOperand *MMO; 12904 12905 switch (N->getOpcode()) { 12906 default: 12907 llvm_unreachable("Unexpected opcode for little endian VSX load"); 12908 case ISD::LOAD: { 12909 LoadSDNode *LD = cast<LoadSDNode>(N); 12910 Chain = LD->getChain(); 12911 Base = LD->getBasePtr(); 12912 MMO = LD->getMemOperand(); 12913 // If the MMO suggests this isn't a load of a full vector, leave 12914 // things alone. For a built-in, we have to make the change for 12915 // correctness, so if there is a size problem that will be a bug. 12916 if (MMO->getSize() < 16) 12917 return SDValue(); 12918 break; 12919 } 12920 case ISD::INTRINSIC_W_CHAIN: { 12921 MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N); 12922 Chain = Intrin->getChain(); 12923 // Similarly to the store case below, Intrin->getBasePtr() doesn't get 12924 // us what we want. Get operand 2 instead. 12925 Base = Intrin->getOperand(2); 12926 MMO = Intrin->getMemOperand(); 12927 break; 12928 } 12929 } 12930 12931 MVT VecTy = N->getValueType(0).getSimpleVT(); 12932 12933 // Do not expand to PPCISD::LXVD2X + PPCISD::XXSWAPD when the load is 12934 // aligned and the type is a vector with elements up to 4 bytes 12935 if (Subtarget.needsSwapsForVSXMemOps() && !(MMO->getAlignment()%16) 12936 && VecTy.getScalarSizeInBits() <= 32 ) { 12937 return SDValue(); 12938 } 12939 12940 SDValue LoadOps[] = { Chain, Base }; 12941 SDValue Load = DAG.getMemIntrinsicNode(PPCISD::LXVD2X, dl, 12942 DAG.getVTList(MVT::v2f64, MVT::Other), 12943 LoadOps, MVT::v2f64, MMO); 12944 12945 DCI.AddToWorklist(Load.getNode()); 12946 Chain = Load.getValue(1); 12947 SDValue Swap = DAG.getNode( 12948 PPCISD::XXSWAPD, dl, DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Load); 12949 DCI.AddToWorklist(Swap.getNode()); 12950 12951 // Add a bitcast if the resulting load type doesn't match v2f64. 12952 if (VecTy != MVT::v2f64) { 12953 SDValue N = DAG.getNode(ISD::BITCAST, dl, VecTy, Swap); 12954 DCI.AddToWorklist(N.getNode()); 12955 // Package {bitcast value, swap's chain} to match Load's shape. 12956 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VecTy, MVT::Other), 12957 N, Swap.getValue(1)); 12958 } 12959 12960 return Swap; 12961 } 12962 12963 // expandVSXStoreForLE - Convert VSX stores (which may be intrinsics for 12964 // builtins) into stores with swaps. 12965 SDValue PPCTargetLowering::expandVSXStoreForLE(SDNode *N, 12966 DAGCombinerInfo &DCI) const { 12967 SelectionDAG &DAG = DCI.DAG; 12968 SDLoc dl(N); 12969 SDValue Chain; 12970 SDValue Base; 12971 unsigned SrcOpnd; 12972 MachineMemOperand *MMO; 12973 12974 switch (N->getOpcode()) { 12975 default: 12976 llvm_unreachable("Unexpected opcode for little endian VSX store"); 12977 case ISD::STORE: { 12978 StoreSDNode *ST = cast<StoreSDNode>(N); 12979 Chain = ST->getChain(); 12980 Base = ST->getBasePtr(); 12981 MMO = ST->getMemOperand(); 12982 SrcOpnd = 1; 12983 // If the MMO suggests this isn't a store of a full vector, leave 12984 // things alone. For a built-in, we have to make the change for 12985 // correctness, so if there is a size problem that will be a bug. 12986 if (MMO->getSize() < 16) 12987 return SDValue(); 12988 break; 12989 } 12990 case ISD::INTRINSIC_VOID: { 12991 MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N); 12992 Chain = Intrin->getChain(); 12993 // Intrin->getBasePtr() oddly does not get what we want. 12994 Base = Intrin->getOperand(3); 12995 MMO = Intrin->getMemOperand(); 12996 SrcOpnd = 2; 12997 break; 12998 } 12999 } 13000 13001 SDValue Src = N->getOperand(SrcOpnd); 13002 MVT VecTy = Src.getValueType().getSimpleVT(); 13003 13004 // Do not expand to PPCISD::XXSWAPD and PPCISD::STXVD2X when the load is 13005 // aligned and the type is a vector with elements up to 4 bytes 13006 if (Subtarget.needsSwapsForVSXMemOps() && !(MMO->getAlignment()%16) 13007 && VecTy.getScalarSizeInBits() <= 32 ) { 13008 return SDValue(); 13009 } 13010 13011 // All stores are done as v2f64 and possible bit cast. 13012 if (VecTy != MVT::v2f64) { 13013 Src = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Src); 13014 DCI.AddToWorklist(Src.getNode()); 13015 } 13016 13017 SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl, 13018 DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Src); 13019 DCI.AddToWorklist(Swap.getNode()); 13020 Chain = Swap.getValue(1); 13021 SDValue StoreOps[] = { Chain, Swap, Base }; 13022 SDValue Store = DAG.getMemIntrinsicNode(PPCISD::STXVD2X, dl, 13023 DAG.getVTList(MVT::Other), 13024 StoreOps, VecTy, MMO); 13025 DCI.AddToWorklist(Store.getNode()); 13026 return Store; 13027 } 13028 13029 // Handle DAG combine for STORE (FP_TO_INT F). 13030 SDValue PPCTargetLowering::combineStoreFPToInt(SDNode *N, 13031 DAGCombinerInfo &DCI) const { 13032 13033 SelectionDAG &DAG = DCI.DAG; 13034 SDLoc dl(N); 13035 unsigned Opcode = N->getOperand(1).getOpcode(); 13036 13037 assert((Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT) 13038 && "Not a FP_TO_INT Instruction!"); 13039 13040 SDValue Val = N->getOperand(1).getOperand(0); 13041 EVT Op1VT = N->getOperand(1).getValueType(); 13042 EVT ResVT = Val.getValueType(); 13043 13044 // Floating point types smaller than 32 bits are not legal on Power. 13045 if (ResVT.getScalarSizeInBits() < 32) 13046 return SDValue(); 13047 13048 // Only perform combine for conversion to i64/i32 or power9 i16/i8. 13049 bool ValidTypeForStoreFltAsInt = 13050 (Op1VT == MVT::i32 || Op1VT == MVT::i64 || 13051 (Subtarget.hasP9Vector() && (Op1VT == MVT::i16 || Op1VT == MVT::i8))); 13052 13053 if (ResVT == MVT::ppcf128 || !Subtarget.hasP8Altivec() || 13054 cast<StoreSDNode>(N)->isTruncatingStore() || !ValidTypeForStoreFltAsInt) 13055 return SDValue(); 13056 13057 // Extend f32 values to f64 13058 if (ResVT.getScalarSizeInBits() == 32) { 13059 Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val); 13060 DCI.AddToWorklist(Val.getNode()); 13061 } 13062 13063 // Set signed or unsigned conversion opcode. 13064 unsigned ConvOpcode = (Opcode == ISD::FP_TO_SINT) ? 13065 PPCISD::FP_TO_SINT_IN_VSR : 13066 PPCISD::FP_TO_UINT_IN_VSR; 13067 13068 Val = DAG.getNode(ConvOpcode, 13069 dl, ResVT == MVT::f128 ? MVT::f128 : MVT::f64, Val); 13070 DCI.AddToWorklist(Val.getNode()); 13071 13072 // Set number of bytes being converted. 13073 unsigned ByteSize = Op1VT.getScalarSizeInBits() / 8; 13074 SDValue Ops[] = { N->getOperand(0), Val, N->getOperand(2), 13075 DAG.getIntPtrConstant(ByteSize, dl, false), 13076 DAG.getValueType(Op1VT) }; 13077 13078 Val = DAG.getMemIntrinsicNode(PPCISD::ST_VSR_SCAL_INT, dl, 13079 DAG.getVTList(MVT::Other), Ops, 13080 cast<StoreSDNode>(N)->getMemoryVT(), 13081 cast<StoreSDNode>(N)->getMemOperand()); 13082 13083 DCI.AddToWorklist(Val.getNode()); 13084 return Val; 13085 } 13086 13087 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N, 13088 DAGCombinerInfo &DCI) const { 13089 SelectionDAG &DAG = DCI.DAG; 13090 SDLoc dl(N); 13091 switch (N->getOpcode()) { 13092 default: break; 13093 case ISD::ADD: 13094 return combineADD(N, DCI); 13095 case ISD::SHL: 13096 return combineSHL(N, DCI); 13097 case ISD::SRA: 13098 return combineSRA(N, DCI); 13099 case ISD::SRL: 13100 return combineSRL(N, DCI); 13101 case ISD::MUL: 13102 return combineMUL(N, DCI); 13103 case PPCISD::SHL: 13104 if (isNullConstant(N->getOperand(0))) // 0 << V -> 0. 13105 return N->getOperand(0); 13106 break; 13107 case PPCISD::SRL: 13108 if (isNullConstant(N->getOperand(0))) // 0 >>u V -> 0. 13109 return N->getOperand(0); 13110 break; 13111 case PPCISD::SRA: 13112 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) { 13113 if (C->isNullValue() || // 0 >>s V -> 0. 13114 C->isAllOnesValue()) // -1 >>s V -> -1. 13115 return N->getOperand(0); 13116 } 13117 break; 13118 case ISD::SIGN_EXTEND: 13119 case ISD::ZERO_EXTEND: 13120 case ISD::ANY_EXTEND: 13121 return DAGCombineExtBoolTrunc(N, DCI); 13122 case ISD::TRUNCATE: 13123 return combineTRUNCATE(N, DCI); 13124 case ISD::SETCC: 13125 if (SDValue CSCC = combineSetCC(N, DCI)) 13126 return CSCC; 13127 LLVM_FALLTHROUGH; 13128 case ISD::SELECT_CC: 13129 return DAGCombineTruncBoolExt(N, DCI); 13130 case ISD::SINT_TO_FP: 13131 case ISD::UINT_TO_FP: 13132 return combineFPToIntToFP(N, DCI); 13133 case ISD::STORE: { 13134 13135 EVT Op1VT = N->getOperand(1).getValueType(); 13136 unsigned Opcode = N->getOperand(1).getOpcode(); 13137 13138 if (Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT) { 13139 SDValue Val= combineStoreFPToInt(N, DCI); 13140 if (Val) 13141 return Val; 13142 } 13143 13144 // Turn STORE (BSWAP) -> sthbrx/stwbrx. 13145 if (cast<StoreSDNode>(N)->isUnindexed() && Opcode == ISD::BSWAP && 13146 N->getOperand(1).getNode()->hasOneUse() && 13147 (Op1VT == MVT::i32 || Op1VT == MVT::i16 || 13148 (Subtarget.hasLDBRX() && Subtarget.isPPC64() && Op1VT == MVT::i64))) { 13149 13150 // STBRX can only handle simple types and it makes no sense to store less 13151 // two bytes in byte-reversed order. 13152 EVT mVT = cast<StoreSDNode>(N)->getMemoryVT(); 13153 if (mVT.isExtended() || mVT.getSizeInBits() < 16) 13154 break; 13155 13156 SDValue BSwapOp = N->getOperand(1).getOperand(0); 13157 // Do an any-extend to 32-bits if this is a half-word input. 13158 if (BSwapOp.getValueType() == MVT::i16) 13159 BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp); 13160 13161 // If the type of BSWAP operand is wider than stored memory width 13162 // it need to be shifted to the right side before STBRX. 13163 if (Op1VT.bitsGT(mVT)) { 13164 int Shift = Op1VT.getSizeInBits() - mVT.getSizeInBits(); 13165 BSwapOp = DAG.getNode(ISD::SRL, dl, Op1VT, BSwapOp, 13166 DAG.getConstant(Shift, dl, MVT::i32)); 13167 // Need to truncate if this is a bswap of i64 stored as i32/i16. 13168 if (Op1VT == MVT::i64) 13169 BSwapOp = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BSwapOp); 13170 } 13171 13172 SDValue Ops[] = { 13173 N->getOperand(0), BSwapOp, N->getOperand(2), DAG.getValueType(mVT) 13174 }; 13175 return 13176 DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other), 13177 Ops, cast<StoreSDNode>(N)->getMemoryVT(), 13178 cast<StoreSDNode>(N)->getMemOperand()); 13179 } 13180 13181 // STORE Constant:i32<0> -> STORE<trunc to i32> Constant:i64<0> 13182 // So it can increase the chance of CSE constant construction. 13183 if (Subtarget.isPPC64() && !DCI.isBeforeLegalize() && 13184 isa<ConstantSDNode>(N->getOperand(1)) && Op1VT == MVT::i32) { 13185 // Need to sign-extended to 64-bits to handle negative values. 13186 EVT MemVT = cast<StoreSDNode>(N)->getMemoryVT(); 13187 uint64_t Val64 = SignExtend64(N->getConstantOperandVal(1), 13188 MemVT.getSizeInBits()); 13189 SDValue Const64 = DAG.getConstant(Val64, dl, MVT::i64); 13190 13191 // DAG.getTruncStore() can't be used here because it doesn't accept 13192 // the general (base + offset) addressing mode. 13193 // So we use UpdateNodeOperands and setTruncatingStore instead. 13194 DAG.UpdateNodeOperands(N, N->getOperand(0), Const64, N->getOperand(2), 13195 N->getOperand(3)); 13196 cast<StoreSDNode>(N)->setTruncatingStore(true); 13197 return SDValue(N, 0); 13198 } 13199 13200 // For little endian, VSX stores require generating xxswapd/lxvd2x. 13201 // Not needed on ISA 3.0 based CPUs since we have a non-permuting store. 13202 if (Op1VT.isSimple()) { 13203 MVT StoreVT = Op1VT.getSimpleVT(); 13204 if (Subtarget.needsSwapsForVSXMemOps() && 13205 (StoreVT == MVT::v2f64 || StoreVT == MVT::v2i64 || 13206 StoreVT == MVT::v4f32 || StoreVT == MVT::v4i32)) 13207 return expandVSXStoreForLE(N, DCI); 13208 } 13209 break; 13210 } 13211 case ISD::LOAD: { 13212 LoadSDNode *LD = cast<LoadSDNode>(N); 13213 EVT VT = LD->getValueType(0); 13214 13215 // For little endian, VSX loads require generating lxvd2x/xxswapd. 13216 // Not needed on ISA 3.0 based CPUs since we have a non-permuting load. 13217 if (VT.isSimple()) { 13218 MVT LoadVT = VT.getSimpleVT(); 13219 if (Subtarget.needsSwapsForVSXMemOps() && 13220 (LoadVT == MVT::v2f64 || LoadVT == MVT::v2i64 || 13221 LoadVT == MVT::v4f32 || LoadVT == MVT::v4i32)) 13222 return expandVSXLoadForLE(N, DCI); 13223 } 13224 13225 // We sometimes end up with a 64-bit integer load, from which we extract 13226 // two single-precision floating-point numbers. This happens with 13227 // std::complex<float>, and other similar structures, because of the way we 13228 // canonicalize structure copies. However, if we lack direct moves, 13229 // then the final bitcasts from the extracted integer values to the 13230 // floating-point numbers turn into store/load pairs. Even with direct moves, 13231 // just loading the two floating-point numbers is likely better. 13232 auto ReplaceTwoFloatLoad = [&]() { 13233 if (VT != MVT::i64) 13234 return false; 13235 13236 if (LD->getExtensionType() != ISD::NON_EXTLOAD || 13237 LD->isVolatile()) 13238 return false; 13239 13240 // We're looking for a sequence like this: 13241 // t13: i64,ch = load<LD8[%ref.tmp]> t0, t6, undef:i64 13242 // t16: i64 = srl t13, Constant:i32<32> 13243 // t17: i32 = truncate t16 13244 // t18: f32 = bitcast t17 13245 // t19: i32 = truncate t13 13246 // t20: f32 = bitcast t19 13247 13248 if (!LD->hasNUsesOfValue(2, 0)) 13249 return false; 13250 13251 auto UI = LD->use_begin(); 13252 while (UI.getUse().getResNo() != 0) ++UI; 13253 SDNode *Trunc = *UI++; 13254 while (UI.getUse().getResNo() != 0) ++UI; 13255 SDNode *RightShift = *UI; 13256 if (Trunc->getOpcode() != ISD::TRUNCATE) 13257 std::swap(Trunc, RightShift); 13258 13259 if (Trunc->getOpcode() != ISD::TRUNCATE || 13260 Trunc->getValueType(0) != MVT::i32 || 13261 !Trunc->hasOneUse()) 13262 return false; 13263 if (RightShift->getOpcode() != ISD::SRL || 13264 !isa<ConstantSDNode>(RightShift->getOperand(1)) || 13265 RightShift->getConstantOperandVal(1) != 32 || 13266 !RightShift->hasOneUse()) 13267 return false; 13268 13269 SDNode *Trunc2 = *RightShift->use_begin(); 13270 if (Trunc2->getOpcode() != ISD::TRUNCATE || 13271 Trunc2->getValueType(0) != MVT::i32 || 13272 !Trunc2->hasOneUse()) 13273 return false; 13274 13275 SDNode *Bitcast = *Trunc->use_begin(); 13276 SDNode *Bitcast2 = *Trunc2->use_begin(); 13277 13278 if (Bitcast->getOpcode() != ISD::BITCAST || 13279 Bitcast->getValueType(0) != MVT::f32) 13280 return false; 13281 if (Bitcast2->getOpcode() != ISD::BITCAST || 13282 Bitcast2->getValueType(0) != MVT::f32) 13283 return false; 13284 13285 if (Subtarget.isLittleEndian()) 13286 std::swap(Bitcast, Bitcast2); 13287 13288 // Bitcast has the second float (in memory-layout order) and Bitcast2 13289 // has the first one. 13290 13291 SDValue BasePtr = LD->getBasePtr(); 13292 if (LD->isIndexed()) { 13293 assert(LD->getAddressingMode() == ISD::PRE_INC && 13294 "Non-pre-inc AM on PPC?"); 13295 BasePtr = 13296 DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, 13297 LD->getOffset()); 13298 } 13299 13300 auto MMOFlags = 13301 LD->getMemOperand()->getFlags() & ~MachineMemOperand::MOVolatile; 13302 SDValue FloatLoad = DAG.getLoad(MVT::f32, dl, LD->getChain(), BasePtr, 13303 LD->getPointerInfo(), LD->getAlignment(), 13304 MMOFlags, LD->getAAInfo()); 13305 SDValue AddPtr = 13306 DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), 13307 BasePtr, DAG.getIntPtrConstant(4, dl)); 13308 SDValue FloatLoad2 = DAG.getLoad( 13309 MVT::f32, dl, SDValue(FloatLoad.getNode(), 1), AddPtr, 13310 LD->getPointerInfo().getWithOffset(4), 13311 MinAlign(LD->getAlignment(), 4), MMOFlags, LD->getAAInfo()); 13312 13313 if (LD->isIndexed()) { 13314 // Note that DAGCombine should re-form any pre-increment load(s) from 13315 // what is produced here if that makes sense. 13316 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), BasePtr); 13317 } 13318 13319 DCI.CombineTo(Bitcast2, FloatLoad); 13320 DCI.CombineTo(Bitcast, FloatLoad2); 13321 13322 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, LD->isIndexed() ? 2 : 1), 13323 SDValue(FloatLoad2.getNode(), 1)); 13324 return true; 13325 }; 13326 13327 if (ReplaceTwoFloatLoad()) 13328 return SDValue(N, 0); 13329 13330 EVT MemVT = LD->getMemoryVT(); 13331 Type *Ty = MemVT.getTypeForEVT(*DAG.getContext()); 13332 unsigned ABIAlignment = DAG.getDataLayout().getABITypeAlignment(Ty); 13333 Type *STy = MemVT.getScalarType().getTypeForEVT(*DAG.getContext()); 13334 unsigned ScalarABIAlignment = DAG.getDataLayout().getABITypeAlignment(STy); 13335 if (LD->isUnindexed() && VT.isVector() && 13336 ((Subtarget.hasAltivec() && ISD::isNON_EXTLoad(N) && 13337 // P8 and later hardware should just use LOAD. 13338 !Subtarget.hasP8Vector() && (VT == MVT::v16i8 || VT == MVT::v8i16 || 13339 VT == MVT::v4i32 || VT == MVT::v4f32)) || 13340 (Subtarget.hasQPX() && (VT == MVT::v4f64 || VT == MVT::v4f32) && 13341 LD->getAlignment() >= ScalarABIAlignment)) && 13342 LD->getAlignment() < ABIAlignment) { 13343 // This is a type-legal unaligned Altivec or QPX load. 13344 SDValue Chain = LD->getChain(); 13345 SDValue Ptr = LD->getBasePtr(); 13346 bool isLittleEndian = Subtarget.isLittleEndian(); 13347 13348 // This implements the loading of unaligned vectors as described in 13349 // the venerable Apple Velocity Engine overview. Specifically: 13350 // https://developer.apple.com/hardwaredrivers/ve/alignment.html 13351 // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html 13352 // 13353 // The general idea is to expand a sequence of one or more unaligned 13354 // loads into an alignment-based permutation-control instruction (lvsl 13355 // or lvsr), a series of regular vector loads (which always truncate 13356 // their input address to an aligned address), and a series of 13357 // permutations. The results of these permutations are the requested 13358 // loaded values. The trick is that the last "extra" load is not taken 13359 // from the address you might suspect (sizeof(vector) bytes after the 13360 // last requested load), but rather sizeof(vector) - 1 bytes after the 13361 // last requested vector. The point of this is to avoid a page fault if 13362 // the base address happened to be aligned. This works because if the 13363 // base address is aligned, then adding less than a full vector length 13364 // will cause the last vector in the sequence to be (re)loaded. 13365 // Otherwise, the next vector will be fetched as you might suspect was 13366 // necessary. 13367 13368 // We might be able to reuse the permutation generation from 13369 // a different base address offset from this one by an aligned amount. 13370 // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this 13371 // optimization later. 13372 Intrinsic::ID Intr, IntrLD, IntrPerm; 13373 MVT PermCntlTy, PermTy, LDTy; 13374 if (Subtarget.hasAltivec()) { 13375 Intr = isLittleEndian ? Intrinsic::ppc_altivec_lvsr : 13376 Intrinsic::ppc_altivec_lvsl; 13377 IntrLD = Intrinsic::ppc_altivec_lvx; 13378 IntrPerm = Intrinsic::ppc_altivec_vperm; 13379 PermCntlTy = MVT::v16i8; 13380 PermTy = MVT::v4i32; 13381 LDTy = MVT::v4i32; 13382 } else { 13383 Intr = MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlpcld : 13384 Intrinsic::ppc_qpx_qvlpcls; 13385 IntrLD = MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlfd : 13386 Intrinsic::ppc_qpx_qvlfs; 13387 IntrPerm = Intrinsic::ppc_qpx_qvfperm; 13388 PermCntlTy = MVT::v4f64; 13389 PermTy = MVT::v4f64; 13390 LDTy = MemVT.getSimpleVT(); 13391 } 13392 13393 SDValue PermCntl = BuildIntrinsicOp(Intr, Ptr, DAG, dl, PermCntlTy); 13394 13395 // Create the new MMO for the new base load. It is like the original MMO, 13396 // but represents an area in memory almost twice the vector size centered 13397 // on the original address. If the address is unaligned, we might start 13398 // reading up to (sizeof(vector)-1) bytes below the address of the 13399 // original unaligned load. 13400 MachineFunction &MF = DAG.getMachineFunction(); 13401 MachineMemOperand *BaseMMO = 13402 MF.getMachineMemOperand(LD->getMemOperand(), 13403 -(long)MemVT.getStoreSize()+1, 13404 2*MemVT.getStoreSize()-1); 13405 13406 // Create the new base load. 13407 SDValue LDXIntID = 13408 DAG.getTargetConstant(IntrLD, dl, getPointerTy(MF.getDataLayout())); 13409 SDValue BaseLoadOps[] = { Chain, LDXIntID, Ptr }; 13410 SDValue BaseLoad = 13411 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl, 13412 DAG.getVTList(PermTy, MVT::Other), 13413 BaseLoadOps, LDTy, BaseMMO); 13414 13415 // Note that the value of IncOffset (which is provided to the next 13416 // load's pointer info offset value, and thus used to calculate the 13417 // alignment), and the value of IncValue (which is actually used to 13418 // increment the pointer value) are different! This is because we 13419 // require the next load to appear to be aligned, even though it 13420 // is actually offset from the base pointer by a lesser amount. 13421 int IncOffset = VT.getSizeInBits() / 8; 13422 int IncValue = IncOffset; 13423 13424 // Walk (both up and down) the chain looking for another load at the real 13425 // (aligned) offset (the alignment of the other load does not matter in 13426 // this case). If found, then do not use the offset reduction trick, as 13427 // that will prevent the loads from being later combined (as they would 13428 // otherwise be duplicates). 13429 if (!findConsecutiveLoad(LD, DAG)) 13430 --IncValue; 13431 13432 SDValue Increment = 13433 DAG.getConstant(IncValue, dl, getPointerTy(MF.getDataLayout())); 13434 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment); 13435 13436 MachineMemOperand *ExtraMMO = 13437 MF.getMachineMemOperand(LD->getMemOperand(), 13438 1, 2*MemVT.getStoreSize()-1); 13439 SDValue ExtraLoadOps[] = { Chain, LDXIntID, Ptr }; 13440 SDValue ExtraLoad = 13441 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl, 13442 DAG.getVTList(PermTy, MVT::Other), 13443 ExtraLoadOps, LDTy, ExtraMMO); 13444 13445 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 13446 BaseLoad.getValue(1), ExtraLoad.getValue(1)); 13447 13448 // Because vperm has a big-endian bias, we must reverse the order 13449 // of the input vectors and complement the permute control vector 13450 // when generating little endian code. We have already handled the 13451 // latter by using lvsr instead of lvsl, so just reverse BaseLoad 13452 // and ExtraLoad here. 13453 SDValue Perm; 13454 if (isLittleEndian) 13455 Perm = BuildIntrinsicOp(IntrPerm, 13456 ExtraLoad, BaseLoad, PermCntl, DAG, dl); 13457 else 13458 Perm = BuildIntrinsicOp(IntrPerm, 13459 BaseLoad, ExtraLoad, PermCntl, DAG, dl); 13460 13461 if (VT != PermTy) 13462 Perm = Subtarget.hasAltivec() ? 13463 DAG.getNode(ISD::BITCAST, dl, VT, Perm) : 13464 DAG.getNode(ISD::FP_ROUND, dl, VT, Perm, // QPX 13465 DAG.getTargetConstant(1, dl, MVT::i64)); 13466 // second argument is 1 because this rounding 13467 // is always exact. 13468 13469 // The output of the permutation is our loaded result, the TokenFactor is 13470 // our new chain. 13471 DCI.CombineTo(N, Perm, TF); 13472 return SDValue(N, 0); 13473 } 13474 } 13475 break; 13476 case ISD::INTRINSIC_WO_CHAIN: { 13477 bool isLittleEndian = Subtarget.isLittleEndian(); 13478 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 13479 Intrinsic::ID Intr = (isLittleEndian ? Intrinsic::ppc_altivec_lvsr 13480 : Intrinsic::ppc_altivec_lvsl); 13481 if ((IID == Intr || 13482 IID == Intrinsic::ppc_qpx_qvlpcld || 13483 IID == Intrinsic::ppc_qpx_qvlpcls) && 13484 N->getOperand(1)->getOpcode() == ISD::ADD) { 13485 SDValue Add = N->getOperand(1); 13486 13487 int Bits = IID == Intrinsic::ppc_qpx_qvlpcld ? 13488 5 /* 32 byte alignment */ : 4 /* 16 byte alignment */; 13489 13490 if (DAG.MaskedValueIsZero(Add->getOperand(1), 13491 APInt::getAllOnesValue(Bits /* alignment */) 13492 .zext(Add.getScalarValueSizeInBits()))) { 13493 SDNode *BasePtr = Add->getOperand(0).getNode(); 13494 for (SDNode::use_iterator UI = BasePtr->use_begin(), 13495 UE = BasePtr->use_end(); 13496 UI != UE; ++UI) { 13497 if (UI->getOpcode() == ISD::INTRINSIC_WO_CHAIN && 13498 cast<ConstantSDNode>(UI->getOperand(0))->getZExtValue() == IID) { 13499 // We've found another LVSL/LVSR, and this address is an aligned 13500 // multiple of that one. The results will be the same, so use the 13501 // one we've just found instead. 13502 13503 return SDValue(*UI, 0); 13504 } 13505 } 13506 } 13507 13508 if (isa<ConstantSDNode>(Add->getOperand(1))) { 13509 SDNode *BasePtr = Add->getOperand(0).getNode(); 13510 for (SDNode::use_iterator UI = BasePtr->use_begin(), 13511 UE = BasePtr->use_end(); UI != UE; ++UI) { 13512 if (UI->getOpcode() == ISD::ADD && 13513 isa<ConstantSDNode>(UI->getOperand(1)) && 13514 (cast<ConstantSDNode>(Add->getOperand(1))->getZExtValue() - 13515 cast<ConstantSDNode>(UI->getOperand(1))->getZExtValue()) % 13516 (1ULL << Bits) == 0) { 13517 SDNode *OtherAdd = *UI; 13518 for (SDNode::use_iterator VI = OtherAdd->use_begin(), 13519 VE = OtherAdd->use_end(); VI != VE; ++VI) { 13520 if (VI->getOpcode() == ISD::INTRINSIC_WO_CHAIN && 13521 cast<ConstantSDNode>(VI->getOperand(0))->getZExtValue() == IID) { 13522 return SDValue(*VI, 0); 13523 } 13524 } 13525 } 13526 } 13527 } 13528 } 13529 13530 // Combine vmaxsw/h/b(a, a's negation) to abs(a) 13531 // Expose the vabsduw/h/b opportunity for down stream 13532 if (!DCI.isAfterLegalizeDAG() && Subtarget.hasP9Altivec() && 13533 (IID == Intrinsic::ppc_altivec_vmaxsw || 13534 IID == Intrinsic::ppc_altivec_vmaxsh || 13535 IID == Intrinsic::ppc_altivec_vmaxsb)) { 13536 SDValue V1 = N->getOperand(1); 13537 SDValue V2 = N->getOperand(2); 13538 if ((V1.getSimpleValueType() == MVT::v4i32 || 13539 V1.getSimpleValueType() == MVT::v8i16 || 13540 V1.getSimpleValueType() == MVT::v16i8) && 13541 V1.getSimpleValueType() == V2.getSimpleValueType()) { 13542 // (0-a, a) 13543 if (V1.getOpcode() == ISD::SUB && 13544 ISD::isBuildVectorAllZeros(V1.getOperand(0).getNode()) && 13545 V1.getOperand(1) == V2) { 13546 return DAG.getNode(ISD::ABS, dl, V2.getValueType(), V2); 13547 } 13548 // (a, 0-a) 13549 if (V2.getOpcode() == ISD::SUB && 13550 ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()) && 13551 V2.getOperand(1) == V1) { 13552 return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1); 13553 } 13554 // (x-y, y-x) 13555 if (V1.getOpcode() == ISD::SUB && V2.getOpcode() == ISD::SUB && 13556 V1.getOperand(0) == V2.getOperand(1) && 13557 V1.getOperand(1) == V2.getOperand(0)) { 13558 return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1); 13559 } 13560 } 13561 } 13562 } 13563 13564 break; 13565 case ISD::INTRINSIC_W_CHAIN: 13566 // For little endian, VSX loads require generating lxvd2x/xxswapd. 13567 // Not needed on ISA 3.0 based CPUs since we have a non-permuting load. 13568 if (Subtarget.needsSwapsForVSXMemOps()) { 13569 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 13570 default: 13571 break; 13572 case Intrinsic::ppc_vsx_lxvw4x: 13573 case Intrinsic::ppc_vsx_lxvd2x: 13574 return expandVSXLoadForLE(N, DCI); 13575 } 13576 } 13577 break; 13578 case ISD::INTRINSIC_VOID: 13579 // For little endian, VSX stores require generating xxswapd/stxvd2x. 13580 // Not needed on ISA 3.0 based CPUs since we have a non-permuting store. 13581 if (Subtarget.needsSwapsForVSXMemOps()) { 13582 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 13583 default: 13584 break; 13585 case Intrinsic::ppc_vsx_stxvw4x: 13586 case Intrinsic::ppc_vsx_stxvd2x: 13587 return expandVSXStoreForLE(N, DCI); 13588 } 13589 } 13590 break; 13591 case ISD::BSWAP: 13592 // Turn BSWAP (LOAD) -> lhbrx/lwbrx. 13593 if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) && 13594 N->getOperand(0).hasOneUse() && 13595 (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 || 13596 (Subtarget.hasLDBRX() && Subtarget.isPPC64() && 13597 N->getValueType(0) == MVT::i64))) { 13598 SDValue Load = N->getOperand(0); 13599 LoadSDNode *LD = cast<LoadSDNode>(Load); 13600 // Create the byte-swapping load. 13601 SDValue Ops[] = { 13602 LD->getChain(), // Chain 13603 LD->getBasePtr(), // Ptr 13604 DAG.getValueType(N->getValueType(0)) // VT 13605 }; 13606 SDValue BSLoad = 13607 DAG.getMemIntrinsicNode(PPCISD::LBRX, dl, 13608 DAG.getVTList(N->getValueType(0) == MVT::i64 ? 13609 MVT::i64 : MVT::i32, MVT::Other), 13610 Ops, LD->getMemoryVT(), LD->getMemOperand()); 13611 13612 // If this is an i16 load, insert the truncate. 13613 SDValue ResVal = BSLoad; 13614 if (N->getValueType(0) == MVT::i16) 13615 ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad); 13616 13617 // First, combine the bswap away. This makes the value produced by the 13618 // load dead. 13619 DCI.CombineTo(N, ResVal); 13620 13621 // Next, combine the load away, we give it a bogus result value but a real 13622 // chain result. The result value is dead because the bswap is dead. 13623 DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1)); 13624 13625 // Return N so it doesn't get rechecked! 13626 return SDValue(N, 0); 13627 } 13628 break; 13629 case PPCISD::VCMP: 13630 // If a VCMPo node already exists with exactly the same operands as this 13631 // node, use its result instead of this node (VCMPo computes both a CR6 and 13632 // a normal output). 13633 // 13634 if (!N->getOperand(0).hasOneUse() && 13635 !N->getOperand(1).hasOneUse() && 13636 !N->getOperand(2).hasOneUse()) { 13637 13638 // Scan all of the users of the LHS, looking for VCMPo's that match. 13639 SDNode *VCMPoNode = nullptr; 13640 13641 SDNode *LHSN = N->getOperand(0).getNode(); 13642 for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end(); 13643 UI != E; ++UI) 13644 if (UI->getOpcode() == PPCISD::VCMPo && 13645 UI->getOperand(1) == N->getOperand(1) && 13646 UI->getOperand(2) == N->getOperand(2) && 13647 UI->getOperand(0) == N->getOperand(0)) { 13648 VCMPoNode = *UI; 13649 break; 13650 } 13651 13652 // If there is no VCMPo node, or if the flag value has a single use, don't 13653 // transform this. 13654 if (!VCMPoNode || VCMPoNode->hasNUsesOfValue(0, 1)) 13655 break; 13656 13657 // Look at the (necessarily single) use of the flag value. If it has a 13658 // chain, this transformation is more complex. Note that multiple things 13659 // could use the value result, which we should ignore. 13660 SDNode *FlagUser = nullptr; 13661 for (SDNode::use_iterator UI = VCMPoNode->use_begin(); 13662 FlagUser == nullptr; ++UI) { 13663 assert(UI != VCMPoNode->use_end() && "Didn't find user!"); 13664 SDNode *User = *UI; 13665 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) { 13666 if (User->getOperand(i) == SDValue(VCMPoNode, 1)) { 13667 FlagUser = User; 13668 break; 13669 } 13670 } 13671 } 13672 13673 // If the user is a MFOCRF instruction, we know this is safe. 13674 // Otherwise we give up for right now. 13675 if (FlagUser->getOpcode() == PPCISD::MFOCRF) 13676 return SDValue(VCMPoNode, 0); 13677 } 13678 break; 13679 case ISD::BRCOND: { 13680 SDValue Cond = N->getOperand(1); 13681 SDValue Target = N->getOperand(2); 13682 13683 if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN && 13684 cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() == 13685 Intrinsic::loop_decrement) { 13686 13687 // We now need to make the intrinsic dead (it cannot be instruction 13688 // selected). 13689 DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0)); 13690 assert(Cond.getNode()->hasOneUse() && 13691 "Counter decrement has more than one use"); 13692 13693 return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other, 13694 N->getOperand(0), Target); 13695 } 13696 } 13697 break; 13698 case ISD::BR_CC: { 13699 // If this is a branch on an altivec predicate comparison, lower this so 13700 // that we don't have to do a MFOCRF: instead, branch directly on CR6. This 13701 // lowering is done pre-legalize, because the legalizer lowers the predicate 13702 // compare down to code that is difficult to reassemble. 13703 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get(); 13704 SDValue LHS = N->getOperand(2), RHS = N->getOperand(3); 13705 13706 // Sometimes the promoted value of the intrinsic is ANDed by some non-zero 13707 // value. If so, pass-through the AND to get to the intrinsic. 13708 if (LHS.getOpcode() == ISD::AND && 13709 LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN && 13710 cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() == 13711 Intrinsic::loop_decrement && 13712 isa<ConstantSDNode>(LHS.getOperand(1)) && 13713 !isNullConstant(LHS.getOperand(1))) 13714 LHS = LHS.getOperand(0); 13715 13716 if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN && 13717 cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() == 13718 Intrinsic::loop_decrement && 13719 isa<ConstantSDNode>(RHS)) { 13720 assert((CC == ISD::SETEQ || CC == ISD::SETNE) && 13721 "Counter decrement comparison is not EQ or NE"); 13722 13723 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue(); 13724 bool isBDNZ = (CC == ISD::SETEQ && Val) || 13725 (CC == ISD::SETNE && !Val); 13726 13727 // We now need to make the intrinsic dead (it cannot be instruction 13728 // selected). 13729 DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0)); 13730 assert(LHS.getNode()->hasOneUse() && 13731 "Counter decrement has more than one use"); 13732 13733 return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other, 13734 N->getOperand(0), N->getOperand(4)); 13735 } 13736 13737 int CompareOpc; 13738 bool isDot; 13739 13740 if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN && 13741 isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) && 13742 getVectorCompareInfo(LHS, CompareOpc, isDot, Subtarget)) { 13743 assert(isDot && "Can't compare against a vector result!"); 13744 13745 // If this is a comparison against something other than 0/1, then we know 13746 // that the condition is never/always true. 13747 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue(); 13748 if (Val != 0 && Val != 1) { 13749 if (CC == ISD::SETEQ) // Cond never true, remove branch. 13750 return N->getOperand(0); 13751 // Always !=, turn it into an unconditional branch. 13752 return DAG.getNode(ISD::BR, dl, MVT::Other, 13753 N->getOperand(0), N->getOperand(4)); 13754 } 13755 13756 bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0); 13757 13758 // Create the PPCISD altivec 'dot' comparison node. 13759 SDValue Ops[] = { 13760 LHS.getOperand(2), // LHS of compare 13761 LHS.getOperand(3), // RHS of compare 13762 DAG.getConstant(CompareOpc, dl, MVT::i32) 13763 }; 13764 EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue }; 13765 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops); 13766 13767 // Unpack the result based on how the target uses it. 13768 PPC::Predicate CompOpc; 13769 switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) { 13770 default: // Can't happen, don't crash on invalid number though. 13771 case 0: // Branch on the value of the EQ bit of CR6. 13772 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE; 13773 break; 13774 case 1: // Branch on the inverted value of the EQ bit of CR6. 13775 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ; 13776 break; 13777 case 2: // Branch on the value of the LT bit of CR6. 13778 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE; 13779 break; 13780 case 3: // Branch on the inverted value of the LT bit of CR6. 13781 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT; 13782 break; 13783 } 13784 13785 return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0), 13786 DAG.getConstant(CompOpc, dl, MVT::i32), 13787 DAG.getRegister(PPC::CR6, MVT::i32), 13788 N->getOperand(4), CompNode.getValue(1)); 13789 } 13790 break; 13791 } 13792 case ISD::BUILD_VECTOR: 13793 return DAGCombineBuildVector(N, DCI); 13794 case ISD::ABS: 13795 return combineABS(N, DCI); 13796 case ISD::VSELECT: 13797 return combineVSelect(N, DCI); 13798 } 13799 13800 return SDValue(); 13801 } 13802 13803 SDValue 13804 PPCTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor, 13805 SelectionDAG &DAG, 13806 SmallVectorImpl<SDNode *> &Created) const { 13807 // fold (sdiv X, pow2) 13808 EVT VT = N->getValueType(0); 13809 if (VT == MVT::i64 && !Subtarget.isPPC64()) 13810 return SDValue(); 13811 if ((VT != MVT::i32 && VT != MVT::i64) || 13812 !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2())) 13813 return SDValue(); 13814 13815 SDLoc DL(N); 13816 SDValue N0 = N->getOperand(0); 13817 13818 bool IsNegPow2 = (-Divisor).isPowerOf2(); 13819 unsigned Lg2 = (IsNegPow2 ? -Divisor : Divisor).countTrailingZeros(); 13820 SDValue ShiftAmt = DAG.getConstant(Lg2, DL, VT); 13821 13822 SDValue Op = DAG.getNode(PPCISD::SRA_ADDZE, DL, VT, N0, ShiftAmt); 13823 Created.push_back(Op.getNode()); 13824 13825 if (IsNegPow2) { 13826 Op = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Op); 13827 Created.push_back(Op.getNode()); 13828 } 13829 13830 return Op; 13831 } 13832 13833 //===----------------------------------------------------------------------===// 13834 // Inline Assembly Support 13835 //===----------------------------------------------------------------------===// 13836 13837 void PPCTargetLowering::computeKnownBitsForTargetNode(const SDValue Op, 13838 KnownBits &Known, 13839 const APInt &DemandedElts, 13840 const SelectionDAG &DAG, 13841 unsigned Depth) const { 13842 Known.resetAll(); 13843 switch (Op.getOpcode()) { 13844 default: break; 13845 case PPCISD::LBRX: { 13846 // lhbrx is known to have the top bits cleared out. 13847 if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16) 13848 Known.Zero = 0xFFFF0000; 13849 break; 13850 } 13851 case ISD::INTRINSIC_WO_CHAIN: { 13852 switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) { 13853 default: break; 13854 case Intrinsic::ppc_altivec_vcmpbfp_p: 13855 case Intrinsic::ppc_altivec_vcmpeqfp_p: 13856 case Intrinsic::ppc_altivec_vcmpequb_p: 13857 case Intrinsic::ppc_altivec_vcmpequh_p: 13858 case Intrinsic::ppc_altivec_vcmpequw_p: 13859 case Intrinsic::ppc_altivec_vcmpequd_p: 13860 case Intrinsic::ppc_altivec_vcmpgefp_p: 13861 case Intrinsic::ppc_altivec_vcmpgtfp_p: 13862 case Intrinsic::ppc_altivec_vcmpgtsb_p: 13863 case Intrinsic::ppc_altivec_vcmpgtsh_p: 13864 case Intrinsic::ppc_altivec_vcmpgtsw_p: 13865 case Intrinsic::ppc_altivec_vcmpgtsd_p: 13866 case Intrinsic::ppc_altivec_vcmpgtub_p: 13867 case Intrinsic::ppc_altivec_vcmpgtuh_p: 13868 case Intrinsic::ppc_altivec_vcmpgtuw_p: 13869 case Intrinsic::ppc_altivec_vcmpgtud_p: 13870 Known.Zero = ~1U; // All bits but the low one are known to be zero. 13871 break; 13872 } 13873 } 13874 } 13875 } 13876 13877 unsigned PPCTargetLowering::getPrefLoopAlignment(MachineLoop *ML) const { 13878 switch (Subtarget.getDarwinDirective()) { 13879 default: break; 13880 case PPC::DIR_970: 13881 case PPC::DIR_PWR4: 13882 case PPC::DIR_PWR5: 13883 case PPC::DIR_PWR5X: 13884 case PPC::DIR_PWR6: 13885 case PPC::DIR_PWR6X: 13886 case PPC::DIR_PWR7: 13887 case PPC::DIR_PWR8: 13888 case PPC::DIR_PWR9: { 13889 if (!ML) 13890 break; 13891 13892 if (!DisableInnermostLoopAlign32) { 13893 // If the nested loop is an innermost loop, prefer to a 32-byte alignment, 13894 // so that we can decrease cache misses and branch-prediction misses. 13895 // Actual alignment of the loop will depend on the hotness check and other 13896 // logic in alignBlocks. 13897 if (ML->getLoopDepth() > 1 && ML->getSubLoops().empty()) 13898 return 5; 13899 } 13900 13901 const PPCInstrInfo *TII = Subtarget.getInstrInfo(); 13902 13903 // For small loops (between 5 and 8 instructions), align to a 32-byte 13904 // boundary so that the entire loop fits in one instruction-cache line. 13905 uint64_t LoopSize = 0; 13906 for (auto I = ML->block_begin(), IE = ML->block_end(); I != IE; ++I) 13907 for (auto J = (*I)->begin(), JE = (*I)->end(); J != JE; ++J) { 13908 LoopSize += TII->getInstSizeInBytes(*J); 13909 if (LoopSize > 32) 13910 break; 13911 } 13912 13913 if (LoopSize > 16 && LoopSize <= 32) 13914 return 5; 13915 13916 break; 13917 } 13918 } 13919 13920 return TargetLowering::getPrefLoopAlignment(ML); 13921 } 13922 13923 /// getConstraintType - Given a constraint, return the type of 13924 /// constraint it is for this target. 13925 PPCTargetLowering::ConstraintType 13926 PPCTargetLowering::getConstraintType(StringRef Constraint) const { 13927 if (Constraint.size() == 1) { 13928 switch (Constraint[0]) { 13929 default: break; 13930 case 'b': 13931 case 'r': 13932 case 'f': 13933 case 'd': 13934 case 'v': 13935 case 'y': 13936 return C_RegisterClass; 13937 case 'Z': 13938 // FIXME: While Z does indicate a memory constraint, it specifically 13939 // indicates an r+r address (used in conjunction with the 'y' modifier 13940 // in the replacement string). Currently, we're forcing the base 13941 // register to be r0 in the asm printer (which is interpreted as zero) 13942 // and forming the complete address in the second register. This is 13943 // suboptimal. 13944 return C_Memory; 13945 } 13946 } else if (Constraint == "wc") { // individual CR bits. 13947 return C_RegisterClass; 13948 } else if (Constraint == "wa" || Constraint == "wd" || 13949 Constraint == "wf" || Constraint == "ws" || 13950 Constraint == "wi") { 13951 return C_RegisterClass; // VSX registers. 13952 } 13953 return TargetLowering::getConstraintType(Constraint); 13954 } 13955 13956 /// Examine constraint type and operand type and determine a weight value. 13957 /// This object must already have been set up with the operand type 13958 /// and the current alternative constraint selected. 13959 TargetLowering::ConstraintWeight 13960 PPCTargetLowering::getSingleConstraintMatchWeight( 13961 AsmOperandInfo &info, const char *constraint) const { 13962 ConstraintWeight weight = CW_Invalid; 13963 Value *CallOperandVal = info.CallOperandVal; 13964 // If we don't have a value, we can't do a match, 13965 // but allow it at the lowest weight. 13966 if (!CallOperandVal) 13967 return CW_Default; 13968 Type *type = CallOperandVal->getType(); 13969 13970 // Look at the constraint type. 13971 if (StringRef(constraint) == "wc" && type->isIntegerTy(1)) 13972 return CW_Register; // an individual CR bit. 13973 else if ((StringRef(constraint) == "wa" || 13974 StringRef(constraint) == "wd" || 13975 StringRef(constraint) == "wf") && 13976 type->isVectorTy()) 13977 return CW_Register; 13978 else if (StringRef(constraint) == "ws" && type->isDoubleTy()) 13979 return CW_Register; 13980 else if (StringRef(constraint) == "wi" && type->isIntegerTy(64)) 13981 return CW_Register; // just hold 64-bit integers data. 13982 13983 switch (*constraint) { 13984 default: 13985 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint); 13986 break; 13987 case 'b': 13988 if (type->isIntegerTy()) 13989 weight = CW_Register; 13990 break; 13991 case 'f': 13992 if (type->isFloatTy()) 13993 weight = CW_Register; 13994 break; 13995 case 'd': 13996 if (type->isDoubleTy()) 13997 weight = CW_Register; 13998 break; 13999 case 'v': 14000 if (type->isVectorTy()) 14001 weight = CW_Register; 14002 break; 14003 case 'y': 14004 weight = CW_Register; 14005 break; 14006 case 'Z': 14007 weight = CW_Memory; 14008 break; 14009 } 14010 return weight; 14011 } 14012 14013 std::pair<unsigned, const TargetRegisterClass *> 14014 PPCTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, 14015 StringRef Constraint, 14016 MVT VT) const { 14017 if (Constraint.size() == 1) { 14018 // GCC RS6000 Constraint Letters 14019 switch (Constraint[0]) { 14020 case 'b': // R1-R31 14021 if (VT == MVT::i64 && Subtarget.isPPC64()) 14022 return std::make_pair(0U, &PPC::G8RC_NOX0RegClass); 14023 return std::make_pair(0U, &PPC::GPRC_NOR0RegClass); 14024 case 'r': // R0-R31 14025 if (VT == MVT::i64 && Subtarget.isPPC64()) 14026 return std::make_pair(0U, &PPC::G8RCRegClass); 14027 return std::make_pair(0U, &PPC::GPRCRegClass); 14028 // 'd' and 'f' constraints are both defined to be "the floating point 14029 // registers", where one is for 32-bit and the other for 64-bit. We don't 14030 // really care overly much here so just give them all the same reg classes. 14031 case 'd': 14032 case 'f': 14033 if (Subtarget.hasSPE()) { 14034 if (VT == MVT::f32 || VT == MVT::i32) 14035 return std::make_pair(0U, &PPC::SPE4RCRegClass); 14036 if (VT == MVT::f64 || VT == MVT::i64) 14037 return std::make_pair(0U, &PPC::SPERCRegClass); 14038 } else { 14039 if (VT == MVT::f32 || VT == MVT::i32) 14040 return std::make_pair(0U, &PPC::F4RCRegClass); 14041 if (VT == MVT::f64 || VT == MVT::i64) 14042 return std::make_pair(0U, &PPC::F8RCRegClass); 14043 if (VT == MVT::v4f64 && Subtarget.hasQPX()) 14044 return std::make_pair(0U, &PPC::QFRCRegClass); 14045 if (VT == MVT::v4f32 && Subtarget.hasQPX()) 14046 return std::make_pair(0U, &PPC::QSRCRegClass); 14047 } 14048 break; 14049 case 'v': 14050 if (VT == MVT::v4f64 && Subtarget.hasQPX()) 14051 return std::make_pair(0U, &PPC::QFRCRegClass); 14052 if (VT == MVT::v4f32 && Subtarget.hasQPX()) 14053 return std::make_pair(0U, &PPC::QSRCRegClass); 14054 if (Subtarget.hasAltivec()) 14055 return std::make_pair(0U, &PPC::VRRCRegClass); 14056 break; 14057 case 'y': // crrc 14058 return std::make_pair(0U, &PPC::CRRCRegClass); 14059 } 14060 } else if (Constraint == "wc" && Subtarget.useCRBits()) { 14061 // An individual CR bit. 14062 return std::make_pair(0U, &PPC::CRBITRCRegClass); 14063 } else if ((Constraint == "wa" || Constraint == "wd" || 14064 Constraint == "wf" || Constraint == "wi") && 14065 Subtarget.hasVSX()) { 14066 return std::make_pair(0U, &PPC::VSRCRegClass); 14067 } else if (Constraint == "ws" && Subtarget.hasVSX()) { 14068 if (VT == MVT::f32 && Subtarget.hasP8Vector()) 14069 return std::make_pair(0U, &PPC::VSSRCRegClass); 14070 else 14071 return std::make_pair(0U, &PPC::VSFRCRegClass); 14072 } 14073 14074 std::pair<unsigned, const TargetRegisterClass *> R = 14075 TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 14076 14077 // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers 14078 // (which we call X[0-9]+). If a 64-bit value has been requested, and a 14079 // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent 14080 // register. 14081 // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use 14082 // the AsmName field from *RegisterInfo.td, then this would not be necessary. 14083 if (R.first && VT == MVT::i64 && Subtarget.isPPC64() && 14084 PPC::GPRCRegClass.contains(R.first)) 14085 return std::make_pair(TRI->getMatchingSuperReg(R.first, 14086 PPC::sub_32, &PPC::G8RCRegClass), 14087 &PPC::G8RCRegClass); 14088 14089 // GCC accepts 'cc' as an alias for 'cr0', and we need to do the same. 14090 if (!R.second && StringRef("{cc}").equals_lower(Constraint)) { 14091 R.first = PPC::CR0; 14092 R.second = &PPC::CRRCRegClass; 14093 } 14094 14095 return R; 14096 } 14097 14098 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops 14099 /// vector. If it is invalid, don't add anything to Ops. 14100 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op, 14101 std::string &Constraint, 14102 std::vector<SDValue>&Ops, 14103 SelectionDAG &DAG) const { 14104 SDValue Result; 14105 14106 // Only support length 1 constraints. 14107 if (Constraint.length() > 1) return; 14108 14109 char Letter = Constraint[0]; 14110 switch (Letter) { 14111 default: break; 14112 case 'I': 14113 case 'J': 14114 case 'K': 14115 case 'L': 14116 case 'M': 14117 case 'N': 14118 case 'O': 14119 case 'P': { 14120 ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op); 14121 if (!CST) return; // Must be an immediate to match. 14122 SDLoc dl(Op); 14123 int64_t Value = CST->getSExtValue(); 14124 EVT TCVT = MVT::i64; // All constants taken to be 64 bits so that negative 14125 // numbers are printed as such. 14126 switch (Letter) { 14127 default: llvm_unreachable("Unknown constraint letter!"); 14128 case 'I': // "I" is a signed 16-bit constant. 14129 if (isInt<16>(Value)) 14130 Result = DAG.getTargetConstant(Value, dl, TCVT); 14131 break; 14132 case 'J': // "J" is a constant with only the high-order 16 bits nonzero. 14133 if (isShiftedUInt<16, 16>(Value)) 14134 Result = DAG.getTargetConstant(Value, dl, TCVT); 14135 break; 14136 case 'L': // "L" is a signed 16-bit constant shifted left 16 bits. 14137 if (isShiftedInt<16, 16>(Value)) 14138 Result = DAG.getTargetConstant(Value, dl, TCVT); 14139 break; 14140 case 'K': // "K" is a constant with only the low-order 16 bits nonzero. 14141 if (isUInt<16>(Value)) 14142 Result = DAG.getTargetConstant(Value, dl, TCVT); 14143 break; 14144 case 'M': // "M" is a constant that is greater than 31. 14145 if (Value > 31) 14146 Result = DAG.getTargetConstant(Value, dl, TCVT); 14147 break; 14148 case 'N': // "N" is a positive constant that is an exact power of two. 14149 if (Value > 0 && isPowerOf2_64(Value)) 14150 Result = DAG.getTargetConstant(Value, dl, TCVT); 14151 break; 14152 case 'O': // "O" is the constant zero. 14153 if (Value == 0) 14154 Result = DAG.getTargetConstant(Value, dl, TCVT); 14155 break; 14156 case 'P': // "P" is a constant whose negation is a signed 16-bit constant. 14157 if (isInt<16>(-Value)) 14158 Result = DAG.getTargetConstant(Value, dl, TCVT); 14159 break; 14160 } 14161 break; 14162 } 14163 } 14164 14165 if (Result.getNode()) { 14166 Ops.push_back(Result); 14167 return; 14168 } 14169 14170 // Handle standard constraint letters. 14171 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 14172 } 14173 14174 // isLegalAddressingMode - Return true if the addressing mode represented 14175 // by AM is legal for this target, for a load/store of the specified type. 14176 bool PPCTargetLowering::isLegalAddressingMode(const DataLayout &DL, 14177 const AddrMode &AM, Type *Ty, 14178 unsigned AS, Instruction *I) const { 14179 // PPC does not allow r+i addressing modes for vectors! 14180 if (Ty->isVectorTy() && AM.BaseOffs != 0) 14181 return false; 14182 14183 // PPC allows a sign-extended 16-bit immediate field. 14184 if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1) 14185 return false; 14186 14187 // No global is ever allowed as a base. 14188 if (AM.BaseGV) 14189 return false; 14190 14191 // PPC only support r+r, 14192 switch (AM.Scale) { 14193 case 0: // "r+i" or just "i", depending on HasBaseReg. 14194 break; 14195 case 1: 14196 if (AM.HasBaseReg && AM.BaseOffs) // "r+r+i" is not allowed. 14197 return false; 14198 // Otherwise we have r+r or r+i. 14199 break; 14200 case 2: 14201 if (AM.HasBaseReg || AM.BaseOffs) // 2*r+r or 2*r+i is not allowed. 14202 return false; 14203 // Allow 2*r as r+r. 14204 break; 14205 default: 14206 // No other scales are supported. 14207 return false; 14208 } 14209 14210 return true; 14211 } 14212 14213 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op, 14214 SelectionDAG &DAG) const { 14215 MachineFunction &MF = DAG.getMachineFunction(); 14216 MachineFrameInfo &MFI = MF.getFrameInfo(); 14217 MFI.setReturnAddressIsTaken(true); 14218 14219 if (verifyReturnAddressArgumentIsConstant(Op, DAG)) 14220 return SDValue(); 14221 14222 SDLoc dl(Op); 14223 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 14224 14225 // Make sure the function does not optimize away the store of the RA to 14226 // the stack. 14227 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 14228 FuncInfo->setLRStoreRequired(); 14229 bool isPPC64 = Subtarget.isPPC64(); 14230 auto PtrVT = getPointerTy(MF.getDataLayout()); 14231 14232 if (Depth > 0) { 14233 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG); 14234 SDValue Offset = 14235 DAG.getConstant(Subtarget.getFrameLowering()->getReturnSaveOffset(), dl, 14236 isPPC64 ? MVT::i64 : MVT::i32); 14237 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), 14238 DAG.getNode(ISD::ADD, dl, PtrVT, FrameAddr, Offset), 14239 MachinePointerInfo()); 14240 } 14241 14242 // Just load the return address off the stack. 14243 SDValue RetAddrFI = getReturnAddrFrameIndex(DAG); 14244 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), RetAddrFI, 14245 MachinePointerInfo()); 14246 } 14247 14248 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op, 14249 SelectionDAG &DAG) const { 14250 SDLoc dl(Op); 14251 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 14252 14253 MachineFunction &MF = DAG.getMachineFunction(); 14254 MachineFrameInfo &MFI = MF.getFrameInfo(); 14255 MFI.setFrameAddressIsTaken(true); 14256 14257 EVT PtrVT = getPointerTy(MF.getDataLayout()); 14258 bool isPPC64 = PtrVT == MVT::i64; 14259 14260 // Naked functions never have a frame pointer, and so we use r1. For all 14261 // other functions, this decision must be delayed until during PEI. 14262 unsigned FrameReg; 14263 if (MF.getFunction().hasFnAttribute(Attribute::Naked)) 14264 FrameReg = isPPC64 ? PPC::X1 : PPC::R1; 14265 else 14266 FrameReg = isPPC64 ? PPC::FP8 : PPC::FP; 14267 14268 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, 14269 PtrVT); 14270 while (Depth--) 14271 FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(), 14272 FrameAddr, MachinePointerInfo()); 14273 return FrameAddr; 14274 } 14275 14276 // FIXME? Maybe this could be a TableGen attribute on some registers and 14277 // this table could be generated automatically from RegInfo. 14278 unsigned PPCTargetLowering::getRegisterByName(const char* RegName, EVT VT, 14279 SelectionDAG &DAG) const { 14280 bool isPPC64 = Subtarget.isPPC64(); 14281 bool isDarwinABI = Subtarget.isDarwinABI(); 14282 14283 if ((isPPC64 && VT != MVT::i64 && VT != MVT::i32) || 14284 (!isPPC64 && VT != MVT::i32)) 14285 report_fatal_error("Invalid register global variable type"); 14286 14287 bool is64Bit = isPPC64 && VT == MVT::i64; 14288 unsigned Reg = StringSwitch<unsigned>(RegName) 14289 .Case("r1", is64Bit ? PPC::X1 : PPC::R1) 14290 .Case("r2", (isDarwinABI || isPPC64) ? 0 : PPC::R2) 14291 .Case("r13", (!isPPC64 && isDarwinABI) ? 0 : 14292 (is64Bit ? PPC::X13 : PPC::R13)) 14293 .Default(0); 14294 14295 if (Reg) 14296 return Reg; 14297 report_fatal_error("Invalid register name global variable"); 14298 } 14299 14300 bool PPCTargetLowering::isAccessedAsGotIndirect(SDValue GA) const { 14301 // 32-bit SVR4 ABI access everything as got-indirect. 14302 if (Subtarget.isSVR4ABI() && !Subtarget.isPPC64()) 14303 return true; 14304 14305 CodeModel::Model CModel = getTargetMachine().getCodeModel(); 14306 // If it is small or large code model, module locals are accessed 14307 // indirectly by loading their address from .toc/.got. The difference 14308 // is that for large code model we have ADDISTocHa + LDtocL and for 14309 // small code model we simply have LDtoc. 14310 if (CModel == CodeModel::Small || CModel == CodeModel::Large) 14311 return true; 14312 14313 // JumpTable and BlockAddress are accessed as got-indirect. 14314 if (isa<JumpTableSDNode>(GA) || isa<BlockAddressSDNode>(GA)) 14315 return true; 14316 14317 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(GA)) { 14318 const GlobalValue *GV = G->getGlobal(); 14319 unsigned char GVFlags = Subtarget.classifyGlobalReference(GV); 14320 // The NLP flag indicates that a global access has to use an 14321 // extra indirection. 14322 if (GVFlags & PPCII::MO_NLP_FLAG) 14323 return true; 14324 } 14325 14326 return false; 14327 } 14328 14329 bool 14330 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 14331 // The PowerPC target isn't yet aware of offsets. 14332 return false; 14333 } 14334 14335 bool PPCTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 14336 const CallInst &I, 14337 MachineFunction &MF, 14338 unsigned Intrinsic) const { 14339 switch (Intrinsic) { 14340 case Intrinsic::ppc_qpx_qvlfd: 14341 case Intrinsic::ppc_qpx_qvlfs: 14342 case Intrinsic::ppc_qpx_qvlfcd: 14343 case Intrinsic::ppc_qpx_qvlfcs: 14344 case Intrinsic::ppc_qpx_qvlfiwa: 14345 case Intrinsic::ppc_qpx_qvlfiwz: 14346 case Intrinsic::ppc_altivec_lvx: 14347 case Intrinsic::ppc_altivec_lvxl: 14348 case Intrinsic::ppc_altivec_lvebx: 14349 case Intrinsic::ppc_altivec_lvehx: 14350 case Intrinsic::ppc_altivec_lvewx: 14351 case Intrinsic::ppc_vsx_lxvd2x: 14352 case Intrinsic::ppc_vsx_lxvw4x: { 14353 EVT VT; 14354 switch (Intrinsic) { 14355 case Intrinsic::ppc_altivec_lvebx: 14356 VT = MVT::i8; 14357 break; 14358 case Intrinsic::ppc_altivec_lvehx: 14359 VT = MVT::i16; 14360 break; 14361 case Intrinsic::ppc_altivec_lvewx: 14362 VT = MVT::i32; 14363 break; 14364 case Intrinsic::ppc_vsx_lxvd2x: 14365 VT = MVT::v2f64; 14366 break; 14367 case Intrinsic::ppc_qpx_qvlfd: 14368 VT = MVT::v4f64; 14369 break; 14370 case Intrinsic::ppc_qpx_qvlfs: 14371 VT = MVT::v4f32; 14372 break; 14373 case Intrinsic::ppc_qpx_qvlfcd: 14374 VT = MVT::v2f64; 14375 break; 14376 case Intrinsic::ppc_qpx_qvlfcs: 14377 VT = MVT::v2f32; 14378 break; 14379 default: 14380 VT = MVT::v4i32; 14381 break; 14382 } 14383 14384 Info.opc = ISD::INTRINSIC_W_CHAIN; 14385 Info.memVT = VT; 14386 Info.ptrVal = I.getArgOperand(0); 14387 Info.offset = -VT.getStoreSize()+1; 14388 Info.size = 2*VT.getStoreSize()-1; 14389 Info.align = 1; 14390 Info.flags = MachineMemOperand::MOLoad; 14391 return true; 14392 } 14393 case Intrinsic::ppc_qpx_qvlfda: 14394 case Intrinsic::ppc_qpx_qvlfsa: 14395 case Intrinsic::ppc_qpx_qvlfcda: 14396 case Intrinsic::ppc_qpx_qvlfcsa: 14397 case Intrinsic::ppc_qpx_qvlfiwaa: 14398 case Intrinsic::ppc_qpx_qvlfiwza: { 14399 EVT VT; 14400 switch (Intrinsic) { 14401 case Intrinsic::ppc_qpx_qvlfda: 14402 VT = MVT::v4f64; 14403 break; 14404 case Intrinsic::ppc_qpx_qvlfsa: 14405 VT = MVT::v4f32; 14406 break; 14407 case Intrinsic::ppc_qpx_qvlfcda: 14408 VT = MVT::v2f64; 14409 break; 14410 case Intrinsic::ppc_qpx_qvlfcsa: 14411 VT = MVT::v2f32; 14412 break; 14413 default: 14414 VT = MVT::v4i32; 14415 break; 14416 } 14417 14418 Info.opc = ISD::INTRINSIC_W_CHAIN; 14419 Info.memVT = VT; 14420 Info.ptrVal = I.getArgOperand(0); 14421 Info.offset = 0; 14422 Info.size = VT.getStoreSize(); 14423 Info.align = 1; 14424 Info.flags = MachineMemOperand::MOLoad; 14425 return true; 14426 } 14427 case Intrinsic::ppc_qpx_qvstfd: 14428 case Intrinsic::ppc_qpx_qvstfs: 14429 case Intrinsic::ppc_qpx_qvstfcd: 14430 case Intrinsic::ppc_qpx_qvstfcs: 14431 case Intrinsic::ppc_qpx_qvstfiw: 14432 case Intrinsic::ppc_altivec_stvx: 14433 case Intrinsic::ppc_altivec_stvxl: 14434 case Intrinsic::ppc_altivec_stvebx: 14435 case Intrinsic::ppc_altivec_stvehx: 14436 case Intrinsic::ppc_altivec_stvewx: 14437 case Intrinsic::ppc_vsx_stxvd2x: 14438 case Intrinsic::ppc_vsx_stxvw4x: { 14439 EVT VT; 14440 switch (Intrinsic) { 14441 case Intrinsic::ppc_altivec_stvebx: 14442 VT = MVT::i8; 14443 break; 14444 case Intrinsic::ppc_altivec_stvehx: 14445 VT = MVT::i16; 14446 break; 14447 case Intrinsic::ppc_altivec_stvewx: 14448 VT = MVT::i32; 14449 break; 14450 case Intrinsic::ppc_vsx_stxvd2x: 14451 VT = MVT::v2f64; 14452 break; 14453 case Intrinsic::ppc_qpx_qvstfd: 14454 VT = MVT::v4f64; 14455 break; 14456 case Intrinsic::ppc_qpx_qvstfs: 14457 VT = MVT::v4f32; 14458 break; 14459 case Intrinsic::ppc_qpx_qvstfcd: 14460 VT = MVT::v2f64; 14461 break; 14462 case Intrinsic::ppc_qpx_qvstfcs: 14463 VT = MVT::v2f32; 14464 break; 14465 default: 14466 VT = MVT::v4i32; 14467 break; 14468 } 14469 14470 Info.opc = ISD::INTRINSIC_VOID; 14471 Info.memVT = VT; 14472 Info.ptrVal = I.getArgOperand(1); 14473 Info.offset = -VT.getStoreSize()+1; 14474 Info.size = 2*VT.getStoreSize()-1; 14475 Info.align = 1; 14476 Info.flags = MachineMemOperand::MOStore; 14477 return true; 14478 } 14479 case Intrinsic::ppc_qpx_qvstfda: 14480 case Intrinsic::ppc_qpx_qvstfsa: 14481 case Intrinsic::ppc_qpx_qvstfcda: 14482 case Intrinsic::ppc_qpx_qvstfcsa: 14483 case Intrinsic::ppc_qpx_qvstfiwa: { 14484 EVT VT; 14485 switch (Intrinsic) { 14486 case Intrinsic::ppc_qpx_qvstfda: 14487 VT = MVT::v4f64; 14488 break; 14489 case Intrinsic::ppc_qpx_qvstfsa: 14490 VT = MVT::v4f32; 14491 break; 14492 case Intrinsic::ppc_qpx_qvstfcda: 14493 VT = MVT::v2f64; 14494 break; 14495 case Intrinsic::ppc_qpx_qvstfcsa: 14496 VT = MVT::v2f32; 14497 break; 14498 default: 14499 VT = MVT::v4i32; 14500 break; 14501 } 14502 14503 Info.opc = ISD::INTRINSIC_VOID; 14504 Info.memVT = VT; 14505 Info.ptrVal = I.getArgOperand(1); 14506 Info.offset = 0; 14507 Info.size = VT.getStoreSize(); 14508 Info.align = 1; 14509 Info.flags = MachineMemOperand::MOStore; 14510 return true; 14511 } 14512 default: 14513 break; 14514 } 14515 14516 return false; 14517 } 14518 14519 /// getOptimalMemOpType - Returns the target specific optimal type for load 14520 /// and store operations as a result of memset, memcpy, and memmove 14521 /// lowering. If DstAlign is zero that means it's safe to destination 14522 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it 14523 /// means there isn't a need to check it against alignment requirement, 14524 /// probably because the source does not need to be loaded. If 'IsMemset' is 14525 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that 14526 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy 14527 /// source is constant so it does not need to be loaded. 14528 /// It returns EVT::Other if the type should be determined using generic 14529 /// target-independent logic. 14530 EVT PPCTargetLowering::getOptimalMemOpType( 14531 uint64_t Size, unsigned DstAlign, unsigned SrcAlign, bool IsMemset, 14532 bool ZeroMemset, bool MemcpyStrSrc, 14533 const AttributeList &FuncAttributes) const { 14534 if (getTargetMachine().getOptLevel() != CodeGenOpt::None) { 14535 // When expanding a memset, require at least two QPX instructions to cover 14536 // the cost of loading the value to be stored from the constant pool. 14537 if (Subtarget.hasQPX() && Size >= 32 && (!IsMemset || Size >= 64) && 14538 (!SrcAlign || SrcAlign >= 32) && (!DstAlign || DstAlign >= 32) && 14539 !FuncAttributes.hasFnAttribute(Attribute::NoImplicitFloat)) { 14540 return MVT::v4f64; 14541 } 14542 14543 // We should use Altivec/VSX loads and stores when available. For unaligned 14544 // addresses, unaligned VSX loads are only fast starting with the P8. 14545 if (Subtarget.hasAltivec() && Size >= 16 && 14546 (((!SrcAlign || SrcAlign >= 16) && (!DstAlign || DstAlign >= 16)) || 14547 ((IsMemset && Subtarget.hasVSX()) || Subtarget.hasP8Vector()))) 14548 return MVT::v4i32; 14549 } 14550 14551 if (Subtarget.isPPC64()) { 14552 return MVT::i64; 14553 } 14554 14555 return MVT::i32; 14556 } 14557 14558 /// Returns true if it is beneficial to convert a load of a constant 14559 /// to just the constant itself. 14560 bool PPCTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 14561 Type *Ty) const { 14562 assert(Ty->isIntegerTy()); 14563 14564 unsigned BitSize = Ty->getPrimitiveSizeInBits(); 14565 return !(BitSize == 0 || BitSize > 64); 14566 } 14567 14568 bool PPCTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const { 14569 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy()) 14570 return false; 14571 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits(); 14572 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits(); 14573 return NumBits1 == 64 && NumBits2 == 32; 14574 } 14575 14576 bool PPCTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const { 14577 if (!VT1.isInteger() || !VT2.isInteger()) 14578 return false; 14579 unsigned NumBits1 = VT1.getSizeInBits(); 14580 unsigned NumBits2 = VT2.getSizeInBits(); 14581 return NumBits1 == 64 && NumBits2 == 32; 14582 } 14583 14584 bool PPCTargetLowering::isZExtFree(SDValue Val, EVT VT2) const { 14585 // Generally speaking, zexts are not free, but they are free when they can be 14586 // folded with other operations. 14587 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Val)) { 14588 EVT MemVT = LD->getMemoryVT(); 14589 if ((MemVT == MVT::i1 || MemVT == MVT::i8 || MemVT == MVT::i16 || 14590 (Subtarget.isPPC64() && MemVT == MVT::i32)) && 14591 (LD->getExtensionType() == ISD::NON_EXTLOAD || 14592 LD->getExtensionType() == ISD::ZEXTLOAD)) 14593 return true; 14594 } 14595 14596 // FIXME: Add other cases... 14597 // - 32-bit shifts with a zext to i64 14598 // - zext after ctlz, bswap, etc. 14599 // - zext after and by a constant mask 14600 14601 return TargetLowering::isZExtFree(Val, VT2); 14602 } 14603 14604 bool PPCTargetLowering::isFPExtFree(EVT DestVT, EVT SrcVT) const { 14605 assert(DestVT.isFloatingPoint() && SrcVT.isFloatingPoint() && 14606 "invalid fpext types"); 14607 // Extending to float128 is not free. 14608 if (DestVT == MVT::f128) 14609 return false; 14610 return true; 14611 } 14612 14613 bool PPCTargetLowering::isLegalICmpImmediate(int64_t Imm) const { 14614 return isInt<16>(Imm) || isUInt<16>(Imm); 14615 } 14616 14617 bool PPCTargetLowering::isLegalAddImmediate(int64_t Imm) const { 14618 return isInt<16>(Imm) || isUInt<16>(Imm); 14619 } 14620 14621 bool PPCTargetLowering::allowsMisalignedMemoryAccesses(EVT VT, 14622 unsigned, 14623 unsigned, 14624 MachineMemOperand::Flags, 14625 bool *Fast) const { 14626 if (DisablePPCUnaligned) 14627 return false; 14628 14629 // PowerPC supports unaligned memory access for simple non-vector types. 14630 // Although accessing unaligned addresses is not as efficient as accessing 14631 // aligned addresses, it is generally more efficient than manual expansion, 14632 // and generally only traps for software emulation when crossing page 14633 // boundaries. 14634 14635 if (!VT.isSimple()) 14636 return false; 14637 14638 if (VT.getSimpleVT().isVector()) { 14639 if (Subtarget.hasVSX()) { 14640 if (VT != MVT::v2f64 && VT != MVT::v2i64 && 14641 VT != MVT::v4f32 && VT != MVT::v4i32) 14642 return false; 14643 } else { 14644 return false; 14645 } 14646 } 14647 14648 if (VT == MVT::ppcf128) 14649 return false; 14650 14651 if (Fast) 14652 *Fast = true; 14653 14654 return true; 14655 } 14656 14657 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const { 14658 VT = VT.getScalarType(); 14659 14660 if (!VT.isSimple()) 14661 return false; 14662 14663 switch (VT.getSimpleVT().SimpleTy) { 14664 case MVT::f32: 14665 case MVT::f64: 14666 return true; 14667 case MVT::f128: 14668 return (EnableQuadPrecision && Subtarget.hasP9Vector()); 14669 default: 14670 break; 14671 } 14672 14673 return false; 14674 } 14675 14676 const MCPhysReg * 14677 PPCTargetLowering::getScratchRegisters(CallingConv::ID) const { 14678 // LR is a callee-save register, but we must treat it as clobbered by any call 14679 // site. Hence we include LR in the scratch registers, which are in turn added 14680 // as implicit-defs for stackmaps and patchpoints. The same reasoning applies 14681 // to CTR, which is used by any indirect call. 14682 static const MCPhysReg ScratchRegs[] = { 14683 PPC::X12, PPC::LR8, PPC::CTR8, 0 14684 }; 14685 14686 return ScratchRegs; 14687 } 14688 14689 unsigned PPCTargetLowering::getExceptionPointerRegister( 14690 const Constant *PersonalityFn) const { 14691 return Subtarget.isPPC64() ? PPC::X3 : PPC::R3; 14692 } 14693 14694 unsigned PPCTargetLowering::getExceptionSelectorRegister( 14695 const Constant *PersonalityFn) const { 14696 return Subtarget.isPPC64() ? PPC::X4 : PPC::R4; 14697 } 14698 14699 bool 14700 PPCTargetLowering::shouldExpandBuildVectorWithShuffles( 14701 EVT VT , unsigned DefinedValues) const { 14702 if (VT == MVT::v2i64) 14703 return Subtarget.hasDirectMove(); // Don't need stack ops with direct moves 14704 14705 if (Subtarget.hasVSX() || Subtarget.hasQPX()) 14706 return true; 14707 14708 return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues); 14709 } 14710 14711 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const { 14712 if (DisableILPPref || Subtarget.enableMachineScheduler()) 14713 return TargetLowering::getSchedulingPreference(N); 14714 14715 return Sched::ILP; 14716 } 14717 14718 // Create a fast isel object. 14719 FastISel * 14720 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo, 14721 const TargetLibraryInfo *LibInfo) const { 14722 return PPC::createFastISel(FuncInfo, LibInfo); 14723 } 14724 14725 void PPCTargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const { 14726 if (Subtarget.isDarwinABI()) return; 14727 if (!Subtarget.isPPC64()) return; 14728 14729 // Update IsSplitCSR in PPCFunctionInfo 14730 PPCFunctionInfo *PFI = Entry->getParent()->getInfo<PPCFunctionInfo>(); 14731 PFI->setIsSplitCSR(true); 14732 } 14733 14734 void PPCTargetLowering::insertCopiesSplitCSR( 14735 MachineBasicBlock *Entry, 14736 const SmallVectorImpl<MachineBasicBlock *> &Exits) const { 14737 const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo(); 14738 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent()); 14739 if (!IStart) 14740 return; 14741 14742 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 14743 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo(); 14744 MachineBasicBlock::iterator MBBI = Entry->begin(); 14745 for (const MCPhysReg *I = IStart; *I; ++I) { 14746 const TargetRegisterClass *RC = nullptr; 14747 if (PPC::G8RCRegClass.contains(*I)) 14748 RC = &PPC::G8RCRegClass; 14749 else if (PPC::F8RCRegClass.contains(*I)) 14750 RC = &PPC::F8RCRegClass; 14751 else if (PPC::CRRCRegClass.contains(*I)) 14752 RC = &PPC::CRRCRegClass; 14753 else if (PPC::VRRCRegClass.contains(*I)) 14754 RC = &PPC::VRRCRegClass; 14755 else 14756 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 14757 14758 unsigned NewVR = MRI->createVirtualRegister(RC); 14759 // Create copy from CSR to a virtual register. 14760 // FIXME: this currently does not emit CFI pseudo-instructions, it works 14761 // fine for CXX_FAST_TLS since the C++-style TLS access functions should be 14762 // nounwind. If we want to generalize this later, we may need to emit 14763 // CFI pseudo-instructions. 14764 assert(Entry->getParent()->getFunction().hasFnAttribute( 14765 Attribute::NoUnwind) && 14766 "Function should be nounwind in insertCopiesSplitCSR!"); 14767 Entry->addLiveIn(*I); 14768 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR) 14769 .addReg(*I); 14770 14771 // Insert the copy-back instructions right before the terminator. 14772 for (auto *Exit : Exits) 14773 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(), 14774 TII->get(TargetOpcode::COPY), *I) 14775 .addReg(NewVR); 14776 } 14777 } 14778 14779 // Override to enable LOAD_STACK_GUARD lowering on Linux. 14780 bool PPCTargetLowering::useLoadStackGuardNode() const { 14781 if (!Subtarget.isTargetLinux()) 14782 return TargetLowering::useLoadStackGuardNode(); 14783 return true; 14784 } 14785 14786 // Override to disable global variable loading on Linux. 14787 void PPCTargetLowering::insertSSPDeclarations(Module &M) const { 14788 if (!Subtarget.isTargetLinux()) 14789 return TargetLowering::insertSSPDeclarations(M); 14790 } 14791 14792 bool PPCTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT, 14793 bool ForCodeSize) const { 14794 if (!VT.isSimple() || !Subtarget.hasVSX()) 14795 return false; 14796 14797 switch(VT.getSimpleVT().SimpleTy) { 14798 default: 14799 // For FP types that are currently not supported by PPC backend, return 14800 // false. Examples: f16, f80. 14801 return false; 14802 case MVT::f32: 14803 case MVT::f64: 14804 case MVT::ppcf128: 14805 return Imm.isPosZero(); 14806 } 14807 } 14808 14809 // For vector shift operation op, fold 14810 // (op x, (and y, ((1 << numbits(x)) - 1))) -> (target op x, y) 14811 static SDValue stripModuloOnShift(const TargetLowering &TLI, SDNode *N, 14812 SelectionDAG &DAG) { 14813 SDValue N0 = N->getOperand(0); 14814 SDValue N1 = N->getOperand(1); 14815 EVT VT = N0.getValueType(); 14816 unsigned OpSizeInBits = VT.getScalarSizeInBits(); 14817 unsigned Opcode = N->getOpcode(); 14818 unsigned TargetOpcode; 14819 14820 switch (Opcode) { 14821 default: 14822 llvm_unreachable("Unexpected shift operation"); 14823 case ISD::SHL: 14824 TargetOpcode = PPCISD::SHL; 14825 break; 14826 case ISD::SRL: 14827 TargetOpcode = PPCISD::SRL; 14828 break; 14829 case ISD::SRA: 14830 TargetOpcode = PPCISD::SRA; 14831 break; 14832 } 14833 14834 if (VT.isVector() && TLI.isOperationLegal(Opcode, VT) && 14835 N1->getOpcode() == ISD::AND) 14836 if (ConstantSDNode *Mask = isConstOrConstSplat(N1->getOperand(1))) 14837 if (Mask->getZExtValue() == OpSizeInBits - 1) 14838 return DAG.getNode(TargetOpcode, SDLoc(N), VT, N0, N1->getOperand(0)); 14839 14840 return SDValue(); 14841 } 14842 14843 SDValue PPCTargetLowering::combineSHL(SDNode *N, DAGCombinerInfo &DCI) const { 14844 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG)) 14845 return Value; 14846 14847 SDValue N0 = N->getOperand(0); 14848 ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N->getOperand(1)); 14849 if (!Subtarget.isISA3_0() || 14850 N0.getOpcode() != ISD::SIGN_EXTEND || 14851 N0.getOperand(0).getValueType() != MVT::i32 || 14852 CN1 == nullptr || N->getValueType(0) != MVT::i64) 14853 return SDValue(); 14854 14855 // We can't save an operation here if the value is already extended, and 14856 // the existing shift is easier to combine. 14857 SDValue ExtsSrc = N0.getOperand(0); 14858 if (ExtsSrc.getOpcode() == ISD::TRUNCATE && 14859 ExtsSrc.getOperand(0).getOpcode() == ISD::AssertSext) 14860 return SDValue(); 14861 14862 SDLoc DL(N0); 14863 SDValue ShiftBy = SDValue(CN1, 0); 14864 // We want the shift amount to be i32 on the extswli, but the shift could 14865 // have an i64. 14866 if (ShiftBy.getValueType() == MVT::i64) 14867 ShiftBy = DCI.DAG.getConstant(CN1->getZExtValue(), DL, MVT::i32); 14868 14869 return DCI.DAG.getNode(PPCISD::EXTSWSLI, DL, MVT::i64, N0->getOperand(0), 14870 ShiftBy); 14871 } 14872 14873 SDValue PPCTargetLowering::combineSRA(SDNode *N, DAGCombinerInfo &DCI) const { 14874 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG)) 14875 return Value; 14876 14877 return SDValue(); 14878 } 14879 14880 SDValue PPCTargetLowering::combineSRL(SDNode *N, DAGCombinerInfo &DCI) const { 14881 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG)) 14882 return Value; 14883 14884 return SDValue(); 14885 } 14886 14887 // Transform (add X, (zext(setne Z, C))) -> (addze X, (addic (addi Z, -C), -1)) 14888 // Transform (add X, (zext(sete Z, C))) -> (addze X, (subfic (addi Z, -C), 0)) 14889 // When C is zero, the equation (addi Z, -C) can be simplified to Z 14890 // Requirement: -C in [-32768, 32767], X and Z are MVT::i64 types 14891 static SDValue combineADDToADDZE(SDNode *N, SelectionDAG &DAG, 14892 const PPCSubtarget &Subtarget) { 14893 if (!Subtarget.isPPC64()) 14894 return SDValue(); 14895 14896 SDValue LHS = N->getOperand(0); 14897 SDValue RHS = N->getOperand(1); 14898 14899 auto isZextOfCompareWithConstant = [](SDValue Op) { 14900 if (Op.getOpcode() != ISD::ZERO_EXTEND || !Op.hasOneUse() || 14901 Op.getValueType() != MVT::i64) 14902 return false; 14903 14904 SDValue Cmp = Op.getOperand(0); 14905 if (Cmp.getOpcode() != ISD::SETCC || !Cmp.hasOneUse() || 14906 Cmp.getOperand(0).getValueType() != MVT::i64) 14907 return false; 14908 14909 if (auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1))) { 14910 int64_t NegConstant = 0 - Constant->getSExtValue(); 14911 // Due to the limitations of the addi instruction, 14912 // -C is required to be [-32768, 32767]. 14913 return isInt<16>(NegConstant); 14914 } 14915 14916 return false; 14917 }; 14918 14919 bool LHSHasPattern = isZextOfCompareWithConstant(LHS); 14920 bool RHSHasPattern = isZextOfCompareWithConstant(RHS); 14921 14922 // If there is a pattern, canonicalize a zext operand to the RHS. 14923 if (LHSHasPattern && !RHSHasPattern) 14924 std::swap(LHS, RHS); 14925 else if (!LHSHasPattern && !RHSHasPattern) 14926 return SDValue(); 14927 14928 SDLoc DL(N); 14929 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Glue); 14930 SDValue Cmp = RHS.getOperand(0); 14931 SDValue Z = Cmp.getOperand(0); 14932 auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1)); 14933 14934 assert(Constant && "Constant Should not be a null pointer."); 14935 int64_t NegConstant = 0 - Constant->getSExtValue(); 14936 14937 switch(cast<CondCodeSDNode>(Cmp.getOperand(2))->get()) { 14938 default: break; 14939 case ISD::SETNE: { 14940 // when C == 0 14941 // --> addze X, (addic Z, -1).carry 14942 // / 14943 // add X, (zext(setne Z, C))-- 14944 // \ when -32768 <= -C <= 32767 && C != 0 14945 // --> addze X, (addic (addi Z, -C), -1).carry 14946 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z, 14947 DAG.getConstant(NegConstant, DL, MVT::i64)); 14948 SDValue AddOrZ = NegConstant != 0 ? Add : Z; 14949 SDValue Addc = DAG.getNode(ISD::ADDC, DL, DAG.getVTList(MVT::i64, MVT::Glue), 14950 AddOrZ, DAG.getConstant(-1ULL, DL, MVT::i64)); 14951 return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64), 14952 SDValue(Addc.getNode(), 1)); 14953 } 14954 case ISD::SETEQ: { 14955 // when C == 0 14956 // --> addze X, (subfic Z, 0).carry 14957 // / 14958 // add X, (zext(sete Z, C))-- 14959 // \ when -32768 <= -C <= 32767 && C != 0 14960 // --> addze X, (subfic (addi Z, -C), 0).carry 14961 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z, 14962 DAG.getConstant(NegConstant, DL, MVT::i64)); 14963 SDValue AddOrZ = NegConstant != 0 ? Add : Z; 14964 SDValue Subc = DAG.getNode(ISD::SUBC, DL, DAG.getVTList(MVT::i64, MVT::Glue), 14965 DAG.getConstant(0, DL, MVT::i64), AddOrZ); 14966 return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64), 14967 SDValue(Subc.getNode(), 1)); 14968 } 14969 } 14970 14971 return SDValue(); 14972 } 14973 14974 SDValue PPCTargetLowering::combineADD(SDNode *N, DAGCombinerInfo &DCI) const { 14975 if (auto Value = combineADDToADDZE(N, DCI.DAG, Subtarget)) 14976 return Value; 14977 14978 return SDValue(); 14979 } 14980 14981 // Detect TRUNCATE operations on bitcasts of float128 values. 14982 // What we are looking for here is the situtation where we extract a subset 14983 // of bits from a 128 bit float. 14984 // This can be of two forms: 14985 // 1) BITCAST of f128 feeding TRUNCATE 14986 // 2) BITCAST of f128 feeding SRL (a shift) feeding TRUNCATE 14987 // The reason this is required is because we do not have a legal i128 type 14988 // and so we want to prevent having to store the f128 and then reload part 14989 // of it. 14990 SDValue PPCTargetLowering::combineTRUNCATE(SDNode *N, 14991 DAGCombinerInfo &DCI) const { 14992 // If we are using CRBits then try that first. 14993 if (Subtarget.useCRBits()) { 14994 // Check if CRBits did anything and return that if it did. 14995 if (SDValue CRTruncValue = DAGCombineTruncBoolExt(N, DCI)) 14996 return CRTruncValue; 14997 } 14998 14999 SDLoc dl(N); 15000 SDValue Op0 = N->getOperand(0); 15001 15002 // Looking for a truncate of i128 to i64. 15003 if (Op0.getValueType() != MVT::i128 || N->getValueType(0) != MVT::i64) 15004 return SDValue(); 15005 15006 int EltToExtract = DCI.DAG.getDataLayout().isBigEndian() ? 1 : 0; 15007 15008 // SRL feeding TRUNCATE. 15009 if (Op0.getOpcode() == ISD::SRL) { 15010 ConstantSDNode *ConstNode = dyn_cast<ConstantSDNode>(Op0.getOperand(1)); 15011 // The right shift has to be by 64 bits. 15012 if (!ConstNode || ConstNode->getZExtValue() != 64) 15013 return SDValue(); 15014 15015 // Switch the element number to extract. 15016 EltToExtract = EltToExtract ? 0 : 1; 15017 // Update Op0 past the SRL. 15018 Op0 = Op0.getOperand(0); 15019 } 15020 15021 // BITCAST feeding a TRUNCATE possibly via SRL. 15022 if (Op0.getOpcode() == ISD::BITCAST && 15023 Op0.getValueType() == MVT::i128 && 15024 Op0.getOperand(0).getValueType() == MVT::f128) { 15025 SDValue Bitcast = DCI.DAG.getBitcast(MVT::v2i64, Op0.getOperand(0)); 15026 return DCI.DAG.getNode( 15027 ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Bitcast, 15028 DCI.DAG.getTargetConstant(EltToExtract, dl, MVT::i32)); 15029 } 15030 return SDValue(); 15031 } 15032 15033 SDValue PPCTargetLowering::combineMUL(SDNode *N, DAGCombinerInfo &DCI) const { 15034 SelectionDAG &DAG = DCI.DAG; 15035 15036 ConstantSDNode *ConstOpOrElement = isConstOrConstSplat(N->getOperand(1)); 15037 if (!ConstOpOrElement) 15038 return SDValue(); 15039 15040 // An imul is usually smaller than the alternative sequence for legal type. 15041 if (DAG.getMachineFunction().getFunction().hasMinSize() && 15042 isOperationLegal(ISD::MUL, N->getValueType(0))) 15043 return SDValue(); 15044 15045 auto IsProfitable = [this](bool IsNeg, bool IsAddOne, EVT VT) -> bool { 15046 switch (this->Subtarget.getDarwinDirective()) { 15047 default: 15048 // TODO: enhance the condition for subtarget before pwr8 15049 return false; 15050 case PPC::DIR_PWR8: 15051 // type mul add shl 15052 // scalar 4 1 1 15053 // vector 7 2 2 15054 return true; 15055 case PPC::DIR_PWR9: 15056 // type mul add shl 15057 // scalar 5 2 2 15058 // vector 7 2 2 15059 15060 // The cycle RATIO of related operations are showed as a table above. 15061 // Because mul is 5(scalar)/7(vector), add/sub/shl are all 2 for both 15062 // scalar and vector type. For 2 instrs patterns, add/sub + shl 15063 // are 4, it is always profitable; but for 3 instrs patterns 15064 // (mul x, -(2^N + 1)) => -(add (shl x, N), x), sub + add + shl are 6. 15065 // So we should only do it for vector type. 15066 return IsAddOne && IsNeg ? VT.isVector() : true; 15067 } 15068 }; 15069 15070 EVT VT = N->getValueType(0); 15071 SDLoc DL(N); 15072 15073 const APInt &MulAmt = ConstOpOrElement->getAPIntValue(); 15074 bool IsNeg = MulAmt.isNegative(); 15075 APInt MulAmtAbs = MulAmt.abs(); 15076 15077 if ((MulAmtAbs - 1).isPowerOf2()) { 15078 // (mul x, 2^N + 1) => (add (shl x, N), x) 15079 // (mul x, -(2^N + 1)) => -(add (shl x, N), x) 15080 15081 if (!IsProfitable(IsNeg, true, VT)) 15082 return SDValue(); 15083 15084 SDValue Op0 = N->getOperand(0); 15085 SDValue Op1 = 15086 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0), 15087 DAG.getConstant((MulAmtAbs - 1).logBase2(), DL, VT)); 15088 SDValue Res = DAG.getNode(ISD::ADD, DL, VT, Op0, Op1); 15089 15090 if (!IsNeg) 15091 return Res; 15092 15093 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Res); 15094 } else if ((MulAmtAbs + 1).isPowerOf2()) { 15095 // (mul x, 2^N - 1) => (sub (shl x, N), x) 15096 // (mul x, -(2^N - 1)) => (sub x, (shl x, N)) 15097 15098 if (!IsProfitable(IsNeg, false, VT)) 15099 return SDValue(); 15100 15101 SDValue Op0 = N->getOperand(0); 15102 SDValue Op1 = 15103 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0), 15104 DAG.getConstant((MulAmtAbs + 1).logBase2(), DL, VT)); 15105 15106 if (!IsNeg) 15107 return DAG.getNode(ISD::SUB, DL, VT, Op1, Op0); 15108 else 15109 return DAG.getNode(ISD::SUB, DL, VT, Op0, Op1); 15110 15111 } else { 15112 return SDValue(); 15113 } 15114 } 15115 15116 bool PPCTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 15117 // Only duplicate to increase tail-calls for the 64bit SysV ABIs. 15118 if (!Subtarget.isSVR4ABI() || !Subtarget.isPPC64()) 15119 return false; 15120 15121 // If not a tail call then no need to proceed. 15122 if (!CI->isTailCall()) 15123 return false; 15124 15125 // If tail calls are disabled for the caller then we are done. 15126 const Function *Caller = CI->getParent()->getParent(); 15127 auto Attr = Caller->getFnAttribute("disable-tail-calls"); 15128 if (Attr.getValueAsString() == "true") 15129 return false; 15130 15131 // If sibling calls have been disabled and tail-calls aren't guaranteed 15132 // there is no reason to duplicate. 15133 auto &TM = getTargetMachine(); 15134 if (!TM.Options.GuaranteedTailCallOpt && DisableSCO) 15135 return false; 15136 15137 // Can't tail call a function called indirectly, or if it has variadic args. 15138 const Function *Callee = CI->getCalledFunction(); 15139 if (!Callee || Callee->isVarArg()) 15140 return false; 15141 15142 // Make sure the callee and caller calling conventions are eligible for tco. 15143 if (!areCallingConvEligibleForTCO_64SVR4(Caller->getCallingConv(), 15144 CI->getCallingConv())) 15145 return false; 15146 15147 // If the function is local then we have a good chance at tail-calling it 15148 return getTargetMachine().shouldAssumeDSOLocal(*Caller->getParent(), Callee); 15149 } 15150 15151 bool PPCTargetLowering::hasBitPreservingFPLogic(EVT VT) const { 15152 if (!Subtarget.hasVSX()) 15153 return false; 15154 if (Subtarget.hasP9Vector() && VT == MVT::f128) 15155 return true; 15156 return VT == MVT::f32 || VT == MVT::f64 || 15157 VT == MVT::v4f32 || VT == MVT::v2f64; 15158 } 15159 15160 bool PPCTargetLowering:: 15161 isMaskAndCmp0FoldingBeneficial(const Instruction &AndI) const { 15162 const Value *Mask = AndI.getOperand(1); 15163 // If the mask is suitable for andi. or andis. we should sink the and. 15164 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Mask)) { 15165 // Can't handle constants wider than 64-bits. 15166 if (CI->getBitWidth() > 64) 15167 return false; 15168 int64_t ConstVal = CI->getZExtValue(); 15169 return isUInt<16>(ConstVal) || 15170 (isUInt<16>(ConstVal >> 16) && !(ConstVal & 0xFFFF)); 15171 } 15172 15173 // For non-constant masks, we can always use the record-form and. 15174 return true; 15175 } 15176 15177 // Transform (abs (sub (zext a), (zext b))) to (vabsd a b 0) 15178 // Transform (abs (sub (zext a), (zext_invec b))) to (vabsd a b 0) 15179 // Transform (abs (sub (zext_invec a), (zext_invec b))) to (vabsd a b 0) 15180 // Transform (abs (sub (zext_invec a), (zext b))) to (vabsd a b 0) 15181 // Transform (abs (sub a, b) to (vabsd a b 1)) if a & b of type v4i32 15182 SDValue PPCTargetLowering::combineABS(SDNode *N, DAGCombinerInfo &DCI) const { 15183 assert((N->getOpcode() == ISD::ABS) && "Need ABS node here"); 15184 assert(Subtarget.hasP9Altivec() && 15185 "Only combine this when P9 altivec supported!"); 15186 EVT VT = N->getValueType(0); 15187 if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8) 15188 return SDValue(); 15189 15190 SelectionDAG &DAG = DCI.DAG; 15191 SDLoc dl(N); 15192 if (N->getOperand(0).getOpcode() == ISD::SUB) { 15193 // Even for signed integers, if it's known to be positive (as signed 15194 // integer) due to zero-extended inputs. 15195 unsigned SubOpcd0 = N->getOperand(0)->getOperand(0).getOpcode(); 15196 unsigned SubOpcd1 = N->getOperand(0)->getOperand(1).getOpcode(); 15197 if ((SubOpcd0 == ISD::ZERO_EXTEND || 15198 SubOpcd0 == ISD::ZERO_EXTEND_VECTOR_INREG) && 15199 (SubOpcd1 == ISD::ZERO_EXTEND || 15200 SubOpcd1 == ISD::ZERO_EXTEND_VECTOR_INREG)) { 15201 return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(), 15202 N->getOperand(0)->getOperand(0), 15203 N->getOperand(0)->getOperand(1), 15204 DAG.getTargetConstant(0, dl, MVT::i32)); 15205 } 15206 15207 // For type v4i32, it can be optimized with xvnegsp + vabsduw 15208 if (N->getOperand(0).getValueType() == MVT::v4i32 && 15209 N->getOperand(0).hasOneUse()) { 15210 return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(), 15211 N->getOperand(0)->getOperand(0), 15212 N->getOperand(0)->getOperand(1), 15213 DAG.getTargetConstant(1, dl, MVT::i32)); 15214 } 15215 } 15216 15217 return SDValue(); 15218 } 15219 15220 // For type v4i32/v8ii16/v16i8, transform 15221 // from (vselect (setcc a, b, setugt), (sub a, b), (sub b, a)) to (vabsd a, b) 15222 // from (vselect (setcc a, b, setuge), (sub a, b), (sub b, a)) to (vabsd a, b) 15223 // from (vselect (setcc a, b, setult), (sub b, a), (sub a, b)) to (vabsd a, b) 15224 // from (vselect (setcc a, b, setule), (sub b, a), (sub a, b)) to (vabsd a, b) 15225 SDValue PPCTargetLowering::combineVSelect(SDNode *N, 15226 DAGCombinerInfo &DCI) const { 15227 assert((N->getOpcode() == ISD::VSELECT) && "Need VSELECT node here"); 15228 assert(Subtarget.hasP9Altivec() && 15229 "Only combine this when P9 altivec supported!"); 15230 15231 SelectionDAG &DAG = DCI.DAG; 15232 SDLoc dl(N); 15233 SDValue Cond = N->getOperand(0); 15234 SDValue TrueOpnd = N->getOperand(1); 15235 SDValue FalseOpnd = N->getOperand(2); 15236 EVT VT = N->getOperand(1).getValueType(); 15237 15238 if (Cond.getOpcode() != ISD::SETCC || TrueOpnd.getOpcode() != ISD::SUB || 15239 FalseOpnd.getOpcode() != ISD::SUB) 15240 return SDValue(); 15241 15242 // ABSD only available for type v4i32/v8i16/v16i8 15243 if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8) 15244 return SDValue(); 15245 15246 // At least to save one more dependent computation 15247 if (!(Cond.hasOneUse() || TrueOpnd.hasOneUse() || FalseOpnd.hasOneUse())) 15248 return SDValue(); 15249 15250 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get(); 15251 15252 // Can only handle unsigned comparison here 15253 switch (CC) { 15254 default: 15255 return SDValue(); 15256 case ISD::SETUGT: 15257 case ISD::SETUGE: 15258 break; 15259 case ISD::SETULT: 15260 case ISD::SETULE: 15261 std::swap(TrueOpnd, FalseOpnd); 15262 break; 15263 } 15264 15265 SDValue CmpOpnd1 = Cond.getOperand(0); 15266 SDValue CmpOpnd2 = Cond.getOperand(1); 15267 15268 // SETCC CmpOpnd1 CmpOpnd2 cond 15269 // TrueOpnd = CmpOpnd1 - CmpOpnd2 15270 // FalseOpnd = CmpOpnd2 - CmpOpnd1 15271 if (TrueOpnd.getOperand(0) == CmpOpnd1 && 15272 TrueOpnd.getOperand(1) == CmpOpnd2 && 15273 FalseOpnd.getOperand(0) == CmpOpnd2 && 15274 FalseOpnd.getOperand(1) == CmpOpnd1) { 15275 return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(1).getValueType(), 15276 CmpOpnd1, CmpOpnd2, 15277 DAG.getTargetConstant(0, dl, MVT::i32)); 15278 } 15279 15280 return SDValue(); 15281 } 15282