1 //===-- PPCISelLowering.cpp - PPC DAG Lowering Implementation -------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements the PPCISelLowering class. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "PPCISelLowering.h" 14 #include "MCTargetDesc/PPCPredicates.h" 15 #include "PPC.h" 16 #include "PPCCCState.h" 17 #include "PPCCallingConv.h" 18 #include "PPCFrameLowering.h" 19 #include "PPCInstrInfo.h" 20 #include "PPCMachineFunctionInfo.h" 21 #include "PPCPerfectShuffle.h" 22 #include "PPCRegisterInfo.h" 23 #include "PPCSubtarget.h" 24 #include "PPCTargetMachine.h" 25 #include "llvm/ADT/APFloat.h" 26 #include "llvm/ADT/APInt.h" 27 #include "llvm/ADT/ArrayRef.h" 28 #include "llvm/ADT/DenseMap.h" 29 #include "llvm/ADT/None.h" 30 #include "llvm/ADT/STLExtras.h" 31 #include "llvm/ADT/SmallPtrSet.h" 32 #include "llvm/ADT/SmallSet.h" 33 #include "llvm/ADT/SmallVector.h" 34 #include "llvm/ADT/Statistic.h" 35 #include "llvm/ADT/StringRef.h" 36 #include "llvm/ADT/StringSwitch.h" 37 #include "llvm/CodeGen/CallingConvLower.h" 38 #include "llvm/CodeGen/ISDOpcodes.h" 39 #include "llvm/CodeGen/MachineBasicBlock.h" 40 #include "llvm/CodeGen/MachineFrameInfo.h" 41 #include "llvm/CodeGen/MachineFunction.h" 42 #include "llvm/CodeGen/MachineInstr.h" 43 #include "llvm/CodeGen/MachineInstrBuilder.h" 44 #include "llvm/CodeGen/MachineJumpTableInfo.h" 45 #include "llvm/CodeGen/MachineLoopInfo.h" 46 #include "llvm/CodeGen/MachineMemOperand.h" 47 #include "llvm/CodeGen/MachineModuleInfo.h" 48 #include "llvm/CodeGen/MachineOperand.h" 49 #include "llvm/CodeGen/MachineRegisterInfo.h" 50 #include "llvm/CodeGen/RuntimeLibcalls.h" 51 #include "llvm/CodeGen/SelectionDAG.h" 52 #include "llvm/CodeGen/SelectionDAGNodes.h" 53 #include "llvm/CodeGen/TargetInstrInfo.h" 54 #include "llvm/CodeGen/TargetLowering.h" 55 #include "llvm/CodeGen/TargetRegisterInfo.h" 56 #include "llvm/CodeGen/ValueTypes.h" 57 #include "llvm/IR/CallSite.h" 58 #include "llvm/IR/CallingConv.h" 59 #include "llvm/IR/Constant.h" 60 #include "llvm/IR/Constants.h" 61 #include "llvm/IR/DataLayout.h" 62 #include "llvm/IR/DebugLoc.h" 63 #include "llvm/IR/DerivedTypes.h" 64 #include "llvm/IR/Function.h" 65 #include "llvm/IR/GlobalValue.h" 66 #include "llvm/IR/IRBuilder.h" 67 #include "llvm/IR/Instructions.h" 68 #include "llvm/IR/Intrinsics.h" 69 #include "llvm/IR/Module.h" 70 #include "llvm/IR/Type.h" 71 #include "llvm/IR/Use.h" 72 #include "llvm/IR/Value.h" 73 #include "llvm/MC/MCContext.h" 74 #include "llvm/MC/MCExpr.h" 75 #include "llvm/MC/MCRegisterInfo.h" 76 #include "llvm/MC/MCSymbolXCOFF.h" 77 #include "llvm/Support/AtomicOrdering.h" 78 #include "llvm/Support/BranchProbability.h" 79 #include "llvm/Support/Casting.h" 80 #include "llvm/Support/CodeGen.h" 81 #include "llvm/Support/CommandLine.h" 82 #include "llvm/Support/Compiler.h" 83 #include "llvm/Support/Debug.h" 84 #include "llvm/Support/ErrorHandling.h" 85 #include "llvm/Support/Format.h" 86 #include "llvm/Support/KnownBits.h" 87 #include "llvm/Support/MachineValueType.h" 88 #include "llvm/Support/MathExtras.h" 89 #include "llvm/Support/raw_ostream.h" 90 #include "llvm/Target/TargetMachine.h" 91 #include "llvm/Target/TargetOptions.h" 92 #include <algorithm> 93 #include <cassert> 94 #include <cstdint> 95 #include <iterator> 96 #include <list> 97 #include <utility> 98 #include <vector> 99 100 using namespace llvm; 101 102 #define DEBUG_TYPE "ppc-lowering" 103 104 static cl::opt<bool> DisablePPCPreinc("disable-ppc-preinc", 105 cl::desc("disable preincrement load/store generation on PPC"), cl::Hidden); 106 107 static cl::opt<bool> DisableILPPref("disable-ppc-ilp-pref", 108 cl::desc("disable setting the node scheduling preference to ILP on PPC"), cl::Hidden); 109 110 static cl::opt<bool> DisablePPCUnaligned("disable-ppc-unaligned", 111 cl::desc("disable unaligned load/store generation on PPC"), cl::Hidden); 112 113 static cl::opt<bool> DisableSCO("disable-ppc-sco", 114 cl::desc("disable sibling call optimization on ppc"), cl::Hidden); 115 116 static cl::opt<bool> DisableInnermostLoopAlign32("disable-ppc-innermost-loop-align32", 117 cl::desc("don't always align innermost loop to 32 bytes on ppc"), cl::Hidden); 118 119 static cl::opt<bool> EnableQuadPrecision("enable-ppc-quad-precision", 120 cl::desc("enable quad precision float support on ppc"), cl::Hidden); 121 122 STATISTIC(NumTailCalls, "Number of tail calls"); 123 STATISTIC(NumSiblingCalls, "Number of sibling calls"); 124 125 static bool isNByteElemShuffleMask(ShuffleVectorSDNode *, unsigned, int); 126 127 static SDValue widenVec(SelectionDAG &DAG, SDValue Vec, const SDLoc &dl); 128 129 // FIXME: Remove this once the bug has been fixed! 130 extern cl::opt<bool> ANDIGlueBug; 131 132 PPCTargetLowering::PPCTargetLowering(const PPCTargetMachine &TM, 133 const PPCSubtarget &STI) 134 : TargetLowering(TM), Subtarget(STI) { 135 // Use _setjmp/_longjmp instead of setjmp/longjmp. 136 setUseUnderscoreSetJmp(true); 137 setUseUnderscoreLongJmp(true); 138 139 // On PPC32/64, arguments smaller than 4/8 bytes are extended, so all 140 // arguments are at least 4/8 bytes aligned. 141 bool isPPC64 = Subtarget.isPPC64(); 142 setMinStackArgumentAlignment(isPPC64 ? 8:4); 143 144 // Set up the register classes. 145 addRegisterClass(MVT::i32, &PPC::GPRCRegClass); 146 if (!useSoftFloat()) { 147 if (hasSPE()) { 148 addRegisterClass(MVT::f32, &PPC::SPE4RCRegClass); 149 addRegisterClass(MVT::f64, &PPC::SPERCRegClass); 150 } else { 151 addRegisterClass(MVT::f32, &PPC::F4RCRegClass); 152 addRegisterClass(MVT::f64, &PPC::F8RCRegClass); 153 } 154 } 155 156 // Match BITREVERSE to customized fast code sequence in the td file. 157 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal); 158 setOperationAction(ISD::BITREVERSE, MVT::i64, Legal); 159 160 // Sub-word ATOMIC_CMP_SWAP need to ensure that the input is zero-extended. 161 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom); 162 163 // PowerPC has an i16 but no i8 (or i1) SEXTLOAD. 164 for (MVT VT : MVT::integer_valuetypes()) { 165 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote); 166 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i8, Expand); 167 } 168 169 setTruncStoreAction(MVT::f64, MVT::f32, Expand); 170 171 // PowerPC has pre-inc load and store's. 172 setIndexedLoadAction(ISD::PRE_INC, MVT::i1, Legal); 173 setIndexedLoadAction(ISD::PRE_INC, MVT::i8, Legal); 174 setIndexedLoadAction(ISD::PRE_INC, MVT::i16, Legal); 175 setIndexedLoadAction(ISD::PRE_INC, MVT::i32, Legal); 176 setIndexedLoadAction(ISD::PRE_INC, MVT::i64, Legal); 177 setIndexedStoreAction(ISD::PRE_INC, MVT::i1, Legal); 178 setIndexedStoreAction(ISD::PRE_INC, MVT::i8, Legal); 179 setIndexedStoreAction(ISD::PRE_INC, MVT::i16, Legal); 180 setIndexedStoreAction(ISD::PRE_INC, MVT::i32, Legal); 181 setIndexedStoreAction(ISD::PRE_INC, MVT::i64, Legal); 182 if (!Subtarget.hasSPE()) { 183 setIndexedLoadAction(ISD::PRE_INC, MVT::f32, Legal); 184 setIndexedLoadAction(ISD::PRE_INC, MVT::f64, Legal); 185 setIndexedStoreAction(ISD::PRE_INC, MVT::f32, Legal); 186 setIndexedStoreAction(ISD::PRE_INC, MVT::f64, Legal); 187 } 188 189 // PowerPC uses ADDC/ADDE/SUBC/SUBE to propagate carry. 190 const MVT ScalarIntVTs[] = { MVT::i32, MVT::i64 }; 191 for (MVT VT : ScalarIntVTs) { 192 setOperationAction(ISD::ADDC, VT, Legal); 193 setOperationAction(ISD::ADDE, VT, Legal); 194 setOperationAction(ISD::SUBC, VT, Legal); 195 setOperationAction(ISD::SUBE, VT, Legal); 196 } 197 198 if (Subtarget.useCRBits()) { 199 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); 200 201 if (isPPC64 || Subtarget.hasFPCVT()) { 202 setOperationAction(ISD::SINT_TO_FP, MVT::i1, Promote); 203 AddPromotedToType (ISD::SINT_TO_FP, MVT::i1, 204 isPPC64 ? MVT::i64 : MVT::i32); 205 setOperationAction(ISD::UINT_TO_FP, MVT::i1, Promote); 206 AddPromotedToType(ISD::UINT_TO_FP, MVT::i1, 207 isPPC64 ? MVT::i64 : MVT::i32); 208 } else { 209 setOperationAction(ISD::SINT_TO_FP, MVT::i1, Custom); 210 setOperationAction(ISD::UINT_TO_FP, MVT::i1, Custom); 211 } 212 213 // PowerPC does not support direct load/store of condition registers. 214 setOperationAction(ISD::LOAD, MVT::i1, Custom); 215 setOperationAction(ISD::STORE, MVT::i1, Custom); 216 217 // FIXME: Remove this once the ANDI glue bug is fixed: 218 if (ANDIGlueBug) 219 setOperationAction(ISD::TRUNCATE, MVT::i1, Custom); 220 221 for (MVT VT : MVT::integer_valuetypes()) { 222 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote); 223 setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote); 224 setTruncStoreAction(VT, MVT::i1, Expand); 225 } 226 227 addRegisterClass(MVT::i1, &PPC::CRBITRCRegClass); 228 } 229 230 // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on 231 // PPC (the libcall is not available). 232 setOperationAction(ISD::FP_TO_SINT, MVT::ppcf128, Custom); 233 setOperationAction(ISD::FP_TO_UINT, MVT::ppcf128, Custom); 234 235 // We do not currently implement these libm ops for PowerPC. 236 setOperationAction(ISD::FFLOOR, MVT::ppcf128, Expand); 237 setOperationAction(ISD::FCEIL, MVT::ppcf128, Expand); 238 setOperationAction(ISD::FTRUNC, MVT::ppcf128, Expand); 239 setOperationAction(ISD::FRINT, MVT::ppcf128, Expand); 240 setOperationAction(ISD::FNEARBYINT, MVT::ppcf128, Expand); 241 setOperationAction(ISD::FREM, MVT::ppcf128, Expand); 242 243 // PowerPC has no SREM/UREM instructions unless we are on P9 244 // On P9 we may use a hardware instruction to compute the remainder. 245 // The instructions are not legalized directly because in the cases where the 246 // result of both the remainder and the division is required it is more 247 // efficient to compute the remainder from the result of the division rather 248 // than use the remainder instruction. 249 if (Subtarget.isISA3_0()) { 250 setOperationAction(ISD::SREM, MVT::i32, Custom); 251 setOperationAction(ISD::UREM, MVT::i32, Custom); 252 setOperationAction(ISD::SREM, MVT::i64, Custom); 253 setOperationAction(ISD::UREM, MVT::i64, Custom); 254 } else { 255 setOperationAction(ISD::SREM, MVT::i32, Expand); 256 setOperationAction(ISD::UREM, MVT::i32, Expand); 257 setOperationAction(ISD::SREM, MVT::i64, Expand); 258 setOperationAction(ISD::UREM, MVT::i64, Expand); 259 } 260 261 // Don't use SMUL_LOHI/UMUL_LOHI or SDIVREM/UDIVREM to lower SREM/UREM. 262 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand); 263 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand); 264 setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand); 265 setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand); 266 setOperationAction(ISD::UDIVREM, MVT::i32, Expand); 267 setOperationAction(ISD::SDIVREM, MVT::i32, Expand); 268 setOperationAction(ISD::UDIVREM, MVT::i64, Expand); 269 setOperationAction(ISD::SDIVREM, MVT::i64, Expand); 270 271 // We don't support sin/cos/sqrt/fmod/pow 272 setOperationAction(ISD::FSIN , MVT::f64, Expand); 273 setOperationAction(ISD::FCOS , MVT::f64, Expand); 274 setOperationAction(ISD::FSINCOS, MVT::f64, Expand); 275 setOperationAction(ISD::FREM , MVT::f64, Expand); 276 setOperationAction(ISD::FPOW , MVT::f64, Expand); 277 setOperationAction(ISD::FSIN , MVT::f32, Expand); 278 setOperationAction(ISD::FCOS , MVT::f32, Expand); 279 setOperationAction(ISD::FSINCOS, MVT::f32, Expand); 280 setOperationAction(ISD::FREM , MVT::f32, Expand); 281 setOperationAction(ISD::FPOW , MVT::f32, Expand); 282 if (Subtarget.hasSPE()) { 283 setOperationAction(ISD::FMA , MVT::f64, Expand); 284 setOperationAction(ISD::FMA , MVT::f32, Expand); 285 } else { 286 setOperationAction(ISD::FMA , MVT::f64, Legal); 287 setOperationAction(ISD::FMA , MVT::f32, Legal); 288 } 289 290 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom); 291 292 // If we're enabling GP optimizations, use hardware square root 293 if (!Subtarget.hasFSQRT() && 294 !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTE() && 295 Subtarget.hasFRE())) 296 setOperationAction(ISD::FSQRT, MVT::f64, Expand); 297 298 if (!Subtarget.hasFSQRT() && 299 !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTES() && 300 Subtarget.hasFRES())) 301 setOperationAction(ISD::FSQRT, MVT::f32, Expand); 302 303 if (Subtarget.hasFCPSGN()) { 304 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Legal); 305 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Legal); 306 } else { 307 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand); 308 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand); 309 } 310 311 if (Subtarget.hasFPRND()) { 312 setOperationAction(ISD::FFLOOR, MVT::f64, Legal); 313 setOperationAction(ISD::FCEIL, MVT::f64, Legal); 314 setOperationAction(ISD::FTRUNC, MVT::f64, Legal); 315 setOperationAction(ISD::FROUND, MVT::f64, Legal); 316 317 setOperationAction(ISD::FFLOOR, MVT::f32, Legal); 318 setOperationAction(ISD::FCEIL, MVT::f32, Legal); 319 setOperationAction(ISD::FTRUNC, MVT::f32, Legal); 320 setOperationAction(ISD::FROUND, MVT::f32, Legal); 321 } 322 323 // PowerPC does not have BSWAP, but we can use vector BSWAP instruction xxbrd 324 // to speed up scalar BSWAP64. 325 // CTPOP or CTTZ were introduced in P8/P9 respectively 326 setOperationAction(ISD::BSWAP, MVT::i32 , Expand); 327 if (Subtarget.hasP9Vector()) 328 setOperationAction(ISD::BSWAP, MVT::i64 , Custom); 329 else 330 setOperationAction(ISD::BSWAP, MVT::i64 , Expand); 331 if (Subtarget.isISA3_0()) { 332 setOperationAction(ISD::CTTZ , MVT::i32 , Legal); 333 setOperationAction(ISD::CTTZ , MVT::i64 , Legal); 334 } else { 335 setOperationAction(ISD::CTTZ , MVT::i32 , Expand); 336 setOperationAction(ISD::CTTZ , MVT::i64 , Expand); 337 } 338 339 if (Subtarget.hasPOPCNTD() == PPCSubtarget::POPCNTD_Fast) { 340 setOperationAction(ISD::CTPOP, MVT::i32 , Legal); 341 setOperationAction(ISD::CTPOP, MVT::i64 , Legal); 342 } else { 343 setOperationAction(ISD::CTPOP, MVT::i32 , Expand); 344 setOperationAction(ISD::CTPOP, MVT::i64 , Expand); 345 } 346 347 // PowerPC does not have ROTR 348 setOperationAction(ISD::ROTR, MVT::i32 , Expand); 349 setOperationAction(ISD::ROTR, MVT::i64 , Expand); 350 351 if (!Subtarget.useCRBits()) { 352 // PowerPC does not have Select 353 setOperationAction(ISD::SELECT, MVT::i32, Expand); 354 setOperationAction(ISD::SELECT, MVT::i64, Expand); 355 setOperationAction(ISD::SELECT, MVT::f32, Expand); 356 setOperationAction(ISD::SELECT, MVT::f64, Expand); 357 } 358 359 // PowerPC wants to turn select_cc of FP into fsel when possible. 360 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom); 361 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom); 362 363 // PowerPC wants to optimize integer setcc a bit 364 if (!Subtarget.useCRBits()) 365 setOperationAction(ISD::SETCC, MVT::i32, Custom); 366 367 // PowerPC does not have BRCOND which requires SetCC 368 if (!Subtarget.useCRBits()) 369 setOperationAction(ISD::BRCOND, MVT::Other, Expand); 370 371 setOperationAction(ISD::BR_JT, MVT::Other, Expand); 372 373 if (Subtarget.hasSPE()) { 374 // SPE has built-in conversions 375 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Legal); 376 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Legal); 377 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Legal); 378 } else { 379 // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores. 380 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 381 382 // PowerPC does not have [U|S]INT_TO_FP 383 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Expand); 384 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand); 385 } 386 387 if (Subtarget.hasDirectMove() && isPPC64) { 388 setOperationAction(ISD::BITCAST, MVT::f32, Legal); 389 setOperationAction(ISD::BITCAST, MVT::i32, Legal); 390 setOperationAction(ISD::BITCAST, MVT::i64, Legal); 391 setOperationAction(ISD::BITCAST, MVT::f64, Legal); 392 } else { 393 setOperationAction(ISD::BITCAST, MVT::f32, Expand); 394 setOperationAction(ISD::BITCAST, MVT::i32, Expand); 395 setOperationAction(ISD::BITCAST, MVT::i64, Expand); 396 setOperationAction(ISD::BITCAST, MVT::f64, Expand); 397 } 398 399 // We cannot sextinreg(i1). Expand to shifts. 400 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); 401 402 // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support 403 // SjLj exception handling but a light-weight setjmp/longjmp replacement to 404 // support continuation, user-level threading, and etc.. As a result, no 405 // other SjLj exception interfaces are implemented and please don't build 406 // your own exception handling based on them. 407 // LLVM/Clang supports zero-cost DWARF exception handling. 408 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom); 409 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom); 410 411 // We want to legalize GlobalAddress and ConstantPool nodes into the 412 // appropriate instructions to materialize the address. 413 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom); 414 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom); 415 setOperationAction(ISD::BlockAddress, MVT::i32, Custom); 416 setOperationAction(ISD::ConstantPool, MVT::i32, Custom); 417 setOperationAction(ISD::JumpTable, MVT::i32, Custom); 418 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom); 419 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom); 420 setOperationAction(ISD::BlockAddress, MVT::i64, Custom); 421 setOperationAction(ISD::ConstantPool, MVT::i64, Custom); 422 setOperationAction(ISD::JumpTable, MVT::i64, Custom); 423 424 // TRAP is legal. 425 setOperationAction(ISD::TRAP, MVT::Other, Legal); 426 427 // TRAMPOLINE is custom lowered. 428 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom); 429 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom); 430 431 // VASTART needs to be custom lowered to use the VarArgsFrameIndex 432 setOperationAction(ISD::VASTART , MVT::Other, Custom); 433 434 if (Subtarget.isSVR4ABI()) { 435 if (isPPC64) { 436 // VAARG always uses double-word chunks, so promote anything smaller. 437 setOperationAction(ISD::VAARG, MVT::i1, Promote); 438 AddPromotedToType (ISD::VAARG, MVT::i1, MVT::i64); 439 setOperationAction(ISD::VAARG, MVT::i8, Promote); 440 AddPromotedToType (ISD::VAARG, MVT::i8, MVT::i64); 441 setOperationAction(ISD::VAARG, MVT::i16, Promote); 442 AddPromotedToType (ISD::VAARG, MVT::i16, MVT::i64); 443 setOperationAction(ISD::VAARG, MVT::i32, Promote); 444 AddPromotedToType (ISD::VAARG, MVT::i32, MVT::i64); 445 setOperationAction(ISD::VAARG, MVT::Other, Expand); 446 } else { 447 // VAARG is custom lowered with the 32-bit SVR4 ABI. 448 setOperationAction(ISD::VAARG, MVT::Other, Custom); 449 setOperationAction(ISD::VAARG, MVT::i64, Custom); 450 } 451 } else 452 setOperationAction(ISD::VAARG, MVT::Other, Expand); 453 454 if (Subtarget.isSVR4ABI() && !isPPC64) 455 // VACOPY is custom lowered with the 32-bit SVR4 ABI. 456 setOperationAction(ISD::VACOPY , MVT::Other, Custom); 457 else 458 setOperationAction(ISD::VACOPY , MVT::Other, Expand); 459 460 // Use the default implementation. 461 setOperationAction(ISD::VAEND , MVT::Other, Expand); 462 setOperationAction(ISD::STACKSAVE , MVT::Other, Expand); 463 setOperationAction(ISD::STACKRESTORE , MVT::Other, Custom); 464 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32 , Custom); 465 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64 , Custom); 466 setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i32, Custom); 467 setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i64, Custom); 468 setOperationAction(ISD::EH_DWARF_CFA, MVT::i32, Custom); 469 setOperationAction(ISD::EH_DWARF_CFA, MVT::i64, Custom); 470 471 // We want to custom lower some of our intrinsics. 472 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 473 474 // To handle counter-based loop conditions. 475 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i1, Custom); 476 477 setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom); 478 setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom); 479 setOperationAction(ISD::INTRINSIC_VOID, MVT::i32, Custom); 480 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom); 481 482 // Comparisons that require checking two conditions. 483 if (Subtarget.hasSPE()) { 484 setCondCodeAction(ISD::SETO, MVT::f32, Expand); 485 setCondCodeAction(ISD::SETO, MVT::f64, Expand); 486 setCondCodeAction(ISD::SETUO, MVT::f32, Expand); 487 setCondCodeAction(ISD::SETUO, MVT::f64, Expand); 488 } 489 setCondCodeAction(ISD::SETULT, MVT::f32, Expand); 490 setCondCodeAction(ISD::SETULT, MVT::f64, Expand); 491 setCondCodeAction(ISD::SETUGT, MVT::f32, Expand); 492 setCondCodeAction(ISD::SETUGT, MVT::f64, Expand); 493 setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand); 494 setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand); 495 setCondCodeAction(ISD::SETOGE, MVT::f32, Expand); 496 setCondCodeAction(ISD::SETOGE, MVT::f64, Expand); 497 setCondCodeAction(ISD::SETOLE, MVT::f32, Expand); 498 setCondCodeAction(ISD::SETOLE, MVT::f64, Expand); 499 setCondCodeAction(ISD::SETONE, MVT::f32, Expand); 500 setCondCodeAction(ISD::SETONE, MVT::f64, Expand); 501 502 if (Subtarget.has64BitSupport()) { 503 // They also have instructions for converting between i64 and fp. 504 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom); 505 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand); 506 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom); 507 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand); 508 // This is just the low 32 bits of a (signed) fp->i64 conversion. 509 // We cannot do this with Promote because i64 is not a legal type. 510 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 511 512 if (Subtarget.hasLFIWAX() || Subtarget.isPPC64()) 513 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom); 514 } else { 515 // PowerPC does not have FP_TO_UINT on 32-bit implementations. 516 if (Subtarget.hasSPE()) 517 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Legal); 518 else 519 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand); 520 } 521 522 // With the instructions enabled under FPCVT, we can do everything. 523 if (Subtarget.hasFPCVT()) { 524 if (Subtarget.has64BitSupport()) { 525 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom); 526 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom); 527 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom); 528 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom); 529 } 530 531 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 532 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 533 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom); 534 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom); 535 } 536 537 if (Subtarget.use64BitRegs()) { 538 // 64-bit PowerPC implementations can support i64 types directly 539 addRegisterClass(MVT::i64, &PPC::G8RCRegClass); 540 // BUILD_PAIR can't be handled natively, and should be expanded to shl/or 541 setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand); 542 // 64-bit PowerPC wants to expand i128 shifts itself. 543 setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom); 544 setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom); 545 setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom); 546 } else { 547 // 32-bit PowerPC wants to expand i64 shifts itself. 548 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom); 549 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom); 550 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom); 551 } 552 553 if (Subtarget.hasAltivec()) { 554 // First set operation action for all vector types to expand. Then we 555 // will selectively turn on ones that can be effectively codegen'd. 556 for (MVT VT : MVT::vector_valuetypes()) { 557 // add/sub are legal for all supported vector VT's. 558 setOperationAction(ISD::ADD, VT, Legal); 559 setOperationAction(ISD::SUB, VT, Legal); 560 561 // For v2i64, these are only valid with P8Vector. This is corrected after 562 // the loop. 563 setOperationAction(ISD::SMAX, VT, Legal); 564 setOperationAction(ISD::SMIN, VT, Legal); 565 setOperationAction(ISD::UMAX, VT, Legal); 566 setOperationAction(ISD::UMIN, VT, Legal); 567 568 if (Subtarget.hasVSX()) { 569 setOperationAction(ISD::FMAXNUM, VT, Legal); 570 setOperationAction(ISD::FMINNUM, VT, Legal); 571 } 572 573 // Vector instructions introduced in P8 574 if (Subtarget.hasP8Altivec() && (VT.SimpleTy != MVT::v1i128)) { 575 setOperationAction(ISD::CTPOP, VT, Legal); 576 setOperationAction(ISD::CTLZ, VT, Legal); 577 } 578 else { 579 setOperationAction(ISD::CTPOP, VT, Expand); 580 setOperationAction(ISD::CTLZ, VT, Expand); 581 } 582 583 // Vector instructions introduced in P9 584 if (Subtarget.hasP9Altivec() && (VT.SimpleTy != MVT::v1i128)) 585 setOperationAction(ISD::CTTZ, VT, Legal); 586 else 587 setOperationAction(ISD::CTTZ, VT, Expand); 588 589 // We promote all shuffles to v16i8. 590 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Promote); 591 AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8); 592 593 // We promote all non-typed operations to v4i32. 594 setOperationAction(ISD::AND , VT, Promote); 595 AddPromotedToType (ISD::AND , VT, MVT::v4i32); 596 setOperationAction(ISD::OR , VT, Promote); 597 AddPromotedToType (ISD::OR , VT, MVT::v4i32); 598 setOperationAction(ISD::XOR , VT, Promote); 599 AddPromotedToType (ISD::XOR , VT, MVT::v4i32); 600 setOperationAction(ISD::LOAD , VT, Promote); 601 AddPromotedToType (ISD::LOAD , VT, MVT::v4i32); 602 setOperationAction(ISD::SELECT, VT, Promote); 603 AddPromotedToType (ISD::SELECT, VT, MVT::v4i32); 604 setOperationAction(ISD::VSELECT, VT, Legal); 605 setOperationAction(ISD::SELECT_CC, VT, Promote); 606 AddPromotedToType (ISD::SELECT_CC, VT, MVT::v4i32); 607 setOperationAction(ISD::STORE, VT, Promote); 608 AddPromotedToType (ISD::STORE, VT, MVT::v4i32); 609 610 // No other operations are legal. 611 setOperationAction(ISD::MUL , VT, Expand); 612 setOperationAction(ISD::SDIV, VT, Expand); 613 setOperationAction(ISD::SREM, VT, Expand); 614 setOperationAction(ISD::UDIV, VT, Expand); 615 setOperationAction(ISD::UREM, VT, Expand); 616 setOperationAction(ISD::FDIV, VT, Expand); 617 setOperationAction(ISD::FREM, VT, Expand); 618 setOperationAction(ISD::FNEG, VT, Expand); 619 setOperationAction(ISD::FSQRT, VT, Expand); 620 setOperationAction(ISD::FLOG, VT, Expand); 621 setOperationAction(ISD::FLOG10, VT, Expand); 622 setOperationAction(ISD::FLOG2, VT, Expand); 623 setOperationAction(ISD::FEXP, VT, Expand); 624 setOperationAction(ISD::FEXP2, VT, Expand); 625 setOperationAction(ISD::FSIN, VT, Expand); 626 setOperationAction(ISD::FCOS, VT, Expand); 627 setOperationAction(ISD::FABS, VT, Expand); 628 setOperationAction(ISD::FFLOOR, VT, Expand); 629 setOperationAction(ISD::FCEIL, VT, Expand); 630 setOperationAction(ISD::FTRUNC, VT, Expand); 631 setOperationAction(ISD::FRINT, VT, Expand); 632 setOperationAction(ISD::FNEARBYINT, VT, Expand); 633 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand); 634 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand); 635 setOperationAction(ISD::BUILD_VECTOR, VT, Expand); 636 setOperationAction(ISD::MULHU, VT, Expand); 637 setOperationAction(ISD::MULHS, VT, Expand); 638 setOperationAction(ISD::UMUL_LOHI, VT, Expand); 639 setOperationAction(ISD::SMUL_LOHI, VT, Expand); 640 setOperationAction(ISD::UDIVREM, VT, Expand); 641 setOperationAction(ISD::SDIVREM, VT, Expand); 642 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand); 643 setOperationAction(ISD::FPOW, VT, Expand); 644 setOperationAction(ISD::BSWAP, VT, Expand); 645 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand); 646 setOperationAction(ISD::ROTL, VT, Expand); 647 setOperationAction(ISD::ROTR, VT, Expand); 648 649 for (MVT InnerVT : MVT::vector_valuetypes()) { 650 setTruncStoreAction(VT, InnerVT, Expand); 651 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand); 652 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand); 653 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand); 654 } 655 } 656 if (!Subtarget.hasP8Vector()) { 657 setOperationAction(ISD::SMAX, MVT::v2i64, Expand); 658 setOperationAction(ISD::SMIN, MVT::v2i64, Expand); 659 setOperationAction(ISD::UMAX, MVT::v2i64, Expand); 660 setOperationAction(ISD::UMIN, MVT::v2i64, Expand); 661 } 662 663 for (auto VT : {MVT::v2i64, MVT::v4i32, MVT::v8i16, MVT::v16i8}) 664 setOperationAction(ISD::ABS, VT, Custom); 665 666 // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle 667 // with merges, splats, etc. 668 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom); 669 670 // Vector truncates to sub-word integer that fit in an Altivec/VSX register 671 // are cheap, so handle them before they get expanded to scalar. 672 setOperationAction(ISD::TRUNCATE, MVT::v8i8, Custom); 673 setOperationAction(ISD::TRUNCATE, MVT::v4i8, Custom); 674 setOperationAction(ISD::TRUNCATE, MVT::v2i8, Custom); 675 setOperationAction(ISD::TRUNCATE, MVT::v4i16, Custom); 676 setOperationAction(ISD::TRUNCATE, MVT::v2i16, Custom); 677 678 setOperationAction(ISD::AND , MVT::v4i32, Legal); 679 setOperationAction(ISD::OR , MVT::v4i32, Legal); 680 setOperationAction(ISD::XOR , MVT::v4i32, Legal); 681 setOperationAction(ISD::LOAD , MVT::v4i32, Legal); 682 setOperationAction(ISD::SELECT, MVT::v4i32, 683 Subtarget.useCRBits() ? Legal : Expand); 684 setOperationAction(ISD::STORE , MVT::v4i32, Legal); 685 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal); 686 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal); 687 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal); 688 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal); 689 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal); 690 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal); 691 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal); 692 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal); 693 694 // Without hasP8Altivec set, v2i64 SMAX isn't available. 695 // But ABS custom lowering requires SMAX support. 696 if (!Subtarget.hasP8Altivec()) 697 setOperationAction(ISD::ABS, MVT::v2i64, Expand); 698 699 addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass); 700 addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass); 701 addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass); 702 addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass); 703 704 setOperationAction(ISD::MUL, MVT::v4f32, Legal); 705 setOperationAction(ISD::FMA, MVT::v4f32, Legal); 706 707 if (TM.Options.UnsafeFPMath || Subtarget.hasVSX()) { 708 setOperationAction(ISD::FDIV, MVT::v4f32, Legal); 709 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal); 710 } 711 712 if (Subtarget.hasP8Altivec()) 713 setOperationAction(ISD::MUL, MVT::v4i32, Legal); 714 else 715 setOperationAction(ISD::MUL, MVT::v4i32, Custom); 716 717 setOperationAction(ISD::MUL, MVT::v8i16, Custom); 718 setOperationAction(ISD::MUL, MVT::v16i8, Custom); 719 720 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom); 721 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom); 722 723 setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom); 724 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom); 725 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom); 726 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom); 727 728 // Altivec does not contain unordered floating-point compare instructions 729 setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand); 730 setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand); 731 setCondCodeAction(ISD::SETO, MVT::v4f32, Expand); 732 setCondCodeAction(ISD::SETONE, MVT::v4f32, Expand); 733 734 if (Subtarget.hasVSX()) { 735 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal); 736 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal); 737 if (Subtarget.hasP8Vector()) { 738 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal); 739 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Legal); 740 } 741 if (Subtarget.hasDirectMove() && isPPC64) { 742 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Legal); 743 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Legal); 744 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Legal); 745 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i64, Legal); 746 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Legal); 747 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Legal); 748 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Legal); 749 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal); 750 } 751 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal); 752 753 setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal); 754 setOperationAction(ISD::FCEIL, MVT::v2f64, Legal); 755 setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal); 756 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal); 757 setOperationAction(ISD::FROUND, MVT::v2f64, Legal); 758 759 setOperationAction(ISD::FROUND, MVT::v4f32, Legal); 760 761 setOperationAction(ISD::MUL, MVT::v2f64, Legal); 762 setOperationAction(ISD::FMA, MVT::v2f64, Legal); 763 764 setOperationAction(ISD::FDIV, MVT::v2f64, Legal); 765 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal); 766 767 // Share the Altivec comparison restrictions. 768 setCondCodeAction(ISD::SETUO, MVT::v2f64, Expand); 769 setCondCodeAction(ISD::SETUEQ, MVT::v2f64, Expand); 770 setCondCodeAction(ISD::SETO, MVT::v2f64, Expand); 771 setCondCodeAction(ISD::SETONE, MVT::v2f64, Expand); 772 773 setOperationAction(ISD::LOAD, MVT::v2f64, Legal); 774 setOperationAction(ISD::STORE, MVT::v2f64, Legal); 775 776 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Legal); 777 778 if (Subtarget.hasP8Vector()) 779 addRegisterClass(MVT::f32, &PPC::VSSRCRegClass); 780 781 addRegisterClass(MVT::f64, &PPC::VSFRCRegClass); 782 783 addRegisterClass(MVT::v4i32, &PPC::VSRCRegClass); 784 addRegisterClass(MVT::v4f32, &PPC::VSRCRegClass); 785 addRegisterClass(MVT::v2f64, &PPC::VSRCRegClass); 786 787 if (Subtarget.hasP8Altivec()) { 788 setOperationAction(ISD::SHL, MVT::v2i64, Legal); 789 setOperationAction(ISD::SRA, MVT::v2i64, Legal); 790 setOperationAction(ISD::SRL, MVT::v2i64, Legal); 791 792 // 128 bit shifts can be accomplished via 3 instructions for SHL and 793 // SRL, but not for SRA because of the instructions available: 794 // VS{RL} and VS{RL}O. However due to direct move costs, it's not worth 795 // doing 796 setOperationAction(ISD::SHL, MVT::v1i128, Expand); 797 setOperationAction(ISD::SRL, MVT::v1i128, Expand); 798 setOperationAction(ISD::SRA, MVT::v1i128, Expand); 799 800 setOperationAction(ISD::SETCC, MVT::v2i64, Legal); 801 } 802 else { 803 setOperationAction(ISD::SHL, MVT::v2i64, Expand); 804 setOperationAction(ISD::SRA, MVT::v2i64, Expand); 805 setOperationAction(ISD::SRL, MVT::v2i64, Expand); 806 807 setOperationAction(ISD::SETCC, MVT::v2i64, Custom); 808 809 // VSX v2i64 only supports non-arithmetic operations. 810 setOperationAction(ISD::ADD, MVT::v2i64, Expand); 811 setOperationAction(ISD::SUB, MVT::v2i64, Expand); 812 } 813 814 setOperationAction(ISD::LOAD, MVT::v2i64, Promote); 815 AddPromotedToType (ISD::LOAD, MVT::v2i64, MVT::v2f64); 816 setOperationAction(ISD::STORE, MVT::v2i64, Promote); 817 AddPromotedToType (ISD::STORE, MVT::v2i64, MVT::v2f64); 818 819 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Legal); 820 821 setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal); 822 setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal); 823 setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal); 824 setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal); 825 826 // Custom handling for partial vectors of integers converted to 827 // floating point. We already have optimal handling for v2i32 through 828 // the DAG combine, so those aren't necessary. 829 setOperationAction(ISD::UINT_TO_FP, MVT::v2i8, Custom); 830 setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Custom); 831 setOperationAction(ISD::UINT_TO_FP, MVT::v2i16, Custom); 832 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom); 833 setOperationAction(ISD::SINT_TO_FP, MVT::v2i8, Custom); 834 setOperationAction(ISD::SINT_TO_FP, MVT::v4i8, Custom); 835 setOperationAction(ISD::SINT_TO_FP, MVT::v2i16, Custom); 836 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom); 837 838 setOperationAction(ISD::FNEG, MVT::v4f32, Legal); 839 setOperationAction(ISD::FNEG, MVT::v2f64, Legal); 840 setOperationAction(ISD::FABS, MVT::v4f32, Legal); 841 setOperationAction(ISD::FABS, MVT::v2f64, Legal); 842 setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Legal); 843 setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Legal); 844 845 if (Subtarget.hasDirectMove()) 846 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom); 847 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom); 848 849 addRegisterClass(MVT::v2i64, &PPC::VSRCRegClass); 850 } 851 852 if (Subtarget.hasP8Altivec()) { 853 addRegisterClass(MVT::v2i64, &PPC::VRRCRegClass); 854 addRegisterClass(MVT::v1i128, &PPC::VRRCRegClass); 855 } 856 857 if (Subtarget.hasP9Vector()) { 858 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom); 859 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom); 860 861 // 128 bit shifts can be accomplished via 3 instructions for SHL and 862 // SRL, but not for SRA because of the instructions available: 863 // VS{RL} and VS{RL}O. 864 setOperationAction(ISD::SHL, MVT::v1i128, Legal); 865 setOperationAction(ISD::SRL, MVT::v1i128, Legal); 866 setOperationAction(ISD::SRA, MVT::v1i128, Expand); 867 868 if (EnableQuadPrecision) { 869 addRegisterClass(MVT::f128, &PPC::VRRCRegClass); 870 setOperationAction(ISD::FADD, MVT::f128, Legal); 871 setOperationAction(ISD::FSUB, MVT::f128, Legal); 872 setOperationAction(ISD::FDIV, MVT::f128, Legal); 873 setOperationAction(ISD::FMUL, MVT::f128, Legal); 874 setOperationAction(ISD::FP_EXTEND, MVT::f128, Legal); 875 // No extending loads to f128 on PPC. 876 for (MVT FPT : MVT::fp_valuetypes()) 877 setLoadExtAction(ISD::EXTLOAD, MVT::f128, FPT, Expand); 878 setOperationAction(ISD::FMA, MVT::f128, Legal); 879 setCondCodeAction(ISD::SETULT, MVT::f128, Expand); 880 setCondCodeAction(ISD::SETUGT, MVT::f128, Expand); 881 setCondCodeAction(ISD::SETUEQ, MVT::f128, Expand); 882 setCondCodeAction(ISD::SETOGE, MVT::f128, Expand); 883 setCondCodeAction(ISD::SETOLE, MVT::f128, Expand); 884 setCondCodeAction(ISD::SETONE, MVT::f128, Expand); 885 886 setOperationAction(ISD::FTRUNC, MVT::f128, Legal); 887 setOperationAction(ISD::FRINT, MVT::f128, Legal); 888 setOperationAction(ISD::FFLOOR, MVT::f128, Legal); 889 setOperationAction(ISD::FCEIL, MVT::f128, Legal); 890 setOperationAction(ISD::FNEARBYINT, MVT::f128, Legal); 891 setOperationAction(ISD::FROUND, MVT::f128, Legal); 892 893 setOperationAction(ISD::SELECT, MVT::f128, Expand); 894 setOperationAction(ISD::FP_ROUND, MVT::f64, Legal); 895 setOperationAction(ISD::FP_ROUND, MVT::f32, Legal); 896 setTruncStoreAction(MVT::f128, MVT::f64, Expand); 897 setTruncStoreAction(MVT::f128, MVT::f32, Expand); 898 setOperationAction(ISD::BITCAST, MVT::i128, Custom); 899 // No implementation for these ops for PowerPC. 900 setOperationAction(ISD::FSIN , MVT::f128, Expand); 901 setOperationAction(ISD::FCOS , MVT::f128, Expand); 902 setOperationAction(ISD::FPOW, MVT::f128, Expand); 903 setOperationAction(ISD::FPOWI, MVT::f128, Expand); 904 setOperationAction(ISD::FREM, MVT::f128, Expand); 905 } 906 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom); 907 908 } 909 910 if (Subtarget.hasP9Altivec()) { 911 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom); 912 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom); 913 } 914 } 915 916 if (Subtarget.hasQPX()) { 917 setOperationAction(ISD::FADD, MVT::v4f64, Legal); 918 setOperationAction(ISD::FSUB, MVT::v4f64, Legal); 919 setOperationAction(ISD::FMUL, MVT::v4f64, Legal); 920 setOperationAction(ISD::FREM, MVT::v4f64, Expand); 921 922 setOperationAction(ISD::FCOPYSIGN, MVT::v4f64, Legal); 923 setOperationAction(ISD::FGETSIGN, MVT::v4f64, Expand); 924 925 setOperationAction(ISD::LOAD , MVT::v4f64, Custom); 926 setOperationAction(ISD::STORE , MVT::v4f64, Custom); 927 928 setTruncStoreAction(MVT::v4f64, MVT::v4f32, Custom); 929 setLoadExtAction(ISD::EXTLOAD, MVT::v4f64, MVT::v4f32, Custom); 930 931 if (!Subtarget.useCRBits()) 932 setOperationAction(ISD::SELECT, MVT::v4f64, Expand); 933 setOperationAction(ISD::VSELECT, MVT::v4f64, Legal); 934 935 setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f64, Legal); 936 setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f64, Expand); 937 setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f64, Expand); 938 setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f64, Expand); 939 setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f64, Custom); 940 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f64, Legal); 941 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f64, Custom); 942 943 setOperationAction(ISD::FP_TO_SINT , MVT::v4f64, Legal); 944 setOperationAction(ISD::FP_TO_UINT , MVT::v4f64, Expand); 945 946 setOperationAction(ISD::FP_ROUND , MVT::v4f32, Legal); 947 setOperationAction(ISD::FP_ROUND_INREG , MVT::v4f32, Expand); 948 setOperationAction(ISD::FP_EXTEND, MVT::v4f64, Legal); 949 950 setOperationAction(ISD::FNEG , MVT::v4f64, Legal); 951 setOperationAction(ISD::FABS , MVT::v4f64, Legal); 952 setOperationAction(ISD::FSIN , MVT::v4f64, Expand); 953 setOperationAction(ISD::FCOS , MVT::v4f64, Expand); 954 setOperationAction(ISD::FPOW , MVT::v4f64, Expand); 955 setOperationAction(ISD::FLOG , MVT::v4f64, Expand); 956 setOperationAction(ISD::FLOG2 , MVT::v4f64, Expand); 957 setOperationAction(ISD::FLOG10 , MVT::v4f64, Expand); 958 setOperationAction(ISD::FEXP , MVT::v4f64, Expand); 959 setOperationAction(ISD::FEXP2 , MVT::v4f64, Expand); 960 961 setOperationAction(ISD::FMINNUM, MVT::v4f64, Legal); 962 setOperationAction(ISD::FMAXNUM, MVT::v4f64, Legal); 963 964 setIndexedLoadAction(ISD::PRE_INC, MVT::v4f64, Legal); 965 setIndexedStoreAction(ISD::PRE_INC, MVT::v4f64, Legal); 966 967 addRegisterClass(MVT::v4f64, &PPC::QFRCRegClass); 968 969 setOperationAction(ISD::FADD, MVT::v4f32, Legal); 970 setOperationAction(ISD::FSUB, MVT::v4f32, Legal); 971 setOperationAction(ISD::FMUL, MVT::v4f32, Legal); 972 setOperationAction(ISD::FREM, MVT::v4f32, Expand); 973 974 setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Legal); 975 setOperationAction(ISD::FGETSIGN, MVT::v4f32, Expand); 976 977 setOperationAction(ISD::LOAD , MVT::v4f32, Custom); 978 setOperationAction(ISD::STORE , MVT::v4f32, Custom); 979 980 if (!Subtarget.useCRBits()) 981 setOperationAction(ISD::SELECT, MVT::v4f32, Expand); 982 setOperationAction(ISD::VSELECT, MVT::v4f32, Legal); 983 984 setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f32, Legal); 985 setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f32, Expand); 986 setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f32, Expand); 987 setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f32, Expand); 988 setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f32, Custom); 989 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal); 990 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom); 991 992 setOperationAction(ISD::FP_TO_SINT , MVT::v4f32, Legal); 993 setOperationAction(ISD::FP_TO_UINT , MVT::v4f32, Expand); 994 995 setOperationAction(ISD::FNEG , MVT::v4f32, Legal); 996 setOperationAction(ISD::FABS , MVT::v4f32, Legal); 997 setOperationAction(ISD::FSIN , MVT::v4f32, Expand); 998 setOperationAction(ISD::FCOS , MVT::v4f32, Expand); 999 setOperationAction(ISD::FPOW , MVT::v4f32, Expand); 1000 setOperationAction(ISD::FLOG , MVT::v4f32, Expand); 1001 setOperationAction(ISD::FLOG2 , MVT::v4f32, Expand); 1002 setOperationAction(ISD::FLOG10 , MVT::v4f32, Expand); 1003 setOperationAction(ISD::FEXP , MVT::v4f32, Expand); 1004 setOperationAction(ISD::FEXP2 , MVT::v4f32, Expand); 1005 1006 setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal); 1007 setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal); 1008 1009 setIndexedLoadAction(ISD::PRE_INC, MVT::v4f32, Legal); 1010 setIndexedStoreAction(ISD::PRE_INC, MVT::v4f32, Legal); 1011 1012 addRegisterClass(MVT::v4f32, &PPC::QSRCRegClass); 1013 1014 setOperationAction(ISD::AND , MVT::v4i1, Legal); 1015 setOperationAction(ISD::OR , MVT::v4i1, Legal); 1016 setOperationAction(ISD::XOR , MVT::v4i1, Legal); 1017 1018 if (!Subtarget.useCRBits()) 1019 setOperationAction(ISD::SELECT, MVT::v4i1, Expand); 1020 setOperationAction(ISD::VSELECT, MVT::v4i1, Legal); 1021 1022 setOperationAction(ISD::LOAD , MVT::v4i1, Custom); 1023 setOperationAction(ISD::STORE , MVT::v4i1, Custom); 1024 1025 setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4i1, Custom); 1026 setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4i1, Expand); 1027 setOperationAction(ISD::CONCAT_VECTORS , MVT::v4i1, Expand); 1028 setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4i1, Expand); 1029 setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4i1, Custom); 1030 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i1, Expand); 1031 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i1, Custom); 1032 1033 setOperationAction(ISD::SINT_TO_FP, MVT::v4i1, Custom); 1034 setOperationAction(ISD::UINT_TO_FP, MVT::v4i1, Custom); 1035 1036 addRegisterClass(MVT::v4i1, &PPC::QBRCRegClass); 1037 1038 setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal); 1039 setOperationAction(ISD::FCEIL, MVT::v4f64, Legal); 1040 setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal); 1041 setOperationAction(ISD::FROUND, MVT::v4f64, Legal); 1042 1043 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal); 1044 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal); 1045 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal); 1046 setOperationAction(ISD::FROUND, MVT::v4f32, Legal); 1047 1048 setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Expand); 1049 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand); 1050 1051 // These need to set FE_INEXACT, and so cannot be vectorized here. 1052 setOperationAction(ISD::FRINT, MVT::v4f64, Expand); 1053 setOperationAction(ISD::FRINT, MVT::v4f32, Expand); 1054 1055 if (TM.Options.UnsafeFPMath) { 1056 setOperationAction(ISD::FDIV, MVT::v4f64, Legal); 1057 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal); 1058 1059 setOperationAction(ISD::FDIV, MVT::v4f32, Legal); 1060 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal); 1061 } else { 1062 setOperationAction(ISD::FDIV, MVT::v4f64, Expand); 1063 setOperationAction(ISD::FSQRT, MVT::v4f64, Expand); 1064 1065 setOperationAction(ISD::FDIV, MVT::v4f32, Expand); 1066 setOperationAction(ISD::FSQRT, MVT::v4f32, Expand); 1067 } 1068 } 1069 1070 if (Subtarget.has64BitSupport()) 1071 setOperationAction(ISD::PREFETCH, MVT::Other, Legal); 1072 1073 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, isPPC64 ? Legal : Custom); 1074 1075 if (!isPPC64) { 1076 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Expand); 1077 setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand); 1078 } 1079 1080 setBooleanContents(ZeroOrOneBooleanContent); 1081 1082 if (Subtarget.hasAltivec()) { 1083 // Altivec instructions set fields to all zeros or all ones. 1084 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent); 1085 } 1086 1087 if (!isPPC64) { 1088 // These libcalls are not available in 32-bit. 1089 setLibcallName(RTLIB::SHL_I128, nullptr); 1090 setLibcallName(RTLIB::SRL_I128, nullptr); 1091 setLibcallName(RTLIB::SRA_I128, nullptr); 1092 } 1093 1094 setStackPointerRegisterToSaveRestore(isPPC64 ? PPC::X1 : PPC::R1); 1095 1096 // We have target-specific dag combine patterns for the following nodes: 1097 setTargetDAGCombine(ISD::ADD); 1098 setTargetDAGCombine(ISD::SHL); 1099 setTargetDAGCombine(ISD::SRA); 1100 setTargetDAGCombine(ISD::SRL); 1101 setTargetDAGCombine(ISD::MUL); 1102 setTargetDAGCombine(ISD::SINT_TO_FP); 1103 setTargetDAGCombine(ISD::BUILD_VECTOR); 1104 if (Subtarget.hasFPCVT()) 1105 setTargetDAGCombine(ISD::UINT_TO_FP); 1106 setTargetDAGCombine(ISD::LOAD); 1107 setTargetDAGCombine(ISD::STORE); 1108 setTargetDAGCombine(ISD::BR_CC); 1109 if (Subtarget.useCRBits()) 1110 setTargetDAGCombine(ISD::BRCOND); 1111 setTargetDAGCombine(ISD::BSWAP); 1112 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN); 1113 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN); 1114 setTargetDAGCombine(ISD::INTRINSIC_VOID); 1115 1116 setTargetDAGCombine(ISD::SIGN_EXTEND); 1117 setTargetDAGCombine(ISD::ZERO_EXTEND); 1118 setTargetDAGCombine(ISD::ANY_EXTEND); 1119 1120 setTargetDAGCombine(ISD::TRUNCATE); 1121 setTargetDAGCombine(ISD::VECTOR_SHUFFLE); 1122 1123 1124 if (Subtarget.useCRBits()) { 1125 setTargetDAGCombine(ISD::TRUNCATE); 1126 setTargetDAGCombine(ISD::SETCC); 1127 setTargetDAGCombine(ISD::SELECT_CC); 1128 } 1129 1130 // Use reciprocal estimates. 1131 if (TM.Options.UnsafeFPMath) { 1132 setTargetDAGCombine(ISD::FDIV); 1133 setTargetDAGCombine(ISD::FSQRT); 1134 } 1135 1136 if (Subtarget.hasP9Altivec()) { 1137 setTargetDAGCombine(ISD::ABS); 1138 setTargetDAGCombine(ISD::VSELECT); 1139 } 1140 1141 // Darwin long double math library functions have $LDBL128 appended. 1142 if (Subtarget.isDarwin()) { 1143 setLibcallName(RTLIB::COS_PPCF128, "cosl$LDBL128"); 1144 setLibcallName(RTLIB::POW_PPCF128, "powl$LDBL128"); 1145 setLibcallName(RTLIB::REM_PPCF128, "fmodl$LDBL128"); 1146 setLibcallName(RTLIB::SIN_PPCF128, "sinl$LDBL128"); 1147 setLibcallName(RTLIB::SQRT_PPCF128, "sqrtl$LDBL128"); 1148 setLibcallName(RTLIB::LOG_PPCF128, "logl$LDBL128"); 1149 setLibcallName(RTLIB::LOG2_PPCF128, "log2l$LDBL128"); 1150 setLibcallName(RTLIB::LOG10_PPCF128, "log10l$LDBL128"); 1151 setLibcallName(RTLIB::EXP_PPCF128, "expl$LDBL128"); 1152 setLibcallName(RTLIB::EXP2_PPCF128, "exp2l$LDBL128"); 1153 } 1154 1155 if (EnableQuadPrecision) { 1156 setLibcallName(RTLIB::LOG_F128, "logf128"); 1157 setLibcallName(RTLIB::LOG2_F128, "log2f128"); 1158 setLibcallName(RTLIB::LOG10_F128, "log10f128"); 1159 setLibcallName(RTLIB::EXP_F128, "expf128"); 1160 setLibcallName(RTLIB::EXP2_F128, "exp2f128"); 1161 setLibcallName(RTLIB::SIN_F128, "sinf128"); 1162 setLibcallName(RTLIB::COS_F128, "cosf128"); 1163 setLibcallName(RTLIB::POW_F128, "powf128"); 1164 setLibcallName(RTLIB::FMIN_F128, "fminf128"); 1165 setLibcallName(RTLIB::FMAX_F128, "fmaxf128"); 1166 setLibcallName(RTLIB::POWI_F128, "__powikf2"); 1167 setLibcallName(RTLIB::REM_F128, "fmodf128"); 1168 } 1169 1170 // With 32 condition bits, we don't need to sink (and duplicate) compares 1171 // aggressively in CodeGenPrep. 1172 if (Subtarget.useCRBits()) { 1173 setHasMultipleConditionRegisters(); 1174 setJumpIsExpensive(); 1175 } 1176 1177 setMinFunctionAlignment(2); 1178 if (Subtarget.isDarwin()) 1179 setPrefFunctionAlignment(4); 1180 1181 switch (Subtarget.getDarwinDirective()) { 1182 default: break; 1183 case PPC::DIR_970: 1184 case PPC::DIR_A2: 1185 case PPC::DIR_E500: 1186 case PPC::DIR_E500mc: 1187 case PPC::DIR_E5500: 1188 case PPC::DIR_PWR4: 1189 case PPC::DIR_PWR5: 1190 case PPC::DIR_PWR5X: 1191 case PPC::DIR_PWR6: 1192 case PPC::DIR_PWR6X: 1193 case PPC::DIR_PWR7: 1194 case PPC::DIR_PWR8: 1195 case PPC::DIR_PWR9: 1196 setPrefFunctionAlignment(4); 1197 setPrefLoopAlignment(4); 1198 break; 1199 } 1200 1201 if (Subtarget.enableMachineScheduler()) 1202 setSchedulingPreference(Sched::Source); 1203 else 1204 setSchedulingPreference(Sched::Hybrid); 1205 1206 computeRegisterProperties(STI.getRegisterInfo()); 1207 1208 // The Freescale cores do better with aggressive inlining of memcpy and 1209 // friends. GCC uses same threshold of 128 bytes (= 32 word stores). 1210 if (Subtarget.getDarwinDirective() == PPC::DIR_E500mc || 1211 Subtarget.getDarwinDirective() == PPC::DIR_E5500) { 1212 MaxStoresPerMemset = 32; 1213 MaxStoresPerMemsetOptSize = 16; 1214 MaxStoresPerMemcpy = 32; 1215 MaxStoresPerMemcpyOptSize = 8; 1216 MaxStoresPerMemmove = 32; 1217 MaxStoresPerMemmoveOptSize = 8; 1218 } else if (Subtarget.getDarwinDirective() == PPC::DIR_A2) { 1219 // The A2 also benefits from (very) aggressive inlining of memcpy and 1220 // friends. The overhead of a the function call, even when warm, can be 1221 // over one hundred cycles. 1222 MaxStoresPerMemset = 128; 1223 MaxStoresPerMemcpy = 128; 1224 MaxStoresPerMemmove = 128; 1225 MaxLoadsPerMemcmp = 128; 1226 } else { 1227 MaxLoadsPerMemcmp = 8; 1228 MaxLoadsPerMemcmpOptSize = 4; 1229 } 1230 } 1231 1232 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine 1233 /// the desired ByVal argument alignment. 1234 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign, 1235 unsigned MaxMaxAlign) { 1236 if (MaxAlign == MaxMaxAlign) 1237 return; 1238 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) { 1239 if (MaxMaxAlign >= 32 && VTy->getBitWidth() >= 256) 1240 MaxAlign = 32; 1241 else if (VTy->getBitWidth() >= 128 && MaxAlign < 16) 1242 MaxAlign = 16; 1243 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) { 1244 unsigned EltAlign = 0; 1245 getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign); 1246 if (EltAlign > MaxAlign) 1247 MaxAlign = EltAlign; 1248 } else if (StructType *STy = dyn_cast<StructType>(Ty)) { 1249 for (auto *EltTy : STy->elements()) { 1250 unsigned EltAlign = 0; 1251 getMaxByValAlign(EltTy, EltAlign, MaxMaxAlign); 1252 if (EltAlign > MaxAlign) 1253 MaxAlign = EltAlign; 1254 if (MaxAlign == MaxMaxAlign) 1255 break; 1256 } 1257 } 1258 } 1259 1260 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate 1261 /// function arguments in the caller parameter area. 1262 unsigned PPCTargetLowering::getByValTypeAlignment(Type *Ty, 1263 const DataLayout &DL) const { 1264 // Darwin passes everything on 4 byte boundary. 1265 if (Subtarget.isDarwin()) 1266 return 4; 1267 1268 // 16byte and wider vectors are passed on 16byte boundary. 1269 // The rest is 8 on PPC64 and 4 on PPC32 boundary. 1270 unsigned Align = Subtarget.isPPC64() ? 8 : 4; 1271 if (Subtarget.hasAltivec() || Subtarget.hasQPX()) 1272 getMaxByValAlign(Ty, Align, Subtarget.hasQPX() ? 32 : 16); 1273 return Align; 1274 } 1275 1276 bool PPCTargetLowering::useSoftFloat() const { 1277 return Subtarget.useSoftFloat(); 1278 } 1279 1280 bool PPCTargetLowering::hasSPE() const { 1281 return Subtarget.hasSPE(); 1282 } 1283 1284 bool PPCTargetLowering::preferIncOfAddToSubOfNot(EVT VT) const { 1285 return VT.isScalarInteger(); 1286 } 1287 1288 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const { 1289 switch ((PPCISD::NodeType)Opcode) { 1290 case PPCISD::FIRST_NUMBER: break; 1291 case PPCISD::FSEL: return "PPCISD::FSEL"; 1292 case PPCISD::FCFID: return "PPCISD::FCFID"; 1293 case PPCISD::FCFIDU: return "PPCISD::FCFIDU"; 1294 case PPCISD::FCFIDS: return "PPCISD::FCFIDS"; 1295 case PPCISD::FCFIDUS: return "PPCISD::FCFIDUS"; 1296 case PPCISD::FCTIDZ: return "PPCISD::FCTIDZ"; 1297 case PPCISD::FCTIWZ: return "PPCISD::FCTIWZ"; 1298 case PPCISD::FCTIDUZ: return "PPCISD::FCTIDUZ"; 1299 case PPCISD::FCTIWUZ: return "PPCISD::FCTIWUZ"; 1300 case PPCISD::FP_TO_UINT_IN_VSR: 1301 return "PPCISD::FP_TO_UINT_IN_VSR,"; 1302 case PPCISD::FP_TO_SINT_IN_VSR: 1303 return "PPCISD::FP_TO_SINT_IN_VSR"; 1304 case PPCISD::FRE: return "PPCISD::FRE"; 1305 case PPCISD::FRSQRTE: return "PPCISD::FRSQRTE"; 1306 case PPCISD::STFIWX: return "PPCISD::STFIWX"; 1307 case PPCISD::VMADDFP: return "PPCISD::VMADDFP"; 1308 case PPCISD::VNMSUBFP: return "PPCISD::VNMSUBFP"; 1309 case PPCISD::VPERM: return "PPCISD::VPERM"; 1310 case PPCISD::XXSPLT: return "PPCISD::XXSPLT"; 1311 case PPCISD::VECINSERT: return "PPCISD::VECINSERT"; 1312 case PPCISD::XXREVERSE: return "PPCISD::XXREVERSE"; 1313 case PPCISD::XXPERMDI: return "PPCISD::XXPERMDI"; 1314 case PPCISD::VECSHL: return "PPCISD::VECSHL"; 1315 case PPCISD::CMPB: return "PPCISD::CMPB"; 1316 case PPCISD::Hi: return "PPCISD::Hi"; 1317 case PPCISD::Lo: return "PPCISD::Lo"; 1318 case PPCISD::TOC_ENTRY: return "PPCISD::TOC_ENTRY"; 1319 case PPCISD::ATOMIC_CMP_SWAP_8: return "PPCISD::ATOMIC_CMP_SWAP_8"; 1320 case PPCISD::ATOMIC_CMP_SWAP_16: return "PPCISD::ATOMIC_CMP_SWAP_16"; 1321 case PPCISD::DYNALLOC: return "PPCISD::DYNALLOC"; 1322 case PPCISD::DYNAREAOFFSET: return "PPCISD::DYNAREAOFFSET"; 1323 case PPCISD::GlobalBaseReg: return "PPCISD::GlobalBaseReg"; 1324 case PPCISD::SRL: return "PPCISD::SRL"; 1325 case PPCISD::SRA: return "PPCISD::SRA"; 1326 case PPCISD::SHL: return "PPCISD::SHL"; 1327 case PPCISD::SRA_ADDZE: return "PPCISD::SRA_ADDZE"; 1328 case PPCISD::CALL: return "PPCISD::CALL"; 1329 case PPCISD::CALL_NOP: return "PPCISD::CALL_NOP"; 1330 case PPCISD::MTCTR: return "PPCISD::MTCTR"; 1331 case PPCISD::BCTRL: return "PPCISD::BCTRL"; 1332 case PPCISD::BCTRL_LOAD_TOC: return "PPCISD::BCTRL_LOAD_TOC"; 1333 case PPCISD::RET_FLAG: return "PPCISD::RET_FLAG"; 1334 case PPCISD::READ_TIME_BASE: return "PPCISD::READ_TIME_BASE"; 1335 case PPCISD::EH_SJLJ_SETJMP: return "PPCISD::EH_SJLJ_SETJMP"; 1336 case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP"; 1337 case PPCISD::MFOCRF: return "PPCISD::MFOCRF"; 1338 case PPCISD::MFVSR: return "PPCISD::MFVSR"; 1339 case PPCISD::MTVSRA: return "PPCISD::MTVSRA"; 1340 case PPCISD::MTVSRZ: return "PPCISD::MTVSRZ"; 1341 case PPCISD::SINT_VEC_TO_FP: return "PPCISD::SINT_VEC_TO_FP"; 1342 case PPCISD::UINT_VEC_TO_FP: return "PPCISD::UINT_VEC_TO_FP"; 1343 case PPCISD::ANDIo_1_EQ_BIT: return "PPCISD::ANDIo_1_EQ_BIT"; 1344 case PPCISD::ANDIo_1_GT_BIT: return "PPCISD::ANDIo_1_GT_BIT"; 1345 case PPCISD::VCMP: return "PPCISD::VCMP"; 1346 case PPCISD::VCMPo: return "PPCISD::VCMPo"; 1347 case PPCISD::LBRX: return "PPCISD::LBRX"; 1348 case PPCISD::STBRX: return "PPCISD::STBRX"; 1349 case PPCISD::LFIWAX: return "PPCISD::LFIWAX"; 1350 case PPCISD::LFIWZX: return "PPCISD::LFIWZX"; 1351 case PPCISD::LXSIZX: return "PPCISD::LXSIZX"; 1352 case PPCISD::STXSIX: return "PPCISD::STXSIX"; 1353 case PPCISD::VEXTS: return "PPCISD::VEXTS"; 1354 case PPCISD::SExtVElems: return "PPCISD::SExtVElems"; 1355 case PPCISD::LXVD2X: return "PPCISD::LXVD2X"; 1356 case PPCISD::STXVD2X: return "PPCISD::STXVD2X"; 1357 case PPCISD::LOAD_VEC_BE: return "PPCISD::LOAD_VEC_BE"; 1358 case PPCISD::STORE_VEC_BE: return "PPCISD::STORE_VEC_BE"; 1359 case PPCISD::ST_VSR_SCAL_INT: 1360 return "PPCISD::ST_VSR_SCAL_INT"; 1361 case PPCISD::COND_BRANCH: return "PPCISD::COND_BRANCH"; 1362 case PPCISD::BDNZ: return "PPCISD::BDNZ"; 1363 case PPCISD::BDZ: return "PPCISD::BDZ"; 1364 case PPCISD::MFFS: return "PPCISD::MFFS"; 1365 case PPCISD::FADDRTZ: return "PPCISD::FADDRTZ"; 1366 case PPCISD::TC_RETURN: return "PPCISD::TC_RETURN"; 1367 case PPCISD::CR6SET: return "PPCISD::CR6SET"; 1368 case PPCISD::CR6UNSET: return "PPCISD::CR6UNSET"; 1369 case PPCISD::PPC32_GOT: return "PPCISD::PPC32_GOT"; 1370 case PPCISD::PPC32_PICGOT: return "PPCISD::PPC32_PICGOT"; 1371 case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA"; 1372 case PPCISD::LD_GOT_TPREL_L: return "PPCISD::LD_GOT_TPREL_L"; 1373 case PPCISD::ADD_TLS: return "PPCISD::ADD_TLS"; 1374 case PPCISD::ADDIS_TLSGD_HA: return "PPCISD::ADDIS_TLSGD_HA"; 1375 case PPCISD::ADDI_TLSGD_L: return "PPCISD::ADDI_TLSGD_L"; 1376 case PPCISD::GET_TLS_ADDR: return "PPCISD::GET_TLS_ADDR"; 1377 case PPCISD::ADDI_TLSGD_L_ADDR: return "PPCISD::ADDI_TLSGD_L_ADDR"; 1378 case PPCISD::ADDIS_TLSLD_HA: return "PPCISD::ADDIS_TLSLD_HA"; 1379 case PPCISD::ADDI_TLSLD_L: return "PPCISD::ADDI_TLSLD_L"; 1380 case PPCISD::GET_TLSLD_ADDR: return "PPCISD::GET_TLSLD_ADDR"; 1381 case PPCISD::ADDI_TLSLD_L_ADDR: return "PPCISD::ADDI_TLSLD_L_ADDR"; 1382 case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA"; 1383 case PPCISD::ADDI_DTPREL_L: return "PPCISD::ADDI_DTPREL_L"; 1384 case PPCISD::VADD_SPLAT: return "PPCISD::VADD_SPLAT"; 1385 case PPCISD::SC: return "PPCISD::SC"; 1386 case PPCISD::CLRBHRB: return "PPCISD::CLRBHRB"; 1387 case PPCISD::MFBHRBE: return "PPCISD::MFBHRBE"; 1388 case PPCISD::RFEBB: return "PPCISD::RFEBB"; 1389 case PPCISD::XXSWAPD: return "PPCISD::XXSWAPD"; 1390 case PPCISD::SWAP_NO_CHAIN: return "PPCISD::SWAP_NO_CHAIN"; 1391 case PPCISD::VABSD: return "PPCISD::VABSD"; 1392 case PPCISD::QVFPERM: return "PPCISD::QVFPERM"; 1393 case PPCISD::QVGPCI: return "PPCISD::QVGPCI"; 1394 case PPCISD::QVALIGNI: return "PPCISD::QVALIGNI"; 1395 case PPCISD::QVESPLATI: return "PPCISD::QVESPLATI"; 1396 case PPCISD::QBFLT: return "PPCISD::QBFLT"; 1397 case PPCISD::QVLFSb: return "PPCISD::QVLFSb"; 1398 case PPCISD::BUILD_FP128: return "PPCISD::BUILD_FP128"; 1399 case PPCISD::BUILD_SPE64: return "PPCISD::BUILD_SPE64"; 1400 case PPCISD::EXTRACT_SPE: return "PPCISD::EXTRACT_SPE"; 1401 case PPCISD::EXTSWSLI: return "PPCISD::EXTSWSLI"; 1402 case PPCISD::LD_VSX_LH: return "PPCISD::LD_VSX_LH"; 1403 case PPCISD::FP_EXTEND_LH: return "PPCISD::FP_EXTEND_LH"; 1404 } 1405 return nullptr; 1406 } 1407 1408 EVT PPCTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &C, 1409 EVT VT) const { 1410 if (!VT.isVector()) 1411 return Subtarget.useCRBits() ? MVT::i1 : MVT::i32; 1412 1413 if (Subtarget.hasQPX()) 1414 return EVT::getVectorVT(C, MVT::i1, VT.getVectorNumElements()); 1415 1416 return VT.changeVectorElementTypeToInteger(); 1417 } 1418 1419 bool PPCTargetLowering::enableAggressiveFMAFusion(EVT VT) const { 1420 assert(VT.isFloatingPoint() && "Non-floating-point FMA?"); 1421 return true; 1422 } 1423 1424 //===----------------------------------------------------------------------===// 1425 // Node matching predicates, for use by the tblgen matching code. 1426 //===----------------------------------------------------------------------===// 1427 1428 /// isFloatingPointZero - Return true if this is 0.0 or -0.0. 1429 static bool isFloatingPointZero(SDValue Op) { 1430 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) 1431 return CFP->getValueAPF().isZero(); 1432 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) { 1433 // Maybe this has already been legalized into the constant pool? 1434 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1))) 1435 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal())) 1436 return CFP->getValueAPF().isZero(); 1437 } 1438 return false; 1439 } 1440 1441 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode. Return 1442 /// true if Op is undef or if it matches the specified value. 1443 static bool isConstantOrUndef(int Op, int Val) { 1444 return Op < 0 || Op == Val; 1445 } 1446 1447 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a 1448 /// VPKUHUM instruction. 1449 /// The ShuffleKind distinguishes between big-endian operations with 1450 /// two different inputs (0), either-endian operations with two identical 1451 /// inputs (1), and little-endian operations with two different inputs (2). 1452 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td). 1453 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind, 1454 SelectionDAG &DAG) { 1455 bool IsLE = DAG.getDataLayout().isLittleEndian(); 1456 if (ShuffleKind == 0) { 1457 if (IsLE) 1458 return false; 1459 for (unsigned i = 0; i != 16; ++i) 1460 if (!isConstantOrUndef(N->getMaskElt(i), i*2+1)) 1461 return false; 1462 } else if (ShuffleKind == 2) { 1463 if (!IsLE) 1464 return false; 1465 for (unsigned i = 0; i != 16; ++i) 1466 if (!isConstantOrUndef(N->getMaskElt(i), i*2)) 1467 return false; 1468 } else if (ShuffleKind == 1) { 1469 unsigned j = IsLE ? 0 : 1; 1470 for (unsigned i = 0; i != 8; ++i) 1471 if (!isConstantOrUndef(N->getMaskElt(i), i*2+j) || 1472 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j)) 1473 return false; 1474 } 1475 return true; 1476 } 1477 1478 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a 1479 /// VPKUWUM instruction. 1480 /// The ShuffleKind distinguishes between big-endian operations with 1481 /// two different inputs (0), either-endian operations with two identical 1482 /// inputs (1), and little-endian operations with two different inputs (2). 1483 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td). 1484 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind, 1485 SelectionDAG &DAG) { 1486 bool IsLE = DAG.getDataLayout().isLittleEndian(); 1487 if (ShuffleKind == 0) { 1488 if (IsLE) 1489 return false; 1490 for (unsigned i = 0; i != 16; i += 2) 1491 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+2) || 1492 !isConstantOrUndef(N->getMaskElt(i+1), i*2+3)) 1493 return false; 1494 } else if (ShuffleKind == 2) { 1495 if (!IsLE) 1496 return false; 1497 for (unsigned i = 0; i != 16; i += 2) 1498 if (!isConstantOrUndef(N->getMaskElt(i ), i*2) || 1499 !isConstantOrUndef(N->getMaskElt(i+1), i*2+1)) 1500 return false; 1501 } else if (ShuffleKind == 1) { 1502 unsigned j = IsLE ? 0 : 2; 1503 for (unsigned i = 0; i != 8; i += 2) 1504 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+j) || 1505 !isConstantOrUndef(N->getMaskElt(i+1), i*2+j+1) || 1506 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j) || 1507 !isConstantOrUndef(N->getMaskElt(i+9), i*2+j+1)) 1508 return false; 1509 } 1510 return true; 1511 } 1512 1513 /// isVPKUDUMShuffleMask - Return true if this is the shuffle mask for a 1514 /// VPKUDUM instruction, AND the VPKUDUM instruction exists for the 1515 /// current subtarget. 1516 /// 1517 /// The ShuffleKind distinguishes between big-endian operations with 1518 /// two different inputs (0), either-endian operations with two identical 1519 /// inputs (1), and little-endian operations with two different inputs (2). 1520 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td). 1521 bool PPC::isVPKUDUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind, 1522 SelectionDAG &DAG) { 1523 const PPCSubtarget& Subtarget = 1524 static_cast<const PPCSubtarget&>(DAG.getSubtarget()); 1525 if (!Subtarget.hasP8Vector()) 1526 return false; 1527 1528 bool IsLE = DAG.getDataLayout().isLittleEndian(); 1529 if (ShuffleKind == 0) { 1530 if (IsLE) 1531 return false; 1532 for (unsigned i = 0; i != 16; i += 4) 1533 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+4) || 1534 !isConstantOrUndef(N->getMaskElt(i+1), i*2+5) || 1535 !isConstantOrUndef(N->getMaskElt(i+2), i*2+6) || 1536 !isConstantOrUndef(N->getMaskElt(i+3), i*2+7)) 1537 return false; 1538 } else if (ShuffleKind == 2) { 1539 if (!IsLE) 1540 return false; 1541 for (unsigned i = 0; i != 16; i += 4) 1542 if (!isConstantOrUndef(N->getMaskElt(i ), i*2) || 1543 !isConstantOrUndef(N->getMaskElt(i+1), i*2+1) || 1544 !isConstantOrUndef(N->getMaskElt(i+2), i*2+2) || 1545 !isConstantOrUndef(N->getMaskElt(i+3), i*2+3)) 1546 return false; 1547 } else if (ShuffleKind == 1) { 1548 unsigned j = IsLE ? 0 : 4; 1549 for (unsigned i = 0; i != 8; i += 4) 1550 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+j) || 1551 !isConstantOrUndef(N->getMaskElt(i+1), i*2+j+1) || 1552 !isConstantOrUndef(N->getMaskElt(i+2), i*2+j+2) || 1553 !isConstantOrUndef(N->getMaskElt(i+3), i*2+j+3) || 1554 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j) || 1555 !isConstantOrUndef(N->getMaskElt(i+9), i*2+j+1) || 1556 !isConstantOrUndef(N->getMaskElt(i+10), i*2+j+2) || 1557 !isConstantOrUndef(N->getMaskElt(i+11), i*2+j+3)) 1558 return false; 1559 } 1560 return true; 1561 } 1562 1563 /// isVMerge - Common function, used to match vmrg* shuffles. 1564 /// 1565 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize, 1566 unsigned LHSStart, unsigned RHSStart) { 1567 if (N->getValueType(0) != MVT::v16i8) 1568 return false; 1569 assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) && 1570 "Unsupported merge size!"); 1571 1572 for (unsigned i = 0; i != 8/UnitSize; ++i) // Step over units 1573 for (unsigned j = 0; j != UnitSize; ++j) { // Step over bytes within unit 1574 if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j), 1575 LHSStart+j+i*UnitSize) || 1576 !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j), 1577 RHSStart+j+i*UnitSize)) 1578 return false; 1579 } 1580 return true; 1581 } 1582 1583 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for 1584 /// a VMRGL* instruction with the specified unit size (1,2 or 4 bytes). 1585 /// The ShuffleKind distinguishes between big-endian merges with two 1586 /// different inputs (0), either-endian merges with two identical inputs (1), 1587 /// and little-endian merges with two different inputs (2). For the latter, 1588 /// the input operands are swapped (see PPCInstrAltivec.td). 1589 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize, 1590 unsigned ShuffleKind, SelectionDAG &DAG) { 1591 if (DAG.getDataLayout().isLittleEndian()) { 1592 if (ShuffleKind == 1) // unary 1593 return isVMerge(N, UnitSize, 0, 0); 1594 else if (ShuffleKind == 2) // swapped 1595 return isVMerge(N, UnitSize, 0, 16); 1596 else 1597 return false; 1598 } else { 1599 if (ShuffleKind == 1) // unary 1600 return isVMerge(N, UnitSize, 8, 8); 1601 else if (ShuffleKind == 0) // normal 1602 return isVMerge(N, UnitSize, 8, 24); 1603 else 1604 return false; 1605 } 1606 } 1607 1608 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for 1609 /// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes). 1610 /// The ShuffleKind distinguishes between big-endian merges with two 1611 /// different inputs (0), either-endian merges with two identical inputs (1), 1612 /// and little-endian merges with two different inputs (2). For the latter, 1613 /// the input operands are swapped (see PPCInstrAltivec.td). 1614 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize, 1615 unsigned ShuffleKind, SelectionDAG &DAG) { 1616 if (DAG.getDataLayout().isLittleEndian()) { 1617 if (ShuffleKind == 1) // unary 1618 return isVMerge(N, UnitSize, 8, 8); 1619 else if (ShuffleKind == 2) // swapped 1620 return isVMerge(N, UnitSize, 8, 24); 1621 else 1622 return false; 1623 } else { 1624 if (ShuffleKind == 1) // unary 1625 return isVMerge(N, UnitSize, 0, 0); 1626 else if (ShuffleKind == 0) // normal 1627 return isVMerge(N, UnitSize, 0, 16); 1628 else 1629 return false; 1630 } 1631 } 1632 1633 /** 1634 * Common function used to match vmrgew and vmrgow shuffles 1635 * 1636 * The indexOffset determines whether to look for even or odd words in 1637 * the shuffle mask. This is based on the of the endianness of the target 1638 * machine. 1639 * - Little Endian: 1640 * - Use offset of 0 to check for odd elements 1641 * - Use offset of 4 to check for even elements 1642 * - Big Endian: 1643 * - Use offset of 0 to check for even elements 1644 * - Use offset of 4 to check for odd elements 1645 * A detailed description of the vector element ordering for little endian and 1646 * big endian can be found at 1647 * http://www.ibm.com/developerworks/library/l-ibm-xl-c-cpp-compiler/index.html 1648 * Targeting your applications - what little endian and big endian IBM XL C/C++ 1649 * compiler differences mean to you 1650 * 1651 * The mask to the shuffle vector instruction specifies the indices of the 1652 * elements from the two input vectors to place in the result. The elements are 1653 * numbered in array-access order, starting with the first vector. These vectors 1654 * are always of type v16i8, thus each vector will contain 16 elements of size 1655 * 8. More info on the shuffle vector can be found in the 1656 * http://llvm.org/docs/LangRef.html#shufflevector-instruction 1657 * Language Reference. 1658 * 1659 * The RHSStartValue indicates whether the same input vectors are used (unary) 1660 * or two different input vectors are used, based on the following: 1661 * - If the instruction uses the same vector for both inputs, the range of the 1662 * indices will be 0 to 15. In this case, the RHSStart value passed should 1663 * be 0. 1664 * - If the instruction has two different vectors then the range of the 1665 * indices will be 0 to 31. In this case, the RHSStart value passed should 1666 * be 16 (indices 0-15 specify elements in the first vector while indices 16 1667 * to 31 specify elements in the second vector). 1668 * 1669 * \param[in] N The shuffle vector SD Node to analyze 1670 * \param[in] IndexOffset Specifies whether to look for even or odd elements 1671 * \param[in] RHSStartValue Specifies the starting index for the righthand input 1672 * vector to the shuffle_vector instruction 1673 * \return true iff this shuffle vector represents an even or odd word merge 1674 */ 1675 static bool isVMerge(ShuffleVectorSDNode *N, unsigned IndexOffset, 1676 unsigned RHSStartValue) { 1677 if (N->getValueType(0) != MVT::v16i8) 1678 return false; 1679 1680 for (unsigned i = 0; i < 2; ++i) 1681 for (unsigned j = 0; j < 4; ++j) 1682 if (!isConstantOrUndef(N->getMaskElt(i*4+j), 1683 i*RHSStartValue+j+IndexOffset) || 1684 !isConstantOrUndef(N->getMaskElt(i*4+j+8), 1685 i*RHSStartValue+j+IndexOffset+8)) 1686 return false; 1687 return true; 1688 } 1689 1690 /** 1691 * Determine if the specified shuffle mask is suitable for the vmrgew or 1692 * vmrgow instructions. 1693 * 1694 * \param[in] N The shuffle vector SD Node to analyze 1695 * \param[in] CheckEven Check for an even merge (true) or an odd merge (false) 1696 * \param[in] ShuffleKind Identify the type of merge: 1697 * - 0 = big-endian merge with two different inputs; 1698 * - 1 = either-endian merge with two identical inputs; 1699 * - 2 = little-endian merge with two different inputs (inputs are swapped for 1700 * little-endian merges). 1701 * \param[in] DAG The current SelectionDAG 1702 * \return true iff this shuffle mask 1703 */ 1704 bool PPC::isVMRGEOShuffleMask(ShuffleVectorSDNode *N, bool CheckEven, 1705 unsigned ShuffleKind, SelectionDAG &DAG) { 1706 if (DAG.getDataLayout().isLittleEndian()) { 1707 unsigned indexOffset = CheckEven ? 4 : 0; 1708 if (ShuffleKind == 1) // Unary 1709 return isVMerge(N, indexOffset, 0); 1710 else if (ShuffleKind == 2) // swapped 1711 return isVMerge(N, indexOffset, 16); 1712 else 1713 return false; 1714 } 1715 else { 1716 unsigned indexOffset = CheckEven ? 0 : 4; 1717 if (ShuffleKind == 1) // Unary 1718 return isVMerge(N, indexOffset, 0); 1719 else if (ShuffleKind == 0) // Normal 1720 return isVMerge(N, indexOffset, 16); 1721 else 1722 return false; 1723 } 1724 return false; 1725 } 1726 1727 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift 1728 /// amount, otherwise return -1. 1729 /// The ShuffleKind distinguishes between big-endian operations with two 1730 /// different inputs (0), either-endian operations with two identical inputs 1731 /// (1), and little-endian operations with two different inputs (2). For the 1732 /// latter, the input operands are swapped (see PPCInstrAltivec.td). 1733 int PPC::isVSLDOIShuffleMask(SDNode *N, unsigned ShuffleKind, 1734 SelectionDAG &DAG) { 1735 if (N->getValueType(0) != MVT::v16i8) 1736 return -1; 1737 1738 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 1739 1740 // Find the first non-undef value in the shuffle mask. 1741 unsigned i; 1742 for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i) 1743 /*search*/; 1744 1745 if (i == 16) return -1; // all undef. 1746 1747 // Otherwise, check to see if the rest of the elements are consecutively 1748 // numbered from this value. 1749 unsigned ShiftAmt = SVOp->getMaskElt(i); 1750 if (ShiftAmt < i) return -1; 1751 1752 ShiftAmt -= i; 1753 bool isLE = DAG.getDataLayout().isLittleEndian(); 1754 1755 if ((ShuffleKind == 0 && !isLE) || (ShuffleKind == 2 && isLE)) { 1756 // Check the rest of the elements to see if they are consecutive. 1757 for (++i; i != 16; ++i) 1758 if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i)) 1759 return -1; 1760 } else if (ShuffleKind == 1) { 1761 // Check the rest of the elements to see if they are consecutive. 1762 for (++i; i != 16; ++i) 1763 if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15)) 1764 return -1; 1765 } else 1766 return -1; 1767 1768 if (isLE) 1769 ShiftAmt = 16 - ShiftAmt; 1770 1771 return ShiftAmt; 1772 } 1773 1774 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand 1775 /// specifies a splat of a single element that is suitable for input to 1776 /// VSPLTB/VSPLTH/VSPLTW. 1777 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) { 1778 assert(N->getValueType(0) == MVT::v16i8 && 1779 (EltSize == 1 || EltSize == 2 || EltSize == 4)); 1780 1781 // The consecutive indices need to specify an element, not part of two 1782 // different elements. So abandon ship early if this isn't the case. 1783 if (N->getMaskElt(0) % EltSize != 0) 1784 return false; 1785 1786 // This is a splat operation if each element of the permute is the same, and 1787 // if the value doesn't reference the second vector. 1788 unsigned ElementBase = N->getMaskElt(0); 1789 1790 // FIXME: Handle UNDEF elements too! 1791 if (ElementBase >= 16) 1792 return false; 1793 1794 // Check that the indices are consecutive, in the case of a multi-byte element 1795 // splatted with a v16i8 mask. 1796 for (unsigned i = 1; i != EltSize; ++i) 1797 if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase)) 1798 return false; 1799 1800 for (unsigned i = EltSize, e = 16; i != e; i += EltSize) { 1801 if (N->getMaskElt(i) < 0) continue; 1802 for (unsigned j = 0; j != EltSize; ++j) 1803 if (N->getMaskElt(i+j) != N->getMaskElt(j)) 1804 return false; 1805 } 1806 return true; 1807 } 1808 1809 /// Check that the mask is shuffling N byte elements. Within each N byte 1810 /// element of the mask, the indices could be either in increasing or 1811 /// decreasing order as long as they are consecutive. 1812 /// \param[in] N the shuffle vector SD Node to analyze 1813 /// \param[in] Width the element width in bytes, could be 2/4/8/16 (HalfWord/ 1814 /// Word/DoubleWord/QuadWord). 1815 /// \param[in] StepLen the delta indices number among the N byte element, if 1816 /// the mask is in increasing/decreasing order then it is 1/-1. 1817 /// \return true iff the mask is shuffling N byte elements. 1818 static bool isNByteElemShuffleMask(ShuffleVectorSDNode *N, unsigned Width, 1819 int StepLen) { 1820 assert((Width == 2 || Width == 4 || Width == 8 || Width == 16) && 1821 "Unexpected element width."); 1822 assert((StepLen == 1 || StepLen == -1) && "Unexpected element width."); 1823 1824 unsigned NumOfElem = 16 / Width; 1825 unsigned MaskVal[16]; // Width is never greater than 16 1826 for (unsigned i = 0; i < NumOfElem; ++i) { 1827 MaskVal[0] = N->getMaskElt(i * Width); 1828 if ((StepLen == 1) && (MaskVal[0] % Width)) { 1829 return false; 1830 } else if ((StepLen == -1) && ((MaskVal[0] + 1) % Width)) { 1831 return false; 1832 } 1833 1834 for (unsigned int j = 1; j < Width; ++j) { 1835 MaskVal[j] = N->getMaskElt(i * Width + j); 1836 if (MaskVal[j] != MaskVal[j-1] + StepLen) { 1837 return false; 1838 } 1839 } 1840 } 1841 1842 return true; 1843 } 1844 1845 bool PPC::isXXINSERTWMask(ShuffleVectorSDNode *N, unsigned &ShiftElts, 1846 unsigned &InsertAtByte, bool &Swap, bool IsLE) { 1847 if (!isNByteElemShuffleMask(N, 4, 1)) 1848 return false; 1849 1850 // Now we look at mask elements 0,4,8,12 1851 unsigned M0 = N->getMaskElt(0) / 4; 1852 unsigned M1 = N->getMaskElt(4) / 4; 1853 unsigned M2 = N->getMaskElt(8) / 4; 1854 unsigned M3 = N->getMaskElt(12) / 4; 1855 unsigned LittleEndianShifts[] = { 2, 1, 0, 3 }; 1856 unsigned BigEndianShifts[] = { 3, 0, 1, 2 }; 1857 1858 // Below, let H and L be arbitrary elements of the shuffle mask 1859 // where H is in the range [4,7] and L is in the range [0,3]. 1860 // H, 1, 2, 3 or L, 5, 6, 7 1861 if ((M0 > 3 && M1 == 1 && M2 == 2 && M3 == 3) || 1862 (M0 < 4 && M1 == 5 && M2 == 6 && M3 == 7)) { 1863 ShiftElts = IsLE ? LittleEndianShifts[M0 & 0x3] : BigEndianShifts[M0 & 0x3]; 1864 InsertAtByte = IsLE ? 12 : 0; 1865 Swap = M0 < 4; 1866 return true; 1867 } 1868 // 0, H, 2, 3 or 4, L, 6, 7 1869 if ((M1 > 3 && M0 == 0 && M2 == 2 && M3 == 3) || 1870 (M1 < 4 && M0 == 4 && M2 == 6 && M3 == 7)) { 1871 ShiftElts = IsLE ? LittleEndianShifts[M1 & 0x3] : BigEndianShifts[M1 & 0x3]; 1872 InsertAtByte = IsLE ? 8 : 4; 1873 Swap = M1 < 4; 1874 return true; 1875 } 1876 // 0, 1, H, 3 or 4, 5, L, 7 1877 if ((M2 > 3 && M0 == 0 && M1 == 1 && M3 == 3) || 1878 (M2 < 4 && M0 == 4 && M1 == 5 && M3 == 7)) { 1879 ShiftElts = IsLE ? LittleEndianShifts[M2 & 0x3] : BigEndianShifts[M2 & 0x3]; 1880 InsertAtByte = IsLE ? 4 : 8; 1881 Swap = M2 < 4; 1882 return true; 1883 } 1884 // 0, 1, 2, H or 4, 5, 6, L 1885 if ((M3 > 3 && M0 == 0 && M1 == 1 && M2 == 2) || 1886 (M3 < 4 && M0 == 4 && M1 == 5 && M2 == 6)) { 1887 ShiftElts = IsLE ? LittleEndianShifts[M3 & 0x3] : BigEndianShifts[M3 & 0x3]; 1888 InsertAtByte = IsLE ? 0 : 12; 1889 Swap = M3 < 4; 1890 return true; 1891 } 1892 1893 // If both vector operands for the shuffle are the same vector, the mask will 1894 // contain only elements from the first one and the second one will be undef. 1895 if (N->getOperand(1).isUndef()) { 1896 ShiftElts = 0; 1897 Swap = true; 1898 unsigned XXINSERTWSrcElem = IsLE ? 2 : 1; 1899 if (M0 == XXINSERTWSrcElem && M1 == 1 && M2 == 2 && M3 == 3) { 1900 InsertAtByte = IsLE ? 12 : 0; 1901 return true; 1902 } 1903 if (M0 == 0 && M1 == XXINSERTWSrcElem && M2 == 2 && M3 == 3) { 1904 InsertAtByte = IsLE ? 8 : 4; 1905 return true; 1906 } 1907 if (M0 == 0 && M1 == 1 && M2 == XXINSERTWSrcElem && M3 == 3) { 1908 InsertAtByte = IsLE ? 4 : 8; 1909 return true; 1910 } 1911 if (M0 == 0 && M1 == 1 && M2 == 2 && M3 == XXINSERTWSrcElem) { 1912 InsertAtByte = IsLE ? 0 : 12; 1913 return true; 1914 } 1915 } 1916 1917 return false; 1918 } 1919 1920 bool PPC::isXXSLDWIShuffleMask(ShuffleVectorSDNode *N, unsigned &ShiftElts, 1921 bool &Swap, bool IsLE) { 1922 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8"); 1923 // Ensure each byte index of the word is consecutive. 1924 if (!isNByteElemShuffleMask(N, 4, 1)) 1925 return false; 1926 1927 // Now we look at mask elements 0,4,8,12, which are the beginning of words. 1928 unsigned M0 = N->getMaskElt(0) / 4; 1929 unsigned M1 = N->getMaskElt(4) / 4; 1930 unsigned M2 = N->getMaskElt(8) / 4; 1931 unsigned M3 = N->getMaskElt(12) / 4; 1932 1933 // If both vector operands for the shuffle are the same vector, the mask will 1934 // contain only elements from the first one and the second one will be undef. 1935 if (N->getOperand(1).isUndef()) { 1936 assert(M0 < 4 && "Indexing into an undef vector?"); 1937 if (M1 != (M0 + 1) % 4 || M2 != (M1 + 1) % 4 || M3 != (M2 + 1) % 4) 1938 return false; 1939 1940 ShiftElts = IsLE ? (4 - M0) % 4 : M0; 1941 Swap = false; 1942 return true; 1943 } 1944 1945 // Ensure each word index of the ShuffleVector Mask is consecutive. 1946 if (M1 != (M0 + 1) % 8 || M2 != (M1 + 1) % 8 || M3 != (M2 + 1) % 8) 1947 return false; 1948 1949 if (IsLE) { 1950 if (M0 == 0 || M0 == 7 || M0 == 6 || M0 == 5) { 1951 // Input vectors don't need to be swapped if the leading element 1952 // of the result is one of the 3 left elements of the second vector 1953 // (or if there is no shift to be done at all). 1954 Swap = false; 1955 ShiftElts = (8 - M0) % 8; 1956 } else if (M0 == 4 || M0 == 3 || M0 == 2 || M0 == 1) { 1957 // Input vectors need to be swapped if the leading element 1958 // of the result is one of the 3 left elements of the first vector 1959 // (or if we're shifting by 4 - thereby simply swapping the vectors). 1960 Swap = true; 1961 ShiftElts = (4 - M0) % 4; 1962 } 1963 1964 return true; 1965 } else { // BE 1966 if (M0 == 0 || M0 == 1 || M0 == 2 || M0 == 3) { 1967 // Input vectors don't need to be swapped if the leading element 1968 // of the result is one of the 4 elements of the first vector. 1969 Swap = false; 1970 ShiftElts = M0; 1971 } else if (M0 == 4 || M0 == 5 || M0 == 6 || M0 == 7) { 1972 // Input vectors need to be swapped if the leading element 1973 // of the result is one of the 4 elements of the right vector. 1974 Swap = true; 1975 ShiftElts = M0 - 4; 1976 } 1977 1978 return true; 1979 } 1980 } 1981 1982 bool static isXXBRShuffleMaskHelper(ShuffleVectorSDNode *N, int Width) { 1983 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8"); 1984 1985 if (!isNByteElemShuffleMask(N, Width, -1)) 1986 return false; 1987 1988 for (int i = 0; i < 16; i += Width) 1989 if (N->getMaskElt(i) != i + Width - 1) 1990 return false; 1991 1992 return true; 1993 } 1994 1995 bool PPC::isXXBRHShuffleMask(ShuffleVectorSDNode *N) { 1996 return isXXBRShuffleMaskHelper(N, 2); 1997 } 1998 1999 bool PPC::isXXBRWShuffleMask(ShuffleVectorSDNode *N) { 2000 return isXXBRShuffleMaskHelper(N, 4); 2001 } 2002 2003 bool PPC::isXXBRDShuffleMask(ShuffleVectorSDNode *N) { 2004 return isXXBRShuffleMaskHelper(N, 8); 2005 } 2006 2007 bool PPC::isXXBRQShuffleMask(ShuffleVectorSDNode *N) { 2008 return isXXBRShuffleMaskHelper(N, 16); 2009 } 2010 2011 /// Can node \p N be lowered to an XXPERMDI instruction? If so, set \p Swap 2012 /// if the inputs to the instruction should be swapped and set \p DM to the 2013 /// value for the immediate. 2014 /// Specifically, set \p Swap to true only if \p N can be lowered to XXPERMDI 2015 /// AND element 0 of the result comes from the first input (LE) or second input 2016 /// (BE). Set \p DM to the calculated result (0-3) only if \p N can be lowered. 2017 /// \return true iff the given mask of shuffle node \p N is a XXPERMDI shuffle 2018 /// mask. 2019 bool PPC::isXXPERMDIShuffleMask(ShuffleVectorSDNode *N, unsigned &DM, 2020 bool &Swap, bool IsLE) { 2021 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8"); 2022 2023 // Ensure each byte index of the double word is consecutive. 2024 if (!isNByteElemShuffleMask(N, 8, 1)) 2025 return false; 2026 2027 unsigned M0 = N->getMaskElt(0) / 8; 2028 unsigned M1 = N->getMaskElt(8) / 8; 2029 assert(((M0 | M1) < 4) && "A mask element out of bounds?"); 2030 2031 // If both vector operands for the shuffle are the same vector, the mask will 2032 // contain only elements from the first one and the second one will be undef. 2033 if (N->getOperand(1).isUndef()) { 2034 if ((M0 | M1) < 2) { 2035 DM = IsLE ? (((~M1) & 1) << 1) + ((~M0) & 1) : (M0 << 1) + (M1 & 1); 2036 Swap = false; 2037 return true; 2038 } else 2039 return false; 2040 } 2041 2042 if (IsLE) { 2043 if (M0 > 1 && M1 < 2) { 2044 Swap = false; 2045 } else if (M0 < 2 && M1 > 1) { 2046 M0 = (M0 + 2) % 4; 2047 M1 = (M1 + 2) % 4; 2048 Swap = true; 2049 } else 2050 return false; 2051 2052 // Note: if control flow comes here that means Swap is already set above 2053 DM = (((~M1) & 1) << 1) + ((~M0) & 1); 2054 return true; 2055 } else { // BE 2056 if (M0 < 2 && M1 > 1) { 2057 Swap = false; 2058 } else if (M0 > 1 && M1 < 2) { 2059 M0 = (M0 + 2) % 4; 2060 M1 = (M1 + 2) % 4; 2061 Swap = true; 2062 } else 2063 return false; 2064 2065 // Note: if control flow comes here that means Swap is already set above 2066 DM = (M0 << 1) + (M1 & 1); 2067 return true; 2068 } 2069 } 2070 2071 2072 /// getVSPLTImmediate - Return the appropriate VSPLT* immediate to splat the 2073 /// specified isSplatShuffleMask VECTOR_SHUFFLE mask. 2074 unsigned PPC::getVSPLTImmediate(SDNode *N, unsigned EltSize, 2075 SelectionDAG &DAG) { 2076 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 2077 assert(isSplatShuffleMask(SVOp, EltSize)); 2078 if (DAG.getDataLayout().isLittleEndian()) 2079 return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize); 2080 else 2081 return SVOp->getMaskElt(0) / EltSize; 2082 } 2083 2084 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed 2085 /// by using a vspltis[bhw] instruction of the specified element size, return 2086 /// the constant being splatted. The ByteSize field indicates the number of 2087 /// bytes of each element [124] -> [bhw]. 2088 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) { 2089 SDValue OpVal(nullptr, 0); 2090 2091 // If ByteSize of the splat is bigger than the element size of the 2092 // build_vector, then we have a case where we are checking for a splat where 2093 // multiple elements of the buildvector are folded together into a single 2094 // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8). 2095 unsigned EltSize = 16/N->getNumOperands(); 2096 if (EltSize < ByteSize) { 2097 unsigned Multiple = ByteSize/EltSize; // Number of BV entries per spltval. 2098 SDValue UniquedVals[4]; 2099 assert(Multiple > 1 && Multiple <= 4 && "How can this happen?"); 2100 2101 // See if all of the elements in the buildvector agree across. 2102 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 2103 if (N->getOperand(i).isUndef()) continue; 2104 // If the element isn't a constant, bail fully out. 2105 if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue(); 2106 2107 if (!UniquedVals[i&(Multiple-1)].getNode()) 2108 UniquedVals[i&(Multiple-1)] = N->getOperand(i); 2109 else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i)) 2110 return SDValue(); // no match. 2111 } 2112 2113 // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains 2114 // either constant or undef values that are identical for each chunk. See 2115 // if these chunks can form into a larger vspltis*. 2116 2117 // Check to see if all of the leading entries are either 0 or -1. If 2118 // neither, then this won't fit into the immediate field. 2119 bool LeadingZero = true; 2120 bool LeadingOnes = true; 2121 for (unsigned i = 0; i != Multiple-1; ++i) { 2122 if (!UniquedVals[i].getNode()) continue; // Must have been undefs. 2123 2124 LeadingZero &= isNullConstant(UniquedVals[i]); 2125 LeadingOnes &= isAllOnesConstant(UniquedVals[i]); 2126 } 2127 // Finally, check the least significant entry. 2128 if (LeadingZero) { 2129 if (!UniquedVals[Multiple-1].getNode()) 2130 return DAG.getTargetConstant(0, SDLoc(N), MVT::i32); // 0,0,0,undef 2131 int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue(); 2132 if (Val < 16) // 0,0,0,4 -> vspltisw(4) 2133 return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32); 2134 } 2135 if (LeadingOnes) { 2136 if (!UniquedVals[Multiple-1].getNode()) 2137 return DAG.getTargetConstant(~0U, SDLoc(N), MVT::i32); // -1,-1,-1,undef 2138 int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue(); 2139 if (Val >= -16) // -1,-1,-1,-2 -> vspltisw(-2) 2140 return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32); 2141 } 2142 2143 return SDValue(); 2144 } 2145 2146 // Check to see if this buildvec has a single non-undef value in its elements. 2147 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 2148 if (N->getOperand(i).isUndef()) continue; 2149 if (!OpVal.getNode()) 2150 OpVal = N->getOperand(i); 2151 else if (OpVal != N->getOperand(i)) 2152 return SDValue(); 2153 } 2154 2155 if (!OpVal.getNode()) return SDValue(); // All UNDEF: use implicit def. 2156 2157 unsigned ValSizeInBytes = EltSize; 2158 uint64_t Value = 0; 2159 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) { 2160 Value = CN->getZExtValue(); 2161 } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) { 2162 assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!"); 2163 Value = FloatToBits(CN->getValueAPF().convertToFloat()); 2164 } 2165 2166 // If the splat value is larger than the element value, then we can never do 2167 // this splat. The only case that we could fit the replicated bits into our 2168 // immediate field for would be zero, and we prefer to use vxor for it. 2169 if (ValSizeInBytes < ByteSize) return SDValue(); 2170 2171 // If the element value is larger than the splat value, check if it consists 2172 // of a repeated bit pattern of size ByteSize. 2173 if (!APInt(ValSizeInBytes * 8, Value).isSplat(ByteSize * 8)) 2174 return SDValue(); 2175 2176 // Properly sign extend the value. 2177 int MaskVal = SignExtend32(Value, ByteSize * 8); 2178 2179 // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros. 2180 if (MaskVal == 0) return SDValue(); 2181 2182 // Finally, if this value fits in a 5 bit sext field, return it 2183 if (SignExtend32<5>(MaskVal) == MaskVal) 2184 return DAG.getTargetConstant(MaskVal, SDLoc(N), MVT::i32); 2185 return SDValue(); 2186 } 2187 2188 /// isQVALIGNIShuffleMask - If this is a qvaligni shuffle mask, return the shift 2189 /// amount, otherwise return -1. 2190 int PPC::isQVALIGNIShuffleMask(SDNode *N) { 2191 EVT VT = N->getValueType(0); 2192 if (VT != MVT::v4f64 && VT != MVT::v4f32 && VT != MVT::v4i1) 2193 return -1; 2194 2195 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 2196 2197 // Find the first non-undef value in the shuffle mask. 2198 unsigned i; 2199 for (i = 0; i != 4 && SVOp->getMaskElt(i) < 0; ++i) 2200 /*search*/; 2201 2202 if (i == 4) return -1; // all undef. 2203 2204 // Otherwise, check to see if the rest of the elements are consecutively 2205 // numbered from this value. 2206 unsigned ShiftAmt = SVOp->getMaskElt(i); 2207 if (ShiftAmt < i) return -1; 2208 ShiftAmt -= i; 2209 2210 // Check the rest of the elements to see if they are consecutive. 2211 for (++i; i != 4; ++i) 2212 if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i)) 2213 return -1; 2214 2215 return ShiftAmt; 2216 } 2217 2218 //===----------------------------------------------------------------------===// 2219 // Addressing Mode Selection 2220 //===----------------------------------------------------------------------===// 2221 2222 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit 2223 /// or 64-bit immediate, and if the value can be accurately represented as a 2224 /// sign extension from a 16-bit value. If so, this returns true and the 2225 /// immediate. 2226 bool llvm::isIntS16Immediate(SDNode *N, int16_t &Imm) { 2227 if (!isa<ConstantSDNode>(N)) 2228 return false; 2229 2230 Imm = (int16_t)cast<ConstantSDNode>(N)->getZExtValue(); 2231 if (N->getValueType(0) == MVT::i32) 2232 return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue(); 2233 else 2234 return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue(); 2235 } 2236 bool llvm::isIntS16Immediate(SDValue Op, int16_t &Imm) { 2237 return isIntS16Immediate(Op.getNode(), Imm); 2238 } 2239 2240 2241 /// SelectAddressEVXRegReg - Given the specified address, check to see if it can 2242 /// be represented as an indexed [r+r] operation. 2243 bool PPCTargetLowering::SelectAddressEVXRegReg(SDValue N, SDValue &Base, 2244 SDValue &Index, 2245 SelectionDAG &DAG) const { 2246 for (SDNode::use_iterator UI = N->use_begin(), E = N->use_end(); 2247 UI != E; ++UI) { 2248 if (MemSDNode *Memop = dyn_cast<MemSDNode>(*UI)) { 2249 if (Memop->getMemoryVT() == MVT::f64) { 2250 Base = N.getOperand(0); 2251 Index = N.getOperand(1); 2252 return true; 2253 } 2254 } 2255 } 2256 return false; 2257 } 2258 2259 /// SelectAddressRegReg - Given the specified addressed, check to see if it 2260 /// can be represented as an indexed [r+r] operation. Returns false if it 2261 /// can be more efficiently represented as [r+imm]. If \p EncodingAlignment is 2262 /// non-zero and N can be represented by a base register plus a signed 16-bit 2263 /// displacement, make a more precise judgement by checking (displacement % \p 2264 /// EncodingAlignment). 2265 bool PPCTargetLowering::SelectAddressRegReg(SDValue N, SDValue &Base, 2266 SDValue &Index, SelectionDAG &DAG, 2267 unsigned EncodingAlignment) const { 2268 int16_t imm = 0; 2269 if (N.getOpcode() == ISD::ADD) { 2270 // Is there any SPE load/store (f64), which can't handle 16bit offset? 2271 // SPE load/store can only handle 8-bit offsets. 2272 if (hasSPE() && SelectAddressEVXRegReg(N, Base, Index, DAG)) 2273 return true; 2274 if (isIntS16Immediate(N.getOperand(1), imm) && 2275 (!EncodingAlignment || !(imm % EncodingAlignment))) 2276 return false; // r+i 2277 if (N.getOperand(1).getOpcode() == PPCISD::Lo) 2278 return false; // r+i 2279 2280 Base = N.getOperand(0); 2281 Index = N.getOperand(1); 2282 return true; 2283 } else if (N.getOpcode() == ISD::OR) { 2284 if (isIntS16Immediate(N.getOperand(1), imm) && 2285 (!EncodingAlignment || !(imm % EncodingAlignment))) 2286 return false; // r+i can fold it if we can. 2287 2288 // If this is an or of disjoint bitfields, we can codegen this as an add 2289 // (for better address arithmetic) if the LHS and RHS of the OR are provably 2290 // disjoint. 2291 KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0)); 2292 2293 if (LHSKnown.Zero.getBoolValue()) { 2294 KnownBits RHSKnown = DAG.computeKnownBits(N.getOperand(1)); 2295 // If all of the bits are known zero on the LHS or RHS, the add won't 2296 // carry. 2297 if (~(LHSKnown.Zero | RHSKnown.Zero) == 0) { 2298 Base = N.getOperand(0); 2299 Index = N.getOperand(1); 2300 return true; 2301 } 2302 } 2303 } 2304 2305 return false; 2306 } 2307 2308 // If we happen to be doing an i64 load or store into a stack slot that has 2309 // less than a 4-byte alignment, then the frame-index elimination may need to 2310 // use an indexed load or store instruction (because the offset may not be a 2311 // multiple of 4). The extra register needed to hold the offset comes from the 2312 // register scavenger, and it is possible that the scavenger will need to use 2313 // an emergency spill slot. As a result, we need to make sure that a spill slot 2314 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned 2315 // stack slot. 2316 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) { 2317 // FIXME: This does not handle the LWA case. 2318 if (VT != MVT::i64) 2319 return; 2320 2321 // NOTE: We'll exclude negative FIs here, which come from argument 2322 // lowering, because there are no known test cases triggering this problem 2323 // using packed structures (or similar). We can remove this exclusion if 2324 // we find such a test case. The reason why this is so test-case driven is 2325 // because this entire 'fixup' is only to prevent crashes (from the 2326 // register scavenger) on not-really-valid inputs. For example, if we have: 2327 // %a = alloca i1 2328 // %b = bitcast i1* %a to i64* 2329 // store i64* a, i64 b 2330 // then the store should really be marked as 'align 1', but is not. If it 2331 // were marked as 'align 1' then the indexed form would have been 2332 // instruction-selected initially, and the problem this 'fixup' is preventing 2333 // won't happen regardless. 2334 if (FrameIdx < 0) 2335 return; 2336 2337 MachineFunction &MF = DAG.getMachineFunction(); 2338 MachineFrameInfo &MFI = MF.getFrameInfo(); 2339 2340 unsigned Align = MFI.getObjectAlignment(FrameIdx); 2341 if (Align >= 4) 2342 return; 2343 2344 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 2345 FuncInfo->setHasNonRISpills(); 2346 } 2347 2348 /// Returns true if the address N can be represented by a base register plus 2349 /// a signed 16-bit displacement [r+imm], and if it is not better 2350 /// represented as reg+reg. If \p EncodingAlignment is non-zero, only accept 2351 /// displacements that are multiples of that value. 2352 bool PPCTargetLowering::SelectAddressRegImm(SDValue N, SDValue &Disp, 2353 SDValue &Base, 2354 SelectionDAG &DAG, 2355 unsigned EncodingAlignment) const { 2356 // FIXME dl should come from parent load or store, not from address 2357 SDLoc dl(N); 2358 // If this can be more profitably realized as r+r, fail. 2359 if (SelectAddressRegReg(N, Disp, Base, DAG, EncodingAlignment)) 2360 return false; 2361 2362 if (N.getOpcode() == ISD::ADD) { 2363 int16_t imm = 0; 2364 if (isIntS16Immediate(N.getOperand(1), imm) && 2365 (!EncodingAlignment || (imm % EncodingAlignment) == 0)) { 2366 Disp = DAG.getTargetConstant(imm, dl, N.getValueType()); 2367 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) { 2368 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2369 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 2370 } else { 2371 Base = N.getOperand(0); 2372 } 2373 return true; // [r+i] 2374 } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) { 2375 // Match LOAD (ADD (X, Lo(G))). 2376 assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue() 2377 && "Cannot handle constant offsets yet!"); 2378 Disp = N.getOperand(1).getOperand(0); // The global address. 2379 assert(Disp.getOpcode() == ISD::TargetGlobalAddress || 2380 Disp.getOpcode() == ISD::TargetGlobalTLSAddress || 2381 Disp.getOpcode() == ISD::TargetConstantPool || 2382 Disp.getOpcode() == ISD::TargetJumpTable); 2383 Base = N.getOperand(0); 2384 return true; // [&g+r] 2385 } 2386 } else if (N.getOpcode() == ISD::OR) { 2387 int16_t imm = 0; 2388 if (isIntS16Immediate(N.getOperand(1), imm) && 2389 (!EncodingAlignment || (imm % EncodingAlignment) == 0)) { 2390 // If this is an or of disjoint bitfields, we can codegen this as an add 2391 // (for better address arithmetic) if the LHS and RHS of the OR are 2392 // provably disjoint. 2393 KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0)); 2394 2395 if ((LHSKnown.Zero.getZExtValue()|~(uint64_t)imm) == ~0ULL) { 2396 // If all of the bits are known zero on the LHS or RHS, the add won't 2397 // carry. 2398 if (FrameIndexSDNode *FI = 2399 dyn_cast<FrameIndexSDNode>(N.getOperand(0))) { 2400 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2401 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 2402 } else { 2403 Base = N.getOperand(0); 2404 } 2405 Disp = DAG.getTargetConstant(imm, dl, N.getValueType()); 2406 return true; 2407 } 2408 } 2409 } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) { 2410 // Loading from a constant address. 2411 2412 // If this address fits entirely in a 16-bit sext immediate field, codegen 2413 // this as "d, 0" 2414 int16_t Imm; 2415 if (isIntS16Immediate(CN, Imm) && 2416 (!EncodingAlignment || (Imm % EncodingAlignment) == 0)) { 2417 Disp = DAG.getTargetConstant(Imm, dl, CN->getValueType(0)); 2418 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO, 2419 CN->getValueType(0)); 2420 return true; 2421 } 2422 2423 // Handle 32-bit sext immediates with LIS + addr mode. 2424 if ((CN->getValueType(0) == MVT::i32 || 2425 (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) && 2426 (!EncodingAlignment || (CN->getZExtValue() % EncodingAlignment) == 0)) { 2427 int Addr = (int)CN->getZExtValue(); 2428 2429 // Otherwise, break this down into an LIS + disp. 2430 Disp = DAG.getTargetConstant((short)Addr, dl, MVT::i32); 2431 2432 Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, dl, 2433 MVT::i32); 2434 unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8; 2435 Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0); 2436 return true; 2437 } 2438 } 2439 2440 Disp = DAG.getTargetConstant(0, dl, getPointerTy(DAG.getDataLayout())); 2441 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) { 2442 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2443 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 2444 } else 2445 Base = N; 2446 return true; // [r+0] 2447 } 2448 2449 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be 2450 /// represented as an indexed [r+r] operation. 2451 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base, 2452 SDValue &Index, 2453 SelectionDAG &DAG) const { 2454 // Check to see if we can easily represent this as an [r+r] address. This 2455 // will fail if it thinks that the address is more profitably represented as 2456 // reg+imm, e.g. where imm = 0. 2457 if (SelectAddressRegReg(N, Base, Index, DAG)) 2458 return true; 2459 2460 // If the address is the result of an add, we will utilize the fact that the 2461 // address calculation includes an implicit add. However, we can reduce 2462 // register pressure if we do not materialize a constant just for use as the 2463 // index register. We only get rid of the add if it is not an add of a 2464 // value and a 16-bit signed constant and both have a single use. 2465 int16_t imm = 0; 2466 if (N.getOpcode() == ISD::ADD && 2467 (!isIntS16Immediate(N.getOperand(1), imm) || 2468 !N.getOperand(1).hasOneUse() || !N.getOperand(0).hasOneUse())) { 2469 Base = N.getOperand(0); 2470 Index = N.getOperand(1); 2471 return true; 2472 } 2473 2474 // Otherwise, do it the hard way, using R0 as the base register. 2475 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO, 2476 N.getValueType()); 2477 Index = N; 2478 return true; 2479 } 2480 2481 /// Returns true if we should use a direct load into vector instruction 2482 /// (such as lxsd or lfd), instead of a load into gpr + direct move sequence. 2483 static bool usePartialVectorLoads(SDNode *N, const PPCSubtarget& ST) { 2484 2485 // If there are any other uses other than scalar to vector, then we should 2486 // keep it as a scalar load -> direct move pattern to prevent multiple 2487 // loads. 2488 LoadSDNode *LD = dyn_cast<LoadSDNode>(N); 2489 if (!LD) 2490 return false; 2491 2492 EVT MemVT = LD->getMemoryVT(); 2493 if (!MemVT.isSimple()) 2494 return false; 2495 switch(MemVT.getSimpleVT().SimpleTy) { 2496 case MVT::i64: 2497 break; 2498 case MVT::i32: 2499 if (!ST.hasP8Vector()) 2500 return false; 2501 break; 2502 case MVT::i16: 2503 case MVT::i8: 2504 if (!ST.hasP9Vector()) 2505 return false; 2506 break; 2507 default: 2508 return false; 2509 } 2510 2511 SDValue LoadedVal(N, 0); 2512 if (!LoadedVal.hasOneUse()) 2513 return false; 2514 2515 for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end(); 2516 UI != UE; ++UI) 2517 if (UI.getUse().get().getResNo() == 0 && 2518 UI->getOpcode() != ISD::SCALAR_TO_VECTOR) 2519 return false; 2520 2521 return true; 2522 } 2523 2524 /// getPreIndexedAddressParts - returns true by value, base pointer and 2525 /// offset pointer and addressing mode by reference if the node's address 2526 /// can be legally represented as pre-indexed load / store address. 2527 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base, 2528 SDValue &Offset, 2529 ISD::MemIndexedMode &AM, 2530 SelectionDAG &DAG) const { 2531 if (DisablePPCPreinc) return false; 2532 2533 bool isLoad = true; 2534 SDValue Ptr; 2535 EVT VT; 2536 unsigned Alignment; 2537 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 2538 Ptr = LD->getBasePtr(); 2539 VT = LD->getMemoryVT(); 2540 Alignment = LD->getAlignment(); 2541 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 2542 Ptr = ST->getBasePtr(); 2543 VT = ST->getMemoryVT(); 2544 Alignment = ST->getAlignment(); 2545 isLoad = false; 2546 } else 2547 return false; 2548 2549 // Do not generate pre-inc forms for specific loads that feed scalar_to_vector 2550 // instructions because we can fold these into a more efficient instruction 2551 // instead, (such as LXSD). 2552 if (isLoad && usePartialVectorLoads(N, Subtarget)) { 2553 return false; 2554 } 2555 2556 // PowerPC doesn't have preinc load/store instructions for vectors (except 2557 // for QPX, which does have preinc r+r forms). 2558 if (VT.isVector()) { 2559 if (!Subtarget.hasQPX() || (VT != MVT::v4f64 && VT != MVT::v4f32)) { 2560 return false; 2561 } else if (SelectAddressRegRegOnly(Ptr, Offset, Base, DAG)) { 2562 AM = ISD::PRE_INC; 2563 return true; 2564 } 2565 } 2566 2567 if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) { 2568 // Common code will reject creating a pre-inc form if the base pointer 2569 // is a frame index, or if N is a store and the base pointer is either 2570 // the same as or a predecessor of the value being stored. Check for 2571 // those situations here, and try with swapped Base/Offset instead. 2572 bool Swap = false; 2573 2574 if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base)) 2575 Swap = true; 2576 else if (!isLoad) { 2577 SDValue Val = cast<StoreSDNode>(N)->getValue(); 2578 if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode())) 2579 Swap = true; 2580 } 2581 2582 if (Swap) 2583 std::swap(Base, Offset); 2584 2585 AM = ISD::PRE_INC; 2586 return true; 2587 } 2588 2589 // LDU/STU can only handle immediates that are a multiple of 4. 2590 if (VT != MVT::i64) { 2591 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, 0)) 2592 return false; 2593 } else { 2594 // LDU/STU need an address with at least 4-byte alignment. 2595 if (Alignment < 4) 2596 return false; 2597 2598 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, 4)) 2599 return false; 2600 } 2601 2602 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 2603 // PPC64 doesn't have lwau, but it does have lwaux. Reject preinc load of 2604 // sext i32 to i64 when addr mode is r+i. 2605 if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 && 2606 LD->getExtensionType() == ISD::SEXTLOAD && 2607 isa<ConstantSDNode>(Offset)) 2608 return false; 2609 } 2610 2611 AM = ISD::PRE_INC; 2612 return true; 2613 } 2614 2615 //===----------------------------------------------------------------------===// 2616 // LowerOperation implementation 2617 //===----------------------------------------------------------------------===// 2618 2619 /// Return true if we should reference labels using a PICBase, set the HiOpFlags 2620 /// and LoOpFlags to the target MO flags. 2621 static void getLabelAccessInfo(bool IsPIC, const PPCSubtarget &Subtarget, 2622 unsigned &HiOpFlags, unsigned &LoOpFlags, 2623 const GlobalValue *GV = nullptr) { 2624 HiOpFlags = PPCII::MO_HA; 2625 LoOpFlags = PPCII::MO_LO; 2626 2627 // Don't use the pic base if not in PIC relocation model. 2628 if (IsPIC) { 2629 HiOpFlags |= PPCII::MO_PIC_FLAG; 2630 LoOpFlags |= PPCII::MO_PIC_FLAG; 2631 } 2632 2633 // If this is a reference to a global value that requires a non-lazy-ptr, make 2634 // sure that instruction lowering adds it. 2635 if (GV && Subtarget.hasLazyResolverStub(GV)) { 2636 HiOpFlags |= PPCII::MO_NLP_FLAG; 2637 LoOpFlags |= PPCII::MO_NLP_FLAG; 2638 2639 if (GV->hasHiddenVisibility()) { 2640 HiOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG; 2641 LoOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG; 2642 } 2643 } 2644 } 2645 2646 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC, 2647 SelectionDAG &DAG) { 2648 SDLoc DL(HiPart); 2649 EVT PtrVT = HiPart.getValueType(); 2650 SDValue Zero = DAG.getConstant(0, DL, PtrVT); 2651 2652 SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero); 2653 SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero); 2654 2655 // With PIC, the first instruction is actually "GR+hi(&G)". 2656 if (isPIC) 2657 Hi = DAG.getNode(ISD::ADD, DL, PtrVT, 2658 DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi); 2659 2660 // Generate non-pic code that has direct accesses to the constant pool. 2661 // The address of the global is just (hi(&g)+lo(&g)). 2662 return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo); 2663 } 2664 2665 static void setUsesTOCBasePtr(MachineFunction &MF) { 2666 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 2667 FuncInfo->setUsesTOCBasePtr(); 2668 } 2669 2670 static void setUsesTOCBasePtr(SelectionDAG &DAG) { 2671 setUsesTOCBasePtr(DAG.getMachineFunction()); 2672 } 2673 2674 SDValue PPCTargetLowering::getTOCEntry(SelectionDAG &DAG, const SDLoc &dl, 2675 SDValue GA) const { 2676 const bool Is64Bit = Subtarget.isPPC64(); 2677 EVT VT = Is64Bit ? MVT::i64 : MVT::i32; 2678 SDValue Reg = Is64Bit ? DAG.getRegister(PPC::X2, VT) 2679 : Subtarget.isAIXABI() 2680 ? DAG.getRegister(PPC::R2, VT) 2681 : DAG.getNode(PPCISD::GlobalBaseReg, dl, VT); 2682 SDValue Ops[] = { GA, Reg }; 2683 return DAG.getMemIntrinsicNode( 2684 PPCISD::TOC_ENTRY, dl, DAG.getVTList(VT, MVT::Other), Ops, VT, 2685 MachinePointerInfo::getGOT(DAG.getMachineFunction()), 0, 2686 MachineMemOperand::MOLoad); 2687 } 2688 2689 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op, 2690 SelectionDAG &DAG) const { 2691 EVT PtrVT = Op.getValueType(); 2692 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op); 2693 const Constant *C = CP->getConstVal(); 2694 2695 // 64-bit SVR4 ABI code is always position-independent. 2696 // The actual address of the GlobalValue is stored in the TOC. 2697 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) { 2698 setUsesTOCBasePtr(DAG); 2699 SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0); 2700 return getTOCEntry(DAG, SDLoc(CP), GA); 2701 } 2702 2703 unsigned MOHiFlag, MOLoFlag; 2704 bool IsPIC = isPositionIndependent(); 2705 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag); 2706 2707 if (IsPIC && Subtarget.isSVR4ABI()) { 2708 SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 2709 PPCII::MO_PIC_FLAG); 2710 return getTOCEntry(DAG, SDLoc(CP), GA); 2711 } 2712 2713 SDValue CPIHi = 2714 DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOHiFlag); 2715 SDValue CPILo = 2716 DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOLoFlag); 2717 return LowerLabelRef(CPIHi, CPILo, IsPIC, DAG); 2718 } 2719 2720 // For 64-bit PowerPC, prefer the more compact relative encodings. 2721 // This trades 32 bits per jump table entry for one or two instructions 2722 // on the jump site. 2723 unsigned PPCTargetLowering::getJumpTableEncoding() const { 2724 if (isJumpTableRelative()) 2725 return MachineJumpTableInfo::EK_LabelDifference32; 2726 2727 return TargetLowering::getJumpTableEncoding(); 2728 } 2729 2730 bool PPCTargetLowering::isJumpTableRelative() const { 2731 if (Subtarget.isPPC64()) 2732 return true; 2733 return TargetLowering::isJumpTableRelative(); 2734 } 2735 2736 SDValue PPCTargetLowering::getPICJumpTableRelocBase(SDValue Table, 2737 SelectionDAG &DAG) const { 2738 if (!Subtarget.isPPC64()) 2739 return TargetLowering::getPICJumpTableRelocBase(Table, DAG); 2740 2741 switch (getTargetMachine().getCodeModel()) { 2742 case CodeModel::Small: 2743 case CodeModel::Medium: 2744 return TargetLowering::getPICJumpTableRelocBase(Table, DAG); 2745 default: 2746 return DAG.getNode(PPCISD::GlobalBaseReg, SDLoc(), 2747 getPointerTy(DAG.getDataLayout())); 2748 } 2749 } 2750 2751 const MCExpr * 2752 PPCTargetLowering::getPICJumpTableRelocBaseExpr(const MachineFunction *MF, 2753 unsigned JTI, 2754 MCContext &Ctx) const { 2755 if (!Subtarget.isPPC64()) 2756 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx); 2757 2758 switch (getTargetMachine().getCodeModel()) { 2759 case CodeModel::Small: 2760 case CodeModel::Medium: 2761 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx); 2762 default: 2763 return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx); 2764 } 2765 } 2766 2767 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const { 2768 EVT PtrVT = Op.getValueType(); 2769 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op); 2770 2771 // 64-bit SVR4 ABI code is always position-independent. 2772 // The actual address of the GlobalValue is stored in the TOC. 2773 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) { 2774 setUsesTOCBasePtr(DAG); 2775 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT); 2776 return getTOCEntry(DAG, SDLoc(JT), GA); 2777 } 2778 2779 unsigned MOHiFlag, MOLoFlag; 2780 bool IsPIC = isPositionIndependent(); 2781 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag); 2782 2783 if (IsPIC && Subtarget.isSVR4ABI()) { 2784 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, 2785 PPCII::MO_PIC_FLAG); 2786 return getTOCEntry(DAG, SDLoc(GA), GA); 2787 } 2788 2789 SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag); 2790 SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag); 2791 return LowerLabelRef(JTIHi, JTILo, IsPIC, DAG); 2792 } 2793 2794 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op, 2795 SelectionDAG &DAG) const { 2796 EVT PtrVT = Op.getValueType(); 2797 BlockAddressSDNode *BASDN = cast<BlockAddressSDNode>(Op); 2798 const BlockAddress *BA = BASDN->getBlockAddress(); 2799 2800 // 64-bit SVR4 ABI code is always position-independent. 2801 // The actual BlockAddress is stored in the TOC. 2802 if (Subtarget.isSVR4ABI() && 2803 (Subtarget.isPPC64() || isPositionIndependent())) { 2804 if (Subtarget.isPPC64()) 2805 setUsesTOCBasePtr(DAG); 2806 SDValue GA = DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset()); 2807 return getTOCEntry(DAG, SDLoc(BASDN), GA); 2808 } 2809 2810 unsigned MOHiFlag, MOLoFlag; 2811 bool IsPIC = isPositionIndependent(); 2812 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag); 2813 SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag); 2814 SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag); 2815 return LowerLabelRef(TgtBAHi, TgtBALo, IsPIC, DAG); 2816 } 2817 2818 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op, 2819 SelectionDAG &DAG) const { 2820 // FIXME: TLS addresses currently use medium model code sequences, 2821 // which is the most useful form. Eventually support for small and 2822 // large models could be added if users need it, at the cost of 2823 // additional complexity. 2824 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op); 2825 if (DAG.getTarget().useEmulatedTLS()) 2826 return LowerToTLSEmulatedModel(GA, DAG); 2827 2828 SDLoc dl(GA); 2829 const GlobalValue *GV = GA->getGlobal(); 2830 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2831 bool is64bit = Subtarget.isPPC64(); 2832 const Module *M = DAG.getMachineFunction().getFunction().getParent(); 2833 PICLevel::Level picLevel = M->getPICLevel(); 2834 2835 const TargetMachine &TM = getTargetMachine(); 2836 TLSModel::Model Model = TM.getTLSModel(GV); 2837 2838 if (Model == TLSModel::LocalExec) { 2839 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 2840 PPCII::MO_TPREL_HA); 2841 SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 2842 PPCII::MO_TPREL_LO); 2843 SDValue TLSReg = is64bit ? DAG.getRegister(PPC::X13, MVT::i64) 2844 : DAG.getRegister(PPC::R2, MVT::i32); 2845 2846 SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg); 2847 return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi); 2848 } 2849 2850 if (Model == TLSModel::InitialExec) { 2851 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0); 2852 SDValue TGATLS = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 2853 PPCII::MO_TLS); 2854 SDValue GOTPtr; 2855 if (is64bit) { 2856 setUsesTOCBasePtr(DAG); 2857 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64); 2858 GOTPtr = DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl, 2859 PtrVT, GOTReg, TGA); 2860 } else { 2861 if (!TM.isPositionIndependent()) 2862 GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT); 2863 else if (picLevel == PICLevel::SmallPIC) 2864 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT); 2865 else 2866 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT); 2867 } 2868 SDValue TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl, 2869 PtrVT, TGA, GOTPtr); 2870 return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS); 2871 } 2872 2873 if (Model == TLSModel::GeneralDynamic) { 2874 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0); 2875 SDValue GOTPtr; 2876 if (is64bit) { 2877 setUsesTOCBasePtr(DAG); 2878 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64); 2879 GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT, 2880 GOTReg, TGA); 2881 } else { 2882 if (picLevel == PICLevel::SmallPIC) 2883 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT); 2884 else 2885 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT); 2886 } 2887 return DAG.getNode(PPCISD::ADDI_TLSGD_L_ADDR, dl, PtrVT, 2888 GOTPtr, TGA, TGA); 2889 } 2890 2891 if (Model == TLSModel::LocalDynamic) { 2892 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0); 2893 SDValue GOTPtr; 2894 if (is64bit) { 2895 setUsesTOCBasePtr(DAG); 2896 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64); 2897 GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT, 2898 GOTReg, TGA); 2899 } else { 2900 if (picLevel == PICLevel::SmallPIC) 2901 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT); 2902 else 2903 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT); 2904 } 2905 SDValue TLSAddr = DAG.getNode(PPCISD::ADDI_TLSLD_L_ADDR, dl, 2906 PtrVT, GOTPtr, TGA, TGA); 2907 SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl, 2908 PtrVT, TLSAddr, TGA); 2909 return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA); 2910 } 2911 2912 llvm_unreachable("Unknown TLS model!"); 2913 } 2914 2915 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op, 2916 SelectionDAG &DAG) const { 2917 EVT PtrVT = Op.getValueType(); 2918 GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op); 2919 SDLoc DL(GSDN); 2920 const GlobalValue *GV = GSDN->getGlobal(); 2921 2922 // 64-bit SVR4 ABI & AIX ABI code is always position-independent. 2923 // The actual address of the GlobalValue is stored in the TOC. 2924 if ((Subtarget.isSVR4ABI() && Subtarget.isPPC64()) || Subtarget.isAIXABI()) { 2925 setUsesTOCBasePtr(DAG); 2926 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset()); 2927 return getTOCEntry(DAG, DL, GA); 2928 } 2929 2930 unsigned MOHiFlag, MOLoFlag; 2931 bool IsPIC = isPositionIndependent(); 2932 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag, GV); 2933 2934 if (IsPIC && Subtarget.isSVR4ABI()) { 2935 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 2936 GSDN->getOffset(), 2937 PPCII::MO_PIC_FLAG); 2938 return getTOCEntry(DAG, DL, GA); 2939 } 2940 2941 SDValue GAHi = 2942 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag); 2943 SDValue GALo = 2944 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag); 2945 2946 SDValue Ptr = LowerLabelRef(GAHi, GALo, IsPIC, DAG); 2947 2948 // If the global reference is actually to a non-lazy-pointer, we have to do an 2949 // extra load to get the address of the global. 2950 if (MOHiFlag & PPCII::MO_NLP_FLAG) 2951 Ptr = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo()); 2952 return Ptr; 2953 } 2954 2955 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const { 2956 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get(); 2957 SDLoc dl(Op); 2958 2959 if (Op.getValueType() == MVT::v2i64) { 2960 // When the operands themselves are v2i64 values, we need to do something 2961 // special because VSX has no underlying comparison operations for these. 2962 if (Op.getOperand(0).getValueType() == MVT::v2i64) { 2963 // Equality can be handled by casting to the legal type for Altivec 2964 // comparisons, everything else needs to be expanded. 2965 if (CC == ISD::SETEQ || CC == ISD::SETNE) { 2966 return DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, 2967 DAG.getSetCC(dl, MVT::v4i32, 2968 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0)), 2969 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(1)), 2970 CC)); 2971 } 2972 2973 return SDValue(); 2974 } 2975 2976 // We handle most of these in the usual way. 2977 return Op; 2978 } 2979 2980 // If we're comparing for equality to zero, expose the fact that this is 2981 // implemented as a ctlz/srl pair on ppc, so that the dag combiner can 2982 // fold the new nodes. 2983 if (SDValue V = lowerCmpEqZeroToCtlzSrl(Op, DAG)) 2984 return V; 2985 2986 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 2987 // Leave comparisons against 0 and -1 alone for now, since they're usually 2988 // optimized. FIXME: revisit this when we can custom lower all setcc 2989 // optimizations. 2990 if (C->isAllOnesValue() || C->isNullValue()) 2991 return SDValue(); 2992 } 2993 2994 // If we have an integer seteq/setne, turn it into a compare against zero 2995 // by xor'ing the rhs with the lhs, which is faster than setting a 2996 // condition register, reading it back out, and masking the correct bit. The 2997 // normal approach here uses sub to do this instead of xor. Using xor exposes 2998 // the result to other bit-twiddling opportunities. 2999 EVT LHSVT = Op.getOperand(0).getValueType(); 3000 if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) { 3001 EVT VT = Op.getValueType(); 3002 SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0), 3003 Op.getOperand(1)); 3004 return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, dl, LHSVT), CC); 3005 } 3006 return SDValue(); 3007 } 3008 3009 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const { 3010 SDNode *Node = Op.getNode(); 3011 EVT VT = Node->getValueType(0); 3012 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3013 SDValue InChain = Node->getOperand(0); 3014 SDValue VAListPtr = Node->getOperand(1); 3015 const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue(); 3016 SDLoc dl(Node); 3017 3018 assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only"); 3019 3020 // gpr_index 3021 SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain, 3022 VAListPtr, MachinePointerInfo(SV), MVT::i8); 3023 InChain = GprIndex.getValue(1); 3024 3025 if (VT == MVT::i64) { 3026 // Check if GprIndex is even 3027 SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex, 3028 DAG.getConstant(1, dl, MVT::i32)); 3029 SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd, 3030 DAG.getConstant(0, dl, MVT::i32), ISD::SETNE); 3031 SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex, 3032 DAG.getConstant(1, dl, MVT::i32)); 3033 // Align GprIndex to be even if it isn't 3034 GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne, 3035 GprIndex); 3036 } 3037 3038 // fpr index is 1 byte after gpr 3039 SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, 3040 DAG.getConstant(1, dl, MVT::i32)); 3041 3042 // fpr 3043 SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain, 3044 FprPtr, MachinePointerInfo(SV), MVT::i8); 3045 InChain = FprIndex.getValue(1); 3046 3047 SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, 3048 DAG.getConstant(8, dl, MVT::i32)); 3049 3050 SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, 3051 DAG.getConstant(4, dl, MVT::i32)); 3052 3053 // areas 3054 SDValue OverflowArea = 3055 DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr, MachinePointerInfo()); 3056 InChain = OverflowArea.getValue(1); 3057 3058 SDValue RegSaveArea = 3059 DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr, MachinePointerInfo()); 3060 InChain = RegSaveArea.getValue(1); 3061 3062 // select overflow_area if index > 8 3063 SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex, 3064 DAG.getConstant(8, dl, MVT::i32), ISD::SETLT); 3065 3066 // adjustment constant gpr_index * 4/8 3067 SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32, 3068 VT.isInteger() ? GprIndex : FprIndex, 3069 DAG.getConstant(VT.isInteger() ? 4 : 8, dl, 3070 MVT::i32)); 3071 3072 // OurReg = RegSaveArea + RegConstant 3073 SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea, 3074 RegConstant); 3075 3076 // Floating types are 32 bytes into RegSaveArea 3077 if (VT.isFloatingPoint()) 3078 OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg, 3079 DAG.getConstant(32, dl, MVT::i32)); 3080 3081 // increase {f,g}pr_index by 1 (or 2 if VT is i64) 3082 SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32, 3083 VT.isInteger() ? GprIndex : FprIndex, 3084 DAG.getConstant(VT == MVT::i64 ? 2 : 1, dl, 3085 MVT::i32)); 3086 3087 InChain = DAG.getTruncStore(InChain, dl, IndexPlus1, 3088 VT.isInteger() ? VAListPtr : FprPtr, 3089 MachinePointerInfo(SV), MVT::i8); 3090 3091 // determine if we should load from reg_save_area or overflow_area 3092 SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea); 3093 3094 // increase overflow_area by 4/8 if gpr/fpr > 8 3095 SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea, 3096 DAG.getConstant(VT.isInteger() ? 4 : 8, 3097 dl, MVT::i32)); 3098 3099 OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea, 3100 OverflowAreaPlusN); 3101 3102 InChain = DAG.getTruncStore(InChain, dl, OverflowArea, OverflowAreaPtr, 3103 MachinePointerInfo(), MVT::i32); 3104 3105 return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo()); 3106 } 3107 3108 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const { 3109 assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only"); 3110 3111 // We have to copy the entire va_list struct: 3112 // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte 3113 return DAG.getMemcpy(Op.getOperand(0), Op, 3114 Op.getOperand(1), Op.getOperand(2), 3115 DAG.getConstant(12, SDLoc(Op), MVT::i32), 8, false, true, 3116 false, MachinePointerInfo(), MachinePointerInfo()); 3117 } 3118 3119 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op, 3120 SelectionDAG &DAG) const { 3121 return Op.getOperand(0); 3122 } 3123 3124 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op, 3125 SelectionDAG &DAG) const { 3126 SDValue Chain = Op.getOperand(0); 3127 SDValue Trmp = Op.getOperand(1); // trampoline 3128 SDValue FPtr = Op.getOperand(2); // nested function 3129 SDValue Nest = Op.getOperand(3); // 'nest' parameter value 3130 SDLoc dl(Op); 3131 3132 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3133 bool isPPC64 = (PtrVT == MVT::i64); 3134 Type *IntPtrTy = DAG.getDataLayout().getIntPtrType(*DAG.getContext()); 3135 3136 TargetLowering::ArgListTy Args; 3137 TargetLowering::ArgListEntry Entry; 3138 3139 Entry.Ty = IntPtrTy; 3140 Entry.Node = Trmp; Args.push_back(Entry); 3141 3142 // TrampSize == (isPPC64 ? 48 : 40); 3143 Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40, dl, 3144 isPPC64 ? MVT::i64 : MVT::i32); 3145 Args.push_back(Entry); 3146 3147 Entry.Node = FPtr; Args.push_back(Entry); 3148 Entry.Node = Nest; Args.push_back(Entry); 3149 3150 // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg) 3151 TargetLowering::CallLoweringInfo CLI(DAG); 3152 CLI.setDebugLoc(dl).setChain(Chain).setLibCallee( 3153 CallingConv::C, Type::getVoidTy(*DAG.getContext()), 3154 DAG.getExternalSymbol("__trampoline_setup", PtrVT), std::move(Args)); 3155 3156 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 3157 return CallResult.second; 3158 } 3159 3160 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const { 3161 MachineFunction &MF = DAG.getMachineFunction(); 3162 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 3163 EVT PtrVT = getPointerTy(MF.getDataLayout()); 3164 3165 SDLoc dl(Op); 3166 3167 if (Subtarget.isDarwinABI() || Subtarget.isPPC64()) { 3168 // vastart just stores the address of the VarArgsFrameIndex slot into the 3169 // memory location argument. 3170 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 3171 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 3172 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1), 3173 MachinePointerInfo(SV)); 3174 } 3175 3176 // For the 32-bit SVR4 ABI we follow the layout of the va_list struct. 3177 // We suppose the given va_list is already allocated. 3178 // 3179 // typedef struct { 3180 // char gpr; /* index into the array of 8 GPRs 3181 // * stored in the register save area 3182 // * gpr=0 corresponds to r3, 3183 // * gpr=1 to r4, etc. 3184 // */ 3185 // char fpr; /* index into the array of 8 FPRs 3186 // * stored in the register save area 3187 // * fpr=0 corresponds to f1, 3188 // * fpr=1 to f2, etc. 3189 // */ 3190 // char *overflow_arg_area; 3191 // /* location on stack that holds 3192 // * the next overflow argument 3193 // */ 3194 // char *reg_save_area; 3195 // /* where r3:r10 and f1:f8 (if saved) 3196 // * are stored 3197 // */ 3198 // } va_list[1]; 3199 3200 SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), dl, MVT::i32); 3201 SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), dl, MVT::i32); 3202 SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(), 3203 PtrVT); 3204 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), 3205 PtrVT); 3206 3207 uint64_t FrameOffset = PtrVT.getSizeInBits()/8; 3208 SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, dl, PtrVT); 3209 3210 uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1; 3211 SDValue ConstStackOffset = DAG.getConstant(StackOffset, dl, PtrVT); 3212 3213 uint64_t FPROffset = 1; 3214 SDValue ConstFPROffset = DAG.getConstant(FPROffset, dl, PtrVT); 3215 3216 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 3217 3218 // Store first byte : number of int regs 3219 SDValue firstStore = 3220 DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR, Op.getOperand(1), 3221 MachinePointerInfo(SV), MVT::i8); 3222 uint64_t nextOffset = FPROffset; 3223 SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1), 3224 ConstFPROffset); 3225 3226 // Store second byte : number of float regs 3227 SDValue secondStore = 3228 DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr, 3229 MachinePointerInfo(SV, nextOffset), MVT::i8); 3230 nextOffset += StackOffset; 3231 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset); 3232 3233 // Store second word : arguments given on stack 3234 SDValue thirdStore = DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr, 3235 MachinePointerInfo(SV, nextOffset)); 3236 nextOffset += FrameOffset; 3237 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset); 3238 3239 // Store third word : arguments given in registers 3240 return DAG.getStore(thirdStore, dl, FR, nextPtr, 3241 MachinePointerInfo(SV, nextOffset)); 3242 } 3243 3244 /// FPR - The set of FP registers that should be allocated for arguments 3245 /// on Darwin and AIX. 3246 static const MCPhysReg FPR[] = {PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, 3247 PPC::F6, PPC::F7, PPC::F8, PPC::F9, PPC::F10, 3248 PPC::F11, PPC::F12, PPC::F13}; 3249 3250 /// QFPR - The set of QPX registers that should be allocated for arguments. 3251 static const MCPhysReg QFPR[] = { 3252 PPC::QF1, PPC::QF2, PPC::QF3, PPC::QF4, PPC::QF5, PPC::QF6, PPC::QF7, 3253 PPC::QF8, PPC::QF9, PPC::QF10, PPC::QF11, PPC::QF12, PPC::QF13}; 3254 3255 /// CalculateStackSlotSize - Calculates the size reserved for this argument on 3256 /// the stack. 3257 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags, 3258 unsigned PtrByteSize) { 3259 unsigned ArgSize = ArgVT.getStoreSize(); 3260 if (Flags.isByVal()) 3261 ArgSize = Flags.getByValSize(); 3262 3263 // Round up to multiples of the pointer size, except for array members, 3264 // which are always packed. 3265 if (!Flags.isInConsecutiveRegs()) 3266 ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3267 3268 return ArgSize; 3269 } 3270 3271 /// CalculateStackSlotAlignment - Calculates the alignment of this argument 3272 /// on the stack. 3273 static unsigned CalculateStackSlotAlignment(EVT ArgVT, EVT OrigVT, 3274 ISD::ArgFlagsTy Flags, 3275 unsigned PtrByteSize) { 3276 unsigned Align = PtrByteSize; 3277 3278 // Altivec parameters are padded to a 16 byte boundary. 3279 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 || 3280 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 || 3281 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 || 3282 ArgVT == MVT::v1i128 || ArgVT == MVT::f128) 3283 Align = 16; 3284 // QPX vector types stored in double-precision are padded to a 32 byte 3285 // boundary. 3286 else if (ArgVT == MVT::v4f64 || ArgVT == MVT::v4i1) 3287 Align = 32; 3288 3289 // ByVal parameters are aligned as requested. 3290 if (Flags.isByVal()) { 3291 unsigned BVAlign = Flags.getByValAlign(); 3292 if (BVAlign > PtrByteSize) { 3293 if (BVAlign % PtrByteSize != 0) 3294 llvm_unreachable( 3295 "ByVal alignment is not a multiple of the pointer size"); 3296 3297 Align = BVAlign; 3298 } 3299 } 3300 3301 // Array members are always packed to their original alignment. 3302 if (Flags.isInConsecutiveRegs()) { 3303 // If the array member was split into multiple registers, the first 3304 // needs to be aligned to the size of the full type. (Except for 3305 // ppcf128, which is only aligned as its f64 components.) 3306 if (Flags.isSplit() && OrigVT != MVT::ppcf128) 3307 Align = OrigVT.getStoreSize(); 3308 else 3309 Align = ArgVT.getStoreSize(); 3310 } 3311 3312 return Align; 3313 } 3314 3315 /// CalculateStackSlotUsed - Return whether this argument will use its 3316 /// stack slot (instead of being passed in registers). ArgOffset, 3317 /// AvailableFPRs, and AvailableVRs must hold the current argument 3318 /// position, and will be updated to account for this argument. 3319 static bool CalculateStackSlotUsed(EVT ArgVT, EVT OrigVT, 3320 ISD::ArgFlagsTy Flags, 3321 unsigned PtrByteSize, 3322 unsigned LinkageSize, 3323 unsigned ParamAreaSize, 3324 unsigned &ArgOffset, 3325 unsigned &AvailableFPRs, 3326 unsigned &AvailableVRs, bool HasQPX) { 3327 bool UseMemory = false; 3328 3329 // Respect alignment of argument on the stack. 3330 unsigned Align = 3331 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize); 3332 ArgOffset = ((ArgOffset + Align - 1) / Align) * Align; 3333 // If there's no space left in the argument save area, we must 3334 // use memory (this check also catches zero-sized arguments). 3335 if (ArgOffset >= LinkageSize + ParamAreaSize) 3336 UseMemory = true; 3337 3338 // Allocate argument on the stack. 3339 ArgOffset += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize); 3340 if (Flags.isInConsecutiveRegsLast()) 3341 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3342 // If we overran the argument save area, we must use memory 3343 // (this check catches arguments passed partially in memory) 3344 if (ArgOffset > LinkageSize + ParamAreaSize) 3345 UseMemory = true; 3346 3347 // However, if the argument is actually passed in an FPR or a VR, 3348 // we don't use memory after all. 3349 if (!Flags.isByVal()) { 3350 if (ArgVT == MVT::f32 || ArgVT == MVT::f64 || 3351 // QPX registers overlap with the scalar FP registers. 3352 (HasQPX && (ArgVT == MVT::v4f32 || 3353 ArgVT == MVT::v4f64 || 3354 ArgVT == MVT::v4i1))) 3355 if (AvailableFPRs > 0) { 3356 --AvailableFPRs; 3357 return false; 3358 } 3359 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 || 3360 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 || 3361 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 || 3362 ArgVT == MVT::v1i128 || ArgVT == MVT::f128) 3363 if (AvailableVRs > 0) { 3364 --AvailableVRs; 3365 return false; 3366 } 3367 } 3368 3369 return UseMemory; 3370 } 3371 3372 /// EnsureStackAlignment - Round stack frame size up from NumBytes to 3373 /// ensure minimum alignment required for target. 3374 static unsigned EnsureStackAlignment(const PPCFrameLowering *Lowering, 3375 unsigned NumBytes) { 3376 unsigned TargetAlign = Lowering->getStackAlignment(); 3377 unsigned AlignMask = TargetAlign - 1; 3378 NumBytes = (NumBytes + AlignMask) & ~AlignMask; 3379 return NumBytes; 3380 } 3381 3382 SDValue PPCTargetLowering::LowerFormalArguments( 3383 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3384 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3385 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3386 if (Subtarget.isSVR4ABI()) { 3387 if (Subtarget.isPPC64()) 3388 return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins, 3389 dl, DAG, InVals); 3390 else 3391 return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins, 3392 dl, DAG, InVals); 3393 } else { 3394 return LowerFormalArguments_Darwin(Chain, CallConv, isVarArg, Ins, 3395 dl, DAG, InVals); 3396 } 3397 } 3398 3399 SDValue PPCTargetLowering::LowerFormalArguments_32SVR4( 3400 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3401 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3402 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3403 3404 // 32-bit SVR4 ABI Stack Frame Layout: 3405 // +-----------------------------------+ 3406 // +--> | Back chain | 3407 // | +-----------------------------------+ 3408 // | | Floating-point register save area | 3409 // | +-----------------------------------+ 3410 // | | General register save area | 3411 // | +-----------------------------------+ 3412 // | | CR save word | 3413 // | +-----------------------------------+ 3414 // | | VRSAVE save word | 3415 // | +-----------------------------------+ 3416 // | | Alignment padding | 3417 // | +-----------------------------------+ 3418 // | | Vector register save area | 3419 // | +-----------------------------------+ 3420 // | | Local variable space | 3421 // | +-----------------------------------+ 3422 // | | Parameter list area | 3423 // | +-----------------------------------+ 3424 // | | LR save word | 3425 // | +-----------------------------------+ 3426 // SP--> +--- | Back chain | 3427 // +-----------------------------------+ 3428 // 3429 // Specifications: 3430 // System V Application Binary Interface PowerPC Processor Supplement 3431 // AltiVec Technology Programming Interface Manual 3432 3433 MachineFunction &MF = DAG.getMachineFunction(); 3434 MachineFrameInfo &MFI = MF.getFrameInfo(); 3435 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 3436 3437 EVT PtrVT = getPointerTy(MF.getDataLayout()); 3438 // Potential tail calls could cause overwriting of argument stack slots. 3439 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt && 3440 (CallConv == CallingConv::Fast)); 3441 unsigned PtrByteSize = 4; 3442 3443 // Assign locations to all of the incoming arguments. 3444 SmallVector<CCValAssign, 16> ArgLocs; 3445 PPCCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 3446 *DAG.getContext()); 3447 3448 // Reserve space for the linkage area on the stack. 3449 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 3450 CCInfo.AllocateStack(LinkageSize, PtrByteSize); 3451 if (useSoftFloat()) 3452 CCInfo.PreAnalyzeFormalArguments(Ins); 3453 3454 CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4); 3455 CCInfo.clearWasPPCF128(); 3456 3457 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 3458 CCValAssign &VA = ArgLocs[i]; 3459 3460 // Arguments stored in registers. 3461 if (VA.isRegLoc()) { 3462 const TargetRegisterClass *RC; 3463 EVT ValVT = VA.getValVT(); 3464 3465 switch (ValVT.getSimpleVT().SimpleTy) { 3466 default: 3467 llvm_unreachable("ValVT not supported by formal arguments Lowering"); 3468 case MVT::i1: 3469 case MVT::i32: 3470 RC = &PPC::GPRCRegClass; 3471 break; 3472 case MVT::f32: 3473 if (Subtarget.hasP8Vector()) 3474 RC = &PPC::VSSRCRegClass; 3475 else if (Subtarget.hasSPE()) 3476 RC = &PPC::SPE4RCRegClass; 3477 else 3478 RC = &PPC::F4RCRegClass; 3479 break; 3480 case MVT::f64: 3481 if (Subtarget.hasVSX()) 3482 RC = &PPC::VSFRCRegClass; 3483 else if (Subtarget.hasSPE()) 3484 // SPE passes doubles in GPR pairs. 3485 RC = &PPC::GPRCRegClass; 3486 else 3487 RC = &PPC::F8RCRegClass; 3488 break; 3489 case MVT::v16i8: 3490 case MVT::v8i16: 3491 case MVT::v4i32: 3492 RC = &PPC::VRRCRegClass; 3493 break; 3494 case MVT::v4f32: 3495 RC = Subtarget.hasQPX() ? &PPC::QSRCRegClass : &PPC::VRRCRegClass; 3496 break; 3497 case MVT::v2f64: 3498 case MVT::v2i64: 3499 RC = &PPC::VRRCRegClass; 3500 break; 3501 case MVT::v4f64: 3502 RC = &PPC::QFRCRegClass; 3503 break; 3504 case MVT::v4i1: 3505 RC = &PPC::QBRCRegClass; 3506 break; 3507 } 3508 3509 SDValue ArgValue; 3510 // Transform the arguments stored in physical registers into 3511 // virtual ones. 3512 if (VA.getLocVT() == MVT::f64 && Subtarget.hasSPE()) { 3513 assert(i + 1 < e && "No second half of double precision argument"); 3514 unsigned RegLo = MF.addLiveIn(VA.getLocReg(), RC); 3515 unsigned RegHi = MF.addLiveIn(ArgLocs[++i].getLocReg(), RC); 3516 SDValue ArgValueLo = DAG.getCopyFromReg(Chain, dl, RegLo, MVT::i32); 3517 SDValue ArgValueHi = DAG.getCopyFromReg(Chain, dl, RegHi, MVT::i32); 3518 if (!Subtarget.isLittleEndian()) 3519 std::swap (ArgValueLo, ArgValueHi); 3520 ArgValue = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, ArgValueLo, 3521 ArgValueHi); 3522 } else { 3523 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC); 3524 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, 3525 ValVT == MVT::i1 ? MVT::i32 : ValVT); 3526 if (ValVT == MVT::i1) 3527 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue); 3528 } 3529 3530 InVals.push_back(ArgValue); 3531 } else { 3532 // Argument stored in memory. 3533 assert(VA.isMemLoc()); 3534 3535 // Get the extended size of the argument type in stack 3536 unsigned ArgSize = VA.getLocVT().getStoreSize(); 3537 // Get the actual size of the argument type 3538 unsigned ObjSize = VA.getValVT().getStoreSize(); 3539 unsigned ArgOffset = VA.getLocMemOffset(); 3540 // Stack objects in PPC32 are right justified. 3541 ArgOffset += ArgSize - ObjSize; 3542 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, isImmutable); 3543 3544 // Create load nodes to retrieve arguments from the stack. 3545 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3546 InVals.push_back( 3547 DAG.getLoad(VA.getValVT(), dl, Chain, FIN, MachinePointerInfo())); 3548 } 3549 } 3550 3551 // Assign locations to all of the incoming aggregate by value arguments. 3552 // Aggregates passed by value are stored in the local variable space of the 3553 // caller's stack frame, right above the parameter list area. 3554 SmallVector<CCValAssign, 16> ByValArgLocs; 3555 CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(), 3556 ByValArgLocs, *DAG.getContext()); 3557 3558 // Reserve stack space for the allocations in CCInfo. 3559 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize); 3560 3561 CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal); 3562 3563 // Area that is at least reserved in the caller of this function. 3564 unsigned MinReservedArea = CCByValInfo.getNextStackOffset(); 3565 MinReservedArea = std::max(MinReservedArea, LinkageSize); 3566 3567 // Set the size that is at least reserved in caller of this function. Tail 3568 // call optimized function's reserved stack space needs to be aligned so that 3569 // taking the difference between two stack areas will result in an aligned 3570 // stack. 3571 MinReservedArea = 3572 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea); 3573 FuncInfo->setMinReservedArea(MinReservedArea); 3574 3575 SmallVector<SDValue, 8> MemOps; 3576 3577 // If the function takes variable number of arguments, make a frame index for 3578 // the start of the first vararg value... for expansion of llvm.va_start. 3579 if (isVarArg) { 3580 static const MCPhysReg GPArgRegs[] = { 3581 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 3582 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 3583 }; 3584 const unsigned NumGPArgRegs = array_lengthof(GPArgRegs); 3585 3586 static const MCPhysReg FPArgRegs[] = { 3587 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7, 3588 PPC::F8 3589 }; 3590 unsigned NumFPArgRegs = array_lengthof(FPArgRegs); 3591 3592 if (useSoftFloat() || hasSPE()) 3593 NumFPArgRegs = 0; 3594 3595 FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs)); 3596 FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs)); 3597 3598 // Make room for NumGPArgRegs and NumFPArgRegs. 3599 int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 + 3600 NumFPArgRegs * MVT(MVT::f64).getSizeInBits()/8; 3601 3602 FuncInfo->setVarArgsStackOffset( 3603 MFI.CreateFixedObject(PtrVT.getSizeInBits()/8, 3604 CCInfo.getNextStackOffset(), true)); 3605 3606 FuncInfo->setVarArgsFrameIndex(MFI.CreateStackObject(Depth, 8, false)); 3607 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 3608 3609 // The fixed integer arguments of a variadic function are stored to the 3610 // VarArgsFrameIndex on the stack so that they may be loaded by 3611 // dereferencing the result of va_next. 3612 for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) { 3613 // Get an existing live-in vreg, or add a new one. 3614 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]); 3615 if (!VReg) 3616 VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass); 3617 3618 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 3619 SDValue Store = 3620 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 3621 MemOps.push_back(Store); 3622 // Increment the address by four for the next argument to store 3623 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT); 3624 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 3625 } 3626 3627 // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6 3628 // is set. 3629 // The double arguments are stored to the VarArgsFrameIndex 3630 // on the stack. 3631 for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) { 3632 // Get an existing live-in vreg, or add a new one. 3633 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]); 3634 if (!VReg) 3635 VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass); 3636 3637 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64); 3638 SDValue Store = 3639 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 3640 MemOps.push_back(Store); 3641 // Increment the address by eight for the next argument to store 3642 SDValue PtrOff = DAG.getConstant(MVT(MVT::f64).getSizeInBits()/8, dl, 3643 PtrVT); 3644 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 3645 } 3646 } 3647 3648 if (!MemOps.empty()) 3649 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 3650 3651 return Chain; 3652 } 3653 3654 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote 3655 // value to MVT::i64 and then truncate to the correct register size. 3656 SDValue PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags, 3657 EVT ObjectVT, SelectionDAG &DAG, 3658 SDValue ArgVal, 3659 const SDLoc &dl) const { 3660 if (Flags.isSExt()) 3661 ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal, 3662 DAG.getValueType(ObjectVT)); 3663 else if (Flags.isZExt()) 3664 ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal, 3665 DAG.getValueType(ObjectVT)); 3666 3667 return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal); 3668 } 3669 3670 SDValue PPCTargetLowering::LowerFormalArguments_64SVR4( 3671 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3672 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3673 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3674 // TODO: add description of PPC stack frame format, or at least some docs. 3675 // 3676 bool isELFv2ABI = Subtarget.isELFv2ABI(); 3677 bool isLittleEndian = Subtarget.isLittleEndian(); 3678 MachineFunction &MF = DAG.getMachineFunction(); 3679 MachineFrameInfo &MFI = MF.getFrameInfo(); 3680 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 3681 3682 assert(!(CallConv == CallingConv::Fast && isVarArg) && 3683 "fastcc not supported on varargs functions"); 3684 3685 EVT PtrVT = getPointerTy(MF.getDataLayout()); 3686 // Potential tail calls could cause overwriting of argument stack slots. 3687 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt && 3688 (CallConv == CallingConv::Fast)); 3689 unsigned PtrByteSize = 8; 3690 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 3691 3692 static const MCPhysReg GPR[] = { 3693 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 3694 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 3695 }; 3696 static const MCPhysReg VR[] = { 3697 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 3698 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 3699 }; 3700 3701 const unsigned Num_GPR_Regs = array_lengthof(GPR); 3702 const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13; 3703 const unsigned Num_VR_Regs = array_lengthof(VR); 3704 const unsigned Num_QFPR_Regs = Num_FPR_Regs; 3705 3706 // Do a first pass over the arguments to determine whether the ABI 3707 // guarantees that our caller has allocated the parameter save area 3708 // on its stack frame. In the ELFv1 ABI, this is always the case; 3709 // in the ELFv2 ABI, it is true if this is a vararg function or if 3710 // any parameter is located in a stack slot. 3711 3712 bool HasParameterArea = !isELFv2ABI || isVarArg; 3713 unsigned ParamAreaSize = Num_GPR_Regs * PtrByteSize; 3714 unsigned NumBytes = LinkageSize; 3715 unsigned AvailableFPRs = Num_FPR_Regs; 3716 unsigned AvailableVRs = Num_VR_Regs; 3717 for (unsigned i = 0, e = Ins.size(); i != e; ++i) { 3718 if (Ins[i].Flags.isNest()) 3719 continue; 3720 3721 if (CalculateStackSlotUsed(Ins[i].VT, Ins[i].ArgVT, Ins[i].Flags, 3722 PtrByteSize, LinkageSize, ParamAreaSize, 3723 NumBytes, AvailableFPRs, AvailableVRs, 3724 Subtarget.hasQPX())) 3725 HasParameterArea = true; 3726 } 3727 3728 // Add DAG nodes to load the arguments or copy them out of registers. On 3729 // entry to a function on PPC, the arguments start after the linkage area, 3730 // although the first ones are often in registers. 3731 3732 unsigned ArgOffset = LinkageSize; 3733 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 3734 unsigned &QFPR_idx = FPR_idx; 3735 SmallVector<SDValue, 8> MemOps; 3736 Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin(); 3737 unsigned CurArgIdx = 0; 3738 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) { 3739 SDValue ArgVal; 3740 bool needsLoad = false; 3741 EVT ObjectVT = Ins[ArgNo].VT; 3742 EVT OrigVT = Ins[ArgNo].ArgVT; 3743 unsigned ObjSize = ObjectVT.getStoreSize(); 3744 unsigned ArgSize = ObjSize; 3745 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags; 3746 if (Ins[ArgNo].isOrigArg()) { 3747 std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx); 3748 CurArgIdx = Ins[ArgNo].getOrigArgIndex(); 3749 } 3750 // We re-align the argument offset for each argument, except when using the 3751 // fast calling convention, when we need to make sure we do that only when 3752 // we'll actually use a stack slot. 3753 unsigned CurArgOffset, Align; 3754 auto ComputeArgOffset = [&]() { 3755 /* Respect alignment of argument on the stack. */ 3756 Align = CalculateStackSlotAlignment(ObjectVT, OrigVT, Flags, PtrByteSize); 3757 ArgOffset = ((ArgOffset + Align - 1) / Align) * Align; 3758 CurArgOffset = ArgOffset; 3759 }; 3760 3761 if (CallConv != CallingConv::Fast) { 3762 ComputeArgOffset(); 3763 3764 /* Compute GPR index associated with argument offset. */ 3765 GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize; 3766 GPR_idx = std::min(GPR_idx, Num_GPR_Regs); 3767 } 3768 3769 // FIXME the codegen can be much improved in some cases. 3770 // We do not have to keep everything in memory. 3771 if (Flags.isByVal()) { 3772 assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit"); 3773 3774 if (CallConv == CallingConv::Fast) 3775 ComputeArgOffset(); 3776 3777 // ObjSize is the true size, ArgSize rounded up to multiple of registers. 3778 ObjSize = Flags.getByValSize(); 3779 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3780 // Empty aggregate parameters do not take up registers. Examples: 3781 // struct { } a; 3782 // union { } b; 3783 // int c[0]; 3784 // etc. However, we have to provide a place-holder in InVals, so 3785 // pretend we have an 8-byte item at the current address for that 3786 // purpose. 3787 if (!ObjSize) { 3788 int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true); 3789 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3790 InVals.push_back(FIN); 3791 continue; 3792 } 3793 3794 // Create a stack object covering all stack doublewords occupied 3795 // by the argument. If the argument is (fully or partially) on 3796 // the stack, or if the argument is fully in registers but the 3797 // caller has allocated the parameter save anyway, we can refer 3798 // directly to the caller's stack frame. Otherwise, create a 3799 // local copy in our own frame. 3800 int FI; 3801 if (HasParameterArea || 3802 ArgSize + ArgOffset > LinkageSize + Num_GPR_Regs * PtrByteSize) 3803 FI = MFI.CreateFixedObject(ArgSize, ArgOffset, false, true); 3804 else 3805 FI = MFI.CreateStackObject(ArgSize, Align, false); 3806 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3807 3808 // Handle aggregates smaller than 8 bytes. 3809 if (ObjSize < PtrByteSize) { 3810 // The value of the object is its address, which differs from the 3811 // address of the enclosing doubleword on big-endian systems. 3812 SDValue Arg = FIN; 3813 if (!isLittleEndian) { 3814 SDValue ArgOff = DAG.getConstant(PtrByteSize - ObjSize, dl, PtrVT); 3815 Arg = DAG.getNode(ISD::ADD, dl, ArgOff.getValueType(), Arg, ArgOff); 3816 } 3817 InVals.push_back(Arg); 3818 3819 if (GPR_idx != Num_GPR_Regs) { 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 Store; 3824 3825 if (ObjSize==1 || ObjSize==2 || ObjSize==4) { 3826 EVT ObjType = (ObjSize == 1 ? MVT::i8 : 3827 (ObjSize == 2 ? MVT::i16 : MVT::i32)); 3828 Store = DAG.getTruncStore(Val.getValue(1), dl, Val, Arg, 3829 MachinePointerInfo(&*FuncArg), ObjType); 3830 } else { 3831 // For sizes that don't fit a truncating store (3, 5, 6, 7), 3832 // store the whole register as-is to the parameter save area 3833 // slot. 3834 Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, 3835 MachinePointerInfo(&*FuncArg)); 3836 } 3837 3838 MemOps.push_back(Store); 3839 } 3840 // Whether we copied from a register or not, advance the offset 3841 // into the parameter save area by a full doubleword. 3842 ArgOffset += PtrByteSize; 3843 continue; 3844 } 3845 3846 // The value of the object is its address, which is the address of 3847 // its first stack doubleword. 3848 InVals.push_back(FIN); 3849 3850 // Store whatever pieces of the object are in registers to memory. 3851 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) { 3852 if (GPR_idx == Num_GPR_Regs) 3853 break; 3854 3855 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 3856 FuncInfo->addLiveInAttr(VReg, Flags); 3857 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 3858 SDValue Addr = FIN; 3859 if (j) { 3860 SDValue Off = DAG.getConstant(j, dl, PtrVT); 3861 Addr = DAG.getNode(ISD::ADD, dl, Off.getValueType(), Addr, Off); 3862 } 3863 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, Addr, 3864 MachinePointerInfo(&*FuncArg, j)); 3865 MemOps.push_back(Store); 3866 ++GPR_idx; 3867 } 3868 ArgOffset += ArgSize; 3869 continue; 3870 } 3871 3872 switch (ObjectVT.getSimpleVT().SimpleTy) { 3873 default: llvm_unreachable("Unhandled argument type!"); 3874 case MVT::i1: 3875 case MVT::i32: 3876 case MVT::i64: 3877 if (Flags.isNest()) { 3878 // The 'nest' parameter, if any, is passed in R11. 3879 unsigned VReg = MF.addLiveIn(PPC::X11, &PPC::G8RCRegClass); 3880 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 3881 3882 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1) 3883 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl); 3884 3885 break; 3886 } 3887 3888 // These can be scalar arguments or elements of an integer array type 3889 // passed directly. Clang may use those instead of "byval" aggregate 3890 // types to avoid forcing arguments to memory unnecessarily. 3891 if (GPR_idx != Num_GPR_Regs) { 3892 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass); 3893 FuncInfo->addLiveInAttr(VReg, Flags); 3894 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 3895 3896 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1) 3897 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote 3898 // value to MVT::i64 and then truncate to the correct register size. 3899 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl); 3900 } else { 3901 if (CallConv == CallingConv::Fast) 3902 ComputeArgOffset(); 3903 3904 needsLoad = true; 3905 ArgSize = PtrByteSize; 3906 } 3907 if (CallConv != CallingConv::Fast || needsLoad) 3908 ArgOffset += 8; 3909 break; 3910 3911 case MVT::f32: 3912 case MVT::f64: 3913 // These can be scalar arguments or elements of a float array type 3914 // passed directly. The latter are used to implement ELFv2 homogenous 3915 // float aggregates. 3916 if (FPR_idx != Num_FPR_Regs) { 3917 unsigned VReg; 3918 3919 if (ObjectVT == MVT::f32) 3920 VReg = MF.addLiveIn(FPR[FPR_idx], 3921 Subtarget.hasP8Vector() 3922 ? &PPC::VSSRCRegClass 3923 : &PPC::F4RCRegClass); 3924 else 3925 VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX() 3926 ? &PPC::VSFRCRegClass 3927 : &PPC::F8RCRegClass); 3928 3929 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 3930 ++FPR_idx; 3931 } else if (GPR_idx != Num_GPR_Regs && CallConv != CallingConv::Fast) { 3932 // FIXME: We may want to re-enable this for CallingConv::Fast on the P8 3933 // once we support fp <-> gpr moves. 3934 3935 // This can only ever happen in the presence of f32 array types, 3936 // since otherwise we never run out of FPRs before running out 3937 // of GPRs. 3938 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass); 3939 FuncInfo->addLiveInAttr(VReg, Flags); 3940 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 3941 3942 if (ObjectVT == MVT::f32) { 3943 if ((ArgOffset % PtrByteSize) == (isLittleEndian ? 4 : 0)) 3944 ArgVal = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgVal, 3945 DAG.getConstant(32, dl, MVT::i32)); 3946 ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal); 3947 } 3948 3949 ArgVal = DAG.getNode(ISD::BITCAST, dl, ObjectVT, ArgVal); 3950 } else { 3951 if (CallConv == CallingConv::Fast) 3952 ComputeArgOffset(); 3953 3954 needsLoad = true; 3955 } 3956 3957 // When passing an array of floats, the array occupies consecutive 3958 // space in the argument area; only round up to the next doubleword 3959 // at the end of the array. Otherwise, each float takes 8 bytes. 3960 if (CallConv != CallingConv::Fast || needsLoad) { 3961 ArgSize = Flags.isInConsecutiveRegs() ? ObjSize : PtrByteSize; 3962 ArgOffset += ArgSize; 3963 if (Flags.isInConsecutiveRegsLast()) 3964 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3965 } 3966 break; 3967 case MVT::v4f32: 3968 case MVT::v4i32: 3969 case MVT::v8i16: 3970 case MVT::v16i8: 3971 case MVT::v2f64: 3972 case MVT::v2i64: 3973 case MVT::v1i128: 3974 case MVT::f128: 3975 if (!Subtarget.hasQPX()) { 3976 // These can be scalar arguments or elements of a vector array type 3977 // passed directly. The latter are used to implement ELFv2 homogenous 3978 // vector aggregates. 3979 if (VR_idx != Num_VR_Regs) { 3980 unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass); 3981 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 3982 ++VR_idx; 3983 } else { 3984 if (CallConv == CallingConv::Fast) 3985 ComputeArgOffset(); 3986 needsLoad = true; 3987 } 3988 if (CallConv != CallingConv::Fast || needsLoad) 3989 ArgOffset += 16; 3990 break; 3991 } // not QPX 3992 3993 assert(ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 && 3994 "Invalid QPX parameter type"); 3995 LLVM_FALLTHROUGH; 3996 3997 case MVT::v4f64: 3998 case MVT::v4i1: 3999 // QPX vectors are treated like their scalar floating-point subregisters 4000 // (except that they're larger). 4001 unsigned Sz = ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 ? 16 : 32; 4002 if (QFPR_idx != Num_QFPR_Regs) { 4003 const TargetRegisterClass *RC; 4004 switch (ObjectVT.getSimpleVT().SimpleTy) { 4005 case MVT::v4f64: RC = &PPC::QFRCRegClass; break; 4006 case MVT::v4f32: RC = &PPC::QSRCRegClass; break; 4007 default: RC = &PPC::QBRCRegClass; break; 4008 } 4009 4010 unsigned VReg = MF.addLiveIn(QFPR[QFPR_idx], RC); 4011 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 4012 ++QFPR_idx; 4013 } else { 4014 if (CallConv == CallingConv::Fast) 4015 ComputeArgOffset(); 4016 needsLoad = true; 4017 } 4018 if (CallConv != CallingConv::Fast || needsLoad) 4019 ArgOffset += Sz; 4020 break; 4021 } 4022 4023 // We need to load the argument to a virtual register if we determined 4024 // above that we ran out of physical registers of the appropriate type. 4025 if (needsLoad) { 4026 if (ObjSize < ArgSize && !isLittleEndian) 4027 CurArgOffset += ArgSize - ObjSize; 4028 int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, isImmutable); 4029 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4030 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo()); 4031 } 4032 4033 InVals.push_back(ArgVal); 4034 } 4035 4036 // Area that is at least reserved in the caller of this function. 4037 unsigned MinReservedArea; 4038 if (HasParameterArea) 4039 MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize); 4040 else 4041 MinReservedArea = LinkageSize; 4042 4043 // Set the size that is at least reserved in caller of this function. Tail 4044 // call optimized functions' reserved stack space needs to be aligned so that 4045 // taking the difference between two stack areas will result in an aligned 4046 // stack. 4047 MinReservedArea = 4048 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea); 4049 FuncInfo->setMinReservedArea(MinReservedArea); 4050 4051 // If the function takes variable number of arguments, make a frame index for 4052 // the start of the first vararg value... for expansion of llvm.va_start. 4053 if (isVarArg) { 4054 int Depth = ArgOffset; 4055 4056 FuncInfo->setVarArgsFrameIndex( 4057 MFI.CreateFixedObject(PtrByteSize, Depth, true)); 4058 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 4059 4060 // If this function is vararg, store any remaining integer argument regs 4061 // to their spots on the stack so that they may be loaded by dereferencing 4062 // the result of va_next. 4063 for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize; 4064 GPR_idx < Num_GPR_Regs; ++GPR_idx) { 4065 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4066 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4067 SDValue Store = 4068 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 4069 MemOps.push_back(Store); 4070 // Increment the address by four for the next argument to store 4071 SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT); 4072 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 4073 } 4074 } 4075 4076 if (!MemOps.empty()) 4077 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 4078 4079 return Chain; 4080 } 4081 4082 SDValue PPCTargetLowering::LowerFormalArguments_Darwin( 4083 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 4084 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 4085 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 4086 // TODO: add description of PPC stack frame format, or at least some docs. 4087 // 4088 MachineFunction &MF = DAG.getMachineFunction(); 4089 MachineFrameInfo &MFI = MF.getFrameInfo(); 4090 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 4091 4092 EVT PtrVT = getPointerTy(MF.getDataLayout()); 4093 bool isPPC64 = PtrVT == MVT::i64; 4094 // Potential tail calls could cause overwriting of argument stack slots. 4095 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt && 4096 (CallConv == CallingConv::Fast)); 4097 unsigned PtrByteSize = isPPC64 ? 8 : 4; 4098 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 4099 unsigned ArgOffset = LinkageSize; 4100 // Area that is at least reserved in caller of this function. 4101 unsigned MinReservedArea = ArgOffset; 4102 4103 static const MCPhysReg GPR_32[] = { // 32-bit registers. 4104 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 4105 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 4106 }; 4107 static const MCPhysReg GPR_64[] = { // 64-bit registers. 4108 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 4109 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 4110 }; 4111 static const MCPhysReg VR[] = { 4112 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 4113 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 4114 }; 4115 4116 const unsigned Num_GPR_Regs = array_lengthof(GPR_32); 4117 const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13; 4118 const unsigned Num_VR_Regs = array_lengthof( VR); 4119 4120 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 4121 4122 const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32; 4123 4124 // In 32-bit non-varargs functions, the stack space for vectors is after the 4125 // stack space for non-vectors. We do not use this space unless we have 4126 // too many vectors to fit in registers, something that only occurs in 4127 // constructed examples:), but we have to walk the arglist to figure 4128 // that out...for the pathological case, compute VecArgOffset as the 4129 // start of the vector parameter area. Computing VecArgOffset is the 4130 // entire point of the following loop. 4131 unsigned VecArgOffset = ArgOffset; 4132 if (!isVarArg && !isPPC64) { 4133 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; 4134 ++ArgNo) { 4135 EVT ObjectVT = Ins[ArgNo].VT; 4136 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags; 4137 4138 if (Flags.isByVal()) { 4139 // ObjSize is the true size, ArgSize rounded up to multiple of regs. 4140 unsigned ObjSize = Flags.getByValSize(); 4141 unsigned ArgSize = 4142 ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 4143 VecArgOffset += ArgSize; 4144 continue; 4145 } 4146 4147 switch(ObjectVT.getSimpleVT().SimpleTy) { 4148 default: llvm_unreachable("Unhandled argument type!"); 4149 case MVT::i1: 4150 case MVT::i32: 4151 case MVT::f32: 4152 VecArgOffset += 4; 4153 break; 4154 case MVT::i64: // PPC64 4155 case MVT::f64: 4156 // FIXME: We are guaranteed to be !isPPC64 at this point. 4157 // Does MVT::i64 apply? 4158 VecArgOffset += 8; 4159 break; 4160 case MVT::v4f32: 4161 case MVT::v4i32: 4162 case MVT::v8i16: 4163 case MVT::v16i8: 4164 // Nothing to do, we're only looking at Nonvector args here. 4165 break; 4166 } 4167 } 4168 } 4169 // We've found where the vector parameter area in memory is. Skip the 4170 // first 12 parameters; these don't use that memory. 4171 VecArgOffset = ((VecArgOffset+15)/16)*16; 4172 VecArgOffset += 12*16; 4173 4174 // Add DAG nodes to load the arguments or copy them out of registers. On 4175 // entry to a function on PPC, the arguments start after the linkage area, 4176 // although the first ones are often in registers. 4177 4178 SmallVector<SDValue, 8> MemOps; 4179 unsigned nAltivecParamsAtEnd = 0; 4180 Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin(); 4181 unsigned CurArgIdx = 0; 4182 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) { 4183 SDValue ArgVal; 4184 bool needsLoad = false; 4185 EVT ObjectVT = Ins[ArgNo].VT; 4186 unsigned ObjSize = ObjectVT.getSizeInBits()/8; 4187 unsigned ArgSize = ObjSize; 4188 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags; 4189 if (Ins[ArgNo].isOrigArg()) { 4190 std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx); 4191 CurArgIdx = Ins[ArgNo].getOrigArgIndex(); 4192 } 4193 unsigned CurArgOffset = ArgOffset; 4194 4195 // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary. 4196 if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 || 4197 ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) { 4198 if (isVarArg || isPPC64) { 4199 MinReservedArea = ((MinReservedArea+15)/16)*16; 4200 MinReservedArea += CalculateStackSlotSize(ObjectVT, 4201 Flags, 4202 PtrByteSize); 4203 } else nAltivecParamsAtEnd++; 4204 } else 4205 // Calculate min reserved area. 4206 MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT, 4207 Flags, 4208 PtrByteSize); 4209 4210 // FIXME the codegen can be much improved in some cases. 4211 // We do not have to keep everything in memory. 4212 if (Flags.isByVal()) { 4213 assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit"); 4214 4215 // ObjSize is the true size, ArgSize rounded up to multiple of registers. 4216 ObjSize = Flags.getByValSize(); 4217 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 4218 // Objects of size 1 and 2 are right justified, everything else is 4219 // left justified. This means the memory address is adjusted forwards. 4220 if (ObjSize==1 || ObjSize==2) { 4221 CurArgOffset = CurArgOffset + (4 - ObjSize); 4222 } 4223 // The value of the object is its address. 4224 int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, false, true); 4225 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4226 InVals.push_back(FIN); 4227 if (ObjSize==1 || ObjSize==2) { 4228 if (GPR_idx != Num_GPR_Regs) { 4229 unsigned VReg; 4230 if (isPPC64) 4231 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4232 else 4233 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 4234 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4235 EVT ObjType = ObjSize == 1 ? MVT::i8 : MVT::i16; 4236 SDValue Store = 4237 DAG.getTruncStore(Val.getValue(1), dl, Val, FIN, 4238 MachinePointerInfo(&*FuncArg), ObjType); 4239 MemOps.push_back(Store); 4240 ++GPR_idx; 4241 } 4242 4243 ArgOffset += PtrByteSize; 4244 4245 continue; 4246 } 4247 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) { 4248 // Store whatever pieces of the object are in registers 4249 // to memory. ArgOffset will be the address of the beginning 4250 // of the object. 4251 if (GPR_idx != Num_GPR_Regs) { 4252 unsigned VReg; 4253 if (isPPC64) 4254 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4255 else 4256 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 4257 int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true); 4258 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4259 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4260 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, 4261 MachinePointerInfo(&*FuncArg, j)); 4262 MemOps.push_back(Store); 4263 ++GPR_idx; 4264 ArgOffset += PtrByteSize; 4265 } else { 4266 ArgOffset += ArgSize - (ArgOffset-CurArgOffset); 4267 break; 4268 } 4269 } 4270 continue; 4271 } 4272 4273 switch (ObjectVT.getSimpleVT().SimpleTy) { 4274 default: llvm_unreachable("Unhandled argument type!"); 4275 case MVT::i1: 4276 case MVT::i32: 4277 if (!isPPC64) { 4278 if (GPR_idx != Num_GPR_Regs) { 4279 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 4280 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32); 4281 4282 if (ObjectVT == MVT::i1) 4283 ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgVal); 4284 4285 ++GPR_idx; 4286 } else { 4287 needsLoad = true; 4288 ArgSize = PtrByteSize; 4289 } 4290 // All int arguments reserve stack space in the Darwin ABI. 4291 ArgOffset += PtrByteSize; 4292 break; 4293 } 4294 LLVM_FALLTHROUGH; 4295 case MVT::i64: // PPC64 4296 if (GPR_idx != Num_GPR_Regs) { 4297 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4298 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 4299 4300 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1) 4301 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote 4302 // value to MVT::i64 and then truncate to the correct register size. 4303 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl); 4304 4305 ++GPR_idx; 4306 } else { 4307 needsLoad = true; 4308 ArgSize = PtrByteSize; 4309 } 4310 // All int arguments reserve stack space in the Darwin ABI. 4311 ArgOffset += 8; 4312 break; 4313 4314 case MVT::f32: 4315 case MVT::f64: 4316 // Every 4 bytes of argument space consumes one of the GPRs available for 4317 // argument passing. 4318 if (GPR_idx != Num_GPR_Regs) { 4319 ++GPR_idx; 4320 if (ObjSize == 8 && GPR_idx != Num_GPR_Regs && !isPPC64) 4321 ++GPR_idx; 4322 } 4323 if (FPR_idx != Num_FPR_Regs) { 4324 unsigned VReg; 4325 4326 if (ObjectVT == MVT::f32) 4327 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass); 4328 else 4329 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass); 4330 4331 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 4332 ++FPR_idx; 4333 } else { 4334 needsLoad = true; 4335 } 4336 4337 // All FP arguments reserve stack space in the Darwin ABI. 4338 ArgOffset += isPPC64 ? 8 : ObjSize; 4339 break; 4340 case MVT::v4f32: 4341 case MVT::v4i32: 4342 case MVT::v8i16: 4343 case MVT::v16i8: 4344 // Note that vector arguments in registers don't reserve stack space, 4345 // except in varargs functions. 4346 if (VR_idx != Num_VR_Regs) { 4347 unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass); 4348 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 4349 if (isVarArg) { 4350 while ((ArgOffset % 16) != 0) { 4351 ArgOffset += PtrByteSize; 4352 if (GPR_idx != Num_GPR_Regs) 4353 GPR_idx++; 4354 } 4355 ArgOffset += 16; 4356 GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64? 4357 } 4358 ++VR_idx; 4359 } else { 4360 if (!isVarArg && !isPPC64) { 4361 // Vectors go after all the nonvectors. 4362 CurArgOffset = VecArgOffset; 4363 VecArgOffset += 16; 4364 } else { 4365 // Vectors are aligned. 4366 ArgOffset = ((ArgOffset+15)/16)*16; 4367 CurArgOffset = ArgOffset; 4368 ArgOffset += 16; 4369 } 4370 needsLoad = true; 4371 } 4372 break; 4373 } 4374 4375 // We need to load the argument to a virtual register if we determined above 4376 // that we ran out of physical registers of the appropriate type. 4377 if (needsLoad) { 4378 int FI = MFI.CreateFixedObject(ObjSize, 4379 CurArgOffset + (ArgSize - ObjSize), 4380 isImmutable); 4381 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4382 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo()); 4383 } 4384 4385 InVals.push_back(ArgVal); 4386 } 4387 4388 // Allow for Altivec parameters at the end, if needed. 4389 if (nAltivecParamsAtEnd) { 4390 MinReservedArea = ((MinReservedArea+15)/16)*16; 4391 MinReservedArea += 16*nAltivecParamsAtEnd; 4392 } 4393 4394 // Area that is at least reserved in the caller of this function. 4395 MinReservedArea = std::max(MinReservedArea, LinkageSize + 8 * PtrByteSize); 4396 4397 // Set the size that is at least reserved in caller of this function. Tail 4398 // call optimized functions' reserved stack space needs to be aligned so that 4399 // taking the difference between two stack areas will result in an aligned 4400 // stack. 4401 MinReservedArea = 4402 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea); 4403 FuncInfo->setMinReservedArea(MinReservedArea); 4404 4405 // If the function takes variable number of arguments, make a frame index for 4406 // the start of the first vararg value... for expansion of llvm.va_start. 4407 if (isVarArg) { 4408 int Depth = ArgOffset; 4409 4410 FuncInfo->setVarArgsFrameIndex( 4411 MFI.CreateFixedObject(PtrVT.getSizeInBits()/8, 4412 Depth, true)); 4413 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 4414 4415 // If this function is vararg, store any remaining integer argument regs 4416 // to their spots on the stack so that they may be loaded by dereferencing 4417 // the result of va_next. 4418 for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) { 4419 unsigned VReg; 4420 4421 if (isPPC64) 4422 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4423 else 4424 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 4425 4426 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4427 SDValue Store = 4428 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 4429 MemOps.push_back(Store); 4430 // Increment the address by four for the next argument to store 4431 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT); 4432 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 4433 } 4434 } 4435 4436 if (!MemOps.empty()) 4437 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 4438 4439 return Chain; 4440 } 4441 4442 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be 4443 /// adjusted to accommodate the arguments for the tailcall. 4444 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall, 4445 unsigned ParamSize) { 4446 4447 if (!isTailCall) return 0; 4448 4449 PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>(); 4450 unsigned CallerMinReservedArea = FI->getMinReservedArea(); 4451 int SPDiff = (int)CallerMinReservedArea - (int)ParamSize; 4452 // Remember only if the new adjustment is bigger. 4453 if (SPDiff < FI->getTailCallSPDelta()) 4454 FI->setTailCallSPDelta(SPDiff); 4455 4456 return SPDiff; 4457 } 4458 4459 static bool isFunctionGlobalAddress(SDValue Callee); 4460 4461 static bool 4462 callsShareTOCBase(const Function *Caller, SDValue Callee, 4463 const TargetMachine &TM) { 4464 // Callee is either a GlobalAddress or an ExternalSymbol. ExternalSymbols 4465 // don't have enough information to determine if the caller and calle share 4466 // the same TOC base, so we have to pessimistically assume they don't for 4467 // correctness. 4468 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee); 4469 if (!G) 4470 return false; 4471 4472 const GlobalValue *GV = G->getGlobal(); 4473 // The medium and large code models are expected to provide a sufficiently 4474 // large TOC to provide all data addressing needs of a module with a 4475 // single TOC. Since each module will be addressed with a single TOC then we 4476 // only need to check that caller and callee don't cross dso boundaries. 4477 if (CodeModel::Medium == TM.getCodeModel() || 4478 CodeModel::Large == TM.getCodeModel()) 4479 return TM.shouldAssumeDSOLocal(*Caller->getParent(), GV); 4480 4481 // Otherwise we need to ensure callee and caller are in the same section, 4482 // since the linker may allocate multiple TOCs, and we don't know which 4483 // sections will belong to the same TOC base. 4484 4485 if (!GV->isStrongDefinitionForLinker()) 4486 return false; 4487 4488 // Any explicitly-specified sections and section prefixes must also match. 4489 // Also, if we're using -ffunction-sections, then each function is always in 4490 // a different section (the same is true for COMDAT functions). 4491 if (TM.getFunctionSections() || GV->hasComdat() || Caller->hasComdat() || 4492 GV->getSection() != Caller->getSection()) 4493 return false; 4494 if (const auto *F = dyn_cast<Function>(GV)) { 4495 if (F->getSectionPrefix() != Caller->getSectionPrefix()) 4496 return false; 4497 } 4498 4499 // If the callee might be interposed, then we can't assume the ultimate call 4500 // target will be in the same section. Even in cases where we can assume that 4501 // interposition won't happen, in any case where the linker might insert a 4502 // stub to allow for interposition, we must generate code as though 4503 // interposition might occur. To understand why this matters, consider a 4504 // situation where: a -> b -> c where the arrows indicate calls. b and c are 4505 // in the same section, but a is in a different module (i.e. has a different 4506 // TOC base pointer). If the linker allows for interposition between b and c, 4507 // then it will generate a stub for the call edge between b and c which will 4508 // save the TOC pointer into the designated stack slot allocated by b. If we 4509 // return true here, and therefore allow a tail call between b and c, that 4510 // stack slot won't exist and the b -> c stub will end up saving b'c TOC base 4511 // pointer into the stack slot allocated by a (where the a -> b stub saved 4512 // a's TOC base pointer). If we're not considering a tail call, but rather, 4513 // whether a nop is needed after the call instruction in b, because the linker 4514 // will insert a stub, it might complain about a missing nop if we omit it 4515 // (although many don't complain in this case). 4516 if (!TM.shouldAssumeDSOLocal(*Caller->getParent(), GV)) 4517 return false; 4518 4519 return true; 4520 } 4521 4522 static bool 4523 needStackSlotPassParameters(const PPCSubtarget &Subtarget, 4524 const SmallVectorImpl<ISD::OutputArg> &Outs) { 4525 assert(Subtarget.isSVR4ABI() && Subtarget.isPPC64()); 4526 4527 const unsigned PtrByteSize = 8; 4528 const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 4529 4530 static const MCPhysReg GPR[] = { 4531 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 4532 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 4533 }; 4534 static const MCPhysReg VR[] = { 4535 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 4536 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 4537 }; 4538 4539 const unsigned NumGPRs = array_lengthof(GPR); 4540 const unsigned NumFPRs = 13; 4541 const unsigned NumVRs = array_lengthof(VR); 4542 const unsigned ParamAreaSize = NumGPRs * PtrByteSize; 4543 4544 unsigned NumBytes = LinkageSize; 4545 unsigned AvailableFPRs = NumFPRs; 4546 unsigned AvailableVRs = NumVRs; 4547 4548 for (const ISD::OutputArg& Param : Outs) { 4549 if (Param.Flags.isNest()) continue; 4550 4551 if (CalculateStackSlotUsed(Param.VT, Param.ArgVT, Param.Flags, 4552 PtrByteSize, LinkageSize, ParamAreaSize, 4553 NumBytes, AvailableFPRs, AvailableVRs, 4554 Subtarget.hasQPX())) 4555 return true; 4556 } 4557 return false; 4558 } 4559 4560 static bool 4561 hasSameArgumentList(const Function *CallerFn, ImmutableCallSite CS) { 4562 if (CS.arg_size() != CallerFn->arg_size()) 4563 return false; 4564 4565 ImmutableCallSite::arg_iterator CalleeArgIter = CS.arg_begin(); 4566 ImmutableCallSite::arg_iterator CalleeArgEnd = CS.arg_end(); 4567 Function::const_arg_iterator CallerArgIter = CallerFn->arg_begin(); 4568 4569 for (; CalleeArgIter != CalleeArgEnd; ++CalleeArgIter, ++CallerArgIter) { 4570 const Value* CalleeArg = *CalleeArgIter; 4571 const Value* CallerArg = &(*CallerArgIter); 4572 if (CalleeArg == CallerArg) 4573 continue; 4574 4575 // e.g. @caller([4 x i64] %a, [4 x i64] %b) { 4576 // tail call @callee([4 x i64] undef, [4 x i64] %b) 4577 // } 4578 // 1st argument of callee is undef and has the same type as caller. 4579 if (CalleeArg->getType() == CallerArg->getType() && 4580 isa<UndefValue>(CalleeArg)) 4581 continue; 4582 4583 return false; 4584 } 4585 4586 return true; 4587 } 4588 4589 // Returns true if TCO is possible between the callers and callees 4590 // calling conventions. 4591 static bool 4592 areCallingConvEligibleForTCO_64SVR4(CallingConv::ID CallerCC, 4593 CallingConv::ID CalleeCC) { 4594 // Tail calls are possible with fastcc and ccc. 4595 auto isTailCallableCC = [] (CallingConv::ID CC){ 4596 return CC == CallingConv::C || CC == CallingConv::Fast; 4597 }; 4598 if (!isTailCallableCC(CallerCC) || !isTailCallableCC(CalleeCC)) 4599 return false; 4600 4601 // We can safely tail call both fastcc and ccc callees from a c calling 4602 // convention caller. If the caller is fastcc, we may have less stack space 4603 // than a non-fastcc caller with the same signature so disable tail-calls in 4604 // that case. 4605 return CallerCC == CallingConv::C || CallerCC == CalleeCC; 4606 } 4607 4608 bool 4609 PPCTargetLowering::IsEligibleForTailCallOptimization_64SVR4( 4610 SDValue Callee, 4611 CallingConv::ID CalleeCC, 4612 ImmutableCallSite CS, 4613 bool isVarArg, 4614 const SmallVectorImpl<ISD::OutputArg> &Outs, 4615 const SmallVectorImpl<ISD::InputArg> &Ins, 4616 SelectionDAG& DAG) const { 4617 bool TailCallOpt = getTargetMachine().Options.GuaranteedTailCallOpt; 4618 4619 if (DisableSCO && !TailCallOpt) return false; 4620 4621 // Variadic argument functions are not supported. 4622 if (isVarArg) return false; 4623 4624 auto &Caller = DAG.getMachineFunction().getFunction(); 4625 // Check that the calling conventions are compatible for tco. 4626 if (!areCallingConvEligibleForTCO_64SVR4(Caller.getCallingConv(), CalleeCC)) 4627 return false; 4628 4629 // Caller contains any byval parameter is not supported. 4630 if (any_of(Ins, [](const ISD::InputArg &IA) { return IA.Flags.isByVal(); })) 4631 return false; 4632 4633 // Callee contains any byval parameter is not supported, too. 4634 // Note: This is a quick work around, because in some cases, e.g. 4635 // caller's stack size > callee's stack size, we are still able to apply 4636 // sibling call optimization. For example, gcc is able to do SCO for caller1 4637 // in the following example, but not for caller2. 4638 // struct test { 4639 // long int a; 4640 // char ary[56]; 4641 // } gTest; 4642 // __attribute__((noinline)) int callee(struct test v, struct test *b) { 4643 // b->a = v.a; 4644 // return 0; 4645 // } 4646 // void caller1(struct test a, struct test c, struct test *b) { 4647 // callee(gTest, b); } 4648 // void caller2(struct test *b) { callee(gTest, b); } 4649 if (any_of(Outs, [](const ISD::OutputArg& OA) { return OA.Flags.isByVal(); })) 4650 return false; 4651 4652 // If callee and caller use different calling conventions, we cannot pass 4653 // parameters on stack since offsets for the parameter area may be different. 4654 if (Caller.getCallingConv() != CalleeCC && 4655 needStackSlotPassParameters(Subtarget, Outs)) 4656 return false; 4657 4658 // No TCO/SCO on indirect call because Caller have to restore its TOC 4659 if (!isFunctionGlobalAddress(Callee) && 4660 !isa<ExternalSymbolSDNode>(Callee)) 4661 return false; 4662 4663 // If the caller and callee potentially have different TOC bases then we 4664 // cannot tail call since we need to restore the TOC pointer after the call. 4665 // ref: https://bugzilla.mozilla.org/show_bug.cgi?id=973977 4666 if (!callsShareTOCBase(&Caller, Callee, getTargetMachine())) 4667 return false; 4668 4669 // TCO allows altering callee ABI, so we don't have to check further. 4670 if (CalleeCC == CallingConv::Fast && TailCallOpt) 4671 return true; 4672 4673 if (DisableSCO) return false; 4674 4675 // If callee use the same argument list that caller is using, then we can 4676 // apply SCO on this case. If it is not, then we need to check if callee needs 4677 // stack for passing arguments. 4678 if (!hasSameArgumentList(&Caller, CS) && 4679 needStackSlotPassParameters(Subtarget, Outs)) { 4680 return false; 4681 } 4682 4683 return true; 4684 } 4685 4686 /// IsEligibleForTailCallOptimization - Check whether the call is eligible 4687 /// for tail call optimization. Targets which want to do tail call 4688 /// optimization should implement this function. 4689 bool 4690 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee, 4691 CallingConv::ID CalleeCC, 4692 bool isVarArg, 4693 const SmallVectorImpl<ISD::InputArg> &Ins, 4694 SelectionDAG& DAG) const { 4695 if (!getTargetMachine().Options.GuaranteedTailCallOpt) 4696 return false; 4697 4698 // Variable argument functions are not supported. 4699 if (isVarArg) 4700 return false; 4701 4702 MachineFunction &MF = DAG.getMachineFunction(); 4703 CallingConv::ID CallerCC = MF.getFunction().getCallingConv(); 4704 if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) { 4705 // Functions containing by val parameters are not supported. 4706 for (unsigned i = 0; i != Ins.size(); i++) { 4707 ISD::ArgFlagsTy Flags = Ins[i].Flags; 4708 if (Flags.isByVal()) return false; 4709 } 4710 4711 // Non-PIC/GOT tail calls are supported. 4712 if (getTargetMachine().getRelocationModel() != Reloc::PIC_) 4713 return true; 4714 4715 // At the moment we can only do local tail calls (in same module, hidden 4716 // or protected) if we are generating PIC. 4717 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) 4718 return G->getGlobal()->hasHiddenVisibility() 4719 || G->getGlobal()->hasProtectedVisibility(); 4720 } 4721 4722 return false; 4723 } 4724 4725 /// isCallCompatibleAddress - Return the immediate to use if the specified 4726 /// 32-bit value is representable in the immediate field of a BxA instruction. 4727 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) { 4728 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op); 4729 if (!C) return nullptr; 4730 4731 int Addr = C->getZExtValue(); 4732 if ((Addr & 3) != 0 || // Low 2 bits are implicitly zero. 4733 SignExtend32<26>(Addr) != Addr) 4734 return nullptr; // Top 6 bits have to be sext of immediate. 4735 4736 return DAG 4737 .getConstant( 4738 (int)C->getZExtValue() >> 2, SDLoc(Op), 4739 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout())) 4740 .getNode(); 4741 } 4742 4743 namespace { 4744 4745 struct TailCallArgumentInfo { 4746 SDValue Arg; 4747 SDValue FrameIdxOp; 4748 int FrameIdx = 0; 4749 4750 TailCallArgumentInfo() = default; 4751 }; 4752 4753 } // end anonymous namespace 4754 4755 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot. 4756 static void StoreTailCallArgumentsToStackSlot( 4757 SelectionDAG &DAG, SDValue Chain, 4758 const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs, 4759 SmallVectorImpl<SDValue> &MemOpChains, const SDLoc &dl) { 4760 for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) { 4761 SDValue Arg = TailCallArgs[i].Arg; 4762 SDValue FIN = TailCallArgs[i].FrameIdxOp; 4763 int FI = TailCallArgs[i].FrameIdx; 4764 // Store relative to framepointer. 4765 MemOpChains.push_back(DAG.getStore( 4766 Chain, dl, Arg, FIN, 4767 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI))); 4768 } 4769 } 4770 4771 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to 4772 /// the appropriate stack slot for the tail call optimized function call. 4773 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG, SDValue Chain, 4774 SDValue OldRetAddr, SDValue OldFP, 4775 int SPDiff, const SDLoc &dl) { 4776 if (SPDiff) { 4777 // Calculate the new stack slot for the return address. 4778 MachineFunction &MF = DAG.getMachineFunction(); 4779 const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>(); 4780 const PPCFrameLowering *FL = Subtarget.getFrameLowering(); 4781 bool isPPC64 = Subtarget.isPPC64(); 4782 int SlotSize = isPPC64 ? 8 : 4; 4783 int NewRetAddrLoc = SPDiff + FL->getReturnSaveOffset(); 4784 int NewRetAddr = MF.getFrameInfo().CreateFixedObject(SlotSize, 4785 NewRetAddrLoc, true); 4786 EVT VT = isPPC64 ? MVT::i64 : MVT::i32; 4787 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT); 4788 Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx, 4789 MachinePointerInfo::getFixedStack(MF, NewRetAddr)); 4790 4791 // When using the 32/64-bit SVR4 ABI there is no need to move the FP stack 4792 // slot as the FP is never overwritten. 4793 if (Subtarget.isDarwinABI()) { 4794 int NewFPLoc = SPDiff + FL->getFramePointerSaveOffset(); 4795 int NewFPIdx = MF.getFrameInfo().CreateFixedObject(SlotSize, NewFPLoc, 4796 true); 4797 SDValue NewFramePtrIdx = DAG.getFrameIndex(NewFPIdx, VT); 4798 Chain = DAG.getStore(Chain, dl, OldFP, NewFramePtrIdx, 4799 MachinePointerInfo::getFixedStack( 4800 DAG.getMachineFunction(), NewFPIdx)); 4801 } 4802 } 4803 return Chain; 4804 } 4805 4806 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate 4807 /// the position of the argument. 4808 static void 4809 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64, 4810 SDValue Arg, int SPDiff, unsigned ArgOffset, 4811 SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) { 4812 int Offset = ArgOffset + SPDiff; 4813 uint32_t OpSize = (Arg.getValueSizeInBits() + 7) / 8; 4814 int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true); 4815 EVT VT = isPPC64 ? MVT::i64 : MVT::i32; 4816 SDValue FIN = DAG.getFrameIndex(FI, VT); 4817 TailCallArgumentInfo Info; 4818 Info.Arg = Arg; 4819 Info.FrameIdxOp = FIN; 4820 Info.FrameIdx = FI; 4821 TailCallArguments.push_back(Info); 4822 } 4823 4824 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address 4825 /// stack slot. Returns the chain as result and the loaded frame pointers in 4826 /// LROpOut/FPOpout. Used when tail calling. 4827 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr( 4828 SelectionDAG &DAG, int SPDiff, SDValue Chain, SDValue &LROpOut, 4829 SDValue &FPOpOut, const SDLoc &dl) const { 4830 if (SPDiff) { 4831 // Load the LR and FP stack slot for later adjusting. 4832 EVT VT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32; 4833 LROpOut = getReturnAddrFrameIndex(DAG); 4834 LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo()); 4835 Chain = SDValue(LROpOut.getNode(), 1); 4836 4837 // When using the 32/64-bit SVR4 ABI there is no need to load the FP stack 4838 // slot as the FP is never overwritten. 4839 if (Subtarget.isDarwinABI()) { 4840 FPOpOut = getFramePointerFrameIndex(DAG); 4841 FPOpOut = DAG.getLoad(VT, dl, Chain, FPOpOut, MachinePointerInfo()); 4842 Chain = SDValue(FPOpOut.getNode(), 1); 4843 } 4844 } 4845 return Chain; 4846 } 4847 4848 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified 4849 /// by "Src" to address "Dst" of size "Size". Alignment information is 4850 /// specified by the specific parameter attribute. The copy will be passed as 4851 /// a byval function parameter. 4852 /// Sometimes what we are copying is the end of a larger object, the part that 4853 /// does not fit in registers. 4854 static SDValue CreateCopyOfByValArgument(SDValue Src, SDValue Dst, 4855 SDValue Chain, ISD::ArgFlagsTy Flags, 4856 SelectionDAG &DAG, const SDLoc &dl) { 4857 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32); 4858 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(), 4859 false, false, false, MachinePointerInfo(), 4860 MachinePointerInfo()); 4861 } 4862 4863 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of 4864 /// tail calls. 4865 static void LowerMemOpCallTo( 4866 SelectionDAG &DAG, MachineFunction &MF, SDValue Chain, SDValue Arg, 4867 SDValue PtrOff, int SPDiff, unsigned ArgOffset, bool isPPC64, 4868 bool isTailCall, bool isVector, SmallVectorImpl<SDValue> &MemOpChains, 4869 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments, const SDLoc &dl) { 4870 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 4871 if (!isTailCall) { 4872 if (isVector) { 4873 SDValue StackPtr; 4874 if (isPPC64) 4875 StackPtr = DAG.getRegister(PPC::X1, MVT::i64); 4876 else 4877 StackPtr = DAG.getRegister(PPC::R1, MVT::i32); 4878 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, 4879 DAG.getConstant(ArgOffset, dl, PtrVT)); 4880 } 4881 MemOpChains.push_back( 4882 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo())); 4883 // Calculate and remember argument location. 4884 } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset, 4885 TailCallArguments); 4886 } 4887 4888 static void 4889 PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain, 4890 const SDLoc &dl, int SPDiff, unsigned NumBytes, SDValue LROp, 4891 SDValue FPOp, 4892 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) { 4893 // Emit a sequence of copyto/copyfrom virtual registers for arguments that 4894 // might overwrite each other in case of tail call optimization. 4895 SmallVector<SDValue, 8> MemOpChains2; 4896 // Do not flag preceding copytoreg stuff together with the following stuff. 4897 InFlag = SDValue(); 4898 StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments, 4899 MemOpChains2, dl); 4900 if (!MemOpChains2.empty()) 4901 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2); 4902 4903 // Store the return address to the appropriate stack slot. 4904 Chain = EmitTailCallStoreFPAndRetAddr(DAG, Chain, LROp, FPOp, SPDiff, dl); 4905 4906 // Emit callseq_end just before tailcall node. 4907 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true), 4908 DAG.getIntPtrConstant(0, dl, true), InFlag, dl); 4909 InFlag = Chain.getValue(1); 4910 } 4911 4912 // Is this global address that of a function that can be called by name? (as 4913 // opposed to something that must hold a descriptor for an indirect call). 4914 static bool isFunctionGlobalAddress(SDValue Callee) { 4915 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 4916 if (Callee.getOpcode() == ISD::GlobalTLSAddress || 4917 Callee.getOpcode() == ISD::TargetGlobalTLSAddress) 4918 return false; 4919 4920 return G->getGlobal()->getValueType()->isFunctionTy(); 4921 } 4922 4923 return false; 4924 } 4925 4926 static unsigned 4927 PrepareCall(SelectionDAG &DAG, SDValue &Callee, SDValue &InFlag, SDValue &Chain, 4928 SDValue CallSeqStart, const SDLoc &dl, int SPDiff, bool isTailCall, 4929 bool isPatchPoint, bool hasNest, 4930 SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass, 4931 SmallVectorImpl<SDValue> &Ops, std::vector<EVT> &NodeTys, 4932 ImmutableCallSite CS, const PPCSubtarget &Subtarget) { 4933 bool isPPC64 = Subtarget.isPPC64(); 4934 bool isSVR4ABI = Subtarget.isSVR4ABI(); 4935 bool isELFv2ABI = Subtarget.isELFv2ABI(); 4936 bool isAIXABI = Subtarget.isAIXABI(); 4937 4938 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 4939 NodeTys.push_back(MVT::Other); // Returns a chain 4940 NodeTys.push_back(MVT::Glue); // Returns a flag for retval copy to use. 4941 4942 unsigned CallOpc = PPCISD::CALL; 4943 4944 bool needIndirectCall = true; 4945 if (!isSVR4ABI || !isPPC64) 4946 if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG)) { 4947 // If this is an absolute destination address, use the munged value. 4948 Callee = SDValue(Dest, 0); 4949 needIndirectCall = false; 4950 } 4951 4952 // PC-relative references to external symbols should go through $stub, unless 4953 // we're building with the leopard linker or later, which automatically 4954 // synthesizes these stubs. 4955 const TargetMachine &TM = DAG.getTarget(); 4956 const Module *Mod = DAG.getMachineFunction().getFunction().getParent(); 4957 const GlobalValue *GV = nullptr; 4958 if (auto *G = dyn_cast<GlobalAddressSDNode>(Callee)) 4959 GV = G->getGlobal(); 4960 bool Local = TM.shouldAssumeDSOLocal(*Mod, GV); 4961 bool UsePlt = !Local && Subtarget.isTargetELF() && !isPPC64; 4962 4963 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, 4964 // every direct call is) turn it into a TargetGlobalAddress / 4965 // TargetExternalSymbol node so that legalize doesn't hack it. 4966 if (isFunctionGlobalAddress(Callee)) { 4967 GlobalAddressSDNode *G = cast<GlobalAddressSDNode>(Callee); 4968 4969 // A call to a TLS address is actually an indirect call to a 4970 // thread-specific pointer. 4971 unsigned OpFlags = 0; 4972 if (UsePlt) 4973 OpFlags = PPCII::MO_PLT; 4974 4975 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl, 4976 Callee.getValueType(), 0, OpFlags); 4977 needIndirectCall = false; 4978 } 4979 4980 if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) { 4981 unsigned char OpFlags = 0; 4982 4983 if (UsePlt) 4984 OpFlags = PPCII::MO_PLT; 4985 4986 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), Callee.getValueType(), 4987 OpFlags); 4988 needIndirectCall = false; 4989 } 4990 4991 if (isPatchPoint) { 4992 // We'll form an invalid direct call when lowering a patchpoint; the full 4993 // sequence for an indirect call is complicated, and many of the 4994 // instructions introduced might have side effects (and, thus, can't be 4995 // removed later). The call itself will be removed as soon as the 4996 // argument/return lowering is complete, so the fact that it has the wrong 4997 // kind of operands should not really matter. 4998 needIndirectCall = false; 4999 } 5000 5001 if (needIndirectCall) { 5002 // Otherwise, this is an indirect call. We have to use a MTCTR/BCTRL pair 5003 // to do the call, we can't use PPCISD::CALL. 5004 SDValue MTCTROps[] = {Chain, Callee, InFlag}; 5005 5006 if (isSVR4ABI && isPPC64 && !isELFv2ABI) { 5007 // Function pointers in the 64-bit SVR4 ABI do not point to the function 5008 // entry point, but to the function descriptor (the function entry point 5009 // address is part of the function descriptor though). 5010 // The function descriptor is a three doubleword structure with the 5011 // following fields: function entry point, TOC base address and 5012 // environment pointer. 5013 // Thus for a call through a function pointer, the following actions need 5014 // to be performed: 5015 // 1. Save the TOC of the caller in the TOC save area of its stack 5016 // frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()). 5017 // 2. Load the address of the function entry point from the function 5018 // descriptor. 5019 // 3. Load the TOC of the callee from the function descriptor into r2. 5020 // 4. Load the environment pointer from the function descriptor into 5021 // r11. 5022 // 5. Branch to the function entry point address. 5023 // 6. On return of the callee, the TOC of the caller needs to be 5024 // restored (this is done in FinishCall()). 5025 // 5026 // The loads are scheduled at the beginning of the call sequence, and the 5027 // register copies are flagged together to ensure that no other 5028 // operations can be scheduled in between. E.g. without flagging the 5029 // copies together, a TOC access in the caller could be scheduled between 5030 // the assignment of the callee TOC and the branch to the callee, which 5031 // results in the TOC access going through the TOC of the callee instead 5032 // of going through the TOC of the caller, which leads to incorrect code. 5033 5034 // Load the address of the function entry point from the function 5035 // descriptor. 5036 SDValue LDChain = CallSeqStart.getValue(CallSeqStart->getNumValues()-1); 5037 if (LDChain.getValueType() == MVT::Glue) 5038 LDChain = CallSeqStart.getValue(CallSeqStart->getNumValues()-2); 5039 5040 auto MMOFlags = Subtarget.hasInvariantFunctionDescriptors() 5041 ? (MachineMemOperand::MODereferenceable | 5042 MachineMemOperand::MOInvariant) 5043 : MachineMemOperand::MONone; 5044 5045 MachinePointerInfo MPI(CS ? CS.getCalledValue() : nullptr); 5046 SDValue LoadFuncPtr = DAG.getLoad(MVT::i64, dl, LDChain, Callee, MPI, 5047 /* Alignment = */ 8, MMOFlags); 5048 5049 // Load environment pointer into r11. 5050 SDValue PtrOff = DAG.getIntPtrConstant(16, dl); 5051 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, PtrOff); 5052 SDValue LoadEnvPtr = 5053 DAG.getLoad(MVT::i64, dl, LDChain, AddPtr, MPI.getWithOffset(16), 5054 /* Alignment = */ 8, MMOFlags); 5055 5056 SDValue TOCOff = DAG.getIntPtrConstant(8, dl); 5057 SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, TOCOff); 5058 SDValue TOCPtr = 5059 DAG.getLoad(MVT::i64, dl, LDChain, AddTOC, MPI.getWithOffset(8), 5060 /* Alignment = */ 8, MMOFlags); 5061 5062 setUsesTOCBasePtr(DAG); 5063 SDValue TOCVal = DAG.getCopyToReg(Chain, dl, PPC::X2, TOCPtr, 5064 InFlag); 5065 Chain = TOCVal.getValue(0); 5066 InFlag = TOCVal.getValue(1); 5067 5068 // If the function call has an explicit 'nest' parameter, it takes the 5069 // place of the environment pointer. 5070 if (!hasNest) { 5071 SDValue EnvVal = DAG.getCopyToReg(Chain, dl, PPC::X11, LoadEnvPtr, 5072 InFlag); 5073 5074 Chain = EnvVal.getValue(0); 5075 InFlag = EnvVal.getValue(1); 5076 } 5077 5078 MTCTROps[0] = Chain; 5079 MTCTROps[1] = LoadFuncPtr; 5080 MTCTROps[2] = InFlag; 5081 } 5082 5083 Chain = DAG.getNode(PPCISD::MTCTR, dl, NodeTys, 5084 makeArrayRef(MTCTROps, InFlag.getNode() ? 3 : 2)); 5085 InFlag = Chain.getValue(1); 5086 5087 NodeTys.clear(); 5088 NodeTys.push_back(MVT::Other); 5089 NodeTys.push_back(MVT::Glue); 5090 Ops.push_back(Chain); 5091 CallOpc = PPCISD::BCTRL; 5092 Callee.setNode(nullptr); 5093 // Add use of X11 (holding environment pointer) 5094 if (isSVR4ABI && isPPC64 && !isELFv2ABI && !hasNest) 5095 Ops.push_back(DAG.getRegister(PPC::X11, PtrVT)); 5096 // Add CTR register as callee so a bctr can be emitted later. 5097 if (isTailCall) 5098 Ops.push_back(DAG.getRegister(isPPC64 ? PPC::CTR8 : PPC::CTR, PtrVT)); 5099 } 5100 5101 // If this is a direct call, pass the chain and the callee. 5102 if (Callee.getNode()) { 5103 Ops.push_back(Chain); 5104 Ops.push_back(Callee); 5105 } 5106 // If this is a tail call add stack pointer delta. 5107 if (isTailCall) 5108 Ops.push_back(DAG.getConstant(SPDiff, dl, MVT::i32)); 5109 5110 // Add argument registers to the end of the list so that they are known live 5111 // into the call. 5112 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) 5113 Ops.push_back(DAG.getRegister(RegsToPass[i].first, 5114 RegsToPass[i].second.getValueType())); 5115 5116 // All calls, in the AIX ABI and 64-bit ELF ABIs, need the TOC register 5117 // live into the call. 5118 // We do need to reserve R2/X2 to appease the verifier for the PATCHPOINT. 5119 if ((isSVR4ABI && isPPC64) || isAIXABI) { 5120 setUsesTOCBasePtr(DAG); 5121 5122 // We cannot add R2/X2 as an operand here for PATCHPOINT, because there is 5123 // no way to mark dependencies as implicit here. 5124 // We will add the R2/X2 dependency in EmitInstrWithCustomInserter. 5125 if (!isPatchPoint) 5126 Ops.push_back(DAG.getRegister(isPPC64 ? PPC::X2 5127 : PPC::R2, PtrVT)); 5128 } 5129 5130 return CallOpc; 5131 } 5132 5133 SDValue PPCTargetLowering::LowerCallResult( 5134 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg, 5135 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 5136 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 5137 SmallVector<CCValAssign, 16> RVLocs; 5138 CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 5139 *DAG.getContext()); 5140 5141 CCRetInfo.AnalyzeCallResult( 5142 Ins, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold) 5143 ? RetCC_PPC_Cold 5144 : RetCC_PPC); 5145 5146 // Copy all of the result registers out of their specified physreg. 5147 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) { 5148 CCValAssign &VA = RVLocs[i]; 5149 assert(VA.isRegLoc() && "Can only return in registers!"); 5150 5151 SDValue Val; 5152 5153 if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) { 5154 SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, 5155 InFlag); 5156 Chain = Lo.getValue(1); 5157 InFlag = Lo.getValue(2); 5158 VA = RVLocs[++i]; // skip ahead to next loc 5159 SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, 5160 InFlag); 5161 Chain = Hi.getValue(1); 5162 InFlag = Hi.getValue(2); 5163 if (!Subtarget.isLittleEndian()) 5164 std::swap (Lo, Hi); 5165 Val = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, Lo, Hi); 5166 } else { 5167 Val = DAG.getCopyFromReg(Chain, dl, 5168 VA.getLocReg(), VA.getLocVT(), InFlag); 5169 Chain = Val.getValue(1); 5170 InFlag = Val.getValue(2); 5171 } 5172 5173 switch (VA.getLocInfo()) { 5174 default: llvm_unreachable("Unknown loc info!"); 5175 case CCValAssign::Full: break; 5176 case CCValAssign::AExt: 5177 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val); 5178 break; 5179 case CCValAssign::ZExt: 5180 Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val, 5181 DAG.getValueType(VA.getValVT())); 5182 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val); 5183 break; 5184 case CCValAssign::SExt: 5185 Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val, 5186 DAG.getValueType(VA.getValVT())); 5187 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val); 5188 break; 5189 } 5190 5191 InVals.push_back(Val); 5192 } 5193 5194 return Chain; 5195 } 5196 5197 SDValue PPCTargetLowering::FinishCall( 5198 CallingConv::ID CallConv, const SDLoc &dl, bool isTailCall, bool isVarArg, 5199 bool isPatchPoint, bool hasNest, SelectionDAG &DAG, 5200 SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, SDValue InFlag, 5201 SDValue Chain, SDValue CallSeqStart, SDValue &Callee, int SPDiff, 5202 unsigned NumBytes, const SmallVectorImpl<ISD::InputArg> &Ins, 5203 SmallVectorImpl<SDValue> &InVals, ImmutableCallSite CS) const { 5204 std::vector<EVT> NodeTys; 5205 SmallVector<SDValue, 8> Ops; 5206 unsigned CallOpc = PrepareCall(DAG, Callee, InFlag, Chain, CallSeqStart, dl, 5207 SPDiff, isTailCall, isPatchPoint, hasNest, 5208 RegsToPass, Ops, NodeTys, CS, Subtarget); 5209 5210 // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls 5211 if (isVarArg && Subtarget.isSVR4ABI() && !Subtarget.isPPC64()) 5212 Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32)); 5213 5214 // When performing tail call optimization the callee pops its arguments off 5215 // the stack. Account for this here so these bytes can be pushed back on in 5216 // PPCFrameLowering::eliminateCallFramePseudoInstr. 5217 int BytesCalleePops = 5218 (CallConv == CallingConv::Fast && 5219 getTargetMachine().Options.GuaranteedTailCallOpt) ? NumBytes : 0; 5220 5221 // Add a register mask operand representing the call-preserved registers. 5222 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo(); 5223 const uint32_t *Mask = 5224 TRI->getCallPreservedMask(DAG.getMachineFunction(), CallConv); 5225 assert(Mask && "Missing call preserved mask for calling convention"); 5226 Ops.push_back(DAG.getRegisterMask(Mask)); 5227 5228 if (InFlag.getNode()) 5229 Ops.push_back(InFlag); 5230 5231 // Emit tail call. 5232 if (isTailCall) { 5233 assert(((Callee.getOpcode() == ISD::Register && 5234 cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) || 5235 Callee.getOpcode() == ISD::TargetExternalSymbol || 5236 Callee.getOpcode() == ISD::TargetGlobalAddress || 5237 isa<ConstantSDNode>(Callee)) && 5238 "Expecting an global address, external symbol, absolute value or register"); 5239 5240 DAG.getMachineFunction().getFrameInfo().setHasTailCall(); 5241 return DAG.getNode(PPCISD::TC_RETURN, dl, MVT::Other, Ops); 5242 } 5243 5244 // Add a NOP immediately after the branch instruction when using the 64-bit 5245 // SVR4 or the AIX ABI. 5246 // At link time, if caller and callee are in a different module and 5247 // thus have a different TOC, the call will be replaced with a call to a stub 5248 // function which saves the current TOC, loads the TOC of the callee and 5249 // branches to the callee. The NOP will be replaced with a load instruction 5250 // which restores the TOC of the caller from the TOC save slot of the current 5251 // stack frame. If caller and callee belong to the same module (and have the 5252 // same TOC), the NOP will remain unchanged, or become some other NOP. 5253 5254 MachineFunction &MF = DAG.getMachineFunction(); 5255 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 5256 if (!isTailCall && !isPatchPoint && 5257 ((Subtarget.isSVR4ABI() && Subtarget.isPPC64()) || 5258 Subtarget.isAIXABI())) { 5259 if (CallOpc == PPCISD::BCTRL) { 5260 if (Subtarget.isAIXABI()) 5261 report_fatal_error("Indirect call on AIX is not implemented."); 5262 5263 // This is a call through a function pointer. 5264 // Restore the caller TOC from the save area into R2. 5265 // See PrepareCall() for more information about calls through function 5266 // pointers in the 64-bit SVR4 ABI. 5267 // We are using a target-specific load with r2 hard coded, because the 5268 // result of a target-independent load would never go directly into r2, 5269 // since r2 is a reserved register (which prevents the register allocator 5270 // from allocating it), resulting in an additional register being 5271 // allocated and an unnecessary move instruction being generated. 5272 CallOpc = PPCISD::BCTRL_LOAD_TOC; 5273 5274 SDValue StackPtr = DAG.getRegister(PPC::X1, PtrVT); 5275 unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset(); 5276 SDValue TOCOff = DAG.getIntPtrConstant(TOCSaveOffset, dl); 5277 SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, StackPtr, TOCOff); 5278 5279 // The address needs to go after the chain input but before the flag (or 5280 // any other variadic arguments). 5281 Ops.insert(std::next(Ops.begin()), AddTOC); 5282 } else if (CallOpc == PPCISD::CALL && 5283 !callsShareTOCBase(&MF.getFunction(), Callee, DAG.getTarget())) { 5284 // Otherwise insert NOP for non-local calls. 5285 CallOpc = PPCISD::CALL_NOP; 5286 } 5287 } 5288 5289 if (Subtarget.isAIXABI() && isFunctionGlobalAddress(Callee)) { 5290 // On AIX, direct function calls reference the symbol for the function's 5291 // entry point, which is named by inserting a "." before the function's 5292 // C-linkage name. 5293 GlobalAddressSDNode *G = cast<GlobalAddressSDNode>(Callee); 5294 auto &Context = DAG.getMachineFunction().getMMI().getContext(); 5295 MCSymbol *S = Context.getOrCreateSymbol(Twine(".") + 5296 Twine(G->getGlobal()->getName())); 5297 Callee = DAG.getMCSymbol(S, PtrVT); 5298 // Replace the GlobalAddressSDNode Callee with the MCSymbolSDNode. 5299 Ops[1] = Callee; 5300 } 5301 5302 Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops); 5303 InFlag = Chain.getValue(1); 5304 5305 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true), 5306 DAG.getIntPtrConstant(BytesCalleePops, dl, true), 5307 InFlag, dl); 5308 if (!Ins.empty()) 5309 InFlag = Chain.getValue(1); 5310 5311 return LowerCallResult(Chain, InFlag, CallConv, isVarArg, 5312 Ins, dl, DAG, InVals); 5313 } 5314 5315 SDValue 5316 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI, 5317 SmallVectorImpl<SDValue> &InVals) const { 5318 SelectionDAG &DAG = CLI.DAG; 5319 SDLoc &dl = CLI.DL; 5320 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs; 5321 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals; 5322 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins; 5323 SDValue Chain = CLI.Chain; 5324 SDValue Callee = CLI.Callee; 5325 bool &isTailCall = CLI.IsTailCall; 5326 CallingConv::ID CallConv = CLI.CallConv; 5327 bool isVarArg = CLI.IsVarArg; 5328 bool isPatchPoint = CLI.IsPatchPoint; 5329 ImmutableCallSite CS = CLI.CS; 5330 5331 if (isTailCall) { 5332 if (Subtarget.useLongCalls() && !(CS && CS.isMustTailCall())) 5333 isTailCall = false; 5334 else if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) 5335 isTailCall = 5336 IsEligibleForTailCallOptimization_64SVR4(Callee, CallConv, CS, 5337 isVarArg, Outs, Ins, DAG); 5338 else 5339 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg, 5340 Ins, DAG); 5341 if (isTailCall) { 5342 ++NumTailCalls; 5343 if (!getTargetMachine().Options.GuaranteedTailCallOpt) 5344 ++NumSiblingCalls; 5345 5346 assert(isa<GlobalAddressSDNode>(Callee) && 5347 "Callee should be an llvm::Function object."); 5348 LLVM_DEBUG( 5349 const GlobalValue *GV = 5350 cast<GlobalAddressSDNode>(Callee)->getGlobal(); 5351 const unsigned Width = 5352 80 - strlen("TCO caller: ") - strlen(", callee linkage: 0, 0"); 5353 dbgs() << "TCO caller: " 5354 << left_justify(DAG.getMachineFunction().getName(), Width) 5355 << ", callee linkage: " << GV->getVisibility() << ", " 5356 << GV->getLinkage() << "\n"); 5357 } 5358 } 5359 5360 if (!isTailCall && CS && CS.isMustTailCall()) 5361 report_fatal_error("failed to perform tail call elimination on a call " 5362 "site marked musttail"); 5363 5364 // When long calls (i.e. indirect calls) are always used, calls are always 5365 // made via function pointer. If we have a function name, first translate it 5366 // into a pointer. 5367 if (Subtarget.useLongCalls() && isa<GlobalAddressSDNode>(Callee) && 5368 !isTailCall) 5369 Callee = LowerGlobalAddress(Callee, DAG); 5370 5371 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) 5372 return LowerCall_64SVR4(Chain, Callee, CallConv, isVarArg, 5373 isTailCall, isPatchPoint, Outs, OutVals, Ins, 5374 dl, DAG, InVals, CS); 5375 5376 if (Subtarget.isSVR4ABI()) 5377 return LowerCall_32SVR4(Chain, Callee, CallConv, isVarArg, 5378 isTailCall, isPatchPoint, Outs, OutVals, Ins, 5379 dl, DAG, InVals, CS); 5380 5381 if (Subtarget.isAIXABI()) 5382 return LowerCall_AIX(Chain, Callee, CallConv, isVarArg, 5383 isTailCall, isPatchPoint, Outs, OutVals, Ins, 5384 dl, DAG, InVals, CS); 5385 5386 return LowerCall_Darwin(Chain, Callee, CallConv, isVarArg, 5387 isTailCall, isPatchPoint, Outs, OutVals, Ins, 5388 dl, DAG, InVals, CS); 5389 } 5390 5391 SDValue PPCTargetLowering::LowerCall_32SVR4( 5392 SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg, 5393 bool isTailCall, bool isPatchPoint, 5394 const SmallVectorImpl<ISD::OutputArg> &Outs, 5395 const SmallVectorImpl<SDValue> &OutVals, 5396 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 5397 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 5398 ImmutableCallSite CS) const { 5399 // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description 5400 // of the 32-bit SVR4 ABI stack frame layout. 5401 5402 assert((CallConv == CallingConv::C || 5403 CallConv == CallingConv::Cold || 5404 CallConv == CallingConv::Fast) && "Unknown calling convention!"); 5405 5406 unsigned PtrByteSize = 4; 5407 5408 MachineFunction &MF = DAG.getMachineFunction(); 5409 5410 // Mark this function as potentially containing a function that contains a 5411 // tail call. As a consequence the frame pointer will be used for dynamicalloc 5412 // and restoring the callers stack pointer in this functions epilog. This is 5413 // done because by tail calling the called function might overwrite the value 5414 // in this function's (MF) stack pointer stack slot 0(SP). 5415 if (getTargetMachine().Options.GuaranteedTailCallOpt && 5416 CallConv == CallingConv::Fast) 5417 MF.getInfo<PPCFunctionInfo>()->setHasFastCall(); 5418 5419 // Count how many bytes are to be pushed on the stack, including the linkage 5420 // area, parameter list area and the part of the local variable space which 5421 // contains copies of aggregates which are passed by value. 5422 5423 // Assign locations to all of the outgoing arguments. 5424 SmallVector<CCValAssign, 16> ArgLocs; 5425 PPCCCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext()); 5426 5427 // Reserve space for the linkage area on the stack. 5428 CCInfo.AllocateStack(Subtarget.getFrameLowering()->getLinkageSize(), 5429 PtrByteSize); 5430 if (useSoftFloat()) 5431 CCInfo.PreAnalyzeCallOperands(Outs); 5432 5433 if (isVarArg) { 5434 // Handle fixed and variable vector arguments differently. 5435 // Fixed vector arguments go into registers as long as registers are 5436 // available. Variable vector arguments always go into memory. 5437 unsigned NumArgs = Outs.size(); 5438 5439 for (unsigned i = 0; i != NumArgs; ++i) { 5440 MVT ArgVT = Outs[i].VT; 5441 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 5442 bool Result; 5443 5444 if (Outs[i].IsFixed) { 5445 Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, 5446 CCInfo); 5447 } else { 5448 Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full, 5449 ArgFlags, CCInfo); 5450 } 5451 5452 if (Result) { 5453 #ifndef NDEBUG 5454 errs() << "Call operand #" << i << " has unhandled type " 5455 << EVT(ArgVT).getEVTString() << "\n"; 5456 #endif 5457 llvm_unreachable(nullptr); 5458 } 5459 } 5460 } else { 5461 // All arguments are treated the same. 5462 CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4); 5463 } 5464 CCInfo.clearWasPPCF128(); 5465 5466 // Assign locations to all of the outgoing aggregate by value arguments. 5467 SmallVector<CCValAssign, 16> ByValArgLocs; 5468 CCState CCByValInfo(CallConv, isVarArg, MF, ByValArgLocs, *DAG.getContext()); 5469 5470 // Reserve stack space for the allocations in CCInfo. 5471 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize); 5472 5473 CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal); 5474 5475 // Size of the linkage area, parameter list area and the part of the local 5476 // space variable where copies of aggregates which are passed by value are 5477 // stored. 5478 unsigned NumBytes = CCByValInfo.getNextStackOffset(); 5479 5480 // Calculate by how many bytes the stack has to be adjusted in case of tail 5481 // call optimization. 5482 int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes); 5483 5484 // Adjust the stack pointer for the new arguments... 5485 // These operations are automatically eliminated by the prolog/epilog pass 5486 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 5487 SDValue CallSeqStart = Chain; 5488 5489 // Load the return address and frame pointer so it can be moved somewhere else 5490 // later. 5491 SDValue LROp, FPOp; 5492 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl); 5493 5494 // Set up a copy of the stack pointer for use loading and storing any 5495 // arguments that may not fit in the registers available for argument 5496 // passing. 5497 SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32); 5498 5499 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 5500 SmallVector<TailCallArgumentInfo, 8> TailCallArguments; 5501 SmallVector<SDValue, 8> MemOpChains; 5502 5503 bool seenFloatArg = false; 5504 // Walk the register/memloc assignments, inserting copies/loads. 5505 // i - Tracks the index into the list of registers allocated for the call 5506 // RealArgIdx - Tracks the index into the list of actual function arguments 5507 // j - Tracks the index into the list of byval arguments 5508 for (unsigned i = 0, RealArgIdx = 0, j = 0, e = ArgLocs.size(); 5509 i != e; 5510 ++i, ++RealArgIdx) { 5511 CCValAssign &VA = ArgLocs[i]; 5512 SDValue Arg = OutVals[RealArgIdx]; 5513 ISD::ArgFlagsTy Flags = Outs[RealArgIdx].Flags; 5514 5515 if (Flags.isByVal()) { 5516 // Argument is an aggregate which is passed by value, thus we need to 5517 // create a copy of it in the local variable space of the current stack 5518 // frame (which is the stack frame of the caller) and pass the address of 5519 // this copy to the callee. 5520 assert((j < ByValArgLocs.size()) && "Index out of bounds!"); 5521 CCValAssign &ByValVA = ByValArgLocs[j++]; 5522 assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!"); 5523 5524 // Memory reserved in the local variable space of the callers stack frame. 5525 unsigned LocMemOffset = ByValVA.getLocMemOffset(); 5526 5527 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 5528 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()), 5529 StackPtr, PtrOff); 5530 5531 // Create a copy of the argument in the local area of the current 5532 // stack frame. 5533 SDValue MemcpyCall = 5534 CreateCopyOfByValArgument(Arg, PtrOff, 5535 CallSeqStart.getNode()->getOperand(0), 5536 Flags, DAG, dl); 5537 5538 // This must go outside the CALLSEQ_START..END. 5539 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, NumBytes, 0, 5540 SDLoc(MemcpyCall)); 5541 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(), 5542 NewCallSeqStart.getNode()); 5543 Chain = CallSeqStart = NewCallSeqStart; 5544 5545 // Pass the address of the aggregate copy on the stack either in a 5546 // physical register or in the parameter list area of the current stack 5547 // frame to the callee. 5548 Arg = PtrOff; 5549 } 5550 5551 // When useCRBits() is true, there can be i1 arguments. 5552 // It is because getRegisterType(MVT::i1) => MVT::i1, 5553 // and for other integer types getRegisterType() => MVT::i32. 5554 // Extend i1 and ensure callee will get i32. 5555 if (Arg.getValueType() == MVT::i1) 5556 Arg = DAG.getNode(Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, 5557 dl, MVT::i32, Arg); 5558 5559 if (VA.isRegLoc()) { 5560 seenFloatArg |= VA.getLocVT().isFloatingPoint(); 5561 // Put argument in a physical register. 5562 if (Subtarget.hasSPE() && Arg.getValueType() == MVT::f64) { 5563 bool IsLE = Subtarget.isLittleEndian(); 5564 SDValue SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg, 5565 DAG.getIntPtrConstant(IsLE ? 0 : 1, dl)); 5566 RegsToPass.push_back(std::make_pair(VA.getLocReg(), SVal.getValue(0))); 5567 SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg, 5568 DAG.getIntPtrConstant(IsLE ? 1 : 0, dl)); 5569 RegsToPass.push_back(std::make_pair(ArgLocs[++i].getLocReg(), 5570 SVal.getValue(0))); 5571 } else 5572 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 5573 } else { 5574 // Put argument in the parameter list area of the current stack frame. 5575 assert(VA.isMemLoc()); 5576 unsigned LocMemOffset = VA.getLocMemOffset(); 5577 5578 if (!isTailCall) { 5579 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 5580 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()), 5581 StackPtr, PtrOff); 5582 5583 MemOpChains.push_back( 5584 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo())); 5585 } else { 5586 // Calculate and remember argument location. 5587 CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset, 5588 TailCallArguments); 5589 } 5590 } 5591 } 5592 5593 if (!MemOpChains.empty()) 5594 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 5595 5596 // Build a sequence of copy-to-reg nodes chained together with token chain 5597 // and flag operands which copy the outgoing args into the appropriate regs. 5598 SDValue InFlag; 5599 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 5600 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 5601 RegsToPass[i].second, InFlag); 5602 InFlag = Chain.getValue(1); 5603 } 5604 5605 // Set CR bit 6 to true if this is a vararg call with floating args passed in 5606 // registers. 5607 if (isVarArg) { 5608 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue); 5609 SDValue Ops[] = { Chain, InFlag }; 5610 5611 Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET, 5612 dl, VTs, makeArrayRef(Ops, InFlag.getNode() ? 2 : 1)); 5613 5614 InFlag = Chain.getValue(1); 5615 } 5616 5617 if (isTailCall) 5618 PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp, 5619 TailCallArguments); 5620 5621 return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint, 5622 /* unused except on PPC64 ELFv1 */ false, DAG, 5623 RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff, 5624 NumBytes, Ins, InVals, CS); 5625 } 5626 5627 // Copy an argument into memory, being careful to do this outside the 5628 // call sequence for the call to which the argument belongs. 5629 SDValue PPCTargetLowering::createMemcpyOutsideCallSeq( 5630 SDValue Arg, SDValue PtrOff, SDValue CallSeqStart, ISD::ArgFlagsTy Flags, 5631 SelectionDAG &DAG, const SDLoc &dl) const { 5632 SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff, 5633 CallSeqStart.getNode()->getOperand(0), 5634 Flags, DAG, dl); 5635 // The MEMCPY must go outside the CALLSEQ_START..END. 5636 int64_t FrameSize = CallSeqStart.getConstantOperandVal(1); 5637 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, FrameSize, 0, 5638 SDLoc(MemcpyCall)); 5639 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(), 5640 NewCallSeqStart.getNode()); 5641 return NewCallSeqStart; 5642 } 5643 5644 SDValue PPCTargetLowering::LowerCall_64SVR4( 5645 SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg, 5646 bool isTailCall, bool isPatchPoint, 5647 const SmallVectorImpl<ISD::OutputArg> &Outs, 5648 const SmallVectorImpl<SDValue> &OutVals, 5649 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 5650 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 5651 ImmutableCallSite CS) const { 5652 bool isELFv2ABI = Subtarget.isELFv2ABI(); 5653 bool isLittleEndian = Subtarget.isLittleEndian(); 5654 unsigned NumOps = Outs.size(); 5655 bool hasNest = false; 5656 bool IsSibCall = false; 5657 5658 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 5659 unsigned PtrByteSize = 8; 5660 5661 MachineFunction &MF = DAG.getMachineFunction(); 5662 5663 if (isTailCall && !getTargetMachine().Options.GuaranteedTailCallOpt) 5664 IsSibCall = true; 5665 5666 // Mark this function as potentially containing a function that contains a 5667 // tail call. As a consequence the frame pointer will be used for dynamicalloc 5668 // and restoring the callers stack pointer in this functions epilog. This is 5669 // done because by tail calling the called function might overwrite the value 5670 // in this function's (MF) stack pointer stack slot 0(SP). 5671 if (getTargetMachine().Options.GuaranteedTailCallOpt && 5672 CallConv == CallingConv::Fast) 5673 MF.getInfo<PPCFunctionInfo>()->setHasFastCall(); 5674 5675 assert(!(CallConv == CallingConv::Fast && isVarArg) && 5676 "fastcc not supported on varargs functions"); 5677 5678 // Count how many bytes are to be pushed on the stack, including the linkage 5679 // area, and parameter passing area. On ELFv1, the linkage area is 48 bytes 5680 // reserved space for [SP][CR][LR][2 x unused][TOC]; on ELFv2, the linkage 5681 // area is 32 bytes reserved space for [SP][CR][LR][TOC]. 5682 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 5683 unsigned NumBytes = LinkageSize; 5684 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 5685 unsigned &QFPR_idx = FPR_idx; 5686 5687 static const MCPhysReg GPR[] = { 5688 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 5689 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 5690 }; 5691 static const MCPhysReg VR[] = { 5692 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 5693 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 5694 }; 5695 5696 const unsigned NumGPRs = array_lengthof(GPR); 5697 const unsigned NumFPRs = useSoftFloat() ? 0 : 13; 5698 const unsigned NumVRs = array_lengthof(VR); 5699 const unsigned NumQFPRs = NumFPRs; 5700 5701 // On ELFv2, we can avoid allocating the parameter area if all the arguments 5702 // can be passed to the callee in registers. 5703 // For the fast calling convention, there is another check below. 5704 // Note: We should keep consistent with LowerFormalArguments_64SVR4() 5705 bool HasParameterArea = !isELFv2ABI || isVarArg || CallConv == CallingConv::Fast; 5706 if (!HasParameterArea) { 5707 unsigned ParamAreaSize = NumGPRs * PtrByteSize; 5708 unsigned AvailableFPRs = NumFPRs; 5709 unsigned AvailableVRs = NumVRs; 5710 unsigned NumBytesTmp = NumBytes; 5711 for (unsigned i = 0; i != NumOps; ++i) { 5712 if (Outs[i].Flags.isNest()) continue; 5713 if (CalculateStackSlotUsed(Outs[i].VT, Outs[i].ArgVT, Outs[i].Flags, 5714 PtrByteSize, LinkageSize, ParamAreaSize, 5715 NumBytesTmp, AvailableFPRs, AvailableVRs, 5716 Subtarget.hasQPX())) 5717 HasParameterArea = true; 5718 } 5719 } 5720 5721 // When using the fast calling convention, we don't provide backing for 5722 // arguments that will be in registers. 5723 unsigned NumGPRsUsed = 0, NumFPRsUsed = 0, NumVRsUsed = 0; 5724 5725 // Avoid allocating parameter area for fastcc functions if all the arguments 5726 // can be passed in the registers. 5727 if (CallConv == CallingConv::Fast) 5728 HasParameterArea = false; 5729 5730 // Add up all the space actually used. 5731 for (unsigned i = 0; i != NumOps; ++i) { 5732 ISD::ArgFlagsTy Flags = Outs[i].Flags; 5733 EVT ArgVT = Outs[i].VT; 5734 EVT OrigVT = Outs[i].ArgVT; 5735 5736 if (Flags.isNest()) 5737 continue; 5738 5739 if (CallConv == CallingConv::Fast) { 5740 if (Flags.isByVal()) { 5741 NumGPRsUsed += (Flags.getByValSize()+7)/8; 5742 if (NumGPRsUsed > NumGPRs) 5743 HasParameterArea = true; 5744 } else { 5745 switch (ArgVT.getSimpleVT().SimpleTy) { 5746 default: llvm_unreachable("Unexpected ValueType for argument!"); 5747 case MVT::i1: 5748 case MVT::i32: 5749 case MVT::i64: 5750 if (++NumGPRsUsed <= NumGPRs) 5751 continue; 5752 break; 5753 case MVT::v4i32: 5754 case MVT::v8i16: 5755 case MVT::v16i8: 5756 case MVT::v2f64: 5757 case MVT::v2i64: 5758 case MVT::v1i128: 5759 case MVT::f128: 5760 if (++NumVRsUsed <= NumVRs) 5761 continue; 5762 break; 5763 case MVT::v4f32: 5764 // When using QPX, this is handled like a FP register, otherwise, it 5765 // is an Altivec register. 5766 if (Subtarget.hasQPX()) { 5767 if (++NumFPRsUsed <= NumFPRs) 5768 continue; 5769 } else { 5770 if (++NumVRsUsed <= NumVRs) 5771 continue; 5772 } 5773 break; 5774 case MVT::f32: 5775 case MVT::f64: 5776 case MVT::v4f64: // QPX 5777 case MVT::v4i1: // QPX 5778 if (++NumFPRsUsed <= NumFPRs) 5779 continue; 5780 break; 5781 } 5782 HasParameterArea = true; 5783 } 5784 } 5785 5786 /* Respect alignment of argument on the stack. */ 5787 unsigned Align = 5788 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize); 5789 NumBytes = ((NumBytes + Align - 1) / Align) * Align; 5790 5791 NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize); 5792 if (Flags.isInConsecutiveRegsLast()) 5793 NumBytes = ((NumBytes + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 5794 } 5795 5796 unsigned NumBytesActuallyUsed = NumBytes; 5797 5798 // In the old ELFv1 ABI, 5799 // the prolog code of the callee may store up to 8 GPR argument registers to 5800 // the stack, allowing va_start to index over them in memory if its varargs. 5801 // Because we cannot tell if this is needed on the caller side, we have to 5802 // conservatively assume that it is needed. As such, make sure we have at 5803 // least enough stack space for the caller to store the 8 GPRs. 5804 // In the ELFv2 ABI, we allocate the parameter area iff a callee 5805 // really requires memory operands, e.g. a vararg function. 5806 if (HasParameterArea) 5807 NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize); 5808 else 5809 NumBytes = LinkageSize; 5810 5811 // Tail call needs the stack to be aligned. 5812 if (getTargetMachine().Options.GuaranteedTailCallOpt && 5813 CallConv == CallingConv::Fast) 5814 NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes); 5815 5816 int SPDiff = 0; 5817 5818 // Calculate by how many bytes the stack has to be adjusted in case of tail 5819 // call optimization. 5820 if (!IsSibCall) 5821 SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes); 5822 5823 // To protect arguments on the stack from being clobbered in a tail call, 5824 // force all the loads to happen before doing any other lowering. 5825 if (isTailCall) 5826 Chain = DAG.getStackArgumentTokenFactor(Chain); 5827 5828 // Adjust the stack pointer for the new arguments... 5829 // These operations are automatically eliminated by the prolog/epilog pass 5830 if (!IsSibCall) 5831 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 5832 SDValue CallSeqStart = Chain; 5833 5834 // Load the return address and frame pointer so it can be move somewhere else 5835 // later. 5836 SDValue LROp, FPOp; 5837 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl); 5838 5839 // Set up a copy of the stack pointer for use loading and storing any 5840 // arguments that may not fit in the registers available for argument 5841 // passing. 5842 SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64); 5843 5844 // Figure out which arguments are going to go in registers, and which in 5845 // memory. Also, if this is a vararg function, floating point operations 5846 // must be stored to our stack, and loaded into integer regs as well, if 5847 // any integer regs are available for argument passing. 5848 unsigned ArgOffset = LinkageSize; 5849 5850 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 5851 SmallVector<TailCallArgumentInfo, 8> TailCallArguments; 5852 5853 SmallVector<SDValue, 8> MemOpChains; 5854 for (unsigned i = 0; i != NumOps; ++i) { 5855 SDValue Arg = OutVals[i]; 5856 ISD::ArgFlagsTy Flags = Outs[i].Flags; 5857 EVT ArgVT = Outs[i].VT; 5858 EVT OrigVT = Outs[i].ArgVT; 5859 5860 // PtrOff will be used to store the current argument to the stack if a 5861 // register cannot be found for it. 5862 SDValue PtrOff; 5863 5864 // We re-align the argument offset for each argument, except when using the 5865 // fast calling convention, when we need to make sure we do that only when 5866 // we'll actually use a stack slot. 5867 auto ComputePtrOff = [&]() { 5868 /* Respect alignment of argument on the stack. */ 5869 unsigned Align = 5870 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize); 5871 ArgOffset = ((ArgOffset + Align - 1) / Align) * Align; 5872 5873 PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType()); 5874 5875 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 5876 }; 5877 5878 if (CallConv != CallingConv::Fast) { 5879 ComputePtrOff(); 5880 5881 /* Compute GPR index associated with argument offset. */ 5882 GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize; 5883 GPR_idx = std::min(GPR_idx, NumGPRs); 5884 } 5885 5886 // Promote integers to 64-bit values. 5887 if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) { 5888 // FIXME: Should this use ANY_EXTEND if neither sext nor zext? 5889 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 5890 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg); 5891 } 5892 5893 // FIXME memcpy is used way more than necessary. Correctness first. 5894 // Note: "by value" is code for passing a structure by value, not 5895 // basic types. 5896 if (Flags.isByVal()) { 5897 // Note: Size includes alignment padding, so 5898 // struct x { short a; char b; } 5899 // will have Size = 4. With #pragma pack(1), it will have Size = 3. 5900 // These are the proper values we need for right-justifying the 5901 // aggregate in a parameter register. 5902 unsigned Size = Flags.getByValSize(); 5903 5904 // An empty aggregate parameter takes up no storage and no 5905 // registers. 5906 if (Size == 0) 5907 continue; 5908 5909 if (CallConv == CallingConv::Fast) 5910 ComputePtrOff(); 5911 5912 // All aggregates smaller than 8 bytes must be passed right-justified. 5913 if (Size==1 || Size==2 || Size==4) { 5914 EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32); 5915 if (GPR_idx != NumGPRs) { 5916 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg, 5917 MachinePointerInfo(), VT); 5918 MemOpChains.push_back(Load.getValue(1)); 5919 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 5920 5921 ArgOffset += PtrByteSize; 5922 continue; 5923 } 5924 } 5925 5926 if (GPR_idx == NumGPRs && Size < 8) { 5927 SDValue AddPtr = PtrOff; 5928 if (!isLittleEndian) { 5929 SDValue Const = DAG.getConstant(PtrByteSize - Size, dl, 5930 PtrOff.getValueType()); 5931 AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const); 5932 } 5933 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr, 5934 CallSeqStart, 5935 Flags, DAG, dl); 5936 ArgOffset += PtrByteSize; 5937 continue; 5938 } 5939 // Copy entire object into memory. There are cases where gcc-generated 5940 // code assumes it is there, even if it could be put entirely into 5941 // registers. (This is not what the doc says.) 5942 5943 // FIXME: The above statement is likely due to a misunderstanding of the 5944 // documents. All arguments must be copied into the parameter area BY 5945 // THE CALLEE in the event that the callee takes the address of any 5946 // formal argument. That has not yet been implemented. However, it is 5947 // reasonable to use the stack area as a staging area for the register 5948 // load. 5949 5950 // Skip this for small aggregates, as we will use the same slot for a 5951 // right-justified copy, below. 5952 if (Size >= 8) 5953 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff, 5954 CallSeqStart, 5955 Flags, DAG, dl); 5956 5957 // When a register is available, pass a small aggregate right-justified. 5958 if (Size < 8 && GPR_idx != NumGPRs) { 5959 // The easiest way to get this right-justified in a register 5960 // is to copy the structure into the rightmost portion of a 5961 // local variable slot, then load the whole slot into the 5962 // register. 5963 // FIXME: The memcpy seems to produce pretty awful code for 5964 // small aggregates, particularly for packed ones. 5965 // FIXME: It would be preferable to use the slot in the 5966 // parameter save area instead of a new local variable. 5967 SDValue AddPtr = PtrOff; 5968 if (!isLittleEndian) { 5969 SDValue Const = DAG.getConstant(8 - Size, dl, PtrOff.getValueType()); 5970 AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const); 5971 } 5972 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr, 5973 CallSeqStart, 5974 Flags, DAG, dl); 5975 5976 // Load the slot into the register. 5977 SDValue Load = 5978 DAG.getLoad(PtrVT, dl, Chain, PtrOff, MachinePointerInfo()); 5979 MemOpChains.push_back(Load.getValue(1)); 5980 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 5981 5982 // Done with this argument. 5983 ArgOffset += PtrByteSize; 5984 continue; 5985 } 5986 5987 // For aggregates larger than PtrByteSize, copy the pieces of the 5988 // object that fit into registers from the parameter save area. 5989 for (unsigned j=0; j<Size; j+=PtrByteSize) { 5990 SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType()); 5991 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const); 5992 if (GPR_idx != NumGPRs) { 5993 SDValue Load = 5994 DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo()); 5995 MemOpChains.push_back(Load.getValue(1)); 5996 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 5997 ArgOffset += PtrByteSize; 5998 } else { 5999 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize; 6000 break; 6001 } 6002 } 6003 continue; 6004 } 6005 6006 switch (Arg.getSimpleValueType().SimpleTy) { 6007 default: llvm_unreachable("Unexpected ValueType for argument!"); 6008 case MVT::i1: 6009 case MVT::i32: 6010 case MVT::i64: 6011 if (Flags.isNest()) { 6012 // The 'nest' parameter, if any, is passed in R11. 6013 RegsToPass.push_back(std::make_pair(PPC::X11, Arg)); 6014 hasNest = true; 6015 break; 6016 } 6017 6018 // These can be scalar arguments or elements of an integer array type 6019 // passed directly. Clang may use those instead of "byval" aggregate 6020 // types to avoid forcing arguments to memory unnecessarily. 6021 if (GPR_idx != NumGPRs) { 6022 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg)); 6023 } else { 6024 if (CallConv == CallingConv::Fast) 6025 ComputePtrOff(); 6026 6027 assert(HasParameterArea && 6028 "Parameter area must exist to pass an argument in memory."); 6029 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6030 true, isTailCall, false, MemOpChains, 6031 TailCallArguments, dl); 6032 if (CallConv == CallingConv::Fast) 6033 ArgOffset += PtrByteSize; 6034 } 6035 if (CallConv != CallingConv::Fast) 6036 ArgOffset += PtrByteSize; 6037 break; 6038 case MVT::f32: 6039 case MVT::f64: { 6040 // These can be scalar arguments or elements of a float array type 6041 // passed directly. The latter are used to implement ELFv2 homogenous 6042 // float aggregates. 6043 6044 // Named arguments go into FPRs first, and once they overflow, the 6045 // remaining arguments go into GPRs and then the parameter save area. 6046 // Unnamed arguments for vararg functions always go to GPRs and 6047 // then the parameter save area. For now, put all arguments to vararg 6048 // routines always in both locations (FPR *and* GPR or stack slot). 6049 bool NeedGPROrStack = isVarArg || FPR_idx == NumFPRs; 6050 bool NeededLoad = false; 6051 6052 // First load the argument into the next available FPR. 6053 if (FPR_idx != NumFPRs) 6054 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg)); 6055 6056 // Next, load the argument into GPR or stack slot if needed. 6057 if (!NeedGPROrStack) 6058 ; 6059 else if (GPR_idx != NumGPRs && CallConv != CallingConv::Fast) { 6060 // FIXME: We may want to re-enable this for CallingConv::Fast on the P8 6061 // once we support fp <-> gpr moves. 6062 6063 // In the non-vararg case, this can only ever happen in the 6064 // presence of f32 array types, since otherwise we never run 6065 // out of FPRs before running out of GPRs. 6066 SDValue ArgVal; 6067 6068 // Double values are always passed in a single GPR. 6069 if (Arg.getValueType() != MVT::f32) { 6070 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg); 6071 6072 // Non-array float values are extended and passed in a GPR. 6073 } else if (!Flags.isInConsecutiveRegs()) { 6074 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg); 6075 ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal); 6076 6077 // If we have an array of floats, we collect every odd element 6078 // together with its predecessor into one GPR. 6079 } else if (ArgOffset % PtrByteSize != 0) { 6080 SDValue Lo, Hi; 6081 Lo = DAG.getNode(ISD::BITCAST, dl, MVT::i32, OutVals[i - 1]); 6082 Hi = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg); 6083 if (!isLittleEndian) 6084 std::swap(Lo, Hi); 6085 ArgVal = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi); 6086 6087 // The final element, if even, goes into the first half of a GPR. 6088 } else if (Flags.isInConsecutiveRegsLast()) { 6089 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg); 6090 ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal); 6091 if (!isLittleEndian) 6092 ArgVal = DAG.getNode(ISD::SHL, dl, MVT::i64, ArgVal, 6093 DAG.getConstant(32, dl, MVT::i32)); 6094 6095 // Non-final even elements are skipped; they will be handled 6096 // together the with subsequent argument on the next go-around. 6097 } else 6098 ArgVal = SDValue(); 6099 6100 if (ArgVal.getNode()) 6101 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], ArgVal)); 6102 } else { 6103 if (CallConv == CallingConv::Fast) 6104 ComputePtrOff(); 6105 6106 // Single-precision floating-point values are mapped to the 6107 // second (rightmost) word of the stack doubleword. 6108 if (Arg.getValueType() == MVT::f32 && 6109 !isLittleEndian && !Flags.isInConsecutiveRegs()) { 6110 SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType()); 6111 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour); 6112 } 6113 6114 assert(HasParameterArea && 6115 "Parameter area must exist to pass an argument in memory."); 6116 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6117 true, isTailCall, false, MemOpChains, 6118 TailCallArguments, dl); 6119 6120 NeededLoad = true; 6121 } 6122 // When passing an array of floats, the array occupies consecutive 6123 // space in the argument area; only round up to the next doubleword 6124 // at the end of the array. Otherwise, each float takes 8 bytes. 6125 if (CallConv != CallingConv::Fast || NeededLoad) { 6126 ArgOffset += (Arg.getValueType() == MVT::f32 && 6127 Flags.isInConsecutiveRegs()) ? 4 : 8; 6128 if (Flags.isInConsecutiveRegsLast()) 6129 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 6130 } 6131 break; 6132 } 6133 case MVT::v4f32: 6134 case MVT::v4i32: 6135 case MVT::v8i16: 6136 case MVT::v16i8: 6137 case MVT::v2f64: 6138 case MVT::v2i64: 6139 case MVT::v1i128: 6140 case MVT::f128: 6141 if (!Subtarget.hasQPX()) { 6142 // These can be scalar arguments or elements of a vector array type 6143 // passed directly. The latter are used to implement ELFv2 homogenous 6144 // vector aggregates. 6145 6146 // For a varargs call, named arguments go into VRs or on the stack as 6147 // usual; unnamed arguments always go to the stack or the corresponding 6148 // GPRs when within range. For now, we always put the value in both 6149 // locations (or even all three). 6150 if (isVarArg) { 6151 assert(HasParameterArea && 6152 "Parameter area must exist if we have a varargs call."); 6153 // We could elide this store in the case where the object fits 6154 // entirely in R registers. Maybe later. 6155 SDValue Store = 6156 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 6157 MemOpChains.push_back(Store); 6158 if (VR_idx != NumVRs) { 6159 SDValue Load = 6160 DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo()); 6161 MemOpChains.push_back(Load.getValue(1)); 6162 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load)); 6163 } 6164 ArgOffset += 16; 6165 for (unsigned i=0; i<16; i+=PtrByteSize) { 6166 if (GPR_idx == NumGPRs) 6167 break; 6168 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, 6169 DAG.getConstant(i, dl, PtrVT)); 6170 SDValue Load = 6171 DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo()); 6172 MemOpChains.push_back(Load.getValue(1)); 6173 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6174 } 6175 break; 6176 } 6177 6178 // Non-varargs Altivec params go into VRs or on the stack. 6179 if (VR_idx != NumVRs) { 6180 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg)); 6181 } else { 6182 if (CallConv == CallingConv::Fast) 6183 ComputePtrOff(); 6184 6185 assert(HasParameterArea && 6186 "Parameter area must exist to pass an argument in memory."); 6187 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6188 true, isTailCall, true, MemOpChains, 6189 TailCallArguments, dl); 6190 if (CallConv == CallingConv::Fast) 6191 ArgOffset += 16; 6192 } 6193 6194 if (CallConv != CallingConv::Fast) 6195 ArgOffset += 16; 6196 break; 6197 } // not QPX 6198 6199 assert(Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32 && 6200 "Invalid QPX parameter type"); 6201 6202 LLVM_FALLTHROUGH; 6203 case MVT::v4f64: 6204 case MVT::v4i1: { 6205 bool IsF32 = Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32; 6206 if (isVarArg) { 6207 assert(HasParameterArea && 6208 "Parameter area must exist if we have a varargs call."); 6209 // We could elide this store in the case where the object fits 6210 // entirely in R registers. Maybe later. 6211 SDValue Store = 6212 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 6213 MemOpChains.push_back(Store); 6214 if (QFPR_idx != NumQFPRs) { 6215 SDValue Load = DAG.getLoad(IsF32 ? MVT::v4f32 : MVT::v4f64, dl, Store, 6216 PtrOff, MachinePointerInfo()); 6217 MemOpChains.push_back(Load.getValue(1)); 6218 RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Load)); 6219 } 6220 ArgOffset += (IsF32 ? 16 : 32); 6221 for (unsigned i = 0; i < (IsF32 ? 16U : 32U); i += PtrByteSize) { 6222 if (GPR_idx == NumGPRs) 6223 break; 6224 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, 6225 DAG.getConstant(i, dl, PtrVT)); 6226 SDValue Load = 6227 DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo()); 6228 MemOpChains.push_back(Load.getValue(1)); 6229 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6230 } 6231 break; 6232 } 6233 6234 // Non-varargs QPX params go into registers or on the stack. 6235 if (QFPR_idx != NumQFPRs) { 6236 RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Arg)); 6237 } else { 6238 if (CallConv == CallingConv::Fast) 6239 ComputePtrOff(); 6240 6241 assert(HasParameterArea && 6242 "Parameter area must exist to pass an argument in memory."); 6243 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6244 true, isTailCall, true, MemOpChains, 6245 TailCallArguments, dl); 6246 if (CallConv == CallingConv::Fast) 6247 ArgOffset += (IsF32 ? 16 : 32); 6248 } 6249 6250 if (CallConv != CallingConv::Fast) 6251 ArgOffset += (IsF32 ? 16 : 32); 6252 break; 6253 } 6254 } 6255 } 6256 6257 assert((!HasParameterArea || NumBytesActuallyUsed == ArgOffset) && 6258 "mismatch in size of parameter area"); 6259 (void)NumBytesActuallyUsed; 6260 6261 if (!MemOpChains.empty()) 6262 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 6263 6264 // Check if this is an indirect call (MTCTR/BCTRL). 6265 // See PrepareCall() for more information about calls through function 6266 // pointers in the 64-bit SVR4 ABI. 6267 if (!isTailCall && !isPatchPoint && 6268 !isFunctionGlobalAddress(Callee) && 6269 !isa<ExternalSymbolSDNode>(Callee)) { 6270 // Load r2 into a virtual register and store it to the TOC save area. 6271 setUsesTOCBasePtr(DAG); 6272 SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64); 6273 // TOC save area offset. 6274 unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset(); 6275 SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl); 6276 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 6277 Chain = DAG.getStore( 6278 Val.getValue(1), dl, Val, AddPtr, 6279 MachinePointerInfo::getStack(DAG.getMachineFunction(), TOCSaveOffset)); 6280 // In the ELFv2 ABI, R12 must contain the address of an indirect callee. 6281 // This does not mean the MTCTR instruction must use R12; it's easier 6282 // to model this as an extra parameter, so do that. 6283 if (isELFv2ABI && !isPatchPoint) 6284 RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee)); 6285 } 6286 6287 // Build a sequence of copy-to-reg nodes chained together with token chain 6288 // and flag operands which copy the outgoing args into the appropriate regs. 6289 SDValue InFlag; 6290 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 6291 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 6292 RegsToPass[i].second, InFlag); 6293 InFlag = Chain.getValue(1); 6294 } 6295 6296 if (isTailCall && !IsSibCall) 6297 PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp, 6298 TailCallArguments); 6299 6300 return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint, hasNest, 6301 DAG, RegsToPass, InFlag, Chain, CallSeqStart, Callee, 6302 SPDiff, NumBytes, Ins, InVals, CS); 6303 } 6304 6305 SDValue PPCTargetLowering::LowerCall_Darwin( 6306 SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg, 6307 bool isTailCall, bool isPatchPoint, 6308 const SmallVectorImpl<ISD::OutputArg> &Outs, 6309 const SmallVectorImpl<SDValue> &OutVals, 6310 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 6311 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 6312 ImmutableCallSite CS) const { 6313 unsigned NumOps = Outs.size(); 6314 6315 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 6316 bool isPPC64 = PtrVT == MVT::i64; 6317 unsigned PtrByteSize = isPPC64 ? 8 : 4; 6318 6319 MachineFunction &MF = DAG.getMachineFunction(); 6320 6321 // Mark this function as potentially containing a function that contains a 6322 // tail call. As a consequence the frame pointer will be used for dynamicalloc 6323 // and restoring the callers stack pointer in this functions epilog. This is 6324 // done because by tail calling the called function might overwrite the value 6325 // in this function's (MF) stack pointer stack slot 0(SP). 6326 if (getTargetMachine().Options.GuaranteedTailCallOpt && 6327 CallConv == CallingConv::Fast) 6328 MF.getInfo<PPCFunctionInfo>()->setHasFastCall(); 6329 6330 // Count how many bytes are to be pushed on the stack, including the linkage 6331 // area, and parameter passing area. We start with 24/48 bytes, which is 6332 // prereserved space for [SP][CR][LR][3 x unused]. 6333 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 6334 unsigned NumBytes = LinkageSize; 6335 6336 // Add up all the space actually used. 6337 // In 32-bit non-varargs calls, Altivec parameters all go at the end; usually 6338 // they all go in registers, but we must reserve stack space for them for 6339 // possible use by the caller. In varargs or 64-bit calls, parameters are 6340 // assigned stack space in order, with padding so Altivec parameters are 6341 // 16-byte aligned. 6342 unsigned nAltivecParamsAtEnd = 0; 6343 for (unsigned i = 0; i != NumOps; ++i) { 6344 ISD::ArgFlagsTy Flags = Outs[i].Flags; 6345 EVT ArgVT = Outs[i].VT; 6346 // Varargs Altivec parameters are padded to a 16 byte boundary. 6347 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 || 6348 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 || 6349 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64) { 6350 if (!isVarArg && !isPPC64) { 6351 // Non-varargs Altivec parameters go after all the non-Altivec 6352 // parameters; handle those later so we know how much padding we need. 6353 nAltivecParamsAtEnd++; 6354 continue; 6355 } 6356 // Varargs and 64-bit Altivec parameters are padded to 16 byte boundary. 6357 NumBytes = ((NumBytes+15)/16)*16; 6358 } 6359 NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize); 6360 } 6361 6362 // Allow for Altivec parameters at the end, if needed. 6363 if (nAltivecParamsAtEnd) { 6364 NumBytes = ((NumBytes+15)/16)*16; 6365 NumBytes += 16*nAltivecParamsAtEnd; 6366 } 6367 6368 // The prolog code of the callee may store up to 8 GPR argument registers to 6369 // the stack, allowing va_start to index over them in memory if its varargs. 6370 // Because we cannot tell if this is needed on the caller side, we have to 6371 // conservatively assume that it is needed. As such, make sure we have at 6372 // least enough stack space for the caller to store the 8 GPRs. 6373 NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize); 6374 6375 // Tail call needs the stack to be aligned. 6376 if (getTargetMachine().Options.GuaranteedTailCallOpt && 6377 CallConv == CallingConv::Fast) 6378 NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes); 6379 6380 // Calculate by how many bytes the stack has to be adjusted in case of tail 6381 // call optimization. 6382 int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes); 6383 6384 // To protect arguments on the stack from being clobbered in a tail call, 6385 // force all the loads to happen before doing any other lowering. 6386 if (isTailCall) 6387 Chain = DAG.getStackArgumentTokenFactor(Chain); 6388 6389 // Adjust the stack pointer for the new arguments... 6390 // These operations are automatically eliminated by the prolog/epilog pass 6391 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 6392 SDValue CallSeqStart = Chain; 6393 6394 // Load the return address and frame pointer so it can be move somewhere else 6395 // later. 6396 SDValue LROp, FPOp; 6397 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl); 6398 6399 // Set up a copy of the stack pointer for use loading and storing any 6400 // arguments that may not fit in the registers available for argument 6401 // passing. 6402 SDValue StackPtr; 6403 if (isPPC64) 6404 StackPtr = DAG.getRegister(PPC::X1, MVT::i64); 6405 else 6406 StackPtr = DAG.getRegister(PPC::R1, MVT::i32); 6407 6408 // Figure out which arguments are going to go in registers, and which in 6409 // memory. Also, if this is a vararg function, floating point operations 6410 // must be stored to our stack, and loaded into integer regs as well, if 6411 // any integer regs are available for argument passing. 6412 unsigned ArgOffset = LinkageSize; 6413 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 6414 6415 static const MCPhysReg GPR_32[] = { // 32-bit registers. 6416 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 6417 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 6418 }; 6419 static const MCPhysReg GPR_64[] = { // 64-bit registers. 6420 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 6421 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 6422 }; 6423 static const MCPhysReg VR[] = { 6424 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 6425 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 6426 }; 6427 const unsigned NumGPRs = array_lengthof(GPR_32); 6428 const unsigned NumFPRs = 13; 6429 const unsigned NumVRs = array_lengthof(VR); 6430 6431 const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32; 6432 6433 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 6434 SmallVector<TailCallArgumentInfo, 8> TailCallArguments; 6435 6436 SmallVector<SDValue, 8> MemOpChains; 6437 for (unsigned i = 0; i != NumOps; ++i) { 6438 SDValue Arg = OutVals[i]; 6439 ISD::ArgFlagsTy Flags = Outs[i].Flags; 6440 6441 // PtrOff will be used to store the current argument to the stack if a 6442 // register cannot be found for it. 6443 SDValue PtrOff; 6444 6445 PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType()); 6446 6447 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 6448 6449 // On PPC64, promote integers to 64-bit values. 6450 if (isPPC64 && Arg.getValueType() == MVT::i32) { 6451 // FIXME: Should this use ANY_EXTEND if neither sext nor zext? 6452 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 6453 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg); 6454 } 6455 6456 // FIXME memcpy is used way more than necessary. Correctness first. 6457 // Note: "by value" is code for passing a structure by value, not 6458 // basic types. 6459 if (Flags.isByVal()) { 6460 unsigned Size = Flags.getByValSize(); 6461 // Very small objects are passed right-justified. Everything else is 6462 // passed left-justified. 6463 if (Size==1 || Size==2) { 6464 EVT VT = (Size==1) ? MVT::i8 : MVT::i16; 6465 if (GPR_idx != NumGPRs) { 6466 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg, 6467 MachinePointerInfo(), VT); 6468 MemOpChains.push_back(Load.getValue(1)); 6469 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6470 6471 ArgOffset += PtrByteSize; 6472 } else { 6473 SDValue Const = DAG.getConstant(PtrByteSize - Size, dl, 6474 PtrOff.getValueType()); 6475 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const); 6476 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr, 6477 CallSeqStart, 6478 Flags, DAG, dl); 6479 ArgOffset += PtrByteSize; 6480 } 6481 continue; 6482 } 6483 // Copy entire object into memory. There are cases where gcc-generated 6484 // code assumes it is there, even if it could be put entirely into 6485 // registers. (This is not what the doc says.) 6486 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff, 6487 CallSeqStart, 6488 Flags, DAG, dl); 6489 6490 // For small aggregates (Darwin only) and aggregates >= PtrByteSize, 6491 // copy the pieces of the object that fit into registers from the 6492 // parameter save area. 6493 for (unsigned j=0; j<Size; j+=PtrByteSize) { 6494 SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType()); 6495 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const); 6496 if (GPR_idx != NumGPRs) { 6497 SDValue Load = 6498 DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo()); 6499 MemOpChains.push_back(Load.getValue(1)); 6500 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6501 ArgOffset += PtrByteSize; 6502 } else { 6503 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize; 6504 break; 6505 } 6506 } 6507 continue; 6508 } 6509 6510 switch (Arg.getSimpleValueType().SimpleTy) { 6511 default: llvm_unreachable("Unexpected ValueType for argument!"); 6512 case MVT::i1: 6513 case MVT::i32: 6514 case MVT::i64: 6515 if (GPR_idx != NumGPRs) { 6516 if (Arg.getValueType() == MVT::i1) 6517 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, PtrVT, Arg); 6518 6519 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg)); 6520 } else { 6521 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6522 isPPC64, isTailCall, false, MemOpChains, 6523 TailCallArguments, dl); 6524 } 6525 ArgOffset += PtrByteSize; 6526 break; 6527 case MVT::f32: 6528 case MVT::f64: 6529 if (FPR_idx != NumFPRs) { 6530 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg)); 6531 6532 if (isVarArg) { 6533 SDValue Store = 6534 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 6535 MemOpChains.push_back(Store); 6536 6537 // Float varargs are always shadowed in available integer registers 6538 if (GPR_idx != NumGPRs) { 6539 SDValue Load = 6540 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo()); 6541 MemOpChains.push_back(Load.getValue(1)); 6542 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6543 } 6544 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && !isPPC64){ 6545 SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType()); 6546 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour); 6547 SDValue Load = 6548 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo()); 6549 MemOpChains.push_back(Load.getValue(1)); 6550 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6551 } 6552 } else { 6553 // If we have any FPRs remaining, we may also have GPRs remaining. 6554 // Args passed in FPRs consume either 1 (f32) or 2 (f64) available 6555 // GPRs. 6556 if (GPR_idx != NumGPRs) 6557 ++GPR_idx; 6558 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && 6559 !isPPC64) // PPC64 has 64-bit GPR's obviously :) 6560 ++GPR_idx; 6561 } 6562 } else 6563 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6564 isPPC64, isTailCall, false, MemOpChains, 6565 TailCallArguments, dl); 6566 if (isPPC64) 6567 ArgOffset += 8; 6568 else 6569 ArgOffset += Arg.getValueType() == MVT::f32 ? 4 : 8; 6570 break; 6571 case MVT::v4f32: 6572 case MVT::v4i32: 6573 case MVT::v8i16: 6574 case MVT::v16i8: 6575 if (isVarArg) { 6576 // These go aligned on the stack, or in the corresponding R registers 6577 // when within range. The Darwin PPC ABI doc claims they also go in 6578 // V registers; in fact gcc does this only for arguments that are 6579 // prototyped, not for those that match the ... We do it for all 6580 // arguments, seems to work. 6581 while (ArgOffset % 16 !=0) { 6582 ArgOffset += PtrByteSize; 6583 if (GPR_idx != NumGPRs) 6584 GPR_idx++; 6585 } 6586 // We could elide this store in the case where the object fits 6587 // entirely in R registers. Maybe later. 6588 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, 6589 DAG.getConstant(ArgOffset, dl, PtrVT)); 6590 SDValue Store = 6591 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 6592 MemOpChains.push_back(Store); 6593 if (VR_idx != NumVRs) { 6594 SDValue Load = 6595 DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo()); 6596 MemOpChains.push_back(Load.getValue(1)); 6597 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load)); 6598 } 6599 ArgOffset += 16; 6600 for (unsigned i=0; i<16; i+=PtrByteSize) { 6601 if (GPR_idx == NumGPRs) 6602 break; 6603 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, 6604 DAG.getConstant(i, dl, PtrVT)); 6605 SDValue Load = 6606 DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo()); 6607 MemOpChains.push_back(Load.getValue(1)); 6608 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6609 } 6610 break; 6611 } 6612 6613 // Non-varargs Altivec params generally go in registers, but have 6614 // stack space allocated at the end. 6615 if (VR_idx != NumVRs) { 6616 // Doesn't have GPR space allocated. 6617 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg)); 6618 } else if (nAltivecParamsAtEnd==0) { 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 break; 6626 } 6627 } 6628 // If all Altivec parameters fit in registers, as they usually do, 6629 // they get stack space following the non-Altivec parameters. We 6630 // don't track this here because nobody below needs it. 6631 // If there are more Altivec parameters than fit in registers emit 6632 // the stores here. 6633 if (!isVarArg && nAltivecParamsAtEnd > NumVRs) { 6634 unsigned j = 0; 6635 // Offset is aligned; skip 1st 12 params which go in V registers. 6636 ArgOffset = ((ArgOffset+15)/16)*16; 6637 ArgOffset += 12*16; 6638 for (unsigned i = 0; i != NumOps; ++i) { 6639 SDValue Arg = OutVals[i]; 6640 EVT ArgType = Outs[i].VT; 6641 if (ArgType==MVT::v4f32 || ArgType==MVT::v4i32 || 6642 ArgType==MVT::v8i16 || ArgType==MVT::v16i8) { 6643 if (++j > NumVRs) { 6644 SDValue PtrOff; 6645 // We are emitting Altivec params in order. 6646 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6647 isPPC64, isTailCall, true, MemOpChains, 6648 TailCallArguments, dl); 6649 ArgOffset += 16; 6650 } 6651 } 6652 } 6653 } 6654 6655 if (!MemOpChains.empty()) 6656 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 6657 6658 // On Darwin, R12 must contain the address of an indirect callee. This does 6659 // not mean the MTCTR instruction must use R12; it's easier to model this as 6660 // an extra parameter, so do that. 6661 if (!isTailCall && 6662 !isFunctionGlobalAddress(Callee) && 6663 !isa<ExternalSymbolSDNode>(Callee) && 6664 !isBLACompatibleAddress(Callee, DAG)) 6665 RegsToPass.push_back(std::make_pair((unsigned)(isPPC64 ? PPC::X12 : 6666 PPC::R12), Callee)); 6667 6668 // Build a sequence of copy-to-reg nodes chained together with token chain 6669 // and flag operands which copy the outgoing args into the appropriate regs. 6670 SDValue InFlag; 6671 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 6672 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 6673 RegsToPass[i].second, InFlag); 6674 InFlag = Chain.getValue(1); 6675 } 6676 6677 if (isTailCall) 6678 PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp, 6679 TailCallArguments); 6680 6681 return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint, 6682 /* unused except on PPC64 ELFv1 */ false, DAG, 6683 RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff, 6684 NumBytes, Ins, InVals, CS); 6685 } 6686 6687 6688 SDValue PPCTargetLowering::LowerCall_AIX( 6689 SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg, 6690 bool isTailCall, bool isPatchPoint, 6691 const SmallVectorImpl<ISD::OutputArg> &Outs, 6692 const SmallVectorImpl<SDValue> &OutVals, 6693 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 6694 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 6695 ImmutableCallSite CS) const { 6696 6697 assert((CallConv == CallingConv::C || CallConv == CallingConv::Fast) && 6698 "Unimplemented calling convention!"); 6699 if (isVarArg || isPatchPoint) 6700 report_fatal_error("This call type is unimplemented on AIX."); 6701 6702 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 6703 bool isPPC64 = PtrVT == MVT::i64; 6704 unsigned PtrByteSize = isPPC64 ? 8 : 4; 6705 unsigned NumOps = Outs.size(); 6706 6707 6708 // Count how many bytes are to be pushed on the stack, including the linkage 6709 // area, parameter list area. 6710 // On XCOFF, we start with 24/48, which is reserved space for 6711 // [SP][CR][LR][2 x reserved][TOC]. 6712 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 6713 6714 // The prolog code of the callee may store up to 8 GPR argument registers to 6715 // the stack, allowing va_start to index over them in memory if the callee 6716 // is variadic. 6717 // Because we cannot tell if this is needed on the caller side, we have to 6718 // conservatively assume that it is needed. As such, make sure we have at 6719 // least enough stack space for the caller to store the 8 GPRs. 6720 unsigned NumBytes = LinkageSize + 8 * PtrByteSize; 6721 6722 // Adjust the stack pointer for the new arguments... 6723 // These operations are automatically eliminated by the prolog/epilog 6724 // inserter pass. 6725 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 6726 SDValue CallSeqStart = Chain; 6727 6728 static const MCPhysReg GPR_32[] = { // 32-bit registers. 6729 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 6730 PPC::R7, PPC::R8, PPC::R9, PPC::R10 6731 }; 6732 static const MCPhysReg GPR_64[] = { // 64-bit registers. 6733 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 6734 PPC::X7, PPC::X8, PPC::X9, PPC::X10 6735 }; 6736 6737 const unsigned NumGPRs = isPPC64 ? array_lengthof(GPR_64) 6738 : array_lengthof(GPR_32); 6739 const unsigned NumFPRs = array_lengthof(FPR); 6740 assert(NumFPRs == 13 && "Only FPR 1-13 could be used for parameter passing " 6741 "on AIX"); 6742 6743 const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32; 6744 unsigned GPR_idx = 0, FPR_idx = 0; 6745 6746 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 6747 6748 if (isTailCall) 6749 report_fatal_error("Handling of tail call is unimplemented!"); 6750 int SPDiff = 0; 6751 6752 for (unsigned i = 0; i != NumOps; ++i) { 6753 SDValue Arg = OutVals[i]; 6754 ISD::ArgFlagsTy Flags = Outs[i].Flags; 6755 6756 // Promote integers if needed. 6757 if (Arg.getValueType() == MVT::i1 || 6758 (isPPC64 && Arg.getValueType() == MVT::i32)) { 6759 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 6760 Arg = DAG.getNode(ExtOp, dl, PtrVT, Arg); 6761 } 6762 6763 // Note: "by value" is code for passing a structure by value, not 6764 // basic types. 6765 if (Flags.isByVal()) 6766 report_fatal_error("Passing structure by value is unimplemented!"); 6767 6768 switch (Arg.getSimpleValueType().SimpleTy) { 6769 default: llvm_unreachable("Unexpected ValueType for argument!"); 6770 case MVT::i1: 6771 case MVT::i32: 6772 case MVT::i64: 6773 if (GPR_idx != NumGPRs) 6774 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg)); 6775 else 6776 report_fatal_error("Handling of placing parameters on the stack is " 6777 "unimplemented!"); 6778 break; 6779 case MVT::f32: 6780 case MVT::f64: 6781 if (FPR_idx != NumFPRs) { 6782 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg)); 6783 6784 // If we have any FPRs remaining, we may also have GPRs remaining. 6785 // Args passed in FPRs consume 1 or 2 (f64 in 32 bit mode) available 6786 // GPRs. 6787 if (GPR_idx != NumGPRs) 6788 ++GPR_idx; 6789 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && !isPPC64) 6790 ++GPR_idx; 6791 } else 6792 report_fatal_error("Handling of placing parameters on the stack is " 6793 "unimplemented!"); 6794 break; 6795 case MVT::v4f32: 6796 case MVT::v4i32: 6797 case MVT::v8i16: 6798 case MVT::v16i8: 6799 case MVT::v2f64: 6800 case MVT::v2i64: 6801 case MVT::v1i128: 6802 case MVT::f128: 6803 case MVT::v4f64: 6804 case MVT::v4i1: 6805 report_fatal_error("Handling of this parameter type is unimplemented!"); 6806 } 6807 } 6808 6809 if (!isFunctionGlobalAddress(Callee) && 6810 !isa<ExternalSymbolSDNode>(Callee)) 6811 report_fatal_error("Handling of indirect call is unimplemented!"); 6812 6813 // Build a sequence of copy-to-reg nodes chained together with token chain 6814 // and flag operands which copy the outgoing args into the appropriate regs. 6815 SDValue InFlag; 6816 for (auto Reg : RegsToPass) { 6817 Chain = DAG.getCopyToReg(Chain, dl, Reg.first, Reg.second, InFlag); 6818 InFlag = Chain.getValue(1); 6819 } 6820 6821 return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint, 6822 /* unused except on PPC64 ELFv1 */ false, DAG, 6823 RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff, 6824 NumBytes, Ins, InVals, CS); 6825 } 6826 6827 bool 6828 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv, 6829 MachineFunction &MF, bool isVarArg, 6830 const SmallVectorImpl<ISD::OutputArg> &Outs, 6831 LLVMContext &Context) const { 6832 SmallVector<CCValAssign, 16> RVLocs; 6833 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context); 6834 return CCInfo.CheckReturn( 6835 Outs, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold) 6836 ? RetCC_PPC_Cold 6837 : RetCC_PPC); 6838 } 6839 6840 SDValue 6841 PPCTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 6842 bool isVarArg, 6843 const SmallVectorImpl<ISD::OutputArg> &Outs, 6844 const SmallVectorImpl<SDValue> &OutVals, 6845 const SDLoc &dl, SelectionDAG &DAG) const { 6846 SmallVector<CCValAssign, 16> RVLocs; 6847 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 6848 *DAG.getContext()); 6849 CCInfo.AnalyzeReturn(Outs, 6850 (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold) 6851 ? RetCC_PPC_Cold 6852 : RetCC_PPC); 6853 6854 SDValue Flag; 6855 SmallVector<SDValue, 4> RetOps(1, Chain); 6856 6857 // Copy the result values into the output registers. 6858 for (unsigned i = 0, RealResIdx = 0; i != RVLocs.size(); ++i, ++RealResIdx) { 6859 CCValAssign &VA = RVLocs[i]; 6860 assert(VA.isRegLoc() && "Can only return in registers!"); 6861 6862 SDValue Arg = OutVals[RealResIdx]; 6863 6864 switch (VA.getLocInfo()) { 6865 default: llvm_unreachable("Unknown loc info!"); 6866 case CCValAssign::Full: break; 6867 case CCValAssign::AExt: 6868 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg); 6869 break; 6870 case CCValAssign::ZExt: 6871 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg); 6872 break; 6873 case CCValAssign::SExt: 6874 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg); 6875 break; 6876 } 6877 if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) { 6878 bool isLittleEndian = Subtarget.isLittleEndian(); 6879 // Legalize ret f64 -> ret 2 x i32. 6880 SDValue SVal = 6881 DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg, 6882 DAG.getIntPtrConstant(isLittleEndian ? 0 : 1, dl)); 6883 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Flag); 6884 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 6885 SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg, 6886 DAG.getIntPtrConstant(isLittleEndian ? 1 : 0, dl)); 6887 Flag = Chain.getValue(1); 6888 VA = RVLocs[++i]; // skip ahead to next loc 6889 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Flag); 6890 } else 6891 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag); 6892 Flag = Chain.getValue(1); 6893 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 6894 } 6895 6896 const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo(); 6897 const MCPhysReg *I = 6898 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction()); 6899 if (I) { 6900 for (; *I; ++I) { 6901 6902 if (PPC::G8RCRegClass.contains(*I)) 6903 RetOps.push_back(DAG.getRegister(*I, MVT::i64)); 6904 else if (PPC::F8RCRegClass.contains(*I)) 6905 RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64))); 6906 else if (PPC::CRRCRegClass.contains(*I)) 6907 RetOps.push_back(DAG.getRegister(*I, MVT::i1)); 6908 else if (PPC::VRRCRegClass.contains(*I)) 6909 RetOps.push_back(DAG.getRegister(*I, MVT::Other)); 6910 else 6911 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 6912 } 6913 } 6914 6915 RetOps[0] = Chain; // Update chain. 6916 6917 // Add the flag if we have it. 6918 if (Flag.getNode()) 6919 RetOps.push_back(Flag); 6920 6921 return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, RetOps); 6922 } 6923 6924 SDValue 6925 PPCTargetLowering::LowerGET_DYNAMIC_AREA_OFFSET(SDValue Op, 6926 SelectionDAG &DAG) const { 6927 SDLoc dl(Op); 6928 6929 // Get the correct type for integers. 6930 EVT IntVT = Op.getValueType(); 6931 6932 // Get the inputs. 6933 SDValue Chain = Op.getOperand(0); 6934 SDValue FPSIdx = getFramePointerFrameIndex(DAG); 6935 // Build a DYNAREAOFFSET node. 6936 SDValue Ops[2] = {Chain, FPSIdx}; 6937 SDVTList VTs = DAG.getVTList(IntVT); 6938 return DAG.getNode(PPCISD::DYNAREAOFFSET, dl, VTs, Ops); 6939 } 6940 6941 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op, 6942 SelectionDAG &DAG) const { 6943 // When we pop the dynamic allocation we need to restore the SP link. 6944 SDLoc dl(Op); 6945 6946 // Get the correct type for pointers. 6947 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 6948 6949 // Construct the stack pointer operand. 6950 bool isPPC64 = Subtarget.isPPC64(); 6951 unsigned SP = isPPC64 ? PPC::X1 : PPC::R1; 6952 SDValue StackPtr = DAG.getRegister(SP, PtrVT); 6953 6954 // Get the operands for the STACKRESTORE. 6955 SDValue Chain = Op.getOperand(0); 6956 SDValue SaveSP = Op.getOperand(1); 6957 6958 // Load the old link SP. 6959 SDValue LoadLinkSP = 6960 DAG.getLoad(PtrVT, dl, Chain, StackPtr, MachinePointerInfo()); 6961 6962 // Restore the stack pointer. 6963 Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP); 6964 6965 // Store the old link SP. 6966 return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo()); 6967 } 6968 6969 SDValue PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG &DAG) const { 6970 MachineFunction &MF = DAG.getMachineFunction(); 6971 bool isPPC64 = Subtarget.isPPC64(); 6972 EVT PtrVT = getPointerTy(MF.getDataLayout()); 6973 6974 // Get current frame pointer save index. The users of this index will be 6975 // primarily DYNALLOC instructions. 6976 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>(); 6977 int RASI = FI->getReturnAddrSaveIndex(); 6978 6979 // If the frame pointer save index hasn't been defined yet. 6980 if (!RASI) { 6981 // Find out what the fix offset of the frame pointer save area. 6982 int LROffset = Subtarget.getFrameLowering()->getReturnSaveOffset(); 6983 // Allocate the frame index for frame pointer save area. 6984 RASI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, LROffset, false); 6985 // Save the result. 6986 FI->setReturnAddrSaveIndex(RASI); 6987 } 6988 return DAG.getFrameIndex(RASI, PtrVT); 6989 } 6990 6991 SDValue 6992 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const { 6993 MachineFunction &MF = DAG.getMachineFunction(); 6994 bool isPPC64 = Subtarget.isPPC64(); 6995 EVT PtrVT = getPointerTy(MF.getDataLayout()); 6996 6997 // Get current frame pointer save index. The users of this index will be 6998 // primarily DYNALLOC instructions. 6999 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>(); 7000 int FPSI = FI->getFramePointerSaveIndex(); 7001 7002 // If the frame pointer save index hasn't been defined yet. 7003 if (!FPSI) { 7004 // Find out what the fix offset of the frame pointer save area. 7005 int FPOffset = Subtarget.getFrameLowering()->getFramePointerSaveOffset(); 7006 // Allocate the frame index for frame pointer save area. 7007 FPSI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, FPOffset, true); 7008 // Save the result. 7009 FI->setFramePointerSaveIndex(FPSI); 7010 } 7011 return DAG.getFrameIndex(FPSI, PtrVT); 7012 } 7013 7014 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, 7015 SelectionDAG &DAG) const { 7016 // Get the inputs. 7017 SDValue Chain = Op.getOperand(0); 7018 SDValue Size = Op.getOperand(1); 7019 SDLoc dl(Op); 7020 7021 // Get the correct type for pointers. 7022 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7023 // Negate the size. 7024 SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT, 7025 DAG.getConstant(0, dl, PtrVT), Size); 7026 // Construct a node for the frame pointer save index. 7027 SDValue FPSIdx = getFramePointerFrameIndex(DAG); 7028 // Build a DYNALLOC node. 7029 SDValue Ops[3] = { Chain, NegSize, FPSIdx }; 7030 SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other); 7031 return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops); 7032 } 7033 7034 SDValue PPCTargetLowering::LowerEH_DWARF_CFA(SDValue Op, 7035 SelectionDAG &DAG) const { 7036 MachineFunction &MF = DAG.getMachineFunction(); 7037 7038 bool isPPC64 = Subtarget.isPPC64(); 7039 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7040 7041 int FI = MF.getFrameInfo().CreateFixedObject(isPPC64 ? 8 : 4, 0, false); 7042 return DAG.getFrameIndex(FI, PtrVT); 7043 } 7044 7045 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op, 7046 SelectionDAG &DAG) const { 7047 SDLoc DL(Op); 7048 return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL, 7049 DAG.getVTList(MVT::i32, MVT::Other), 7050 Op.getOperand(0), Op.getOperand(1)); 7051 } 7052 7053 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op, 7054 SelectionDAG &DAG) const { 7055 SDLoc DL(Op); 7056 return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other, 7057 Op.getOperand(0), Op.getOperand(1)); 7058 } 7059 7060 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const { 7061 if (Op.getValueType().isVector()) 7062 return LowerVectorLoad(Op, DAG); 7063 7064 assert(Op.getValueType() == MVT::i1 && 7065 "Custom lowering only for i1 loads"); 7066 7067 // First, load 8 bits into 32 bits, then truncate to 1 bit. 7068 7069 SDLoc dl(Op); 7070 LoadSDNode *LD = cast<LoadSDNode>(Op); 7071 7072 SDValue Chain = LD->getChain(); 7073 SDValue BasePtr = LD->getBasePtr(); 7074 MachineMemOperand *MMO = LD->getMemOperand(); 7075 7076 SDValue NewLD = 7077 DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(DAG.getDataLayout()), Chain, 7078 BasePtr, MVT::i8, MMO); 7079 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD); 7080 7081 SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) }; 7082 return DAG.getMergeValues(Ops, dl); 7083 } 7084 7085 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const { 7086 if (Op.getOperand(1).getValueType().isVector()) 7087 return LowerVectorStore(Op, DAG); 7088 7089 assert(Op.getOperand(1).getValueType() == MVT::i1 && 7090 "Custom lowering only for i1 stores"); 7091 7092 // First, zero extend to 32 bits, then use a truncating store to 8 bits. 7093 7094 SDLoc dl(Op); 7095 StoreSDNode *ST = cast<StoreSDNode>(Op); 7096 7097 SDValue Chain = ST->getChain(); 7098 SDValue BasePtr = ST->getBasePtr(); 7099 SDValue Value = ST->getValue(); 7100 MachineMemOperand *MMO = ST->getMemOperand(); 7101 7102 Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(DAG.getDataLayout()), 7103 Value); 7104 return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO); 7105 } 7106 7107 // FIXME: Remove this once the ANDI glue bug is fixed: 7108 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const { 7109 assert(Op.getValueType() == MVT::i1 && 7110 "Custom lowering only for i1 results"); 7111 7112 SDLoc DL(Op); 7113 return DAG.getNode(PPCISD::ANDIo_1_GT_BIT, DL, MVT::i1, 7114 Op.getOperand(0)); 7115 } 7116 7117 SDValue PPCTargetLowering::LowerTRUNCATEVector(SDValue Op, 7118 SelectionDAG &DAG) const { 7119 7120 // Implements a vector truncate that fits in a vector register as a shuffle. 7121 // We want to legalize vector truncates down to where the source fits in 7122 // a vector register (and target is therefore smaller than vector register 7123 // size). At that point legalization will try to custom lower the sub-legal 7124 // result and get here - where we can contain the truncate as a single target 7125 // operation. 7126 7127 // For example a trunc <2 x i16> to <2 x i8> could be visualized as follows: 7128 // <MSB1|LSB1, MSB2|LSB2> to <LSB1, LSB2> 7129 // 7130 // We will implement it for big-endian ordering as this (where x denotes 7131 // undefined): 7132 // < MSB1|LSB1, MSB2|LSB2, uu, uu, uu, uu, uu, uu> to 7133 // < LSB1, LSB2, u, u, u, u, u, u, u, u, u, u, u, u, u, u> 7134 // 7135 // The same operation in little-endian ordering will be: 7136 // <uu, uu, uu, uu, uu, uu, LSB2|MSB2, LSB1|MSB1> to 7137 // <u, u, u, u, u, u, u, u, u, u, u, u, u, u, LSB2, LSB1> 7138 7139 assert(Op.getValueType().isVector() && "Vector type expected."); 7140 7141 SDLoc DL(Op); 7142 SDValue N1 = Op.getOperand(0); 7143 unsigned SrcSize = N1.getValueType().getSizeInBits(); 7144 assert(SrcSize <= 128 && "Source must fit in an Altivec/VSX vector"); 7145 SDValue WideSrc = SrcSize == 128 ? N1 : widenVec(DAG, N1, DL); 7146 7147 EVT TrgVT = Op.getValueType(); 7148 unsigned TrgNumElts = TrgVT.getVectorNumElements(); 7149 EVT EltVT = TrgVT.getVectorElementType(); 7150 unsigned WideNumElts = 128 / EltVT.getSizeInBits(); 7151 EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts); 7152 7153 // First list the elements we want to keep. 7154 unsigned SizeMult = SrcSize / TrgVT.getSizeInBits(); 7155 SmallVector<int, 16> ShuffV; 7156 if (Subtarget.isLittleEndian()) 7157 for (unsigned i = 0; i < TrgNumElts; ++i) 7158 ShuffV.push_back(i * SizeMult); 7159 else 7160 for (unsigned i = 1; i <= TrgNumElts; ++i) 7161 ShuffV.push_back(i * SizeMult - 1); 7162 7163 // Populate the remaining elements with undefs. 7164 for (unsigned i = TrgNumElts; i < WideNumElts; ++i) 7165 // ShuffV.push_back(i + WideNumElts); 7166 ShuffV.push_back(WideNumElts + 1); 7167 7168 SDValue Conv = DAG.getNode(ISD::BITCAST, DL, WideVT, WideSrc); 7169 return DAG.getVectorShuffle(WideVT, DL, Conv, DAG.getUNDEF(WideVT), ShuffV); 7170 } 7171 7172 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when 7173 /// possible. 7174 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const { 7175 // Not FP? Not a fsel. 7176 if (!Op.getOperand(0).getValueType().isFloatingPoint() || 7177 !Op.getOperand(2).getValueType().isFloatingPoint()) 7178 return Op; 7179 7180 // We might be able to do better than this under some circumstances, but in 7181 // general, fsel-based lowering of select is a finite-math-only optimization. 7182 // For more information, see section F.3 of the 2.06 ISA specification. 7183 if (!DAG.getTarget().Options.NoInfsFPMath || 7184 !DAG.getTarget().Options.NoNaNsFPMath) 7185 return Op; 7186 // TODO: Propagate flags from the select rather than global settings. 7187 SDNodeFlags Flags; 7188 Flags.setNoInfs(true); 7189 Flags.setNoNaNs(true); 7190 7191 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get(); 7192 7193 EVT ResVT = Op.getValueType(); 7194 EVT CmpVT = Op.getOperand(0).getValueType(); 7195 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 7196 SDValue TV = Op.getOperand(2), FV = Op.getOperand(3); 7197 SDLoc dl(Op); 7198 7199 // If the RHS of the comparison is a 0.0, we don't need to do the 7200 // subtraction at all. 7201 SDValue Sel1; 7202 if (isFloatingPointZero(RHS)) 7203 switch (CC) { 7204 default: break; // SETUO etc aren't handled by fsel. 7205 case ISD::SETNE: 7206 std::swap(TV, FV); 7207 LLVM_FALLTHROUGH; 7208 case ISD::SETEQ: 7209 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits 7210 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); 7211 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV); 7212 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits 7213 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1); 7214 return DAG.getNode(PPCISD::FSEL, dl, ResVT, 7215 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV); 7216 case ISD::SETULT: 7217 case ISD::SETLT: 7218 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt 7219 LLVM_FALLTHROUGH; 7220 case ISD::SETOGE: 7221 case ISD::SETGE: 7222 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits 7223 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); 7224 return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV); 7225 case ISD::SETUGT: 7226 case ISD::SETGT: 7227 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt 7228 LLVM_FALLTHROUGH; 7229 case ISD::SETOLE: 7230 case ISD::SETLE: 7231 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits 7232 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); 7233 return DAG.getNode(PPCISD::FSEL, dl, ResVT, 7234 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV); 7235 } 7236 7237 SDValue Cmp; 7238 switch (CC) { 7239 default: break; // SETUO etc aren't handled by fsel. 7240 case ISD::SETNE: 7241 std::swap(TV, FV); 7242 LLVM_FALLTHROUGH; 7243 case ISD::SETEQ: 7244 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags); 7245 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 7246 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 7247 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); 7248 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits 7249 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1); 7250 return DAG.getNode(PPCISD::FSEL, dl, ResVT, 7251 DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV); 7252 case ISD::SETULT: 7253 case ISD::SETLT: 7254 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags); 7255 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 7256 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 7257 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV); 7258 case ISD::SETOGE: 7259 case ISD::SETGE: 7260 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags); 7261 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 7262 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 7263 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); 7264 case ISD::SETUGT: 7265 case ISD::SETGT: 7266 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags); 7267 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 7268 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 7269 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV); 7270 case ISD::SETOLE: 7271 case ISD::SETLE: 7272 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags); 7273 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 7274 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 7275 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); 7276 } 7277 return Op; 7278 } 7279 7280 void PPCTargetLowering::LowerFP_TO_INTForReuse(SDValue Op, ReuseLoadInfo &RLI, 7281 SelectionDAG &DAG, 7282 const SDLoc &dl) const { 7283 assert(Op.getOperand(0).getValueType().isFloatingPoint()); 7284 SDValue Src = Op.getOperand(0); 7285 if (Src.getValueType() == MVT::f32) 7286 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src); 7287 7288 SDValue Tmp; 7289 switch (Op.getSimpleValueType().SimpleTy) { 7290 default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!"); 7291 case MVT::i32: 7292 Tmp = DAG.getNode( 7293 Op.getOpcode() == ISD::FP_TO_SINT 7294 ? PPCISD::FCTIWZ 7295 : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ), 7296 dl, MVT::f64, Src); 7297 break; 7298 case MVT::i64: 7299 assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) && 7300 "i64 FP_TO_UINT is supported only with FPCVT"); 7301 Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ : 7302 PPCISD::FCTIDUZ, 7303 dl, MVT::f64, Src); 7304 break; 7305 } 7306 7307 // Convert the FP value to an int value through memory. 7308 bool i32Stack = Op.getValueType() == MVT::i32 && Subtarget.hasSTFIWX() && 7309 (Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()); 7310 SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64); 7311 int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex(); 7312 MachinePointerInfo MPI = 7313 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI); 7314 7315 // Emit a store to the stack slot. 7316 SDValue Chain; 7317 if (i32Stack) { 7318 MachineFunction &MF = DAG.getMachineFunction(); 7319 MachineMemOperand *MMO = 7320 MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, 4); 7321 SDValue Ops[] = { DAG.getEntryNode(), Tmp, FIPtr }; 7322 Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl, 7323 DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO); 7324 } else 7325 Chain = DAG.getStore(DAG.getEntryNode(), dl, Tmp, FIPtr, MPI); 7326 7327 // Result is a load from the stack slot. If loading 4 bytes, make sure to 7328 // add in a bias on big endian. 7329 if (Op.getValueType() == MVT::i32 && !i32Stack) { 7330 FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr, 7331 DAG.getConstant(4, dl, FIPtr.getValueType())); 7332 MPI = MPI.getWithOffset(Subtarget.isLittleEndian() ? 0 : 4); 7333 } 7334 7335 RLI.Chain = Chain; 7336 RLI.Ptr = FIPtr; 7337 RLI.MPI = MPI; 7338 } 7339 7340 /// Custom lowers floating point to integer conversions to use 7341 /// the direct move instructions available in ISA 2.07 to avoid the 7342 /// need for load/store combinations. 7343 SDValue PPCTargetLowering::LowerFP_TO_INTDirectMove(SDValue Op, 7344 SelectionDAG &DAG, 7345 const SDLoc &dl) const { 7346 assert(Op.getOperand(0).getValueType().isFloatingPoint()); 7347 SDValue Src = Op.getOperand(0); 7348 7349 if (Src.getValueType() == MVT::f32) 7350 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src); 7351 7352 SDValue Tmp; 7353 switch (Op.getSimpleValueType().SimpleTy) { 7354 default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!"); 7355 case MVT::i32: 7356 Tmp = DAG.getNode( 7357 Op.getOpcode() == ISD::FP_TO_SINT 7358 ? PPCISD::FCTIWZ 7359 : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ), 7360 dl, MVT::f64, Src); 7361 Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i32, Tmp); 7362 break; 7363 case MVT::i64: 7364 assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) && 7365 "i64 FP_TO_UINT is supported only with FPCVT"); 7366 Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ : 7367 PPCISD::FCTIDUZ, 7368 dl, MVT::f64, Src); 7369 Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i64, Tmp); 7370 break; 7371 } 7372 return Tmp; 7373 } 7374 7375 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG, 7376 const SDLoc &dl) const { 7377 7378 // FP to INT conversions are legal for f128. 7379 if (EnableQuadPrecision && (Op->getOperand(0).getValueType() == MVT::f128)) 7380 return Op; 7381 7382 // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on 7383 // PPC (the libcall is not available). 7384 if (Op.getOperand(0).getValueType() == MVT::ppcf128) { 7385 if (Op.getValueType() == MVT::i32) { 7386 if (Op.getOpcode() == ISD::FP_TO_SINT) { 7387 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, 7388 MVT::f64, Op.getOperand(0), 7389 DAG.getIntPtrConstant(0, dl)); 7390 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, 7391 MVT::f64, Op.getOperand(0), 7392 DAG.getIntPtrConstant(1, dl)); 7393 7394 // Add the two halves of the long double in round-to-zero mode. 7395 SDValue Res = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi); 7396 7397 // Now use a smaller FP_TO_SINT. 7398 return DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Res); 7399 } 7400 if (Op.getOpcode() == ISD::FP_TO_UINT) { 7401 const uint64_t TwoE31[] = {0x41e0000000000000LL, 0}; 7402 APFloat APF = APFloat(APFloat::PPCDoubleDouble(), APInt(128, TwoE31)); 7403 SDValue Tmp = DAG.getConstantFP(APF, dl, MVT::ppcf128); 7404 // X>=2^31 ? (int)(X-2^31)+0x80000000 : (int)X 7405 // FIXME: generated code sucks. 7406 // TODO: Are there fast-math-flags to propagate to this FSUB? 7407 SDValue True = DAG.getNode(ISD::FSUB, dl, MVT::ppcf128, 7408 Op.getOperand(0), Tmp); 7409 True = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, True); 7410 True = DAG.getNode(ISD::ADD, dl, MVT::i32, True, 7411 DAG.getConstant(0x80000000, dl, MVT::i32)); 7412 SDValue False = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, 7413 Op.getOperand(0)); 7414 return DAG.getSelectCC(dl, Op.getOperand(0), Tmp, True, False, 7415 ISD::SETGE); 7416 } 7417 } 7418 7419 return SDValue(); 7420 } 7421 7422 if (Subtarget.hasDirectMove() && Subtarget.isPPC64()) 7423 return LowerFP_TO_INTDirectMove(Op, DAG, dl); 7424 7425 ReuseLoadInfo RLI; 7426 LowerFP_TO_INTForReuse(Op, RLI, DAG, dl); 7427 7428 return DAG.getLoad(Op.getValueType(), dl, RLI.Chain, RLI.Ptr, RLI.MPI, 7429 RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges); 7430 } 7431 7432 // We're trying to insert a regular store, S, and then a load, L. If the 7433 // incoming value, O, is a load, we might just be able to have our load use the 7434 // address used by O. However, we don't know if anything else will store to 7435 // that address before we can load from it. To prevent this situation, we need 7436 // to insert our load, L, into the chain as a peer of O. To do this, we give L 7437 // the same chain operand as O, we create a token factor from the chain results 7438 // of O and L, and we replace all uses of O's chain result with that token 7439 // factor (see spliceIntoChain below for this last part). 7440 bool PPCTargetLowering::canReuseLoadAddress(SDValue Op, EVT MemVT, 7441 ReuseLoadInfo &RLI, 7442 SelectionDAG &DAG, 7443 ISD::LoadExtType ET) const { 7444 SDLoc dl(Op); 7445 if (ET == ISD::NON_EXTLOAD && 7446 (Op.getOpcode() == ISD::FP_TO_UINT || 7447 Op.getOpcode() == ISD::FP_TO_SINT) && 7448 isOperationLegalOrCustom(Op.getOpcode(), 7449 Op.getOperand(0).getValueType())) { 7450 7451 LowerFP_TO_INTForReuse(Op, RLI, DAG, dl); 7452 return true; 7453 } 7454 7455 LoadSDNode *LD = dyn_cast<LoadSDNode>(Op); 7456 if (!LD || LD->getExtensionType() != ET || LD->isVolatile() || 7457 LD->isNonTemporal()) 7458 return false; 7459 if (LD->getMemoryVT() != MemVT) 7460 return false; 7461 7462 RLI.Ptr = LD->getBasePtr(); 7463 if (LD->isIndexed() && !LD->getOffset().isUndef()) { 7464 assert(LD->getAddressingMode() == ISD::PRE_INC && 7465 "Non-pre-inc AM on PPC?"); 7466 RLI.Ptr = DAG.getNode(ISD::ADD, dl, RLI.Ptr.getValueType(), RLI.Ptr, 7467 LD->getOffset()); 7468 } 7469 7470 RLI.Chain = LD->getChain(); 7471 RLI.MPI = LD->getPointerInfo(); 7472 RLI.IsDereferenceable = LD->isDereferenceable(); 7473 RLI.IsInvariant = LD->isInvariant(); 7474 RLI.Alignment = LD->getAlignment(); 7475 RLI.AAInfo = LD->getAAInfo(); 7476 RLI.Ranges = LD->getRanges(); 7477 7478 RLI.ResChain = SDValue(LD, LD->isIndexed() ? 2 : 1); 7479 return true; 7480 } 7481 7482 // Given the head of the old chain, ResChain, insert a token factor containing 7483 // it and NewResChain, and make users of ResChain now be users of that token 7484 // factor. 7485 // TODO: Remove and use DAG::makeEquivalentMemoryOrdering() instead. 7486 void PPCTargetLowering::spliceIntoChain(SDValue ResChain, 7487 SDValue NewResChain, 7488 SelectionDAG &DAG) const { 7489 if (!ResChain) 7490 return; 7491 7492 SDLoc dl(NewResChain); 7493 7494 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 7495 NewResChain, DAG.getUNDEF(MVT::Other)); 7496 assert(TF.getNode() != NewResChain.getNode() && 7497 "A new TF really is required here"); 7498 7499 DAG.ReplaceAllUsesOfValueWith(ResChain, TF); 7500 DAG.UpdateNodeOperands(TF.getNode(), ResChain, NewResChain); 7501 } 7502 7503 /// Analyze profitability of direct move 7504 /// prefer float load to int load plus direct move 7505 /// when there is no integer use of int load 7506 bool PPCTargetLowering::directMoveIsProfitable(const SDValue &Op) const { 7507 SDNode *Origin = Op.getOperand(0).getNode(); 7508 if (Origin->getOpcode() != ISD::LOAD) 7509 return true; 7510 7511 // If there is no LXSIBZX/LXSIHZX, like Power8, 7512 // prefer direct move if the memory size is 1 or 2 bytes. 7513 MachineMemOperand *MMO = cast<LoadSDNode>(Origin)->getMemOperand(); 7514 if (!Subtarget.hasP9Vector() && MMO->getSize() <= 2) 7515 return true; 7516 7517 for (SDNode::use_iterator UI = Origin->use_begin(), 7518 UE = Origin->use_end(); 7519 UI != UE; ++UI) { 7520 7521 // Only look at the users of the loaded value. 7522 if (UI.getUse().get().getResNo() != 0) 7523 continue; 7524 7525 if (UI->getOpcode() != ISD::SINT_TO_FP && 7526 UI->getOpcode() != ISD::UINT_TO_FP) 7527 return true; 7528 } 7529 7530 return false; 7531 } 7532 7533 /// Custom lowers integer to floating point conversions to use 7534 /// the direct move instructions available in ISA 2.07 to avoid the 7535 /// need for load/store combinations. 7536 SDValue PPCTargetLowering::LowerINT_TO_FPDirectMove(SDValue Op, 7537 SelectionDAG &DAG, 7538 const SDLoc &dl) const { 7539 assert((Op.getValueType() == MVT::f32 || 7540 Op.getValueType() == MVT::f64) && 7541 "Invalid floating point type as target of conversion"); 7542 assert(Subtarget.hasFPCVT() && 7543 "Int to FP conversions with direct moves require FPCVT"); 7544 SDValue FP; 7545 SDValue Src = Op.getOperand(0); 7546 bool SinglePrec = Op.getValueType() == MVT::f32; 7547 bool WordInt = Src.getSimpleValueType().SimpleTy == MVT::i32; 7548 bool Signed = Op.getOpcode() == ISD::SINT_TO_FP; 7549 unsigned ConvOp = Signed ? (SinglePrec ? PPCISD::FCFIDS : PPCISD::FCFID) : 7550 (SinglePrec ? PPCISD::FCFIDUS : PPCISD::FCFIDU); 7551 7552 if (WordInt) { 7553 FP = DAG.getNode(Signed ? PPCISD::MTVSRA : PPCISD::MTVSRZ, 7554 dl, MVT::f64, Src); 7555 FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP); 7556 } 7557 else { 7558 FP = DAG.getNode(PPCISD::MTVSRA, dl, MVT::f64, Src); 7559 FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP); 7560 } 7561 7562 return FP; 7563 } 7564 7565 static SDValue widenVec(SelectionDAG &DAG, SDValue Vec, const SDLoc &dl) { 7566 7567 EVT VecVT = Vec.getValueType(); 7568 assert(VecVT.isVector() && "Expected a vector type."); 7569 assert(VecVT.getSizeInBits() < 128 && "Vector is already full width."); 7570 7571 EVT EltVT = VecVT.getVectorElementType(); 7572 unsigned WideNumElts = 128 / EltVT.getSizeInBits(); 7573 EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts); 7574 7575 unsigned NumConcat = WideNumElts / VecVT.getVectorNumElements(); 7576 SmallVector<SDValue, 16> Ops(NumConcat); 7577 Ops[0] = Vec; 7578 SDValue UndefVec = DAG.getUNDEF(VecVT); 7579 for (unsigned i = 1; i < NumConcat; ++i) 7580 Ops[i] = UndefVec; 7581 7582 return DAG.getNode(ISD::CONCAT_VECTORS, dl, WideVT, Ops); 7583 } 7584 7585 SDValue PPCTargetLowering::LowerINT_TO_FPVector(SDValue Op, SelectionDAG &DAG, 7586 const SDLoc &dl) const { 7587 7588 unsigned Opc = Op.getOpcode(); 7589 assert((Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP) && 7590 "Unexpected conversion type"); 7591 assert((Op.getValueType() == MVT::v2f64 || Op.getValueType() == MVT::v4f32) && 7592 "Supports conversions to v2f64/v4f32 only."); 7593 7594 bool SignedConv = Opc == ISD::SINT_TO_FP; 7595 bool FourEltRes = Op.getValueType() == MVT::v4f32; 7596 7597 SDValue Wide = widenVec(DAG, Op.getOperand(0), dl); 7598 EVT WideVT = Wide.getValueType(); 7599 unsigned WideNumElts = WideVT.getVectorNumElements(); 7600 MVT IntermediateVT = FourEltRes ? MVT::v4i32 : MVT::v2i64; 7601 7602 SmallVector<int, 16> ShuffV; 7603 for (unsigned i = 0; i < WideNumElts; ++i) 7604 ShuffV.push_back(i + WideNumElts); 7605 7606 int Stride = FourEltRes ? WideNumElts / 4 : WideNumElts / 2; 7607 int SaveElts = FourEltRes ? 4 : 2; 7608 if (Subtarget.isLittleEndian()) 7609 for (int i = 0; i < SaveElts; i++) 7610 ShuffV[i * Stride] = i; 7611 else 7612 for (int i = 1; i <= SaveElts; i++) 7613 ShuffV[i * Stride - 1] = i - 1; 7614 7615 SDValue ShuffleSrc2 = 7616 SignedConv ? DAG.getUNDEF(WideVT) : DAG.getConstant(0, dl, WideVT); 7617 SDValue Arrange = DAG.getVectorShuffle(WideVT, dl, Wide, ShuffleSrc2, ShuffV); 7618 unsigned ExtendOp = 7619 SignedConv ? (unsigned)PPCISD::SExtVElems : (unsigned)ISD::BITCAST; 7620 7621 SDValue Extend; 7622 if (!Subtarget.hasP9Altivec() && SignedConv) { 7623 Arrange = DAG.getBitcast(IntermediateVT, Arrange); 7624 Extend = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, IntermediateVT, Arrange, 7625 DAG.getValueType(Op.getOperand(0).getValueType())); 7626 } else 7627 Extend = DAG.getNode(ExtendOp, dl, IntermediateVT, Arrange); 7628 7629 return DAG.getNode(Opc, dl, Op.getValueType(), Extend); 7630 } 7631 7632 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op, 7633 SelectionDAG &DAG) const { 7634 SDLoc dl(Op); 7635 7636 EVT InVT = Op.getOperand(0).getValueType(); 7637 EVT OutVT = Op.getValueType(); 7638 if (OutVT.isVector() && OutVT.isFloatingPoint() && 7639 isOperationCustom(Op.getOpcode(), InVT)) 7640 return LowerINT_TO_FPVector(Op, DAG, dl); 7641 7642 // Conversions to f128 are legal. 7643 if (EnableQuadPrecision && (Op.getValueType() == MVT::f128)) 7644 return Op; 7645 7646 if (Subtarget.hasQPX() && Op.getOperand(0).getValueType() == MVT::v4i1) { 7647 if (Op.getValueType() != MVT::v4f32 && Op.getValueType() != MVT::v4f64) 7648 return SDValue(); 7649 7650 SDValue Value = Op.getOperand(0); 7651 // The values are now known to be -1 (false) or 1 (true). To convert this 7652 // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5). 7653 // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5 7654 Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value); 7655 7656 SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64); 7657 7658 Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs); 7659 7660 if (Op.getValueType() != MVT::v4f64) 7661 Value = DAG.getNode(ISD::FP_ROUND, dl, 7662 Op.getValueType(), Value, 7663 DAG.getIntPtrConstant(1, dl)); 7664 return Value; 7665 } 7666 7667 // Don't handle ppc_fp128 here; let it be lowered to a libcall. 7668 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64) 7669 return SDValue(); 7670 7671 if (Op.getOperand(0).getValueType() == MVT::i1) 7672 return DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Op.getOperand(0), 7673 DAG.getConstantFP(1.0, dl, Op.getValueType()), 7674 DAG.getConstantFP(0.0, dl, Op.getValueType())); 7675 7676 // If we have direct moves, we can do all the conversion, skip the store/load 7677 // however, without FPCVT we can't do most conversions. 7678 if (Subtarget.hasDirectMove() && directMoveIsProfitable(Op) && 7679 Subtarget.isPPC64() && Subtarget.hasFPCVT()) 7680 return LowerINT_TO_FPDirectMove(Op, DAG, dl); 7681 7682 assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) && 7683 "UINT_TO_FP is supported only with FPCVT"); 7684 7685 // If we have FCFIDS, then use it when converting to single-precision. 7686 // Otherwise, convert to double-precision and then round. 7687 unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 7688 ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS 7689 : PPCISD::FCFIDS) 7690 : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU 7691 : PPCISD::FCFID); 7692 MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 7693 ? MVT::f32 7694 : MVT::f64; 7695 7696 if (Op.getOperand(0).getValueType() == MVT::i64) { 7697 SDValue SINT = Op.getOperand(0); 7698 // When converting to single-precision, we actually need to convert 7699 // to double-precision first and then round to single-precision. 7700 // To avoid double-rounding effects during that operation, we have 7701 // to prepare the input operand. Bits that might be truncated when 7702 // converting to double-precision are replaced by a bit that won't 7703 // be lost at this stage, but is below the single-precision rounding 7704 // position. 7705 // 7706 // However, if -enable-unsafe-fp-math is in effect, accept double 7707 // rounding to avoid the extra overhead. 7708 if (Op.getValueType() == MVT::f32 && 7709 !Subtarget.hasFPCVT() && 7710 !DAG.getTarget().Options.UnsafeFPMath) { 7711 7712 // Twiddle input to make sure the low 11 bits are zero. (If this 7713 // is the case, we are guaranteed the value will fit into the 53 bit 7714 // mantissa of an IEEE double-precision value without rounding.) 7715 // If any of those low 11 bits were not zero originally, make sure 7716 // bit 12 (value 2048) is set instead, so that the final rounding 7717 // to single-precision gets the correct result. 7718 SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64, 7719 SINT, DAG.getConstant(2047, dl, MVT::i64)); 7720 Round = DAG.getNode(ISD::ADD, dl, MVT::i64, 7721 Round, DAG.getConstant(2047, dl, MVT::i64)); 7722 Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT); 7723 Round = DAG.getNode(ISD::AND, dl, MVT::i64, 7724 Round, DAG.getConstant(-2048, dl, MVT::i64)); 7725 7726 // However, we cannot use that value unconditionally: if the magnitude 7727 // of the input value is small, the bit-twiddling we did above might 7728 // end up visibly changing the output. Fortunately, in that case, we 7729 // don't need to twiddle bits since the original input will convert 7730 // exactly to double-precision floating-point already. Therefore, 7731 // construct a conditional to use the original value if the top 11 7732 // bits are all sign-bit copies, and use the rounded value computed 7733 // above otherwise. 7734 SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64, 7735 SINT, DAG.getConstant(53, dl, MVT::i32)); 7736 Cond = DAG.getNode(ISD::ADD, dl, MVT::i64, 7737 Cond, DAG.getConstant(1, dl, MVT::i64)); 7738 Cond = DAG.getSetCC(dl, MVT::i32, 7739 Cond, DAG.getConstant(1, dl, MVT::i64), ISD::SETUGT); 7740 7741 SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT); 7742 } 7743 7744 ReuseLoadInfo RLI; 7745 SDValue Bits; 7746 7747 MachineFunction &MF = DAG.getMachineFunction(); 7748 if (canReuseLoadAddress(SINT, MVT::i64, RLI, DAG)) { 7749 Bits = DAG.getLoad(MVT::f64, dl, RLI.Chain, RLI.Ptr, RLI.MPI, 7750 RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges); 7751 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG); 7752 } else if (Subtarget.hasLFIWAX() && 7753 canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::SEXTLOAD)) { 7754 MachineMemOperand *MMO = 7755 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 7756 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 7757 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 7758 Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWAX, dl, 7759 DAG.getVTList(MVT::f64, MVT::Other), 7760 Ops, MVT::i32, MMO); 7761 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG); 7762 } else if (Subtarget.hasFPCVT() && 7763 canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::ZEXTLOAD)) { 7764 MachineMemOperand *MMO = 7765 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 7766 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 7767 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 7768 Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWZX, dl, 7769 DAG.getVTList(MVT::f64, MVT::Other), 7770 Ops, MVT::i32, MMO); 7771 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG); 7772 } else if (((Subtarget.hasLFIWAX() && 7773 SINT.getOpcode() == ISD::SIGN_EXTEND) || 7774 (Subtarget.hasFPCVT() && 7775 SINT.getOpcode() == ISD::ZERO_EXTEND)) && 7776 SINT.getOperand(0).getValueType() == MVT::i32) { 7777 MachineFrameInfo &MFI = MF.getFrameInfo(); 7778 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7779 7780 int FrameIdx = MFI.CreateStackObject(4, 4, false); 7781 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 7782 7783 SDValue Store = 7784 DAG.getStore(DAG.getEntryNode(), dl, SINT.getOperand(0), FIdx, 7785 MachinePointerInfo::getFixedStack( 7786 DAG.getMachineFunction(), FrameIdx)); 7787 7788 assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 && 7789 "Expected an i32 store"); 7790 7791 RLI.Ptr = FIdx; 7792 RLI.Chain = Store; 7793 RLI.MPI = 7794 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 7795 RLI.Alignment = 4; 7796 7797 MachineMemOperand *MMO = 7798 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 7799 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 7800 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 7801 Bits = DAG.getMemIntrinsicNode(SINT.getOpcode() == ISD::ZERO_EXTEND ? 7802 PPCISD::LFIWZX : PPCISD::LFIWAX, 7803 dl, DAG.getVTList(MVT::f64, MVT::Other), 7804 Ops, MVT::i32, MMO); 7805 } else 7806 Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT); 7807 7808 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Bits); 7809 7810 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) 7811 FP = DAG.getNode(ISD::FP_ROUND, dl, 7812 MVT::f32, FP, DAG.getIntPtrConstant(0, dl)); 7813 return FP; 7814 } 7815 7816 assert(Op.getOperand(0).getValueType() == MVT::i32 && 7817 "Unhandled INT_TO_FP type in custom expander!"); 7818 // Since we only generate this in 64-bit mode, we can take advantage of 7819 // 64-bit registers. In particular, sign extend the input value into the 7820 // 64-bit register with extsw, store the WHOLE 64-bit value into the stack 7821 // then lfd it and fcfid it. 7822 MachineFunction &MF = DAG.getMachineFunction(); 7823 MachineFrameInfo &MFI = MF.getFrameInfo(); 7824 EVT PtrVT = getPointerTy(MF.getDataLayout()); 7825 7826 SDValue Ld; 7827 if (Subtarget.hasLFIWAX() || Subtarget.hasFPCVT()) { 7828 ReuseLoadInfo RLI; 7829 bool ReusingLoad; 7830 if (!(ReusingLoad = canReuseLoadAddress(Op.getOperand(0), MVT::i32, RLI, 7831 DAG))) { 7832 int FrameIdx = MFI.CreateStackObject(4, 4, false); 7833 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 7834 7835 SDValue Store = 7836 DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx, 7837 MachinePointerInfo::getFixedStack( 7838 DAG.getMachineFunction(), FrameIdx)); 7839 7840 assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 && 7841 "Expected an i32 store"); 7842 7843 RLI.Ptr = FIdx; 7844 RLI.Chain = Store; 7845 RLI.MPI = 7846 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 7847 RLI.Alignment = 4; 7848 } 7849 7850 MachineMemOperand *MMO = 7851 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 7852 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 7853 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 7854 Ld = DAG.getMemIntrinsicNode(Op.getOpcode() == ISD::UINT_TO_FP ? 7855 PPCISD::LFIWZX : PPCISD::LFIWAX, 7856 dl, DAG.getVTList(MVT::f64, MVT::Other), 7857 Ops, MVT::i32, MMO); 7858 if (ReusingLoad) 7859 spliceIntoChain(RLI.ResChain, Ld.getValue(1), DAG); 7860 } else { 7861 assert(Subtarget.isPPC64() && 7862 "i32->FP without LFIWAX supported only on PPC64"); 7863 7864 int FrameIdx = MFI.CreateStackObject(8, 8, false); 7865 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 7866 7867 SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64, 7868 Op.getOperand(0)); 7869 7870 // STD the extended value into the stack slot. 7871 SDValue Store = DAG.getStore( 7872 DAG.getEntryNode(), dl, Ext64, FIdx, 7873 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx)); 7874 7875 // Load the value as a double. 7876 Ld = DAG.getLoad( 7877 MVT::f64, dl, Store, FIdx, 7878 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx)); 7879 } 7880 7881 // FCFID it and return it. 7882 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Ld); 7883 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) 7884 FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP, 7885 DAG.getIntPtrConstant(0, dl)); 7886 return FP; 7887 } 7888 7889 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op, 7890 SelectionDAG &DAG) const { 7891 SDLoc dl(Op); 7892 /* 7893 The rounding mode is in bits 30:31 of FPSR, and has the following 7894 settings: 7895 00 Round to nearest 7896 01 Round to 0 7897 10 Round to +inf 7898 11 Round to -inf 7899 7900 FLT_ROUNDS, on the other hand, expects the following: 7901 -1 Undefined 7902 0 Round to 0 7903 1 Round to nearest 7904 2 Round to +inf 7905 3 Round to -inf 7906 7907 To perform the conversion, we do: 7908 ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1)) 7909 */ 7910 7911 MachineFunction &MF = DAG.getMachineFunction(); 7912 EVT VT = Op.getValueType(); 7913 EVT PtrVT = getPointerTy(MF.getDataLayout()); 7914 7915 // Save FP Control Word to register 7916 EVT NodeTys[] = { 7917 MVT::f64, // return register 7918 MVT::Glue // unused in this context 7919 }; 7920 SDValue Chain = DAG.getNode(PPCISD::MFFS, dl, NodeTys, None); 7921 7922 // Save FP register to stack slot 7923 int SSFI = MF.getFrameInfo().CreateStackObject(8, 8, false); 7924 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT); 7925 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Chain, StackSlot, 7926 MachinePointerInfo()); 7927 7928 // Load FP Control Word from low 32 bits of stack slot. 7929 SDValue Four = DAG.getConstant(4, dl, PtrVT); 7930 SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four); 7931 SDValue CWD = DAG.getLoad(MVT::i32, dl, Store, Addr, MachinePointerInfo()); 7932 7933 // Transform as necessary 7934 SDValue CWD1 = 7935 DAG.getNode(ISD::AND, dl, MVT::i32, 7936 CWD, DAG.getConstant(3, dl, MVT::i32)); 7937 SDValue CWD2 = 7938 DAG.getNode(ISD::SRL, dl, MVT::i32, 7939 DAG.getNode(ISD::AND, dl, MVT::i32, 7940 DAG.getNode(ISD::XOR, dl, MVT::i32, 7941 CWD, DAG.getConstant(3, dl, MVT::i32)), 7942 DAG.getConstant(3, dl, MVT::i32)), 7943 DAG.getConstant(1, dl, MVT::i32)); 7944 7945 SDValue RetVal = 7946 DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2); 7947 7948 return DAG.getNode((VT.getSizeInBits() < 16 ? 7949 ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal); 7950 } 7951 7952 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const { 7953 EVT VT = Op.getValueType(); 7954 unsigned BitWidth = VT.getSizeInBits(); 7955 SDLoc dl(Op); 7956 assert(Op.getNumOperands() == 3 && 7957 VT == Op.getOperand(1).getValueType() && 7958 "Unexpected SHL!"); 7959 7960 // Expand into a bunch of logical ops. Note that these ops 7961 // depend on the PPC behavior for oversized shift amounts. 7962 SDValue Lo = Op.getOperand(0); 7963 SDValue Hi = Op.getOperand(1); 7964 SDValue Amt = Op.getOperand(2); 7965 EVT AmtVT = Amt.getValueType(); 7966 7967 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, 7968 DAG.getConstant(BitWidth, dl, AmtVT), Amt); 7969 SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt); 7970 SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1); 7971 SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3); 7972 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, 7973 DAG.getConstant(-BitWidth, dl, AmtVT)); 7974 SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5); 7975 SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6); 7976 SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt); 7977 SDValue OutOps[] = { OutLo, OutHi }; 7978 return DAG.getMergeValues(OutOps, dl); 7979 } 7980 7981 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const { 7982 EVT VT = Op.getValueType(); 7983 SDLoc dl(Op); 7984 unsigned BitWidth = VT.getSizeInBits(); 7985 assert(Op.getNumOperands() == 3 && 7986 VT == Op.getOperand(1).getValueType() && 7987 "Unexpected SRL!"); 7988 7989 // Expand into a bunch of logical ops. Note that these ops 7990 // depend on the PPC behavior for oversized shift amounts. 7991 SDValue Lo = Op.getOperand(0); 7992 SDValue Hi = Op.getOperand(1); 7993 SDValue Amt = Op.getOperand(2); 7994 EVT AmtVT = Amt.getValueType(); 7995 7996 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, 7997 DAG.getConstant(BitWidth, dl, AmtVT), Amt); 7998 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt); 7999 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1); 8000 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3); 8001 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, 8002 DAG.getConstant(-BitWidth, dl, AmtVT)); 8003 SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5); 8004 SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6); 8005 SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt); 8006 SDValue OutOps[] = { OutLo, OutHi }; 8007 return DAG.getMergeValues(OutOps, dl); 8008 } 8009 8010 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const { 8011 SDLoc dl(Op); 8012 EVT VT = Op.getValueType(); 8013 unsigned BitWidth = VT.getSizeInBits(); 8014 assert(Op.getNumOperands() == 3 && 8015 VT == Op.getOperand(1).getValueType() && 8016 "Unexpected SRA!"); 8017 8018 // Expand into a bunch of logical ops, followed by a select_cc. 8019 SDValue Lo = Op.getOperand(0); 8020 SDValue Hi = Op.getOperand(1); 8021 SDValue Amt = Op.getOperand(2); 8022 EVT AmtVT = Amt.getValueType(); 8023 8024 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, 8025 DAG.getConstant(BitWidth, dl, AmtVT), Amt); 8026 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt); 8027 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1); 8028 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3); 8029 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, 8030 DAG.getConstant(-BitWidth, dl, AmtVT)); 8031 SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5); 8032 SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt); 8033 SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, dl, AmtVT), 8034 Tmp4, Tmp6, ISD::SETLE); 8035 SDValue OutOps[] = { OutLo, OutHi }; 8036 return DAG.getMergeValues(OutOps, dl); 8037 } 8038 8039 //===----------------------------------------------------------------------===// 8040 // Vector related lowering. 8041 // 8042 8043 /// BuildSplatI - Build a canonical splati of Val with an element size of 8044 /// SplatSize. Cast the result to VT. 8045 static SDValue BuildSplatI(int Val, unsigned SplatSize, EVT VT, 8046 SelectionDAG &DAG, const SDLoc &dl) { 8047 assert(Val >= -16 && Val <= 15 && "vsplti is out of range!"); 8048 8049 static const MVT VTys[] = { // canonical VT to use for each size. 8050 MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32 8051 }; 8052 8053 EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1]; 8054 8055 // Force vspltis[hw] -1 to vspltisb -1 to canonicalize. 8056 if (Val == -1) 8057 SplatSize = 1; 8058 8059 EVT CanonicalVT = VTys[SplatSize-1]; 8060 8061 // Build a canonical splat for this value. 8062 return DAG.getBitcast(ReqVT, DAG.getConstant(Val, dl, CanonicalVT)); 8063 } 8064 8065 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the 8066 /// specified intrinsic ID. 8067 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op, SelectionDAG &DAG, 8068 const SDLoc &dl, EVT DestVT = MVT::Other) { 8069 if (DestVT == MVT::Other) DestVT = Op.getValueType(); 8070 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 8071 DAG.getConstant(IID, dl, MVT::i32), Op); 8072 } 8073 8074 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the 8075 /// specified intrinsic ID. 8076 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS, 8077 SelectionDAG &DAG, const SDLoc &dl, 8078 EVT DestVT = MVT::Other) { 8079 if (DestVT == MVT::Other) DestVT = LHS.getValueType(); 8080 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 8081 DAG.getConstant(IID, dl, MVT::i32), LHS, RHS); 8082 } 8083 8084 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the 8085 /// specified intrinsic ID. 8086 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1, 8087 SDValue Op2, SelectionDAG &DAG, const SDLoc &dl, 8088 EVT DestVT = MVT::Other) { 8089 if (DestVT == MVT::Other) DestVT = Op0.getValueType(); 8090 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 8091 DAG.getConstant(IID, dl, MVT::i32), Op0, Op1, Op2); 8092 } 8093 8094 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified 8095 /// amount. The result has the specified value type. 8096 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt, EVT VT, 8097 SelectionDAG &DAG, const SDLoc &dl) { 8098 // Force LHS/RHS to be the right type. 8099 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS); 8100 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS); 8101 8102 int Ops[16]; 8103 for (unsigned i = 0; i != 16; ++i) 8104 Ops[i] = i + Amt; 8105 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops); 8106 return DAG.getNode(ISD::BITCAST, dl, VT, T); 8107 } 8108 8109 /// Do we have an efficient pattern in a .td file for this node? 8110 /// 8111 /// \param V - pointer to the BuildVectorSDNode being matched 8112 /// \param HasDirectMove - does this subtarget have VSR <-> GPR direct moves? 8113 /// 8114 /// There are some patterns where it is beneficial to keep a BUILD_VECTOR 8115 /// node as a BUILD_VECTOR node rather than expanding it. The patterns where 8116 /// the opposite is true (expansion is beneficial) are: 8117 /// - The node builds a vector out of integers that are not 32 or 64-bits 8118 /// - The node builds a vector out of constants 8119 /// - The node is a "load-and-splat" 8120 /// In all other cases, we will choose to keep the BUILD_VECTOR. 8121 static bool haveEfficientBuildVectorPattern(BuildVectorSDNode *V, 8122 bool HasDirectMove, 8123 bool HasP8Vector) { 8124 EVT VecVT = V->getValueType(0); 8125 bool RightType = VecVT == MVT::v2f64 || 8126 (HasP8Vector && VecVT == MVT::v4f32) || 8127 (HasDirectMove && (VecVT == MVT::v2i64 || VecVT == MVT::v4i32)); 8128 if (!RightType) 8129 return false; 8130 8131 bool IsSplat = true; 8132 bool IsLoad = false; 8133 SDValue Op0 = V->getOperand(0); 8134 8135 // This function is called in a block that confirms the node is not a constant 8136 // splat. So a constant BUILD_VECTOR here means the vector is built out of 8137 // different constants. 8138 if (V->isConstant()) 8139 return false; 8140 for (int i = 0, e = V->getNumOperands(); i < e; ++i) { 8141 if (V->getOperand(i).isUndef()) 8142 return false; 8143 // We want to expand nodes that represent load-and-splat even if the 8144 // loaded value is a floating point truncation or conversion to int. 8145 if (V->getOperand(i).getOpcode() == ISD::LOAD || 8146 (V->getOperand(i).getOpcode() == ISD::FP_ROUND && 8147 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) || 8148 (V->getOperand(i).getOpcode() == ISD::FP_TO_SINT && 8149 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) || 8150 (V->getOperand(i).getOpcode() == ISD::FP_TO_UINT && 8151 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD)) 8152 IsLoad = true; 8153 // If the operands are different or the input is not a load and has more 8154 // uses than just this BV node, then it isn't a splat. 8155 if (V->getOperand(i) != Op0 || 8156 (!IsLoad && !V->isOnlyUserOf(V->getOperand(i).getNode()))) 8157 IsSplat = false; 8158 } 8159 return !(IsSplat && IsLoad); 8160 } 8161 8162 // Lower BITCAST(f128, (build_pair i64, i64)) to BUILD_FP128. 8163 SDValue PPCTargetLowering::LowerBITCAST(SDValue Op, SelectionDAG &DAG) const { 8164 8165 SDLoc dl(Op); 8166 SDValue Op0 = Op->getOperand(0); 8167 8168 if (!EnableQuadPrecision || 8169 (Op.getValueType() != MVT::f128 ) || 8170 (Op0.getOpcode() != ISD::BUILD_PAIR) || 8171 (Op0.getOperand(0).getValueType() != MVT::i64) || 8172 (Op0.getOperand(1).getValueType() != MVT::i64)) 8173 return SDValue(); 8174 8175 return DAG.getNode(PPCISD::BUILD_FP128, dl, MVT::f128, Op0.getOperand(0), 8176 Op0.getOperand(1)); 8177 } 8178 8179 // If this is a case we can't handle, return null and let the default 8180 // expansion code take care of it. If we CAN select this case, and if it 8181 // selects to a single instruction, return Op. Otherwise, if we can codegen 8182 // this case more efficiently than a constant pool load, lower it to the 8183 // sequence of ops that should be used. 8184 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op, 8185 SelectionDAG &DAG) const { 8186 SDLoc dl(Op); 8187 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode()); 8188 assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR"); 8189 8190 if (Subtarget.hasQPX() && Op.getValueType() == MVT::v4i1) { 8191 // We first build an i32 vector, load it into a QPX register, 8192 // then convert it to a floating-point vector and compare it 8193 // to a zero vector to get the boolean result. 8194 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 8195 int FrameIdx = MFI.CreateStackObject(16, 16, false); 8196 MachinePointerInfo PtrInfo = 8197 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 8198 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 8199 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 8200 8201 assert(BVN->getNumOperands() == 4 && 8202 "BUILD_VECTOR for v4i1 does not have 4 operands"); 8203 8204 bool IsConst = true; 8205 for (unsigned i = 0; i < 4; ++i) { 8206 if (BVN->getOperand(i).isUndef()) continue; 8207 if (!isa<ConstantSDNode>(BVN->getOperand(i))) { 8208 IsConst = false; 8209 break; 8210 } 8211 } 8212 8213 if (IsConst) { 8214 Constant *One = 8215 ConstantFP::get(Type::getFloatTy(*DAG.getContext()), 1.0); 8216 Constant *NegOne = 8217 ConstantFP::get(Type::getFloatTy(*DAG.getContext()), -1.0); 8218 8219 Constant *CV[4]; 8220 for (unsigned i = 0; i < 4; ++i) { 8221 if (BVN->getOperand(i).isUndef()) 8222 CV[i] = UndefValue::get(Type::getFloatTy(*DAG.getContext())); 8223 else if (isNullConstant(BVN->getOperand(i))) 8224 CV[i] = NegOne; 8225 else 8226 CV[i] = One; 8227 } 8228 8229 Constant *CP = ConstantVector::get(CV); 8230 SDValue CPIdx = DAG.getConstantPool(CP, getPointerTy(DAG.getDataLayout()), 8231 16 /* alignment */); 8232 8233 SDValue Ops[] = {DAG.getEntryNode(), CPIdx}; 8234 SDVTList VTs = DAG.getVTList({MVT::v4i1, /*chain*/ MVT::Other}); 8235 return DAG.getMemIntrinsicNode( 8236 PPCISD::QVLFSb, dl, VTs, Ops, MVT::v4f32, 8237 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 8238 } 8239 8240 SmallVector<SDValue, 4> Stores; 8241 for (unsigned i = 0; i < 4; ++i) { 8242 if (BVN->getOperand(i).isUndef()) continue; 8243 8244 unsigned Offset = 4*i; 8245 SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType()); 8246 Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx); 8247 8248 unsigned StoreSize = BVN->getOperand(i).getValueType().getStoreSize(); 8249 if (StoreSize > 4) { 8250 Stores.push_back( 8251 DAG.getTruncStore(DAG.getEntryNode(), dl, BVN->getOperand(i), Idx, 8252 PtrInfo.getWithOffset(Offset), MVT::i32)); 8253 } else { 8254 SDValue StoreValue = BVN->getOperand(i); 8255 if (StoreSize < 4) 8256 StoreValue = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, StoreValue); 8257 8258 Stores.push_back(DAG.getStore(DAG.getEntryNode(), dl, StoreValue, Idx, 8259 PtrInfo.getWithOffset(Offset))); 8260 } 8261 } 8262 8263 SDValue StoreChain; 8264 if (!Stores.empty()) 8265 StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores); 8266 else 8267 StoreChain = DAG.getEntryNode(); 8268 8269 // Now load from v4i32 into the QPX register; this will extend it to 8270 // v4i64 but not yet convert it to a floating point. Nevertheless, this 8271 // is typed as v4f64 because the QPX register integer states are not 8272 // explicitly represented. 8273 8274 SDValue Ops[] = {StoreChain, 8275 DAG.getConstant(Intrinsic::ppc_qpx_qvlfiwz, dl, MVT::i32), 8276 FIdx}; 8277 SDVTList VTs = DAG.getVTList({MVT::v4f64, /*chain*/ MVT::Other}); 8278 8279 SDValue LoadedVect = DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, 8280 dl, VTs, Ops, MVT::v4i32, PtrInfo); 8281 LoadedVect = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64, 8282 DAG.getConstant(Intrinsic::ppc_qpx_qvfcfidu, dl, MVT::i32), 8283 LoadedVect); 8284 8285 SDValue FPZeros = DAG.getConstantFP(0.0, dl, MVT::v4f64); 8286 8287 return DAG.getSetCC(dl, MVT::v4i1, LoadedVect, FPZeros, ISD::SETEQ); 8288 } 8289 8290 // All other QPX vectors are handled by generic code. 8291 if (Subtarget.hasQPX()) 8292 return SDValue(); 8293 8294 // Check if this is a splat of a constant value. 8295 APInt APSplatBits, APSplatUndef; 8296 unsigned SplatBitSize; 8297 bool HasAnyUndefs; 8298 if (! BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize, 8299 HasAnyUndefs, 0, !Subtarget.isLittleEndian()) || 8300 SplatBitSize > 32) { 8301 // BUILD_VECTOR nodes that are not constant splats of up to 32-bits can be 8302 // lowered to VSX instructions under certain conditions. 8303 // Without VSX, there is no pattern more efficient than expanding the node. 8304 if (Subtarget.hasVSX() && 8305 haveEfficientBuildVectorPattern(BVN, Subtarget.hasDirectMove(), 8306 Subtarget.hasP8Vector())) 8307 return Op; 8308 return SDValue(); 8309 } 8310 8311 unsigned SplatBits = APSplatBits.getZExtValue(); 8312 unsigned SplatUndef = APSplatUndef.getZExtValue(); 8313 unsigned SplatSize = SplatBitSize / 8; 8314 8315 // First, handle single instruction cases. 8316 8317 // All zeros? 8318 if (SplatBits == 0) { 8319 // Canonicalize all zero vectors to be v4i32. 8320 if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) { 8321 SDValue Z = DAG.getConstant(0, dl, MVT::v4i32); 8322 Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z); 8323 } 8324 return Op; 8325 } 8326 8327 // We have XXSPLTIB for constant splats one byte wide 8328 if (Subtarget.hasP9Vector() && SplatSize == 1) { 8329 // This is a splat of 1-byte elements with some elements potentially undef. 8330 // Rather than trying to match undef in the SDAG patterns, ensure that all 8331 // elements are the same constant. 8332 if (HasAnyUndefs || ISD::isBuildVectorAllOnes(BVN)) { 8333 SmallVector<SDValue, 16> Ops(16, DAG.getConstant(SplatBits, 8334 dl, MVT::i32)); 8335 SDValue NewBV = DAG.getBuildVector(MVT::v16i8, dl, Ops); 8336 if (Op.getValueType() != MVT::v16i8) 8337 return DAG.getBitcast(Op.getValueType(), NewBV); 8338 return NewBV; 8339 } 8340 8341 // BuildVectorSDNode::isConstantSplat() is actually pretty smart. It'll 8342 // detect that constant splats like v8i16: 0xABAB are really just splats 8343 // of a 1-byte constant. In this case, we need to convert the node to a 8344 // splat of v16i8 and a bitcast. 8345 if (Op.getValueType() != MVT::v16i8) 8346 return DAG.getBitcast(Op.getValueType(), 8347 DAG.getConstant(SplatBits, dl, MVT::v16i8)); 8348 8349 return Op; 8350 } 8351 8352 // If the sign extended value is in the range [-16,15], use VSPLTI[bhw]. 8353 int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >> 8354 (32-SplatBitSize)); 8355 if (SextVal >= -16 && SextVal <= 15) 8356 return BuildSplatI(SextVal, SplatSize, Op.getValueType(), DAG, dl); 8357 8358 // Two instruction sequences. 8359 8360 // If this value is in the range [-32,30] and is even, use: 8361 // VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2) 8362 // If this value is in the range [17,31] and is odd, use: 8363 // VSPLTI[bhw](val-16) - VSPLTI[bhw](-16) 8364 // If this value is in the range [-31,-17] and is odd, use: 8365 // VSPLTI[bhw](val+16) + VSPLTI[bhw](-16) 8366 // Note the last two are three-instruction sequences. 8367 if (SextVal >= -32 && SextVal <= 31) { 8368 // To avoid having these optimizations undone by constant folding, 8369 // we convert to a pseudo that will be expanded later into one of 8370 // the above forms. 8371 SDValue Elt = DAG.getConstant(SextVal, dl, MVT::i32); 8372 EVT VT = (SplatSize == 1 ? MVT::v16i8 : 8373 (SplatSize == 2 ? MVT::v8i16 : MVT::v4i32)); 8374 SDValue EltSize = DAG.getConstant(SplatSize, dl, MVT::i32); 8375 SDValue RetVal = DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize); 8376 if (VT == Op.getValueType()) 8377 return RetVal; 8378 else 8379 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), RetVal); 8380 } 8381 8382 // If this is 0x8000_0000 x 4, turn into vspltisw + vslw. If it is 8383 // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000). This is important 8384 // for fneg/fabs. 8385 if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) { 8386 // Make -1 and vspltisw -1: 8387 SDValue OnesV = BuildSplatI(-1, 4, MVT::v4i32, DAG, dl); 8388 8389 // Make the VSLW intrinsic, computing 0x8000_0000. 8390 SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV, 8391 OnesV, DAG, dl); 8392 8393 // xor by OnesV to invert it. 8394 Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV); 8395 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 8396 } 8397 8398 // Check to see if this is a wide variety of vsplti*, binop self cases. 8399 static const signed char SplatCsts[] = { 8400 -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7, 8401 -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16 8402 }; 8403 8404 for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) { 8405 // Indirect through the SplatCsts array so that we favor 'vsplti -1' for 8406 // cases which are ambiguous (e.g. formation of 0x8000_0000). 'vsplti -1' 8407 int i = SplatCsts[idx]; 8408 8409 // Figure out what shift amount will be used by altivec if shifted by i in 8410 // this splat size. 8411 unsigned TypeShiftAmt = i & (SplatBitSize-1); 8412 8413 // vsplti + shl self. 8414 if (SextVal == (int)((unsigned)i << TypeShiftAmt)) { 8415 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl); 8416 static const unsigned IIDs[] = { // Intrinsic to use for each size. 8417 Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0, 8418 Intrinsic::ppc_altivec_vslw 8419 }; 8420 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 8421 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 8422 } 8423 8424 // vsplti + srl self. 8425 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) { 8426 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl); 8427 static const unsigned IIDs[] = { // Intrinsic to use for each size. 8428 Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0, 8429 Intrinsic::ppc_altivec_vsrw 8430 }; 8431 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 8432 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 8433 } 8434 8435 // vsplti + sra self. 8436 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) { 8437 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl); 8438 static const unsigned IIDs[] = { // Intrinsic to use for each size. 8439 Intrinsic::ppc_altivec_vsrab, Intrinsic::ppc_altivec_vsrah, 0, 8440 Intrinsic::ppc_altivec_vsraw 8441 }; 8442 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 8443 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 8444 } 8445 8446 // vsplti + rol self. 8447 if (SextVal == (int)(((unsigned)i << TypeShiftAmt) | 8448 ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) { 8449 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl); 8450 static const unsigned IIDs[] = { // Intrinsic to use for each size. 8451 Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0, 8452 Intrinsic::ppc_altivec_vrlw 8453 }; 8454 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 8455 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 8456 } 8457 8458 // t = vsplti c, result = vsldoi t, t, 1 8459 if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) { 8460 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl); 8461 unsigned Amt = Subtarget.isLittleEndian() ? 15 : 1; 8462 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl); 8463 } 8464 // t = vsplti c, result = vsldoi t, t, 2 8465 if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) { 8466 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl); 8467 unsigned Amt = Subtarget.isLittleEndian() ? 14 : 2; 8468 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl); 8469 } 8470 // t = vsplti c, result = vsldoi t, t, 3 8471 if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) { 8472 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl); 8473 unsigned Amt = Subtarget.isLittleEndian() ? 13 : 3; 8474 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl); 8475 } 8476 } 8477 8478 return SDValue(); 8479 } 8480 8481 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit 8482 /// the specified operations to build the shuffle. 8483 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS, 8484 SDValue RHS, SelectionDAG &DAG, 8485 const SDLoc &dl) { 8486 unsigned OpNum = (PFEntry >> 26) & 0x0F; 8487 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1); 8488 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1); 8489 8490 enum { 8491 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3> 8492 OP_VMRGHW, 8493 OP_VMRGLW, 8494 OP_VSPLTISW0, 8495 OP_VSPLTISW1, 8496 OP_VSPLTISW2, 8497 OP_VSPLTISW3, 8498 OP_VSLDOI4, 8499 OP_VSLDOI8, 8500 OP_VSLDOI12 8501 }; 8502 8503 if (OpNum == OP_COPY) { 8504 if (LHSID == (1*9+2)*9+3) return LHS; 8505 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!"); 8506 return RHS; 8507 } 8508 8509 SDValue OpLHS, OpRHS; 8510 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl); 8511 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl); 8512 8513 int ShufIdxs[16]; 8514 switch (OpNum) { 8515 default: llvm_unreachable("Unknown i32 permute!"); 8516 case OP_VMRGHW: 8517 ShufIdxs[ 0] = 0; ShufIdxs[ 1] = 1; ShufIdxs[ 2] = 2; ShufIdxs[ 3] = 3; 8518 ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19; 8519 ShufIdxs[ 8] = 4; ShufIdxs[ 9] = 5; ShufIdxs[10] = 6; ShufIdxs[11] = 7; 8520 ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23; 8521 break; 8522 case OP_VMRGLW: 8523 ShufIdxs[ 0] = 8; ShufIdxs[ 1] = 9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11; 8524 ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27; 8525 ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15; 8526 ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31; 8527 break; 8528 case OP_VSPLTISW0: 8529 for (unsigned i = 0; i != 16; ++i) 8530 ShufIdxs[i] = (i&3)+0; 8531 break; 8532 case OP_VSPLTISW1: 8533 for (unsigned i = 0; i != 16; ++i) 8534 ShufIdxs[i] = (i&3)+4; 8535 break; 8536 case OP_VSPLTISW2: 8537 for (unsigned i = 0; i != 16; ++i) 8538 ShufIdxs[i] = (i&3)+8; 8539 break; 8540 case OP_VSPLTISW3: 8541 for (unsigned i = 0; i != 16; ++i) 8542 ShufIdxs[i] = (i&3)+12; 8543 break; 8544 case OP_VSLDOI4: 8545 return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl); 8546 case OP_VSLDOI8: 8547 return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl); 8548 case OP_VSLDOI12: 8549 return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl); 8550 } 8551 EVT VT = OpLHS.getValueType(); 8552 OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS); 8553 OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS); 8554 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs); 8555 return DAG.getNode(ISD::BITCAST, dl, VT, T); 8556 } 8557 8558 /// lowerToVINSERTB - Return the SDValue if this VECTOR_SHUFFLE can be handled 8559 /// by the VINSERTB instruction introduced in ISA 3.0, else just return default 8560 /// SDValue. 8561 SDValue PPCTargetLowering::lowerToVINSERTB(ShuffleVectorSDNode *N, 8562 SelectionDAG &DAG) const { 8563 const unsigned BytesInVector = 16; 8564 bool IsLE = Subtarget.isLittleEndian(); 8565 SDLoc dl(N); 8566 SDValue V1 = N->getOperand(0); 8567 SDValue V2 = N->getOperand(1); 8568 unsigned ShiftElts = 0, InsertAtByte = 0; 8569 bool Swap = false; 8570 8571 // Shifts required to get the byte we want at element 7. 8572 unsigned LittleEndianShifts[] = {8, 7, 6, 5, 4, 3, 2, 1, 8573 0, 15, 14, 13, 12, 11, 10, 9}; 8574 unsigned BigEndianShifts[] = {9, 10, 11, 12, 13, 14, 15, 0, 8575 1, 2, 3, 4, 5, 6, 7, 8}; 8576 8577 ArrayRef<int> Mask = N->getMask(); 8578 int OriginalOrder[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}; 8579 8580 // For each mask element, find out if we're just inserting something 8581 // from V2 into V1 or vice versa. 8582 // Possible permutations inserting an element from V2 into V1: 8583 // X, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 8584 // 0, X, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 8585 // ... 8586 // 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, X 8587 // Inserting from V1 into V2 will be similar, except mask range will be 8588 // [16,31]. 8589 8590 bool FoundCandidate = false; 8591 // If both vector operands for the shuffle are the same vector, the mask 8592 // will contain only elements from the first one and the second one will be 8593 // undef. 8594 unsigned VINSERTBSrcElem = IsLE ? 8 : 7; 8595 // Go through the mask of half-words to find an element that's being moved 8596 // from one vector to the other. 8597 for (unsigned i = 0; i < BytesInVector; ++i) { 8598 unsigned CurrentElement = Mask[i]; 8599 // If 2nd operand is undefined, we should only look for element 7 in the 8600 // Mask. 8601 if (V2.isUndef() && CurrentElement != VINSERTBSrcElem) 8602 continue; 8603 8604 bool OtherElementsInOrder = true; 8605 // Examine the other elements in the Mask to see if they're in original 8606 // order. 8607 for (unsigned j = 0; j < BytesInVector; ++j) { 8608 if (j == i) 8609 continue; 8610 // If CurrentElement is from V1 [0,15], then we the rest of the Mask to be 8611 // from V2 [16,31] and vice versa. Unless the 2nd operand is undefined, 8612 // in which we always assume we're always picking from the 1st operand. 8613 int MaskOffset = 8614 (!V2.isUndef() && CurrentElement < BytesInVector) ? BytesInVector : 0; 8615 if (Mask[j] != OriginalOrder[j] + MaskOffset) { 8616 OtherElementsInOrder = false; 8617 break; 8618 } 8619 } 8620 // If other elements are in original order, we record the number of shifts 8621 // we need to get the element we want into element 7. Also record which byte 8622 // in the vector we should insert into. 8623 if (OtherElementsInOrder) { 8624 // If 2nd operand is undefined, we assume no shifts and no swapping. 8625 if (V2.isUndef()) { 8626 ShiftElts = 0; 8627 Swap = false; 8628 } else { 8629 // Only need the last 4-bits for shifts because operands will be swapped if CurrentElement is >= 2^4. 8630 ShiftElts = IsLE ? LittleEndianShifts[CurrentElement & 0xF] 8631 : BigEndianShifts[CurrentElement & 0xF]; 8632 Swap = CurrentElement < BytesInVector; 8633 } 8634 InsertAtByte = IsLE ? BytesInVector - (i + 1) : i; 8635 FoundCandidate = true; 8636 break; 8637 } 8638 } 8639 8640 if (!FoundCandidate) 8641 return SDValue(); 8642 8643 // Candidate found, construct the proper SDAG sequence with VINSERTB, 8644 // optionally with VECSHL if shift is required. 8645 if (Swap) 8646 std::swap(V1, V2); 8647 if (V2.isUndef()) 8648 V2 = V1; 8649 if (ShiftElts) { 8650 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2, 8651 DAG.getConstant(ShiftElts, dl, MVT::i32)); 8652 return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, Shl, 8653 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 8654 } 8655 return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, V2, 8656 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 8657 } 8658 8659 /// lowerToVINSERTH - Return the SDValue if this VECTOR_SHUFFLE can be handled 8660 /// by the VINSERTH instruction introduced in ISA 3.0, else just return default 8661 /// SDValue. 8662 SDValue PPCTargetLowering::lowerToVINSERTH(ShuffleVectorSDNode *N, 8663 SelectionDAG &DAG) const { 8664 const unsigned NumHalfWords = 8; 8665 const unsigned BytesInVector = NumHalfWords * 2; 8666 // Check that the shuffle is on half-words. 8667 if (!isNByteElemShuffleMask(N, 2, 1)) 8668 return SDValue(); 8669 8670 bool IsLE = Subtarget.isLittleEndian(); 8671 SDLoc dl(N); 8672 SDValue V1 = N->getOperand(0); 8673 SDValue V2 = N->getOperand(1); 8674 unsigned ShiftElts = 0, InsertAtByte = 0; 8675 bool Swap = false; 8676 8677 // Shifts required to get the half-word we want at element 3. 8678 unsigned LittleEndianShifts[] = {4, 3, 2, 1, 0, 7, 6, 5}; 8679 unsigned BigEndianShifts[] = {5, 6, 7, 0, 1, 2, 3, 4}; 8680 8681 uint32_t Mask = 0; 8682 uint32_t OriginalOrderLow = 0x1234567; 8683 uint32_t OriginalOrderHigh = 0x89ABCDEF; 8684 // Now we look at mask elements 0,2,4,6,8,10,12,14. Pack the mask into a 8685 // 32-bit space, only need 4-bit nibbles per element. 8686 for (unsigned i = 0; i < NumHalfWords; ++i) { 8687 unsigned MaskShift = (NumHalfWords - 1 - i) * 4; 8688 Mask |= ((uint32_t)(N->getMaskElt(i * 2) / 2) << MaskShift); 8689 } 8690 8691 // For each mask element, find out if we're just inserting something 8692 // from V2 into V1 or vice versa. Possible permutations inserting an element 8693 // from V2 into V1: 8694 // X, 1, 2, 3, 4, 5, 6, 7 8695 // 0, X, 2, 3, 4, 5, 6, 7 8696 // 0, 1, X, 3, 4, 5, 6, 7 8697 // 0, 1, 2, X, 4, 5, 6, 7 8698 // 0, 1, 2, 3, X, 5, 6, 7 8699 // 0, 1, 2, 3, 4, X, 6, 7 8700 // 0, 1, 2, 3, 4, 5, X, 7 8701 // 0, 1, 2, 3, 4, 5, 6, X 8702 // Inserting from V1 into V2 will be similar, except mask range will be [8,15]. 8703 8704 bool FoundCandidate = false; 8705 // Go through the mask of half-words to find an element that's being moved 8706 // from one vector to the other. 8707 for (unsigned i = 0; i < NumHalfWords; ++i) { 8708 unsigned MaskShift = (NumHalfWords - 1 - i) * 4; 8709 uint32_t MaskOneElt = (Mask >> MaskShift) & 0xF; 8710 uint32_t MaskOtherElts = ~(0xF << MaskShift); 8711 uint32_t TargetOrder = 0x0; 8712 8713 // If both vector operands for the shuffle are the same vector, the mask 8714 // will contain only elements from the first one and the second one will be 8715 // undef. 8716 if (V2.isUndef()) { 8717 ShiftElts = 0; 8718 unsigned VINSERTHSrcElem = IsLE ? 4 : 3; 8719 TargetOrder = OriginalOrderLow; 8720 Swap = false; 8721 // Skip if not the correct element or mask of other elements don't equal 8722 // to our expected order. 8723 if (MaskOneElt == VINSERTHSrcElem && 8724 (Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) { 8725 InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2; 8726 FoundCandidate = true; 8727 break; 8728 } 8729 } else { // If both operands are defined. 8730 // Target order is [8,15] if the current mask is between [0,7]. 8731 TargetOrder = 8732 (MaskOneElt < NumHalfWords) ? OriginalOrderHigh : OriginalOrderLow; 8733 // Skip if mask of other elements don't equal our expected order. 8734 if ((Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) { 8735 // We only need the last 3 bits for the number of shifts. 8736 ShiftElts = IsLE ? LittleEndianShifts[MaskOneElt & 0x7] 8737 : BigEndianShifts[MaskOneElt & 0x7]; 8738 InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2; 8739 Swap = MaskOneElt < NumHalfWords; 8740 FoundCandidate = true; 8741 break; 8742 } 8743 } 8744 } 8745 8746 if (!FoundCandidate) 8747 return SDValue(); 8748 8749 // Candidate found, construct the proper SDAG sequence with VINSERTH, 8750 // optionally with VECSHL if shift is required. 8751 if (Swap) 8752 std::swap(V1, V2); 8753 if (V2.isUndef()) 8754 V2 = V1; 8755 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1); 8756 if (ShiftElts) { 8757 // Double ShiftElts because we're left shifting on v16i8 type. 8758 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2, 8759 DAG.getConstant(2 * ShiftElts, dl, MVT::i32)); 8760 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, Shl); 8761 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2, 8762 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 8763 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 8764 } 8765 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2); 8766 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2, 8767 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 8768 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 8769 } 8770 8771 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE. If this 8772 /// is a shuffle we can handle in a single instruction, return it. Otherwise, 8773 /// return the code it can be lowered into. Worst case, it can always be 8774 /// lowered into a vperm. 8775 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, 8776 SelectionDAG &DAG) const { 8777 SDLoc dl(Op); 8778 SDValue V1 = Op.getOperand(0); 8779 SDValue V2 = Op.getOperand(1); 8780 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op); 8781 EVT VT = Op.getValueType(); 8782 bool isLittleEndian = Subtarget.isLittleEndian(); 8783 8784 unsigned ShiftElts, InsertAtByte; 8785 bool Swap = false; 8786 if (Subtarget.hasP9Vector() && 8787 PPC::isXXINSERTWMask(SVOp, ShiftElts, InsertAtByte, Swap, 8788 isLittleEndian)) { 8789 if (Swap) 8790 std::swap(V1, V2); 8791 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 8792 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2); 8793 if (ShiftElts) { 8794 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv2, Conv2, 8795 DAG.getConstant(ShiftElts, dl, MVT::i32)); 8796 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Shl, 8797 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 8798 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 8799 } 8800 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Conv2, 8801 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 8802 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 8803 } 8804 8805 if (Subtarget.hasP9Altivec()) { 8806 SDValue NewISDNode; 8807 if ((NewISDNode = lowerToVINSERTH(SVOp, DAG))) 8808 return NewISDNode; 8809 8810 if ((NewISDNode = lowerToVINSERTB(SVOp, DAG))) 8811 return NewISDNode; 8812 } 8813 8814 if (Subtarget.hasVSX() && 8815 PPC::isXXSLDWIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) { 8816 if (Swap) 8817 std::swap(V1, V2); 8818 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 8819 SDValue Conv2 = 8820 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2.isUndef() ? V1 : V2); 8821 8822 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv1, Conv2, 8823 DAG.getConstant(ShiftElts, dl, MVT::i32)); 8824 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Shl); 8825 } 8826 8827 if (Subtarget.hasVSX() && 8828 PPC::isXXPERMDIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) { 8829 if (Swap) 8830 std::swap(V1, V2); 8831 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1); 8832 SDValue Conv2 = 8833 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2.isUndef() ? V1 : V2); 8834 8835 SDValue PermDI = DAG.getNode(PPCISD::XXPERMDI, dl, MVT::v2i64, Conv1, Conv2, 8836 DAG.getConstant(ShiftElts, dl, MVT::i32)); 8837 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, PermDI); 8838 } 8839 8840 if (Subtarget.hasP9Vector()) { 8841 if (PPC::isXXBRHShuffleMask(SVOp)) { 8842 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1); 8843 SDValue ReveHWord = DAG.getNode(PPCISD::XXREVERSE, dl, MVT::v8i16, Conv); 8844 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveHWord); 8845 } else if (PPC::isXXBRWShuffleMask(SVOp)) { 8846 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 8847 SDValue ReveWord = DAG.getNode(PPCISD::XXREVERSE, dl, MVT::v4i32, Conv); 8848 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveWord); 8849 } else if (PPC::isXXBRDShuffleMask(SVOp)) { 8850 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1); 8851 SDValue ReveDWord = DAG.getNode(PPCISD::XXREVERSE, dl, MVT::v2i64, Conv); 8852 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveDWord); 8853 } else if (PPC::isXXBRQShuffleMask(SVOp)) { 8854 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, V1); 8855 SDValue ReveQWord = DAG.getNode(PPCISD::XXREVERSE, dl, MVT::v1i128, Conv); 8856 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveQWord); 8857 } 8858 } 8859 8860 if (Subtarget.hasVSX()) { 8861 if (V2.isUndef() && PPC::isSplatShuffleMask(SVOp, 4)) { 8862 int SplatIdx = PPC::getVSPLTImmediate(SVOp, 4, DAG); 8863 8864 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 8865 SDValue Splat = DAG.getNode(PPCISD::XXSPLT, dl, MVT::v4i32, Conv, 8866 DAG.getConstant(SplatIdx, dl, MVT::i32)); 8867 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Splat); 8868 } 8869 8870 // Left shifts of 8 bytes are actually swaps. Convert accordingly. 8871 if (V2.isUndef() && PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) == 8) { 8872 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1); 8873 SDValue Swap = DAG.getNode(PPCISD::SWAP_NO_CHAIN, dl, MVT::v2f64, Conv); 8874 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Swap); 8875 } 8876 } 8877 8878 if (Subtarget.hasQPX()) { 8879 if (VT.getVectorNumElements() != 4) 8880 return SDValue(); 8881 8882 if (V2.isUndef()) V2 = V1; 8883 8884 int AlignIdx = PPC::isQVALIGNIShuffleMask(SVOp); 8885 if (AlignIdx != -1) { 8886 return DAG.getNode(PPCISD::QVALIGNI, dl, VT, V1, V2, 8887 DAG.getConstant(AlignIdx, dl, MVT::i32)); 8888 } else if (SVOp->isSplat()) { 8889 int SplatIdx = SVOp->getSplatIndex(); 8890 if (SplatIdx >= 4) { 8891 std::swap(V1, V2); 8892 SplatIdx -= 4; 8893 } 8894 8895 return DAG.getNode(PPCISD::QVESPLATI, dl, VT, V1, 8896 DAG.getConstant(SplatIdx, dl, MVT::i32)); 8897 } 8898 8899 // Lower this into a qvgpci/qvfperm pair. 8900 8901 // Compute the qvgpci literal 8902 unsigned idx = 0; 8903 for (unsigned i = 0; i < 4; ++i) { 8904 int m = SVOp->getMaskElt(i); 8905 unsigned mm = m >= 0 ? (unsigned) m : i; 8906 idx |= mm << (3-i)*3; 8907 } 8908 8909 SDValue V3 = DAG.getNode(PPCISD::QVGPCI, dl, MVT::v4f64, 8910 DAG.getConstant(idx, dl, MVT::i32)); 8911 return DAG.getNode(PPCISD::QVFPERM, dl, VT, V1, V2, V3); 8912 } 8913 8914 // Cases that are handled by instructions that take permute immediates 8915 // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be 8916 // selected by the instruction selector. 8917 if (V2.isUndef()) { 8918 if (PPC::isSplatShuffleMask(SVOp, 1) || 8919 PPC::isSplatShuffleMask(SVOp, 2) || 8920 PPC::isSplatShuffleMask(SVOp, 4) || 8921 PPC::isVPKUWUMShuffleMask(SVOp, 1, DAG) || 8922 PPC::isVPKUHUMShuffleMask(SVOp, 1, DAG) || 8923 PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) != -1 || 8924 PPC::isVMRGLShuffleMask(SVOp, 1, 1, DAG) || 8925 PPC::isVMRGLShuffleMask(SVOp, 2, 1, DAG) || 8926 PPC::isVMRGLShuffleMask(SVOp, 4, 1, DAG) || 8927 PPC::isVMRGHShuffleMask(SVOp, 1, 1, DAG) || 8928 PPC::isVMRGHShuffleMask(SVOp, 2, 1, DAG) || 8929 PPC::isVMRGHShuffleMask(SVOp, 4, 1, DAG) || 8930 (Subtarget.hasP8Altivec() && ( 8931 PPC::isVPKUDUMShuffleMask(SVOp, 1, DAG) || 8932 PPC::isVMRGEOShuffleMask(SVOp, true, 1, DAG) || 8933 PPC::isVMRGEOShuffleMask(SVOp, false, 1, DAG)))) { 8934 return Op; 8935 } 8936 } 8937 8938 // Altivec has a variety of "shuffle immediates" that take two vector inputs 8939 // and produce a fixed permutation. If any of these match, do not lower to 8940 // VPERM. 8941 unsigned int ShuffleKind = isLittleEndian ? 2 : 0; 8942 if (PPC::isVPKUWUMShuffleMask(SVOp, ShuffleKind, DAG) || 8943 PPC::isVPKUHUMShuffleMask(SVOp, ShuffleKind, DAG) || 8944 PPC::isVSLDOIShuffleMask(SVOp, ShuffleKind, DAG) != -1 || 8945 PPC::isVMRGLShuffleMask(SVOp, 1, ShuffleKind, DAG) || 8946 PPC::isVMRGLShuffleMask(SVOp, 2, ShuffleKind, DAG) || 8947 PPC::isVMRGLShuffleMask(SVOp, 4, ShuffleKind, DAG) || 8948 PPC::isVMRGHShuffleMask(SVOp, 1, ShuffleKind, DAG) || 8949 PPC::isVMRGHShuffleMask(SVOp, 2, ShuffleKind, DAG) || 8950 PPC::isVMRGHShuffleMask(SVOp, 4, ShuffleKind, DAG) || 8951 (Subtarget.hasP8Altivec() && ( 8952 PPC::isVPKUDUMShuffleMask(SVOp, ShuffleKind, DAG) || 8953 PPC::isVMRGEOShuffleMask(SVOp, true, ShuffleKind, DAG) || 8954 PPC::isVMRGEOShuffleMask(SVOp, false, ShuffleKind, DAG)))) 8955 return Op; 8956 8957 // Check to see if this is a shuffle of 4-byte values. If so, we can use our 8958 // perfect shuffle table to emit an optimal matching sequence. 8959 ArrayRef<int> PermMask = SVOp->getMask(); 8960 8961 unsigned PFIndexes[4]; 8962 bool isFourElementShuffle = true; 8963 for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number 8964 unsigned EltNo = 8; // Start out undef. 8965 for (unsigned j = 0; j != 4; ++j) { // Intra-element byte. 8966 if (PermMask[i*4+j] < 0) 8967 continue; // Undef, ignore it. 8968 8969 unsigned ByteSource = PermMask[i*4+j]; 8970 if ((ByteSource & 3) != j) { 8971 isFourElementShuffle = false; 8972 break; 8973 } 8974 8975 if (EltNo == 8) { 8976 EltNo = ByteSource/4; 8977 } else if (EltNo != ByteSource/4) { 8978 isFourElementShuffle = false; 8979 break; 8980 } 8981 } 8982 PFIndexes[i] = EltNo; 8983 } 8984 8985 // If this shuffle can be expressed as a shuffle of 4-byte elements, use the 8986 // perfect shuffle vector to determine if it is cost effective to do this as 8987 // discrete instructions, or whether we should use a vperm. 8988 // For now, we skip this for little endian until such time as we have a 8989 // little-endian perfect shuffle table. 8990 if (isFourElementShuffle && !isLittleEndian) { 8991 // Compute the index in the perfect shuffle table. 8992 unsigned PFTableIndex = 8993 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3]; 8994 8995 unsigned PFEntry = PerfectShuffleTable[PFTableIndex]; 8996 unsigned Cost = (PFEntry >> 30); 8997 8998 // Determining when to avoid vperm is tricky. Many things affect the cost 8999 // of vperm, particularly how many times the perm mask needs to be computed. 9000 // For example, if the perm mask can be hoisted out of a loop or is already 9001 // used (perhaps because there are multiple permutes with the same shuffle 9002 // mask?) the vperm has a cost of 1. OTOH, hoisting the permute mask out of 9003 // the loop requires an extra register. 9004 // 9005 // As a compromise, we only emit discrete instructions if the shuffle can be 9006 // generated in 3 or fewer operations. When we have loop information 9007 // available, if this block is within a loop, we should avoid using vperm 9008 // for 3-operation perms and use a constant pool load instead. 9009 if (Cost < 3) 9010 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl); 9011 } 9012 9013 // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant 9014 // vector that will get spilled to the constant pool. 9015 if (V2.isUndef()) V2 = V1; 9016 9017 // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except 9018 // that it is in input element units, not in bytes. Convert now. 9019 9020 // For little endian, the order of the input vectors is reversed, and 9021 // the permutation mask is complemented with respect to 31. This is 9022 // necessary to produce proper semantics with the big-endian-biased vperm 9023 // instruction. 9024 EVT EltVT = V1.getValueType().getVectorElementType(); 9025 unsigned BytesPerElement = EltVT.getSizeInBits()/8; 9026 9027 SmallVector<SDValue, 16> ResultMask; 9028 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) { 9029 unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i]; 9030 9031 for (unsigned j = 0; j != BytesPerElement; ++j) 9032 if (isLittleEndian) 9033 ResultMask.push_back(DAG.getConstant(31 - (SrcElt*BytesPerElement + j), 9034 dl, MVT::i32)); 9035 else 9036 ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement + j, dl, 9037 MVT::i32)); 9038 } 9039 9040 SDValue VPermMask = DAG.getBuildVector(MVT::v16i8, dl, ResultMask); 9041 if (isLittleEndian) 9042 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(), 9043 V2, V1, VPermMask); 9044 else 9045 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(), 9046 V1, V2, VPermMask); 9047 } 9048 9049 /// getVectorCompareInfo - Given an intrinsic, return false if it is not a 9050 /// vector comparison. If it is, return true and fill in Opc/isDot with 9051 /// information about the intrinsic. 9052 static bool getVectorCompareInfo(SDValue Intrin, int &CompareOpc, 9053 bool &isDot, const PPCSubtarget &Subtarget) { 9054 unsigned IntrinsicID = 9055 cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue(); 9056 CompareOpc = -1; 9057 isDot = false; 9058 switch (IntrinsicID) { 9059 default: 9060 return false; 9061 // Comparison predicates. 9062 case Intrinsic::ppc_altivec_vcmpbfp_p: 9063 CompareOpc = 966; 9064 isDot = true; 9065 break; 9066 case Intrinsic::ppc_altivec_vcmpeqfp_p: 9067 CompareOpc = 198; 9068 isDot = true; 9069 break; 9070 case Intrinsic::ppc_altivec_vcmpequb_p: 9071 CompareOpc = 6; 9072 isDot = true; 9073 break; 9074 case Intrinsic::ppc_altivec_vcmpequh_p: 9075 CompareOpc = 70; 9076 isDot = true; 9077 break; 9078 case Intrinsic::ppc_altivec_vcmpequw_p: 9079 CompareOpc = 134; 9080 isDot = true; 9081 break; 9082 case Intrinsic::ppc_altivec_vcmpequd_p: 9083 if (Subtarget.hasP8Altivec()) { 9084 CompareOpc = 199; 9085 isDot = true; 9086 } else 9087 return false; 9088 break; 9089 case Intrinsic::ppc_altivec_vcmpneb_p: 9090 case Intrinsic::ppc_altivec_vcmpneh_p: 9091 case Intrinsic::ppc_altivec_vcmpnew_p: 9092 case Intrinsic::ppc_altivec_vcmpnezb_p: 9093 case Intrinsic::ppc_altivec_vcmpnezh_p: 9094 case Intrinsic::ppc_altivec_vcmpnezw_p: 9095 if (Subtarget.hasP9Altivec()) { 9096 switch (IntrinsicID) { 9097 default: 9098 llvm_unreachable("Unknown comparison intrinsic."); 9099 case Intrinsic::ppc_altivec_vcmpneb_p: 9100 CompareOpc = 7; 9101 break; 9102 case Intrinsic::ppc_altivec_vcmpneh_p: 9103 CompareOpc = 71; 9104 break; 9105 case Intrinsic::ppc_altivec_vcmpnew_p: 9106 CompareOpc = 135; 9107 break; 9108 case Intrinsic::ppc_altivec_vcmpnezb_p: 9109 CompareOpc = 263; 9110 break; 9111 case Intrinsic::ppc_altivec_vcmpnezh_p: 9112 CompareOpc = 327; 9113 break; 9114 case Intrinsic::ppc_altivec_vcmpnezw_p: 9115 CompareOpc = 391; 9116 break; 9117 } 9118 isDot = true; 9119 } else 9120 return false; 9121 break; 9122 case Intrinsic::ppc_altivec_vcmpgefp_p: 9123 CompareOpc = 454; 9124 isDot = true; 9125 break; 9126 case Intrinsic::ppc_altivec_vcmpgtfp_p: 9127 CompareOpc = 710; 9128 isDot = true; 9129 break; 9130 case Intrinsic::ppc_altivec_vcmpgtsb_p: 9131 CompareOpc = 774; 9132 isDot = true; 9133 break; 9134 case Intrinsic::ppc_altivec_vcmpgtsh_p: 9135 CompareOpc = 838; 9136 isDot = true; 9137 break; 9138 case Intrinsic::ppc_altivec_vcmpgtsw_p: 9139 CompareOpc = 902; 9140 isDot = true; 9141 break; 9142 case Intrinsic::ppc_altivec_vcmpgtsd_p: 9143 if (Subtarget.hasP8Altivec()) { 9144 CompareOpc = 967; 9145 isDot = true; 9146 } else 9147 return false; 9148 break; 9149 case Intrinsic::ppc_altivec_vcmpgtub_p: 9150 CompareOpc = 518; 9151 isDot = true; 9152 break; 9153 case Intrinsic::ppc_altivec_vcmpgtuh_p: 9154 CompareOpc = 582; 9155 isDot = true; 9156 break; 9157 case Intrinsic::ppc_altivec_vcmpgtuw_p: 9158 CompareOpc = 646; 9159 isDot = true; 9160 break; 9161 case Intrinsic::ppc_altivec_vcmpgtud_p: 9162 if (Subtarget.hasP8Altivec()) { 9163 CompareOpc = 711; 9164 isDot = true; 9165 } else 9166 return false; 9167 break; 9168 9169 // VSX predicate comparisons use the same infrastructure 9170 case Intrinsic::ppc_vsx_xvcmpeqdp_p: 9171 case Intrinsic::ppc_vsx_xvcmpgedp_p: 9172 case Intrinsic::ppc_vsx_xvcmpgtdp_p: 9173 case Intrinsic::ppc_vsx_xvcmpeqsp_p: 9174 case Intrinsic::ppc_vsx_xvcmpgesp_p: 9175 case Intrinsic::ppc_vsx_xvcmpgtsp_p: 9176 if (Subtarget.hasVSX()) { 9177 switch (IntrinsicID) { 9178 case Intrinsic::ppc_vsx_xvcmpeqdp_p: 9179 CompareOpc = 99; 9180 break; 9181 case Intrinsic::ppc_vsx_xvcmpgedp_p: 9182 CompareOpc = 115; 9183 break; 9184 case Intrinsic::ppc_vsx_xvcmpgtdp_p: 9185 CompareOpc = 107; 9186 break; 9187 case Intrinsic::ppc_vsx_xvcmpeqsp_p: 9188 CompareOpc = 67; 9189 break; 9190 case Intrinsic::ppc_vsx_xvcmpgesp_p: 9191 CompareOpc = 83; 9192 break; 9193 case Intrinsic::ppc_vsx_xvcmpgtsp_p: 9194 CompareOpc = 75; 9195 break; 9196 } 9197 isDot = true; 9198 } else 9199 return false; 9200 break; 9201 9202 // Normal Comparisons. 9203 case Intrinsic::ppc_altivec_vcmpbfp: 9204 CompareOpc = 966; 9205 break; 9206 case Intrinsic::ppc_altivec_vcmpeqfp: 9207 CompareOpc = 198; 9208 break; 9209 case Intrinsic::ppc_altivec_vcmpequb: 9210 CompareOpc = 6; 9211 break; 9212 case Intrinsic::ppc_altivec_vcmpequh: 9213 CompareOpc = 70; 9214 break; 9215 case Intrinsic::ppc_altivec_vcmpequw: 9216 CompareOpc = 134; 9217 break; 9218 case Intrinsic::ppc_altivec_vcmpequd: 9219 if (Subtarget.hasP8Altivec()) 9220 CompareOpc = 199; 9221 else 9222 return false; 9223 break; 9224 case Intrinsic::ppc_altivec_vcmpneb: 9225 case Intrinsic::ppc_altivec_vcmpneh: 9226 case Intrinsic::ppc_altivec_vcmpnew: 9227 case Intrinsic::ppc_altivec_vcmpnezb: 9228 case Intrinsic::ppc_altivec_vcmpnezh: 9229 case Intrinsic::ppc_altivec_vcmpnezw: 9230 if (Subtarget.hasP9Altivec()) 9231 switch (IntrinsicID) { 9232 default: 9233 llvm_unreachable("Unknown comparison intrinsic."); 9234 case Intrinsic::ppc_altivec_vcmpneb: 9235 CompareOpc = 7; 9236 break; 9237 case Intrinsic::ppc_altivec_vcmpneh: 9238 CompareOpc = 71; 9239 break; 9240 case Intrinsic::ppc_altivec_vcmpnew: 9241 CompareOpc = 135; 9242 break; 9243 case Intrinsic::ppc_altivec_vcmpnezb: 9244 CompareOpc = 263; 9245 break; 9246 case Intrinsic::ppc_altivec_vcmpnezh: 9247 CompareOpc = 327; 9248 break; 9249 case Intrinsic::ppc_altivec_vcmpnezw: 9250 CompareOpc = 391; 9251 break; 9252 } 9253 else 9254 return false; 9255 break; 9256 case Intrinsic::ppc_altivec_vcmpgefp: 9257 CompareOpc = 454; 9258 break; 9259 case Intrinsic::ppc_altivec_vcmpgtfp: 9260 CompareOpc = 710; 9261 break; 9262 case Intrinsic::ppc_altivec_vcmpgtsb: 9263 CompareOpc = 774; 9264 break; 9265 case Intrinsic::ppc_altivec_vcmpgtsh: 9266 CompareOpc = 838; 9267 break; 9268 case Intrinsic::ppc_altivec_vcmpgtsw: 9269 CompareOpc = 902; 9270 break; 9271 case Intrinsic::ppc_altivec_vcmpgtsd: 9272 if (Subtarget.hasP8Altivec()) 9273 CompareOpc = 967; 9274 else 9275 return false; 9276 break; 9277 case Intrinsic::ppc_altivec_vcmpgtub: 9278 CompareOpc = 518; 9279 break; 9280 case Intrinsic::ppc_altivec_vcmpgtuh: 9281 CompareOpc = 582; 9282 break; 9283 case Intrinsic::ppc_altivec_vcmpgtuw: 9284 CompareOpc = 646; 9285 break; 9286 case Intrinsic::ppc_altivec_vcmpgtud: 9287 if (Subtarget.hasP8Altivec()) 9288 CompareOpc = 711; 9289 else 9290 return false; 9291 break; 9292 } 9293 return true; 9294 } 9295 9296 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom 9297 /// lower, do it, otherwise return null. 9298 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 9299 SelectionDAG &DAG) const { 9300 unsigned IntrinsicID = 9301 cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 9302 9303 SDLoc dl(Op); 9304 9305 if (IntrinsicID == Intrinsic::thread_pointer) { 9306 // Reads the thread pointer register, used for __builtin_thread_pointer. 9307 if (Subtarget.isPPC64()) 9308 return DAG.getRegister(PPC::X13, MVT::i64); 9309 return DAG.getRegister(PPC::R2, MVT::i32); 9310 } 9311 9312 // If this is a lowered altivec predicate compare, CompareOpc is set to the 9313 // opcode number of the comparison. 9314 int CompareOpc; 9315 bool isDot; 9316 if (!getVectorCompareInfo(Op, CompareOpc, isDot, Subtarget)) 9317 return SDValue(); // Don't custom lower most intrinsics. 9318 9319 // If this is a non-dot comparison, make the VCMP node and we are done. 9320 if (!isDot) { 9321 SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(), 9322 Op.getOperand(1), Op.getOperand(2), 9323 DAG.getConstant(CompareOpc, dl, MVT::i32)); 9324 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp); 9325 } 9326 9327 // Create the PPCISD altivec 'dot' comparison node. 9328 SDValue Ops[] = { 9329 Op.getOperand(2), // LHS 9330 Op.getOperand(3), // RHS 9331 DAG.getConstant(CompareOpc, dl, MVT::i32) 9332 }; 9333 EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue }; 9334 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops); 9335 9336 // Now that we have the comparison, emit a copy from the CR to a GPR. 9337 // This is flagged to the above dot comparison. 9338 SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32, 9339 DAG.getRegister(PPC::CR6, MVT::i32), 9340 CompNode.getValue(1)); 9341 9342 // Unpack the result based on how the target uses it. 9343 unsigned BitNo; // Bit # of CR6. 9344 bool InvertBit; // Invert result? 9345 switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) { 9346 default: // Can't happen, don't crash on invalid number though. 9347 case 0: // Return the value of the EQ bit of CR6. 9348 BitNo = 0; InvertBit = false; 9349 break; 9350 case 1: // Return the inverted value of the EQ bit of CR6. 9351 BitNo = 0; InvertBit = true; 9352 break; 9353 case 2: // Return the value of the LT bit of CR6. 9354 BitNo = 2; InvertBit = false; 9355 break; 9356 case 3: // Return the inverted value of the LT bit of CR6. 9357 BitNo = 2; InvertBit = true; 9358 break; 9359 } 9360 9361 // Shift the bit into the low position. 9362 Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags, 9363 DAG.getConstant(8 - (3 - BitNo), dl, MVT::i32)); 9364 // Isolate the bit. 9365 Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags, 9366 DAG.getConstant(1, dl, MVT::i32)); 9367 9368 // If we are supposed to, toggle the bit. 9369 if (InvertBit) 9370 Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags, 9371 DAG.getConstant(1, dl, MVT::i32)); 9372 return Flags; 9373 } 9374 9375 SDValue PPCTargetLowering::LowerINTRINSIC_VOID(SDValue Op, 9376 SelectionDAG &DAG) const { 9377 // SelectionDAGBuilder::visitTargetIntrinsic may insert one extra chain to 9378 // the beginning of the argument list. 9379 int ArgStart = isa<ConstantSDNode>(Op.getOperand(0)) ? 0 : 1; 9380 SDLoc DL(Op); 9381 switch (cast<ConstantSDNode>(Op.getOperand(ArgStart))->getZExtValue()) { 9382 case Intrinsic::ppc_cfence: { 9383 assert(ArgStart == 1 && "llvm.ppc.cfence must carry a chain argument."); 9384 assert(Subtarget.isPPC64() && "Only 64-bit is supported for now."); 9385 return SDValue(DAG.getMachineNode(PPC::CFENCE8, DL, MVT::Other, 9386 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, 9387 Op.getOperand(ArgStart + 1)), 9388 Op.getOperand(0)), 9389 0); 9390 } 9391 default: 9392 break; 9393 } 9394 return SDValue(); 9395 } 9396 9397 SDValue PPCTargetLowering::LowerREM(SDValue Op, SelectionDAG &DAG) const { 9398 // Check for a DIV with the same operands as this REM. 9399 for (auto UI : Op.getOperand(1)->uses()) { 9400 if ((Op.getOpcode() == ISD::SREM && UI->getOpcode() == ISD::SDIV) || 9401 (Op.getOpcode() == ISD::UREM && UI->getOpcode() == ISD::UDIV)) 9402 if (UI->getOperand(0) == Op.getOperand(0) && 9403 UI->getOperand(1) == Op.getOperand(1)) 9404 return SDValue(); 9405 } 9406 return Op; 9407 } 9408 9409 // Lower scalar BSWAP64 to xxbrd. 9410 SDValue PPCTargetLowering::LowerBSWAP(SDValue Op, SelectionDAG &DAG) const { 9411 SDLoc dl(Op); 9412 // MTVSRDD 9413 Op = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i64, Op.getOperand(0), 9414 Op.getOperand(0)); 9415 // XXBRD 9416 Op = DAG.getNode(PPCISD::XXREVERSE, dl, MVT::v2i64, Op); 9417 // MFVSRD 9418 int VectorIndex = 0; 9419 if (Subtarget.isLittleEndian()) 9420 VectorIndex = 1; 9421 Op = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Op, 9422 DAG.getTargetConstant(VectorIndex, dl, MVT::i32)); 9423 return Op; 9424 } 9425 9426 // ATOMIC_CMP_SWAP for i8/i16 needs to zero-extend its input since it will be 9427 // compared to a value that is atomically loaded (atomic loads zero-extend). 9428 SDValue PPCTargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, 9429 SelectionDAG &DAG) const { 9430 assert(Op.getOpcode() == ISD::ATOMIC_CMP_SWAP && 9431 "Expecting an atomic compare-and-swap here."); 9432 SDLoc dl(Op); 9433 auto *AtomicNode = cast<AtomicSDNode>(Op.getNode()); 9434 EVT MemVT = AtomicNode->getMemoryVT(); 9435 if (MemVT.getSizeInBits() >= 32) 9436 return Op; 9437 9438 SDValue CmpOp = Op.getOperand(2); 9439 // If this is already correctly zero-extended, leave it alone. 9440 auto HighBits = APInt::getHighBitsSet(32, 32 - MemVT.getSizeInBits()); 9441 if (DAG.MaskedValueIsZero(CmpOp, HighBits)) 9442 return Op; 9443 9444 // Clear the high bits of the compare operand. 9445 unsigned MaskVal = (1 << MemVT.getSizeInBits()) - 1; 9446 SDValue NewCmpOp = 9447 DAG.getNode(ISD::AND, dl, MVT::i32, CmpOp, 9448 DAG.getConstant(MaskVal, dl, MVT::i32)); 9449 9450 // Replace the existing compare operand with the properly zero-extended one. 9451 SmallVector<SDValue, 4> Ops; 9452 for (int i = 0, e = AtomicNode->getNumOperands(); i < e; i++) 9453 Ops.push_back(AtomicNode->getOperand(i)); 9454 Ops[2] = NewCmpOp; 9455 MachineMemOperand *MMO = AtomicNode->getMemOperand(); 9456 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::Other); 9457 auto NodeTy = 9458 (MemVT == MVT::i8) ? PPCISD::ATOMIC_CMP_SWAP_8 : PPCISD::ATOMIC_CMP_SWAP_16; 9459 return DAG.getMemIntrinsicNode(NodeTy, dl, Tys, Ops, MemVT, MMO); 9460 } 9461 9462 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, 9463 SelectionDAG &DAG) const { 9464 SDLoc dl(Op); 9465 // Create a stack slot that is 16-byte aligned. 9466 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 9467 int FrameIdx = MFI.CreateStackObject(16, 16, false); 9468 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 9469 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 9470 9471 // Store the input value into Value#0 of the stack slot. 9472 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx, 9473 MachinePointerInfo()); 9474 // Load it out. 9475 return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo()); 9476 } 9477 9478 SDValue PPCTargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, 9479 SelectionDAG &DAG) const { 9480 assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && 9481 "Should only be called for ISD::INSERT_VECTOR_ELT"); 9482 9483 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(2)); 9484 // We have legal lowering for constant indices but not for variable ones. 9485 if (!C) 9486 return SDValue(); 9487 9488 EVT VT = Op.getValueType(); 9489 SDLoc dl(Op); 9490 SDValue V1 = Op.getOperand(0); 9491 SDValue V2 = Op.getOperand(1); 9492 // We can use MTVSRZ + VECINSERT for v8i16 and v16i8 types. 9493 if (VT == MVT::v8i16 || VT == MVT::v16i8) { 9494 SDValue Mtvsrz = DAG.getNode(PPCISD::MTVSRZ, dl, VT, V2); 9495 unsigned BytesInEachElement = VT.getVectorElementType().getSizeInBits() / 8; 9496 unsigned InsertAtElement = C->getZExtValue(); 9497 unsigned InsertAtByte = InsertAtElement * BytesInEachElement; 9498 if (Subtarget.isLittleEndian()) { 9499 InsertAtByte = (16 - BytesInEachElement) - InsertAtByte; 9500 } 9501 return DAG.getNode(PPCISD::VECINSERT, dl, VT, V1, Mtvsrz, 9502 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9503 } 9504 return Op; 9505 } 9506 9507 SDValue PPCTargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op, 9508 SelectionDAG &DAG) const { 9509 SDLoc dl(Op); 9510 SDNode *N = Op.getNode(); 9511 9512 assert(N->getOperand(0).getValueType() == MVT::v4i1 && 9513 "Unknown extract_vector_elt type"); 9514 9515 SDValue Value = N->getOperand(0); 9516 9517 // The first part of this is like the store lowering except that we don't 9518 // need to track the chain. 9519 9520 // The values are now known to be -1 (false) or 1 (true). To convert this 9521 // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5). 9522 // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5 9523 Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value); 9524 9525 // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to 9526 // understand how to form the extending load. 9527 SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64); 9528 9529 Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs); 9530 9531 // Now convert to an integer and store. 9532 Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64, 9533 DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32), 9534 Value); 9535 9536 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 9537 int FrameIdx = MFI.CreateStackObject(16, 16, false); 9538 MachinePointerInfo PtrInfo = 9539 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 9540 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 9541 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 9542 9543 SDValue StoreChain = DAG.getEntryNode(); 9544 SDValue Ops[] = {StoreChain, 9545 DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32), 9546 Value, FIdx}; 9547 SDVTList VTs = DAG.getVTList(/*chain*/ MVT::Other); 9548 9549 StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, 9550 dl, VTs, Ops, MVT::v4i32, PtrInfo); 9551 9552 // Extract the value requested. 9553 unsigned Offset = 4*cast<ConstantSDNode>(N->getOperand(1))->getZExtValue(); 9554 SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType()); 9555 Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx); 9556 9557 SDValue IntVal = 9558 DAG.getLoad(MVT::i32, dl, StoreChain, Idx, PtrInfo.getWithOffset(Offset)); 9559 9560 if (!Subtarget.useCRBits()) 9561 return IntVal; 9562 9563 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, IntVal); 9564 } 9565 9566 /// Lowering for QPX v4i1 loads 9567 SDValue PPCTargetLowering::LowerVectorLoad(SDValue Op, 9568 SelectionDAG &DAG) const { 9569 SDLoc dl(Op); 9570 LoadSDNode *LN = cast<LoadSDNode>(Op.getNode()); 9571 SDValue LoadChain = LN->getChain(); 9572 SDValue BasePtr = LN->getBasePtr(); 9573 9574 if (Op.getValueType() == MVT::v4f64 || 9575 Op.getValueType() == MVT::v4f32) { 9576 EVT MemVT = LN->getMemoryVT(); 9577 unsigned Alignment = LN->getAlignment(); 9578 9579 // If this load is properly aligned, then it is legal. 9580 if (Alignment >= MemVT.getStoreSize()) 9581 return Op; 9582 9583 EVT ScalarVT = Op.getValueType().getScalarType(), 9584 ScalarMemVT = MemVT.getScalarType(); 9585 unsigned Stride = ScalarMemVT.getStoreSize(); 9586 9587 SDValue Vals[4], LoadChains[4]; 9588 for (unsigned Idx = 0; Idx < 4; ++Idx) { 9589 SDValue Load; 9590 if (ScalarVT != ScalarMemVT) 9591 Load = DAG.getExtLoad(LN->getExtensionType(), dl, ScalarVT, LoadChain, 9592 BasePtr, 9593 LN->getPointerInfo().getWithOffset(Idx * Stride), 9594 ScalarMemVT, MinAlign(Alignment, Idx * Stride), 9595 LN->getMemOperand()->getFlags(), LN->getAAInfo()); 9596 else 9597 Load = DAG.getLoad(ScalarVT, dl, LoadChain, BasePtr, 9598 LN->getPointerInfo().getWithOffset(Idx * Stride), 9599 MinAlign(Alignment, Idx * Stride), 9600 LN->getMemOperand()->getFlags(), LN->getAAInfo()); 9601 9602 if (Idx == 0 && LN->isIndexed()) { 9603 assert(LN->getAddressingMode() == ISD::PRE_INC && 9604 "Unknown addressing mode on vector load"); 9605 Load = DAG.getIndexedLoad(Load, dl, BasePtr, LN->getOffset(), 9606 LN->getAddressingMode()); 9607 } 9608 9609 Vals[Idx] = Load; 9610 LoadChains[Idx] = Load.getValue(1); 9611 9612 BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, 9613 DAG.getConstant(Stride, dl, 9614 BasePtr.getValueType())); 9615 } 9616 9617 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains); 9618 SDValue Value = DAG.getBuildVector(Op.getValueType(), dl, Vals); 9619 9620 if (LN->isIndexed()) { 9621 SDValue RetOps[] = { Value, Vals[0].getValue(1), TF }; 9622 return DAG.getMergeValues(RetOps, dl); 9623 } 9624 9625 SDValue RetOps[] = { Value, TF }; 9626 return DAG.getMergeValues(RetOps, dl); 9627 } 9628 9629 assert(Op.getValueType() == MVT::v4i1 && "Unknown load to lower"); 9630 assert(LN->isUnindexed() && "Indexed v4i1 loads are not supported"); 9631 9632 // To lower v4i1 from a byte array, we load the byte elements of the 9633 // vector and then reuse the BUILD_VECTOR logic. 9634 9635 SDValue VectElmts[4], VectElmtChains[4]; 9636 for (unsigned i = 0; i < 4; ++i) { 9637 SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType()); 9638 Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx); 9639 9640 VectElmts[i] = DAG.getExtLoad( 9641 ISD::EXTLOAD, dl, MVT::i32, LoadChain, Idx, 9642 LN->getPointerInfo().getWithOffset(i), MVT::i8, 9643 /* Alignment = */ 1, LN->getMemOperand()->getFlags(), LN->getAAInfo()); 9644 VectElmtChains[i] = VectElmts[i].getValue(1); 9645 } 9646 9647 LoadChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, VectElmtChains); 9648 SDValue Value = DAG.getBuildVector(MVT::v4i1, dl, VectElmts); 9649 9650 SDValue RVals[] = { Value, LoadChain }; 9651 return DAG.getMergeValues(RVals, dl); 9652 } 9653 9654 /// Lowering for QPX v4i1 stores 9655 SDValue PPCTargetLowering::LowerVectorStore(SDValue Op, 9656 SelectionDAG &DAG) const { 9657 SDLoc dl(Op); 9658 StoreSDNode *SN = cast<StoreSDNode>(Op.getNode()); 9659 SDValue StoreChain = SN->getChain(); 9660 SDValue BasePtr = SN->getBasePtr(); 9661 SDValue Value = SN->getValue(); 9662 9663 if (Value.getValueType() == MVT::v4f64 || 9664 Value.getValueType() == MVT::v4f32) { 9665 EVT MemVT = SN->getMemoryVT(); 9666 unsigned Alignment = SN->getAlignment(); 9667 9668 // If this store is properly aligned, then it is legal. 9669 if (Alignment >= MemVT.getStoreSize()) 9670 return Op; 9671 9672 EVT ScalarVT = Value.getValueType().getScalarType(), 9673 ScalarMemVT = MemVT.getScalarType(); 9674 unsigned Stride = ScalarMemVT.getStoreSize(); 9675 9676 SDValue Stores[4]; 9677 for (unsigned Idx = 0; Idx < 4; ++Idx) { 9678 SDValue Ex = DAG.getNode( 9679 ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, Value, 9680 DAG.getConstant(Idx, dl, getVectorIdxTy(DAG.getDataLayout()))); 9681 SDValue Store; 9682 if (ScalarVT != ScalarMemVT) 9683 Store = 9684 DAG.getTruncStore(StoreChain, dl, Ex, BasePtr, 9685 SN->getPointerInfo().getWithOffset(Idx * Stride), 9686 ScalarMemVT, MinAlign(Alignment, Idx * Stride), 9687 SN->getMemOperand()->getFlags(), SN->getAAInfo()); 9688 else 9689 Store = DAG.getStore(StoreChain, dl, Ex, BasePtr, 9690 SN->getPointerInfo().getWithOffset(Idx * Stride), 9691 MinAlign(Alignment, Idx * Stride), 9692 SN->getMemOperand()->getFlags(), SN->getAAInfo()); 9693 9694 if (Idx == 0 && SN->isIndexed()) { 9695 assert(SN->getAddressingMode() == ISD::PRE_INC && 9696 "Unknown addressing mode on vector store"); 9697 Store = DAG.getIndexedStore(Store, dl, BasePtr, SN->getOffset(), 9698 SN->getAddressingMode()); 9699 } 9700 9701 BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, 9702 DAG.getConstant(Stride, dl, 9703 BasePtr.getValueType())); 9704 Stores[Idx] = Store; 9705 } 9706 9707 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores); 9708 9709 if (SN->isIndexed()) { 9710 SDValue RetOps[] = { TF, Stores[0].getValue(1) }; 9711 return DAG.getMergeValues(RetOps, dl); 9712 } 9713 9714 return TF; 9715 } 9716 9717 assert(SN->isUnindexed() && "Indexed v4i1 stores are not supported"); 9718 assert(Value.getValueType() == MVT::v4i1 && "Unknown store to lower"); 9719 9720 // The values are now known to be -1 (false) or 1 (true). To convert this 9721 // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5). 9722 // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5 9723 Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value); 9724 9725 // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to 9726 // understand how to form the extending load. 9727 SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64); 9728 9729 Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs); 9730 9731 // Now convert to an integer and store. 9732 Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64, 9733 DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32), 9734 Value); 9735 9736 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 9737 int FrameIdx = MFI.CreateStackObject(16, 16, false); 9738 MachinePointerInfo PtrInfo = 9739 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 9740 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 9741 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 9742 9743 SDValue Ops[] = {StoreChain, 9744 DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32), 9745 Value, FIdx}; 9746 SDVTList VTs = DAG.getVTList(/*chain*/ MVT::Other); 9747 9748 StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, 9749 dl, VTs, Ops, MVT::v4i32, PtrInfo); 9750 9751 // Move data into the byte array. 9752 SDValue Loads[4], LoadChains[4]; 9753 for (unsigned i = 0; i < 4; ++i) { 9754 unsigned Offset = 4*i; 9755 SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType()); 9756 Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx); 9757 9758 Loads[i] = DAG.getLoad(MVT::i32, dl, StoreChain, Idx, 9759 PtrInfo.getWithOffset(Offset)); 9760 LoadChains[i] = Loads[i].getValue(1); 9761 } 9762 9763 StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains); 9764 9765 SDValue Stores[4]; 9766 for (unsigned i = 0; i < 4; ++i) { 9767 SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType()); 9768 Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx); 9769 9770 Stores[i] = DAG.getTruncStore( 9771 StoreChain, dl, Loads[i], Idx, SN->getPointerInfo().getWithOffset(i), 9772 MVT::i8, /* Alignment = */ 1, SN->getMemOperand()->getFlags(), 9773 SN->getAAInfo()); 9774 } 9775 9776 StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores); 9777 9778 return StoreChain; 9779 } 9780 9781 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const { 9782 SDLoc dl(Op); 9783 if (Op.getValueType() == MVT::v4i32) { 9784 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 9785 9786 SDValue Zero = BuildSplatI( 0, 1, MVT::v4i32, DAG, dl); 9787 SDValue Neg16 = BuildSplatI(-16, 4, MVT::v4i32, DAG, dl);//+16 as shift amt. 9788 9789 SDValue RHSSwap = // = vrlw RHS, 16 9790 BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl); 9791 9792 // Shrinkify inputs to v8i16. 9793 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS); 9794 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS); 9795 RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap); 9796 9797 // Low parts multiplied together, generating 32-bit results (we ignore the 9798 // top parts). 9799 SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh, 9800 LHS, RHS, DAG, dl, MVT::v4i32); 9801 9802 SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm, 9803 LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32); 9804 // Shift the high parts up 16 bits. 9805 HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd, 9806 Neg16, DAG, dl); 9807 return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd); 9808 } else if (Op.getValueType() == MVT::v8i16) { 9809 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 9810 9811 SDValue Zero = BuildSplatI(0, 1, MVT::v8i16, DAG, dl); 9812 9813 return BuildIntrinsicOp(Intrinsic::ppc_altivec_vmladduhm, 9814 LHS, RHS, Zero, DAG, dl); 9815 } else if (Op.getValueType() == MVT::v16i8) { 9816 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 9817 bool isLittleEndian = Subtarget.isLittleEndian(); 9818 9819 // Multiply the even 8-bit parts, producing 16-bit sums. 9820 SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub, 9821 LHS, RHS, DAG, dl, MVT::v8i16); 9822 EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts); 9823 9824 // Multiply the odd 8-bit parts, producing 16-bit sums. 9825 SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub, 9826 LHS, RHS, DAG, dl, MVT::v8i16); 9827 OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts); 9828 9829 // Merge the results together. Because vmuleub and vmuloub are 9830 // instructions with a big-endian bias, we must reverse the 9831 // element numbering and reverse the meaning of "odd" and "even" 9832 // when generating little endian code. 9833 int Ops[16]; 9834 for (unsigned i = 0; i != 8; ++i) { 9835 if (isLittleEndian) { 9836 Ops[i*2 ] = 2*i; 9837 Ops[i*2+1] = 2*i+16; 9838 } else { 9839 Ops[i*2 ] = 2*i+1; 9840 Ops[i*2+1] = 2*i+1+16; 9841 } 9842 } 9843 if (isLittleEndian) 9844 return DAG.getVectorShuffle(MVT::v16i8, dl, OddParts, EvenParts, Ops); 9845 else 9846 return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops); 9847 } else { 9848 llvm_unreachable("Unknown mul to lower!"); 9849 } 9850 } 9851 9852 SDValue PPCTargetLowering::LowerABS(SDValue Op, SelectionDAG &DAG) const { 9853 9854 assert(Op.getOpcode() == ISD::ABS && "Should only be called for ISD::ABS"); 9855 9856 EVT VT = Op.getValueType(); 9857 assert(VT.isVector() && 9858 "Only set vector abs as custom, scalar abs shouldn't reach here!"); 9859 assert((VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 || 9860 VT == MVT::v16i8) && 9861 "Unexpected vector element type!"); 9862 assert((VT != MVT::v2i64 || Subtarget.hasP8Altivec()) && 9863 "Current subtarget doesn't support smax v2i64!"); 9864 9865 // For vector abs, it can be lowered to: 9866 // abs x 9867 // ==> 9868 // y = -x 9869 // smax(x, y) 9870 9871 SDLoc dl(Op); 9872 SDValue X = Op.getOperand(0); 9873 SDValue Zero = DAG.getConstant(0, dl, VT); 9874 SDValue Y = DAG.getNode(ISD::SUB, dl, VT, Zero, X); 9875 9876 // SMAX patch https://reviews.llvm.org/D47332 9877 // hasn't landed yet, so use intrinsic first here. 9878 // TODO: Should use SMAX directly once SMAX patch landed 9879 Intrinsic::ID BifID = Intrinsic::ppc_altivec_vmaxsw; 9880 if (VT == MVT::v2i64) 9881 BifID = Intrinsic::ppc_altivec_vmaxsd; 9882 else if (VT == MVT::v8i16) 9883 BifID = Intrinsic::ppc_altivec_vmaxsh; 9884 else if (VT == MVT::v16i8) 9885 BifID = Intrinsic::ppc_altivec_vmaxsb; 9886 9887 return BuildIntrinsicOp(BifID, X, Y, DAG, dl, VT); 9888 } 9889 9890 // Custom lowering for fpext vf32 to v2f64 9891 SDValue PPCTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const { 9892 9893 assert(Op.getOpcode() == ISD::FP_EXTEND && 9894 "Should only be called for ISD::FP_EXTEND"); 9895 9896 // We only want to custom lower an extend from v2f32 to v2f64. 9897 if (Op.getValueType() != MVT::v2f64 || 9898 Op.getOperand(0).getValueType() != MVT::v2f32) 9899 return SDValue(); 9900 9901 SDLoc dl(Op); 9902 SDValue Op0 = Op.getOperand(0); 9903 9904 switch (Op0.getOpcode()) { 9905 default: 9906 return SDValue(); 9907 case ISD::FADD: 9908 case ISD::FMUL: 9909 case ISD::FSUB: { 9910 SDValue NewLoad[2]; 9911 for (unsigned i = 0, ie = Op0.getNumOperands(); i != ie; ++i) { 9912 // Ensure both input are loads. 9913 SDValue LdOp = Op0.getOperand(i); 9914 if (LdOp.getOpcode() != ISD::LOAD) 9915 return SDValue(); 9916 // Generate new load node. 9917 LoadSDNode *LD = cast<LoadSDNode>(LdOp); 9918 SDValue LoadOps[] = { LD->getChain(), LD->getBasePtr() }; 9919 NewLoad[i] = 9920 DAG.getMemIntrinsicNode(PPCISD::LD_VSX_LH, dl, 9921 DAG.getVTList(MVT::v4f32, MVT::Other), 9922 LoadOps, LD->getMemoryVT(), 9923 LD->getMemOperand()); 9924 } 9925 SDValue NewOp = DAG.getNode(Op0.getOpcode(), SDLoc(Op0), MVT::v4f32, 9926 NewLoad[0], NewLoad[1], 9927 Op0.getNode()->getFlags()); 9928 return DAG.getNode(PPCISD::FP_EXTEND_LH, dl, MVT::v2f64, NewOp); 9929 } 9930 case ISD::LOAD: { 9931 LoadSDNode *LD = cast<LoadSDNode>(Op0); 9932 SDValue LoadOps[] = { LD->getChain(), LD->getBasePtr() }; 9933 SDValue NewLd = 9934 DAG.getMemIntrinsicNode(PPCISD::LD_VSX_LH, dl, 9935 DAG.getVTList(MVT::v4f32, MVT::Other), 9936 LoadOps, LD->getMemoryVT(), LD->getMemOperand()); 9937 return DAG.getNode(PPCISD::FP_EXTEND_LH, dl, MVT::v2f64, NewLd); 9938 } 9939 } 9940 llvm_unreachable("ERROR:Should return for all cases within swtich."); 9941 } 9942 9943 /// LowerOperation - Provide custom lowering hooks for some operations. 9944 /// 9945 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 9946 switch (Op.getOpcode()) { 9947 default: llvm_unreachable("Wasn't expecting to be able to lower this!"); 9948 case ISD::ConstantPool: return LowerConstantPool(Op, DAG); 9949 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG); 9950 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG); 9951 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG); 9952 case ISD::JumpTable: return LowerJumpTable(Op, DAG); 9953 case ISD::SETCC: return LowerSETCC(Op, DAG); 9954 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG); 9955 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG); 9956 9957 // Variable argument lowering. 9958 case ISD::VASTART: return LowerVASTART(Op, DAG); 9959 case ISD::VAARG: return LowerVAARG(Op, DAG); 9960 case ISD::VACOPY: return LowerVACOPY(Op, DAG); 9961 9962 case ISD::STACKRESTORE: return LowerSTACKRESTORE(Op, DAG); 9963 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG); 9964 case ISD::GET_DYNAMIC_AREA_OFFSET: 9965 return LowerGET_DYNAMIC_AREA_OFFSET(Op, DAG); 9966 9967 // Exception handling lowering. 9968 case ISD::EH_DWARF_CFA: return LowerEH_DWARF_CFA(Op, DAG); 9969 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG); 9970 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG); 9971 9972 case ISD::LOAD: return LowerLOAD(Op, DAG); 9973 case ISD::STORE: return LowerSTORE(Op, DAG); 9974 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG); 9975 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG); 9976 case ISD::FP_TO_UINT: 9977 case ISD::FP_TO_SINT: return LowerFP_TO_INT(Op, DAG, SDLoc(Op)); 9978 case ISD::UINT_TO_FP: 9979 case ISD::SINT_TO_FP: return LowerINT_TO_FP(Op, DAG); 9980 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG); 9981 9982 // Lower 64-bit shifts. 9983 case ISD::SHL_PARTS: return LowerSHL_PARTS(Op, DAG); 9984 case ISD::SRL_PARTS: return LowerSRL_PARTS(Op, DAG); 9985 case ISD::SRA_PARTS: return LowerSRA_PARTS(Op, DAG); 9986 9987 // Vector-related lowering. 9988 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG); 9989 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG); 9990 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG); 9991 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG); 9992 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG); 9993 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG); 9994 case ISD::MUL: return LowerMUL(Op, DAG); 9995 case ISD::ABS: return LowerABS(Op, DAG); 9996 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG); 9997 9998 // For counter-based loop handling. 9999 case ISD::INTRINSIC_W_CHAIN: return SDValue(); 10000 10001 case ISD::BITCAST: return LowerBITCAST(Op, DAG); 10002 10003 // Frame & Return address. 10004 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG); 10005 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG); 10006 10007 case ISD::INTRINSIC_VOID: 10008 return LowerINTRINSIC_VOID(Op, DAG); 10009 case ISD::SREM: 10010 case ISD::UREM: 10011 return LowerREM(Op, DAG); 10012 case ISD::BSWAP: 10013 return LowerBSWAP(Op, DAG); 10014 case ISD::ATOMIC_CMP_SWAP: 10015 return LowerATOMIC_CMP_SWAP(Op, DAG); 10016 } 10017 } 10018 10019 void PPCTargetLowering::ReplaceNodeResults(SDNode *N, 10020 SmallVectorImpl<SDValue>&Results, 10021 SelectionDAG &DAG) const { 10022 SDLoc dl(N); 10023 switch (N->getOpcode()) { 10024 default: 10025 llvm_unreachable("Do not know how to custom type legalize this operation!"); 10026 case ISD::READCYCLECOUNTER: { 10027 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other); 10028 SDValue RTB = DAG.getNode(PPCISD::READ_TIME_BASE, dl, VTs, N->getOperand(0)); 10029 10030 Results.push_back(RTB); 10031 Results.push_back(RTB.getValue(1)); 10032 Results.push_back(RTB.getValue(2)); 10033 break; 10034 } 10035 case ISD::INTRINSIC_W_CHAIN: { 10036 if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 10037 Intrinsic::loop_decrement) 10038 break; 10039 10040 assert(N->getValueType(0) == MVT::i1 && 10041 "Unexpected result type for CTR decrement intrinsic"); 10042 EVT SVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 10043 N->getValueType(0)); 10044 SDVTList VTs = DAG.getVTList(SVT, MVT::Other); 10045 SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0), 10046 N->getOperand(1)); 10047 10048 Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewInt)); 10049 Results.push_back(NewInt.getValue(1)); 10050 break; 10051 } 10052 case ISD::VAARG: { 10053 if (!Subtarget.isSVR4ABI() || Subtarget.isPPC64()) 10054 return; 10055 10056 EVT VT = N->getValueType(0); 10057 10058 if (VT == MVT::i64) { 10059 SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG); 10060 10061 Results.push_back(NewNode); 10062 Results.push_back(NewNode.getValue(1)); 10063 } 10064 return; 10065 } 10066 case ISD::FP_TO_SINT: 10067 case ISD::FP_TO_UINT: 10068 // LowerFP_TO_INT() can only handle f32 and f64. 10069 if (N->getOperand(0).getValueType() == MVT::ppcf128) 10070 return; 10071 Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl)); 10072 return; 10073 case ISD::TRUNCATE: { 10074 EVT TrgVT = N->getValueType(0); 10075 EVT OpVT = N->getOperand(0).getValueType(); 10076 if (TrgVT.isVector() && 10077 isOperationCustom(N->getOpcode(), TrgVT) && 10078 OpVT.getSizeInBits() <= 128 && 10079 isPowerOf2_32(OpVT.getVectorElementType().getSizeInBits())) 10080 Results.push_back(LowerTRUNCATEVector(SDValue(N, 0), DAG)); 10081 return; 10082 } 10083 case ISD::BITCAST: 10084 // Don't handle bitcast here. 10085 return; 10086 } 10087 } 10088 10089 //===----------------------------------------------------------------------===// 10090 // Other Lowering Code 10091 //===----------------------------------------------------------------------===// 10092 10093 static Instruction* callIntrinsic(IRBuilder<> &Builder, Intrinsic::ID Id) { 10094 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 10095 Function *Func = Intrinsic::getDeclaration(M, Id); 10096 return Builder.CreateCall(Func, {}); 10097 } 10098 10099 // The mappings for emitLeading/TrailingFence is taken from 10100 // http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html 10101 Instruction *PPCTargetLowering::emitLeadingFence(IRBuilder<> &Builder, 10102 Instruction *Inst, 10103 AtomicOrdering Ord) const { 10104 if (Ord == AtomicOrdering::SequentiallyConsistent) 10105 return callIntrinsic(Builder, Intrinsic::ppc_sync); 10106 if (isReleaseOrStronger(Ord)) 10107 return callIntrinsic(Builder, Intrinsic::ppc_lwsync); 10108 return nullptr; 10109 } 10110 10111 Instruction *PPCTargetLowering::emitTrailingFence(IRBuilder<> &Builder, 10112 Instruction *Inst, 10113 AtomicOrdering Ord) const { 10114 if (Inst->hasAtomicLoad() && isAcquireOrStronger(Ord)) { 10115 // See http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html and 10116 // http://www.rdrop.com/users/paulmck/scalability/paper/N2745r.2011.03.04a.html 10117 // and http://www.cl.cam.ac.uk/~pes20/cppppc/ for justification. 10118 if (isa<LoadInst>(Inst) && Subtarget.isPPC64()) 10119 return Builder.CreateCall( 10120 Intrinsic::getDeclaration( 10121 Builder.GetInsertBlock()->getParent()->getParent(), 10122 Intrinsic::ppc_cfence, {Inst->getType()}), 10123 {Inst}); 10124 // FIXME: Can use isync for rmw operation. 10125 return callIntrinsic(Builder, Intrinsic::ppc_lwsync); 10126 } 10127 return nullptr; 10128 } 10129 10130 MachineBasicBlock * 10131 PPCTargetLowering::EmitAtomicBinary(MachineInstr &MI, MachineBasicBlock *BB, 10132 unsigned AtomicSize, 10133 unsigned BinOpcode, 10134 unsigned CmpOpcode, 10135 unsigned CmpPred) const { 10136 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0. 10137 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 10138 10139 auto LoadMnemonic = PPC::LDARX; 10140 auto StoreMnemonic = PPC::STDCX; 10141 switch (AtomicSize) { 10142 default: 10143 llvm_unreachable("Unexpected size of atomic entity"); 10144 case 1: 10145 LoadMnemonic = PPC::LBARX; 10146 StoreMnemonic = PPC::STBCX; 10147 assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4"); 10148 break; 10149 case 2: 10150 LoadMnemonic = PPC::LHARX; 10151 StoreMnemonic = PPC::STHCX; 10152 assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4"); 10153 break; 10154 case 4: 10155 LoadMnemonic = PPC::LWARX; 10156 StoreMnemonic = PPC::STWCX; 10157 break; 10158 case 8: 10159 LoadMnemonic = PPC::LDARX; 10160 StoreMnemonic = PPC::STDCX; 10161 break; 10162 } 10163 10164 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 10165 MachineFunction *F = BB->getParent(); 10166 MachineFunction::iterator It = ++BB->getIterator(); 10167 10168 Register dest = MI.getOperand(0).getReg(); 10169 Register ptrA = MI.getOperand(1).getReg(); 10170 Register ptrB = MI.getOperand(2).getReg(); 10171 Register incr = MI.getOperand(3).getReg(); 10172 DebugLoc dl = MI.getDebugLoc(); 10173 10174 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB); 10175 MachineBasicBlock *loop2MBB = 10176 CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr; 10177 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 10178 F->insert(It, loopMBB); 10179 if (CmpOpcode) 10180 F->insert(It, loop2MBB); 10181 F->insert(It, exitMBB); 10182 exitMBB->splice(exitMBB->begin(), BB, 10183 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 10184 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 10185 10186 MachineRegisterInfo &RegInfo = F->getRegInfo(); 10187 Register TmpReg = (!BinOpcode) ? incr : 10188 RegInfo.createVirtualRegister( AtomicSize == 8 ? &PPC::G8RCRegClass 10189 : &PPC::GPRCRegClass); 10190 10191 // thisMBB: 10192 // ... 10193 // fallthrough --> loopMBB 10194 BB->addSuccessor(loopMBB); 10195 10196 // loopMBB: 10197 // l[wd]arx dest, ptr 10198 // add r0, dest, incr 10199 // st[wd]cx. r0, ptr 10200 // bne- loopMBB 10201 // fallthrough --> exitMBB 10202 10203 // For max/min... 10204 // loopMBB: 10205 // l[wd]arx dest, ptr 10206 // cmpl?[wd] incr, dest 10207 // bgt exitMBB 10208 // loop2MBB: 10209 // st[wd]cx. dest, ptr 10210 // bne- loopMBB 10211 // fallthrough --> exitMBB 10212 10213 BB = loopMBB; 10214 BuildMI(BB, dl, TII->get(LoadMnemonic), dest) 10215 .addReg(ptrA).addReg(ptrB); 10216 if (BinOpcode) 10217 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest); 10218 if (CmpOpcode) { 10219 // Signed comparisons of byte or halfword values must be sign-extended. 10220 if (CmpOpcode == PPC::CMPW && AtomicSize < 4) { 10221 unsigned ExtReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass); 10222 BuildMI(BB, dl, TII->get(AtomicSize == 1 ? PPC::EXTSB : PPC::EXTSH), 10223 ExtReg).addReg(dest); 10224 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0) 10225 .addReg(incr).addReg(ExtReg); 10226 } else 10227 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0) 10228 .addReg(incr).addReg(dest); 10229 10230 BuildMI(BB, dl, TII->get(PPC::BCC)) 10231 .addImm(CmpPred).addReg(PPC::CR0).addMBB(exitMBB); 10232 BB->addSuccessor(loop2MBB); 10233 BB->addSuccessor(exitMBB); 10234 BB = loop2MBB; 10235 } 10236 BuildMI(BB, dl, TII->get(StoreMnemonic)) 10237 .addReg(TmpReg).addReg(ptrA).addReg(ptrB); 10238 BuildMI(BB, dl, TII->get(PPC::BCC)) 10239 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB); 10240 BB->addSuccessor(loopMBB); 10241 BB->addSuccessor(exitMBB); 10242 10243 // exitMBB: 10244 // ... 10245 BB = exitMBB; 10246 return BB; 10247 } 10248 10249 MachineBasicBlock *PPCTargetLowering::EmitPartwordAtomicBinary( 10250 MachineInstr &MI, MachineBasicBlock *BB, 10251 bool is8bit, // operation 10252 unsigned BinOpcode, unsigned CmpOpcode, unsigned CmpPred) const { 10253 // If we support part-word atomic mnemonics, just use them 10254 if (Subtarget.hasPartwordAtomics()) 10255 return EmitAtomicBinary(MI, BB, is8bit ? 1 : 2, BinOpcode, CmpOpcode, 10256 CmpPred); 10257 10258 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0. 10259 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 10260 // In 64 bit mode we have to use 64 bits for addresses, even though the 10261 // lwarx/stwcx are 32 bits. With the 32-bit atomics we can use address 10262 // registers without caring whether they're 32 or 64, but here we're 10263 // doing actual arithmetic on the addresses. 10264 bool is64bit = Subtarget.isPPC64(); 10265 bool isLittleEndian = Subtarget.isLittleEndian(); 10266 unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO; 10267 10268 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 10269 MachineFunction *F = BB->getParent(); 10270 MachineFunction::iterator It = ++BB->getIterator(); 10271 10272 unsigned dest = MI.getOperand(0).getReg(); 10273 unsigned ptrA = MI.getOperand(1).getReg(); 10274 unsigned ptrB = MI.getOperand(2).getReg(); 10275 unsigned incr = MI.getOperand(3).getReg(); 10276 DebugLoc dl = MI.getDebugLoc(); 10277 10278 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB); 10279 MachineBasicBlock *loop2MBB = 10280 CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr; 10281 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 10282 F->insert(It, loopMBB); 10283 if (CmpOpcode) 10284 F->insert(It, loop2MBB); 10285 F->insert(It, exitMBB); 10286 exitMBB->splice(exitMBB->begin(), BB, 10287 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 10288 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 10289 10290 MachineRegisterInfo &RegInfo = F->getRegInfo(); 10291 const TargetRegisterClass *RC = 10292 is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 10293 const TargetRegisterClass *GPRC = &PPC::GPRCRegClass; 10294 10295 Register PtrReg = RegInfo.createVirtualRegister(RC); 10296 Register Shift1Reg = RegInfo.createVirtualRegister(GPRC); 10297 Register ShiftReg = 10298 isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC); 10299 Register Incr2Reg = RegInfo.createVirtualRegister(GPRC); 10300 Register MaskReg = RegInfo.createVirtualRegister(GPRC); 10301 Register Mask2Reg = RegInfo.createVirtualRegister(GPRC); 10302 Register Mask3Reg = RegInfo.createVirtualRegister(GPRC); 10303 Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC); 10304 Register Tmp3Reg = RegInfo.createVirtualRegister(GPRC); 10305 Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC); 10306 Register TmpDestReg = RegInfo.createVirtualRegister(GPRC); 10307 Register Ptr1Reg; 10308 Register TmpReg = 10309 (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(GPRC); 10310 10311 // thisMBB: 10312 // ... 10313 // fallthrough --> loopMBB 10314 BB->addSuccessor(loopMBB); 10315 10316 // The 4-byte load must be aligned, while a char or short may be 10317 // anywhere in the word. Hence all this nasty bookkeeping code. 10318 // add ptr1, ptrA, ptrB [copy if ptrA==0] 10319 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27] 10320 // xori shift, shift1, 24 [16] 10321 // rlwinm ptr, ptr1, 0, 0, 29 10322 // slw incr2, incr, shift 10323 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535] 10324 // slw mask, mask2, shift 10325 // loopMBB: 10326 // lwarx tmpDest, ptr 10327 // add tmp, tmpDest, incr2 10328 // andc tmp2, tmpDest, mask 10329 // and tmp3, tmp, mask 10330 // or tmp4, tmp3, tmp2 10331 // stwcx. tmp4, ptr 10332 // bne- loopMBB 10333 // fallthrough --> exitMBB 10334 // srw dest, tmpDest, shift 10335 if (ptrA != ZeroReg) { 10336 Ptr1Reg = RegInfo.createVirtualRegister(RC); 10337 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg) 10338 .addReg(ptrA) 10339 .addReg(ptrB); 10340 } else { 10341 Ptr1Reg = ptrB; 10342 } 10343 // We need use 32-bit subregister to avoid mismatch register class in 64-bit 10344 // mode. 10345 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg) 10346 .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0) 10347 .addImm(3) 10348 .addImm(27) 10349 .addImm(is8bit ? 28 : 27); 10350 if (!isLittleEndian) 10351 BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg) 10352 .addReg(Shift1Reg) 10353 .addImm(is8bit ? 24 : 16); 10354 if (is64bit) 10355 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg) 10356 .addReg(Ptr1Reg) 10357 .addImm(0) 10358 .addImm(61); 10359 else 10360 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg) 10361 .addReg(Ptr1Reg) 10362 .addImm(0) 10363 .addImm(0) 10364 .addImm(29); 10365 BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg).addReg(incr).addReg(ShiftReg); 10366 if (is8bit) 10367 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255); 10368 else { 10369 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0); 10370 BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg) 10371 .addReg(Mask3Reg) 10372 .addImm(65535); 10373 } 10374 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg) 10375 .addReg(Mask2Reg) 10376 .addReg(ShiftReg); 10377 10378 BB = loopMBB; 10379 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg) 10380 .addReg(ZeroReg) 10381 .addReg(PtrReg); 10382 if (BinOpcode) 10383 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg) 10384 .addReg(Incr2Reg) 10385 .addReg(TmpDestReg); 10386 BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg) 10387 .addReg(TmpDestReg) 10388 .addReg(MaskReg); 10389 BuildMI(BB, dl, TII->get(PPC::AND), Tmp3Reg).addReg(TmpReg).addReg(MaskReg); 10390 if (CmpOpcode) { 10391 // For unsigned comparisons, we can directly compare the shifted values. 10392 // For signed comparisons we shift and sign extend. 10393 unsigned SReg = RegInfo.createVirtualRegister(GPRC); 10394 BuildMI(BB, dl, TII->get(PPC::AND), SReg) 10395 .addReg(TmpDestReg) 10396 .addReg(MaskReg); 10397 unsigned ValueReg = SReg; 10398 unsigned CmpReg = Incr2Reg; 10399 if (CmpOpcode == PPC::CMPW) { 10400 ValueReg = RegInfo.createVirtualRegister(GPRC); 10401 BuildMI(BB, dl, TII->get(PPC::SRW), ValueReg) 10402 .addReg(SReg) 10403 .addReg(ShiftReg); 10404 unsigned ValueSReg = RegInfo.createVirtualRegister(GPRC); 10405 BuildMI(BB, dl, TII->get(is8bit ? PPC::EXTSB : PPC::EXTSH), ValueSReg) 10406 .addReg(ValueReg); 10407 ValueReg = ValueSReg; 10408 CmpReg = incr; 10409 } 10410 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0) 10411 .addReg(CmpReg) 10412 .addReg(ValueReg); 10413 BuildMI(BB, dl, TII->get(PPC::BCC)) 10414 .addImm(CmpPred) 10415 .addReg(PPC::CR0) 10416 .addMBB(exitMBB); 10417 BB->addSuccessor(loop2MBB); 10418 BB->addSuccessor(exitMBB); 10419 BB = loop2MBB; 10420 } 10421 BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg).addReg(Tmp3Reg).addReg(Tmp2Reg); 10422 BuildMI(BB, dl, TII->get(PPC::STWCX)) 10423 .addReg(Tmp4Reg) 10424 .addReg(ZeroReg) 10425 .addReg(PtrReg); 10426 BuildMI(BB, dl, TII->get(PPC::BCC)) 10427 .addImm(PPC::PRED_NE) 10428 .addReg(PPC::CR0) 10429 .addMBB(loopMBB); 10430 BB->addSuccessor(loopMBB); 10431 BB->addSuccessor(exitMBB); 10432 10433 // exitMBB: 10434 // ... 10435 BB = exitMBB; 10436 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest) 10437 .addReg(TmpDestReg) 10438 .addReg(ShiftReg); 10439 return BB; 10440 } 10441 10442 llvm::MachineBasicBlock * 10443 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr &MI, 10444 MachineBasicBlock *MBB) const { 10445 DebugLoc DL = MI.getDebugLoc(); 10446 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 10447 const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo(); 10448 10449 MachineFunction *MF = MBB->getParent(); 10450 MachineRegisterInfo &MRI = MF->getRegInfo(); 10451 10452 const BasicBlock *BB = MBB->getBasicBlock(); 10453 MachineFunction::iterator I = ++MBB->getIterator(); 10454 10455 unsigned DstReg = MI.getOperand(0).getReg(); 10456 const TargetRegisterClass *RC = MRI.getRegClass(DstReg); 10457 assert(TRI->isTypeLegalForClass(*RC, MVT::i32) && "Invalid destination!"); 10458 unsigned mainDstReg = MRI.createVirtualRegister(RC); 10459 unsigned restoreDstReg = MRI.createVirtualRegister(RC); 10460 10461 MVT PVT = getPointerTy(MF->getDataLayout()); 10462 assert((PVT == MVT::i64 || PVT == MVT::i32) && 10463 "Invalid Pointer Size!"); 10464 // For v = setjmp(buf), we generate 10465 // 10466 // thisMBB: 10467 // SjLjSetup mainMBB 10468 // bl mainMBB 10469 // v_restore = 1 10470 // b sinkMBB 10471 // 10472 // mainMBB: 10473 // buf[LabelOffset] = LR 10474 // v_main = 0 10475 // 10476 // sinkMBB: 10477 // v = phi(main, restore) 10478 // 10479 10480 MachineBasicBlock *thisMBB = MBB; 10481 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB); 10482 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB); 10483 MF->insert(I, mainMBB); 10484 MF->insert(I, sinkMBB); 10485 10486 MachineInstrBuilder MIB; 10487 10488 // Transfer the remainder of BB and its successor edges to sinkMBB. 10489 sinkMBB->splice(sinkMBB->begin(), MBB, 10490 std::next(MachineBasicBlock::iterator(MI)), MBB->end()); 10491 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB); 10492 10493 // Note that the structure of the jmp_buf used here is not compatible 10494 // with that used by libc, and is not designed to be. Specifically, it 10495 // stores only those 'reserved' registers that LLVM does not otherwise 10496 // understand how to spill. Also, by convention, by the time this 10497 // intrinsic is called, Clang has already stored the frame address in the 10498 // first slot of the buffer and stack address in the third. Following the 10499 // X86 target code, we'll store the jump address in the second slot. We also 10500 // need to save the TOC pointer (R2) to handle jumps between shared 10501 // libraries, and that will be stored in the fourth slot. The thread 10502 // identifier (R13) is not affected. 10503 10504 // thisMBB: 10505 const int64_t LabelOffset = 1 * PVT.getStoreSize(); 10506 const int64_t TOCOffset = 3 * PVT.getStoreSize(); 10507 const int64_t BPOffset = 4 * PVT.getStoreSize(); 10508 10509 // Prepare IP either in reg. 10510 const TargetRegisterClass *PtrRC = getRegClassFor(PVT); 10511 unsigned LabelReg = MRI.createVirtualRegister(PtrRC); 10512 unsigned BufReg = MI.getOperand(1).getReg(); 10513 10514 if (Subtarget.isPPC64() && Subtarget.isSVR4ABI()) { 10515 setUsesTOCBasePtr(*MBB->getParent()); 10516 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD)) 10517 .addReg(PPC::X2) 10518 .addImm(TOCOffset) 10519 .addReg(BufReg) 10520 .cloneMemRefs(MI); 10521 } 10522 10523 // Naked functions never have a base pointer, and so we use r1. For all 10524 // other functions, this decision must be delayed until during PEI. 10525 unsigned BaseReg; 10526 if (MF->getFunction().hasFnAttribute(Attribute::Naked)) 10527 BaseReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1; 10528 else 10529 BaseReg = Subtarget.isPPC64() ? PPC::BP8 : PPC::BP; 10530 10531 MIB = BuildMI(*thisMBB, MI, DL, 10532 TII->get(Subtarget.isPPC64() ? PPC::STD : PPC::STW)) 10533 .addReg(BaseReg) 10534 .addImm(BPOffset) 10535 .addReg(BufReg) 10536 .cloneMemRefs(MI); 10537 10538 // Setup 10539 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB); 10540 MIB.addRegMask(TRI->getNoPreservedMask()); 10541 10542 BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1); 10543 10544 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup)) 10545 .addMBB(mainMBB); 10546 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB); 10547 10548 thisMBB->addSuccessor(mainMBB, BranchProbability::getZero()); 10549 thisMBB->addSuccessor(sinkMBB, BranchProbability::getOne()); 10550 10551 // mainMBB: 10552 // mainDstReg = 0 10553 MIB = 10554 BuildMI(mainMBB, DL, 10555 TII->get(Subtarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg); 10556 10557 // Store IP 10558 if (Subtarget.isPPC64()) { 10559 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD)) 10560 .addReg(LabelReg) 10561 .addImm(LabelOffset) 10562 .addReg(BufReg); 10563 } else { 10564 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW)) 10565 .addReg(LabelReg) 10566 .addImm(LabelOffset) 10567 .addReg(BufReg); 10568 } 10569 MIB.cloneMemRefs(MI); 10570 10571 BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0); 10572 mainMBB->addSuccessor(sinkMBB); 10573 10574 // sinkMBB: 10575 BuildMI(*sinkMBB, sinkMBB->begin(), DL, 10576 TII->get(PPC::PHI), DstReg) 10577 .addReg(mainDstReg).addMBB(mainMBB) 10578 .addReg(restoreDstReg).addMBB(thisMBB); 10579 10580 MI.eraseFromParent(); 10581 return sinkMBB; 10582 } 10583 10584 MachineBasicBlock * 10585 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr &MI, 10586 MachineBasicBlock *MBB) const { 10587 DebugLoc DL = MI.getDebugLoc(); 10588 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 10589 10590 MachineFunction *MF = MBB->getParent(); 10591 MachineRegisterInfo &MRI = MF->getRegInfo(); 10592 10593 MVT PVT = getPointerTy(MF->getDataLayout()); 10594 assert((PVT == MVT::i64 || PVT == MVT::i32) && 10595 "Invalid Pointer Size!"); 10596 10597 const TargetRegisterClass *RC = 10598 (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 10599 unsigned Tmp = MRI.createVirtualRegister(RC); 10600 // Since FP is only updated here but NOT referenced, it's treated as GPR. 10601 unsigned FP = (PVT == MVT::i64) ? PPC::X31 : PPC::R31; 10602 unsigned SP = (PVT == MVT::i64) ? PPC::X1 : PPC::R1; 10603 unsigned BP = 10604 (PVT == MVT::i64) 10605 ? PPC::X30 10606 : (Subtarget.isSVR4ABI() && isPositionIndependent() ? PPC::R29 10607 : PPC::R30); 10608 10609 MachineInstrBuilder MIB; 10610 10611 const int64_t LabelOffset = 1 * PVT.getStoreSize(); 10612 const int64_t SPOffset = 2 * PVT.getStoreSize(); 10613 const int64_t TOCOffset = 3 * PVT.getStoreSize(); 10614 const int64_t BPOffset = 4 * PVT.getStoreSize(); 10615 10616 unsigned BufReg = MI.getOperand(0).getReg(); 10617 10618 // Reload FP (the jumped-to function may not have had a 10619 // frame pointer, and if so, then its r31 will be restored 10620 // as necessary). 10621 if (PVT == MVT::i64) { 10622 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP) 10623 .addImm(0) 10624 .addReg(BufReg); 10625 } else { 10626 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP) 10627 .addImm(0) 10628 .addReg(BufReg); 10629 } 10630 MIB.cloneMemRefs(MI); 10631 10632 // Reload IP 10633 if (PVT == MVT::i64) { 10634 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp) 10635 .addImm(LabelOffset) 10636 .addReg(BufReg); 10637 } else { 10638 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp) 10639 .addImm(LabelOffset) 10640 .addReg(BufReg); 10641 } 10642 MIB.cloneMemRefs(MI); 10643 10644 // Reload SP 10645 if (PVT == MVT::i64) { 10646 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP) 10647 .addImm(SPOffset) 10648 .addReg(BufReg); 10649 } else { 10650 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP) 10651 .addImm(SPOffset) 10652 .addReg(BufReg); 10653 } 10654 MIB.cloneMemRefs(MI); 10655 10656 // Reload BP 10657 if (PVT == MVT::i64) { 10658 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP) 10659 .addImm(BPOffset) 10660 .addReg(BufReg); 10661 } else { 10662 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP) 10663 .addImm(BPOffset) 10664 .addReg(BufReg); 10665 } 10666 MIB.cloneMemRefs(MI); 10667 10668 // Reload TOC 10669 if (PVT == MVT::i64 && Subtarget.isSVR4ABI()) { 10670 setUsesTOCBasePtr(*MBB->getParent()); 10671 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2) 10672 .addImm(TOCOffset) 10673 .addReg(BufReg) 10674 .cloneMemRefs(MI); 10675 } 10676 10677 // Jump 10678 BuildMI(*MBB, MI, DL, 10679 TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp); 10680 BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR)); 10681 10682 MI.eraseFromParent(); 10683 return MBB; 10684 } 10685 10686 MachineBasicBlock * 10687 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI, 10688 MachineBasicBlock *BB) const { 10689 if (MI.getOpcode() == TargetOpcode::STACKMAP || 10690 MI.getOpcode() == TargetOpcode::PATCHPOINT) { 10691 if (Subtarget.isPPC64() && Subtarget.isSVR4ABI() && 10692 MI.getOpcode() == TargetOpcode::PATCHPOINT) { 10693 // Call lowering should have added an r2 operand to indicate a dependence 10694 // on the TOC base pointer value. It can't however, because there is no 10695 // way to mark the dependence as implicit there, and so the stackmap code 10696 // will confuse it with a regular operand. Instead, add the dependence 10697 // here. 10698 MI.addOperand(MachineOperand::CreateReg(PPC::X2, false, true)); 10699 } 10700 10701 return emitPatchPoint(MI, BB); 10702 } 10703 10704 if (MI.getOpcode() == PPC::EH_SjLj_SetJmp32 || 10705 MI.getOpcode() == PPC::EH_SjLj_SetJmp64) { 10706 return emitEHSjLjSetJmp(MI, BB); 10707 } else if (MI.getOpcode() == PPC::EH_SjLj_LongJmp32 || 10708 MI.getOpcode() == PPC::EH_SjLj_LongJmp64) { 10709 return emitEHSjLjLongJmp(MI, BB); 10710 } 10711 10712 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 10713 10714 // To "insert" these instructions we actually have to insert their 10715 // control-flow patterns. 10716 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 10717 MachineFunction::iterator It = ++BB->getIterator(); 10718 10719 MachineFunction *F = BB->getParent(); 10720 10721 if (MI.getOpcode() == PPC::SELECT_CC_I4 || 10722 MI.getOpcode() == PPC::SELECT_CC_I8 || MI.getOpcode() == PPC::SELECT_I4 || 10723 MI.getOpcode() == PPC::SELECT_I8) { 10724 SmallVector<MachineOperand, 2> Cond; 10725 if (MI.getOpcode() == PPC::SELECT_CC_I4 || 10726 MI.getOpcode() == PPC::SELECT_CC_I8) 10727 Cond.push_back(MI.getOperand(4)); 10728 else 10729 Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET)); 10730 Cond.push_back(MI.getOperand(1)); 10731 10732 DebugLoc dl = MI.getDebugLoc(); 10733 TII->insertSelect(*BB, MI, dl, MI.getOperand(0).getReg(), Cond, 10734 MI.getOperand(2).getReg(), MI.getOperand(3).getReg()); 10735 } else if (MI.getOpcode() == PPC::SELECT_CC_I4 || 10736 MI.getOpcode() == PPC::SELECT_CC_I8 || 10737 MI.getOpcode() == PPC::SELECT_CC_F4 || 10738 MI.getOpcode() == PPC::SELECT_CC_F8 || 10739 MI.getOpcode() == PPC::SELECT_CC_F16 || 10740 MI.getOpcode() == PPC::SELECT_CC_QFRC || 10741 MI.getOpcode() == PPC::SELECT_CC_QSRC || 10742 MI.getOpcode() == PPC::SELECT_CC_QBRC || 10743 MI.getOpcode() == PPC::SELECT_CC_VRRC || 10744 MI.getOpcode() == PPC::SELECT_CC_VSFRC || 10745 MI.getOpcode() == PPC::SELECT_CC_VSSRC || 10746 MI.getOpcode() == PPC::SELECT_CC_VSRC || 10747 MI.getOpcode() == PPC::SELECT_CC_SPE4 || 10748 MI.getOpcode() == PPC::SELECT_CC_SPE || 10749 MI.getOpcode() == PPC::SELECT_I4 || 10750 MI.getOpcode() == PPC::SELECT_I8 || 10751 MI.getOpcode() == PPC::SELECT_F4 || 10752 MI.getOpcode() == PPC::SELECT_F8 || 10753 MI.getOpcode() == PPC::SELECT_F16 || 10754 MI.getOpcode() == PPC::SELECT_QFRC || 10755 MI.getOpcode() == PPC::SELECT_QSRC || 10756 MI.getOpcode() == PPC::SELECT_QBRC || 10757 MI.getOpcode() == PPC::SELECT_SPE || 10758 MI.getOpcode() == PPC::SELECT_SPE4 || 10759 MI.getOpcode() == PPC::SELECT_VRRC || 10760 MI.getOpcode() == PPC::SELECT_VSFRC || 10761 MI.getOpcode() == PPC::SELECT_VSSRC || 10762 MI.getOpcode() == PPC::SELECT_VSRC) { 10763 // The incoming instruction knows the destination vreg to set, the 10764 // condition code register to branch on, the true/false values to 10765 // select between, and a branch opcode to use. 10766 10767 // thisMBB: 10768 // ... 10769 // TrueVal = ... 10770 // cmpTY ccX, r1, r2 10771 // bCC copy1MBB 10772 // fallthrough --> copy0MBB 10773 MachineBasicBlock *thisMBB = BB; 10774 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB); 10775 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 10776 DebugLoc dl = MI.getDebugLoc(); 10777 F->insert(It, copy0MBB); 10778 F->insert(It, sinkMBB); 10779 10780 // Transfer the remainder of BB and its successor edges to sinkMBB. 10781 sinkMBB->splice(sinkMBB->begin(), BB, 10782 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 10783 sinkMBB->transferSuccessorsAndUpdatePHIs(BB); 10784 10785 // Next, add the true and fallthrough blocks as its successors. 10786 BB->addSuccessor(copy0MBB); 10787 BB->addSuccessor(sinkMBB); 10788 10789 if (MI.getOpcode() == PPC::SELECT_I4 || MI.getOpcode() == PPC::SELECT_I8 || 10790 MI.getOpcode() == PPC::SELECT_F4 || MI.getOpcode() == PPC::SELECT_F8 || 10791 MI.getOpcode() == PPC::SELECT_F16 || 10792 MI.getOpcode() == PPC::SELECT_SPE4 || 10793 MI.getOpcode() == PPC::SELECT_SPE || 10794 MI.getOpcode() == PPC::SELECT_QFRC || 10795 MI.getOpcode() == PPC::SELECT_QSRC || 10796 MI.getOpcode() == PPC::SELECT_QBRC || 10797 MI.getOpcode() == PPC::SELECT_VRRC || 10798 MI.getOpcode() == PPC::SELECT_VSFRC || 10799 MI.getOpcode() == PPC::SELECT_VSSRC || 10800 MI.getOpcode() == PPC::SELECT_VSRC) { 10801 BuildMI(BB, dl, TII->get(PPC::BC)) 10802 .addReg(MI.getOperand(1).getReg()) 10803 .addMBB(sinkMBB); 10804 } else { 10805 unsigned SelectPred = MI.getOperand(4).getImm(); 10806 BuildMI(BB, dl, TII->get(PPC::BCC)) 10807 .addImm(SelectPred) 10808 .addReg(MI.getOperand(1).getReg()) 10809 .addMBB(sinkMBB); 10810 } 10811 10812 // copy0MBB: 10813 // %FalseValue = ... 10814 // # fallthrough to sinkMBB 10815 BB = copy0MBB; 10816 10817 // Update machine-CFG edges 10818 BB->addSuccessor(sinkMBB); 10819 10820 // sinkMBB: 10821 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ] 10822 // ... 10823 BB = sinkMBB; 10824 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::PHI), MI.getOperand(0).getReg()) 10825 .addReg(MI.getOperand(3).getReg()) 10826 .addMBB(copy0MBB) 10827 .addReg(MI.getOperand(2).getReg()) 10828 .addMBB(thisMBB); 10829 } else if (MI.getOpcode() == PPC::ReadTB) { 10830 // To read the 64-bit time-base register on a 32-bit target, we read the 10831 // two halves. Should the counter have wrapped while it was being read, we 10832 // need to try again. 10833 // ... 10834 // readLoop: 10835 // mfspr Rx,TBU # load from TBU 10836 // mfspr Ry,TB # load from TB 10837 // mfspr Rz,TBU # load from TBU 10838 // cmpw crX,Rx,Rz # check if 'old'='new' 10839 // bne readLoop # branch if they're not equal 10840 // ... 10841 10842 MachineBasicBlock *readMBB = F->CreateMachineBasicBlock(LLVM_BB); 10843 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 10844 DebugLoc dl = MI.getDebugLoc(); 10845 F->insert(It, readMBB); 10846 F->insert(It, sinkMBB); 10847 10848 // Transfer the remainder of BB and its successor edges to sinkMBB. 10849 sinkMBB->splice(sinkMBB->begin(), BB, 10850 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 10851 sinkMBB->transferSuccessorsAndUpdatePHIs(BB); 10852 10853 BB->addSuccessor(readMBB); 10854 BB = readMBB; 10855 10856 MachineRegisterInfo &RegInfo = F->getRegInfo(); 10857 unsigned ReadAgainReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass); 10858 unsigned LoReg = MI.getOperand(0).getReg(); 10859 unsigned HiReg = MI.getOperand(1).getReg(); 10860 10861 BuildMI(BB, dl, TII->get(PPC::MFSPR), HiReg).addImm(269); 10862 BuildMI(BB, dl, TII->get(PPC::MFSPR), LoReg).addImm(268); 10863 BuildMI(BB, dl, TII->get(PPC::MFSPR), ReadAgainReg).addImm(269); 10864 10865 unsigned CmpReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass); 10866 10867 BuildMI(BB, dl, TII->get(PPC::CMPW), CmpReg) 10868 .addReg(HiReg) 10869 .addReg(ReadAgainReg); 10870 BuildMI(BB, dl, TII->get(PPC::BCC)) 10871 .addImm(PPC::PRED_NE) 10872 .addReg(CmpReg) 10873 .addMBB(readMBB); 10874 10875 BB->addSuccessor(readMBB); 10876 BB->addSuccessor(sinkMBB); 10877 } else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I8) 10878 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4); 10879 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I16) 10880 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4); 10881 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I32) 10882 BB = EmitAtomicBinary(MI, BB, 4, PPC::ADD4); 10883 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I64) 10884 BB = EmitAtomicBinary(MI, BB, 8, PPC::ADD8); 10885 10886 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I8) 10887 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND); 10888 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I16) 10889 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND); 10890 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I32) 10891 BB = EmitAtomicBinary(MI, BB, 4, PPC::AND); 10892 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I64) 10893 BB = EmitAtomicBinary(MI, BB, 8, PPC::AND8); 10894 10895 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I8) 10896 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR); 10897 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I16) 10898 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR); 10899 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I32) 10900 BB = EmitAtomicBinary(MI, BB, 4, PPC::OR); 10901 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I64) 10902 BB = EmitAtomicBinary(MI, BB, 8, PPC::OR8); 10903 10904 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I8) 10905 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR); 10906 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I16) 10907 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR); 10908 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I32) 10909 BB = EmitAtomicBinary(MI, BB, 4, PPC::XOR); 10910 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I64) 10911 BB = EmitAtomicBinary(MI, BB, 8, PPC::XOR8); 10912 10913 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I8) 10914 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::NAND); 10915 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I16) 10916 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::NAND); 10917 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I32) 10918 BB = EmitAtomicBinary(MI, BB, 4, PPC::NAND); 10919 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I64) 10920 BB = EmitAtomicBinary(MI, BB, 8, PPC::NAND8); 10921 10922 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I8) 10923 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF); 10924 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I16) 10925 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF); 10926 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I32) 10927 BB = EmitAtomicBinary(MI, BB, 4, PPC::SUBF); 10928 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I64) 10929 BB = EmitAtomicBinary(MI, BB, 8, PPC::SUBF8); 10930 10931 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I8) 10932 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_GE); 10933 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I16) 10934 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_GE); 10935 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I32) 10936 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_GE); 10937 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I64) 10938 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_GE); 10939 10940 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I8) 10941 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_LE); 10942 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I16) 10943 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_LE); 10944 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I32) 10945 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_LE); 10946 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I64) 10947 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_LE); 10948 10949 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I8) 10950 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_GE); 10951 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I16) 10952 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_GE); 10953 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I32) 10954 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_GE); 10955 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I64) 10956 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_GE); 10957 10958 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I8) 10959 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_LE); 10960 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I16) 10961 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_LE); 10962 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I32) 10963 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_LE); 10964 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I64) 10965 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_LE); 10966 10967 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I8) 10968 BB = EmitPartwordAtomicBinary(MI, BB, true, 0); 10969 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I16) 10970 BB = EmitPartwordAtomicBinary(MI, BB, false, 0); 10971 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I32) 10972 BB = EmitAtomicBinary(MI, BB, 4, 0); 10973 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I64) 10974 BB = EmitAtomicBinary(MI, BB, 8, 0); 10975 else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 || 10976 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64 || 10977 (Subtarget.hasPartwordAtomics() && 10978 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8) || 10979 (Subtarget.hasPartwordAtomics() && 10980 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16)) { 10981 bool is64bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64; 10982 10983 auto LoadMnemonic = PPC::LDARX; 10984 auto StoreMnemonic = PPC::STDCX; 10985 switch (MI.getOpcode()) { 10986 default: 10987 llvm_unreachable("Compare and swap of unknown size"); 10988 case PPC::ATOMIC_CMP_SWAP_I8: 10989 LoadMnemonic = PPC::LBARX; 10990 StoreMnemonic = PPC::STBCX; 10991 assert(Subtarget.hasPartwordAtomics() && "No support partword atomics."); 10992 break; 10993 case PPC::ATOMIC_CMP_SWAP_I16: 10994 LoadMnemonic = PPC::LHARX; 10995 StoreMnemonic = PPC::STHCX; 10996 assert(Subtarget.hasPartwordAtomics() && "No support partword atomics."); 10997 break; 10998 case PPC::ATOMIC_CMP_SWAP_I32: 10999 LoadMnemonic = PPC::LWARX; 11000 StoreMnemonic = PPC::STWCX; 11001 break; 11002 case PPC::ATOMIC_CMP_SWAP_I64: 11003 LoadMnemonic = PPC::LDARX; 11004 StoreMnemonic = PPC::STDCX; 11005 break; 11006 } 11007 unsigned dest = MI.getOperand(0).getReg(); 11008 unsigned ptrA = MI.getOperand(1).getReg(); 11009 unsigned ptrB = MI.getOperand(2).getReg(); 11010 unsigned oldval = MI.getOperand(3).getReg(); 11011 unsigned newval = MI.getOperand(4).getReg(); 11012 DebugLoc dl = MI.getDebugLoc(); 11013 11014 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB); 11015 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB); 11016 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB); 11017 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 11018 F->insert(It, loop1MBB); 11019 F->insert(It, loop2MBB); 11020 F->insert(It, midMBB); 11021 F->insert(It, exitMBB); 11022 exitMBB->splice(exitMBB->begin(), BB, 11023 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 11024 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 11025 11026 // thisMBB: 11027 // ... 11028 // fallthrough --> loopMBB 11029 BB->addSuccessor(loop1MBB); 11030 11031 // loop1MBB: 11032 // l[bhwd]arx dest, ptr 11033 // cmp[wd] dest, oldval 11034 // bne- midMBB 11035 // loop2MBB: 11036 // st[bhwd]cx. newval, ptr 11037 // bne- loopMBB 11038 // b exitBB 11039 // midMBB: 11040 // st[bhwd]cx. dest, ptr 11041 // exitBB: 11042 BB = loop1MBB; 11043 BuildMI(BB, dl, TII->get(LoadMnemonic), dest).addReg(ptrA).addReg(ptrB); 11044 BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0) 11045 .addReg(oldval) 11046 .addReg(dest); 11047 BuildMI(BB, dl, TII->get(PPC::BCC)) 11048 .addImm(PPC::PRED_NE) 11049 .addReg(PPC::CR0) 11050 .addMBB(midMBB); 11051 BB->addSuccessor(loop2MBB); 11052 BB->addSuccessor(midMBB); 11053 11054 BB = loop2MBB; 11055 BuildMI(BB, dl, TII->get(StoreMnemonic)) 11056 .addReg(newval) 11057 .addReg(ptrA) 11058 .addReg(ptrB); 11059 BuildMI(BB, dl, TII->get(PPC::BCC)) 11060 .addImm(PPC::PRED_NE) 11061 .addReg(PPC::CR0) 11062 .addMBB(loop1MBB); 11063 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB); 11064 BB->addSuccessor(loop1MBB); 11065 BB->addSuccessor(exitMBB); 11066 11067 BB = midMBB; 11068 BuildMI(BB, dl, TII->get(StoreMnemonic)) 11069 .addReg(dest) 11070 .addReg(ptrA) 11071 .addReg(ptrB); 11072 BB->addSuccessor(exitMBB); 11073 11074 // exitMBB: 11075 // ... 11076 BB = exitMBB; 11077 } else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 || 11078 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) { 11079 // We must use 64-bit registers for addresses when targeting 64-bit, 11080 // since we're actually doing arithmetic on them. Other registers 11081 // can be 32-bit. 11082 bool is64bit = Subtarget.isPPC64(); 11083 bool isLittleEndian = Subtarget.isLittleEndian(); 11084 bool is8bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8; 11085 11086 unsigned dest = MI.getOperand(0).getReg(); 11087 unsigned ptrA = MI.getOperand(1).getReg(); 11088 unsigned ptrB = MI.getOperand(2).getReg(); 11089 unsigned oldval = MI.getOperand(3).getReg(); 11090 unsigned newval = MI.getOperand(4).getReg(); 11091 DebugLoc dl = MI.getDebugLoc(); 11092 11093 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB); 11094 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB); 11095 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB); 11096 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 11097 F->insert(It, loop1MBB); 11098 F->insert(It, loop2MBB); 11099 F->insert(It, midMBB); 11100 F->insert(It, exitMBB); 11101 exitMBB->splice(exitMBB->begin(), BB, 11102 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 11103 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 11104 11105 MachineRegisterInfo &RegInfo = F->getRegInfo(); 11106 const TargetRegisterClass *RC = 11107 is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 11108 const TargetRegisterClass *GPRC = &PPC::GPRCRegClass; 11109 11110 Register PtrReg = RegInfo.createVirtualRegister(RC); 11111 Register Shift1Reg = RegInfo.createVirtualRegister(GPRC); 11112 Register ShiftReg = 11113 isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC); 11114 Register NewVal2Reg = RegInfo.createVirtualRegister(GPRC); 11115 Register NewVal3Reg = RegInfo.createVirtualRegister(GPRC); 11116 Register OldVal2Reg = RegInfo.createVirtualRegister(GPRC); 11117 Register OldVal3Reg = RegInfo.createVirtualRegister(GPRC); 11118 Register MaskReg = RegInfo.createVirtualRegister(GPRC); 11119 Register Mask2Reg = RegInfo.createVirtualRegister(GPRC); 11120 Register Mask3Reg = RegInfo.createVirtualRegister(GPRC); 11121 Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC); 11122 Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC); 11123 Register TmpDestReg = RegInfo.createVirtualRegister(GPRC); 11124 Register Ptr1Reg; 11125 Register TmpReg = RegInfo.createVirtualRegister(GPRC); 11126 Register ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO; 11127 // thisMBB: 11128 // ... 11129 // fallthrough --> loopMBB 11130 BB->addSuccessor(loop1MBB); 11131 11132 // The 4-byte load must be aligned, while a char or short may be 11133 // anywhere in the word. Hence all this nasty bookkeeping code. 11134 // add ptr1, ptrA, ptrB [copy if ptrA==0] 11135 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27] 11136 // xori shift, shift1, 24 [16] 11137 // rlwinm ptr, ptr1, 0, 0, 29 11138 // slw newval2, newval, shift 11139 // slw oldval2, oldval,shift 11140 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535] 11141 // slw mask, mask2, shift 11142 // and newval3, newval2, mask 11143 // and oldval3, oldval2, mask 11144 // loop1MBB: 11145 // lwarx tmpDest, ptr 11146 // and tmp, tmpDest, mask 11147 // cmpw tmp, oldval3 11148 // bne- midMBB 11149 // loop2MBB: 11150 // andc tmp2, tmpDest, mask 11151 // or tmp4, tmp2, newval3 11152 // stwcx. tmp4, ptr 11153 // bne- loop1MBB 11154 // b exitBB 11155 // midMBB: 11156 // stwcx. tmpDest, ptr 11157 // exitBB: 11158 // srw dest, tmpDest, shift 11159 if (ptrA != ZeroReg) { 11160 Ptr1Reg = RegInfo.createVirtualRegister(RC); 11161 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg) 11162 .addReg(ptrA) 11163 .addReg(ptrB); 11164 } else { 11165 Ptr1Reg = ptrB; 11166 } 11167 11168 // We need use 32-bit subregister to avoid mismatch register class in 64-bit 11169 // mode. 11170 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg) 11171 .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0) 11172 .addImm(3) 11173 .addImm(27) 11174 .addImm(is8bit ? 28 : 27); 11175 if (!isLittleEndian) 11176 BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg) 11177 .addReg(Shift1Reg) 11178 .addImm(is8bit ? 24 : 16); 11179 if (is64bit) 11180 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg) 11181 .addReg(Ptr1Reg) 11182 .addImm(0) 11183 .addImm(61); 11184 else 11185 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg) 11186 .addReg(Ptr1Reg) 11187 .addImm(0) 11188 .addImm(0) 11189 .addImm(29); 11190 BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg) 11191 .addReg(newval) 11192 .addReg(ShiftReg); 11193 BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg) 11194 .addReg(oldval) 11195 .addReg(ShiftReg); 11196 if (is8bit) 11197 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255); 11198 else { 11199 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0); 11200 BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg) 11201 .addReg(Mask3Reg) 11202 .addImm(65535); 11203 } 11204 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg) 11205 .addReg(Mask2Reg) 11206 .addReg(ShiftReg); 11207 BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg) 11208 .addReg(NewVal2Reg) 11209 .addReg(MaskReg); 11210 BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg) 11211 .addReg(OldVal2Reg) 11212 .addReg(MaskReg); 11213 11214 BB = loop1MBB; 11215 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg) 11216 .addReg(ZeroReg) 11217 .addReg(PtrReg); 11218 BuildMI(BB, dl, TII->get(PPC::AND), TmpReg) 11219 .addReg(TmpDestReg) 11220 .addReg(MaskReg); 11221 BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0) 11222 .addReg(TmpReg) 11223 .addReg(OldVal3Reg); 11224 BuildMI(BB, dl, TII->get(PPC::BCC)) 11225 .addImm(PPC::PRED_NE) 11226 .addReg(PPC::CR0) 11227 .addMBB(midMBB); 11228 BB->addSuccessor(loop2MBB); 11229 BB->addSuccessor(midMBB); 11230 11231 BB = loop2MBB; 11232 BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg) 11233 .addReg(TmpDestReg) 11234 .addReg(MaskReg); 11235 BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg) 11236 .addReg(Tmp2Reg) 11237 .addReg(NewVal3Reg); 11238 BuildMI(BB, dl, TII->get(PPC::STWCX)) 11239 .addReg(Tmp4Reg) 11240 .addReg(ZeroReg) 11241 .addReg(PtrReg); 11242 BuildMI(BB, dl, TII->get(PPC::BCC)) 11243 .addImm(PPC::PRED_NE) 11244 .addReg(PPC::CR0) 11245 .addMBB(loop1MBB); 11246 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB); 11247 BB->addSuccessor(loop1MBB); 11248 BB->addSuccessor(exitMBB); 11249 11250 BB = midMBB; 11251 BuildMI(BB, dl, TII->get(PPC::STWCX)) 11252 .addReg(TmpDestReg) 11253 .addReg(ZeroReg) 11254 .addReg(PtrReg); 11255 BB->addSuccessor(exitMBB); 11256 11257 // exitMBB: 11258 // ... 11259 BB = exitMBB; 11260 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest) 11261 .addReg(TmpReg) 11262 .addReg(ShiftReg); 11263 } else if (MI.getOpcode() == PPC::FADDrtz) { 11264 // This pseudo performs an FADD with rounding mode temporarily forced 11265 // to round-to-zero. We emit this via custom inserter since the FPSCR 11266 // is not modeled at the SelectionDAG level. 11267 unsigned Dest = MI.getOperand(0).getReg(); 11268 unsigned Src1 = MI.getOperand(1).getReg(); 11269 unsigned Src2 = MI.getOperand(2).getReg(); 11270 DebugLoc dl = MI.getDebugLoc(); 11271 11272 MachineRegisterInfo &RegInfo = F->getRegInfo(); 11273 unsigned MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass); 11274 11275 // Save FPSCR value. 11276 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg); 11277 11278 // Set rounding mode to round-to-zero. 11279 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1)).addImm(31); 11280 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0)).addImm(30); 11281 11282 // Perform addition. 11283 BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest).addReg(Src1).addReg(Src2); 11284 11285 // Restore FPSCR value. 11286 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSFb)).addImm(1).addReg(MFFSReg); 11287 } else if (MI.getOpcode() == PPC::ANDIo_1_EQ_BIT || 11288 MI.getOpcode() == PPC::ANDIo_1_GT_BIT || 11289 MI.getOpcode() == PPC::ANDIo_1_EQ_BIT8 || 11290 MI.getOpcode() == PPC::ANDIo_1_GT_BIT8) { 11291 unsigned Opcode = (MI.getOpcode() == PPC::ANDIo_1_EQ_BIT8 || 11292 MI.getOpcode() == PPC::ANDIo_1_GT_BIT8) 11293 ? PPC::ANDIo8 11294 : PPC::ANDIo; 11295 bool isEQ = (MI.getOpcode() == PPC::ANDIo_1_EQ_BIT || 11296 MI.getOpcode() == PPC::ANDIo_1_EQ_BIT8); 11297 11298 MachineRegisterInfo &RegInfo = F->getRegInfo(); 11299 unsigned Dest = RegInfo.createVirtualRegister( 11300 Opcode == PPC::ANDIo ? &PPC::GPRCRegClass : &PPC::G8RCRegClass); 11301 11302 DebugLoc dl = MI.getDebugLoc(); 11303 BuildMI(*BB, MI, dl, TII->get(Opcode), Dest) 11304 .addReg(MI.getOperand(1).getReg()) 11305 .addImm(1); 11306 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), 11307 MI.getOperand(0).getReg()) 11308 .addReg(isEQ ? PPC::CR0EQ : PPC::CR0GT); 11309 } else if (MI.getOpcode() == PPC::TCHECK_RET) { 11310 DebugLoc Dl = MI.getDebugLoc(); 11311 MachineRegisterInfo &RegInfo = F->getRegInfo(); 11312 unsigned CRReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass); 11313 BuildMI(*BB, MI, Dl, TII->get(PPC::TCHECK), CRReg); 11314 BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY), 11315 MI.getOperand(0).getReg()) 11316 .addReg(CRReg); 11317 } else if (MI.getOpcode() == PPC::TBEGIN_RET) { 11318 DebugLoc Dl = MI.getDebugLoc(); 11319 unsigned Imm = MI.getOperand(1).getImm(); 11320 BuildMI(*BB, MI, Dl, TII->get(PPC::TBEGIN)).addImm(Imm); 11321 BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY), 11322 MI.getOperand(0).getReg()) 11323 .addReg(PPC::CR0EQ); 11324 } else if (MI.getOpcode() == PPC::SETRNDi) { 11325 DebugLoc dl = MI.getDebugLoc(); 11326 unsigned OldFPSCRReg = MI.getOperand(0).getReg(); 11327 11328 // Save FPSCR value. 11329 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg); 11330 11331 // The floating point rounding mode is in the bits 62:63 of FPCSR, and has 11332 // the following settings: 11333 // 00 Round to nearest 11334 // 01 Round to 0 11335 // 10 Round to +inf 11336 // 11 Round to -inf 11337 11338 // When the operand is immediate, using the two least significant bits of 11339 // the immediate to set the bits 62:63 of FPSCR. 11340 unsigned Mode = MI.getOperand(1).getImm(); 11341 BuildMI(*BB, MI, dl, TII->get((Mode & 1) ? PPC::MTFSB1 : PPC::MTFSB0)) 11342 .addImm(31); 11343 11344 BuildMI(*BB, MI, dl, TII->get((Mode & 2) ? PPC::MTFSB1 : PPC::MTFSB0)) 11345 .addImm(30); 11346 } else if (MI.getOpcode() == PPC::SETRND) { 11347 DebugLoc dl = MI.getDebugLoc(); 11348 11349 // Copy register from F8RCRegClass::SrcReg to G8RCRegClass::DestReg 11350 // or copy register from G8RCRegClass::SrcReg to F8RCRegClass::DestReg. 11351 // If the target doesn't have DirectMove, we should use stack to do the 11352 // conversion, because the target doesn't have the instructions like mtvsrd 11353 // or mfvsrd to do this conversion directly. 11354 auto copyRegFromG8RCOrF8RC = [&] (unsigned DestReg, unsigned SrcReg) { 11355 if (Subtarget.hasDirectMove()) { 11356 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), DestReg) 11357 .addReg(SrcReg); 11358 } else { 11359 // Use stack to do the register copy. 11360 unsigned StoreOp = PPC::STD, LoadOp = PPC::LFD; 11361 MachineRegisterInfo &RegInfo = F->getRegInfo(); 11362 const TargetRegisterClass *RC = RegInfo.getRegClass(SrcReg); 11363 if (RC == &PPC::F8RCRegClass) { 11364 // Copy register from F8RCRegClass to G8RCRegclass. 11365 assert((RegInfo.getRegClass(DestReg) == &PPC::G8RCRegClass) && 11366 "Unsupported RegClass."); 11367 11368 StoreOp = PPC::STFD; 11369 LoadOp = PPC::LD; 11370 } else { 11371 // Copy register from G8RCRegClass to F8RCRegclass. 11372 assert((RegInfo.getRegClass(SrcReg) == &PPC::G8RCRegClass) && 11373 (RegInfo.getRegClass(DestReg) == &PPC::F8RCRegClass) && 11374 "Unsupported RegClass."); 11375 } 11376 11377 MachineFrameInfo &MFI = F->getFrameInfo(); 11378 int FrameIdx = MFI.CreateStackObject(8, 8, false); 11379 11380 MachineMemOperand *MMOStore = F->getMachineMemOperand( 11381 MachinePointerInfo::getFixedStack(*F, FrameIdx, 0), 11382 MachineMemOperand::MOStore, MFI.getObjectSize(FrameIdx), 11383 MFI.getObjectAlignment(FrameIdx)); 11384 11385 // Store the SrcReg into the stack. 11386 BuildMI(*BB, MI, dl, TII->get(StoreOp)) 11387 .addReg(SrcReg) 11388 .addImm(0) 11389 .addFrameIndex(FrameIdx) 11390 .addMemOperand(MMOStore); 11391 11392 MachineMemOperand *MMOLoad = F->getMachineMemOperand( 11393 MachinePointerInfo::getFixedStack(*F, FrameIdx, 0), 11394 MachineMemOperand::MOLoad, MFI.getObjectSize(FrameIdx), 11395 MFI.getObjectAlignment(FrameIdx)); 11396 11397 // Load from the stack where SrcReg is stored, and save to DestReg, 11398 // so we have done the RegClass conversion from RegClass::SrcReg to 11399 // RegClass::DestReg. 11400 BuildMI(*BB, MI, dl, TII->get(LoadOp), DestReg) 11401 .addImm(0) 11402 .addFrameIndex(FrameIdx) 11403 .addMemOperand(MMOLoad); 11404 } 11405 }; 11406 11407 unsigned OldFPSCRReg = MI.getOperand(0).getReg(); 11408 11409 // Save FPSCR value. 11410 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg); 11411 11412 // When the operand is gprc register, use two least significant bits of the 11413 // register and mtfsf instruction to set the bits 62:63 of FPSCR. 11414 // 11415 // copy OldFPSCRTmpReg, OldFPSCRReg 11416 // (INSERT_SUBREG ExtSrcReg, (IMPLICIT_DEF ImDefReg), SrcOp, 1) 11417 // rldimi NewFPSCRTmpReg, ExtSrcReg, OldFPSCRReg, 0, 62 11418 // copy NewFPSCRReg, NewFPSCRTmpReg 11419 // mtfsf 255, NewFPSCRReg 11420 MachineOperand SrcOp = MI.getOperand(1); 11421 MachineRegisterInfo &RegInfo = F->getRegInfo(); 11422 unsigned OldFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 11423 11424 copyRegFromG8RCOrF8RC(OldFPSCRTmpReg, OldFPSCRReg); 11425 11426 unsigned ImDefReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 11427 unsigned ExtSrcReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 11428 11429 // The first operand of INSERT_SUBREG should be a register which has 11430 // subregisters, we only care about its RegClass, so we should use an 11431 // IMPLICIT_DEF register. 11432 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::IMPLICIT_DEF), ImDefReg); 11433 BuildMI(*BB, MI, dl, TII->get(PPC::INSERT_SUBREG), ExtSrcReg) 11434 .addReg(ImDefReg) 11435 .add(SrcOp) 11436 .addImm(1); 11437 11438 unsigned NewFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 11439 BuildMI(*BB, MI, dl, TII->get(PPC::RLDIMI), NewFPSCRTmpReg) 11440 .addReg(OldFPSCRTmpReg) 11441 .addReg(ExtSrcReg) 11442 .addImm(0) 11443 .addImm(62); 11444 11445 unsigned NewFPSCRReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass); 11446 copyRegFromG8RCOrF8RC(NewFPSCRReg, NewFPSCRTmpReg); 11447 11448 // The mask 255 means that put the 32:63 bits of NewFPSCRReg to the 32:63 11449 // bits of FPSCR. 11450 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSF)) 11451 .addImm(255) 11452 .addReg(NewFPSCRReg) 11453 .addImm(0) 11454 .addImm(0); 11455 } else { 11456 llvm_unreachable("Unexpected instr type to insert"); 11457 } 11458 11459 MI.eraseFromParent(); // The pseudo instruction is gone now. 11460 return BB; 11461 } 11462 11463 //===----------------------------------------------------------------------===// 11464 // Target Optimization Hooks 11465 //===----------------------------------------------------------------------===// 11466 11467 static int getEstimateRefinementSteps(EVT VT, const PPCSubtarget &Subtarget) { 11468 // For the estimates, convergence is quadratic, so we essentially double the 11469 // number of digits correct after every iteration. For both FRE and FRSQRTE, 11470 // the minimum architected relative accuracy is 2^-5. When hasRecipPrec(), 11471 // this is 2^-14. IEEE float has 23 digits and double has 52 digits. 11472 int RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3; 11473 if (VT.getScalarType() == MVT::f64) 11474 RefinementSteps++; 11475 return RefinementSteps; 11476 } 11477 11478 SDValue PPCTargetLowering::getSqrtEstimate(SDValue Operand, SelectionDAG &DAG, 11479 int Enabled, int &RefinementSteps, 11480 bool &UseOneConstNR, 11481 bool Reciprocal) const { 11482 EVT VT = Operand.getValueType(); 11483 if ((VT == MVT::f32 && Subtarget.hasFRSQRTES()) || 11484 (VT == MVT::f64 && Subtarget.hasFRSQRTE()) || 11485 (VT == MVT::v4f32 && Subtarget.hasAltivec()) || 11486 (VT == MVT::v2f64 && Subtarget.hasVSX()) || 11487 (VT == MVT::v4f32 && Subtarget.hasQPX()) || 11488 (VT == MVT::v4f64 && Subtarget.hasQPX())) { 11489 if (RefinementSteps == ReciprocalEstimate::Unspecified) 11490 RefinementSteps = getEstimateRefinementSteps(VT, Subtarget); 11491 11492 // The Newton-Raphson computation with a single constant does not provide 11493 // enough accuracy on some CPUs. 11494 UseOneConstNR = !Subtarget.needsTwoConstNR(); 11495 return DAG.getNode(PPCISD::FRSQRTE, SDLoc(Operand), VT, Operand); 11496 } 11497 return SDValue(); 11498 } 11499 11500 SDValue PPCTargetLowering::getRecipEstimate(SDValue Operand, SelectionDAG &DAG, 11501 int Enabled, 11502 int &RefinementSteps) const { 11503 EVT VT = Operand.getValueType(); 11504 if ((VT == MVT::f32 && Subtarget.hasFRES()) || 11505 (VT == MVT::f64 && Subtarget.hasFRE()) || 11506 (VT == MVT::v4f32 && Subtarget.hasAltivec()) || 11507 (VT == MVT::v2f64 && Subtarget.hasVSX()) || 11508 (VT == MVT::v4f32 && Subtarget.hasQPX()) || 11509 (VT == MVT::v4f64 && Subtarget.hasQPX())) { 11510 if (RefinementSteps == ReciprocalEstimate::Unspecified) 11511 RefinementSteps = getEstimateRefinementSteps(VT, Subtarget); 11512 return DAG.getNode(PPCISD::FRE, SDLoc(Operand), VT, Operand); 11513 } 11514 return SDValue(); 11515 } 11516 11517 unsigned PPCTargetLowering::combineRepeatedFPDivisors() const { 11518 // Note: This functionality is used only when unsafe-fp-math is enabled, and 11519 // on cores with reciprocal estimates (which are used when unsafe-fp-math is 11520 // enabled for division), this functionality is redundant with the default 11521 // combiner logic (once the division -> reciprocal/multiply transformation 11522 // has taken place). As a result, this matters more for older cores than for 11523 // newer ones. 11524 11525 // Combine multiple FDIVs with the same divisor into multiple FMULs by the 11526 // reciprocal if there are two or more FDIVs (for embedded cores with only 11527 // one FP pipeline) for three or more FDIVs (for generic OOO cores). 11528 switch (Subtarget.getDarwinDirective()) { 11529 default: 11530 return 3; 11531 case PPC::DIR_440: 11532 case PPC::DIR_A2: 11533 case PPC::DIR_E500: 11534 case PPC::DIR_E500mc: 11535 case PPC::DIR_E5500: 11536 return 2; 11537 } 11538 } 11539 11540 // isConsecutiveLSLoc needs to work even if all adds have not yet been 11541 // collapsed, and so we need to look through chains of them. 11542 static void getBaseWithConstantOffset(SDValue Loc, SDValue &Base, 11543 int64_t& Offset, SelectionDAG &DAG) { 11544 if (DAG.isBaseWithConstantOffset(Loc)) { 11545 Base = Loc.getOperand(0); 11546 Offset += cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue(); 11547 11548 // The base might itself be a base plus an offset, and if so, accumulate 11549 // that as well. 11550 getBaseWithConstantOffset(Loc.getOperand(0), Base, Offset, DAG); 11551 } 11552 } 11553 11554 static bool isConsecutiveLSLoc(SDValue Loc, EVT VT, LSBaseSDNode *Base, 11555 unsigned Bytes, int Dist, 11556 SelectionDAG &DAG) { 11557 if (VT.getSizeInBits() / 8 != Bytes) 11558 return false; 11559 11560 SDValue BaseLoc = Base->getBasePtr(); 11561 if (Loc.getOpcode() == ISD::FrameIndex) { 11562 if (BaseLoc.getOpcode() != ISD::FrameIndex) 11563 return false; 11564 const MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 11565 int FI = cast<FrameIndexSDNode>(Loc)->getIndex(); 11566 int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex(); 11567 int FS = MFI.getObjectSize(FI); 11568 int BFS = MFI.getObjectSize(BFI); 11569 if (FS != BFS || FS != (int)Bytes) return false; 11570 return MFI.getObjectOffset(FI) == (MFI.getObjectOffset(BFI) + Dist*Bytes); 11571 } 11572 11573 SDValue Base1 = Loc, Base2 = BaseLoc; 11574 int64_t Offset1 = 0, Offset2 = 0; 11575 getBaseWithConstantOffset(Loc, Base1, Offset1, DAG); 11576 getBaseWithConstantOffset(BaseLoc, Base2, Offset2, DAG); 11577 if (Base1 == Base2 && Offset1 == (Offset2 + Dist * Bytes)) 11578 return true; 11579 11580 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11581 const GlobalValue *GV1 = nullptr; 11582 const GlobalValue *GV2 = nullptr; 11583 Offset1 = 0; 11584 Offset2 = 0; 11585 bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1); 11586 bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2); 11587 if (isGA1 && isGA2 && GV1 == GV2) 11588 return Offset1 == (Offset2 + Dist*Bytes); 11589 return false; 11590 } 11591 11592 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does 11593 // not enforce equality of the chain operands. 11594 static bool isConsecutiveLS(SDNode *N, LSBaseSDNode *Base, 11595 unsigned Bytes, int Dist, 11596 SelectionDAG &DAG) { 11597 if (LSBaseSDNode *LS = dyn_cast<LSBaseSDNode>(N)) { 11598 EVT VT = LS->getMemoryVT(); 11599 SDValue Loc = LS->getBasePtr(); 11600 return isConsecutiveLSLoc(Loc, VT, Base, Bytes, Dist, DAG); 11601 } 11602 11603 if (N->getOpcode() == ISD::INTRINSIC_W_CHAIN) { 11604 EVT VT; 11605 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 11606 default: return false; 11607 case Intrinsic::ppc_qpx_qvlfd: 11608 case Intrinsic::ppc_qpx_qvlfda: 11609 VT = MVT::v4f64; 11610 break; 11611 case Intrinsic::ppc_qpx_qvlfs: 11612 case Intrinsic::ppc_qpx_qvlfsa: 11613 VT = MVT::v4f32; 11614 break; 11615 case Intrinsic::ppc_qpx_qvlfcd: 11616 case Intrinsic::ppc_qpx_qvlfcda: 11617 VT = MVT::v2f64; 11618 break; 11619 case Intrinsic::ppc_qpx_qvlfcs: 11620 case Intrinsic::ppc_qpx_qvlfcsa: 11621 VT = MVT::v2f32; 11622 break; 11623 case Intrinsic::ppc_qpx_qvlfiwa: 11624 case Intrinsic::ppc_qpx_qvlfiwz: 11625 case Intrinsic::ppc_altivec_lvx: 11626 case Intrinsic::ppc_altivec_lvxl: 11627 case Intrinsic::ppc_vsx_lxvw4x: 11628 case Intrinsic::ppc_vsx_lxvw4x_be: 11629 VT = MVT::v4i32; 11630 break; 11631 case Intrinsic::ppc_vsx_lxvd2x: 11632 case Intrinsic::ppc_vsx_lxvd2x_be: 11633 VT = MVT::v2f64; 11634 break; 11635 case Intrinsic::ppc_altivec_lvebx: 11636 VT = MVT::i8; 11637 break; 11638 case Intrinsic::ppc_altivec_lvehx: 11639 VT = MVT::i16; 11640 break; 11641 case Intrinsic::ppc_altivec_lvewx: 11642 VT = MVT::i32; 11643 break; 11644 } 11645 11646 return isConsecutiveLSLoc(N->getOperand(2), VT, Base, Bytes, Dist, DAG); 11647 } 11648 11649 if (N->getOpcode() == ISD::INTRINSIC_VOID) { 11650 EVT VT; 11651 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 11652 default: return false; 11653 case Intrinsic::ppc_qpx_qvstfd: 11654 case Intrinsic::ppc_qpx_qvstfda: 11655 VT = MVT::v4f64; 11656 break; 11657 case Intrinsic::ppc_qpx_qvstfs: 11658 case Intrinsic::ppc_qpx_qvstfsa: 11659 VT = MVT::v4f32; 11660 break; 11661 case Intrinsic::ppc_qpx_qvstfcd: 11662 case Intrinsic::ppc_qpx_qvstfcda: 11663 VT = MVT::v2f64; 11664 break; 11665 case Intrinsic::ppc_qpx_qvstfcs: 11666 case Intrinsic::ppc_qpx_qvstfcsa: 11667 VT = MVT::v2f32; 11668 break; 11669 case Intrinsic::ppc_qpx_qvstfiw: 11670 case Intrinsic::ppc_qpx_qvstfiwa: 11671 case Intrinsic::ppc_altivec_stvx: 11672 case Intrinsic::ppc_altivec_stvxl: 11673 case Intrinsic::ppc_vsx_stxvw4x: 11674 VT = MVT::v4i32; 11675 break; 11676 case Intrinsic::ppc_vsx_stxvd2x: 11677 VT = MVT::v2f64; 11678 break; 11679 case Intrinsic::ppc_vsx_stxvw4x_be: 11680 VT = MVT::v4i32; 11681 break; 11682 case Intrinsic::ppc_vsx_stxvd2x_be: 11683 VT = MVT::v2f64; 11684 break; 11685 case Intrinsic::ppc_altivec_stvebx: 11686 VT = MVT::i8; 11687 break; 11688 case Intrinsic::ppc_altivec_stvehx: 11689 VT = MVT::i16; 11690 break; 11691 case Intrinsic::ppc_altivec_stvewx: 11692 VT = MVT::i32; 11693 break; 11694 } 11695 11696 return isConsecutiveLSLoc(N->getOperand(3), VT, Base, Bytes, Dist, DAG); 11697 } 11698 11699 return false; 11700 } 11701 11702 // Return true is there is a nearyby consecutive load to the one provided 11703 // (regardless of alignment). We search up and down the chain, looking though 11704 // token factors and other loads (but nothing else). As a result, a true result 11705 // indicates that it is safe to create a new consecutive load adjacent to the 11706 // load provided. 11707 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) { 11708 SDValue Chain = LD->getChain(); 11709 EVT VT = LD->getMemoryVT(); 11710 11711 SmallSet<SDNode *, 16> LoadRoots; 11712 SmallVector<SDNode *, 8> Queue(1, Chain.getNode()); 11713 SmallSet<SDNode *, 16> Visited; 11714 11715 // First, search up the chain, branching to follow all token-factor operands. 11716 // If we find a consecutive load, then we're done, otherwise, record all 11717 // nodes just above the top-level loads and token factors. 11718 while (!Queue.empty()) { 11719 SDNode *ChainNext = Queue.pop_back_val(); 11720 if (!Visited.insert(ChainNext).second) 11721 continue; 11722 11723 if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(ChainNext)) { 11724 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG)) 11725 return true; 11726 11727 if (!Visited.count(ChainLD->getChain().getNode())) 11728 Queue.push_back(ChainLD->getChain().getNode()); 11729 } else if (ChainNext->getOpcode() == ISD::TokenFactor) { 11730 for (const SDUse &O : ChainNext->ops()) 11731 if (!Visited.count(O.getNode())) 11732 Queue.push_back(O.getNode()); 11733 } else 11734 LoadRoots.insert(ChainNext); 11735 } 11736 11737 // Second, search down the chain, starting from the top-level nodes recorded 11738 // in the first phase. These top-level nodes are the nodes just above all 11739 // loads and token factors. Starting with their uses, recursively look though 11740 // all loads (just the chain uses) and token factors to find a consecutive 11741 // load. 11742 Visited.clear(); 11743 Queue.clear(); 11744 11745 for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(), 11746 IE = LoadRoots.end(); I != IE; ++I) { 11747 Queue.push_back(*I); 11748 11749 while (!Queue.empty()) { 11750 SDNode *LoadRoot = Queue.pop_back_val(); 11751 if (!Visited.insert(LoadRoot).second) 11752 continue; 11753 11754 if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(LoadRoot)) 11755 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG)) 11756 return true; 11757 11758 for (SDNode::use_iterator UI = LoadRoot->use_begin(), 11759 UE = LoadRoot->use_end(); UI != UE; ++UI) 11760 if (((isa<MemSDNode>(*UI) && 11761 cast<MemSDNode>(*UI)->getChain().getNode() == LoadRoot) || 11762 UI->getOpcode() == ISD::TokenFactor) && !Visited.count(*UI)) 11763 Queue.push_back(*UI); 11764 } 11765 } 11766 11767 return false; 11768 } 11769 11770 /// This function is called when we have proved that a SETCC node can be replaced 11771 /// by subtraction (and other supporting instructions) so that the result of 11772 /// comparison is kept in a GPR instead of CR. This function is purely for 11773 /// codegen purposes and has some flags to guide the codegen process. 11774 static SDValue generateEquivalentSub(SDNode *N, int Size, bool Complement, 11775 bool Swap, SDLoc &DL, SelectionDAG &DAG) { 11776 assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected."); 11777 11778 // Zero extend the operands to the largest legal integer. Originally, they 11779 // must be of a strictly smaller size. 11780 auto Op0 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(0), 11781 DAG.getConstant(Size, DL, MVT::i32)); 11782 auto Op1 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1), 11783 DAG.getConstant(Size, DL, MVT::i32)); 11784 11785 // Swap if needed. Depends on the condition code. 11786 if (Swap) 11787 std::swap(Op0, Op1); 11788 11789 // Subtract extended integers. 11790 auto SubNode = DAG.getNode(ISD::SUB, DL, MVT::i64, Op0, Op1); 11791 11792 // Move the sign bit to the least significant position and zero out the rest. 11793 // Now the least significant bit carries the result of original comparison. 11794 auto Shifted = DAG.getNode(ISD::SRL, DL, MVT::i64, SubNode, 11795 DAG.getConstant(Size - 1, DL, MVT::i32)); 11796 auto Final = Shifted; 11797 11798 // Complement the result if needed. Based on the condition code. 11799 if (Complement) 11800 Final = DAG.getNode(ISD::XOR, DL, MVT::i64, Shifted, 11801 DAG.getConstant(1, DL, MVT::i64)); 11802 11803 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Final); 11804 } 11805 11806 SDValue PPCTargetLowering::ConvertSETCCToSubtract(SDNode *N, 11807 DAGCombinerInfo &DCI) const { 11808 assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected."); 11809 11810 SelectionDAG &DAG = DCI.DAG; 11811 SDLoc DL(N); 11812 11813 // Size of integers being compared has a critical role in the following 11814 // analysis, so we prefer to do this when all types are legal. 11815 if (!DCI.isAfterLegalizeDAG()) 11816 return SDValue(); 11817 11818 // If all users of SETCC extend its value to a legal integer type 11819 // then we replace SETCC with a subtraction 11820 for (SDNode::use_iterator UI = N->use_begin(), 11821 UE = N->use_end(); UI != UE; ++UI) { 11822 if (UI->getOpcode() != ISD::ZERO_EXTEND) 11823 return SDValue(); 11824 } 11825 11826 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 11827 auto OpSize = N->getOperand(0).getValueSizeInBits(); 11828 11829 unsigned Size = DAG.getDataLayout().getLargestLegalIntTypeSizeInBits(); 11830 11831 if (OpSize < Size) { 11832 switch (CC) { 11833 default: break; 11834 case ISD::SETULT: 11835 return generateEquivalentSub(N, Size, false, false, DL, DAG); 11836 case ISD::SETULE: 11837 return generateEquivalentSub(N, Size, true, true, DL, DAG); 11838 case ISD::SETUGT: 11839 return generateEquivalentSub(N, Size, false, true, DL, DAG); 11840 case ISD::SETUGE: 11841 return generateEquivalentSub(N, Size, true, false, DL, DAG); 11842 } 11843 } 11844 11845 return SDValue(); 11846 } 11847 11848 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N, 11849 DAGCombinerInfo &DCI) const { 11850 SelectionDAG &DAG = DCI.DAG; 11851 SDLoc dl(N); 11852 11853 assert(Subtarget.useCRBits() && "Expecting to be tracking CR bits"); 11854 // If we're tracking CR bits, we need to be careful that we don't have: 11855 // trunc(binary-ops(zext(x), zext(y))) 11856 // or 11857 // trunc(binary-ops(binary-ops(zext(x), zext(y)), ...) 11858 // such that we're unnecessarily moving things into GPRs when it would be 11859 // better to keep them in CR bits. 11860 11861 // Note that trunc here can be an actual i1 trunc, or can be the effective 11862 // truncation that comes from a setcc or select_cc. 11863 if (N->getOpcode() == ISD::TRUNCATE && 11864 N->getValueType(0) != MVT::i1) 11865 return SDValue(); 11866 11867 if (N->getOperand(0).getValueType() != MVT::i32 && 11868 N->getOperand(0).getValueType() != MVT::i64) 11869 return SDValue(); 11870 11871 if (N->getOpcode() == ISD::SETCC || 11872 N->getOpcode() == ISD::SELECT_CC) { 11873 // If we're looking at a comparison, then we need to make sure that the 11874 // high bits (all except for the first) don't matter the result. 11875 ISD::CondCode CC = 11876 cast<CondCodeSDNode>(N->getOperand( 11877 N->getOpcode() == ISD::SETCC ? 2 : 4))->get(); 11878 unsigned OpBits = N->getOperand(0).getValueSizeInBits(); 11879 11880 if (ISD::isSignedIntSetCC(CC)) { 11881 if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits || 11882 DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits) 11883 return SDValue(); 11884 } else if (ISD::isUnsignedIntSetCC(CC)) { 11885 if (!DAG.MaskedValueIsZero(N->getOperand(0), 11886 APInt::getHighBitsSet(OpBits, OpBits-1)) || 11887 !DAG.MaskedValueIsZero(N->getOperand(1), 11888 APInt::getHighBitsSet(OpBits, OpBits-1))) 11889 return (N->getOpcode() == ISD::SETCC ? ConvertSETCCToSubtract(N, DCI) 11890 : SDValue()); 11891 } else { 11892 // This is neither a signed nor an unsigned comparison, just make sure 11893 // that the high bits are equal. 11894 KnownBits Op1Known = DAG.computeKnownBits(N->getOperand(0)); 11895 KnownBits Op2Known = DAG.computeKnownBits(N->getOperand(1)); 11896 11897 // We don't really care about what is known about the first bit (if 11898 // anything), so clear it in all masks prior to comparing them. 11899 Op1Known.Zero.clearBit(0); Op1Known.One.clearBit(0); 11900 Op2Known.Zero.clearBit(0); Op2Known.One.clearBit(0); 11901 11902 if (Op1Known.Zero != Op2Known.Zero || Op1Known.One != Op2Known.One) 11903 return SDValue(); 11904 } 11905 } 11906 11907 // We now know that the higher-order bits are irrelevant, we just need to 11908 // make sure that all of the intermediate operations are bit operations, and 11909 // all inputs are extensions. 11910 if (N->getOperand(0).getOpcode() != ISD::AND && 11911 N->getOperand(0).getOpcode() != ISD::OR && 11912 N->getOperand(0).getOpcode() != ISD::XOR && 11913 N->getOperand(0).getOpcode() != ISD::SELECT && 11914 N->getOperand(0).getOpcode() != ISD::SELECT_CC && 11915 N->getOperand(0).getOpcode() != ISD::TRUNCATE && 11916 N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND && 11917 N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND && 11918 N->getOperand(0).getOpcode() != ISD::ANY_EXTEND) 11919 return SDValue(); 11920 11921 if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) && 11922 N->getOperand(1).getOpcode() != ISD::AND && 11923 N->getOperand(1).getOpcode() != ISD::OR && 11924 N->getOperand(1).getOpcode() != ISD::XOR && 11925 N->getOperand(1).getOpcode() != ISD::SELECT && 11926 N->getOperand(1).getOpcode() != ISD::SELECT_CC && 11927 N->getOperand(1).getOpcode() != ISD::TRUNCATE && 11928 N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND && 11929 N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND && 11930 N->getOperand(1).getOpcode() != ISD::ANY_EXTEND) 11931 return SDValue(); 11932 11933 SmallVector<SDValue, 4> Inputs; 11934 SmallVector<SDValue, 8> BinOps, PromOps; 11935 SmallPtrSet<SDNode *, 16> Visited; 11936 11937 for (unsigned i = 0; i < 2; ++i) { 11938 if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND || 11939 N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND || 11940 N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) && 11941 N->getOperand(i).getOperand(0).getValueType() == MVT::i1) || 11942 isa<ConstantSDNode>(N->getOperand(i))) 11943 Inputs.push_back(N->getOperand(i)); 11944 else 11945 BinOps.push_back(N->getOperand(i)); 11946 11947 if (N->getOpcode() == ISD::TRUNCATE) 11948 break; 11949 } 11950 11951 // Visit all inputs, collect all binary operations (and, or, xor and 11952 // select) that are all fed by extensions. 11953 while (!BinOps.empty()) { 11954 SDValue BinOp = BinOps.back(); 11955 BinOps.pop_back(); 11956 11957 if (!Visited.insert(BinOp.getNode()).second) 11958 continue; 11959 11960 PromOps.push_back(BinOp); 11961 11962 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) { 11963 // The condition of the select is not promoted. 11964 if (BinOp.getOpcode() == ISD::SELECT && i == 0) 11965 continue; 11966 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3) 11967 continue; 11968 11969 if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND || 11970 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND || 11971 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) && 11972 BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) || 11973 isa<ConstantSDNode>(BinOp.getOperand(i))) { 11974 Inputs.push_back(BinOp.getOperand(i)); 11975 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND || 11976 BinOp.getOperand(i).getOpcode() == ISD::OR || 11977 BinOp.getOperand(i).getOpcode() == ISD::XOR || 11978 BinOp.getOperand(i).getOpcode() == ISD::SELECT || 11979 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC || 11980 BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE || 11981 BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND || 11982 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND || 11983 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) { 11984 BinOps.push_back(BinOp.getOperand(i)); 11985 } else { 11986 // We have an input that is not an extension or another binary 11987 // operation; we'll abort this transformation. 11988 return SDValue(); 11989 } 11990 } 11991 } 11992 11993 // Make sure that this is a self-contained cluster of operations (which 11994 // is not quite the same thing as saying that everything has only one 11995 // use). 11996 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 11997 if (isa<ConstantSDNode>(Inputs[i])) 11998 continue; 11999 12000 for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(), 12001 UE = Inputs[i].getNode()->use_end(); 12002 UI != UE; ++UI) { 12003 SDNode *User = *UI; 12004 if (User != N && !Visited.count(User)) 12005 return SDValue(); 12006 12007 // Make sure that we're not going to promote the non-output-value 12008 // operand(s) or SELECT or SELECT_CC. 12009 // FIXME: Although we could sometimes handle this, and it does occur in 12010 // practice that one of the condition inputs to the select is also one of 12011 // the outputs, we currently can't deal with this. 12012 if (User->getOpcode() == ISD::SELECT) { 12013 if (User->getOperand(0) == Inputs[i]) 12014 return SDValue(); 12015 } else if (User->getOpcode() == ISD::SELECT_CC) { 12016 if (User->getOperand(0) == Inputs[i] || 12017 User->getOperand(1) == Inputs[i]) 12018 return SDValue(); 12019 } 12020 } 12021 } 12022 12023 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) { 12024 for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(), 12025 UE = PromOps[i].getNode()->use_end(); 12026 UI != UE; ++UI) { 12027 SDNode *User = *UI; 12028 if (User != N && !Visited.count(User)) 12029 return SDValue(); 12030 12031 // Make sure that we're not going to promote the non-output-value 12032 // operand(s) or SELECT or SELECT_CC. 12033 // FIXME: Although we could sometimes handle this, and it does occur in 12034 // practice that one of the condition inputs to the select is also one of 12035 // the outputs, we currently can't deal with this. 12036 if (User->getOpcode() == ISD::SELECT) { 12037 if (User->getOperand(0) == PromOps[i]) 12038 return SDValue(); 12039 } else if (User->getOpcode() == ISD::SELECT_CC) { 12040 if (User->getOperand(0) == PromOps[i] || 12041 User->getOperand(1) == PromOps[i]) 12042 return SDValue(); 12043 } 12044 } 12045 } 12046 12047 // Replace all inputs with the extension operand. 12048 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 12049 // Constants may have users outside the cluster of to-be-promoted nodes, 12050 // and so we need to replace those as we do the promotions. 12051 if (isa<ConstantSDNode>(Inputs[i])) 12052 continue; 12053 else 12054 DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0)); 12055 } 12056 12057 std::list<HandleSDNode> PromOpHandles; 12058 for (auto &PromOp : PromOps) 12059 PromOpHandles.emplace_back(PromOp); 12060 12061 // Replace all operations (these are all the same, but have a different 12062 // (i1) return type). DAG.getNode will validate that the types of 12063 // a binary operator match, so go through the list in reverse so that 12064 // we've likely promoted both operands first. Any intermediate truncations or 12065 // extensions disappear. 12066 while (!PromOpHandles.empty()) { 12067 SDValue PromOp = PromOpHandles.back().getValue(); 12068 PromOpHandles.pop_back(); 12069 12070 if (PromOp.getOpcode() == ISD::TRUNCATE || 12071 PromOp.getOpcode() == ISD::SIGN_EXTEND || 12072 PromOp.getOpcode() == ISD::ZERO_EXTEND || 12073 PromOp.getOpcode() == ISD::ANY_EXTEND) { 12074 if (!isa<ConstantSDNode>(PromOp.getOperand(0)) && 12075 PromOp.getOperand(0).getValueType() != MVT::i1) { 12076 // The operand is not yet ready (see comment below). 12077 PromOpHandles.emplace_front(PromOp); 12078 continue; 12079 } 12080 12081 SDValue RepValue = PromOp.getOperand(0); 12082 if (isa<ConstantSDNode>(RepValue)) 12083 RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue); 12084 12085 DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue); 12086 continue; 12087 } 12088 12089 unsigned C; 12090 switch (PromOp.getOpcode()) { 12091 default: C = 0; break; 12092 case ISD::SELECT: C = 1; break; 12093 case ISD::SELECT_CC: C = 2; break; 12094 } 12095 12096 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) && 12097 PromOp.getOperand(C).getValueType() != MVT::i1) || 12098 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) && 12099 PromOp.getOperand(C+1).getValueType() != MVT::i1)) { 12100 // The to-be-promoted operands of this node have not yet been 12101 // promoted (this should be rare because we're going through the 12102 // list backward, but if one of the operands has several users in 12103 // this cluster of to-be-promoted nodes, it is possible). 12104 PromOpHandles.emplace_front(PromOp); 12105 continue; 12106 } 12107 12108 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(), 12109 PromOp.getNode()->op_end()); 12110 12111 // If there are any constant inputs, make sure they're replaced now. 12112 for (unsigned i = 0; i < 2; ++i) 12113 if (isa<ConstantSDNode>(Ops[C+i])) 12114 Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]); 12115 12116 DAG.ReplaceAllUsesOfValueWith(PromOp, 12117 DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops)); 12118 } 12119 12120 // Now we're left with the initial truncation itself. 12121 if (N->getOpcode() == ISD::TRUNCATE) 12122 return N->getOperand(0); 12123 12124 // Otherwise, this is a comparison. The operands to be compared have just 12125 // changed type (to i1), but everything else is the same. 12126 return SDValue(N, 0); 12127 } 12128 12129 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N, 12130 DAGCombinerInfo &DCI) const { 12131 SelectionDAG &DAG = DCI.DAG; 12132 SDLoc dl(N); 12133 12134 // If we're tracking CR bits, we need to be careful that we don't have: 12135 // zext(binary-ops(trunc(x), trunc(y))) 12136 // or 12137 // zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...) 12138 // such that we're unnecessarily moving things into CR bits that can more 12139 // efficiently stay in GPRs. Note that if we're not certain that the high 12140 // bits are set as required by the final extension, we still may need to do 12141 // some masking to get the proper behavior. 12142 12143 // This same functionality is important on PPC64 when dealing with 12144 // 32-to-64-bit extensions; these occur often when 32-bit values are used as 12145 // the return values of functions. Because it is so similar, it is handled 12146 // here as well. 12147 12148 if (N->getValueType(0) != MVT::i32 && 12149 N->getValueType(0) != MVT::i64) 12150 return SDValue(); 12151 12152 if (!((N->getOperand(0).getValueType() == MVT::i1 && Subtarget.useCRBits()) || 12153 (N->getOperand(0).getValueType() == MVT::i32 && Subtarget.isPPC64()))) 12154 return SDValue(); 12155 12156 if (N->getOperand(0).getOpcode() != ISD::AND && 12157 N->getOperand(0).getOpcode() != ISD::OR && 12158 N->getOperand(0).getOpcode() != ISD::XOR && 12159 N->getOperand(0).getOpcode() != ISD::SELECT && 12160 N->getOperand(0).getOpcode() != ISD::SELECT_CC) 12161 return SDValue(); 12162 12163 SmallVector<SDValue, 4> Inputs; 12164 SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps; 12165 SmallPtrSet<SDNode *, 16> Visited; 12166 12167 // Visit all inputs, collect all binary operations (and, or, xor and 12168 // select) that are all fed by truncations. 12169 while (!BinOps.empty()) { 12170 SDValue BinOp = BinOps.back(); 12171 BinOps.pop_back(); 12172 12173 if (!Visited.insert(BinOp.getNode()).second) 12174 continue; 12175 12176 PromOps.push_back(BinOp); 12177 12178 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) { 12179 // The condition of the select is not promoted. 12180 if (BinOp.getOpcode() == ISD::SELECT && i == 0) 12181 continue; 12182 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3) 12183 continue; 12184 12185 if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE || 12186 isa<ConstantSDNode>(BinOp.getOperand(i))) { 12187 Inputs.push_back(BinOp.getOperand(i)); 12188 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND || 12189 BinOp.getOperand(i).getOpcode() == ISD::OR || 12190 BinOp.getOperand(i).getOpcode() == ISD::XOR || 12191 BinOp.getOperand(i).getOpcode() == ISD::SELECT || 12192 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) { 12193 BinOps.push_back(BinOp.getOperand(i)); 12194 } else { 12195 // We have an input that is not a truncation or another binary 12196 // operation; we'll abort this transformation. 12197 return SDValue(); 12198 } 12199 } 12200 } 12201 12202 // The operands of a select that must be truncated when the select is 12203 // promoted because the operand is actually part of the to-be-promoted set. 12204 DenseMap<SDNode *, EVT> SelectTruncOp[2]; 12205 12206 // Make sure that this is a self-contained cluster of operations (which 12207 // is not quite the same thing as saying that everything has only one 12208 // use). 12209 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 12210 if (isa<ConstantSDNode>(Inputs[i])) 12211 continue; 12212 12213 for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(), 12214 UE = Inputs[i].getNode()->use_end(); 12215 UI != UE; ++UI) { 12216 SDNode *User = *UI; 12217 if (User != N && !Visited.count(User)) 12218 return SDValue(); 12219 12220 // If we're going to promote the non-output-value operand(s) or SELECT or 12221 // SELECT_CC, record them for truncation. 12222 if (User->getOpcode() == ISD::SELECT) { 12223 if (User->getOperand(0) == Inputs[i]) 12224 SelectTruncOp[0].insert(std::make_pair(User, 12225 User->getOperand(0).getValueType())); 12226 } else if (User->getOpcode() == ISD::SELECT_CC) { 12227 if (User->getOperand(0) == Inputs[i]) 12228 SelectTruncOp[0].insert(std::make_pair(User, 12229 User->getOperand(0).getValueType())); 12230 if (User->getOperand(1) == Inputs[i]) 12231 SelectTruncOp[1].insert(std::make_pair(User, 12232 User->getOperand(1).getValueType())); 12233 } 12234 } 12235 } 12236 12237 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) { 12238 for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(), 12239 UE = PromOps[i].getNode()->use_end(); 12240 UI != UE; ++UI) { 12241 SDNode *User = *UI; 12242 if (User != N && !Visited.count(User)) 12243 return SDValue(); 12244 12245 // If we're going to promote the non-output-value operand(s) or SELECT or 12246 // SELECT_CC, record them for truncation. 12247 if (User->getOpcode() == ISD::SELECT) { 12248 if (User->getOperand(0) == PromOps[i]) 12249 SelectTruncOp[0].insert(std::make_pair(User, 12250 User->getOperand(0).getValueType())); 12251 } else if (User->getOpcode() == ISD::SELECT_CC) { 12252 if (User->getOperand(0) == PromOps[i]) 12253 SelectTruncOp[0].insert(std::make_pair(User, 12254 User->getOperand(0).getValueType())); 12255 if (User->getOperand(1) == PromOps[i]) 12256 SelectTruncOp[1].insert(std::make_pair(User, 12257 User->getOperand(1).getValueType())); 12258 } 12259 } 12260 } 12261 12262 unsigned PromBits = N->getOperand(0).getValueSizeInBits(); 12263 bool ReallyNeedsExt = false; 12264 if (N->getOpcode() != ISD::ANY_EXTEND) { 12265 // If all of the inputs are not already sign/zero extended, then 12266 // we'll still need to do that at the end. 12267 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 12268 if (isa<ConstantSDNode>(Inputs[i])) 12269 continue; 12270 12271 unsigned OpBits = 12272 Inputs[i].getOperand(0).getValueSizeInBits(); 12273 assert(PromBits < OpBits && "Truncation not to a smaller bit count?"); 12274 12275 if ((N->getOpcode() == ISD::ZERO_EXTEND && 12276 !DAG.MaskedValueIsZero(Inputs[i].getOperand(0), 12277 APInt::getHighBitsSet(OpBits, 12278 OpBits-PromBits))) || 12279 (N->getOpcode() == ISD::SIGN_EXTEND && 12280 DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) < 12281 (OpBits-(PromBits-1)))) { 12282 ReallyNeedsExt = true; 12283 break; 12284 } 12285 } 12286 } 12287 12288 // Replace all inputs, either with the truncation operand, or a 12289 // truncation or extension to the final output type. 12290 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 12291 // Constant inputs need to be replaced with the to-be-promoted nodes that 12292 // use them because they might have users outside of the cluster of 12293 // promoted nodes. 12294 if (isa<ConstantSDNode>(Inputs[i])) 12295 continue; 12296 12297 SDValue InSrc = Inputs[i].getOperand(0); 12298 if (Inputs[i].getValueType() == N->getValueType(0)) 12299 DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc); 12300 else if (N->getOpcode() == ISD::SIGN_EXTEND) 12301 DAG.ReplaceAllUsesOfValueWith(Inputs[i], 12302 DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0))); 12303 else if (N->getOpcode() == ISD::ZERO_EXTEND) 12304 DAG.ReplaceAllUsesOfValueWith(Inputs[i], 12305 DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0))); 12306 else 12307 DAG.ReplaceAllUsesOfValueWith(Inputs[i], 12308 DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0))); 12309 } 12310 12311 std::list<HandleSDNode> PromOpHandles; 12312 for (auto &PromOp : PromOps) 12313 PromOpHandles.emplace_back(PromOp); 12314 12315 // Replace all operations (these are all the same, but have a different 12316 // (promoted) return type). DAG.getNode will validate that the types of 12317 // a binary operator match, so go through the list in reverse so that 12318 // we've likely promoted both operands first. 12319 while (!PromOpHandles.empty()) { 12320 SDValue PromOp = PromOpHandles.back().getValue(); 12321 PromOpHandles.pop_back(); 12322 12323 unsigned C; 12324 switch (PromOp.getOpcode()) { 12325 default: C = 0; break; 12326 case ISD::SELECT: C = 1; break; 12327 case ISD::SELECT_CC: C = 2; break; 12328 } 12329 12330 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) && 12331 PromOp.getOperand(C).getValueType() != N->getValueType(0)) || 12332 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) && 12333 PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) { 12334 // The to-be-promoted operands of this node have not yet been 12335 // promoted (this should be rare because we're going through the 12336 // list backward, but if one of the operands has several users in 12337 // this cluster of to-be-promoted nodes, it is possible). 12338 PromOpHandles.emplace_front(PromOp); 12339 continue; 12340 } 12341 12342 // For SELECT and SELECT_CC nodes, we do a similar check for any 12343 // to-be-promoted comparison inputs. 12344 if (PromOp.getOpcode() == ISD::SELECT || 12345 PromOp.getOpcode() == ISD::SELECT_CC) { 12346 if ((SelectTruncOp[0].count(PromOp.getNode()) && 12347 PromOp.getOperand(0).getValueType() != N->getValueType(0)) || 12348 (SelectTruncOp[1].count(PromOp.getNode()) && 12349 PromOp.getOperand(1).getValueType() != N->getValueType(0))) { 12350 PromOpHandles.emplace_front(PromOp); 12351 continue; 12352 } 12353 } 12354 12355 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(), 12356 PromOp.getNode()->op_end()); 12357 12358 // If this node has constant inputs, then they'll need to be promoted here. 12359 for (unsigned i = 0; i < 2; ++i) { 12360 if (!isa<ConstantSDNode>(Ops[C+i])) 12361 continue; 12362 if (Ops[C+i].getValueType() == N->getValueType(0)) 12363 continue; 12364 12365 if (N->getOpcode() == ISD::SIGN_EXTEND) 12366 Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); 12367 else if (N->getOpcode() == ISD::ZERO_EXTEND) 12368 Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); 12369 else 12370 Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); 12371 } 12372 12373 // If we've promoted the comparison inputs of a SELECT or SELECT_CC, 12374 // truncate them again to the original value type. 12375 if (PromOp.getOpcode() == ISD::SELECT || 12376 PromOp.getOpcode() == ISD::SELECT_CC) { 12377 auto SI0 = SelectTruncOp[0].find(PromOp.getNode()); 12378 if (SI0 != SelectTruncOp[0].end()) 12379 Ops[0] = DAG.getNode(ISD::TRUNCATE, dl, SI0->second, Ops[0]); 12380 auto SI1 = SelectTruncOp[1].find(PromOp.getNode()); 12381 if (SI1 != SelectTruncOp[1].end()) 12382 Ops[1] = DAG.getNode(ISD::TRUNCATE, dl, SI1->second, Ops[1]); 12383 } 12384 12385 DAG.ReplaceAllUsesOfValueWith(PromOp, 12386 DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops)); 12387 } 12388 12389 // Now we're left with the initial extension itself. 12390 if (!ReallyNeedsExt) 12391 return N->getOperand(0); 12392 12393 // To zero extend, just mask off everything except for the first bit (in the 12394 // i1 case). 12395 if (N->getOpcode() == ISD::ZERO_EXTEND) 12396 return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0), 12397 DAG.getConstant(APInt::getLowBitsSet( 12398 N->getValueSizeInBits(0), PromBits), 12399 dl, N->getValueType(0))); 12400 12401 assert(N->getOpcode() == ISD::SIGN_EXTEND && 12402 "Invalid extension type"); 12403 EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0), DAG.getDataLayout()); 12404 SDValue ShiftCst = 12405 DAG.getConstant(N->getValueSizeInBits(0) - PromBits, dl, ShiftAmountTy); 12406 return DAG.getNode( 12407 ISD::SRA, dl, N->getValueType(0), 12408 DAG.getNode(ISD::SHL, dl, N->getValueType(0), N->getOperand(0), ShiftCst), 12409 ShiftCst); 12410 } 12411 12412 SDValue PPCTargetLowering::combineSetCC(SDNode *N, 12413 DAGCombinerInfo &DCI) const { 12414 assert(N->getOpcode() == ISD::SETCC && 12415 "Should be called with a SETCC node"); 12416 12417 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 12418 if (CC == ISD::SETNE || CC == ISD::SETEQ) { 12419 SDValue LHS = N->getOperand(0); 12420 SDValue RHS = N->getOperand(1); 12421 12422 // If there is a '0 - y' pattern, canonicalize the pattern to the RHS. 12423 if (LHS.getOpcode() == ISD::SUB && isNullConstant(LHS.getOperand(0)) && 12424 LHS.hasOneUse()) 12425 std::swap(LHS, RHS); 12426 12427 // x == 0-y --> x+y == 0 12428 // x != 0-y --> x+y != 0 12429 if (RHS.getOpcode() == ISD::SUB && isNullConstant(RHS.getOperand(0)) && 12430 RHS.hasOneUse()) { 12431 SDLoc DL(N); 12432 SelectionDAG &DAG = DCI.DAG; 12433 EVT VT = N->getValueType(0); 12434 EVT OpVT = LHS.getValueType(); 12435 SDValue Add = DAG.getNode(ISD::ADD, DL, OpVT, LHS, RHS.getOperand(1)); 12436 return DAG.getSetCC(DL, VT, Add, DAG.getConstant(0, DL, OpVT), CC); 12437 } 12438 } 12439 12440 return DAGCombineTruncBoolExt(N, DCI); 12441 } 12442 12443 // Is this an extending load from an f32 to an f64? 12444 static bool isFPExtLoad(SDValue Op) { 12445 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op.getNode())) 12446 return LD->getExtensionType() == ISD::EXTLOAD && 12447 Op.getValueType() == MVT::f64; 12448 return false; 12449 } 12450 12451 /// Reduces the number of fp-to-int conversion when building a vector. 12452 /// 12453 /// If this vector is built out of floating to integer conversions, 12454 /// transform it to a vector built out of floating point values followed by a 12455 /// single floating to integer conversion of the vector. 12456 /// Namely (build_vector (fptosi $A), (fptosi $B), ...) 12457 /// becomes (fptosi (build_vector ($A, $B, ...))) 12458 SDValue PPCTargetLowering:: 12459 combineElementTruncationToVectorTruncation(SDNode *N, 12460 DAGCombinerInfo &DCI) const { 12461 assert(N->getOpcode() == ISD::BUILD_VECTOR && 12462 "Should be called with a BUILD_VECTOR node"); 12463 12464 SelectionDAG &DAG = DCI.DAG; 12465 SDLoc dl(N); 12466 12467 SDValue FirstInput = N->getOperand(0); 12468 assert(FirstInput.getOpcode() == PPCISD::MFVSR && 12469 "The input operand must be an fp-to-int conversion."); 12470 12471 // This combine happens after legalization so the fp_to_[su]i nodes are 12472 // already converted to PPCSISD nodes. 12473 unsigned FirstConversion = FirstInput.getOperand(0).getOpcode(); 12474 if (FirstConversion == PPCISD::FCTIDZ || 12475 FirstConversion == PPCISD::FCTIDUZ || 12476 FirstConversion == PPCISD::FCTIWZ || 12477 FirstConversion == PPCISD::FCTIWUZ) { 12478 bool IsSplat = true; 12479 bool Is32Bit = FirstConversion == PPCISD::FCTIWZ || 12480 FirstConversion == PPCISD::FCTIWUZ; 12481 EVT SrcVT = FirstInput.getOperand(0).getValueType(); 12482 SmallVector<SDValue, 4> Ops; 12483 EVT TargetVT = N->getValueType(0); 12484 for (int i = 0, e = N->getNumOperands(); i < e; ++i) { 12485 SDValue NextOp = N->getOperand(i); 12486 if (NextOp.getOpcode() != PPCISD::MFVSR) 12487 return SDValue(); 12488 unsigned NextConversion = NextOp.getOperand(0).getOpcode(); 12489 if (NextConversion != FirstConversion) 12490 return SDValue(); 12491 // If we are converting to 32-bit integers, we need to add an FP_ROUND. 12492 // This is not valid if the input was originally double precision. It is 12493 // also not profitable to do unless this is an extending load in which 12494 // case doing this combine will allow us to combine consecutive loads. 12495 if (Is32Bit && !isFPExtLoad(NextOp.getOperand(0).getOperand(0))) 12496 return SDValue(); 12497 if (N->getOperand(i) != FirstInput) 12498 IsSplat = false; 12499 } 12500 12501 // If this is a splat, we leave it as-is since there will be only a single 12502 // fp-to-int conversion followed by a splat of the integer. This is better 12503 // for 32-bit and smaller ints and neutral for 64-bit ints. 12504 if (IsSplat) 12505 return SDValue(); 12506 12507 // Now that we know we have the right type of node, get its operands 12508 for (int i = 0, e = N->getNumOperands(); i < e; ++i) { 12509 SDValue In = N->getOperand(i).getOperand(0); 12510 if (Is32Bit) { 12511 // For 32-bit values, we need to add an FP_ROUND node (if we made it 12512 // here, we know that all inputs are extending loads so this is safe). 12513 if (In.isUndef()) 12514 Ops.push_back(DAG.getUNDEF(SrcVT)); 12515 else { 12516 SDValue Trunc = DAG.getNode(ISD::FP_ROUND, dl, 12517 MVT::f32, In.getOperand(0), 12518 DAG.getIntPtrConstant(1, dl)); 12519 Ops.push_back(Trunc); 12520 } 12521 } else 12522 Ops.push_back(In.isUndef() ? DAG.getUNDEF(SrcVT) : In.getOperand(0)); 12523 } 12524 12525 unsigned Opcode; 12526 if (FirstConversion == PPCISD::FCTIDZ || 12527 FirstConversion == PPCISD::FCTIWZ) 12528 Opcode = ISD::FP_TO_SINT; 12529 else 12530 Opcode = ISD::FP_TO_UINT; 12531 12532 EVT NewVT = TargetVT == MVT::v2i64 ? MVT::v2f64 : MVT::v4f32; 12533 SDValue BV = DAG.getBuildVector(NewVT, dl, Ops); 12534 return DAG.getNode(Opcode, dl, TargetVT, BV); 12535 } 12536 return SDValue(); 12537 } 12538 12539 /// Reduce the number of loads when building a vector. 12540 /// 12541 /// Building a vector out of multiple loads can be converted to a load 12542 /// of the vector type if the loads are consecutive. If the loads are 12543 /// consecutive but in descending order, a shuffle is added at the end 12544 /// to reorder the vector. 12545 static SDValue combineBVOfConsecutiveLoads(SDNode *N, SelectionDAG &DAG) { 12546 assert(N->getOpcode() == ISD::BUILD_VECTOR && 12547 "Should be called with a BUILD_VECTOR node"); 12548 12549 SDLoc dl(N); 12550 12551 // Return early for non byte-sized type, as they can't be consecutive. 12552 if (!N->getValueType(0).getVectorElementType().isByteSized()) 12553 return SDValue(); 12554 12555 bool InputsAreConsecutiveLoads = true; 12556 bool InputsAreReverseConsecutive = true; 12557 unsigned ElemSize = N->getValueType(0).getScalarType().getStoreSize(); 12558 SDValue FirstInput = N->getOperand(0); 12559 bool IsRoundOfExtLoad = false; 12560 12561 if (FirstInput.getOpcode() == ISD::FP_ROUND && 12562 FirstInput.getOperand(0).getOpcode() == ISD::LOAD) { 12563 LoadSDNode *LD = dyn_cast<LoadSDNode>(FirstInput.getOperand(0)); 12564 IsRoundOfExtLoad = LD->getExtensionType() == ISD::EXTLOAD; 12565 } 12566 // Not a build vector of (possibly fp_rounded) loads. 12567 if ((!IsRoundOfExtLoad && FirstInput.getOpcode() != ISD::LOAD) || 12568 N->getNumOperands() == 1) 12569 return SDValue(); 12570 12571 for (int i = 1, e = N->getNumOperands(); i < e; ++i) { 12572 // If any inputs are fp_round(extload), they all must be. 12573 if (IsRoundOfExtLoad && N->getOperand(i).getOpcode() != ISD::FP_ROUND) 12574 return SDValue(); 12575 12576 SDValue NextInput = IsRoundOfExtLoad ? N->getOperand(i).getOperand(0) : 12577 N->getOperand(i); 12578 if (NextInput.getOpcode() != ISD::LOAD) 12579 return SDValue(); 12580 12581 SDValue PreviousInput = 12582 IsRoundOfExtLoad ? N->getOperand(i-1).getOperand(0) : N->getOperand(i-1); 12583 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(PreviousInput); 12584 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(NextInput); 12585 12586 // If any inputs are fp_round(extload), they all must be. 12587 if (IsRoundOfExtLoad && LD2->getExtensionType() != ISD::EXTLOAD) 12588 return SDValue(); 12589 12590 if (!isConsecutiveLS(LD2, LD1, ElemSize, 1, DAG)) 12591 InputsAreConsecutiveLoads = false; 12592 if (!isConsecutiveLS(LD1, LD2, ElemSize, 1, DAG)) 12593 InputsAreReverseConsecutive = false; 12594 12595 // Exit early if the loads are neither consecutive nor reverse consecutive. 12596 if (!InputsAreConsecutiveLoads && !InputsAreReverseConsecutive) 12597 return SDValue(); 12598 } 12599 12600 assert(!(InputsAreConsecutiveLoads && InputsAreReverseConsecutive) && 12601 "The loads cannot be both consecutive and reverse consecutive."); 12602 12603 SDValue FirstLoadOp = 12604 IsRoundOfExtLoad ? FirstInput.getOperand(0) : FirstInput; 12605 SDValue LastLoadOp = 12606 IsRoundOfExtLoad ? N->getOperand(N->getNumOperands()-1).getOperand(0) : 12607 N->getOperand(N->getNumOperands()-1); 12608 12609 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(FirstLoadOp); 12610 LoadSDNode *LDL = dyn_cast<LoadSDNode>(LastLoadOp); 12611 if (InputsAreConsecutiveLoads) { 12612 assert(LD1 && "Input needs to be a LoadSDNode."); 12613 return DAG.getLoad(N->getValueType(0), dl, LD1->getChain(), 12614 LD1->getBasePtr(), LD1->getPointerInfo(), 12615 LD1->getAlignment()); 12616 } 12617 if (InputsAreReverseConsecutive) { 12618 assert(LDL && "Input needs to be a LoadSDNode."); 12619 SDValue Load = DAG.getLoad(N->getValueType(0), dl, LDL->getChain(), 12620 LDL->getBasePtr(), LDL->getPointerInfo(), 12621 LDL->getAlignment()); 12622 SmallVector<int, 16> Ops; 12623 for (int i = N->getNumOperands() - 1; i >= 0; i--) 12624 Ops.push_back(i); 12625 12626 return DAG.getVectorShuffle(N->getValueType(0), dl, Load, 12627 DAG.getUNDEF(N->getValueType(0)), Ops); 12628 } 12629 return SDValue(); 12630 } 12631 12632 // This function adds the required vector_shuffle needed to get 12633 // the elements of the vector extract in the correct position 12634 // as specified by the CorrectElems encoding. 12635 static SDValue addShuffleForVecExtend(SDNode *N, SelectionDAG &DAG, 12636 SDValue Input, uint64_t Elems, 12637 uint64_t CorrectElems) { 12638 SDLoc dl(N); 12639 12640 unsigned NumElems = Input.getValueType().getVectorNumElements(); 12641 SmallVector<int, 16> ShuffleMask(NumElems, -1); 12642 12643 // Knowing the element indices being extracted from the original 12644 // vector and the order in which they're being inserted, just put 12645 // them at element indices required for the instruction. 12646 for (unsigned i = 0; i < N->getNumOperands(); i++) { 12647 if (DAG.getDataLayout().isLittleEndian()) 12648 ShuffleMask[CorrectElems & 0xF] = Elems & 0xF; 12649 else 12650 ShuffleMask[(CorrectElems & 0xF0) >> 4] = (Elems & 0xF0) >> 4; 12651 CorrectElems = CorrectElems >> 8; 12652 Elems = Elems >> 8; 12653 } 12654 12655 SDValue Shuffle = 12656 DAG.getVectorShuffle(Input.getValueType(), dl, Input, 12657 DAG.getUNDEF(Input.getValueType()), ShuffleMask); 12658 12659 EVT Ty = N->getValueType(0); 12660 SDValue BV = DAG.getNode(PPCISD::SExtVElems, dl, Ty, Shuffle); 12661 return BV; 12662 } 12663 12664 // Look for build vector patterns where input operands come from sign 12665 // extended vector_extract elements of specific indices. If the correct indices 12666 // aren't used, add a vector shuffle to fix up the indices and create a new 12667 // PPCISD:SExtVElems node which selects the vector sign extend instructions 12668 // during instruction selection. 12669 static SDValue combineBVOfVecSExt(SDNode *N, SelectionDAG &DAG) { 12670 // This array encodes the indices that the vector sign extend instructions 12671 // extract from when extending from one type to another for both BE and LE. 12672 // The right nibble of each byte corresponds to the LE incides. 12673 // and the left nibble of each byte corresponds to the BE incides. 12674 // For example: 0x3074B8FC byte->word 12675 // For LE: the allowed indices are: 0x0,0x4,0x8,0xC 12676 // For BE: the allowed indices are: 0x3,0x7,0xB,0xF 12677 // For example: 0x000070F8 byte->double word 12678 // For LE: the allowed indices are: 0x0,0x8 12679 // For BE: the allowed indices are: 0x7,0xF 12680 uint64_t TargetElems[] = { 12681 0x3074B8FC, // b->w 12682 0x000070F8, // b->d 12683 0x10325476, // h->w 12684 0x00003074, // h->d 12685 0x00001032, // w->d 12686 }; 12687 12688 uint64_t Elems = 0; 12689 int Index; 12690 SDValue Input; 12691 12692 auto isSExtOfVecExtract = [&](SDValue Op) -> bool { 12693 if (!Op) 12694 return false; 12695 if (Op.getOpcode() != ISD::SIGN_EXTEND && 12696 Op.getOpcode() != ISD::SIGN_EXTEND_INREG) 12697 return false; 12698 12699 // A SIGN_EXTEND_INREG might be fed by an ANY_EXTEND to produce a value 12700 // of the right width. 12701 SDValue Extract = Op.getOperand(0); 12702 if (Extract.getOpcode() == ISD::ANY_EXTEND) 12703 Extract = Extract.getOperand(0); 12704 if (Extract.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 12705 return false; 12706 12707 ConstantSDNode *ExtOp = dyn_cast<ConstantSDNode>(Extract.getOperand(1)); 12708 if (!ExtOp) 12709 return false; 12710 12711 Index = ExtOp->getZExtValue(); 12712 if (Input && Input != Extract.getOperand(0)) 12713 return false; 12714 12715 if (!Input) 12716 Input = Extract.getOperand(0); 12717 12718 Elems = Elems << 8; 12719 Index = DAG.getDataLayout().isLittleEndian() ? Index : Index << 4; 12720 Elems |= Index; 12721 12722 return true; 12723 }; 12724 12725 // If the build vector operands aren't sign extended vector extracts, 12726 // of the same input vector, then return. 12727 for (unsigned i = 0; i < N->getNumOperands(); i++) { 12728 if (!isSExtOfVecExtract(N->getOperand(i))) { 12729 return SDValue(); 12730 } 12731 } 12732 12733 // If the vector extract indicies are not correct, add the appropriate 12734 // vector_shuffle. 12735 int TgtElemArrayIdx; 12736 int InputSize = Input.getValueType().getScalarSizeInBits(); 12737 int OutputSize = N->getValueType(0).getScalarSizeInBits(); 12738 if (InputSize + OutputSize == 40) 12739 TgtElemArrayIdx = 0; 12740 else if (InputSize + OutputSize == 72) 12741 TgtElemArrayIdx = 1; 12742 else if (InputSize + OutputSize == 48) 12743 TgtElemArrayIdx = 2; 12744 else if (InputSize + OutputSize == 80) 12745 TgtElemArrayIdx = 3; 12746 else if (InputSize + OutputSize == 96) 12747 TgtElemArrayIdx = 4; 12748 else 12749 return SDValue(); 12750 12751 uint64_t CorrectElems = TargetElems[TgtElemArrayIdx]; 12752 CorrectElems = DAG.getDataLayout().isLittleEndian() 12753 ? CorrectElems & 0x0F0F0F0F0F0F0F0F 12754 : CorrectElems & 0xF0F0F0F0F0F0F0F0; 12755 if (Elems != CorrectElems) { 12756 return addShuffleForVecExtend(N, DAG, Input, Elems, CorrectElems); 12757 } 12758 12759 // Regular lowering will catch cases where a shuffle is not needed. 12760 return SDValue(); 12761 } 12762 12763 SDValue PPCTargetLowering::DAGCombineBuildVector(SDNode *N, 12764 DAGCombinerInfo &DCI) const { 12765 assert(N->getOpcode() == ISD::BUILD_VECTOR && 12766 "Should be called with a BUILD_VECTOR node"); 12767 12768 SelectionDAG &DAG = DCI.DAG; 12769 SDLoc dl(N); 12770 12771 if (!Subtarget.hasVSX()) 12772 return SDValue(); 12773 12774 // The target independent DAG combiner will leave a build_vector of 12775 // float-to-int conversions intact. We can generate MUCH better code for 12776 // a float-to-int conversion of a vector of floats. 12777 SDValue FirstInput = N->getOperand(0); 12778 if (FirstInput.getOpcode() == PPCISD::MFVSR) { 12779 SDValue Reduced = combineElementTruncationToVectorTruncation(N, DCI); 12780 if (Reduced) 12781 return Reduced; 12782 } 12783 12784 // If we're building a vector out of consecutive loads, just load that 12785 // vector type. 12786 SDValue Reduced = combineBVOfConsecutiveLoads(N, DAG); 12787 if (Reduced) 12788 return Reduced; 12789 12790 // If we're building a vector out of extended elements from another vector 12791 // we have P9 vector integer extend instructions. The code assumes legal 12792 // input types (i.e. it can't handle things like v4i16) so do not run before 12793 // legalization. 12794 if (Subtarget.hasP9Altivec() && !DCI.isBeforeLegalize()) { 12795 Reduced = combineBVOfVecSExt(N, DAG); 12796 if (Reduced) 12797 return Reduced; 12798 } 12799 12800 12801 if (N->getValueType(0) != MVT::v2f64) 12802 return SDValue(); 12803 12804 // Looking for: 12805 // (build_vector ([su]int_to_fp (extractelt 0)), [su]int_to_fp (extractelt 1)) 12806 if (FirstInput.getOpcode() != ISD::SINT_TO_FP && 12807 FirstInput.getOpcode() != ISD::UINT_TO_FP) 12808 return SDValue(); 12809 if (N->getOperand(1).getOpcode() != ISD::SINT_TO_FP && 12810 N->getOperand(1).getOpcode() != ISD::UINT_TO_FP) 12811 return SDValue(); 12812 if (FirstInput.getOpcode() != N->getOperand(1).getOpcode()) 12813 return SDValue(); 12814 12815 SDValue Ext1 = FirstInput.getOperand(0); 12816 SDValue Ext2 = N->getOperand(1).getOperand(0); 12817 if(Ext1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 12818 Ext2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 12819 return SDValue(); 12820 12821 ConstantSDNode *Ext1Op = dyn_cast<ConstantSDNode>(Ext1.getOperand(1)); 12822 ConstantSDNode *Ext2Op = dyn_cast<ConstantSDNode>(Ext2.getOperand(1)); 12823 if (!Ext1Op || !Ext2Op) 12824 return SDValue(); 12825 if (Ext1.getOperand(0).getValueType() != MVT::v4i32 || 12826 Ext1.getOperand(0) != Ext2.getOperand(0)) 12827 return SDValue(); 12828 12829 int FirstElem = Ext1Op->getZExtValue(); 12830 int SecondElem = Ext2Op->getZExtValue(); 12831 int SubvecIdx; 12832 if (FirstElem == 0 && SecondElem == 1) 12833 SubvecIdx = Subtarget.isLittleEndian() ? 1 : 0; 12834 else if (FirstElem == 2 && SecondElem == 3) 12835 SubvecIdx = Subtarget.isLittleEndian() ? 0 : 1; 12836 else 12837 return SDValue(); 12838 12839 SDValue SrcVec = Ext1.getOperand(0); 12840 auto NodeType = (N->getOperand(1).getOpcode() == ISD::SINT_TO_FP) ? 12841 PPCISD::SINT_VEC_TO_FP : PPCISD::UINT_VEC_TO_FP; 12842 return DAG.getNode(NodeType, dl, MVT::v2f64, 12843 SrcVec, DAG.getIntPtrConstant(SubvecIdx, dl)); 12844 } 12845 12846 SDValue PPCTargetLowering::combineFPToIntToFP(SDNode *N, 12847 DAGCombinerInfo &DCI) const { 12848 assert((N->getOpcode() == ISD::SINT_TO_FP || 12849 N->getOpcode() == ISD::UINT_TO_FP) && 12850 "Need an int -> FP conversion node here"); 12851 12852 if (useSoftFloat() || !Subtarget.has64BitSupport()) 12853 return SDValue(); 12854 12855 SelectionDAG &DAG = DCI.DAG; 12856 SDLoc dl(N); 12857 SDValue Op(N, 0); 12858 12859 // Don't handle ppc_fp128 here or conversions that are out-of-range capable 12860 // from the hardware. 12861 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64) 12862 return SDValue(); 12863 if (Op.getOperand(0).getValueType().getSimpleVT() <= MVT(MVT::i1) || 12864 Op.getOperand(0).getValueType().getSimpleVT() > MVT(MVT::i64)) 12865 return SDValue(); 12866 12867 SDValue FirstOperand(Op.getOperand(0)); 12868 bool SubWordLoad = FirstOperand.getOpcode() == ISD::LOAD && 12869 (FirstOperand.getValueType() == MVT::i8 || 12870 FirstOperand.getValueType() == MVT::i16); 12871 if (Subtarget.hasP9Vector() && Subtarget.hasP9Altivec() && SubWordLoad) { 12872 bool Signed = N->getOpcode() == ISD::SINT_TO_FP; 12873 bool DstDouble = Op.getValueType() == MVT::f64; 12874 unsigned ConvOp = Signed ? 12875 (DstDouble ? PPCISD::FCFID : PPCISD::FCFIDS) : 12876 (DstDouble ? PPCISD::FCFIDU : PPCISD::FCFIDUS); 12877 SDValue WidthConst = 12878 DAG.getIntPtrConstant(FirstOperand.getValueType() == MVT::i8 ? 1 : 2, 12879 dl, false); 12880 LoadSDNode *LDN = cast<LoadSDNode>(FirstOperand.getNode()); 12881 SDValue Ops[] = { LDN->getChain(), LDN->getBasePtr(), WidthConst }; 12882 SDValue Ld = DAG.getMemIntrinsicNode(PPCISD::LXSIZX, dl, 12883 DAG.getVTList(MVT::f64, MVT::Other), 12884 Ops, MVT::i8, LDN->getMemOperand()); 12885 12886 // For signed conversion, we need to sign-extend the value in the VSR 12887 if (Signed) { 12888 SDValue ExtOps[] = { Ld, WidthConst }; 12889 SDValue Ext = DAG.getNode(PPCISD::VEXTS, dl, MVT::f64, ExtOps); 12890 return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ext); 12891 } else 12892 return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ld); 12893 } 12894 12895 12896 // For i32 intermediate values, unfortunately, the conversion functions 12897 // leave the upper 32 bits of the value are undefined. Within the set of 12898 // scalar instructions, we have no method for zero- or sign-extending the 12899 // value. Thus, we cannot handle i32 intermediate values here. 12900 if (Op.getOperand(0).getValueType() == MVT::i32) 12901 return SDValue(); 12902 12903 assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) && 12904 "UINT_TO_FP is supported only with FPCVT"); 12905 12906 // If we have FCFIDS, then use it when converting to single-precision. 12907 // Otherwise, convert to double-precision and then round. 12908 unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 12909 ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS 12910 : PPCISD::FCFIDS) 12911 : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU 12912 : PPCISD::FCFID); 12913 MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 12914 ? MVT::f32 12915 : MVT::f64; 12916 12917 // If we're converting from a float, to an int, and back to a float again, 12918 // then we don't need the store/load pair at all. 12919 if ((Op.getOperand(0).getOpcode() == ISD::FP_TO_UINT && 12920 Subtarget.hasFPCVT()) || 12921 (Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT)) { 12922 SDValue Src = Op.getOperand(0).getOperand(0); 12923 if (Src.getValueType() == MVT::f32) { 12924 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src); 12925 DCI.AddToWorklist(Src.getNode()); 12926 } else if (Src.getValueType() != MVT::f64) { 12927 // Make sure that we don't pick up a ppc_fp128 source value. 12928 return SDValue(); 12929 } 12930 12931 unsigned FCTOp = 12932 Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT ? PPCISD::FCTIDZ : 12933 PPCISD::FCTIDUZ; 12934 12935 SDValue Tmp = DAG.getNode(FCTOp, dl, MVT::f64, Src); 12936 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Tmp); 12937 12938 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) { 12939 FP = DAG.getNode(ISD::FP_ROUND, dl, 12940 MVT::f32, FP, DAG.getIntPtrConstant(0, dl)); 12941 DCI.AddToWorklist(FP.getNode()); 12942 } 12943 12944 return FP; 12945 } 12946 12947 return SDValue(); 12948 } 12949 12950 // expandVSXLoadForLE - Convert VSX loads (which may be intrinsics for 12951 // builtins) into loads with swaps. 12952 SDValue PPCTargetLowering::expandVSXLoadForLE(SDNode *N, 12953 DAGCombinerInfo &DCI) const { 12954 SelectionDAG &DAG = DCI.DAG; 12955 SDLoc dl(N); 12956 SDValue Chain; 12957 SDValue Base; 12958 MachineMemOperand *MMO; 12959 12960 switch (N->getOpcode()) { 12961 default: 12962 llvm_unreachable("Unexpected opcode for little endian VSX load"); 12963 case ISD::LOAD: { 12964 LoadSDNode *LD = cast<LoadSDNode>(N); 12965 Chain = LD->getChain(); 12966 Base = LD->getBasePtr(); 12967 MMO = LD->getMemOperand(); 12968 // If the MMO suggests this isn't a load of a full vector, leave 12969 // things alone. For a built-in, we have to make the change for 12970 // correctness, so if there is a size problem that will be a bug. 12971 if (MMO->getSize() < 16) 12972 return SDValue(); 12973 break; 12974 } 12975 case ISD::INTRINSIC_W_CHAIN: { 12976 MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N); 12977 Chain = Intrin->getChain(); 12978 // Similarly to the store case below, Intrin->getBasePtr() doesn't get 12979 // us what we want. Get operand 2 instead. 12980 Base = Intrin->getOperand(2); 12981 MMO = Intrin->getMemOperand(); 12982 break; 12983 } 12984 } 12985 12986 MVT VecTy = N->getValueType(0).getSimpleVT(); 12987 12988 // Do not expand to PPCISD::LXVD2X + PPCISD::XXSWAPD when the load is 12989 // aligned and the type is a vector with elements up to 4 bytes 12990 if (Subtarget.needsSwapsForVSXMemOps() && !(MMO->getAlignment()%16) 12991 && VecTy.getScalarSizeInBits() <= 32 ) { 12992 return SDValue(); 12993 } 12994 12995 SDValue LoadOps[] = { Chain, Base }; 12996 SDValue Load = DAG.getMemIntrinsicNode(PPCISD::LXVD2X, dl, 12997 DAG.getVTList(MVT::v2f64, MVT::Other), 12998 LoadOps, MVT::v2f64, MMO); 12999 13000 DCI.AddToWorklist(Load.getNode()); 13001 Chain = Load.getValue(1); 13002 SDValue Swap = DAG.getNode( 13003 PPCISD::XXSWAPD, dl, DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Load); 13004 DCI.AddToWorklist(Swap.getNode()); 13005 13006 // Add a bitcast if the resulting load type doesn't match v2f64. 13007 if (VecTy != MVT::v2f64) { 13008 SDValue N = DAG.getNode(ISD::BITCAST, dl, VecTy, Swap); 13009 DCI.AddToWorklist(N.getNode()); 13010 // Package {bitcast value, swap's chain} to match Load's shape. 13011 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VecTy, MVT::Other), 13012 N, Swap.getValue(1)); 13013 } 13014 13015 return Swap; 13016 } 13017 13018 // expandVSXStoreForLE - Convert VSX stores (which may be intrinsics for 13019 // builtins) into stores with swaps. 13020 SDValue PPCTargetLowering::expandVSXStoreForLE(SDNode *N, 13021 DAGCombinerInfo &DCI) const { 13022 SelectionDAG &DAG = DCI.DAG; 13023 SDLoc dl(N); 13024 SDValue Chain; 13025 SDValue Base; 13026 unsigned SrcOpnd; 13027 MachineMemOperand *MMO; 13028 13029 switch (N->getOpcode()) { 13030 default: 13031 llvm_unreachable("Unexpected opcode for little endian VSX store"); 13032 case ISD::STORE: { 13033 StoreSDNode *ST = cast<StoreSDNode>(N); 13034 Chain = ST->getChain(); 13035 Base = ST->getBasePtr(); 13036 MMO = ST->getMemOperand(); 13037 SrcOpnd = 1; 13038 // If the MMO suggests this isn't a store of a full vector, leave 13039 // things alone. For a built-in, we have to make the change for 13040 // correctness, so if there is a size problem that will be a bug. 13041 if (MMO->getSize() < 16) 13042 return SDValue(); 13043 break; 13044 } 13045 case ISD::INTRINSIC_VOID: { 13046 MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N); 13047 Chain = Intrin->getChain(); 13048 // Intrin->getBasePtr() oddly does not get what we want. 13049 Base = Intrin->getOperand(3); 13050 MMO = Intrin->getMemOperand(); 13051 SrcOpnd = 2; 13052 break; 13053 } 13054 } 13055 13056 SDValue Src = N->getOperand(SrcOpnd); 13057 MVT VecTy = Src.getValueType().getSimpleVT(); 13058 13059 // Do not expand to PPCISD::XXSWAPD and PPCISD::STXVD2X when the load is 13060 // aligned and the type is a vector with elements up to 4 bytes 13061 if (Subtarget.needsSwapsForVSXMemOps() && !(MMO->getAlignment()%16) 13062 && VecTy.getScalarSizeInBits() <= 32 ) { 13063 return SDValue(); 13064 } 13065 13066 // All stores are done as v2f64 and possible bit cast. 13067 if (VecTy != MVT::v2f64) { 13068 Src = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Src); 13069 DCI.AddToWorklist(Src.getNode()); 13070 } 13071 13072 SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl, 13073 DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Src); 13074 DCI.AddToWorklist(Swap.getNode()); 13075 Chain = Swap.getValue(1); 13076 SDValue StoreOps[] = { Chain, Swap, Base }; 13077 SDValue Store = DAG.getMemIntrinsicNode(PPCISD::STXVD2X, dl, 13078 DAG.getVTList(MVT::Other), 13079 StoreOps, VecTy, MMO); 13080 DCI.AddToWorklist(Store.getNode()); 13081 return Store; 13082 } 13083 13084 // Handle DAG combine for STORE (FP_TO_INT F). 13085 SDValue PPCTargetLowering::combineStoreFPToInt(SDNode *N, 13086 DAGCombinerInfo &DCI) const { 13087 13088 SelectionDAG &DAG = DCI.DAG; 13089 SDLoc dl(N); 13090 unsigned Opcode = N->getOperand(1).getOpcode(); 13091 13092 assert((Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT) 13093 && "Not a FP_TO_INT Instruction!"); 13094 13095 SDValue Val = N->getOperand(1).getOperand(0); 13096 EVT Op1VT = N->getOperand(1).getValueType(); 13097 EVT ResVT = Val.getValueType(); 13098 13099 // Floating point types smaller than 32 bits are not legal on Power. 13100 if (ResVT.getScalarSizeInBits() < 32) 13101 return SDValue(); 13102 13103 // Only perform combine for conversion to i64/i32 or power9 i16/i8. 13104 bool ValidTypeForStoreFltAsInt = 13105 (Op1VT == MVT::i32 || Op1VT == MVT::i64 || 13106 (Subtarget.hasP9Vector() && (Op1VT == MVT::i16 || Op1VT == MVT::i8))); 13107 13108 if (ResVT == MVT::ppcf128 || !Subtarget.hasP8Altivec() || 13109 cast<StoreSDNode>(N)->isTruncatingStore() || !ValidTypeForStoreFltAsInt) 13110 return SDValue(); 13111 13112 // Extend f32 values to f64 13113 if (ResVT.getScalarSizeInBits() == 32) { 13114 Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val); 13115 DCI.AddToWorklist(Val.getNode()); 13116 } 13117 13118 // Set signed or unsigned conversion opcode. 13119 unsigned ConvOpcode = (Opcode == ISD::FP_TO_SINT) ? 13120 PPCISD::FP_TO_SINT_IN_VSR : 13121 PPCISD::FP_TO_UINT_IN_VSR; 13122 13123 Val = DAG.getNode(ConvOpcode, 13124 dl, ResVT == MVT::f128 ? MVT::f128 : MVT::f64, Val); 13125 DCI.AddToWorklist(Val.getNode()); 13126 13127 // Set number of bytes being converted. 13128 unsigned ByteSize = Op1VT.getScalarSizeInBits() / 8; 13129 SDValue Ops[] = { N->getOperand(0), Val, N->getOperand(2), 13130 DAG.getIntPtrConstant(ByteSize, dl, false), 13131 DAG.getValueType(Op1VT) }; 13132 13133 Val = DAG.getMemIntrinsicNode(PPCISD::ST_VSR_SCAL_INT, dl, 13134 DAG.getVTList(MVT::Other), Ops, 13135 cast<StoreSDNode>(N)->getMemoryVT(), 13136 cast<StoreSDNode>(N)->getMemOperand()); 13137 13138 DCI.AddToWorklist(Val.getNode()); 13139 return Val; 13140 } 13141 13142 SDValue PPCTargetLowering::combineVReverseMemOP(ShuffleVectorSDNode *SVN, 13143 LSBaseSDNode *LSBase, 13144 DAGCombinerInfo &DCI) const { 13145 assert((ISD::isNormalLoad(LSBase) || ISD::isNormalStore(LSBase)) && 13146 "Not a reverse memop pattern!"); 13147 13148 auto IsElementReverse = [](const ShuffleVectorSDNode *SVN) -> bool { 13149 auto Mask = SVN->getMask(); 13150 int i = 0; 13151 auto I = Mask.rbegin(); 13152 auto E = Mask.rend(); 13153 13154 for (; I != E; ++I) { 13155 if (*I != i) 13156 return false; 13157 i++; 13158 } 13159 return true; 13160 }; 13161 13162 SelectionDAG &DAG = DCI.DAG; 13163 EVT VT = SVN->getValueType(0); 13164 13165 if (!isTypeLegal(VT) || !Subtarget.isLittleEndian() || !Subtarget.hasVSX()) 13166 return SDValue(); 13167 13168 // Before P9, we have PPCVSXSwapRemoval pass to hack the element order. 13169 // See comment in PPCVSXSwapRemoval.cpp. 13170 // It is conflict with PPCVSXSwapRemoval opt. So we don't do it. 13171 if (!Subtarget.hasP9Vector()) 13172 return SDValue(); 13173 13174 if(!IsElementReverse(SVN)) 13175 return SDValue(); 13176 13177 if (LSBase->getOpcode() == ISD::LOAD) { 13178 SDLoc dl(SVN); 13179 SDValue LoadOps[] = {LSBase->getChain(), LSBase->getBasePtr()}; 13180 return DAG.getMemIntrinsicNode( 13181 PPCISD::LOAD_VEC_BE, dl, DAG.getVTList(VT, MVT::Other), LoadOps, 13182 LSBase->getMemoryVT(), LSBase->getMemOperand()); 13183 } 13184 13185 if (LSBase->getOpcode() == ISD::STORE) { 13186 SDLoc dl(LSBase); 13187 SDValue StoreOps[] = {LSBase->getChain(), SVN->getOperand(0), 13188 LSBase->getBasePtr()}; 13189 return DAG.getMemIntrinsicNode( 13190 PPCISD::STORE_VEC_BE, dl, DAG.getVTList(MVT::Other), StoreOps, 13191 LSBase->getMemoryVT(), LSBase->getMemOperand()); 13192 } 13193 13194 llvm_unreachable("Expected a load or store node here"); 13195 } 13196 13197 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N, 13198 DAGCombinerInfo &DCI) const { 13199 SelectionDAG &DAG = DCI.DAG; 13200 SDLoc dl(N); 13201 switch (N->getOpcode()) { 13202 default: break; 13203 case ISD::ADD: 13204 return combineADD(N, DCI); 13205 case ISD::SHL: 13206 return combineSHL(N, DCI); 13207 case ISD::SRA: 13208 return combineSRA(N, DCI); 13209 case ISD::SRL: 13210 return combineSRL(N, DCI); 13211 case ISD::MUL: 13212 return combineMUL(N, DCI); 13213 case PPCISD::SHL: 13214 if (isNullConstant(N->getOperand(0))) // 0 << V -> 0. 13215 return N->getOperand(0); 13216 break; 13217 case PPCISD::SRL: 13218 if (isNullConstant(N->getOperand(0))) // 0 >>u V -> 0. 13219 return N->getOperand(0); 13220 break; 13221 case PPCISD::SRA: 13222 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) { 13223 if (C->isNullValue() || // 0 >>s V -> 0. 13224 C->isAllOnesValue()) // -1 >>s V -> -1. 13225 return N->getOperand(0); 13226 } 13227 break; 13228 case ISD::SIGN_EXTEND: 13229 case ISD::ZERO_EXTEND: 13230 case ISD::ANY_EXTEND: 13231 return DAGCombineExtBoolTrunc(N, DCI); 13232 case ISD::TRUNCATE: 13233 return combineTRUNCATE(N, DCI); 13234 case ISD::SETCC: 13235 if (SDValue CSCC = combineSetCC(N, DCI)) 13236 return CSCC; 13237 LLVM_FALLTHROUGH; 13238 case ISD::SELECT_CC: 13239 return DAGCombineTruncBoolExt(N, DCI); 13240 case ISD::SINT_TO_FP: 13241 case ISD::UINT_TO_FP: 13242 return combineFPToIntToFP(N, DCI); 13243 case ISD::VECTOR_SHUFFLE: 13244 if (ISD::isNormalLoad(N->getOperand(0).getNode())) { 13245 LSBaseSDNode* LSBase = cast<LSBaseSDNode>(N->getOperand(0)); 13246 return combineVReverseMemOP(cast<ShuffleVectorSDNode>(N), LSBase, DCI); 13247 } 13248 break; 13249 case ISD::STORE: { 13250 13251 EVT Op1VT = N->getOperand(1).getValueType(); 13252 unsigned Opcode = N->getOperand(1).getOpcode(); 13253 13254 if (Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT) { 13255 SDValue Val= combineStoreFPToInt(N, DCI); 13256 if (Val) 13257 return Val; 13258 } 13259 13260 if (Opcode == ISD::VECTOR_SHUFFLE && ISD::isNormalStore(N)) { 13261 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N->getOperand(1)); 13262 SDValue Val= combineVReverseMemOP(SVN, cast<LSBaseSDNode>(N), DCI); 13263 if (Val) 13264 return Val; 13265 } 13266 13267 // Turn STORE (BSWAP) -> sthbrx/stwbrx. 13268 if (cast<StoreSDNode>(N)->isUnindexed() && Opcode == ISD::BSWAP && 13269 N->getOperand(1).getNode()->hasOneUse() && 13270 (Op1VT == MVT::i32 || Op1VT == MVT::i16 || 13271 (Subtarget.hasLDBRX() && Subtarget.isPPC64() && Op1VT == MVT::i64))) { 13272 13273 // STBRX can only handle simple types and it makes no sense to store less 13274 // two bytes in byte-reversed order. 13275 EVT mVT = cast<StoreSDNode>(N)->getMemoryVT(); 13276 if (mVT.isExtended() || mVT.getSizeInBits() < 16) 13277 break; 13278 13279 SDValue BSwapOp = N->getOperand(1).getOperand(0); 13280 // Do an any-extend to 32-bits if this is a half-word input. 13281 if (BSwapOp.getValueType() == MVT::i16) 13282 BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp); 13283 13284 // If the type of BSWAP operand is wider than stored memory width 13285 // it need to be shifted to the right side before STBRX. 13286 if (Op1VT.bitsGT(mVT)) { 13287 int Shift = Op1VT.getSizeInBits() - mVT.getSizeInBits(); 13288 BSwapOp = DAG.getNode(ISD::SRL, dl, Op1VT, BSwapOp, 13289 DAG.getConstant(Shift, dl, MVT::i32)); 13290 // Need to truncate if this is a bswap of i64 stored as i32/i16. 13291 if (Op1VT == MVT::i64) 13292 BSwapOp = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BSwapOp); 13293 } 13294 13295 SDValue Ops[] = { 13296 N->getOperand(0), BSwapOp, N->getOperand(2), DAG.getValueType(mVT) 13297 }; 13298 return 13299 DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other), 13300 Ops, cast<StoreSDNode>(N)->getMemoryVT(), 13301 cast<StoreSDNode>(N)->getMemOperand()); 13302 } 13303 13304 // STORE Constant:i32<0> -> STORE<trunc to i32> Constant:i64<0> 13305 // So it can increase the chance of CSE constant construction. 13306 if (Subtarget.isPPC64() && !DCI.isBeforeLegalize() && 13307 isa<ConstantSDNode>(N->getOperand(1)) && Op1VT == MVT::i32) { 13308 // Need to sign-extended to 64-bits to handle negative values. 13309 EVT MemVT = cast<StoreSDNode>(N)->getMemoryVT(); 13310 uint64_t Val64 = SignExtend64(N->getConstantOperandVal(1), 13311 MemVT.getSizeInBits()); 13312 SDValue Const64 = DAG.getConstant(Val64, dl, MVT::i64); 13313 13314 // DAG.getTruncStore() can't be used here because it doesn't accept 13315 // the general (base + offset) addressing mode. 13316 // So we use UpdateNodeOperands and setTruncatingStore instead. 13317 DAG.UpdateNodeOperands(N, N->getOperand(0), Const64, N->getOperand(2), 13318 N->getOperand(3)); 13319 cast<StoreSDNode>(N)->setTruncatingStore(true); 13320 return SDValue(N, 0); 13321 } 13322 13323 // For little endian, VSX stores require generating xxswapd/lxvd2x. 13324 // Not needed on ISA 3.0 based CPUs since we have a non-permuting store. 13325 if (Op1VT.isSimple()) { 13326 MVT StoreVT = Op1VT.getSimpleVT(); 13327 if (Subtarget.needsSwapsForVSXMemOps() && 13328 (StoreVT == MVT::v2f64 || StoreVT == MVT::v2i64 || 13329 StoreVT == MVT::v4f32 || StoreVT == MVT::v4i32)) 13330 return expandVSXStoreForLE(N, DCI); 13331 } 13332 break; 13333 } 13334 case ISD::LOAD: { 13335 LoadSDNode *LD = cast<LoadSDNode>(N); 13336 EVT VT = LD->getValueType(0); 13337 13338 // For little endian, VSX loads require generating lxvd2x/xxswapd. 13339 // Not needed on ISA 3.0 based CPUs since we have a non-permuting load. 13340 if (VT.isSimple()) { 13341 MVT LoadVT = VT.getSimpleVT(); 13342 if (Subtarget.needsSwapsForVSXMemOps() && 13343 (LoadVT == MVT::v2f64 || LoadVT == MVT::v2i64 || 13344 LoadVT == MVT::v4f32 || LoadVT == MVT::v4i32)) 13345 return expandVSXLoadForLE(N, DCI); 13346 } 13347 13348 // We sometimes end up with a 64-bit integer load, from which we extract 13349 // two single-precision floating-point numbers. This happens with 13350 // std::complex<float>, and other similar structures, because of the way we 13351 // canonicalize structure copies. However, if we lack direct moves, 13352 // then the final bitcasts from the extracted integer values to the 13353 // floating-point numbers turn into store/load pairs. Even with direct moves, 13354 // just loading the two floating-point numbers is likely better. 13355 auto ReplaceTwoFloatLoad = [&]() { 13356 if (VT != MVT::i64) 13357 return false; 13358 13359 if (LD->getExtensionType() != ISD::NON_EXTLOAD || 13360 LD->isVolatile()) 13361 return false; 13362 13363 // We're looking for a sequence like this: 13364 // t13: i64,ch = load<LD8[%ref.tmp]> t0, t6, undef:i64 13365 // t16: i64 = srl t13, Constant:i32<32> 13366 // t17: i32 = truncate t16 13367 // t18: f32 = bitcast t17 13368 // t19: i32 = truncate t13 13369 // t20: f32 = bitcast t19 13370 13371 if (!LD->hasNUsesOfValue(2, 0)) 13372 return false; 13373 13374 auto UI = LD->use_begin(); 13375 while (UI.getUse().getResNo() != 0) ++UI; 13376 SDNode *Trunc = *UI++; 13377 while (UI.getUse().getResNo() != 0) ++UI; 13378 SDNode *RightShift = *UI; 13379 if (Trunc->getOpcode() != ISD::TRUNCATE) 13380 std::swap(Trunc, RightShift); 13381 13382 if (Trunc->getOpcode() != ISD::TRUNCATE || 13383 Trunc->getValueType(0) != MVT::i32 || 13384 !Trunc->hasOneUse()) 13385 return false; 13386 if (RightShift->getOpcode() != ISD::SRL || 13387 !isa<ConstantSDNode>(RightShift->getOperand(1)) || 13388 RightShift->getConstantOperandVal(1) != 32 || 13389 !RightShift->hasOneUse()) 13390 return false; 13391 13392 SDNode *Trunc2 = *RightShift->use_begin(); 13393 if (Trunc2->getOpcode() != ISD::TRUNCATE || 13394 Trunc2->getValueType(0) != MVT::i32 || 13395 !Trunc2->hasOneUse()) 13396 return false; 13397 13398 SDNode *Bitcast = *Trunc->use_begin(); 13399 SDNode *Bitcast2 = *Trunc2->use_begin(); 13400 13401 if (Bitcast->getOpcode() != ISD::BITCAST || 13402 Bitcast->getValueType(0) != MVT::f32) 13403 return false; 13404 if (Bitcast2->getOpcode() != ISD::BITCAST || 13405 Bitcast2->getValueType(0) != MVT::f32) 13406 return false; 13407 13408 if (Subtarget.isLittleEndian()) 13409 std::swap(Bitcast, Bitcast2); 13410 13411 // Bitcast has the second float (in memory-layout order) and Bitcast2 13412 // has the first one. 13413 13414 SDValue BasePtr = LD->getBasePtr(); 13415 if (LD->isIndexed()) { 13416 assert(LD->getAddressingMode() == ISD::PRE_INC && 13417 "Non-pre-inc AM on PPC?"); 13418 BasePtr = 13419 DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, 13420 LD->getOffset()); 13421 } 13422 13423 auto MMOFlags = 13424 LD->getMemOperand()->getFlags() & ~MachineMemOperand::MOVolatile; 13425 SDValue FloatLoad = DAG.getLoad(MVT::f32, dl, LD->getChain(), BasePtr, 13426 LD->getPointerInfo(), LD->getAlignment(), 13427 MMOFlags, LD->getAAInfo()); 13428 SDValue AddPtr = 13429 DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), 13430 BasePtr, DAG.getIntPtrConstant(4, dl)); 13431 SDValue FloatLoad2 = DAG.getLoad( 13432 MVT::f32, dl, SDValue(FloatLoad.getNode(), 1), AddPtr, 13433 LD->getPointerInfo().getWithOffset(4), 13434 MinAlign(LD->getAlignment(), 4), MMOFlags, LD->getAAInfo()); 13435 13436 if (LD->isIndexed()) { 13437 // Note that DAGCombine should re-form any pre-increment load(s) from 13438 // what is produced here if that makes sense. 13439 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), BasePtr); 13440 } 13441 13442 DCI.CombineTo(Bitcast2, FloatLoad); 13443 DCI.CombineTo(Bitcast, FloatLoad2); 13444 13445 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, LD->isIndexed() ? 2 : 1), 13446 SDValue(FloatLoad2.getNode(), 1)); 13447 return true; 13448 }; 13449 13450 if (ReplaceTwoFloatLoad()) 13451 return SDValue(N, 0); 13452 13453 EVT MemVT = LD->getMemoryVT(); 13454 Type *Ty = MemVT.getTypeForEVT(*DAG.getContext()); 13455 unsigned ABIAlignment = DAG.getDataLayout().getABITypeAlignment(Ty); 13456 Type *STy = MemVT.getScalarType().getTypeForEVT(*DAG.getContext()); 13457 unsigned ScalarABIAlignment = DAG.getDataLayout().getABITypeAlignment(STy); 13458 if (LD->isUnindexed() && VT.isVector() && 13459 ((Subtarget.hasAltivec() && ISD::isNON_EXTLoad(N) && 13460 // P8 and later hardware should just use LOAD. 13461 !Subtarget.hasP8Vector() && (VT == MVT::v16i8 || VT == MVT::v8i16 || 13462 VT == MVT::v4i32 || VT == MVT::v4f32)) || 13463 (Subtarget.hasQPX() && (VT == MVT::v4f64 || VT == MVT::v4f32) && 13464 LD->getAlignment() >= ScalarABIAlignment)) && 13465 LD->getAlignment() < ABIAlignment) { 13466 // This is a type-legal unaligned Altivec or QPX load. 13467 SDValue Chain = LD->getChain(); 13468 SDValue Ptr = LD->getBasePtr(); 13469 bool isLittleEndian = Subtarget.isLittleEndian(); 13470 13471 // This implements the loading of unaligned vectors as described in 13472 // the venerable Apple Velocity Engine overview. Specifically: 13473 // https://developer.apple.com/hardwaredrivers/ve/alignment.html 13474 // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html 13475 // 13476 // The general idea is to expand a sequence of one or more unaligned 13477 // loads into an alignment-based permutation-control instruction (lvsl 13478 // or lvsr), a series of regular vector loads (which always truncate 13479 // their input address to an aligned address), and a series of 13480 // permutations. The results of these permutations are the requested 13481 // loaded values. The trick is that the last "extra" load is not taken 13482 // from the address you might suspect (sizeof(vector) bytes after the 13483 // last requested load), but rather sizeof(vector) - 1 bytes after the 13484 // last requested vector. The point of this is to avoid a page fault if 13485 // the base address happened to be aligned. This works because if the 13486 // base address is aligned, then adding less than a full vector length 13487 // will cause the last vector in the sequence to be (re)loaded. 13488 // Otherwise, the next vector will be fetched as you might suspect was 13489 // necessary. 13490 13491 // We might be able to reuse the permutation generation from 13492 // a different base address offset from this one by an aligned amount. 13493 // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this 13494 // optimization later. 13495 Intrinsic::ID Intr, IntrLD, IntrPerm; 13496 MVT PermCntlTy, PermTy, LDTy; 13497 if (Subtarget.hasAltivec()) { 13498 Intr = isLittleEndian ? Intrinsic::ppc_altivec_lvsr : 13499 Intrinsic::ppc_altivec_lvsl; 13500 IntrLD = Intrinsic::ppc_altivec_lvx; 13501 IntrPerm = Intrinsic::ppc_altivec_vperm; 13502 PermCntlTy = MVT::v16i8; 13503 PermTy = MVT::v4i32; 13504 LDTy = MVT::v4i32; 13505 } else { 13506 Intr = MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlpcld : 13507 Intrinsic::ppc_qpx_qvlpcls; 13508 IntrLD = MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlfd : 13509 Intrinsic::ppc_qpx_qvlfs; 13510 IntrPerm = Intrinsic::ppc_qpx_qvfperm; 13511 PermCntlTy = MVT::v4f64; 13512 PermTy = MVT::v4f64; 13513 LDTy = MemVT.getSimpleVT(); 13514 } 13515 13516 SDValue PermCntl = BuildIntrinsicOp(Intr, Ptr, DAG, dl, PermCntlTy); 13517 13518 // Create the new MMO for the new base load. It is like the original MMO, 13519 // but represents an area in memory almost twice the vector size centered 13520 // on the original address. If the address is unaligned, we might start 13521 // reading up to (sizeof(vector)-1) bytes below the address of the 13522 // original unaligned load. 13523 MachineFunction &MF = DAG.getMachineFunction(); 13524 MachineMemOperand *BaseMMO = 13525 MF.getMachineMemOperand(LD->getMemOperand(), 13526 -(long)MemVT.getStoreSize()+1, 13527 2*MemVT.getStoreSize()-1); 13528 13529 // Create the new base load. 13530 SDValue LDXIntID = 13531 DAG.getTargetConstant(IntrLD, dl, getPointerTy(MF.getDataLayout())); 13532 SDValue BaseLoadOps[] = { Chain, LDXIntID, Ptr }; 13533 SDValue BaseLoad = 13534 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl, 13535 DAG.getVTList(PermTy, MVT::Other), 13536 BaseLoadOps, LDTy, BaseMMO); 13537 13538 // Note that the value of IncOffset (which is provided to the next 13539 // load's pointer info offset value, and thus used to calculate the 13540 // alignment), and the value of IncValue (which is actually used to 13541 // increment the pointer value) are different! This is because we 13542 // require the next load to appear to be aligned, even though it 13543 // is actually offset from the base pointer by a lesser amount. 13544 int IncOffset = VT.getSizeInBits() / 8; 13545 int IncValue = IncOffset; 13546 13547 // Walk (both up and down) the chain looking for another load at the real 13548 // (aligned) offset (the alignment of the other load does not matter in 13549 // this case). If found, then do not use the offset reduction trick, as 13550 // that will prevent the loads from being later combined (as they would 13551 // otherwise be duplicates). 13552 if (!findConsecutiveLoad(LD, DAG)) 13553 --IncValue; 13554 13555 SDValue Increment = 13556 DAG.getConstant(IncValue, dl, getPointerTy(MF.getDataLayout())); 13557 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment); 13558 13559 MachineMemOperand *ExtraMMO = 13560 MF.getMachineMemOperand(LD->getMemOperand(), 13561 1, 2*MemVT.getStoreSize()-1); 13562 SDValue ExtraLoadOps[] = { Chain, LDXIntID, Ptr }; 13563 SDValue ExtraLoad = 13564 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl, 13565 DAG.getVTList(PermTy, MVT::Other), 13566 ExtraLoadOps, LDTy, ExtraMMO); 13567 13568 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 13569 BaseLoad.getValue(1), ExtraLoad.getValue(1)); 13570 13571 // Because vperm has a big-endian bias, we must reverse the order 13572 // of the input vectors and complement the permute control vector 13573 // when generating little endian code. We have already handled the 13574 // latter by using lvsr instead of lvsl, so just reverse BaseLoad 13575 // and ExtraLoad here. 13576 SDValue Perm; 13577 if (isLittleEndian) 13578 Perm = BuildIntrinsicOp(IntrPerm, 13579 ExtraLoad, BaseLoad, PermCntl, DAG, dl); 13580 else 13581 Perm = BuildIntrinsicOp(IntrPerm, 13582 BaseLoad, ExtraLoad, PermCntl, DAG, dl); 13583 13584 if (VT != PermTy) 13585 Perm = Subtarget.hasAltivec() ? 13586 DAG.getNode(ISD::BITCAST, dl, VT, Perm) : 13587 DAG.getNode(ISD::FP_ROUND, dl, VT, Perm, // QPX 13588 DAG.getTargetConstant(1, dl, MVT::i64)); 13589 // second argument is 1 because this rounding 13590 // is always exact. 13591 13592 // The output of the permutation is our loaded result, the TokenFactor is 13593 // our new chain. 13594 DCI.CombineTo(N, Perm, TF); 13595 return SDValue(N, 0); 13596 } 13597 } 13598 break; 13599 case ISD::INTRINSIC_WO_CHAIN: { 13600 bool isLittleEndian = Subtarget.isLittleEndian(); 13601 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 13602 Intrinsic::ID Intr = (isLittleEndian ? Intrinsic::ppc_altivec_lvsr 13603 : Intrinsic::ppc_altivec_lvsl); 13604 if ((IID == Intr || 13605 IID == Intrinsic::ppc_qpx_qvlpcld || 13606 IID == Intrinsic::ppc_qpx_qvlpcls) && 13607 N->getOperand(1)->getOpcode() == ISD::ADD) { 13608 SDValue Add = N->getOperand(1); 13609 13610 int Bits = IID == Intrinsic::ppc_qpx_qvlpcld ? 13611 5 /* 32 byte alignment */ : 4 /* 16 byte alignment */; 13612 13613 if (DAG.MaskedValueIsZero(Add->getOperand(1), 13614 APInt::getAllOnesValue(Bits /* alignment */) 13615 .zext(Add.getScalarValueSizeInBits()))) { 13616 SDNode *BasePtr = Add->getOperand(0).getNode(); 13617 for (SDNode::use_iterator UI = BasePtr->use_begin(), 13618 UE = BasePtr->use_end(); 13619 UI != UE; ++UI) { 13620 if (UI->getOpcode() == ISD::INTRINSIC_WO_CHAIN && 13621 cast<ConstantSDNode>(UI->getOperand(0))->getZExtValue() == IID) { 13622 // We've found another LVSL/LVSR, and this address is an aligned 13623 // multiple of that one. The results will be the same, so use the 13624 // one we've just found instead. 13625 13626 return SDValue(*UI, 0); 13627 } 13628 } 13629 } 13630 13631 if (isa<ConstantSDNode>(Add->getOperand(1))) { 13632 SDNode *BasePtr = Add->getOperand(0).getNode(); 13633 for (SDNode::use_iterator UI = BasePtr->use_begin(), 13634 UE = BasePtr->use_end(); UI != UE; ++UI) { 13635 if (UI->getOpcode() == ISD::ADD && 13636 isa<ConstantSDNode>(UI->getOperand(1)) && 13637 (cast<ConstantSDNode>(Add->getOperand(1))->getZExtValue() - 13638 cast<ConstantSDNode>(UI->getOperand(1))->getZExtValue()) % 13639 (1ULL << Bits) == 0) { 13640 SDNode *OtherAdd = *UI; 13641 for (SDNode::use_iterator VI = OtherAdd->use_begin(), 13642 VE = OtherAdd->use_end(); VI != VE; ++VI) { 13643 if (VI->getOpcode() == ISD::INTRINSIC_WO_CHAIN && 13644 cast<ConstantSDNode>(VI->getOperand(0))->getZExtValue() == IID) { 13645 return SDValue(*VI, 0); 13646 } 13647 } 13648 } 13649 } 13650 } 13651 } 13652 13653 // Combine vmaxsw/h/b(a, a's negation) to abs(a) 13654 // Expose the vabsduw/h/b opportunity for down stream 13655 if (!DCI.isAfterLegalizeDAG() && Subtarget.hasP9Altivec() && 13656 (IID == Intrinsic::ppc_altivec_vmaxsw || 13657 IID == Intrinsic::ppc_altivec_vmaxsh || 13658 IID == Intrinsic::ppc_altivec_vmaxsb)) { 13659 SDValue V1 = N->getOperand(1); 13660 SDValue V2 = N->getOperand(2); 13661 if ((V1.getSimpleValueType() == MVT::v4i32 || 13662 V1.getSimpleValueType() == MVT::v8i16 || 13663 V1.getSimpleValueType() == MVT::v16i8) && 13664 V1.getSimpleValueType() == V2.getSimpleValueType()) { 13665 // (0-a, a) 13666 if (V1.getOpcode() == ISD::SUB && 13667 ISD::isBuildVectorAllZeros(V1.getOperand(0).getNode()) && 13668 V1.getOperand(1) == V2) { 13669 return DAG.getNode(ISD::ABS, dl, V2.getValueType(), V2); 13670 } 13671 // (a, 0-a) 13672 if (V2.getOpcode() == ISD::SUB && 13673 ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()) && 13674 V2.getOperand(1) == V1) { 13675 return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1); 13676 } 13677 // (x-y, y-x) 13678 if (V1.getOpcode() == ISD::SUB && V2.getOpcode() == ISD::SUB && 13679 V1.getOperand(0) == V2.getOperand(1) && 13680 V1.getOperand(1) == V2.getOperand(0)) { 13681 return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1); 13682 } 13683 } 13684 } 13685 } 13686 13687 break; 13688 case ISD::INTRINSIC_W_CHAIN: 13689 // For little endian, VSX loads require generating lxvd2x/xxswapd. 13690 // Not needed on ISA 3.0 based CPUs since we have a non-permuting load. 13691 if (Subtarget.needsSwapsForVSXMemOps()) { 13692 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 13693 default: 13694 break; 13695 case Intrinsic::ppc_vsx_lxvw4x: 13696 case Intrinsic::ppc_vsx_lxvd2x: 13697 return expandVSXLoadForLE(N, DCI); 13698 } 13699 } 13700 break; 13701 case ISD::INTRINSIC_VOID: 13702 // For little endian, VSX stores require generating xxswapd/stxvd2x. 13703 // Not needed on ISA 3.0 based CPUs since we have a non-permuting store. 13704 if (Subtarget.needsSwapsForVSXMemOps()) { 13705 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 13706 default: 13707 break; 13708 case Intrinsic::ppc_vsx_stxvw4x: 13709 case Intrinsic::ppc_vsx_stxvd2x: 13710 return expandVSXStoreForLE(N, DCI); 13711 } 13712 } 13713 break; 13714 case ISD::BSWAP: 13715 // Turn BSWAP (LOAD) -> lhbrx/lwbrx. 13716 if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) && 13717 N->getOperand(0).hasOneUse() && 13718 (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 || 13719 (Subtarget.hasLDBRX() && Subtarget.isPPC64() && 13720 N->getValueType(0) == MVT::i64))) { 13721 SDValue Load = N->getOperand(0); 13722 LoadSDNode *LD = cast<LoadSDNode>(Load); 13723 // Create the byte-swapping load. 13724 SDValue Ops[] = { 13725 LD->getChain(), // Chain 13726 LD->getBasePtr(), // Ptr 13727 DAG.getValueType(N->getValueType(0)) // VT 13728 }; 13729 SDValue BSLoad = 13730 DAG.getMemIntrinsicNode(PPCISD::LBRX, dl, 13731 DAG.getVTList(N->getValueType(0) == MVT::i64 ? 13732 MVT::i64 : MVT::i32, MVT::Other), 13733 Ops, LD->getMemoryVT(), LD->getMemOperand()); 13734 13735 // If this is an i16 load, insert the truncate. 13736 SDValue ResVal = BSLoad; 13737 if (N->getValueType(0) == MVT::i16) 13738 ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad); 13739 13740 // First, combine the bswap away. This makes the value produced by the 13741 // load dead. 13742 DCI.CombineTo(N, ResVal); 13743 13744 // Next, combine the load away, we give it a bogus result value but a real 13745 // chain result. The result value is dead because the bswap is dead. 13746 DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1)); 13747 13748 // Return N so it doesn't get rechecked! 13749 return SDValue(N, 0); 13750 } 13751 break; 13752 case PPCISD::VCMP: 13753 // If a VCMPo node already exists with exactly the same operands as this 13754 // node, use its result instead of this node (VCMPo computes both a CR6 and 13755 // a normal output). 13756 // 13757 if (!N->getOperand(0).hasOneUse() && 13758 !N->getOperand(1).hasOneUse() && 13759 !N->getOperand(2).hasOneUse()) { 13760 13761 // Scan all of the users of the LHS, looking for VCMPo's that match. 13762 SDNode *VCMPoNode = nullptr; 13763 13764 SDNode *LHSN = N->getOperand(0).getNode(); 13765 for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end(); 13766 UI != E; ++UI) 13767 if (UI->getOpcode() == PPCISD::VCMPo && 13768 UI->getOperand(1) == N->getOperand(1) && 13769 UI->getOperand(2) == N->getOperand(2) && 13770 UI->getOperand(0) == N->getOperand(0)) { 13771 VCMPoNode = *UI; 13772 break; 13773 } 13774 13775 // If there is no VCMPo node, or if the flag value has a single use, don't 13776 // transform this. 13777 if (!VCMPoNode || VCMPoNode->hasNUsesOfValue(0, 1)) 13778 break; 13779 13780 // Look at the (necessarily single) use of the flag value. If it has a 13781 // chain, this transformation is more complex. Note that multiple things 13782 // could use the value result, which we should ignore. 13783 SDNode *FlagUser = nullptr; 13784 for (SDNode::use_iterator UI = VCMPoNode->use_begin(); 13785 FlagUser == nullptr; ++UI) { 13786 assert(UI != VCMPoNode->use_end() && "Didn't find user!"); 13787 SDNode *User = *UI; 13788 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) { 13789 if (User->getOperand(i) == SDValue(VCMPoNode, 1)) { 13790 FlagUser = User; 13791 break; 13792 } 13793 } 13794 } 13795 13796 // If the user is a MFOCRF instruction, we know this is safe. 13797 // Otherwise we give up for right now. 13798 if (FlagUser->getOpcode() == PPCISD::MFOCRF) 13799 return SDValue(VCMPoNode, 0); 13800 } 13801 break; 13802 case ISD::BRCOND: { 13803 SDValue Cond = N->getOperand(1); 13804 SDValue Target = N->getOperand(2); 13805 13806 if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN && 13807 cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() == 13808 Intrinsic::loop_decrement) { 13809 13810 // We now need to make the intrinsic dead (it cannot be instruction 13811 // selected). 13812 DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0)); 13813 assert(Cond.getNode()->hasOneUse() && 13814 "Counter decrement has more than one use"); 13815 13816 return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other, 13817 N->getOperand(0), Target); 13818 } 13819 } 13820 break; 13821 case ISD::BR_CC: { 13822 // If this is a branch on an altivec predicate comparison, lower this so 13823 // that we don't have to do a MFOCRF: instead, branch directly on CR6. This 13824 // lowering is done pre-legalize, because the legalizer lowers the predicate 13825 // compare down to code that is difficult to reassemble. 13826 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get(); 13827 SDValue LHS = N->getOperand(2), RHS = N->getOperand(3); 13828 13829 // Sometimes the promoted value of the intrinsic is ANDed by some non-zero 13830 // value. If so, pass-through the AND to get to the intrinsic. 13831 if (LHS.getOpcode() == ISD::AND && 13832 LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN && 13833 cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() == 13834 Intrinsic::loop_decrement && 13835 isa<ConstantSDNode>(LHS.getOperand(1)) && 13836 !isNullConstant(LHS.getOperand(1))) 13837 LHS = LHS.getOperand(0); 13838 13839 if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN && 13840 cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() == 13841 Intrinsic::loop_decrement && 13842 isa<ConstantSDNode>(RHS)) { 13843 assert((CC == ISD::SETEQ || CC == ISD::SETNE) && 13844 "Counter decrement comparison is not EQ or NE"); 13845 13846 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue(); 13847 bool isBDNZ = (CC == ISD::SETEQ && Val) || 13848 (CC == ISD::SETNE && !Val); 13849 13850 // We now need to make the intrinsic dead (it cannot be instruction 13851 // selected). 13852 DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0)); 13853 assert(LHS.getNode()->hasOneUse() && 13854 "Counter decrement has more than one use"); 13855 13856 return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other, 13857 N->getOperand(0), N->getOperand(4)); 13858 } 13859 13860 int CompareOpc; 13861 bool isDot; 13862 13863 if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN && 13864 isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) && 13865 getVectorCompareInfo(LHS, CompareOpc, isDot, Subtarget)) { 13866 assert(isDot && "Can't compare against a vector result!"); 13867 13868 // If this is a comparison against something other than 0/1, then we know 13869 // that the condition is never/always true. 13870 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue(); 13871 if (Val != 0 && Val != 1) { 13872 if (CC == ISD::SETEQ) // Cond never true, remove branch. 13873 return N->getOperand(0); 13874 // Always !=, turn it into an unconditional branch. 13875 return DAG.getNode(ISD::BR, dl, MVT::Other, 13876 N->getOperand(0), N->getOperand(4)); 13877 } 13878 13879 bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0); 13880 13881 // Create the PPCISD altivec 'dot' comparison node. 13882 SDValue Ops[] = { 13883 LHS.getOperand(2), // LHS of compare 13884 LHS.getOperand(3), // RHS of compare 13885 DAG.getConstant(CompareOpc, dl, MVT::i32) 13886 }; 13887 EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue }; 13888 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops); 13889 13890 // Unpack the result based on how the target uses it. 13891 PPC::Predicate CompOpc; 13892 switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) { 13893 default: // Can't happen, don't crash on invalid number though. 13894 case 0: // Branch on the value of the EQ bit of CR6. 13895 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE; 13896 break; 13897 case 1: // Branch on the inverted value of the EQ bit of CR6. 13898 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ; 13899 break; 13900 case 2: // Branch on the value of the LT bit of CR6. 13901 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE; 13902 break; 13903 case 3: // Branch on the inverted value of the LT bit of CR6. 13904 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT; 13905 break; 13906 } 13907 13908 return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0), 13909 DAG.getConstant(CompOpc, dl, MVT::i32), 13910 DAG.getRegister(PPC::CR6, MVT::i32), 13911 N->getOperand(4), CompNode.getValue(1)); 13912 } 13913 break; 13914 } 13915 case ISD::BUILD_VECTOR: 13916 return DAGCombineBuildVector(N, DCI); 13917 case ISD::ABS: 13918 return combineABS(N, DCI); 13919 case ISD::VSELECT: 13920 return combineVSelect(N, DCI); 13921 } 13922 13923 return SDValue(); 13924 } 13925 13926 SDValue 13927 PPCTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor, 13928 SelectionDAG &DAG, 13929 SmallVectorImpl<SDNode *> &Created) const { 13930 // fold (sdiv X, pow2) 13931 EVT VT = N->getValueType(0); 13932 if (VT == MVT::i64 && !Subtarget.isPPC64()) 13933 return SDValue(); 13934 if ((VT != MVT::i32 && VT != MVT::i64) || 13935 !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2())) 13936 return SDValue(); 13937 13938 SDLoc DL(N); 13939 SDValue N0 = N->getOperand(0); 13940 13941 bool IsNegPow2 = (-Divisor).isPowerOf2(); 13942 unsigned Lg2 = (IsNegPow2 ? -Divisor : Divisor).countTrailingZeros(); 13943 SDValue ShiftAmt = DAG.getConstant(Lg2, DL, VT); 13944 13945 SDValue Op = DAG.getNode(PPCISD::SRA_ADDZE, DL, VT, N0, ShiftAmt); 13946 Created.push_back(Op.getNode()); 13947 13948 if (IsNegPow2) { 13949 Op = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Op); 13950 Created.push_back(Op.getNode()); 13951 } 13952 13953 return Op; 13954 } 13955 13956 //===----------------------------------------------------------------------===// 13957 // Inline Assembly Support 13958 //===----------------------------------------------------------------------===// 13959 13960 void PPCTargetLowering::computeKnownBitsForTargetNode(const SDValue Op, 13961 KnownBits &Known, 13962 const APInt &DemandedElts, 13963 const SelectionDAG &DAG, 13964 unsigned Depth) const { 13965 Known.resetAll(); 13966 switch (Op.getOpcode()) { 13967 default: break; 13968 case PPCISD::LBRX: { 13969 // lhbrx is known to have the top bits cleared out. 13970 if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16) 13971 Known.Zero = 0xFFFF0000; 13972 break; 13973 } 13974 case ISD::INTRINSIC_WO_CHAIN: { 13975 switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) { 13976 default: break; 13977 case Intrinsic::ppc_altivec_vcmpbfp_p: 13978 case Intrinsic::ppc_altivec_vcmpeqfp_p: 13979 case Intrinsic::ppc_altivec_vcmpequb_p: 13980 case Intrinsic::ppc_altivec_vcmpequh_p: 13981 case Intrinsic::ppc_altivec_vcmpequw_p: 13982 case Intrinsic::ppc_altivec_vcmpequd_p: 13983 case Intrinsic::ppc_altivec_vcmpgefp_p: 13984 case Intrinsic::ppc_altivec_vcmpgtfp_p: 13985 case Intrinsic::ppc_altivec_vcmpgtsb_p: 13986 case Intrinsic::ppc_altivec_vcmpgtsh_p: 13987 case Intrinsic::ppc_altivec_vcmpgtsw_p: 13988 case Intrinsic::ppc_altivec_vcmpgtsd_p: 13989 case Intrinsic::ppc_altivec_vcmpgtub_p: 13990 case Intrinsic::ppc_altivec_vcmpgtuh_p: 13991 case Intrinsic::ppc_altivec_vcmpgtuw_p: 13992 case Intrinsic::ppc_altivec_vcmpgtud_p: 13993 Known.Zero = ~1U; // All bits but the low one are known to be zero. 13994 break; 13995 } 13996 } 13997 } 13998 } 13999 14000 unsigned PPCTargetLowering::getPrefLoopAlignment(MachineLoop *ML) const { 14001 switch (Subtarget.getDarwinDirective()) { 14002 default: break; 14003 case PPC::DIR_970: 14004 case PPC::DIR_PWR4: 14005 case PPC::DIR_PWR5: 14006 case PPC::DIR_PWR5X: 14007 case PPC::DIR_PWR6: 14008 case PPC::DIR_PWR6X: 14009 case PPC::DIR_PWR7: 14010 case PPC::DIR_PWR8: 14011 case PPC::DIR_PWR9: { 14012 if (!ML) 14013 break; 14014 14015 if (!DisableInnermostLoopAlign32) { 14016 // If the nested loop is an innermost loop, prefer to a 32-byte alignment, 14017 // so that we can decrease cache misses and branch-prediction misses. 14018 // Actual alignment of the loop will depend on the hotness check and other 14019 // logic in alignBlocks. 14020 if (ML->getLoopDepth() > 1 && ML->getSubLoops().empty()) 14021 return 5; 14022 } 14023 14024 const PPCInstrInfo *TII = Subtarget.getInstrInfo(); 14025 14026 // For small loops (between 5 and 8 instructions), align to a 32-byte 14027 // boundary so that the entire loop fits in one instruction-cache line. 14028 uint64_t LoopSize = 0; 14029 for (auto I = ML->block_begin(), IE = ML->block_end(); I != IE; ++I) 14030 for (auto J = (*I)->begin(), JE = (*I)->end(); J != JE; ++J) { 14031 LoopSize += TII->getInstSizeInBytes(*J); 14032 if (LoopSize > 32) 14033 break; 14034 } 14035 14036 if (LoopSize > 16 && LoopSize <= 32) 14037 return 5; 14038 14039 break; 14040 } 14041 } 14042 14043 return TargetLowering::getPrefLoopAlignment(ML); 14044 } 14045 14046 /// getConstraintType - Given a constraint, return the type of 14047 /// constraint it is for this target. 14048 PPCTargetLowering::ConstraintType 14049 PPCTargetLowering::getConstraintType(StringRef Constraint) const { 14050 if (Constraint.size() == 1) { 14051 switch (Constraint[0]) { 14052 default: break; 14053 case 'b': 14054 case 'r': 14055 case 'f': 14056 case 'd': 14057 case 'v': 14058 case 'y': 14059 return C_RegisterClass; 14060 case 'Z': 14061 // FIXME: While Z does indicate a memory constraint, it specifically 14062 // indicates an r+r address (used in conjunction with the 'y' modifier 14063 // in the replacement string). Currently, we're forcing the base 14064 // register to be r0 in the asm printer (which is interpreted as zero) 14065 // and forming the complete address in the second register. This is 14066 // suboptimal. 14067 return C_Memory; 14068 } 14069 } else if (Constraint == "wc") { // individual CR bits. 14070 return C_RegisterClass; 14071 } else if (Constraint == "wa" || Constraint == "wd" || 14072 Constraint == "wf" || Constraint == "ws" || 14073 Constraint == "wi" || Constraint == "ww") { 14074 return C_RegisterClass; // VSX registers. 14075 } 14076 return TargetLowering::getConstraintType(Constraint); 14077 } 14078 14079 /// Examine constraint type and operand type and determine a weight value. 14080 /// This object must already have been set up with the operand type 14081 /// and the current alternative constraint selected. 14082 TargetLowering::ConstraintWeight 14083 PPCTargetLowering::getSingleConstraintMatchWeight( 14084 AsmOperandInfo &info, const char *constraint) const { 14085 ConstraintWeight weight = CW_Invalid; 14086 Value *CallOperandVal = info.CallOperandVal; 14087 // If we don't have a value, we can't do a match, 14088 // but allow it at the lowest weight. 14089 if (!CallOperandVal) 14090 return CW_Default; 14091 Type *type = CallOperandVal->getType(); 14092 14093 // Look at the constraint type. 14094 if (StringRef(constraint) == "wc" && type->isIntegerTy(1)) 14095 return CW_Register; // an individual CR bit. 14096 else if ((StringRef(constraint) == "wa" || 14097 StringRef(constraint) == "wd" || 14098 StringRef(constraint) == "wf") && 14099 type->isVectorTy()) 14100 return CW_Register; 14101 else if (StringRef(constraint) == "wi" && type->isIntegerTy(64)) 14102 return CW_Register; // just hold 64-bit integers data. 14103 else if (StringRef(constraint) == "ws" && type->isDoubleTy()) 14104 return CW_Register; 14105 else if (StringRef(constraint) == "ww" && type->isFloatTy()) 14106 return CW_Register; 14107 14108 switch (*constraint) { 14109 default: 14110 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint); 14111 break; 14112 case 'b': 14113 if (type->isIntegerTy()) 14114 weight = CW_Register; 14115 break; 14116 case 'f': 14117 if (type->isFloatTy()) 14118 weight = CW_Register; 14119 break; 14120 case 'd': 14121 if (type->isDoubleTy()) 14122 weight = CW_Register; 14123 break; 14124 case 'v': 14125 if (type->isVectorTy()) 14126 weight = CW_Register; 14127 break; 14128 case 'y': 14129 weight = CW_Register; 14130 break; 14131 case 'Z': 14132 weight = CW_Memory; 14133 break; 14134 } 14135 return weight; 14136 } 14137 14138 std::pair<unsigned, const TargetRegisterClass *> 14139 PPCTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, 14140 StringRef Constraint, 14141 MVT VT) const { 14142 if (Constraint.size() == 1) { 14143 // GCC RS6000 Constraint Letters 14144 switch (Constraint[0]) { 14145 case 'b': // R1-R31 14146 if (VT == MVT::i64 && Subtarget.isPPC64()) 14147 return std::make_pair(0U, &PPC::G8RC_NOX0RegClass); 14148 return std::make_pair(0U, &PPC::GPRC_NOR0RegClass); 14149 case 'r': // R0-R31 14150 if (VT == MVT::i64 && Subtarget.isPPC64()) 14151 return std::make_pair(0U, &PPC::G8RCRegClass); 14152 return std::make_pair(0U, &PPC::GPRCRegClass); 14153 // 'd' and 'f' constraints are both defined to be "the floating point 14154 // registers", where one is for 32-bit and the other for 64-bit. We don't 14155 // really care overly much here so just give them all the same reg classes. 14156 case 'd': 14157 case 'f': 14158 if (Subtarget.hasSPE()) { 14159 if (VT == MVT::f32 || VT == MVT::i32) 14160 return std::make_pair(0U, &PPC::SPE4RCRegClass); 14161 if (VT == MVT::f64 || VT == MVT::i64) 14162 return std::make_pair(0U, &PPC::SPERCRegClass); 14163 } else { 14164 if (VT == MVT::f32 || VT == MVT::i32) 14165 return std::make_pair(0U, &PPC::F4RCRegClass); 14166 if (VT == MVT::f64 || VT == MVT::i64) 14167 return std::make_pair(0U, &PPC::F8RCRegClass); 14168 if (VT == MVT::v4f64 && Subtarget.hasQPX()) 14169 return std::make_pair(0U, &PPC::QFRCRegClass); 14170 if (VT == MVT::v4f32 && Subtarget.hasQPX()) 14171 return std::make_pair(0U, &PPC::QSRCRegClass); 14172 } 14173 break; 14174 case 'v': 14175 if (VT == MVT::v4f64 && Subtarget.hasQPX()) 14176 return std::make_pair(0U, &PPC::QFRCRegClass); 14177 if (VT == MVT::v4f32 && Subtarget.hasQPX()) 14178 return std::make_pair(0U, &PPC::QSRCRegClass); 14179 if (Subtarget.hasAltivec()) 14180 return std::make_pair(0U, &PPC::VRRCRegClass); 14181 break; 14182 case 'y': // crrc 14183 return std::make_pair(0U, &PPC::CRRCRegClass); 14184 } 14185 } else if (Constraint == "wc" && Subtarget.useCRBits()) { 14186 // An individual CR bit. 14187 return std::make_pair(0U, &PPC::CRBITRCRegClass); 14188 } else if ((Constraint == "wa" || Constraint == "wd" || 14189 Constraint == "wf" || Constraint == "wi") && 14190 Subtarget.hasVSX()) { 14191 return std::make_pair(0U, &PPC::VSRCRegClass); 14192 } else if ((Constraint == "ws" || Constraint == "ww") && Subtarget.hasVSX()) { 14193 if (VT == MVT::f32 && Subtarget.hasP8Vector()) 14194 return std::make_pair(0U, &PPC::VSSRCRegClass); 14195 else 14196 return std::make_pair(0U, &PPC::VSFRCRegClass); 14197 } 14198 14199 std::pair<unsigned, const TargetRegisterClass *> R = 14200 TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 14201 14202 // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers 14203 // (which we call X[0-9]+). If a 64-bit value has been requested, and a 14204 // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent 14205 // register. 14206 // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use 14207 // the AsmName field from *RegisterInfo.td, then this would not be necessary. 14208 if (R.first && VT == MVT::i64 && Subtarget.isPPC64() && 14209 PPC::GPRCRegClass.contains(R.first)) 14210 return std::make_pair(TRI->getMatchingSuperReg(R.first, 14211 PPC::sub_32, &PPC::G8RCRegClass), 14212 &PPC::G8RCRegClass); 14213 14214 // GCC accepts 'cc' as an alias for 'cr0', and we need to do the same. 14215 if (!R.second && StringRef("{cc}").equals_lower(Constraint)) { 14216 R.first = PPC::CR0; 14217 R.second = &PPC::CRRCRegClass; 14218 } 14219 14220 return R; 14221 } 14222 14223 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops 14224 /// vector. If it is invalid, don't add anything to Ops. 14225 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op, 14226 std::string &Constraint, 14227 std::vector<SDValue>&Ops, 14228 SelectionDAG &DAG) const { 14229 SDValue Result; 14230 14231 // Only support length 1 constraints. 14232 if (Constraint.length() > 1) return; 14233 14234 char Letter = Constraint[0]; 14235 switch (Letter) { 14236 default: break; 14237 case 'I': 14238 case 'J': 14239 case 'K': 14240 case 'L': 14241 case 'M': 14242 case 'N': 14243 case 'O': 14244 case 'P': { 14245 ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op); 14246 if (!CST) return; // Must be an immediate to match. 14247 SDLoc dl(Op); 14248 int64_t Value = CST->getSExtValue(); 14249 EVT TCVT = MVT::i64; // All constants taken to be 64 bits so that negative 14250 // numbers are printed as such. 14251 switch (Letter) { 14252 default: llvm_unreachable("Unknown constraint letter!"); 14253 case 'I': // "I" is a signed 16-bit constant. 14254 if (isInt<16>(Value)) 14255 Result = DAG.getTargetConstant(Value, dl, TCVT); 14256 break; 14257 case 'J': // "J" is a constant with only the high-order 16 bits nonzero. 14258 if (isShiftedUInt<16, 16>(Value)) 14259 Result = DAG.getTargetConstant(Value, dl, TCVT); 14260 break; 14261 case 'L': // "L" is a signed 16-bit constant shifted left 16 bits. 14262 if (isShiftedInt<16, 16>(Value)) 14263 Result = DAG.getTargetConstant(Value, dl, TCVT); 14264 break; 14265 case 'K': // "K" is a constant with only the low-order 16 bits nonzero. 14266 if (isUInt<16>(Value)) 14267 Result = DAG.getTargetConstant(Value, dl, TCVT); 14268 break; 14269 case 'M': // "M" is a constant that is greater than 31. 14270 if (Value > 31) 14271 Result = DAG.getTargetConstant(Value, dl, TCVT); 14272 break; 14273 case 'N': // "N" is a positive constant that is an exact power of two. 14274 if (Value > 0 && isPowerOf2_64(Value)) 14275 Result = DAG.getTargetConstant(Value, dl, TCVT); 14276 break; 14277 case 'O': // "O" is the constant zero. 14278 if (Value == 0) 14279 Result = DAG.getTargetConstant(Value, dl, TCVT); 14280 break; 14281 case 'P': // "P" is a constant whose negation is a signed 16-bit constant. 14282 if (isInt<16>(-Value)) 14283 Result = DAG.getTargetConstant(Value, dl, TCVT); 14284 break; 14285 } 14286 break; 14287 } 14288 } 14289 14290 if (Result.getNode()) { 14291 Ops.push_back(Result); 14292 return; 14293 } 14294 14295 // Handle standard constraint letters. 14296 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 14297 } 14298 14299 // isLegalAddressingMode - Return true if the addressing mode represented 14300 // by AM is legal for this target, for a load/store of the specified type. 14301 bool PPCTargetLowering::isLegalAddressingMode(const DataLayout &DL, 14302 const AddrMode &AM, Type *Ty, 14303 unsigned AS, Instruction *I) const { 14304 // PPC does not allow r+i addressing modes for vectors! 14305 if (Ty->isVectorTy() && AM.BaseOffs != 0) 14306 return false; 14307 14308 // PPC allows a sign-extended 16-bit immediate field. 14309 if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1) 14310 return false; 14311 14312 // No global is ever allowed as a base. 14313 if (AM.BaseGV) 14314 return false; 14315 14316 // PPC only support r+r, 14317 switch (AM.Scale) { 14318 case 0: // "r+i" or just "i", depending on HasBaseReg. 14319 break; 14320 case 1: 14321 if (AM.HasBaseReg && AM.BaseOffs) // "r+r+i" is not allowed. 14322 return false; 14323 // Otherwise we have r+r or r+i. 14324 break; 14325 case 2: 14326 if (AM.HasBaseReg || AM.BaseOffs) // 2*r+r or 2*r+i is not allowed. 14327 return false; 14328 // Allow 2*r as r+r. 14329 break; 14330 default: 14331 // No other scales are supported. 14332 return false; 14333 } 14334 14335 return true; 14336 } 14337 14338 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op, 14339 SelectionDAG &DAG) const { 14340 MachineFunction &MF = DAG.getMachineFunction(); 14341 MachineFrameInfo &MFI = MF.getFrameInfo(); 14342 MFI.setReturnAddressIsTaken(true); 14343 14344 if (verifyReturnAddressArgumentIsConstant(Op, DAG)) 14345 return SDValue(); 14346 14347 SDLoc dl(Op); 14348 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 14349 14350 // Make sure the function does not optimize away the store of the RA to 14351 // the stack. 14352 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 14353 FuncInfo->setLRStoreRequired(); 14354 bool isPPC64 = Subtarget.isPPC64(); 14355 auto PtrVT = getPointerTy(MF.getDataLayout()); 14356 14357 if (Depth > 0) { 14358 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG); 14359 SDValue Offset = 14360 DAG.getConstant(Subtarget.getFrameLowering()->getReturnSaveOffset(), dl, 14361 isPPC64 ? MVT::i64 : MVT::i32); 14362 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), 14363 DAG.getNode(ISD::ADD, dl, PtrVT, FrameAddr, Offset), 14364 MachinePointerInfo()); 14365 } 14366 14367 // Just load the return address off the stack. 14368 SDValue RetAddrFI = getReturnAddrFrameIndex(DAG); 14369 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), RetAddrFI, 14370 MachinePointerInfo()); 14371 } 14372 14373 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op, 14374 SelectionDAG &DAG) const { 14375 SDLoc dl(Op); 14376 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 14377 14378 MachineFunction &MF = DAG.getMachineFunction(); 14379 MachineFrameInfo &MFI = MF.getFrameInfo(); 14380 MFI.setFrameAddressIsTaken(true); 14381 14382 EVT PtrVT = getPointerTy(MF.getDataLayout()); 14383 bool isPPC64 = PtrVT == MVT::i64; 14384 14385 // Naked functions never have a frame pointer, and so we use r1. For all 14386 // other functions, this decision must be delayed until during PEI. 14387 unsigned FrameReg; 14388 if (MF.getFunction().hasFnAttribute(Attribute::Naked)) 14389 FrameReg = isPPC64 ? PPC::X1 : PPC::R1; 14390 else 14391 FrameReg = isPPC64 ? PPC::FP8 : PPC::FP; 14392 14393 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, 14394 PtrVT); 14395 while (Depth--) 14396 FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(), 14397 FrameAddr, MachinePointerInfo()); 14398 return FrameAddr; 14399 } 14400 14401 // FIXME? Maybe this could be a TableGen attribute on some registers and 14402 // this table could be generated automatically from RegInfo. 14403 unsigned PPCTargetLowering::getRegisterByName(const char* RegName, EVT VT, 14404 SelectionDAG &DAG) const { 14405 bool isPPC64 = Subtarget.isPPC64(); 14406 bool isDarwinABI = Subtarget.isDarwinABI(); 14407 14408 if ((isPPC64 && VT != MVT::i64 && VT != MVT::i32) || 14409 (!isPPC64 && VT != MVT::i32)) 14410 report_fatal_error("Invalid register global variable type"); 14411 14412 bool is64Bit = isPPC64 && VT == MVT::i64; 14413 unsigned Reg = StringSwitch<unsigned>(RegName) 14414 .Case("r1", is64Bit ? PPC::X1 : PPC::R1) 14415 .Case("r2", (isDarwinABI || isPPC64) ? 0 : PPC::R2) 14416 .Case("r13", (!isPPC64 && isDarwinABI) ? 0 : 14417 (is64Bit ? PPC::X13 : PPC::R13)) 14418 .Default(0); 14419 14420 if (Reg) 14421 return Reg; 14422 report_fatal_error("Invalid register name global variable"); 14423 } 14424 14425 bool PPCTargetLowering::isAccessedAsGotIndirect(SDValue GA) const { 14426 // 32-bit SVR4 ABI access everything as got-indirect. 14427 if (Subtarget.isSVR4ABI() && !Subtarget.isPPC64()) 14428 return true; 14429 14430 // AIX accesses everything indirectly through the TOC, which is similar to 14431 // the GOT. 14432 if (Subtarget.isAIXABI()) 14433 return true; 14434 14435 CodeModel::Model CModel = getTargetMachine().getCodeModel(); 14436 // If it is small or large code model, module locals are accessed 14437 // indirectly by loading their address from .toc/.got. 14438 if (CModel == CodeModel::Small || CModel == CodeModel::Large) 14439 return true; 14440 14441 // JumpTable and BlockAddress are accessed as got-indirect. 14442 if (isa<JumpTableSDNode>(GA) || isa<BlockAddressSDNode>(GA)) 14443 return true; 14444 14445 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(GA)) { 14446 const GlobalValue *GV = G->getGlobal(); 14447 unsigned char GVFlags = Subtarget.classifyGlobalReference(GV); 14448 // The NLP flag indicates that a global access has to use an 14449 // extra indirection. 14450 if (GVFlags & PPCII::MO_NLP_FLAG) 14451 return true; 14452 } 14453 14454 return false; 14455 } 14456 14457 bool 14458 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 14459 // The PowerPC target isn't yet aware of offsets. 14460 return false; 14461 } 14462 14463 bool PPCTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 14464 const CallInst &I, 14465 MachineFunction &MF, 14466 unsigned Intrinsic) const { 14467 switch (Intrinsic) { 14468 case Intrinsic::ppc_qpx_qvlfd: 14469 case Intrinsic::ppc_qpx_qvlfs: 14470 case Intrinsic::ppc_qpx_qvlfcd: 14471 case Intrinsic::ppc_qpx_qvlfcs: 14472 case Intrinsic::ppc_qpx_qvlfiwa: 14473 case Intrinsic::ppc_qpx_qvlfiwz: 14474 case Intrinsic::ppc_altivec_lvx: 14475 case Intrinsic::ppc_altivec_lvxl: 14476 case Intrinsic::ppc_altivec_lvebx: 14477 case Intrinsic::ppc_altivec_lvehx: 14478 case Intrinsic::ppc_altivec_lvewx: 14479 case Intrinsic::ppc_vsx_lxvd2x: 14480 case Intrinsic::ppc_vsx_lxvw4x: { 14481 EVT VT; 14482 switch (Intrinsic) { 14483 case Intrinsic::ppc_altivec_lvebx: 14484 VT = MVT::i8; 14485 break; 14486 case Intrinsic::ppc_altivec_lvehx: 14487 VT = MVT::i16; 14488 break; 14489 case Intrinsic::ppc_altivec_lvewx: 14490 VT = MVT::i32; 14491 break; 14492 case Intrinsic::ppc_vsx_lxvd2x: 14493 VT = MVT::v2f64; 14494 break; 14495 case Intrinsic::ppc_qpx_qvlfd: 14496 VT = MVT::v4f64; 14497 break; 14498 case Intrinsic::ppc_qpx_qvlfs: 14499 VT = MVT::v4f32; 14500 break; 14501 case Intrinsic::ppc_qpx_qvlfcd: 14502 VT = MVT::v2f64; 14503 break; 14504 case Intrinsic::ppc_qpx_qvlfcs: 14505 VT = MVT::v2f32; 14506 break; 14507 default: 14508 VT = MVT::v4i32; 14509 break; 14510 } 14511 14512 Info.opc = ISD::INTRINSIC_W_CHAIN; 14513 Info.memVT = VT; 14514 Info.ptrVal = I.getArgOperand(0); 14515 Info.offset = -VT.getStoreSize()+1; 14516 Info.size = 2*VT.getStoreSize()-1; 14517 Info.align = Align(1); 14518 Info.flags = MachineMemOperand::MOLoad; 14519 return true; 14520 } 14521 case Intrinsic::ppc_qpx_qvlfda: 14522 case Intrinsic::ppc_qpx_qvlfsa: 14523 case Intrinsic::ppc_qpx_qvlfcda: 14524 case Intrinsic::ppc_qpx_qvlfcsa: 14525 case Intrinsic::ppc_qpx_qvlfiwaa: 14526 case Intrinsic::ppc_qpx_qvlfiwza: { 14527 EVT VT; 14528 switch (Intrinsic) { 14529 case Intrinsic::ppc_qpx_qvlfda: 14530 VT = MVT::v4f64; 14531 break; 14532 case Intrinsic::ppc_qpx_qvlfsa: 14533 VT = MVT::v4f32; 14534 break; 14535 case Intrinsic::ppc_qpx_qvlfcda: 14536 VT = MVT::v2f64; 14537 break; 14538 case Intrinsic::ppc_qpx_qvlfcsa: 14539 VT = MVT::v2f32; 14540 break; 14541 default: 14542 VT = MVT::v4i32; 14543 break; 14544 } 14545 14546 Info.opc = ISD::INTRINSIC_W_CHAIN; 14547 Info.memVT = VT; 14548 Info.ptrVal = I.getArgOperand(0); 14549 Info.offset = 0; 14550 Info.size = VT.getStoreSize(); 14551 Info.align = Align(1); 14552 Info.flags = MachineMemOperand::MOLoad; 14553 return true; 14554 } 14555 case Intrinsic::ppc_qpx_qvstfd: 14556 case Intrinsic::ppc_qpx_qvstfs: 14557 case Intrinsic::ppc_qpx_qvstfcd: 14558 case Intrinsic::ppc_qpx_qvstfcs: 14559 case Intrinsic::ppc_qpx_qvstfiw: 14560 case Intrinsic::ppc_altivec_stvx: 14561 case Intrinsic::ppc_altivec_stvxl: 14562 case Intrinsic::ppc_altivec_stvebx: 14563 case Intrinsic::ppc_altivec_stvehx: 14564 case Intrinsic::ppc_altivec_stvewx: 14565 case Intrinsic::ppc_vsx_stxvd2x: 14566 case Intrinsic::ppc_vsx_stxvw4x: { 14567 EVT VT; 14568 switch (Intrinsic) { 14569 case Intrinsic::ppc_altivec_stvebx: 14570 VT = MVT::i8; 14571 break; 14572 case Intrinsic::ppc_altivec_stvehx: 14573 VT = MVT::i16; 14574 break; 14575 case Intrinsic::ppc_altivec_stvewx: 14576 VT = MVT::i32; 14577 break; 14578 case Intrinsic::ppc_vsx_stxvd2x: 14579 VT = MVT::v2f64; 14580 break; 14581 case Intrinsic::ppc_qpx_qvstfd: 14582 VT = MVT::v4f64; 14583 break; 14584 case Intrinsic::ppc_qpx_qvstfs: 14585 VT = MVT::v4f32; 14586 break; 14587 case Intrinsic::ppc_qpx_qvstfcd: 14588 VT = MVT::v2f64; 14589 break; 14590 case Intrinsic::ppc_qpx_qvstfcs: 14591 VT = MVT::v2f32; 14592 break; 14593 default: 14594 VT = MVT::v4i32; 14595 break; 14596 } 14597 14598 Info.opc = ISD::INTRINSIC_VOID; 14599 Info.memVT = VT; 14600 Info.ptrVal = I.getArgOperand(1); 14601 Info.offset = -VT.getStoreSize()+1; 14602 Info.size = 2*VT.getStoreSize()-1; 14603 Info.align = Align(1); 14604 Info.flags = MachineMemOperand::MOStore; 14605 return true; 14606 } 14607 case Intrinsic::ppc_qpx_qvstfda: 14608 case Intrinsic::ppc_qpx_qvstfsa: 14609 case Intrinsic::ppc_qpx_qvstfcda: 14610 case Intrinsic::ppc_qpx_qvstfcsa: 14611 case Intrinsic::ppc_qpx_qvstfiwa: { 14612 EVT VT; 14613 switch (Intrinsic) { 14614 case Intrinsic::ppc_qpx_qvstfda: 14615 VT = MVT::v4f64; 14616 break; 14617 case Intrinsic::ppc_qpx_qvstfsa: 14618 VT = MVT::v4f32; 14619 break; 14620 case Intrinsic::ppc_qpx_qvstfcda: 14621 VT = MVT::v2f64; 14622 break; 14623 case Intrinsic::ppc_qpx_qvstfcsa: 14624 VT = MVT::v2f32; 14625 break; 14626 default: 14627 VT = MVT::v4i32; 14628 break; 14629 } 14630 14631 Info.opc = ISD::INTRINSIC_VOID; 14632 Info.memVT = VT; 14633 Info.ptrVal = I.getArgOperand(1); 14634 Info.offset = 0; 14635 Info.size = VT.getStoreSize(); 14636 Info.align = Align(1); 14637 Info.flags = MachineMemOperand::MOStore; 14638 return true; 14639 } 14640 default: 14641 break; 14642 } 14643 14644 return false; 14645 } 14646 14647 /// getOptimalMemOpType - Returns the target specific optimal type for load 14648 /// and store operations as a result of memset, memcpy, and memmove 14649 /// lowering. If DstAlign is zero that means it's safe to destination 14650 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it 14651 /// means there isn't a need to check it against alignment requirement, 14652 /// probably because the source does not need to be loaded. If 'IsMemset' is 14653 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that 14654 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy 14655 /// source is constant so it does not need to be loaded. 14656 /// It returns EVT::Other if the type should be determined using generic 14657 /// target-independent logic. 14658 EVT PPCTargetLowering::getOptimalMemOpType( 14659 uint64_t Size, unsigned DstAlign, unsigned SrcAlign, bool IsMemset, 14660 bool ZeroMemset, bool MemcpyStrSrc, 14661 const AttributeList &FuncAttributes) const { 14662 if (getTargetMachine().getOptLevel() != CodeGenOpt::None) { 14663 // When expanding a memset, require at least two QPX instructions to cover 14664 // the cost of loading the value to be stored from the constant pool. 14665 if (Subtarget.hasQPX() && Size >= 32 && (!IsMemset || Size >= 64) && 14666 (!SrcAlign || SrcAlign >= 32) && (!DstAlign || DstAlign >= 32) && 14667 !FuncAttributes.hasFnAttribute(Attribute::NoImplicitFloat)) { 14668 return MVT::v4f64; 14669 } 14670 14671 // We should use Altivec/VSX loads and stores when available. For unaligned 14672 // addresses, unaligned VSX loads are only fast starting with the P8. 14673 if (Subtarget.hasAltivec() && Size >= 16 && 14674 (((!SrcAlign || SrcAlign >= 16) && (!DstAlign || DstAlign >= 16)) || 14675 ((IsMemset && Subtarget.hasVSX()) || Subtarget.hasP8Vector()))) 14676 return MVT::v4i32; 14677 } 14678 14679 if (Subtarget.isPPC64()) { 14680 return MVT::i64; 14681 } 14682 14683 return MVT::i32; 14684 } 14685 14686 /// Returns true if it is beneficial to convert a load of a constant 14687 /// to just the constant itself. 14688 bool PPCTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 14689 Type *Ty) const { 14690 assert(Ty->isIntegerTy()); 14691 14692 unsigned BitSize = Ty->getPrimitiveSizeInBits(); 14693 return !(BitSize == 0 || BitSize > 64); 14694 } 14695 14696 bool PPCTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const { 14697 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy()) 14698 return false; 14699 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits(); 14700 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits(); 14701 return NumBits1 == 64 && NumBits2 == 32; 14702 } 14703 14704 bool PPCTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const { 14705 if (!VT1.isInteger() || !VT2.isInteger()) 14706 return false; 14707 unsigned NumBits1 = VT1.getSizeInBits(); 14708 unsigned NumBits2 = VT2.getSizeInBits(); 14709 return NumBits1 == 64 && NumBits2 == 32; 14710 } 14711 14712 bool PPCTargetLowering::isZExtFree(SDValue Val, EVT VT2) const { 14713 // Generally speaking, zexts are not free, but they are free when they can be 14714 // folded with other operations. 14715 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Val)) { 14716 EVT MemVT = LD->getMemoryVT(); 14717 if ((MemVT == MVT::i1 || MemVT == MVT::i8 || MemVT == MVT::i16 || 14718 (Subtarget.isPPC64() && MemVT == MVT::i32)) && 14719 (LD->getExtensionType() == ISD::NON_EXTLOAD || 14720 LD->getExtensionType() == ISD::ZEXTLOAD)) 14721 return true; 14722 } 14723 14724 // FIXME: Add other cases... 14725 // - 32-bit shifts with a zext to i64 14726 // - zext after ctlz, bswap, etc. 14727 // - zext after and by a constant mask 14728 14729 return TargetLowering::isZExtFree(Val, VT2); 14730 } 14731 14732 bool PPCTargetLowering::isFPExtFree(EVT DestVT, EVT SrcVT) const { 14733 assert(DestVT.isFloatingPoint() && SrcVT.isFloatingPoint() && 14734 "invalid fpext types"); 14735 // Extending to float128 is not free. 14736 if (DestVT == MVT::f128) 14737 return false; 14738 return true; 14739 } 14740 14741 bool PPCTargetLowering::isLegalICmpImmediate(int64_t Imm) const { 14742 return isInt<16>(Imm) || isUInt<16>(Imm); 14743 } 14744 14745 bool PPCTargetLowering::isLegalAddImmediate(int64_t Imm) const { 14746 return isInt<16>(Imm) || isUInt<16>(Imm); 14747 } 14748 14749 bool PPCTargetLowering::allowsMisalignedMemoryAccesses(EVT VT, 14750 unsigned, 14751 unsigned, 14752 MachineMemOperand::Flags, 14753 bool *Fast) const { 14754 if (DisablePPCUnaligned) 14755 return false; 14756 14757 // PowerPC supports unaligned memory access for simple non-vector types. 14758 // Although accessing unaligned addresses is not as efficient as accessing 14759 // aligned addresses, it is generally more efficient than manual expansion, 14760 // and generally only traps for software emulation when crossing page 14761 // boundaries. 14762 14763 if (!VT.isSimple()) 14764 return false; 14765 14766 if (VT.getSimpleVT().isVector()) { 14767 if (Subtarget.hasVSX()) { 14768 if (VT != MVT::v2f64 && VT != MVT::v2i64 && 14769 VT != MVT::v4f32 && VT != MVT::v4i32) 14770 return false; 14771 } else { 14772 return false; 14773 } 14774 } 14775 14776 if (VT == MVT::ppcf128) 14777 return false; 14778 14779 if (Fast) 14780 *Fast = true; 14781 14782 return true; 14783 } 14784 14785 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const { 14786 VT = VT.getScalarType(); 14787 14788 if (!VT.isSimple()) 14789 return false; 14790 14791 switch (VT.getSimpleVT().SimpleTy) { 14792 case MVT::f32: 14793 case MVT::f64: 14794 return true; 14795 case MVT::f128: 14796 return (EnableQuadPrecision && Subtarget.hasP9Vector()); 14797 default: 14798 break; 14799 } 14800 14801 return false; 14802 } 14803 14804 const MCPhysReg * 14805 PPCTargetLowering::getScratchRegisters(CallingConv::ID) const { 14806 // LR is a callee-save register, but we must treat it as clobbered by any call 14807 // site. Hence we include LR in the scratch registers, which are in turn added 14808 // as implicit-defs for stackmaps and patchpoints. The same reasoning applies 14809 // to CTR, which is used by any indirect call. 14810 static const MCPhysReg ScratchRegs[] = { 14811 PPC::X12, PPC::LR8, PPC::CTR8, 0 14812 }; 14813 14814 return ScratchRegs; 14815 } 14816 14817 unsigned PPCTargetLowering::getExceptionPointerRegister( 14818 const Constant *PersonalityFn) const { 14819 return Subtarget.isPPC64() ? PPC::X3 : PPC::R3; 14820 } 14821 14822 unsigned PPCTargetLowering::getExceptionSelectorRegister( 14823 const Constant *PersonalityFn) const { 14824 return Subtarget.isPPC64() ? PPC::X4 : PPC::R4; 14825 } 14826 14827 bool 14828 PPCTargetLowering::shouldExpandBuildVectorWithShuffles( 14829 EVT VT , unsigned DefinedValues) const { 14830 if (VT == MVT::v2i64) 14831 return Subtarget.hasDirectMove(); // Don't need stack ops with direct moves 14832 14833 if (Subtarget.hasVSX() || Subtarget.hasQPX()) 14834 return true; 14835 14836 return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues); 14837 } 14838 14839 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const { 14840 if (DisableILPPref || Subtarget.enableMachineScheduler()) 14841 return TargetLowering::getSchedulingPreference(N); 14842 14843 return Sched::ILP; 14844 } 14845 14846 // Create a fast isel object. 14847 FastISel * 14848 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo, 14849 const TargetLibraryInfo *LibInfo) const { 14850 return PPC::createFastISel(FuncInfo, LibInfo); 14851 } 14852 14853 void PPCTargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const { 14854 if (Subtarget.isDarwinABI()) return; 14855 if (!Subtarget.isPPC64()) return; 14856 14857 // Update IsSplitCSR in PPCFunctionInfo 14858 PPCFunctionInfo *PFI = Entry->getParent()->getInfo<PPCFunctionInfo>(); 14859 PFI->setIsSplitCSR(true); 14860 } 14861 14862 void PPCTargetLowering::insertCopiesSplitCSR( 14863 MachineBasicBlock *Entry, 14864 const SmallVectorImpl<MachineBasicBlock *> &Exits) const { 14865 const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo(); 14866 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent()); 14867 if (!IStart) 14868 return; 14869 14870 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 14871 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo(); 14872 MachineBasicBlock::iterator MBBI = Entry->begin(); 14873 for (const MCPhysReg *I = IStart; *I; ++I) { 14874 const TargetRegisterClass *RC = nullptr; 14875 if (PPC::G8RCRegClass.contains(*I)) 14876 RC = &PPC::G8RCRegClass; 14877 else if (PPC::F8RCRegClass.contains(*I)) 14878 RC = &PPC::F8RCRegClass; 14879 else if (PPC::CRRCRegClass.contains(*I)) 14880 RC = &PPC::CRRCRegClass; 14881 else if (PPC::VRRCRegClass.contains(*I)) 14882 RC = &PPC::VRRCRegClass; 14883 else 14884 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 14885 14886 unsigned NewVR = MRI->createVirtualRegister(RC); 14887 // Create copy from CSR to a virtual register. 14888 // FIXME: this currently does not emit CFI pseudo-instructions, it works 14889 // fine for CXX_FAST_TLS since the C++-style TLS access functions should be 14890 // nounwind. If we want to generalize this later, we may need to emit 14891 // CFI pseudo-instructions. 14892 assert(Entry->getParent()->getFunction().hasFnAttribute( 14893 Attribute::NoUnwind) && 14894 "Function should be nounwind in insertCopiesSplitCSR!"); 14895 Entry->addLiveIn(*I); 14896 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR) 14897 .addReg(*I); 14898 14899 // Insert the copy-back instructions right before the terminator. 14900 for (auto *Exit : Exits) 14901 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(), 14902 TII->get(TargetOpcode::COPY), *I) 14903 .addReg(NewVR); 14904 } 14905 } 14906 14907 // Override to enable LOAD_STACK_GUARD lowering on Linux. 14908 bool PPCTargetLowering::useLoadStackGuardNode() const { 14909 if (!Subtarget.isTargetLinux()) 14910 return TargetLowering::useLoadStackGuardNode(); 14911 return true; 14912 } 14913 14914 // Override to disable global variable loading on Linux. 14915 void PPCTargetLowering::insertSSPDeclarations(Module &M) const { 14916 if (!Subtarget.isTargetLinux()) 14917 return TargetLowering::insertSSPDeclarations(M); 14918 } 14919 14920 bool PPCTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT, 14921 bool ForCodeSize) const { 14922 if (!VT.isSimple() || !Subtarget.hasVSX()) 14923 return false; 14924 14925 switch(VT.getSimpleVT().SimpleTy) { 14926 default: 14927 // For FP types that are currently not supported by PPC backend, return 14928 // false. Examples: f16, f80. 14929 return false; 14930 case MVT::f32: 14931 case MVT::f64: 14932 case MVT::ppcf128: 14933 return Imm.isPosZero(); 14934 } 14935 } 14936 14937 // For vector shift operation op, fold 14938 // (op x, (and y, ((1 << numbits(x)) - 1))) -> (target op x, y) 14939 static SDValue stripModuloOnShift(const TargetLowering &TLI, SDNode *N, 14940 SelectionDAG &DAG) { 14941 SDValue N0 = N->getOperand(0); 14942 SDValue N1 = N->getOperand(1); 14943 EVT VT = N0.getValueType(); 14944 unsigned OpSizeInBits = VT.getScalarSizeInBits(); 14945 unsigned Opcode = N->getOpcode(); 14946 unsigned TargetOpcode; 14947 14948 switch (Opcode) { 14949 default: 14950 llvm_unreachable("Unexpected shift operation"); 14951 case ISD::SHL: 14952 TargetOpcode = PPCISD::SHL; 14953 break; 14954 case ISD::SRL: 14955 TargetOpcode = PPCISD::SRL; 14956 break; 14957 case ISD::SRA: 14958 TargetOpcode = PPCISD::SRA; 14959 break; 14960 } 14961 14962 if (VT.isVector() && TLI.isOperationLegal(Opcode, VT) && 14963 N1->getOpcode() == ISD::AND) 14964 if (ConstantSDNode *Mask = isConstOrConstSplat(N1->getOperand(1))) 14965 if (Mask->getZExtValue() == OpSizeInBits - 1) 14966 return DAG.getNode(TargetOpcode, SDLoc(N), VT, N0, N1->getOperand(0)); 14967 14968 return SDValue(); 14969 } 14970 14971 SDValue PPCTargetLowering::combineSHL(SDNode *N, DAGCombinerInfo &DCI) const { 14972 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG)) 14973 return Value; 14974 14975 SDValue N0 = N->getOperand(0); 14976 ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N->getOperand(1)); 14977 if (!Subtarget.isISA3_0() || 14978 N0.getOpcode() != ISD::SIGN_EXTEND || 14979 N0.getOperand(0).getValueType() != MVT::i32 || 14980 CN1 == nullptr || N->getValueType(0) != MVT::i64) 14981 return SDValue(); 14982 14983 // We can't save an operation here if the value is already extended, and 14984 // the existing shift is easier to combine. 14985 SDValue ExtsSrc = N0.getOperand(0); 14986 if (ExtsSrc.getOpcode() == ISD::TRUNCATE && 14987 ExtsSrc.getOperand(0).getOpcode() == ISD::AssertSext) 14988 return SDValue(); 14989 14990 SDLoc DL(N0); 14991 SDValue ShiftBy = SDValue(CN1, 0); 14992 // We want the shift amount to be i32 on the extswli, but the shift could 14993 // have an i64. 14994 if (ShiftBy.getValueType() == MVT::i64) 14995 ShiftBy = DCI.DAG.getConstant(CN1->getZExtValue(), DL, MVT::i32); 14996 14997 return DCI.DAG.getNode(PPCISD::EXTSWSLI, DL, MVT::i64, N0->getOperand(0), 14998 ShiftBy); 14999 } 15000 15001 SDValue PPCTargetLowering::combineSRA(SDNode *N, DAGCombinerInfo &DCI) const { 15002 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG)) 15003 return Value; 15004 15005 return SDValue(); 15006 } 15007 15008 SDValue PPCTargetLowering::combineSRL(SDNode *N, DAGCombinerInfo &DCI) const { 15009 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG)) 15010 return Value; 15011 15012 return SDValue(); 15013 } 15014 15015 // Transform (add X, (zext(setne Z, C))) -> (addze X, (addic (addi Z, -C), -1)) 15016 // Transform (add X, (zext(sete Z, C))) -> (addze X, (subfic (addi Z, -C), 0)) 15017 // When C is zero, the equation (addi Z, -C) can be simplified to Z 15018 // Requirement: -C in [-32768, 32767], X and Z are MVT::i64 types 15019 static SDValue combineADDToADDZE(SDNode *N, SelectionDAG &DAG, 15020 const PPCSubtarget &Subtarget) { 15021 if (!Subtarget.isPPC64()) 15022 return SDValue(); 15023 15024 SDValue LHS = N->getOperand(0); 15025 SDValue RHS = N->getOperand(1); 15026 15027 auto isZextOfCompareWithConstant = [](SDValue Op) { 15028 if (Op.getOpcode() != ISD::ZERO_EXTEND || !Op.hasOneUse() || 15029 Op.getValueType() != MVT::i64) 15030 return false; 15031 15032 SDValue Cmp = Op.getOperand(0); 15033 if (Cmp.getOpcode() != ISD::SETCC || !Cmp.hasOneUse() || 15034 Cmp.getOperand(0).getValueType() != MVT::i64) 15035 return false; 15036 15037 if (auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1))) { 15038 int64_t NegConstant = 0 - Constant->getSExtValue(); 15039 // Due to the limitations of the addi instruction, 15040 // -C is required to be [-32768, 32767]. 15041 return isInt<16>(NegConstant); 15042 } 15043 15044 return false; 15045 }; 15046 15047 bool LHSHasPattern = isZextOfCompareWithConstant(LHS); 15048 bool RHSHasPattern = isZextOfCompareWithConstant(RHS); 15049 15050 // If there is a pattern, canonicalize a zext operand to the RHS. 15051 if (LHSHasPattern && !RHSHasPattern) 15052 std::swap(LHS, RHS); 15053 else if (!LHSHasPattern && !RHSHasPattern) 15054 return SDValue(); 15055 15056 SDLoc DL(N); 15057 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Glue); 15058 SDValue Cmp = RHS.getOperand(0); 15059 SDValue Z = Cmp.getOperand(0); 15060 auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1)); 15061 15062 assert(Constant && "Constant Should not be a null pointer."); 15063 int64_t NegConstant = 0 - Constant->getSExtValue(); 15064 15065 switch(cast<CondCodeSDNode>(Cmp.getOperand(2))->get()) { 15066 default: break; 15067 case ISD::SETNE: { 15068 // when C == 0 15069 // --> addze X, (addic Z, -1).carry 15070 // / 15071 // add X, (zext(setne Z, C))-- 15072 // \ when -32768 <= -C <= 32767 && C != 0 15073 // --> addze X, (addic (addi Z, -C), -1).carry 15074 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z, 15075 DAG.getConstant(NegConstant, DL, MVT::i64)); 15076 SDValue AddOrZ = NegConstant != 0 ? Add : Z; 15077 SDValue Addc = DAG.getNode(ISD::ADDC, DL, DAG.getVTList(MVT::i64, MVT::Glue), 15078 AddOrZ, DAG.getConstant(-1ULL, DL, MVT::i64)); 15079 return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64), 15080 SDValue(Addc.getNode(), 1)); 15081 } 15082 case ISD::SETEQ: { 15083 // when C == 0 15084 // --> addze X, (subfic Z, 0).carry 15085 // / 15086 // add X, (zext(sete Z, C))-- 15087 // \ when -32768 <= -C <= 32767 && C != 0 15088 // --> addze X, (subfic (addi Z, -C), 0).carry 15089 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z, 15090 DAG.getConstant(NegConstant, DL, MVT::i64)); 15091 SDValue AddOrZ = NegConstant != 0 ? Add : Z; 15092 SDValue Subc = DAG.getNode(ISD::SUBC, DL, DAG.getVTList(MVT::i64, MVT::Glue), 15093 DAG.getConstant(0, DL, MVT::i64), AddOrZ); 15094 return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64), 15095 SDValue(Subc.getNode(), 1)); 15096 } 15097 } 15098 15099 return SDValue(); 15100 } 15101 15102 SDValue PPCTargetLowering::combineADD(SDNode *N, DAGCombinerInfo &DCI) const { 15103 if (auto Value = combineADDToADDZE(N, DCI.DAG, Subtarget)) 15104 return Value; 15105 15106 return SDValue(); 15107 } 15108 15109 // Detect TRUNCATE operations on bitcasts of float128 values. 15110 // What we are looking for here is the situtation where we extract a subset 15111 // of bits from a 128 bit float. 15112 // This can be of two forms: 15113 // 1) BITCAST of f128 feeding TRUNCATE 15114 // 2) BITCAST of f128 feeding SRL (a shift) feeding TRUNCATE 15115 // The reason this is required is because we do not have a legal i128 type 15116 // and so we want to prevent having to store the f128 and then reload part 15117 // of it. 15118 SDValue PPCTargetLowering::combineTRUNCATE(SDNode *N, 15119 DAGCombinerInfo &DCI) const { 15120 // If we are using CRBits then try that first. 15121 if (Subtarget.useCRBits()) { 15122 // Check if CRBits did anything and return that if it did. 15123 if (SDValue CRTruncValue = DAGCombineTruncBoolExt(N, DCI)) 15124 return CRTruncValue; 15125 } 15126 15127 SDLoc dl(N); 15128 SDValue Op0 = N->getOperand(0); 15129 15130 // Looking for a truncate of i128 to i64. 15131 if (Op0.getValueType() != MVT::i128 || N->getValueType(0) != MVT::i64) 15132 return SDValue(); 15133 15134 int EltToExtract = DCI.DAG.getDataLayout().isBigEndian() ? 1 : 0; 15135 15136 // SRL feeding TRUNCATE. 15137 if (Op0.getOpcode() == ISD::SRL) { 15138 ConstantSDNode *ConstNode = dyn_cast<ConstantSDNode>(Op0.getOperand(1)); 15139 // The right shift has to be by 64 bits. 15140 if (!ConstNode || ConstNode->getZExtValue() != 64) 15141 return SDValue(); 15142 15143 // Switch the element number to extract. 15144 EltToExtract = EltToExtract ? 0 : 1; 15145 // Update Op0 past the SRL. 15146 Op0 = Op0.getOperand(0); 15147 } 15148 15149 // BITCAST feeding a TRUNCATE possibly via SRL. 15150 if (Op0.getOpcode() == ISD::BITCAST && 15151 Op0.getValueType() == MVT::i128 && 15152 Op0.getOperand(0).getValueType() == MVT::f128) { 15153 SDValue Bitcast = DCI.DAG.getBitcast(MVT::v2i64, Op0.getOperand(0)); 15154 return DCI.DAG.getNode( 15155 ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Bitcast, 15156 DCI.DAG.getTargetConstant(EltToExtract, dl, MVT::i32)); 15157 } 15158 return SDValue(); 15159 } 15160 15161 SDValue PPCTargetLowering::combineMUL(SDNode *N, DAGCombinerInfo &DCI) const { 15162 SelectionDAG &DAG = DCI.DAG; 15163 15164 ConstantSDNode *ConstOpOrElement = isConstOrConstSplat(N->getOperand(1)); 15165 if (!ConstOpOrElement) 15166 return SDValue(); 15167 15168 // An imul is usually smaller than the alternative sequence for legal type. 15169 if (DAG.getMachineFunction().getFunction().hasMinSize() && 15170 isOperationLegal(ISD::MUL, N->getValueType(0))) 15171 return SDValue(); 15172 15173 auto IsProfitable = [this](bool IsNeg, bool IsAddOne, EVT VT) -> bool { 15174 switch (this->Subtarget.getDarwinDirective()) { 15175 default: 15176 // TODO: enhance the condition for subtarget before pwr8 15177 return false; 15178 case PPC::DIR_PWR8: 15179 // type mul add shl 15180 // scalar 4 1 1 15181 // vector 7 2 2 15182 return true; 15183 case PPC::DIR_PWR9: 15184 // type mul add shl 15185 // scalar 5 2 2 15186 // vector 7 2 2 15187 15188 // The cycle RATIO of related operations are showed as a table above. 15189 // Because mul is 5(scalar)/7(vector), add/sub/shl are all 2 for both 15190 // scalar and vector type. For 2 instrs patterns, add/sub + shl 15191 // are 4, it is always profitable; but for 3 instrs patterns 15192 // (mul x, -(2^N + 1)) => -(add (shl x, N), x), sub + add + shl are 6. 15193 // So we should only do it for vector type. 15194 return IsAddOne && IsNeg ? VT.isVector() : true; 15195 } 15196 }; 15197 15198 EVT VT = N->getValueType(0); 15199 SDLoc DL(N); 15200 15201 const APInt &MulAmt = ConstOpOrElement->getAPIntValue(); 15202 bool IsNeg = MulAmt.isNegative(); 15203 APInt MulAmtAbs = MulAmt.abs(); 15204 15205 if ((MulAmtAbs - 1).isPowerOf2()) { 15206 // (mul x, 2^N + 1) => (add (shl x, N), x) 15207 // (mul x, -(2^N + 1)) => -(add (shl x, N), x) 15208 15209 if (!IsProfitable(IsNeg, true, VT)) 15210 return SDValue(); 15211 15212 SDValue Op0 = N->getOperand(0); 15213 SDValue Op1 = 15214 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0), 15215 DAG.getConstant((MulAmtAbs - 1).logBase2(), DL, VT)); 15216 SDValue Res = DAG.getNode(ISD::ADD, DL, VT, Op0, Op1); 15217 15218 if (!IsNeg) 15219 return Res; 15220 15221 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Res); 15222 } else if ((MulAmtAbs + 1).isPowerOf2()) { 15223 // (mul x, 2^N - 1) => (sub (shl x, N), x) 15224 // (mul x, -(2^N - 1)) => (sub x, (shl x, N)) 15225 15226 if (!IsProfitable(IsNeg, false, VT)) 15227 return SDValue(); 15228 15229 SDValue Op0 = N->getOperand(0); 15230 SDValue Op1 = 15231 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0), 15232 DAG.getConstant((MulAmtAbs + 1).logBase2(), DL, VT)); 15233 15234 if (!IsNeg) 15235 return DAG.getNode(ISD::SUB, DL, VT, Op1, Op0); 15236 else 15237 return DAG.getNode(ISD::SUB, DL, VT, Op0, Op1); 15238 15239 } else { 15240 return SDValue(); 15241 } 15242 } 15243 15244 bool PPCTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 15245 // Only duplicate to increase tail-calls for the 64bit SysV ABIs. 15246 if (!Subtarget.isSVR4ABI() || !Subtarget.isPPC64()) 15247 return false; 15248 15249 // If not a tail call then no need to proceed. 15250 if (!CI->isTailCall()) 15251 return false; 15252 15253 // If tail calls are disabled for the caller then we are done. 15254 const Function *Caller = CI->getParent()->getParent(); 15255 auto Attr = Caller->getFnAttribute("disable-tail-calls"); 15256 if (Attr.getValueAsString() == "true") 15257 return false; 15258 15259 // If sibling calls have been disabled and tail-calls aren't guaranteed 15260 // there is no reason to duplicate. 15261 auto &TM = getTargetMachine(); 15262 if (!TM.Options.GuaranteedTailCallOpt && DisableSCO) 15263 return false; 15264 15265 // Can't tail call a function called indirectly, or if it has variadic args. 15266 const Function *Callee = CI->getCalledFunction(); 15267 if (!Callee || Callee->isVarArg()) 15268 return false; 15269 15270 // Make sure the callee and caller calling conventions are eligible for tco. 15271 if (!areCallingConvEligibleForTCO_64SVR4(Caller->getCallingConv(), 15272 CI->getCallingConv())) 15273 return false; 15274 15275 // If the function is local then we have a good chance at tail-calling it 15276 return getTargetMachine().shouldAssumeDSOLocal(*Caller->getParent(), Callee); 15277 } 15278 15279 bool PPCTargetLowering::hasBitPreservingFPLogic(EVT VT) const { 15280 if (!Subtarget.hasVSX()) 15281 return false; 15282 if (Subtarget.hasP9Vector() && VT == MVT::f128) 15283 return true; 15284 return VT == MVT::f32 || VT == MVT::f64 || 15285 VT == MVT::v4f32 || VT == MVT::v2f64; 15286 } 15287 15288 bool PPCTargetLowering:: 15289 isMaskAndCmp0FoldingBeneficial(const Instruction &AndI) const { 15290 const Value *Mask = AndI.getOperand(1); 15291 // If the mask is suitable for andi. or andis. we should sink the and. 15292 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Mask)) { 15293 // Can't handle constants wider than 64-bits. 15294 if (CI->getBitWidth() > 64) 15295 return false; 15296 int64_t ConstVal = CI->getZExtValue(); 15297 return isUInt<16>(ConstVal) || 15298 (isUInt<16>(ConstVal >> 16) && !(ConstVal & 0xFFFF)); 15299 } 15300 15301 // For non-constant masks, we can always use the record-form and. 15302 return true; 15303 } 15304 15305 // Transform (abs (sub (zext a), (zext b))) to (vabsd a b 0) 15306 // Transform (abs (sub (zext a), (zext_invec b))) to (vabsd a b 0) 15307 // Transform (abs (sub (zext_invec a), (zext_invec b))) to (vabsd a b 0) 15308 // Transform (abs (sub (zext_invec a), (zext b))) to (vabsd a b 0) 15309 // Transform (abs (sub a, b) to (vabsd a b 1)) if a & b of type v4i32 15310 SDValue PPCTargetLowering::combineABS(SDNode *N, DAGCombinerInfo &DCI) const { 15311 assert((N->getOpcode() == ISD::ABS) && "Need ABS node here"); 15312 assert(Subtarget.hasP9Altivec() && 15313 "Only combine this when P9 altivec supported!"); 15314 EVT VT = N->getValueType(0); 15315 if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8) 15316 return SDValue(); 15317 15318 SelectionDAG &DAG = DCI.DAG; 15319 SDLoc dl(N); 15320 if (N->getOperand(0).getOpcode() == ISD::SUB) { 15321 // Even for signed integers, if it's known to be positive (as signed 15322 // integer) due to zero-extended inputs. 15323 unsigned SubOpcd0 = N->getOperand(0)->getOperand(0).getOpcode(); 15324 unsigned SubOpcd1 = N->getOperand(0)->getOperand(1).getOpcode(); 15325 if ((SubOpcd0 == ISD::ZERO_EXTEND || 15326 SubOpcd0 == ISD::ZERO_EXTEND_VECTOR_INREG) && 15327 (SubOpcd1 == ISD::ZERO_EXTEND || 15328 SubOpcd1 == ISD::ZERO_EXTEND_VECTOR_INREG)) { 15329 return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(), 15330 N->getOperand(0)->getOperand(0), 15331 N->getOperand(0)->getOperand(1), 15332 DAG.getTargetConstant(0, dl, MVT::i32)); 15333 } 15334 15335 // For type v4i32, it can be optimized with xvnegsp + vabsduw 15336 if (N->getOperand(0).getValueType() == MVT::v4i32 && 15337 N->getOperand(0).hasOneUse()) { 15338 return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(), 15339 N->getOperand(0)->getOperand(0), 15340 N->getOperand(0)->getOperand(1), 15341 DAG.getTargetConstant(1, dl, MVT::i32)); 15342 } 15343 } 15344 15345 return SDValue(); 15346 } 15347 15348 // For type v4i32/v8ii16/v16i8, transform 15349 // from (vselect (setcc a, b, setugt), (sub a, b), (sub b, a)) to (vabsd a, b) 15350 // from (vselect (setcc a, b, setuge), (sub a, b), (sub b, a)) to (vabsd a, b) 15351 // from (vselect (setcc a, b, setult), (sub b, a), (sub a, b)) to (vabsd a, b) 15352 // from (vselect (setcc a, b, setule), (sub b, a), (sub a, b)) to (vabsd a, b) 15353 SDValue PPCTargetLowering::combineVSelect(SDNode *N, 15354 DAGCombinerInfo &DCI) const { 15355 assert((N->getOpcode() == ISD::VSELECT) && "Need VSELECT node here"); 15356 assert(Subtarget.hasP9Altivec() && 15357 "Only combine this when P9 altivec supported!"); 15358 15359 SelectionDAG &DAG = DCI.DAG; 15360 SDLoc dl(N); 15361 SDValue Cond = N->getOperand(0); 15362 SDValue TrueOpnd = N->getOperand(1); 15363 SDValue FalseOpnd = N->getOperand(2); 15364 EVT VT = N->getOperand(1).getValueType(); 15365 15366 if (Cond.getOpcode() != ISD::SETCC || TrueOpnd.getOpcode() != ISD::SUB || 15367 FalseOpnd.getOpcode() != ISD::SUB) 15368 return SDValue(); 15369 15370 // ABSD only available for type v4i32/v8i16/v16i8 15371 if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8) 15372 return SDValue(); 15373 15374 // At least to save one more dependent computation 15375 if (!(Cond.hasOneUse() || TrueOpnd.hasOneUse() || FalseOpnd.hasOneUse())) 15376 return SDValue(); 15377 15378 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get(); 15379 15380 // Can only handle unsigned comparison here 15381 switch (CC) { 15382 default: 15383 return SDValue(); 15384 case ISD::SETUGT: 15385 case ISD::SETUGE: 15386 break; 15387 case ISD::SETULT: 15388 case ISD::SETULE: 15389 std::swap(TrueOpnd, FalseOpnd); 15390 break; 15391 } 15392 15393 SDValue CmpOpnd1 = Cond.getOperand(0); 15394 SDValue CmpOpnd2 = Cond.getOperand(1); 15395 15396 // SETCC CmpOpnd1 CmpOpnd2 cond 15397 // TrueOpnd = CmpOpnd1 - CmpOpnd2 15398 // FalseOpnd = CmpOpnd2 - CmpOpnd1 15399 if (TrueOpnd.getOperand(0) == CmpOpnd1 && 15400 TrueOpnd.getOperand(1) == CmpOpnd2 && 15401 FalseOpnd.getOperand(0) == CmpOpnd2 && 15402 FalseOpnd.getOperand(1) == CmpOpnd1) { 15403 return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(1).getValueType(), 15404 CmpOpnd1, CmpOpnd2, 15405 DAG.getTargetConstant(0, dl, MVT::i32)); 15406 } 15407 15408 return SDValue(); 15409 } 15410