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/TargetLoweringObjectFileImpl.h" 56 #include "llvm/CodeGen/TargetRegisterInfo.h" 57 #include "llvm/CodeGen/ValueTypes.h" 58 #include "llvm/IR/CallSite.h" 59 #include "llvm/IR/CallingConv.h" 60 #include "llvm/IR/Constant.h" 61 #include "llvm/IR/Constants.h" 62 #include "llvm/IR/DataLayout.h" 63 #include "llvm/IR/DebugLoc.h" 64 #include "llvm/IR/DerivedTypes.h" 65 #include "llvm/IR/Function.h" 66 #include "llvm/IR/GlobalValue.h" 67 #include "llvm/IR/IRBuilder.h" 68 #include "llvm/IR/Instructions.h" 69 #include "llvm/IR/Intrinsics.h" 70 #include "llvm/IR/IntrinsicsPowerPC.h" 71 #include "llvm/IR/Module.h" 72 #include "llvm/IR/Type.h" 73 #include "llvm/IR/Use.h" 74 #include "llvm/IR/Value.h" 75 #include "llvm/MC/MCContext.h" 76 #include "llvm/MC/MCExpr.h" 77 #include "llvm/MC/MCRegisterInfo.h" 78 #include "llvm/MC/MCSymbolXCOFF.h" 79 #include "llvm/Support/AtomicOrdering.h" 80 #include "llvm/Support/BranchProbability.h" 81 #include "llvm/Support/Casting.h" 82 #include "llvm/Support/CodeGen.h" 83 #include "llvm/Support/CommandLine.h" 84 #include "llvm/Support/Compiler.h" 85 #include "llvm/Support/Debug.h" 86 #include "llvm/Support/ErrorHandling.h" 87 #include "llvm/Support/Format.h" 88 #include "llvm/Support/KnownBits.h" 89 #include "llvm/Support/MachineValueType.h" 90 #include "llvm/Support/MathExtras.h" 91 #include "llvm/Support/raw_ostream.h" 92 #include "llvm/Target/TargetMachine.h" 93 #include "llvm/Target/TargetOptions.h" 94 #include <algorithm> 95 #include <cassert> 96 #include <cstdint> 97 #include <iterator> 98 #include <list> 99 #include <utility> 100 #include <vector> 101 102 using namespace llvm; 103 104 #define DEBUG_TYPE "ppc-lowering" 105 106 static cl::opt<bool> DisablePPCPreinc("disable-ppc-preinc", 107 cl::desc("disable preincrement load/store generation on PPC"), cl::Hidden); 108 109 static cl::opt<bool> DisableILPPref("disable-ppc-ilp-pref", 110 cl::desc("disable setting the node scheduling preference to ILP on PPC"), cl::Hidden); 111 112 static cl::opt<bool> DisablePPCUnaligned("disable-ppc-unaligned", 113 cl::desc("disable unaligned load/store generation on PPC"), cl::Hidden); 114 115 static cl::opt<bool> DisableSCO("disable-ppc-sco", 116 cl::desc("disable sibling call optimization on ppc"), cl::Hidden); 117 118 static cl::opt<bool> DisableInnermostLoopAlign32("disable-ppc-innermost-loop-align32", 119 cl::desc("don't always align innermost loop to 32 bytes on ppc"), cl::Hidden); 120 121 static cl::opt<bool> EnableQuadPrecision("enable-ppc-quad-precision", 122 cl::desc("enable quad precision float support on ppc"), cl::Hidden); 123 124 static cl::opt<bool> UseAbsoluteJumpTables("ppc-use-absolute-jumptables", 125 cl::desc("use absolute jump tables on ppc"), cl::Hidden); 126 127 STATISTIC(NumTailCalls, "Number of tail calls"); 128 STATISTIC(NumSiblingCalls, "Number of sibling calls"); 129 130 static bool isNByteElemShuffleMask(ShuffleVectorSDNode *, unsigned, int); 131 132 static SDValue widenVec(SelectionDAG &DAG, SDValue Vec, const SDLoc &dl); 133 134 // FIXME: Remove this once the bug has been fixed! 135 extern cl::opt<bool> ANDIGlueBug; 136 137 PPCTargetLowering::PPCTargetLowering(const PPCTargetMachine &TM, 138 const PPCSubtarget &STI) 139 : TargetLowering(TM), Subtarget(STI) { 140 // On PPC32/64, arguments smaller than 4/8 bytes are extended, so all 141 // arguments are at least 4/8 bytes aligned. 142 bool isPPC64 = Subtarget.isPPC64(); 143 setMinStackArgumentAlignment(isPPC64 ? Align(8) : Align(4)); 144 145 // Set up the register classes. 146 addRegisterClass(MVT::i32, &PPC::GPRCRegClass); 147 if (!useSoftFloat()) { 148 if (hasSPE()) { 149 addRegisterClass(MVT::f32, &PPC::GPRCRegClass); 150 addRegisterClass(MVT::f64, &PPC::SPERCRegClass); 151 } else { 152 addRegisterClass(MVT::f32, &PPC::F4RCRegClass); 153 addRegisterClass(MVT::f64, &PPC::F8RCRegClass); 154 } 155 } 156 157 // Match BITREVERSE to customized fast code sequence in the td file. 158 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal); 159 setOperationAction(ISD::BITREVERSE, MVT::i64, Legal); 160 161 // Sub-word ATOMIC_CMP_SWAP need to ensure that the input is zero-extended. 162 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom); 163 164 // PowerPC has an i16 but no i8 (or i1) SEXTLOAD. 165 for (MVT VT : MVT::integer_valuetypes()) { 166 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote); 167 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i8, Expand); 168 } 169 170 setTruncStoreAction(MVT::f64, MVT::f32, Expand); 171 172 // PowerPC has pre-inc load and store's. 173 setIndexedLoadAction(ISD::PRE_INC, MVT::i1, Legal); 174 setIndexedLoadAction(ISD::PRE_INC, MVT::i8, Legal); 175 setIndexedLoadAction(ISD::PRE_INC, MVT::i16, Legal); 176 setIndexedLoadAction(ISD::PRE_INC, MVT::i32, Legal); 177 setIndexedLoadAction(ISD::PRE_INC, MVT::i64, Legal); 178 setIndexedStoreAction(ISD::PRE_INC, MVT::i1, Legal); 179 setIndexedStoreAction(ISD::PRE_INC, MVT::i8, Legal); 180 setIndexedStoreAction(ISD::PRE_INC, MVT::i16, Legal); 181 setIndexedStoreAction(ISD::PRE_INC, MVT::i32, Legal); 182 setIndexedStoreAction(ISD::PRE_INC, MVT::i64, Legal); 183 if (!Subtarget.hasSPE()) { 184 setIndexedLoadAction(ISD::PRE_INC, MVT::f32, Legal); 185 setIndexedLoadAction(ISD::PRE_INC, MVT::f64, Legal); 186 setIndexedStoreAction(ISD::PRE_INC, MVT::f32, Legal); 187 setIndexedStoreAction(ISD::PRE_INC, MVT::f64, Legal); 188 } 189 190 // PowerPC uses ADDC/ADDE/SUBC/SUBE to propagate carry. 191 const MVT ScalarIntVTs[] = { MVT::i32, MVT::i64 }; 192 for (MVT VT : ScalarIntVTs) { 193 setOperationAction(ISD::ADDC, VT, Legal); 194 setOperationAction(ISD::ADDE, VT, Legal); 195 setOperationAction(ISD::SUBC, VT, Legal); 196 setOperationAction(ISD::SUBE, VT, Legal); 197 } 198 199 if (Subtarget.useCRBits()) { 200 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); 201 202 if (isPPC64 || Subtarget.hasFPCVT()) { 203 setOperationAction(ISD::SINT_TO_FP, MVT::i1, Promote); 204 AddPromotedToType (ISD::SINT_TO_FP, MVT::i1, 205 isPPC64 ? MVT::i64 : MVT::i32); 206 setOperationAction(ISD::UINT_TO_FP, MVT::i1, Promote); 207 AddPromotedToType(ISD::UINT_TO_FP, MVT::i1, 208 isPPC64 ? MVT::i64 : MVT::i32); 209 } else { 210 setOperationAction(ISD::SINT_TO_FP, MVT::i1, Custom); 211 setOperationAction(ISD::UINT_TO_FP, MVT::i1, Custom); 212 } 213 214 // PowerPC does not support direct load/store of condition registers. 215 setOperationAction(ISD::LOAD, MVT::i1, Custom); 216 setOperationAction(ISD::STORE, MVT::i1, Custom); 217 218 // FIXME: Remove this once the ANDI glue bug is fixed: 219 if (ANDIGlueBug) 220 setOperationAction(ISD::TRUNCATE, MVT::i1, Custom); 221 222 for (MVT VT : MVT::integer_valuetypes()) { 223 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote); 224 setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote); 225 setTruncStoreAction(VT, MVT::i1, Expand); 226 } 227 228 addRegisterClass(MVT::i1, &PPC::CRBITRCRegClass); 229 } 230 231 // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on 232 // PPC (the libcall is not available). 233 setOperationAction(ISD::FP_TO_SINT, MVT::ppcf128, Custom); 234 setOperationAction(ISD::FP_TO_UINT, MVT::ppcf128, Custom); 235 236 // We do not currently implement these libm ops for PowerPC. 237 setOperationAction(ISD::FFLOOR, MVT::ppcf128, Expand); 238 setOperationAction(ISD::FCEIL, MVT::ppcf128, Expand); 239 setOperationAction(ISD::FTRUNC, MVT::ppcf128, Expand); 240 setOperationAction(ISD::FRINT, MVT::ppcf128, Expand); 241 setOperationAction(ISD::FNEARBYINT, MVT::ppcf128, Expand); 242 setOperationAction(ISD::FREM, MVT::ppcf128, Expand); 243 244 // PowerPC has no SREM/UREM instructions unless we are on P9 245 // On P9 we may use a hardware instruction to compute the remainder. 246 // The instructions are not legalized directly because in the cases where the 247 // result of both the remainder and the division is required it is more 248 // efficient to compute the remainder from the result of the division rather 249 // than use the remainder instruction. 250 if (Subtarget.isISA3_0()) { 251 setOperationAction(ISD::SREM, MVT::i32, Custom); 252 setOperationAction(ISD::UREM, MVT::i32, Custom); 253 setOperationAction(ISD::SREM, MVT::i64, Custom); 254 setOperationAction(ISD::UREM, MVT::i64, Custom); 255 } else { 256 setOperationAction(ISD::SREM, MVT::i32, Expand); 257 setOperationAction(ISD::UREM, MVT::i32, Expand); 258 setOperationAction(ISD::SREM, MVT::i64, Expand); 259 setOperationAction(ISD::UREM, MVT::i64, Expand); 260 } 261 262 // Don't use SMUL_LOHI/UMUL_LOHI or SDIVREM/UDIVREM to lower SREM/UREM. 263 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand); 264 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand); 265 setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand); 266 setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand); 267 setOperationAction(ISD::UDIVREM, MVT::i32, Expand); 268 setOperationAction(ISD::SDIVREM, MVT::i32, Expand); 269 setOperationAction(ISD::UDIVREM, MVT::i64, Expand); 270 setOperationAction(ISD::SDIVREM, MVT::i64, Expand); 271 272 // We don't support sin/cos/sqrt/fmod/pow 273 setOperationAction(ISD::FSIN , MVT::f64, Expand); 274 setOperationAction(ISD::FCOS , MVT::f64, Expand); 275 setOperationAction(ISD::FSINCOS, MVT::f64, Expand); 276 setOperationAction(ISD::FREM , MVT::f64, Expand); 277 setOperationAction(ISD::FPOW , MVT::f64, Expand); 278 setOperationAction(ISD::FSIN , MVT::f32, Expand); 279 setOperationAction(ISD::FCOS , MVT::f32, Expand); 280 setOperationAction(ISD::FSINCOS, MVT::f32, Expand); 281 setOperationAction(ISD::FREM , MVT::f32, Expand); 282 setOperationAction(ISD::FPOW , MVT::f32, Expand); 283 if (Subtarget.hasSPE()) { 284 setOperationAction(ISD::FMA , MVT::f64, Expand); 285 setOperationAction(ISD::FMA , MVT::f32, Expand); 286 } else { 287 setOperationAction(ISD::FMA , MVT::f64, Legal); 288 setOperationAction(ISD::FMA , MVT::f32, Legal); 289 } 290 291 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom); 292 293 // If we're enabling GP optimizations, use hardware square root 294 if (!Subtarget.hasFSQRT() && 295 !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTE() && 296 Subtarget.hasFRE())) 297 setOperationAction(ISD::FSQRT, MVT::f64, Expand); 298 299 if (!Subtarget.hasFSQRT() && 300 !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTES() && 301 Subtarget.hasFRES())) 302 setOperationAction(ISD::FSQRT, MVT::f32, Expand); 303 304 if (Subtarget.hasFCPSGN()) { 305 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Legal); 306 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Legal); 307 } else { 308 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand); 309 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand); 310 } 311 312 if (Subtarget.hasFPRND()) { 313 setOperationAction(ISD::FFLOOR, MVT::f64, Legal); 314 setOperationAction(ISD::FCEIL, MVT::f64, Legal); 315 setOperationAction(ISD::FTRUNC, MVT::f64, Legal); 316 setOperationAction(ISD::FROUND, MVT::f64, Legal); 317 318 setOperationAction(ISD::FFLOOR, MVT::f32, Legal); 319 setOperationAction(ISD::FCEIL, MVT::f32, Legal); 320 setOperationAction(ISD::FTRUNC, MVT::f32, Legal); 321 setOperationAction(ISD::FROUND, MVT::f32, Legal); 322 } 323 324 // PowerPC does not have BSWAP, but we can use vector BSWAP instruction xxbrd 325 // to speed up scalar BSWAP64. 326 // CTPOP or CTTZ were introduced in P8/P9 respectively 327 setOperationAction(ISD::BSWAP, MVT::i32 , Expand); 328 if (Subtarget.hasP9Vector()) 329 setOperationAction(ISD::BSWAP, MVT::i64 , Custom); 330 else 331 setOperationAction(ISD::BSWAP, MVT::i64 , Expand); 332 if (Subtarget.isISA3_0()) { 333 setOperationAction(ISD::CTTZ , MVT::i32 , Legal); 334 setOperationAction(ISD::CTTZ , MVT::i64 , Legal); 335 } else { 336 setOperationAction(ISD::CTTZ , MVT::i32 , Expand); 337 setOperationAction(ISD::CTTZ , MVT::i64 , Expand); 338 } 339 340 if (Subtarget.hasPOPCNTD() == PPCSubtarget::POPCNTD_Fast) { 341 setOperationAction(ISD::CTPOP, MVT::i32 , Legal); 342 setOperationAction(ISD::CTPOP, MVT::i64 , Legal); 343 } else { 344 setOperationAction(ISD::CTPOP, MVT::i32 , Expand); 345 setOperationAction(ISD::CTPOP, MVT::i64 , Expand); 346 } 347 348 // PowerPC does not have ROTR 349 setOperationAction(ISD::ROTR, MVT::i32 , Expand); 350 setOperationAction(ISD::ROTR, MVT::i64 , Expand); 351 352 if (!Subtarget.useCRBits()) { 353 // PowerPC does not have Select 354 setOperationAction(ISD::SELECT, MVT::i32, Expand); 355 setOperationAction(ISD::SELECT, MVT::i64, Expand); 356 setOperationAction(ISD::SELECT, MVT::f32, Expand); 357 setOperationAction(ISD::SELECT, MVT::f64, Expand); 358 } 359 360 // PowerPC wants to turn select_cc of FP into fsel when possible. 361 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom); 362 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom); 363 364 // PowerPC wants to optimize integer setcc a bit 365 if (!Subtarget.useCRBits()) 366 setOperationAction(ISD::SETCC, MVT::i32, Custom); 367 368 // PowerPC does not have BRCOND which requires SetCC 369 if (!Subtarget.useCRBits()) 370 setOperationAction(ISD::BRCOND, MVT::Other, Expand); 371 372 setOperationAction(ISD::BR_JT, MVT::Other, Expand); 373 374 if (Subtarget.hasSPE()) { 375 // SPE has built-in conversions 376 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Legal); 377 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Legal); 378 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Legal); 379 } else { 380 // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores. 381 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 382 383 // PowerPC does not have [U|S]INT_TO_FP 384 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Expand); 385 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand); 386 } 387 388 if (Subtarget.hasDirectMove() && isPPC64) { 389 setOperationAction(ISD::BITCAST, MVT::f32, Legal); 390 setOperationAction(ISD::BITCAST, MVT::i32, Legal); 391 setOperationAction(ISD::BITCAST, MVT::i64, Legal); 392 setOperationAction(ISD::BITCAST, MVT::f64, Legal); 393 if (TM.Options.UnsafeFPMath) { 394 setOperationAction(ISD::LRINT, MVT::f64, Legal); 395 setOperationAction(ISD::LRINT, MVT::f32, Legal); 396 setOperationAction(ISD::LLRINT, MVT::f64, Legal); 397 setOperationAction(ISD::LLRINT, MVT::f32, Legal); 398 setOperationAction(ISD::LROUND, MVT::f64, Legal); 399 setOperationAction(ISD::LROUND, MVT::f32, Legal); 400 setOperationAction(ISD::LLROUND, MVT::f64, Legal); 401 setOperationAction(ISD::LLROUND, MVT::f32, Legal); 402 } 403 } else { 404 setOperationAction(ISD::BITCAST, MVT::f32, Expand); 405 setOperationAction(ISD::BITCAST, MVT::i32, Expand); 406 setOperationAction(ISD::BITCAST, MVT::i64, Expand); 407 setOperationAction(ISD::BITCAST, MVT::f64, Expand); 408 } 409 410 // We cannot sextinreg(i1). Expand to shifts. 411 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); 412 413 // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support 414 // SjLj exception handling but a light-weight setjmp/longjmp replacement to 415 // support continuation, user-level threading, and etc.. As a result, no 416 // other SjLj exception interfaces are implemented and please don't build 417 // your own exception handling based on them. 418 // LLVM/Clang supports zero-cost DWARF exception handling. 419 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom); 420 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom); 421 422 // We want to legalize GlobalAddress and ConstantPool nodes into the 423 // appropriate instructions to materialize the address. 424 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom); 425 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom); 426 setOperationAction(ISD::BlockAddress, MVT::i32, Custom); 427 setOperationAction(ISD::ConstantPool, MVT::i32, Custom); 428 setOperationAction(ISD::JumpTable, MVT::i32, Custom); 429 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom); 430 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom); 431 setOperationAction(ISD::BlockAddress, MVT::i64, Custom); 432 setOperationAction(ISD::ConstantPool, MVT::i64, Custom); 433 setOperationAction(ISD::JumpTable, MVT::i64, Custom); 434 435 // TRAP is legal. 436 setOperationAction(ISD::TRAP, MVT::Other, Legal); 437 438 // TRAMPOLINE is custom lowered. 439 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom); 440 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom); 441 442 // VASTART needs to be custom lowered to use the VarArgsFrameIndex 443 setOperationAction(ISD::VASTART , MVT::Other, Custom); 444 445 if (Subtarget.is64BitELFABI()) { 446 // VAARG always uses double-word chunks, so promote anything smaller. 447 setOperationAction(ISD::VAARG, MVT::i1, Promote); 448 AddPromotedToType(ISD::VAARG, MVT::i1, MVT::i64); 449 setOperationAction(ISD::VAARG, MVT::i8, Promote); 450 AddPromotedToType(ISD::VAARG, MVT::i8, MVT::i64); 451 setOperationAction(ISD::VAARG, MVT::i16, Promote); 452 AddPromotedToType(ISD::VAARG, MVT::i16, MVT::i64); 453 setOperationAction(ISD::VAARG, MVT::i32, Promote); 454 AddPromotedToType(ISD::VAARG, MVT::i32, MVT::i64); 455 setOperationAction(ISD::VAARG, MVT::Other, Expand); 456 } else if (Subtarget.is32BitELFABI()) { 457 // VAARG is custom lowered with the 32-bit SVR4 ABI. 458 setOperationAction(ISD::VAARG, MVT::Other, Custom); 459 setOperationAction(ISD::VAARG, MVT::i64, Custom); 460 } else 461 setOperationAction(ISD::VAARG, MVT::Other, Expand); 462 463 // VACOPY is custom lowered with the 32-bit SVR4 ABI. 464 if (Subtarget.is32BitELFABI()) 465 setOperationAction(ISD::VACOPY , MVT::Other, Custom); 466 else 467 setOperationAction(ISD::VACOPY , MVT::Other, Expand); 468 469 // Use the default implementation. 470 setOperationAction(ISD::VAEND , MVT::Other, Expand); 471 setOperationAction(ISD::STACKSAVE , MVT::Other, Expand); 472 setOperationAction(ISD::STACKRESTORE , MVT::Other, Custom); 473 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32 , Custom); 474 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64 , Custom); 475 setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i32, Custom); 476 setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i64, Custom); 477 setOperationAction(ISD::EH_DWARF_CFA, MVT::i32, Custom); 478 setOperationAction(ISD::EH_DWARF_CFA, MVT::i64, Custom); 479 480 // We want to custom lower some of our intrinsics. 481 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 482 483 // To handle counter-based loop conditions. 484 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i1, Custom); 485 486 setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom); 487 setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom); 488 setOperationAction(ISD::INTRINSIC_VOID, MVT::i32, Custom); 489 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom); 490 491 // Comparisons that require checking two conditions. 492 if (Subtarget.hasSPE()) { 493 setCondCodeAction(ISD::SETO, MVT::f32, Expand); 494 setCondCodeAction(ISD::SETO, MVT::f64, Expand); 495 setCondCodeAction(ISD::SETUO, MVT::f32, Expand); 496 setCondCodeAction(ISD::SETUO, MVT::f64, Expand); 497 } 498 setCondCodeAction(ISD::SETULT, MVT::f32, Expand); 499 setCondCodeAction(ISD::SETULT, MVT::f64, Expand); 500 setCondCodeAction(ISD::SETUGT, MVT::f32, Expand); 501 setCondCodeAction(ISD::SETUGT, MVT::f64, Expand); 502 setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand); 503 setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand); 504 setCondCodeAction(ISD::SETOGE, MVT::f32, Expand); 505 setCondCodeAction(ISD::SETOGE, MVT::f64, Expand); 506 setCondCodeAction(ISD::SETOLE, MVT::f32, Expand); 507 setCondCodeAction(ISD::SETOLE, MVT::f64, Expand); 508 setCondCodeAction(ISD::SETONE, MVT::f32, Expand); 509 setCondCodeAction(ISD::SETONE, MVT::f64, Expand); 510 511 if (Subtarget.has64BitSupport()) { 512 // They also have instructions for converting between i64 and fp. 513 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom); 514 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand); 515 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom); 516 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand); 517 // This is just the low 32 bits of a (signed) fp->i64 conversion. 518 // We cannot do this with Promote because i64 is not a legal type. 519 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 520 521 if (Subtarget.hasLFIWAX() || Subtarget.isPPC64()) 522 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom); 523 } else { 524 // PowerPC does not have FP_TO_UINT on 32-bit implementations. 525 if (Subtarget.hasSPE()) 526 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Legal); 527 else 528 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand); 529 } 530 531 // With the instructions enabled under FPCVT, we can do everything. 532 if (Subtarget.hasFPCVT()) { 533 if (Subtarget.has64BitSupport()) { 534 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom); 535 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom); 536 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom); 537 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom); 538 } 539 540 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 541 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 542 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom); 543 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom); 544 } 545 546 if (Subtarget.use64BitRegs()) { 547 // 64-bit PowerPC implementations can support i64 types directly 548 addRegisterClass(MVT::i64, &PPC::G8RCRegClass); 549 // BUILD_PAIR can't be handled natively, and should be expanded to shl/or 550 setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand); 551 // 64-bit PowerPC wants to expand i128 shifts itself. 552 setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom); 553 setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom); 554 setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom); 555 } else { 556 // 32-bit PowerPC wants to expand i64 shifts itself. 557 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom); 558 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom); 559 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom); 560 } 561 562 if (Subtarget.hasVSX()) { 563 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f64, Legal); 564 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f32, Legal); 565 setOperationAction(ISD::FMINNUM_IEEE, MVT::f64, Legal); 566 setOperationAction(ISD::FMINNUM_IEEE, MVT::f32, Legal); 567 } 568 569 if (Subtarget.hasAltivec()) { 570 for (MVT VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32 }) { 571 setOperationAction(ISD::SADDSAT, VT, Legal); 572 setOperationAction(ISD::SSUBSAT, VT, Legal); 573 setOperationAction(ISD::UADDSAT, VT, Legal); 574 setOperationAction(ISD::USUBSAT, VT, Legal); 575 } 576 // First set operation action for all vector types to expand. Then we 577 // will selectively turn on ones that can be effectively codegen'd. 578 for (MVT VT : MVT::fixedlen_vector_valuetypes()) { 579 // add/sub are legal for all supported vector VT's. 580 setOperationAction(ISD::ADD, VT, Legal); 581 setOperationAction(ISD::SUB, VT, Legal); 582 583 // For v2i64, these are only valid with P8Vector. This is corrected after 584 // the loop. 585 if (VT.getSizeInBits() <= 128 && VT.getScalarSizeInBits() <= 64) { 586 setOperationAction(ISD::SMAX, VT, Legal); 587 setOperationAction(ISD::SMIN, VT, Legal); 588 setOperationAction(ISD::UMAX, VT, Legal); 589 setOperationAction(ISD::UMIN, VT, Legal); 590 } 591 else { 592 setOperationAction(ISD::SMAX, VT, Expand); 593 setOperationAction(ISD::SMIN, VT, Expand); 594 setOperationAction(ISD::UMAX, VT, Expand); 595 setOperationAction(ISD::UMIN, VT, Expand); 596 } 597 598 if (Subtarget.hasVSX()) { 599 setOperationAction(ISD::FMAXNUM, VT, Legal); 600 setOperationAction(ISD::FMINNUM, VT, Legal); 601 } 602 603 // Vector instructions introduced in P8 604 if (Subtarget.hasP8Altivec() && (VT.SimpleTy != MVT::v1i128)) { 605 setOperationAction(ISD::CTPOP, VT, Legal); 606 setOperationAction(ISD::CTLZ, VT, Legal); 607 } 608 else { 609 setOperationAction(ISD::CTPOP, VT, Expand); 610 setOperationAction(ISD::CTLZ, VT, Expand); 611 } 612 613 // Vector instructions introduced in P9 614 if (Subtarget.hasP9Altivec() && (VT.SimpleTy != MVT::v1i128)) 615 setOperationAction(ISD::CTTZ, VT, Legal); 616 else 617 setOperationAction(ISD::CTTZ, VT, Expand); 618 619 // We promote all shuffles to v16i8. 620 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Promote); 621 AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8); 622 623 // We promote all non-typed operations to v4i32. 624 setOperationAction(ISD::AND , VT, Promote); 625 AddPromotedToType (ISD::AND , VT, MVT::v4i32); 626 setOperationAction(ISD::OR , VT, Promote); 627 AddPromotedToType (ISD::OR , VT, MVT::v4i32); 628 setOperationAction(ISD::XOR , VT, Promote); 629 AddPromotedToType (ISD::XOR , VT, MVT::v4i32); 630 setOperationAction(ISD::LOAD , VT, Promote); 631 AddPromotedToType (ISD::LOAD , VT, MVT::v4i32); 632 setOperationAction(ISD::SELECT, VT, Promote); 633 AddPromotedToType (ISD::SELECT, VT, MVT::v4i32); 634 setOperationAction(ISD::VSELECT, VT, Legal); 635 setOperationAction(ISD::SELECT_CC, VT, Promote); 636 AddPromotedToType (ISD::SELECT_CC, VT, MVT::v4i32); 637 setOperationAction(ISD::STORE, VT, Promote); 638 AddPromotedToType (ISD::STORE, VT, MVT::v4i32); 639 640 // No other operations are legal. 641 setOperationAction(ISD::MUL , VT, Expand); 642 setOperationAction(ISD::SDIV, VT, Expand); 643 setOperationAction(ISD::SREM, VT, Expand); 644 setOperationAction(ISD::UDIV, VT, Expand); 645 setOperationAction(ISD::UREM, VT, Expand); 646 setOperationAction(ISD::FDIV, VT, Expand); 647 setOperationAction(ISD::FREM, VT, Expand); 648 setOperationAction(ISD::FNEG, VT, Expand); 649 setOperationAction(ISD::FSQRT, VT, Expand); 650 setOperationAction(ISD::FLOG, VT, Expand); 651 setOperationAction(ISD::FLOG10, VT, Expand); 652 setOperationAction(ISD::FLOG2, VT, Expand); 653 setOperationAction(ISD::FEXP, VT, Expand); 654 setOperationAction(ISD::FEXP2, VT, Expand); 655 setOperationAction(ISD::FSIN, VT, Expand); 656 setOperationAction(ISD::FCOS, VT, Expand); 657 setOperationAction(ISD::FABS, VT, Expand); 658 setOperationAction(ISD::FFLOOR, VT, Expand); 659 setOperationAction(ISD::FCEIL, VT, Expand); 660 setOperationAction(ISD::FTRUNC, VT, Expand); 661 setOperationAction(ISD::FRINT, VT, Expand); 662 setOperationAction(ISD::FNEARBYINT, VT, Expand); 663 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand); 664 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand); 665 setOperationAction(ISD::BUILD_VECTOR, VT, Expand); 666 setOperationAction(ISD::MULHU, VT, Expand); 667 setOperationAction(ISD::MULHS, VT, Expand); 668 setOperationAction(ISD::UMUL_LOHI, VT, Expand); 669 setOperationAction(ISD::SMUL_LOHI, VT, Expand); 670 setOperationAction(ISD::UDIVREM, VT, Expand); 671 setOperationAction(ISD::SDIVREM, VT, Expand); 672 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand); 673 setOperationAction(ISD::FPOW, VT, Expand); 674 setOperationAction(ISD::BSWAP, VT, Expand); 675 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand); 676 setOperationAction(ISD::ROTL, VT, Expand); 677 setOperationAction(ISD::ROTR, VT, Expand); 678 679 for (MVT InnerVT : MVT::fixedlen_vector_valuetypes()) { 680 setTruncStoreAction(VT, InnerVT, Expand); 681 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand); 682 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand); 683 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand); 684 } 685 } 686 if (!Subtarget.hasP8Vector()) { 687 setOperationAction(ISD::SMAX, MVT::v2i64, Expand); 688 setOperationAction(ISD::SMIN, MVT::v2i64, Expand); 689 setOperationAction(ISD::UMAX, MVT::v2i64, Expand); 690 setOperationAction(ISD::UMIN, MVT::v2i64, Expand); 691 } 692 693 for (auto VT : {MVT::v2i64, MVT::v4i32, MVT::v8i16, MVT::v16i8}) 694 setOperationAction(ISD::ABS, VT, Custom); 695 696 // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle 697 // with merges, splats, etc. 698 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom); 699 700 // Vector truncates to sub-word integer that fit in an Altivec/VSX register 701 // are cheap, so handle them before they get expanded to scalar. 702 setOperationAction(ISD::TRUNCATE, MVT::v8i8, Custom); 703 setOperationAction(ISD::TRUNCATE, MVT::v4i8, Custom); 704 setOperationAction(ISD::TRUNCATE, MVT::v2i8, Custom); 705 setOperationAction(ISD::TRUNCATE, MVT::v4i16, Custom); 706 setOperationAction(ISD::TRUNCATE, MVT::v2i16, Custom); 707 708 setOperationAction(ISD::AND , MVT::v4i32, Legal); 709 setOperationAction(ISD::OR , MVT::v4i32, Legal); 710 setOperationAction(ISD::XOR , MVT::v4i32, Legal); 711 setOperationAction(ISD::LOAD , MVT::v4i32, Legal); 712 setOperationAction(ISD::SELECT, MVT::v4i32, 713 Subtarget.useCRBits() ? Legal : Expand); 714 setOperationAction(ISD::STORE , MVT::v4i32, Legal); 715 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal); 716 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal); 717 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal); 718 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal); 719 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal); 720 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal); 721 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal); 722 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal); 723 724 // Without hasP8Altivec set, v2i64 SMAX isn't available. 725 // But ABS custom lowering requires SMAX support. 726 if (!Subtarget.hasP8Altivec()) 727 setOperationAction(ISD::ABS, MVT::v2i64, Expand); 728 729 // With hasAltivec set, we can lower ISD::ROTL to vrl(b|h|w). 730 if (Subtarget.hasAltivec()) 731 for (auto VT : {MVT::v4i32, MVT::v8i16, MVT::v16i8}) 732 setOperationAction(ISD::ROTL, VT, Legal); 733 // With hasP8Altivec set, we can lower ISD::ROTL to vrld. 734 if (Subtarget.hasP8Altivec()) 735 setOperationAction(ISD::ROTL, MVT::v2i64, Legal); 736 737 addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass); 738 addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass); 739 addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass); 740 addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass); 741 742 setOperationAction(ISD::MUL, MVT::v4f32, Legal); 743 setOperationAction(ISD::FMA, MVT::v4f32, Legal); 744 745 if (TM.Options.UnsafeFPMath || Subtarget.hasVSX()) { 746 setOperationAction(ISD::FDIV, MVT::v4f32, Legal); 747 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal); 748 } 749 750 if (Subtarget.hasP8Altivec()) 751 setOperationAction(ISD::MUL, MVT::v4i32, Legal); 752 else 753 setOperationAction(ISD::MUL, MVT::v4i32, Custom); 754 755 setOperationAction(ISD::MUL, MVT::v8i16, Custom); 756 setOperationAction(ISD::MUL, MVT::v16i8, Custom); 757 758 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom); 759 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom); 760 761 setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom); 762 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom); 763 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom); 764 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom); 765 766 // Altivec does not contain unordered floating-point compare instructions 767 setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand); 768 setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand); 769 setCondCodeAction(ISD::SETO, MVT::v4f32, Expand); 770 setCondCodeAction(ISD::SETONE, MVT::v4f32, Expand); 771 772 if (Subtarget.hasVSX()) { 773 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal); 774 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal); 775 if (Subtarget.hasP8Vector()) { 776 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal); 777 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Legal); 778 } 779 if (Subtarget.hasDirectMove() && isPPC64) { 780 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Legal); 781 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Legal); 782 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Legal); 783 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i64, Legal); 784 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Legal); 785 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Legal); 786 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Legal); 787 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal); 788 } 789 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal); 790 791 // The nearbyint variants are not allowed to raise the inexact exception 792 // so we can only code-gen them with unsafe math. 793 if (TM.Options.UnsafeFPMath) { 794 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal); 795 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal); 796 } 797 798 setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal); 799 setOperationAction(ISD::FCEIL, MVT::v2f64, Legal); 800 setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal); 801 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal); 802 setOperationAction(ISD::FROUND, MVT::v2f64, Legal); 803 setOperationAction(ISD::FROUND, MVT::f64, Legal); 804 805 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal); 806 setOperationAction(ISD::FROUND, MVT::v4f32, Legal); 807 setOperationAction(ISD::FROUND, MVT::f32, Legal); 808 809 setOperationAction(ISD::MUL, MVT::v2f64, Legal); 810 setOperationAction(ISD::FMA, MVT::v2f64, Legal); 811 812 setOperationAction(ISD::FDIV, MVT::v2f64, Legal); 813 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal); 814 815 // Share the Altivec comparison restrictions. 816 setCondCodeAction(ISD::SETUO, MVT::v2f64, Expand); 817 setCondCodeAction(ISD::SETUEQ, MVT::v2f64, Expand); 818 setCondCodeAction(ISD::SETO, MVT::v2f64, Expand); 819 setCondCodeAction(ISD::SETONE, MVT::v2f64, Expand); 820 821 setOperationAction(ISD::LOAD, MVT::v2f64, Legal); 822 setOperationAction(ISD::STORE, MVT::v2f64, Legal); 823 824 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Legal); 825 826 if (Subtarget.hasP8Vector()) 827 addRegisterClass(MVT::f32, &PPC::VSSRCRegClass); 828 829 addRegisterClass(MVT::f64, &PPC::VSFRCRegClass); 830 831 addRegisterClass(MVT::v4i32, &PPC::VSRCRegClass); 832 addRegisterClass(MVT::v4f32, &PPC::VSRCRegClass); 833 addRegisterClass(MVT::v2f64, &PPC::VSRCRegClass); 834 835 if (Subtarget.hasP8Altivec()) { 836 setOperationAction(ISD::SHL, MVT::v2i64, Legal); 837 setOperationAction(ISD::SRA, MVT::v2i64, Legal); 838 setOperationAction(ISD::SRL, MVT::v2i64, Legal); 839 840 // 128 bit shifts can be accomplished via 3 instructions for SHL and 841 // SRL, but not for SRA because of the instructions available: 842 // VS{RL} and VS{RL}O. However due to direct move costs, it's not worth 843 // doing 844 setOperationAction(ISD::SHL, MVT::v1i128, Expand); 845 setOperationAction(ISD::SRL, MVT::v1i128, Expand); 846 setOperationAction(ISD::SRA, MVT::v1i128, Expand); 847 848 setOperationAction(ISD::SETCC, MVT::v2i64, Legal); 849 } 850 else { 851 setOperationAction(ISD::SHL, MVT::v2i64, Expand); 852 setOperationAction(ISD::SRA, MVT::v2i64, Expand); 853 setOperationAction(ISD::SRL, MVT::v2i64, Expand); 854 855 setOperationAction(ISD::SETCC, MVT::v2i64, Custom); 856 857 // VSX v2i64 only supports non-arithmetic operations. 858 setOperationAction(ISD::ADD, MVT::v2i64, Expand); 859 setOperationAction(ISD::SUB, MVT::v2i64, Expand); 860 } 861 862 setOperationAction(ISD::LOAD, MVT::v2i64, Promote); 863 AddPromotedToType (ISD::LOAD, MVT::v2i64, MVT::v2f64); 864 setOperationAction(ISD::STORE, MVT::v2i64, Promote); 865 AddPromotedToType (ISD::STORE, MVT::v2i64, MVT::v2f64); 866 867 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Legal); 868 869 setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal); 870 setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal); 871 setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal); 872 setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal); 873 874 // Custom handling for partial vectors of integers converted to 875 // floating point. We already have optimal handling for v2i32 through 876 // the DAG combine, so those aren't necessary. 877 setOperationAction(ISD::UINT_TO_FP, MVT::v2i8, Custom); 878 setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Custom); 879 setOperationAction(ISD::UINT_TO_FP, MVT::v2i16, Custom); 880 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom); 881 setOperationAction(ISD::SINT_TO_FP, MVT::v2i8, Custom); 882 setOperationAction(ISD::SINT_TO_FP, MVT::v4i8, Custom); 883 setOperationAction(ISD::SINT_TO_FP, MVT::v2i16, Custom); 884 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom); 885 886 setOperationAction(ISD::FNEG, MVT::v4f32, Legal); 887 setOperationAction(ISD::FNEG, MVT::v2f64, Legal); 888 setOperationAction(ISD::FABS, MVT::v4f32, Legal); 889 setOperationAction(ISD::FABS, MVT::v2f64, Legal); 890 setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Legal); 891 setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Legal); 892 893 if (Subtarget.hasDirectMove()) 894 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom); 895 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom); 896 897 addRegisterClass(MVT::v2i64, &PPC::VSRCRegClass); 898 } 899 900 if (Subtarget.hasP8Altivec()) { 901 addRegisterClass(MVT::v2i64, &PPC::VRRCRegClass); 902 addRegisterClass(MVT::v1i128, &PPC::VRRCRegClass); 903 } 904 905 if (Subtarget.hasP9Vector()) { 906 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom); 907 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom); 908 909 // 128 bit shifts can be accomplished via 3 instructions for SHL and 910 // SRL, but not for SRA because of the instructions available: 911 // VS{RL} and VS{RL}O. 912 setOperationAction(ISD::SHL, MVT::v1i128, Legal); 913 setOperationAction(ISD::SRL, MVT::v1i128, Legal); 914 setOperationAction(ISD::SRA, MVT::v1i128, Expand); 915 916 if (EnableQuadPrecision) { 917 addRegisterClass(MVT::f128, &PPC::VRRCRegClass); 918 setOperationAction(ISD::FADD, MVT::f128, Legal); 919 setOperationAction(ISD::FSUB, MVT::f128, Legal); 920 setOperationAction(ISD::FDIV, MVT::f128, Legal); 921 setOperationAction(ISD::FMUL, MVT::f128, Legal); 922 setOperationAction(ISD::FP_EXTEND, MVT::f128, Legal); 923 // No extending loads to f128 on PPC. 924 for (MVT FPT : MVT::fp_valuetypes()) 925 setLoadExtAction(ISD::EXTLOAD, MVT::f128, FPT, Expand); 926 setOperationAction(ISD::FMA, MVT::f128, Legal); 927 setCondCodeAction(ISD::SETULT, MVT::f128, Expand); 928 setCondCodeAction(ISD::SETUGT, MVT::f128, Expand); 929 setCondCodeAction(ISD::SETUEQ, MVT::f128, Expand); 930 setCondCodeAction(ISD::SETOGE, MVT::f128, Expand); 931 setCondCodeAction(ISD::SETOLE, MVT::f128, Expand); 932 setCondCodeAction(ISD::SETONE, MVT::f128, Expand); 933 934 setOperationAction(ISD::FTRUNC, MVT::f128, Legal); 935 setOperationAction(ISD::FRINT, MVT::f128, Legal); 936 setOperationAction(ISD::FFLOOR, MVT::f128, Legal); 937 setOperationAction(ISD::FCEIL, MVT::f128, Legal); 938 setOperationAction(ISD::FNEARBYINT, MVT::f128, Legal); 939 setOperationAction(ISD::FROUND, MVT::f128, Legal); 940 941 setOperationAction(ISD::SELECT, MVT::f128, Expand); 942 setOperationAction(ISD::FP_ROUND, MVT::f64, Legal); 943 setOperationAction(ISD::FP_ROUND, MVT::f32, Legal); 944 setTruncStoreAction(MVT::f128, MVT::f64, Expand); 945 setTruncStoreAction(MVT::f128, MVT::f32, Expand); 946 setOperationAction(ISD::BITCAST, MVT::i128, Custom); 947 // No implementation for these ops for PowerPC. 948 setOperationAction(ISD::FSIN , MVT::f128, Expand); 949 setOperationAction(ISD::FCOS , MVT::f128, Expand); 950 setOperationAction(ISD::FPOW, MVT::f128, Expand); 951 setOperationAction(ISD::FPOWI, MVT::f128, Expand); 952 setOperationAction(ISD::FREM, MVT::f128, Expand); 953 } 954 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom); 955 setOperationAction(ISD::BSWAP, MVT::v8i16, Legal); 956 setOperationAction(ISD::BSWAP, MVT::v4i32, Legal); 957 setOperationAction(ISD::BSWAP, MVT::v2i64, Legal); 958 setOperationAction(ISD::BSWAP, MVT::v1i128, Legal); 959 } 960 961 if (Subtarget.hasP9Altivec()) { 962 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom); 963 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom); 964 965 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Legal); 966 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Legal); 967 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i32, Legal); 968 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Legal); 969 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Legal); 970 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i32, Legal); 971 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i64, Legal); 972 } 973 } 974 975 if (Subtarget.hasQPX()) { 976 setOperationAction(ISD::FADD, MVT::v4f64, Legal); 977 setOperationAction(ISD::FSUB, MVT::v4f64, Legal); 978 setOperationAction(ISD::FMUL, MVT::v4f64, Legal); 979 setOperationAction(ISD::FREM, MVT::v4f64, Expand); 980 981 setOperationAction(ISD::FCOPYSIGN, MVT::v4f64, Legal); 982 setOperationAction(ISD::FGETSIGN, MVT::v4f64, Expand); 983 984 setOperationAction(ISD::LOAD , MVT::v4f64, Custom); 985 setOperationAction(ISD::STORE , MVT::v4f64, Custom); 986 987 setTruncStoreAction(MVT::v4f64, MVT::v4f32, Custom); 988 setLoadExtAction(ISD::EXTLOAD, MVT::v4f64, MVT::v4f32, Custom); 989 990 if (!Subtarget.useCRBits()) 991 setOperationAction(ISD::SELECT, MVT::v4f64, Expand); 992 setOperationAction(ISD::VSELECT, MVT::v4f64, Legal); 993 994 setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f64, Legal); 995 setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f64, Expand); 996 setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f64, Expand); 997 setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f64, Expand); 998 setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f64, Custom); 999 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f64, Legal); 1000 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f64, Custom); 1001 1002 setOperationAction(ISD::FP_TO_SINT , MVT::v4f64, Legal); 1003 setOperationAction(ISD::FP_TO_UINT , MVT::v4f64, Expand); 1004 1005 setOperationAction(ISD::FP_ROUND , MVT::v4f32, Legal); 1006 setOperationAction(ISD::FP_EXTEND, MVT::v4f64, Legal); 1007 1008 setOperationAction(ISD::FNEG , MVT::v4f64, Legal); 1009 setOperationAction(ISD::FABS , MVT::v4f64, Legal); 1010 setOperationAction(ISD::FSIN , MVT::v4f64, Expand); 1011 setOperationAction(ISD::FCOS , MVT::v4f64, Expand); 1012 setOperationAction(ISD::FPOW , MVT::v4f64, Expand); 1013 setOperationAction(ISD::FLOG , MVT::v4f64, Expand); 1014 setOperationAction(ISD::FLOG2 , MVT::v4f64, Expand); 1015 setOperationAction(ISD::FLOG10 , MVT::v4f64, Expand); 1016 setOperationAction(ISD::FEXP , MVT::v4f64, Expand); 1017 setOperationAction(ISD::FEXP2 , MVT::v4f64, Expand); 1018 1019 setOperationAction(ISD::FMINNUM, MVT::v4f64, Legal); 1020 setOperationAction(ISD::FMAXNUM, MVT::v4f64, Legal); 1021 1022 setIndexedLoadAction(ISD::PRE_INC, MVT::v4f64, Legal); 1023 setIndexedStoreAction(ISD::PRE_INC, MVT::v4f64, Legal); 1024 1025 addRegisterClass(MVT::v4f64, &PPC::QFRCRegClass); 1026 1027 setOperationAction(ISD::FADD, MVT::v4f32, Legal); 1028 setOperationAction(ISD::FSUB, MVT::v4f32, Legal); 1029 setOperationAction(ISD::FMUL, MVT::v4f32, Legal); 1030 setOperationAction(ISD::FREM, MVT::v4f32, Expand); 1031 1032 setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Legal); 1033 setOperationAction(ISD::FGETSIGN, MVT::v4f32, Expand); 1034 1035 setOperationAction(ISD::LOAD , MVT::v4f32, Custom); 1036 setOperationAction(ISD::STORE , MVT::v4f32, Custom); 1037 1038 if (!Subtarget.useCRBits()) 1039 setOperationAction(ISD::SELECT, MVT::v4f32, Expand); 1040 setOperationAction(ISD::VSELECT, MVT::v4f32, Legal); 1041 1042 setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f32, Legal); 1043 setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f32, Expand); 1044 setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f32, Expand); 1045 setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f32, Expand); 1046 setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f32, Custom); 1047 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal); 1048 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom); 1049 1050 setOperationAction(ISD::FP_TO_SINT , MVT::v4f32, Legal); 1051 setOperationAction(ISD::FP_TO_UINT , MVT::v4f32, Expand); 1052 1053 setOperationAction(ISD::FNEG , MVT::v4f32, Legal); 1054 setOperationAction(ISD::FABS , MVT::v4f32, Legal); 1055 setOperationAction(ISD::FSIN , MVT::v4f32, Expand); 1056 setOperationAction(ISD::FCOS , MVT::v4f32, Expand); 1057 setOperationAction(ISD::FPOW , MVT::v4f32, Expand); 1058 setOperationAction(ISD::FLOG , MVT::v4f32, Expand); 1059 setOperationAction(ISD::FLOG2 , MVT::v4f32, Expand); 1060 setOperationAction(ISD::FLOG10 , MVT::v4f32, Expand); 1061 setOperationAction(ISD::FEXP , MVT::v4f32, Expand); 1062 setOperationAction(ISD::FEXP2 , MVT::v4f32, Expand); 1063 1064 setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal); 1065 setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal); 1066 1067 setIndexedLoadAction(ISD::PRE_INC, MVT::v4f32, Legal); 1068 setIndexedStoreAction(ISD::PRE_INC, MVT::v4f32, Legal); 1069 1070 addRegisterClass(MVT::v4f32, &PPC::QSRCRegClass); 1071 1072 setOperationAction(ISD::AND , MVT::v4i1, Legal); 1073 setOperationAction(ISD::OR , MVT::v4i1, Legal); 1074 setOperationAction(ISD::XOR , MVT::v4i1, Legal); 1075 1076 if (!Subtarget.useCRBits()) 1077 setOperationAction(ISD::SELECT, MVT::v4i1, Expand); 1078 setOperationAction(ISD::VSELECT, MVT::v4i1, Legal); 1079 1080 setOperationAction(ISD::LOAD , MVT::v4i1, Custom); 1081 setOperationAction(ISD::STORE , MVT::v4i1, Custom); 1082 1083 setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4i1, Custom); 1084 setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4i1, Expand); 1085 setOperationAction(ISD::CONCAT_VECTORS , MVT::v4i1, Expand); 1086 setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4i1, Expand); 1087 setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4i1, Custom); 1088 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i1, Expand); 1089 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i1, Custom); 1090 1091 setOperationAction(ISD::SINT_TO_FP, MVT::v4i1, Custom); 1092 setOperationAction(ISD::UINT_TO_FP, MVT::v4i1, Custom); 1093 1094 addRegisterClass(MVT::v4i1, &PPC::QBRCRegClass); 1095 1096 setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal); 1097 setOperationAction(ISD::FCEIL, MVT::v4f64, Legal); 1098 setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal); 1099 setOperationAction(ISD::FROUND, MVT::v4f64, Legal); 1100 1101 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal); 1102 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal); 1103 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal); 1104 setOperationAction(ISD::FROUND, MVT::v4f32, Legal); 1105 1106 setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Expand); 1107 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand); 1108 1109 // These need to set FE_INEXACT, and so cannot be vectorized here. 1110 setOperationAction(ISD::FRINT, MVT::v4f64, Expand); 1111 setOperationAction(ISD::FRINT, MVT::v4f32, Expand); 1112 1113 if (TM.Options.UnsafeFPMath) { 1114 setOperationAction(ISD::FDIV, MVT::v4f64, Legal); 1115 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal); 1116 1117 setOperationAction(ISD::FDIV, MVT::v4f32, Legal); 1118 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal); 1119 } else { 1120 setOperationAction(ISD::FDIV, MVT::v4f64, Expand); 1121 setOperationAction(ISD::FSQRT, MVT::v4f64, Expand); 1122 1123 setOperationAction(ISD::FDIV, MVT::v4f32, Expand); 1124 setOperationAction(ISD::FSQRT, MVT::v4f32, Expand); 1125 } 1126 } 1127 1128 if (Subtarget.has64BitSupport()) 1129 setOperationAction(ISD::PREFETCH, MVT::Other, Legal); 1130 1131 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, isPPC64 ? Legal : Custom); 1132 1133 if (!isPPC64) { 1134 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Expand); 1135 setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand); 1136 } 1137 1138 setBooleanContents(ZeroOrOneBooleanContent); 1139 1140 if (Subtarget.hasAltivec()) { 1141 // Altivec instructions set fields to all zeros or all ones. 1142 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent); 1143 } 1144 1145 if (!isPPC64) { 1146 // These libcalls are not available in 32-bit. 1147 setLibcallName(RTLIB::SHL_I128, nullptr); 1148 setLibcallName(RTLIB::SRL_I128, nullptr); 1149 setLibcallName(RTLIB::SRA_I128, nullptr); 1150 } 1151 1152 setStackPointerRegisterToSaveRestore(isPPC64 ? PPC::X1 : PPC::R1); 1153 1154 // We have target-specific dag combine patterns for the following nodes: 1155 setTargetDAGCombine(ISD::ADD); 1156 setTargetDAGCombine(ISD::SHL); 1157 setTargetDAGCombine(ISD::SRA); 1158 setTargetDAGCombine(ISD::SRL); 1159 setTargetDAGCombine(ISD::MUL); 1160 setTargetDAGCombine(ISD::SINT_TO_FP); 1161 setTargetDAGCombine(ISD::BUILD_VECTOR); 1162 if (Subtarget.hasFPCVT()) 1163 setTargetDAGCombine(ISD::UINT_TO_FP); 1164 setTargetDAGCombine(ISD::LOAD); 1165 setTargetDAGCombine(ISD::STORE); 1166 setTargetDAGCombine(ISD::BR_CC); 1167 if (Subtarget.useCRBits()) 1168 setTargetDAGCombine(ISD::BRCOND); 1169 setTargetDAGCombine(ISD::BSWAP); 1170 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN); 1171 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN); 1172 setTargetDAGCombine(ISD::INTRINSIC_VOID); 1173 1174 setTargetDAGCombine(ISD::SIGN_EXTEND); 1175 setTargetDAGCombine(ISD::ZERO_EXTEND); 1176 setTargetDAGCombine(ISD::ANY_EXTEND); 1177 1178 setTargetDAGCombine(ISD::TRUNCATE); 1179 setTargetDAGCombine(ISD::VECTOR_SHUFFLE); 1180 1181 1182 if (Subtarget.useCRBits()) { 1183 setTargetDAGCombine(ISD::TRUNCATE); 1184 setTargetDAGCombine(ISD::SETCC); 1185 setTargetDAGCombine(ISD::SELECT_CC); 1186 } 1187 1188 // Use reciprocal estimates. 1189 if (TM.Options.UnsafeFPMath) { 1190 setTargetDAGCombine(ISD::FDIV); 1191 setTargetDAGCombine(ISD::FSQRT); 1192 } 1193 1194 if (Subtarget.hasP9Altivec()) { 1195 setTargetDAGCombine(ISD::ABS); 1196 setTargetDAGCombine(ISD::VSELECT); 1197 } 1198 1199 if (EnableQuadPrecision) { 1200 setLibcallName(RTLIB::LOG_F128, "logf128"); 1201 setLibcallName(RTLIB::LOG2_F128, "log2f128"); 1202 setLibcallName(RTLIB::LOG10_F128, "log10f128"); 1203 setLibcallName(RTLIB::EXP_F128, "expf128"); 1204 setLibcallName(RTLIB::EXP2_F128, "exp2f128"); 1205 setLibcallName(RTLIB::SIN_F128, "sinf128"); 1206 setLibcallName(RTLIB::COS_F128, "cosf128"); 1207 setLibcallName(RTLIB::POW_F128, "powf128"); 1208 setLibcallName(RTLIB::FMIN_F128, "fminf128"); 1209 setLibcallName(RTLIB::FMAX_F128, "fmaxf128"); 1210 setLibcallName(RTLIB::POWI_F128, "__powikf2"); 1211 setLibcallName(RTLIB::REM_F128, "fmodf128"); 1212 } 1213 1214 // With 32 condition bits, we don't need to sink (and duplicate) compares 1215 // aggressively in CodeGenPrep. 1216 if (Subtarget.useCRBits()) { 1217 setHasMultipleConditionRegisters(); 1218 setJumpIsExpensive(); 1219 } 1220 1221 setMinFunctionAlignment(Align(4)); 1222 1223 switch (Subtarget.getCPUDirective()) { 1224 default: break; 1225 case PPC::DIR_970: 1226 case PPC::DIR_A2: 1227 case PPC::DIR_E500: 1228 case PPC::DIR_E500mc: 1229 case PPC::DIR_E5500: 1230 case PPC::DIR_PWR4: 1231 case PPC::DIR_PWR5: 1232 case PPC::DIR_PWR5X: 1233 case PPC::DIR_PWR6: 1234 case PPC::DIR_PWR6X: 1235 case PPC::DIR_PWR7: 1236 case PPC::DIR_PWR8: 1237 case PPC::DIR_PWR9: 1238 case PPC::DIR_PWR_FUTURE: 1239 setPrefLoopAlignment(Align(16)); 1240 setPrefFunctionAlignment(Align(16)); 1241 break; 1242 } 1243 1244 if (Subtarget.enableMachineScheduler()) 1245 setSchedulingPreference(Sched::Source); 1246 else 1247 setSchedulingPreference(Sched::Hybrid); 1248 1249 computeRegisterProperties(STI.getRegisterInfo()); 1250 1251 // The Freescale cores do better with aggressive inlining of memcpy and 1252 // friends. GCC uses same threshold of 128 bytes (= 32 word stores). 1253 if (Subtarget.getCPUDirective() == PPC::DIR_E500mc || 1254 Subtarget.getCPUDirective() == PPC::DIR_E5500) { 1255 MaxStoresPerMemset = 32; 1256 MaxStoresPerMemsetOptSize = 16; 1257 MaxStoresPerMemcpy = 32; 1258 MaxStoresPerMemcpyOptSize = 8; 1259 MaxStoresPerMemmove = 32; 1260 MaxStoresPerMemmoveOptSize = 8; 1261 } else if (Subtarget.getCPUDirective() == PPC::DIR_A2) { 1262 // The A2 also benefits from (very) aggressive inlining of memcpy and 1263 // friends. The overhead of a the function call, even when warm, can be 1264 // over one hundred cycles. 1265 MaxStoresPerMemset = 128; 1266 MaxStoresPerMemcpy = 128; 1267 MaxStoresPerMemmove = 128; 1268 MaxLoadsPerMemcmp = 128; 1269 } else { 1270 MaxLoadsPerMemcmp = 8; 1271 MaxLoadsPerMemcmpOptSize = 4; 1272 } 1273 } 1274 1275 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine 1276 /// the desired ByVal argument alignment. 1277 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign, 1278 unsigned MaxMaxAlign) { 1279 if (MaxAlign == MaxMaxAlign) 1280 return; 1281 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) { 1282 if (MaxMaxAlign >= 32 && VTy->getBitWidth() >= 256) 1283 MaxAlign = 32; 1284 else if (VTy->getBitWidth() >= 128 && MaxAlign < 16) 1285 MaxAlign = 16; 1286 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) { 1287 unsigned EltAlign = 0; 1288 getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign); 1289 if (EltAlign > MaxAlign) 1290 MaxAlign = EltAlign; 1291 } else if (StructType *STy = dyn_cast<StructType>(Ty)) { 1292 for (auto *EltTy : STy->elements()) { 1293 unsigned EltAlign = 0; 1294 getMaxByValAlign(EltTy, EltAlign, MaxMaxAlign); 1295 if (EltAlign > MaxAlign) 1296 MaxAlign = EltAlign; 1297 if (MaxAlign == MaxMaxAlign) 1298 break; 1299 } 1300 } 1301 } 1302 1303 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate 1304 /// function arguments in the caller parameter area. 1305 unsigned PPCTargetLowering::getByValTypeAlignment(Type *Ty, 1306 const DataLayout &DL) const { 1307 // 16byte and wider vectors are passed on 16byte boundary. 1308 // The rest is 8 on PPC64 and 4 on PPC32 boundary. 1309 unsigned Align = Subtarget.isPPC64() ? 8 : 4; 1310 if (Subtarget.hasAltivec() || Subtarget.hasQPX()) 1311 getMaxByValAlign(Ty, Align, Subtarget.hasQPX() ? 32 : 16); 1312 return Align; 1313 } 1314 1315 bool PPCTargetLowering::useSoftFloat() const { 1316 return Subtarget.useSoftFloat(); 1317 } 1318 1319 bool PPCTargetLowering::hasSPE() const { 1320 return Subtarget.hasSPE(); 1321 } 1322 1323 bool PPCTargetLowering::preferIncOfAddToSubOfNot(EVT VT) const { 1324 return VT.isScalarInteger(); 1325 } 1326 1327 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const { 1328 switch ((PPCISD::NodeType)Opcode) { 1329 case PPCISD::FIRST_NUMBER: break; 1330 case PPCISD::FSEL: return "PPCISD::FSEL"; 1331 case PPCISD::XSMAXCDP: return "PPCISD::XSMAXCDP"; 1332 case PPCISD::XSMINCDP: return "PPCISD::XSMINCDP"; 1333 case PPCISD::FCFID: return "PPCISD::FCFID"; 1334 case PPCISD::FCFIDU: return "PPCISD::FCFIDU"; 1335 case PPCISD::FCFIDS: return "PPCISD::FCFIDS"; 1336 case PPCISD::FCFIDUS: return "PPCISD::FCFIDUS"; 1337 case PPCISD::FCTIDZ: return "PPCISD::FCTIDZ"; 1338 case PPCISD::FCTIWZ: return "PPCISD::FCTIWZ"; 1339 case PPCISD::FCTIDUZ: return "PPCISD::FCTIDUZ"; 1340 case PPCISD::FCTIWUZ: return "PPCISD::FCTIWUZ"; 1341 case PPCISD::FP_TO_UINT_IN_VSR: 1342 return "PPCISD::FP_TO_UINT_IN_VSR,"; 1343 case PPCISD::FP_TO_SINT_IN_VSR: 1344 return "PPCISD::FP_TO_SINT_IN_VSR"; 1345 case PPCISD::FRE: return "PPCISD::FRE"; 1346 case PPCISD::FRSQRTE: return "PPCISD::FRSQRTE"; 1347 case PPCISD::STFIWX: return "PPCISD::STFIWX"; 1348 case PPCISD::VMADDFP: return "PPCISD::VMADDFP"; 1349 case PPCISD::VNMSUBFP: return "PPCISD::VNMSUBFP"; 1350 case PPCISD::VPERM: return "PPCISD::VPERM"; 1351 case PPCISD::XXSPLT: return "PPCISD::XXSPLT"; 1352 case PPCISD::VECINSERT: return "PPCISD::VECINSERT"; 1353 case PPCISD::XXPERMDI: return "PPCISD::XXPERMDI"; 1354 case PPCISD::VECSHL: return "PPCISD::VECSHL"; 1355 case PPCISD::CMPB: return "PPCISD::CMPB"; 1356 case PPCISD::Hi: return "PPCISD::Hi"; 1357 case PPCISD::Lo: return "PPCISD::Lo"; 1358 case PPCISD::TOC_ENTRY: return "PPCISD::TOC_ENTRY"; 1359 case PPCISD::ATOMIC_CMP_SWAP_8: return "PPCISD::ATOMIC_CMP_SWAP_8"; 1360 case PPCISD::ATOMIC_CMP_SWAP_16: return "PPCISD::ATOMIC_CMP_SWAP_16"; 1361 case PPCISD::DYNALLOC: return "PPCISD::DYNALLOC"; 1362 case PPCISD::DYNAREAOFFSET: return "PPCISD::DYNAREAOFFSET"; 1363 case PPCISD::GlobalBaseReg: return "PPCISD::GlobalBaseReg"; 1364 case PPCISD::SRL: return "PPCISD::SRL"; 1365 case PPCISD::SRA: return "PPCISD::SRA"; 1366 case PPCISD::SHL: return "PPCISD::SHL"; 1367 case PPCISD::SRA_ADDZE: return "PPCISD::SRA_ADDZE"; 1368 case PPCISD::CALL: return "PPCISD::CALL"; 1369 case PPCISD::CALL_NOP: return "PPCISD::CALL_NOP"; 1370 case PPCISD::MTCTR: return "PPCISD::MTCTR"; 1371 case PPCISD::BCTRL: return "PPCISD::BCTRL"; 1372 case PPCISD::BCTRL_LOAD_TOC: return "PPCISD::BCTRL_LOAD_TOC"; 1373 case PPCISD::RET_FLAG: return "PPCISD::RET_FLAG"; 1374 case PPCISD::READ_TIME_BASE: return "PPCISD::READ_TIME_BASE"; 1375 case PPCISD::EH_SJLJ_SETJMP: return "PPCISD::EH_SJLJ_SETJMP"; 1376 case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP"; 1377 case PPCISD::MFOCRF: return "PPCISD::MFOCRF"; 1378 case PPCISD::MFVSR: return "PPCISD::MFVSR"; 1379 case PPCISD::MTVSRA: return "PPCISD::MTVSRA"; 1380 case PPCISD::MTVSRZ: return "PPCISD::MTVSRZ"; 1381 case PPCISD::SINT_VEC_TO_FP: return "PPCISD::SINT_VEC_TO_FP"; 1382 case PPCISD::UINT_VEC_TO_FP: return "PPCISD::UINT_VEC_TO_FP"; 1383 case PPCISD::ANDI_rec_1_EQ_BIT: 1384 return "PPCISD::ANDI_rec_1_EQ_BIT"; 1385 case PPCISD::ANDI_rec_1_GT_BIT: 1386 return "PPCISD::ANDI_rec_1_GT_BIT"; 1387 case PPCISD::VCMP: return "PPCISD::VCMP"; 1388 case PPCISD::VCMPo: return "PPCISD::VCMPo"; 1389 case PPCISD::LBRX: return "PPCISD::LBRX"; 1390 case PPCISD::STBRX: return "PPCISD::STBRX"; 1391 case PPCISD::LFIWAX: return "PPCISD::LFIWAX"; 1392 case PPCISD::LFIWZX: return "PPCISD::LFIWZX"; 1393 case PPCISD::LXSIZX: return "PPCISD::LXSIZX"; 1394 case PPCISD::STXSIX: return "PPCISD::STXSIX"; 1395 case PPCISD::VEXTS: return "PPCISD::VEXTS"; 1396 case PPCISD::SExtVElems: return "PPCISD::SExtVElems"; 1397 case PPCISD::LXVD2X: return "PPCISD::LXVD2X"; 1398 case PPCISD::STXVD2X: return "PPCISD::STXVD2X"; 1399 case PPCISD::LOAD_VEC_BE: return "PPCISD::LOAD_VEC_BE"; 1400 case PPCISD::STORE_VEC_BE: return "PPCISD::STORE_VEC_BE"; 1401 case PPCISD::ST_VSR_SCAL_INT: 1402 return "PPCISD::ST_VSR_SCAL_INT"; 1403 case PPCISD::COND_BRANCH: return "PPCISD::COND_BRANCH"; 1404 case PPCISD::BDNZ: return "PPCISD::BDNZ"; 1405 case PPCISD::BDZ: return "PPCISD::BDZ"; 1406 case PPCISD::MFFS: return "PPCISD::MFFS"; 1407 case PPCISD::FADDRTZ: return "PPCISD::FADDRTZ"; 1408 case PPCISD::TC_RETURN: return "PPCISD::TC_RETURN"; 1409 case PPCISD::CR6SET: return "PPCISD::CR6SET"; 1410 case PPCISD::CR6UNSET: return "PPCISD::CR6UNSET"; 1411 case PPCISD::PPC32_GOT: return "PPCISD::PPC32_GOT"; 1412 case PPCISD::PPC32_PICGOT: return "PPCISD::PPC32_PICGOT"; 1413 case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA"; 1414 case PPCISD::LD_GOT_TPREL_L: return "PPCISD::LD_GOT_TPREL_L"; 1415 case PPCISD::ADD_TLS: return "PPCISD::ADD_TLS"; 1416 case PPCISD::ADDIS_TLSGD_HA: return "PPCISD::ADDIS_TLSGD_HA"; 1417 case PPCISD::ADDI_TLSGD_L: return "PPCISD::ADDI_TLSGD_L"; 1418 case PPCISD::GET_TLS_ADDR: return "PPCISD::GET_TLS_ADDR"; 1419 case PPCISD::ADDI_TLSGD_L_ADDR: return "PPCISD::ADDI_TLSGD_L_ADDR"; 1420 case PPCISD::ADDIS_TLSLD_HA: return "PPCISD::ADDIS_TLSLD_HA"; 1421 case PPCISD::ADDI_TLSLD_L: return "PPCISD::ADDI_TLSLD_L"; 1422 case PPCISD::GET_TLSLD_ADDR: return "PPCISD::GET_TLSLD_ADDR"; 1423 case PPCISD::ADDI_TLSLD_L_ADDR: return "PPCISD::ADDI_TLSLD_L_ADDR"; 1424 case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA"; 1425 case PPCISD::ADDI_DTPREL_L: return "PPCISD::ADDI_DTPREL_L"; 1426 case PPCISD::VADD_SPLAT: return "PPCISD::VADD_SPLAT"; 1427 case PPCISD::SC: return "PPCISD::SC"; 1428 case PPCISD::CLRBHRB: return "PPCISD::CLRBHRB"; 1429 case PPCISD::MFBHRBE: return "PPCISD::MFBHRBE"; 1430 case PPCISD::RFEBB: return "PPCISD::RFEBB"; 1431 case PPCISD::XXSWAPD: return "PPCISD::XXSWAPD"; 1432 case PPCISD::SWAP_NO_CHAIN: return "PPCISD::SWAP_NO_CHAIN"; 1433 case PPCISD::VABSD: return "PPCISD::VABSD"; 1434 case PPCISD::QVFPERM: return "PPCISD::QVFPERM"; 1435 case PPCISD::QVGPCI: return "PPCISD::QVGPCI"; 1436 case PPCISD::QVALIGNI: return "PPCISD::QVALIGNI"; 1437 case PPCISD::QVESPLATI: return "PPCISD::QVESPLATI"; 1438 case PPCISD::QBFLT: return "PPCISD::QBFLT"; 1439 case PPCISD::QVLFSb: return "PPCISD::QVLFSb"; 1440 case PPCISD::BUILD_FP128: return "PPCISD::BUILD_FP128"; 1441 case PPCISD::BUILD_SPE64: return "PPCISD::BUILD_SPE64"; 1442 case PPCISD::EXTRACT_SPE: return "PPCISD::EXTRACT_SPE"; 1443 case PPCISD::EXTSWSLI: return "PPCISD::EXTSWSLI"; 1444 case PPCISD::LD_VSX_LH: return "PPCISD::LD_VSX_LH"; 1445 case PPCISD::FP_EXTEND_HALF: return "PPCISD::FP_EXTEND_HALF"; 1446 case PPCISD::LD_SPLAT: return "PPCISD::LD_SPLAT"; 1447 } 1448 return nullptr; 1449 } 1450 1451 EVT PPCTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &C, 1452 EVT VT) const { 1453 if (!VT.isVector()) 1454 return Subtarget.useCRBits() ? MVT::i1 : MVT::i32; 1455 1456 if (Subtarget.hasQPX()) 1457 return EVT::getVectorVT(C, MVT::i1, VT.getVectorNumElements()); 1458 1459 return VT.changeVectorElementTypeToInteger(); 1460 } 1461 1462 bool PPCTargetLowering::enableAggressiveFMAFusion(EVT VT) const { 1463 assert(VT.isFloatingPoint() && "Non-floating-point FMA?"); 1464 return true; 1465 } 1466 1467 //===----------------------------------------------------------------------===// 1468 // Node matching predicates, for use by the tblgen matching code. 1469 //===----------------------------------------------------------------------===// 1470 1471 /// isFloatingPointZero - Return true if this is 0.0 or -0.0. 1472 static bool isFloatingPointZero(SDValue Op) { 1473 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) 1474 return CFP->getValueAPF().isZero(); 1475 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) { 1476 // Maybe this has already been legalized into the constant pool? 1477 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1))) 1478 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal())) 1479 return CFP->getValueAPF().isZero(); 1480 } 1481 return false; 1482 } 1483 1484 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode. Return 1485 /// true if Op is undef or if it matches the specified value. 1486 static bool isConstantOrUndef(int Op, int Val) { 1487 return Op < 0 || Op == Val; 1488 } 1489 1490 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a 1491 /// VPKUHUM instruction. 1492 /// The ShuffleKind distinguishes between big-endian operations with 1493 /// two different inputs (0), either-endian operations with two identical 1494 /// inputs (1), and little-endian operations with two different inputs (2). 1495 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td). 1496 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind, 1497 SelectionDAG &DAG) { 1498 bool IsLE = DAG.getDataLayout().isLittleEndian(); 1499 if (ShuffleKind == 0) { 1500 if (IsLE) 1501 return false; 1502 for (unsigned i = 0; i != 16; ++i) 1503 if (!isConstantOrUndef(N->getMaskElt(i), i*2+1)) 1504 return false; 1505 } else if (ShuffleKind == 2) { 1506 if (!IsLE) 1507 return false; 1508 for (unsigned i = 0; i != 16; ++i) 1509 if (!isConstantOrUndef(N->getMaskElt(i), i*2)) 1510 return false; 1511 } else if (ShuffleKind == 1) { 1512 unsigned j = IsLE ? 0 : 1; 1513 for (unsigned i = 0; i != 8; ++i) 1514 if (!isConstantOrUndef(N->getMaskElt(i), i*2+j) || 1515 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j)) 1516 return false; 1517 } 1518 return true; 1519 } 1520 1521 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a 1522 /// VPKUWUM instruction. 1523 /// The ShuffleKind distinguishes between big-endian operations with 1524 /// two different inputs (0), either-endian operations with two identical 1525 /// inputs (1), and little-endian operations with two different inputs (2). 1526 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td). 1527 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind, 1528 SelectionDAG &DAG) { 1529 bool IsLE = DAG.getDataLayout().isLittleEndian(); 1530 if (ShuffleKind == 0) { 1531 if (IsLE) 1532 return false; 1533 for (unsigned i = 0; i != 16; i += 2) 1534 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+2) || 1535 !isConstantOrUndef(N->getMaskElt(i+1), i*2+3)) 1536 return false; 1537 } else if (ShuffleKind == 2) { 1538 if (!IsLE) 1539 return false; 1540 for (unsigned i = 0; i != 16; i += 2) 1541 if (!isConstantOrUndef(N->getMaskElt(i ), i*2) || 1542 !isConstantOrUndef(N->getMaskElt(i+1), i*2+1)) 1543 return false; 1544 } else if (ShuffleKind == 1) { 1545 unsigned j = IsLE ? 0 : 2; 1546 for (unsigned i = 0; i != 8; i += 2) 1547 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+j) || 1548 !isConstantOrUndef(N->getMaskElt(i+1), i*2+j+1) || 1549 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j) || 1550 !isConstantOrUndef(N->getMaskElt(i+9), i*2+j+1)) 1551 return false; 1552 } 1553 return true; 1554 } 1555 1556 /// isVPKUDUMShuffleMask - Return true if this is the shuffle mask for a 1557 /// VPKUDUM instruction, AND the VPKUDUM instruction exists for the 1558 /// current subtarget. 1559 /// 1560 /// The ShuffleKind distinguishes between big-endian operations with 1561 /// two different inputs (0), either-endian operations with two identical 1562 /// inputs (1), and little-endian operations with two different inputs (2). 1563 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td). 1564 bool PPC::isVPKUDUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind, 1565 SelectionDAG &DAG) { 1566 const PPCSubtarget& Subtarget = 1567 static_cast<const PPCSubtarget&>(DAG.getSubtarget()); 1568 if (!Subtarget.hasP8Vector()) 1569 return false; 1570 1571 bool IsLE = DAG.getDataLayout().isLittleEndian(); 1572 if (ShuffleKind == 0) { 1573 if (IsLE) 1574 return false; 1575 for (unsigned i = 0; i != 16; i += 4) 1576 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+4) || 1577 !isConstantOrUndef(N->getMaskElt(i+1), i*2+5) || 1578 !isConstantOrUndef(N->getMaskElt(i+2), i*2+6) || 1579 !isConstantOrUndef(N->getMaskElt(i+3), i*2+7)) 1580 return false; 1581 } else if (ShuffleKind == 2) { 1582 if (!IsLE) 1583 return false; 1584 for (unsigned i = 0; i != 16; i += 4) 1585 if (!isConstantOrUndef(N->getMaskElt(i ), i*2) || 1586 !isConstantOrUndef(N->getMaskElt(i+1), i*2+1) || 1587 !isConstantOrUndef(N->getMaskElt(i+2), i*2+2) || 1588 !isConstantOrUndef(N->getMaskElt(i+3), i*2+3)) 1589 return false; 1590 } else if (ShuffleKind == 1) { 1591 unsigned j = IsLE ? 0 : 4; 1592 for (unsigned i = 0; i != 8; i += 4) 1593 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+j) || 1594 !isConstantOrUndef(N->getMaskElt(i+1), i*2+j+1) || 1595 !isConstantOrUndef(N->getMaskElt(i+2), i*2+j+2) || 1596 !isConstantOrUndef(N->getMaskElt(i+3), i*2+j+3) || 1597 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j) || 1598 !isConstantOrUndef(N->getMaskElt(i+9), i*2+j+1) || 1599 !isConstantOrUndef(N->getMaskElt(i+10), i*2+j+2) || 1600 !isConstantOrUndef(N->getMaskElt(i+11), i*2+j+3)) 1601 return false; 1602 } 1603 return true; 1604 } 1605 1606 /// isVMerge - Common function, used to match vmrg* shuffles. 1607 /// 1608 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize, 1609 unsigned LHSStart, unsigned RHSStart) { 1610 if (N->getValueType(0) != MVT::v16i8) 1611 return false; 1612 assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) && 1613 "Unsupported merge size!"); 1614 1615 for (unsigned i = 0; i != 8/UnitSize; ++i) // Step over units 1616 for (unsigned j = 0; j != UnitSize; ++j) { // Step over bytes within unit 1617 if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j), 1618 LHSStart+j+i*UnitSize) || 1619 !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j), 1620 RHSStart+j+i*UnitSize)) 1621 return false; 1622 } 1623 return true; 1624 } 1625 1626 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for 1627 /// a VMRGL* instruction with the specified unit size (1,2 or 4 bytes). 1628 /// The ShuffleKind distinguishes between big-endian merges with two 1629 /// different inputs (0), either-endian merges with two identical inputs (1), 1630 /// and little-endian merges with two different inputs (2). For the latter, 1631 /// the input operands are swapped (see PPCInstrAltivec.td). 1632 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize, 1633 unsigned ShuffleKind, SelectionDAG &DAG) { 1634 if (DAG.getDataLayout().isLittleEndian()) { 1635 if (ShuffleKind == 1) // unary 1636 return isVMerge(N, UnitSize, 0, 0); 1637 else if (ShuffleKind == 2) // swapped 1638 return isVMerge(N, UnitSize, 0, 16); 1639 else 1640 return false; 1641 } else { 1642 if (ShuffleKind == 1) // unary 1643 return isVMerge(N, UnitSize, 8, 8); 1644 else if (ShuffleKind == 0) // normal 1645 return isVMerge(N, UnitSize, 8, 24); 1646 else 1647 return false; 1648 } 1649 } 1650 1651 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for 1652 /// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes). 1653 /// The ShuffleKind distinguishes between big-endian merges with two 1654 /// different inputs (0), either-endian merges with two identical inputs (1), 1655 /// and little-endian merges with two different inputs (2). For the latter, 1656 /// the input operands are swapped (see PPCInstrAltivec.td). 1657 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize, 1658 unsigned ShuffleKind, SelectionDAG &DAG) { 1659 if (DAG.getDataLayout().isLittleEndian()) { 1660 if (ShuffleKind == 1) // unary 1661 return isVMerge(N, UnitSize, 8, 8); 1662 else if (ShuffleKind == 2) // swapped 1663 return isVMerge(N, UnitSize, 8, 24); 1664 else 1665 return false; 1666 } else { 1667 if (ShuffleKind == 1) // unary 1668 return isVMerge(N, UnitSize, 0, 0); 1669 else if (ShuffleKind == 0) // normal 1670 return isVMerge(N, UnitSize, 0, 16); 1671 else 1672 return false; 1673 } 1674 } 1675 1676 /** 1677 * Common function used to match vmrgew and vmrgow shuffles 1678 * 1679 * The indexOffset determines whether to look for even or odd words in 1680 * the shuffle mask. This is based on the of the endianness of the target 1681 * machine. 1682 * - Little Endian: 1683 * - Use offset of 0 to check for odd elements 1684 * - Use offset of 4 to check for even elements 1685 * - Big Endian: 1686 * - Use offset of 0 to check for even elements 1687 * - Use offset of 4 to check for odd elements 1688 * A detailed description of the vector element ordering for little endian and 1689 * big endian can be found at 1690 * http://www.ibm.com/developerworks/library/l-ibm-xl-c-cpp-compiler/index.html 1691 * Targeting your applications - what little endian and big endian IBM XL C/C++ 1692 * compiler differences mean to you 1693 * 1694 * The mask to the shuffle vector instruction specifies the indices of the 1695 * elements from the two input vectors to place in the result. The elements are 1696 * numbered in array-access order, starting with the first vector. These vectors 1697 * are always of type v16i8, thus each vector will contain 16 elements of size 1698 * 8. More info on the shuffle vector can be found in the 1699 * http://llvm.org/docs/LangRef.html#shufflevector-instruction 1700 * Language Reference. 1701 * 1702 * The RHSStartValue indicates whether the same input vectors are used (unary) 1703 * or two different input vectors are used, based on the following: 1704 * - If the instruction uses the same vector for both inputs, the range of the 1705 * indices will be 0 to 15. In this case, the RHSStart value passed should 1706 * be 0. 1707 * - If the instruction has two different vectors then the range of the 1708 * indices will be 0 to 31. In this case, the RHSStart value passed should 1709 * be 16 (indices 0-15 specify elements in the first vector while indices 16 1710 * to 31 specify elements in the second vector). 1711 * 1712 * \param[in] N The shuffle vector SD Node to analyze 1713 * \param[in] IndexOffset Specifies whether to look for even or odd elements 1714 * \param[in] RHSStartValue Specifies the starting index for the righthand input 1715 * vector to the shuffle_vector instruction 1716 * \return true iff this shuffle vector represents an even or odd word merge 1717 */ 1718 static bool isVMerge(ShuffleVectorSDNode *N, unsigned IndexOffset, 1719 unsigned RHSStartValue) { 1720 if (N->getValueType(0) != MVT::v16i8) 1721 return false; 1722 1723 for (unsigned i = 0; i < 2; ++i) 1724 for (unsigned j = 0; j < 4; ++j) 1725 if (!isConstantOrUndef(N->getMaskElt(i*4+j), 1726 i*RHSStartValue+j+IndexOffset) || 1727 !isConstantOrUndef(N->getMaskElt(i*4+j+8), 1728 i*RHSStartValue+j+IndexOffset+8)) 1729 return false; 1730 return true; 1731 } 1732 1733 /** 1734 * Determine if the specified shuffle mask is suitable for the vmrgew or 1735 * vmrgow instructions. 1736 * 1737 * \param[in] N The shuffle vector SD Node to analyze 1738 * \param[in] CheckEven Check for an even merge (true) or an odd merge (false) 1739 * \param[in] ShuffleKind Identify the type of merge: 1740 * - 0 = big-endian merge with two different inputs; 1741 * - 1 = either-endian merge with two identical inputs; 1742 * - 2 = little-endian merge with two different inputs (inputs are swapped for 1743 * little-endian merges). 1744 * \param[in] DAG The current SelectionDAG 1745 * \return true iff this shuffle mask 1746 */ 1747 bool PPC::isVMRGEOShuffleMask(ShuffleVectorSDNode *N, bool CheckEven, 1748 unsigned ShuffleKind, SelectionDAG &DAG) { 1749 if (DAG.getDataLayout().isLittleEndian()) { 1750 unsigned indexOffset = CheckEven ? 4 : 0; 1751 if (ShuffleKind == 1) // Unary 1752 return isVMerge(N, indexOffset, 0); 1753 else if (ShuffleKind == 2) // swapped 1754 return isVMerge(N, indexOffset, 16); 1755 else 1756 return false; 1757 } 1758 else { 1759 unsigned indexOffset = CheckEven ? 0 : 4; 1760 if (ShuffleKind == 1) // Unary 1761 return isVMerge(N, indexOffset, 0); 1762 else if (ShuffleKind == 0) // Normal 1763 return isVMerge(N, indexOffset, 16); 1764 else 1765 return false; 1766 } 1767 return false; 1768 } 1769 1770 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift 1771 /// amount, otherwise return -1. 1772 /// The ShuffleKind distinguishes between big-endian operations with two 1773 /// different inputs (0), either-endian operations with two identical inputs 1774 /// (1), and little-endian operations with two different inputs (2). For the 1775 /// latter, the input operands are swapped (see PPCInstrAltivec.td). 1776 int PPC::isVSLDOIShuffleMask(SDNode *N, unsigned ShuffleKind, 1777 SelectionDAG &DAG) { 1778 if (N->getValueType(0) != MVT::v16i8) 1779 return -1; 1780 1781 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 1782 1783 // Find the first non-undef value in the shuffle mask. 1784 unsigned i; 1785 for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i) 1786 /*search*/; 1787 1788 if (i == 16) return -1; // all undef. 1789 1790 // Otherwise, check to see if the rest of the elements are consecutively 1791 // numbered from this value. 1792 unsigned ShiftAmt = SVOp->getMaskElt(i); 1793 if (ShiftAmt < i) return -1; 1794 1795 ShiftAmt -= i; 1796 bool isLE = DAG.getDataLayout().isLittleEndian(); 1797 1798 if ((ShuffleKind == 0 && !isLE) || (ShuffleKind == 2 && isLE)) { 1799 // Check the rest of the elements to see if they are consecutive. 1800 for (++i; i != 16; ++i) 1801 if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i)) 1802 return -1; 1803 } else if (ShuffleKind == 1) { 1804 // Check the rest of the elements to see if they are consecutive. 1805 for (++i; i != 16; ++i) 1806 if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15)) 1807 return -1; 1808 } else 1809 return -1; 1810 1811 if (isLE) 1812 ShiftAmt = 16 - ShiftAmt; 1813 1814 return ShiftAmt; 1815 } 1816 1817 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand 1818 /// specifies a splat of a single element that is suitable for input to 1819 /// one of the splat operations (VSPLTB/VSPLTH/VSPLTW/XXSPLTW/LXVDSX/etc.). 1820 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) { 1821 assert(N->getValueType(0) == MVT::v16i8 && isPowerOf2_32(EltSize) && 1822 EltSize <= 8 && "Can only handle 1,2,4,8 byte element sizes"); 1823 1824 // The consecutive indices need to specify an element, not part of two 1825 // different elements. So abandon ship early if this isn't the case. 1826 if (N->getMaskElt(0) % EltSize != 0) 1827 return false; 1828 1829 // This is a splat operation if each element of the permute is the same, and 1830 // if the value doesn't reference the second vector. 1831 unsigned ElementBase = N->getMaskElt(0); 1832 1833 // FIXME: Handle UNDEF elements too! 1834 if (ElementBase >= 16) 1835 return false; 1836 1837 // Check that the indices are consecutive, in the case of a multi-byte element 1838 // splatted with a v16i8 mask. 1839 for (unsigned i = 1; i != EltSize; ++i) 1840 if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase)) 1841 return false; 1842 1843 for (unsigned i = EltSize, e = 16; i != e; i += EltSize) { 1844 if (N->getMaskElt(i) < 0) continue; 1845 for (unsigned j = 0; j != EltSize; ++j) 1846 if (N->getMaskElt(i+j) != N->getMaskElt(j)) 1847 return false; 1848 } 1849 return true; 1850 } 1851 1852 /// Check that the mask is shuffling N byte elements. Within each N byte 1853 /// element of the mask, the indices could be either in increasing or 1854 /// decreasing order as long as they are consecutive. 1855 /// \param[in] N the shuffle vector SD Node to analyze 1856 /// \param[in] Width the element width in bytes, could be 2/4/8/16 (HalfWord/ 1857 /// Word/DoubleWord/QuadWord). 1858 /// \param[in] StepLen the delta indices number among the N byte element, if 1859 /// the mask is in increasing/decreasing order then it is 1/-1. 1860 /// \return true iff the mask is shuffling N byte elements. 1861 static bool isNByteElemShuffleMask(ShuffleVectorSDNode *N, unsigned Width, 1862 int StepLen) { 1863 assert((Width == 2 || Width == 4 || Width == 8 || Width == 16) && 1864 "Unexpected element width."); 1865 assert((StepLen == 1 || StepLen == -1) && "Unexpected element width."); 1866 1867 unsigned NumOfElem = 16 / Width; 1868 unsigned MaskVal[16]; // Width is never greater than 16 1869 for (unsigned i = 0; i < NumOfElem; ++i) { 1870 MaskVal[0] = N->getMaskElt(i * Width); 1871 if ((StepLen == 1) && (MaskVal[0] % Width)) { 1872 return false; 1873 } else if ((StepLen == -1) && ((MaskVal[0] + 1) % Width)) { 1874 return false; 1875 } 1876 1877 for (unsigned int j = 1; j < Width; ++j) { 1878 MaskVal[j] = N->getMaskElt(i * Width + j); 1879 if (MaskVal[j] != MaskVal[j-1] + StepLen) { 1880 return false; 1881 } 1882 } 1883 } 1884 1885 return true; 1886 } 1887 1888 bool PPC::isXXINSERTWMask(ShuffleVectorSDNode *N, unsigned &ShiftElts, 1889 unsigned &InsertAtByte, bool &Swap, bool IsLE) { 1890 if (!isNByteElemShuffleMask(N, 4, 1)) 1891 return false; 1892 1893 // Now we look at mask elements 0,4,8,12 1894 unsigned M0 = N->getMaskElt(0) / 4; 1895 unsigned M1 = N->getMaskElt(4) / 4; 1896 unsigned M2 = N->getMaskElt(8) / 4; 1897 unsigned M3 = N->getMaskElt(12) / 4; 1898 unsigned LittleEndianShifts[] = { 2, 1, 0, 3 }; 1899 unsigned BigEndianShifts[] = { 3, 0, 1, 2 }; 1900 1901 // Below, let H and L be arbitrary elements of the shuffle mask 1902 // where H is in the range [4,7] and L is in the range [0,3]. 1903 // H, 1, 2, 3 or L, 5, 6, 7 1904 if ((M0 > 3 && M1 == 1 && M2 == 2 && M3 == 3) || 1905 (M0 < 4 && M1 == 5 && M2 == 6 && M3 == 7)) { 1906 ShiftElts = IsLE ? LittleEndianShifts[M0 & 0x3] : BigEndianShifts[M0 & 0x3]; 1907 InsertAtByte = IsLE ? 12 : 0; 1908 Swap = M0 < 4; 1909 return true; 1910 } 1911 // 0, H, 2, 3 or 4, L, 6, 7 1912 if ((M1 > 3 && M0 == 0 && M2 == 2 && M3 == 3) || 1913 (M1 < 4 && M0 == 4 && M2 == 6 && M3 == 7)) { 1914 ShiftElts = IsLE ? LittleEndianShifts[M1 & 0x3] : BigEndianShifts[M1 & 0x3]; 1915 InsertAtByte = IsLE ? 8 : 4; 1916 Swap = M1 < 4; 1917 return true; 1918 } 1919 // 0, 1, H, 3 or 4, 5, L, 7 1920 if ((M2 > 3 && M0 == 0 && M1 == 1 && M3 == 3) || 1921 (M2 < 4 && M0 == 4 && M1 == 5 && M3 == 7)) { 1922 ShiftElts = IsLE ? LittleEndianShifts[M2 & 0x3] : BigEndianShifts[M2 & 0x3]; 1923 InsertAtByte = IsLE ? 4 : 8; 1924 Swap = M2 < 4; 1925 return true; 1926 } 1927 // 0, 1, 2, H or 4, 5, 6, L 1928 if ((M3 > 3 && M0 == 0 && M1 == 1 && M2 == 2) || 1929 (M3 < 4 && M0 == 4 && M1 == 5 && M2 == 6)) { 1930 ShiftElts = IsLE ? LittleEndianShifts[M3 & 0x3] : BigEndianShifts[M3 & 0x3]; 1931 InsertAtByte = IsLE ? 0 : 12; 1932 Swap = M3 < 4; 1933 return true; 1934 } 1935 1936 // If both vector operands for the shuffle are the same vector, the mask will 1937 // contain only elements from the first one and the second one will be undef. 1938 if (N->getOperand(1).isUndef()) { 1939 ShiftElts = 0; 1940 Swap = true; 1941 unsigned XXINSERTWSrcElem = IsLE ? 2 : 1; 1942 if (M0 == XXINSERTWSrcElem && M1 == 1 && M2 == 2 && M3 == 3) { 1943 InsertAtByte = IsLE ? 12 : 0; 1944 return true; 1945 } 1946 if (M0 == 0 && M1 == XXINSERTWSrcElem && M2 == 2 && M3 == 3) { 1947 InsertAtByte = IsLE ? 8 : 4; 1948 return true; 1949 } 1950 if (M0 == 0 && M1 == 1 && M2 == XXINSERTWSrcElem && M3 == 3) { 1951 InsertAtByte = IsLE ? 4 : 8; 1952 return true; 1953 } 1954 if (M0 == 0 && M1 == 1 && M2 == 2 && M3 == XXINSERTWSrcElem) { 1955 InsertAtByte = IsLE ? 0 : 12; 1956 return true; 1957 } 1958 } 1959 1960 return false; 1961 } 1962 1963 bool PPC::isXXSLDWIShuffleMask(ShuffleVectorSDNode *N, unsigned &ShiftElts, 1964 bool &Swap, bool IsLE) { 1965 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8"); 1966 // Ensure each byte index of the word is consecutive. 1967 if (!isNByteElemShuffleMask(N, 4, 1)) 1968 return false; 1969 1970 // Now we look at mask elements 0,4,8,12, which are the beginning of words. 1971 unsigned M0 = N->getMaskElt(0) / 4; 1972 unsigned M1 = N->getMaskElt(4) / 4; 1973 unsigned M2 = N->getMaskElt(8) / 4; 1974 unsigned M3 = N->getMaskElt(12) / 4; 1975 1976 // If both vector operands for the shuffle are the same vector, the mask will 1977 // contain only elements from the first one and the second one will be undef. 1978 if (N->getOperand(1).isUndef()) { 1979 assert(M0 < 4 && "Indexing into an undef vector?"); 1980 if (M1 != (M0 + 1) % 4 || M2 != (M1 + 1) % 4 || M3 != (M2 + 1) % 4) 1981 return false; 1982 1983 ShiftElts = IsLE ? (4 - M0) % 4 : M0; 1984 Swap = false; 1985 return true; 1986 } 1987 1988 // Ensure each word index of the ShuffleVector Mask is consecutive. 1989 if (M1 != (M0 + 1) % 8 || M2 != (M1 + 1) % 8 || M3 != (M2 + 1) % 8) 1990 return false; 1991 1992 if (IsLE) { 1993 if (M0 == 0 || M0 == 7 || M0 == 6 || M0 == 5) { 1994 // Input vectors don't need to be swapped if the leading element 1995 // of the result is one of the 3 left elements of the second vector 1996 // (or if there is no shift to be done at all). 1997 Swap = false; 1998 ShiftElts = (8 - M0) % 8; 1999 } else if (M0 == 4 || M0 == 3 || M0 == 2 || M0 == 1) { 2000 // Input vectors need to be swapped if the leading element 2001 // of the result is one of the 3 left elements of the first vector 2002 // (or if we're shifting by 4 - thereby simply swapping the vectors). 2003 Swap = true; 2004 ShiftElts = (4 - M0) % 4; 2005 } 2006 2007 return true; 2008 } else { // BE 2009 if (M0 == 0 || M0 == 1 || M0 == 2 || M0 == 3) { 2010 // Input vectors don't need to be swapped if the leading element 2011 // of the result is one of the 4 elements of the first vector. 2012 Swap = false; 2013 ShiftElts = M0; 2014 } else if (M0 == 4 || M0 == 5 || M0 == 6 || M0 == 7) { 2015 // Input vectors need to be swapped if the leading element 2016 // of the result is one of the 4 elements of the right vector. 2017 Swap = true; 2018 ShiftElts = M0 - 4; 2019 } 2020 2021 return true; 2022 } 2023 } 2024 2025 bool static isXXBRShuffleMaskHelper(ShuffleVectorSDNode *N, int Width) { 2026 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8"); 2027 2028 if (!isNByteElemShuffleMask(N, Width, -1)) 2029 return false; 2030 2031 for (int i = 0; i < 16; i += Width) 2032 if (N->getMaskElt(i) != i + Width - 1) 2033 return false; 2034 2035 return true; 2036 } 2037 2038 bool PPC::isXXBRHShuffleMask(ShuffleVectorSDNode *N) { 2039 return isXXBRShuffleMaskHelper(N, 2); 2040 } 2041 2042 bool PPC::isXXBRWShuffleMask(ShuffleVectorSDNode *N) { 2043 return isXXBRShuffleMaskHelper(N, 4); 2044 } 2045 2046 bool PPC::isXXBRDShuffleMask(ShuffleVectorSDNode *N) { 2047 return isXXBRShuffleMaskHelper(N, 8); 2048 } 2049 2050 bool PPC::isXXBRQShuffleMask(ShuffleVectorSDNode *N) { 2051 return isXXBRShuffleMaskHelper(N, 16); 2052 } 2053 2054 /// Can node \p N be lowered to an XXPERMDI instruction? If so, set \p Swap 2055 /// if the inputs to the instruction should be swapped and set \p DM to the 2056 /// value for the immediate. 2057 /// Specifically, set \p Swap to true only if \p N can be lowered to XXPERMDI 2058 /// AND element 0 of the result comes from the first input (LE) or second input 2059 /// (BE). Set \p DM to the calculated result (0-3) only if \p N can be lowered. 2060 /// \return true iff the given mask of shuffle node \p N is a XXPERMDI shuffle 2061 /// mask. 2062 bool PPC::isXXPERMDIShuffleMask(ShuffleVectorSDNode *N, unsigned &DM, 2063 bool &Swap, bool IsLE) { 2064 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8"); 2065 2066 // Ensure each byte index of the double word is consecutive. 2067 if (!isNByteElemShuffleMask(N, 8, 1)) 2068 return false; 2069 2070 unsigned M0 = N->getMaskElt(0) / 8; 2071 unsigned M1 = N->getMaskElt(8) / 8; 2072 assert(((M0 | M1) < 4) && "A mask element out of bounds?"); 2073 2074 // If both vector operands for the shuffle are the same vector, the mask will 2075 // contain only elements from the first one and the second one will be undef. 2076 if (N->getOperand(1).isUndef()) { 2077 if ((M0 | M1) < 2) { 2078 DM = IsLE ? (((~M1) & 1) << 1) + ((~M0) & 1) : (M0 << 1) + (M1 & 1); 2079 Swap = false; 2080 return true; 2081 } else 2082 return false; 2083 } 2084 2085 if (IsLE) { 2086 if (M0 > 1 && M1 < 2) { 2087 Swap = false; 2088 } else if (M0 < 2 && M1 > 1) { 2089 M0 = (M0 + 2) % 4; 2090 M1 = (M1 + 2) % 4; 2091 Swap = true; 2092 } else 2093 return false; 2094 2095 // Note: if control flow comes here that means Swap is already set above 2096 DM = (((~M1) & 1) << 1) + ((~M0) & 1); 2097 return true; 2098 } else { // BE 2099 if (M0 < 2 && M1 > 1) { 2100 Swap = false; 2101 } else if (M0 > 1 && M1 < 2) { 2102 M0 = (M0 + 2) % 4; 2103 M1 = (M1 + 2) % 4; 2104 Swap = true; 2105 } else 2106 return false; 2107 2108 // Note: if control flow comes here that means Swap is already set above 2109 DM = (M0 << 1) + (M1 & 1); 2110 return true; 2111 } 2112 } 2113 2114 2115 /// getSplatIdxForPPCMnemonics - Return the splat index as a value that is 2116 /// appropriate for PPC mnemonics (which have a big endian bias - namely 2117 /// elements are counted from the left of the vector register). 2118 unsigned PPC::getSplatIdxForPPCMnemonics(SDNode *N, unsigned EltSize, 2119 SelectionDAG &DAG) { 2120 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 2121 assert(isSplatShuffleMask(SVOp, EltSize)); 2122 if (DAG.getDataLayout().isLittleEndian()) 2123 return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize); 2124 else 2125 return SVOp->getMaskElt(0) / EltSize; 2126 } 2127 2128 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed 2129 /// by using a vspltis[bhw] instruction of the specified element size, return 2130 /// the constant being splatted. The ByteSize field indicates the number of 2131 /// bytes of each element [124] -> [bhw]. 2132 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) { 2133 SDValue OpVal(nullptr, 0); 2134 2135 // If ByteSize of the splat is bigger than the element size of the 2136 // build_vector, then we have a case where we are checking for a splat where 2137 // multiple elements of the buildvector are folded together into a single 2138 // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8). 2139 unsigned EltSize = 16/N->getNumOperands(); 2140 if (EltSize < ByteSize) { 2141 unsigned Multiple = ByteSize/EltSize; // Number of BV entries per spltval. 2142 SDValue UniquedVals[4]; 2143 assert(Multiple > 1 && Multiple <= 4 && "How can this happen?"); 2144 2145 // See if all of the elements in the buildvector agree across. 2146 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 2147 if (N->getOperand(i).isUndef()) continue; 2148 // If the element isn't a constant, bail fully out. 2149 if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue(); 2150 2151 if (!UniquedVals[i&(Multiple-1)].getNode()) 2152 UniquedVals[i&(Multiple-1)] = N->getOperand(i); 2153 else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i)) 2154 return SDValue(); // no match. 2155 } 2156 2157 // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains 2158 // either constant or undef values that are identical for each chunk. See 2159 // if these chunks can form into a larger vspltis*. 2160 2161 // Check to see if all of the leading entries are either 0 or -1. If 2162 // neither, then this won't fit into the immediate field. 2163 bool LeadingZero = true; 2164 bool LeadingOnes = true; 2165 for (unsigned i = 0; i != Multiple-1; ++i) { 2166 if (!UniquedVals[i].getNode()) continue; // Must have been undefs. 2167 2168 LeadingZero &= isNullConstant(UniquedVals[i]); 2169 LeadingOnes &= isAllOnesConstant(UniquedVals[i]); 2170 } 2171 // Finally, check the least significant entry. 2172 if (LeadingZero) { 2173 if (!UniquedVals[Multiple-1].getNode()) 2174 return DAG.getTargetConstant(0, SDLoc(N), MVT::i32); // 0,0,0,undef 2175 int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue(); 2176 if (Val < 16) // 0,0,0,4 -> vspltisw(4) 2177 return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32); 2178 } 2179 if (LeadingOnes) { 2180 if (!UniquedVals[Multiple-1].getNode()) 2181 return DAG.getTargetConstant(~0U, SDLoc(N), MVT::i32); // -1,-1,-1,undef 2182 int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue(); 2183 if (Val >= -16) // -1,-1,-1,-2 -> vspltisw(-2) 2184 return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32); 2185 } 2186 2187 return SDValue(); 2188 } 2189 2190 // Check to see if this buildvec has a single non-undef value in its elements. 2191 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 2192 if (N->getOperand(i).isUndef()) continue; 2193 if (!OpVal.getNode()) 2194 OpVal = N->getOperand(i); 2195 else if (OpVal != N->getOperand(i)) 2196 return SDValue(); 2197 } 2198 2199 if (!OpVal.getNode()) return SDValue(); // All UNDEF: use implicit def. 2200 2201 unsigned ValSizeInBytes = EltSize; 2202 uint64_t Value = 0; 2203 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) { 2204 Value = CN->getZExtValue(); 2205 } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) { 2206 assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!"); 2207 Value = FloatToBits(CN->getValueAPF().convertToFloat()); 2208 } 2209 2210 // If the splat value is larger than the element value, then we can never do 2211 // this splat. The only case that we could fit the replicated bits into our 2212 // immediate field for would be zero, and we prefer to use vxor for it. 2213 if (ValSizeInBytes < ByteSize) return SDValue(); 2214 2215 // If the element value is larger than the splat value, check if it consists 2216 // of a repeated bit pattern of size ByteSize. 2217 if (!APInt(ValSizeInBytes * 8, Value).isSplat(ByteSize * 8)) 2218 return SDValue(); 2219 2220 // Properly sign extend the value. 2221 int MaskVal = SignExtend32(Value, ByteSize * 8); 2222 2223 // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros. 2224 if (MaskVal == 0) return SDValue(); 2225 2226 // Finally, if this value fits in a 5 bit sext field, return it 2227 if (SignExtend32<5>(MaskVal) == MaskVal) 2228 return DAG.getTargetConstant(MaskVal, SDLoc(N), MVT::i32); 2229 return SDValue(); 2230 } 2231 2232 /// isQVALIGNIShuffleMask - If this is a qvaligni shuffle mask, return the shift 2233 /// amount, otherwise return -1. 2234 int PPC::isQVALIGNIShuffleMask(SDNode *N) { 2235 EVT VT = N->getValueType(0); 2236 if (VT != MVT::v4f64 && VT != MVT::v4f32 && VT != MVT::v4i1) 2237 return -1; 2238 2239 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 2240 2241 // Find the first non-undef value in the shuffle mask. 2242 unsigned i; 2243 for (i = 0; i != 4 && SVOp->getMaskElt(i) < 0; ++i) 2244 /*search*/; 2245 2246 if (i == 4) return -1; // all undef. 2247 2248 // Otherwise, check to see if the rest of the elements are consecutively 2249 // numbered from this value. 2250 unsigned ShiftAmt = SVOp->getMaskElt(i); 2251 if (ShiftAmt < i) return -1; 2252 ShiftAmt -= i; 2253 2254 // Check the rest of the elements to see if they are consecutive. 2255 for (++i; i != 4; ++i) 2256 if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i)) 2257 return -1; 2258 2259 return ShiftAmt; 2260 } 2261 2262 //===----------------------------------------------------------------------===// 2263 // Addressing Mode Selection 2264 //===----------------------------------------------------------------------===// 2265 2266 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit 2267 /// or 64-bit immediate, and if the value can be accurately represented as a 2268 /// sign extension from a 16-bit value. If so, this returns true and the 2269 /// immediate. 2270 bool llvm::isIntS16Immediate(SDNode *N, int16_t &Imm) { 2271 if (!isa<ConstantSDNode>(N)) 2272 return false; 2273 2274 Imm = (int16_t)cast<ConstantSDNode>(N)->getZExtValue(); 2275 if (N->getValueType(0) == MVT::i32) 2276 return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue(); 2277 else 2278 return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue(); 2279 } 2280 bool llvm::isIntS16Immediate(SDValue Op, int16_t &Imm) { 2281 return isIntS16Immediate(Op.getNode(), Imm); 2282 } 2283 2284 2285 /// SelectAddressEVXRegReg - Given the specified address, check to see if it can 2286 /// be represented as an indexed [r+r] operation. 2287 bool PPCTargetLowering::SelectAddressEVXRegReg(SDValue N, SDValue &Base, 2288 SDValue &Index, 2289 SelectionDAG &DAG) const { 2290 for (SDNode::use_iterator UI = N->use_begin(), E = N->use_end(); 2291 UI != E; ++UI) { 2292 if (MemSDNode *Memop = dyn_cast<MemSDNode>(*UI)) { 2293 if (Memop->getMemoryVT() == MVT::f64) { 2294 Base = N.getOperand(0); 2295 Index = N.getOperand(1); 2296 return true; 2297 } 2298 } 2299 } 2300 return false; 2301 } 2302 2303 /// SelectAddressRegReg - Given the specified addressed, check to see if it 2304 /// can be represented as an indexed [r+r] operation. Returns false if it 2305 /// can be more efficiently represented as [r+imm]. If \p EncodingAlignment is 2306 /// non-zero and N can be represented by a base register plus a signed 16-bit 2307 /// displacement, make a more precise judgement by checking (displacement % \p 2308 /// EncodingAlignment). 2309 bool PPCTargetLowering::SelectAddressRegReg(SDValue N, SDValue &Base, 2310 SDValue &Index, SelectionDAG &DAG, 2311 unsigned EncodingAlignment) const { 2312 int16_t imm = 0; 2313 if (N.getOpcode() == ISD::ADD) { 2314 // Is there any SPE load/store (f64), which can't handle 16bit offset? 2315 // SPE load/store can only handle 8-bit offsets. 2316 if (hasSPE() && SelectAddressEVXRegReg(N, Base, Index, DAG)) 2317 return true; 2318 if (isIntS16Immediate(N.getOperand(1), imm) && 2319 (!EncodingAlignment || !(imm % EncodingAlignment))) 2320 return false; // r+i 2321 if (N.getOperand(1).getOpcode() == PPCISD::Lo) 2322 return false; // r+i 2323 2324 Base = N.getOperand(0); 2325 Index = N.getOperand(1); 2326 return true; 2327 } else if (N.getOpcode() == ISD::OR) { 2328 if (isIntS16Immediate(N.getOperand(1), imm) && 2329 (!EncodingAlignment || !(imm % EncodingAlignment))) 2330 return false; // r+i can fold it if we can. 2331 2332 // If this is an or of disjoint bitfields, we can codegen this as an add 2333 // (for better address arithmetic) if the LHS and RHS of the OR are provably 2334 // disjoint. 2335 KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0)); 2336 2337 if (LHSKnown.Zero.getBoolValue()) { 2338 KnownBits RHSKnown = DAG.computeKnownBits(N.getOperand(1)); 2339 // If all of the bits are known zero on the LHS or RHS, the add won't 2340 // carry. 2341 if (~(LHSKnown.Zero | RHSKnown.Zero) == 0) { 2342 Base = N.getOperand(0); 2343 Index = N.getOperand(1); 2344 return true; 2345 } 2346 } 2347 } 2348 2349 return false; 2350 } 2351 2352 // If we happen to be doing an i64 load or store into a stack slot that has 2353 // less than a 4-byte alignment, then the frame-index elimination may need to 2354 // use an indexed load or store instruction (because the offset may not be a 2355 // multiple of 4). The extra register needed to hold the offset comes from the 2356 // register scavenger, and it is possible that the scavenger will need to use 2357 // an emergency spill slot. As a result, we need to make sure that a spill slot 2358 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned 2359 // stack slot. 2360 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) { 2361 // FIXME: This does not handle the LWA case. 2362 if (VT != MVT::i64) 2363 return; 2364 2365 // NOTE: We'll exclude negative FIs here, which come from argument 2366 // lowering, because there are no known test cases triggering this problem 2367 // using packed structures (or similar). We can remove this exclusion if 2368 // we find such a test case. The reason why this is so test-case driven is 2369 // because this entire 'fixup' is only to prevent crashes (from the 2370 // register scavenger) on not-really-valid inputs. For example, if we have: 2371 // %a = alloca i1 2372 // %b = bitcast i1* %a to i64* 2373 // store i64* a, i64 b 2374 // then the store should really be marked as 'align 1', but is not. If it 2375 // were marked as 'align 1' then the indexed form would have been 2376 // instruction-selected initially, and the problem this 'fixup' is preventing 2377 // won't happen regardless. 2378 if (FrameIdx < 0) 2379 return; 2380 2381 MachineFunction &MF = DAG.getMachineFunction(); 2382 MachineFrameInfo &MFI = MF.getFrameInfo(); 2383 2384 unsigned Align = MFI.getObjectAlignment(FrameIdx); 2385 if (Align >= 4) 2386 return; 2387 2388 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 2389 FuncInfo->setHasNonRISpills(); 2390 } 2391 2392 /// Returns true if the address N can be represented by a base register plus 2393 /// a signed 16-bit displacement [r+imm], and if it is not better 2394 /// represented as reg+reg. If \p EncodingAlignment is non-zero, only accept 2395 /// displacements that are multiples of that value. 2396 bool PPCTargetLowering::SelectAddressRegImm(SDValue N, SDValue &Disp, 2397 SDValue &Base, 2398 SelectionDAG &DAG, 2399 unsigned EncodingAlignment) const { 2400 // FIXME dl should come from parent load or store, not from address 2401 SDLoc dl(N); 2402 // If this can be more profitably realized as r+r, fail. 2403 if (SelectAddressRegReg(N, Disp, Base, DAG, EncodingAlignment)) 2404 return false; 2405 2406 if (N.getOpcode() == ISD::ADD) { 2407 int16_t imm = 0; 2408 if (isIntS16Immediate(N.getOperand(1), imm) && 2409 (!EncodingAlignment || (imm % EncodingAlignment) == 0)) { 2410 Disp = DAG.getTargetConstant(imm, dl, N.getValueType()); 2411 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) { 2412 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2413 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 2414 } else { 2415 Base = N.getOperand(0); 2416 } 2417 return true; // [r+i] 2418 } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) { 2419 // Match LOAD (ADD (X, Lo(G))). 2420 assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue() 2421 && "Cannot handle constant offsets yet!"); 2422 Disp = N.getOperand(1).getOperand(0); // The global address. 2423 assert(Disp.getOpcode() == ISD::TargetGlobalAddress || 2424 Disp.getOpcode() == ISD::TargetGlobalTLSAddress || 2425 Disp.getOpcode() == ISD::TargetConstantPool || 2426 Disp.getOpcode() == ISD::TargetJumpTable); 2427 Base = N.getOperand(0); 2428 return true; // [&g+r] 2429 } 2430 } else if (N.getOpcode() == ISD::OR) { 2431 int16_t imm = 0; 2432 if (isIntS16Immediate(N.getOperand(1), imm) && 2433 (!EncodingAlignment || (imm % EncodingAlignment) == 0)) { 2434 // If this is an or of disjoint bitfields, we can codegen this as an add 2435 // (for better address arithmetic) if the LHS and RHS of the OR are 2436 // provably disjoint. 2437 KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0)); 2438 2439 if ((LHSKnown.Zero.getZExtValue()|~(uint64_t)imm) == ~0ULL) { 2440 // If all of the bits are known zero on the LHS or RHS, the add won't 2441 // carry. 2442 if (FrameIndexSDNode *FI = 2443 dyn_cast<FrameIndexSDNode>(N.getOperand(0))) { 2444 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2445 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 2446 } else { 2447 Base = N.getOperand(0); 2448 } 2449 Disp = DAG.getTargetConstant(imm, dl, N.getValueType()); 2450 return true; 2451 } 2452 } 2453 } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) { 2454 // Loading from a constant address. 2455 2456 // If this address fits entirely in a 16-bit sext immediate field, codegen 2457 // this as "d, 0" 2458 int16_t Imm; 2459 if (isIntS16Immediate(CN, Imm) && 2460 (!EncodingAlignment || (Imm % EncodingAlignment) == 0)) { 2461 Disp = DAG.getTargetConstant(Imm, dl, CN->getValueType(0)); 2462 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO, 2463 CN->getValueType(0)); 2464 return true; 2465 } 2466 2467 // Handle 32-bit sext immediates with LIS + addr mode. 2468 if ((CN->getValueType(0) == MVT::i32 || 2469 (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) && 2470 (!EncodingAlignment || (CN->getZExtValue() % EncodingAlignment) == 0)) { 2471 int Addr = (int)CN->getZExtValue(); 2472 2473 // Otherwise, break this down into an LIS + disp. 2474 Disp = DAG.getTargetConstant((short)Addr, dl, MVT::i32); 2475 2476 Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, dl, 2477 MVT::i32); 2478 unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8; 2479 Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0); 2480 return true; 2481 } 2482 } 2483 2484 Disp = DAG.getTargetConstant(0, dl, getPointerTy(DAG.getDataLayout())); 2485 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) { 2486 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2487 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 2488 } else 2489 Base = N; 2490 return true; // [r+0] 2491 } 2492 2493 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be 2494 /// represented as an indexed [r+r] operation. 2495 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base, 2496 SDValue &Index, 2497 SelectionDAG &DAG) const { 2498 // Check to see if we can easily represent this as an [r+r] address. This 2499 // will fail if it thinks that the address is more profitably represented as 2500 // reg+imm, e.g. where imm = 0. 2501 if (SelectAddressRegReg(N, Base, Index, DAG)) 2502 return true; 2503 2504 // If the address is the result of an add, we will utilize the fact that the 2505 // address calculation includes an implicit add. However, we can reduce 2506 // register pressure if we do not materialize a constant just for use as the 2507 // index register. We only get rid of the add if it is not an add of a 2508 // value and a 16-bit signed constant and both have a single use. 2509 int16_t imm = 0; 2510 if (N.getOpcode() == ISD::ADD && 2511 (!isIntS16Immediate(N.getOperand(1), imm) || 2512 !N.getOperand(1).hasOneUse() || !N.getOperand(0).hasOneUse())) { 2513 Base = N.getOperand(0); 2514 Index = N.getOperand(1); 2515 return true; 2516 } 2517 2518 // Otherwise, do it the hard way, using R0 as the base register. 2519 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO, 2520 N.getValueType()); 2521 Index = N; 2522 return true; 2523 } 2524 2525 /// Returns true if we should use a direct load into vector instruction 2526 /// (such as lxsd or lfd), instead of a load into gpr + direct move sequence. 2527 static bool usePartialVectorLoads(SDNode *N, const PPCSubtarget& ST) { 2528 2529 // If there are any other uses other than scalar to vector, then we should 2530 // keep it as a scalar load -> direct move pattern to prevent multiple 2531 // loads. 2532 LoadSDNode *LD = dyn_cast<LoadSDNode>(N); 2533 if (!LD) 2534 return false; 2535 2536 EVT MemVT = LD->getMemoryVT(); 2537 if (!MemVT.isSimple()) 2538 return false; 2539 switch(MemVT.getSimpleVT().SimpleTy) { 2540 case MVT::i64: 2541 break; 2542 case MVT::i32: 2543 if (!ST.hasP8Vector()) 2544 return false; 2545 break; 2546 case MVT::i16: 2547 case MVT::i8: 2548 if (!ST.hasP9Vector()) 2549 return false; 2550 break; 2551 default: 2552 return false; 2553 } 2554 2555 SDValue LoadedVal(N, 0); 2556 if (!LoadedVal.hasOneUse()) 2557 return false; 2558 2559 for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end(); 2560 UI != UE; ++UI) 2561 if (UI.getUse().get().getResNo() == 0 && 2562 UI->getOpcode() != ISD::SCALAR_TO_VECTOR) 2563 return false; 2564 2565 return true; 2566 } 2567 2568 /// getPreIndexedAddressParts - returns true by value, base pointer and 2569 /// offset pointer and addressing mode by reference if the node's address 2570 /// can be legally represented as pre-indexed load / store address. 2571 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base, 2572 SDValue &Offset, 2573 ISD::MemIndexedMode &AM, 2574 SelectionDAG &DAG) const { 2575 if (DisablePPCPreinc) return false; 2576 2577 bool isLoad = true; 2578 SDValue Ptr; 2579 EVT VT; 2580 unsigned Alignment; 2581 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 2582 Ptr = LD->getBasePtr(); 2583 VT = LD->getMemoryVT(); 2584 Alignment = LD->getAlignment(); 2585 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 2586 Ptr = ST->getBasePtr(); 2587 VT = ST->getMemoryVT(); 2588 Alignment = ST->getAlignment(); 2589 isLoad = false; 2590 } else 2591 return false; 2592 2593 // Do not generate pre-inc forms for specific loads that feed scalar_to_vector 2594 // instructions because we can fold these into a more efficient instruction 2595 // instead, (such as LXSD). 2596 if (isLoad && usePartialVectorLoads(N, Subtarget)) { 2597 return false; 2598 } 2599 2600 // PowerPC doesn't have preinc load/store instructions for vectors (except 2601 // for QPX, which does have preinc r+r forms). 2602 if (VT.isVector()) { 2603 if (!Subtarget.hasQPX() || (VT != MVT::v4f64 && VT != MVT::v4f32)) { 2604 return false; 2605 } else if (SelectAddressRegRegOnly(Ptr, Offset, Base, DAG)) { 2606 AM = ISD::PRE_INC; 2607 return true; 2608 } 2609 } 2610 2611 if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) { 2612 // Common code will reject creating a pre-inc form if the base pointer 2613 // is a frame index, or if N is a store and the base pointer is either 2614 // the same as or a predecessor of the value being stored. Check for 2615 // those situations here, and try with swapped Base/Offset instead. 2616 bool Swap = false; 2617 2618 if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base)) 2619 Swap = true; 2620 else if (!isLoad) { 2621 SDValue Val = cast<StoreSDNode>(N)->getValue(); 2622 if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode())) 2623 Swap = true; 2624 } 2625 2626 if (Swap) 2627 std::swap(Base, Offset); 2628 2629 AM = ISD::PRE_INC; 2630 return true; 2631 } 2632 2633 // LDU/STU can only handle immediates that are a multiple of 4. 2634 if (VT != MVT::i64) { 2635 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, 0)) 2636 return false; 2637 } else { 2638 // LDU/STU need an address with at least 4-byte alignment. 2639 if (Alignment < 4) 2640 return false; 2641 2642 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, 4)) 2643 return false; 2644 } 2645 2646 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 2647 // PPC64 doesn't have lwau, but it does have lwaux. Reject preinc load of 2648 // sext i32 to i64 when addr mode is r+i. 2649 if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 && 2650 LD->getExtensionType() == ISD::SEXTLOAD && 2651 isa<ConstantSDNode>(Offset)) 2652 return false; 2653 } 2654 2655 AM = ISD::PRE_INC; 2656 return true; 2657 } 2658 2659 //===----------------------------------------------------------------------===// 2660 // LowerOperation implementation 2661 //===----------------------------------------------------------------------===// 2662 2663 /// Return true if we should reference labels using a PICBase, set the HiOpFlags 2664 /// and LoOpFlags to the target MO flags. 2665 static void getLabelAccessInfo(bool IsPIC, const PPCSubtarget &Subtarget, 2666 unsigned &HiOpFlags, unsigned &LoOpFlags, 2667 const GlobalValue *GV = nullptr) { 2668 HiOpFlags = PPCII::MO_HA; 2669 LoOpFlags = PPCII::MO_LO; 2670 2671 // Don't use the pic base if not in PIC relocation model. 2672 if (IsPIC) { 2673 HiOpFlags |= PPCII::MO_PIC_FLAG; 2674 LoOpFlags |= PPCII::MO_PIC_FLAG; 2675 } 2676 } 2677 2678 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC, 2679 SelectionDAG &DAG) { 2680 SDLoc DL(HiPart); 2681 EVT PtrVT = HiPart.getValueType(); 2682 SDValue Zero = DAG.getConstant(0, DL, PtrVT); 2683 2684 SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero); 2685 SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero); 2686 2687 // With PIC, the first instruction is actually "GR+hi(&G)". 2688 if (isPIC) 2689 Hi = DAG.getNode(ISD::ADD, DL, PtrVT, 2690 DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi); 2691 2692 // Generate non-pic code that has direct accesses to the constant pool. 2693 // The address of the global is just (hi(&g)+lo(&g)). 2694 return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo); 2695 } 2696 2697 static void setUsesTOCBasePtr(MachineFunction &MF) { 2698 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 2699 FuncInfo->setUsesTOCBasePtr(); 2700 } 2701 2702 static void setUsesTOCBasePtr(SelectionDAG &DAG) { 2703 setUsesTOCBasePtr(DAG.getMachineFunction()); 2704 } 2705 2706 SDValue PPCTargetLowering::getTOCEntry(SelectionDAG &DAG, const SDLoc &dl, 2707 SDValue GA) const { 2708 const bool Is64Bit = Subtarget.isPPC64(); 2709 EVT VT = Is64Bit ? MVT::i64 : MVT::i32; 2710 SDValue Reg = Is64Bit ? DAG.getRegister(PPC::X2, VT) 2711 : Subtarget.isAIXABI() 2712 ? DAG.getRegister(PPC::R2, VT) 2713 : DAG.getNode(PPCISD::GlobalBaseReg, dl, VT); 2714 SDValue Ops[] = { GA, Reg }; 2715 return DAG.getMemIntrinsicNode( 2716 PPCISD::TOC_ENTRY, dl, DAG.getVTList(VT, MVT::Other), Ops, VT, 2717 MachinePointerInfo::getGOT(DAG.getMachineFunction()), 0, 2718 MachineMemOperand::MOLoad); 2719 } 2720 2721 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op, 2722 SelectionDAG &DAG) const { 2723 EVT PtrVT = Op.getValueType(); 2724 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op); 2725 const Constant *C = CP->getConstVal(); 2726 2727 // 64-bit SVR4 ABI and AIX ABI code are always position-independent. 2728 // The actual address of the GlobalValue is stored in the TOC. 2729 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) { 2730 setUsesTOCBasePtr(DAG); 2731 SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0); 2732 return getTOCEntry(DAG, SDLoc(CP), GA); 2733 } 2734 2735 unsigned MOHiFlag, MOLoFlag; 2736 bool IsPIC = isPositionIndependent(); 2737 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag); 2738 2739 if (IsPIC && Subtarget.isSVR4ABI()) { 2740 SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 2741 PPCII::MO_PIC_FLAG); 2742 return getTOCEntry(DAG, SDLoc(CP), GA); 2743 } 2744 2745 SDValue CPIHi = 2746 DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOHiFlag); 2747 SDValue CPILo = 2748 DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOLoFlag); 2749 return LowerLabelRef(CPIHi, CPILo, IsPIC, DAG); 2750 } 2751 2752 // For 64-bit PowerPC, prefer the more compact relative encodings. 2753 // This trades 32 bits per jump table entry for one or two instructions 2754 // on the jump site. 2755 unsigned PPCTargetLowering::getJumpTableEncoding() const { 2756 if (isJumpTableRelative()) 2757 return MachineJumpTableInfo::EK_LabelDifference32; 2758 2759 return TargetLowering::getJumpTableEncoding(); 2760 } 2761 2762 bool PPCTargetLowering::isJumpTableRelative() const { 2763 if (UseAbsoluteJumpTables) 2764 return false; 2765 if (Subtarget.isPPC64() || Subtarget.isAIXABI()) 2766 return true; 2767 return TargetLowering::isJumpTableRelative(); 2768 } 2769 2770 SDValue PPCTargetLowering::getPICJumpTableRelocBase(SDValue Table, 2771 SelectionDAG &DAG) const { 2772 if (!Subtarget.isPPC64() || Subtarget.isAIXABI()) 2773 return TargetLowering::getPICJumpTableRelocBase(Table, DAG); 2774 2775 switch (getTargetMachine().getCodeModel()) { 2776 case CodeModel::Small: 2777 case CodeModel::Medium: 2778 return TargetLowering::getPICJumpTableRelocBase(Table, DAG); 2779 default: 2780 return DAG.getNode(PPCISD::GlobalBaseReg, SDLoc(), 2781 getPointerTy(DAG.getDataLayout())); 2782 } 2783 } 2784 2785 const MCExpr * 2786 PPCTargetLowering::getPICJumpTableRelocBaseExpr(const MachineFunction *MF, 2787 unsigned JTI, 2788 MCContext &Ctx) const { 2789 if (!Subtarget.isPPC64() || Subtarget.isAIXABI()) 2790 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx); 2791 2792 switch (getTargetMachine().getCodeModel()) { 2793 case CodeModel::Small: 2794 case CodeModel::Medium: 2795 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx); 2796 default: 2797 return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx); 2798 } 2799 } 2800 2801 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const { 2802 EVT PtrVT = Op.getValueType(); 2803 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op); 2804 2805 // 64-bit SVR4 ABI and AIX ABI code are always position-independent. 2806 // The actual address of the GlobalValue is stored in the TOC. 2807 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) { 2808 setUsesTOCBasePtr(DAG); 2809 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT); 2810 return getTOCEntry(DAG, SDLoc(JT), GA); 2811 } 2812 2813 unsigned MOHiFlag, MOLoFlag; 2814 bool IsPIC = isPositionIndependent(); 2815 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag); 2816 2817 if (IsPIC && Subtarget.isSVR4ABI()) { 2818 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, 2819 PPCII::MO_PIC_FLAG); 2820 return getTOCEntry(DAG, SDLoc(GA), GA); 2821 } 2822 2823 SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag); 2824 SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag); 2825 return LowerLabelRef(JTIHi, JTILo, IsPIC, DAG); 2826 } 2827 2828 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op, 2829 SelectionDAG &DAG) const { 2830 EVT PtrVT = Op.getValueType(); 2831 BlockAddressSDNode *BASDN = cast<BlockAddressSDNode>(Op); 2832 const BlockAddress *BA = BASDN->getBlockAddress(); 2833 2834 // 64-bit SVR4 ABI and AIX ABI code are always position-independent. 2835 // The actual BlockAddress is stored in the TOC. 2836 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) { 2837 setUsesTOCBasePtr(DAG); 2838 SDValue GA = DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset()); 2839 return getTOCEntry(DAG, SDLoc(BASDN), GA); 2840 } 2841 2842 // 32-bit position-independent ELF stores the BlockAddress in the .got. 2843 if (Subtarget.is32BitELFABI() && isPositionIndependent()) 2844 return getTOCEntry( 2845 DAG, SDLoc(BASDN), 2846 DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset())); 2847 2848 unsigned MOHiFlag, MOLoFlag; 2849 bool IsPIC = isPositionIndependent(); 2850 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag); 2851 SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag); 2852 SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag); 2853 return LowerLabelRef(TgtBAHi, TgtBALo, IsPIC, DAG); 2854 } 2855 2856 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op, 2857 SelectionDAG &DAG) const { 2858 // FIXME: TLS addresses currently use medium model code sequences, 2859 // which is the most useful form. Eventually support for small and 2860 // large models could be added if users need it, at the cost of 2861 // additional complexity. 2862 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op); 2863 if (DAG.getTarget().useEmulatedTLS()) 2864 return LowerToTLSEmulatedModel(GA, DAG); 2865 2866 SDLoc dl(GA); 2867 const GlobalValue *GV = GA->getGlobal(); 2868 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2869 bool is64bit = Subtarget.isPPC64(); 2870 const Module *M = DAG.getMachineFunction().getFunction().getParent(); 2871 PICLevel::Level picLevel = M->getPICLevel(); 2872 2873 const TargetMachine &TM = getTargetMachine(); 2874 TLSModel::Model Model = TM.getTLSModel(GV); 2875 2876 if (Model == TLSModel::LocalExec) { 2877 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 2878 PPCII::MO_TPREL_HA); 2879 SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 2880 PPCII::MO_TPREL_LO); 2881 SDValue TLSReg = is64bit ? DAG.getRegister(PPC::X13, MVT::i64) 2882 : DAG.getRegister(PPC::R2, MVT::i32); 2883 2884 SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg); 2885 return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi); 2886 } 2887 2888 if (Model == TLSModel::InitialExec) { 2889 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0); 2890 SDValue TGATLS = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 2891 PPCII::MO_TLS); 2892 SDValue GOTPtr; 2893 if (is64bit) { 2894 setUsesTOCBasePtr(DAG); 2895 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64); 2896 GOTPtr = DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl, 2897 PtrVT, GOTReg, TGA); 2898 } else { 2899 if (!TM.isPositionIndependent()) 2900 GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT); 2901 else if (picLevel == PICLevel::SmallPIC) 2902 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT); 2903 else 2904 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT); 2905 } 2906 SDValue TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl, 2907 PtrVT, TGA, GOTPtr); 2908 return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS); 2909 } 2910 2911 if (Model == TLSModel::GeneralDynamic) { 2912 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0); 2913 SDValue GOTPtr; 2914 if (is64bit) { 2915 setUsesTOCBasePtr(DAG); 2916 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64); 2917 GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT, 2918 GOTReg, TGA); 2919 } else { 2920 if (picLevel == PICLevel::SmallPIC) 2921 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT); 2922 else 2923 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT); 2924 } 2925 return DAG.getNode(PPCISD::ADDI_TLSGD_L_ADDR, dl, PtrVT, 2926 GOTPtr, TGA, TGA); 2927 } 2928 2929 if (Model == TLSModel::LocalDynamic) { 2930 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0); 2931 SDValue GOTPtr; 2932 if (is64bit) { 2933 setUsesTOCBasePtr(DAG); 2934 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64); 2935 GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT, 2936 GOTReg, TGA); 2937 } else { 2938 if (picLevel == PICLevel::SmallPIC) 2939 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT); 2940 else 2941 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT); 2942 } 2943 SDValue TLSAddr = DAG.getNode(PPCISD::ADDI_TLSLD_L_ADDR, dl, 2944 PtrVT, GOTPtr, TGA, TGA); 2945 SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl, 2946 PtrVT, TLSAddr, TGA); 2947 return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA); 2948 } 2949 2950 llvm_unreachable("Unknown TLS model!"); 2951 } 2952 2953 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op, 2954 SelectionDAG &DAG) const { 2955 EVT PtrVT = Op.getValueType(); 2956 GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op); 2957 SDLoc DL(GSDN); 2958 const GlobalValue *GV = GSDN->getGlobal(); 2959 2960 // 64-bit SVR4 ABI & AIX ABI code is always position-independent. 2961 // The actual address of the GlobalValue is stored in the TOC. 2962 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) { 2963 setUsesTOCBasePtr(DAG); 2964 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset()); 2965 return getTOCEntry(DAG, DL, GA); 2966 } 2967 2968 unsigned MOHiFlag, MOLoFlag; 2969 bool IsPIC = isPositionIndependent(); 2970 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag, GV); 2971 2972 if (IsPIC && Subtarget.isSVR4ABI()) { 2973 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 2974 GSDN->getOffset(), 2975 PPCII::MO_PIC_FLAG); 2976 return getTOCEntry(DAG, DL, GA); 2977 } 2978 2979 SDValue GAHi = 2980 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag); 2981 SDValue GALo = 2982 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag); 2983 2984 return LowerLabelRef(GAHi, GALo, IsPIC, DAG); 2985 } 2986 2987 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const { 2988 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get(); 2989 SDLoc dl(Op); 2990 2991 if (Op.getValueType() == MVT::v2i64) { 2992 // When the operands themselves are v2i64 values, we need to do something 2993 // special because VSX has no underlying comparison operations for these. 2994 if (Op.getOperand(0).getValueType() == MVT::v2i64) { 2995 // Equality can be handled by casting to the legal type for Altivec 2996 // comparisons, everything else needs to be expanded. 2997 if (CC == ISD::SETEQ || CC == ISD::SETNE) { 2998 return DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, 2999 DAG.getSetCC(dl, MVT::v4i32, 3000 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0)), 3001 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(1)), 3002 CC)); 3003 } 3004 3005 return SDValue(); 3006 } 3007 3008 // We handle most of these in the usual way. 3009 return Op; 3010 } 3011 3012 // If we're comparing for equality to zero, expose the fact that this is 3013 // implemented as a ctlz/srl pair on ppc, so that the dag combiner can 3014 // fold the new nodes. 3015 if (SDValue V = lowerCmpEqZeroToCtlzSrl(Op, DAG)) 3016 return V; 3017 3018 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 3019 // Leave comparisons against 0 and -1 alone for now, since they're usually 3020 // optimized. FIXME: revisit this when we can custom lower all setcc 3021 // optimizations. 3022 if (C->isAllOnesValue() || C->isNullValue()) 3023 return SDValue(); 3024 } 3025 3026 // If we have an integer seteq/setne, turn it into a compare against zero 3027 // by xor'ing the rhs with the lhs, which is faster than setting a 3028 // condition register, reading it back out, and masking the correct bit. The 3029 // normal approach here uses sub to do this instead of xor. Using xor exposes 3030 // the result to other bit-twiddling opportunities. 3031 EVT LHSVT = Op.getOperand(0).getValueType(); 3032 if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) { 3033 EVT VT = Op.getValueType(); 3034 SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0), 3035 Op.getOperand(1)); 3036 return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, dl, LHSVT), CC); 3037 } 3038 return SDValue(); 3039 } 3040 3041 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const { 3042 SDNode *Node = Op.getNode(); 3043 EVT VT = Node->getValueType(0); 3044 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3045 SDValue InChain = Node->getOperand(0); 3046 SDValue VAListPtr = Node->getOperand(1); 3047 const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue(); 3048 SDLoc dl(Node); 3049 3050 assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only"); 3051 3052 // gpr_index 3053 SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain, 3054 VAListPtr, MachinePointerInfo(SV), MVT::i8); 3055 InChain = GprIndex.getValue(1); 3056 3057 if (VT == MVT::i64) { 3058 // Check if GprIndex is even 3059 SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex, 3060 DAG.getConstant(1, dl, MVT::i32)); 3061 SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd, 3062 DAG.getConstant(0, dl, MVT::i32), ISD::SETNE); 3063 SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex, 3064 DAG.getConstant(1, dl, MVT::i32)); 3065 // Align GprIndex to be even if it isn't 3066 GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne, 3067 GprIndex); 3068 } 3069 3070 // fpr index is 1 byte after gpr 3071 SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, 3072 DAG.getConstant(1, dl, MVT::i32)); 3073 3074 // fpr 3075 SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain, 3076 FprPtr, MachinePointerInfo(SV), MVT::i8); 3077 InChain = FprIndex.getValue(1); 3078 3079 SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, 3080 DAG.getConstant(8, dl, MVT::i32)); 3081 3082 SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, 3083 DAG.getConstant(4, dl, MVT::i32)); 3084 3085 // areas 3086 SDValue OverflowArea = 3087 DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr, MachinePointerInfo()); 3088 InChain = OverflowArea.getValue(1); 3089 3090 SDValue RegSaveArea = 3091 DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr, MachinePointerInfo()); 3092 InChain = RegSaveArea.getValue(1); 3093 3094 // select overflow_area if index > 8 3095 SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex, 3096 DAG.getConstant(8, dl, MVT::i32), ISD::SETLT); 3097 3098 // adjustment constant gpr_index * 4/8 3099 SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32, 3100 VT.isInteger() ? GprIndex : FprIndex, 3101 DAG.getConstant(VT.isInteger() ? 4 : 8, dl, 3102 MVT::i32)); 3103 3104 // OurReg = RegSaveArea + RegConstant 3105 SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea, 3106 RegConstant); 3107 3108 // Floating types are 32 bytes into RegSaveArea 3109 if (VT.isFloatingPoint()) 3110 OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg, 3111 DAG.getConstant(32, dl, MVT::i32)); 3112 3113 // increase {f,g}pr_index by 1 (or 2 if VT is i64) 3114 SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32, 3115 VT.isInteger() ? GprIndex : FprIndex, 3116 DAG.getConstant(VT == MVT::i64 ? 2 : 1, dl, 3117 MVT::i32)); 3118 3119 InChain = DAG.getTruncStore(InChain, dl, IndexPlus1, 3120 VT.isInteger() ? VAListPtr : FprPtr, 3121 MachinePointerInfo(SV), MVT::i8); 3122 3123 // determine if we should load from reg_save_area or overflow_area 3124 SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea); 3125 3126 // increase overflow_area by 4/8 if gpr/fpr > 8 3127 SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea, 3128 DAG.getConstant(VT.isInteger() ? 4 : 8, 3129 dl, MVT::i32)); 3130 3131 OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea, 3132 OverflowAreaPlusN); 3133 3134 InChain = DAG.getTruncStore(InChain, dl, OverflowArea, OverflowAreaPtr, 3135 MachinePointerInfo(), MVT::i32); 3136 3137 return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo()); 3138 } 3139 3140 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const { 3141 assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only"); 3142 3143 // We have to copy the entire va_list struct: 3144 // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte 3145 return DAG.getMemcpy(Op.getOperand(0), Op, 3146 Op.getOperand(1), Op.getOperand(2), 3147 DAG.getConstant(12, SDLoc(Op), MVT::i32), 8, false, true, 3148 false, MachinePointerInfo(), MachinePointerInfo()); 3149 } 3150 3151 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op, 3152 SelectionDAG &DAG) const { 3153 if (Subtarget.isAIXABI()) 3154 report_fatal_error("ADJUST_TRAMPOLINE operation is not supported on AIX."); 3155 3156 return Op.getOperand(0); 3157 } 3158 3159 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op, 3160 SelectionDAG &DAG) const { 3161 if (Subtarget.isAIXABI()) 3162 report_fatal_error("INIT_TRAMPOLINE operation is not supported on AIX."); 3163 3164 SDValue Chain = Op.getOperand(0); 3165 SDValue Trmp = Op.getOperand(1); // trampoline 3166 SDValue FPtr = Op.getOperand(2); // nested function 3167 SDValue Nest = Op.getOperand(3); // 'nest' parameter value 3168 SDLoc dl(Op); 3169 3170 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3171 bool isPPC64 = (PtrVT == MVT::i64); 3172 Type *IntPtrTy = DAG.getDataLayout().getIntPtrType(*DAG.getContext()); 3173 3174 TargetLowering::ArgListTy Args; 3175 TargetLowering::ArgListEntry Entry; 3176 3177 Entry.Ty = IntPtrTy; 3178 Entry.Node = Trmp; Args.push_back(Entry); 3179 3180 // TrampSize == (isPPC64 ? 48 : 40); 3181 Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40, dl, 3182 isPPC64 ? MVT::i64 : MVT::i32); 3183 Args.push_back(Entry); 3184 3185 Entry.Node = FPtr; Args.push_back(Entry); 3186 Entry.Node = Nest; Args.push_back(Entry); 3187 3188 // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg) 3189 TargetLowering::CallLoweringInfo CLI(DAG); 3190 CLI.setDebugLoc(dl).setChain(Chain).setLibCallee( 3191 CallingConv::C, Type::getVoidTy(*DAG.getContext()), 3192 DAG.getExternalSymbol("__trampoline_setup", PtrVT), std::move(Args)); 3193 3194 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 3195 return CallResult.second; 3196 } 3197 3198 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const { 3199 MachineFunction &MF = DAG.getMachineFunction(); 3200 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 3201 EVT PtrVT = getPointerTy(MF.getDataLayout()); 3202 3203 SDLoc dl(Op); 3204 3205 if (Subtarget.isPPC64()) { 3206 // vastart just stores the address of the VarArgsFrameIndex slot into the 3207 // memory location argument. 3208 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 3209 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 3210 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1), 3211 MachinePointerInfo(SV)); 3212 } 3213 3214 // For the 32-bit SVR4 ABI we follow the layout of the va_list struct. 3215 // We suppose the given va_list is already allocated. 3216 // 3217 // typedef struct { 3218 // char gpr; /* index into the array of 8 GPRs 3219 // * stored in the register save area 3220 // * gpr=0 corresponds to r3, 3221 // * gpr=1 to r4, etc. 3222 // */ 3223 // char fpr; /* index into the array of 8 FPRs 3224 // * stored in the register save area 3225 // * fpr=0 corresponds to f1, 3226 // * fpr=1 to f2, etc. 3227 // */ 3228 // char *overflow_arg_area; 3229 // /* location on stack that holds 3230 // * the next overflow argument 3231 // */ 3232 // char *reg_save_area; 3233 // /* where r3:r10 and f1:f8 (if saved) 3234 // * are stored 3235 // */ 3236 // } va_list[1]; 3237 3238 SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), dl, MVT::i32); 3239 SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), dl, MVT::i32); 3240 SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(), 3241 PtrVT); 3242 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), 3243 PtrVT); 3244 3245 uint64_t FrameOffset = PtrVT.getSizeInBits()/8; 3246 SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, dl, PtrVT); 3247 3248 uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1; 3249 SDValue ConstStackOffset = DAG.getConstant(StackOffset, dl, PtrVT); 3250 3251 uint64_t FPROffset = 1; 3252 SDValue ConstFPROffset = DAG.getConstant(FPROffset, dl, PtrVT); 3253 3254 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 3255 3256 // Store first byte : number of int regs 3257 SDValue firstStore = 3258 DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR, Op.getOperand(1), 3259 MachinePointerInfo(SV), MVT::i8); 3260 uint64_t nextOffset = FPROffset; 3261 SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1), 3262 ConstFPROffset); 3263 3264 // Store second byte : number of float regs 3265 SDValue secondStore = 3266 DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr, 3267 MachinePointerInfo(SV, nextOffset), MVT::i8); 3268 nextOffset += StackOffset; 3269 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset); 3270 3271 // Store second word : arguments given on stack 3272 SDValue thirdStore = DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr, 3273 MachinePointerInfo(SV, nextOffset)); 3274 nextOffset += FrameOffset; 3275 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset); 3276 3277 // Store third word : arguments given in registers 3278 return DAG.getStore(thirdStore, dl, FR, nextPtr, 3279 MachinePointerInfo(SV, nextOffset)); 3280 } 3281 3282 /// FPR - The set of FP registers that should be allocated for arguments 3283 /// on Darwin and AIX. 3284 static const MCPhysReg FPR[] = {PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, 3285 PPC::F6, PPC::F7, PPC::F8, PPC::F9, PPC::F10, 3286 PPC::F11, PPC::F12, PPC::F13}; 3287 3288 /// QFPR - The set of QPX registers that should be allocated for arguments. 3289 static const MCPhysReg QFPR[] = { 3290 PPC::QF1, PPC::QF2, PPC::QF3, PPC::QF4, PPC::QF5, PPC::QF6, PPC::QF7, 3291 PPC::QF8, PPC::QF9, PPC::QF10, PPC::QF11, PPC::QF12, PPC::QF13}; 3292 3293 /// CalculateStackSlotSize - Calculates the size reserved for this argument on 3294 /// the stack. 3295 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags, 3296 unsigned PtrByteSize) { 3297 unsigned ArgSize = ArgVT.getStoreSize(); 3298 if (Flags.isByVal()) 3299 ArgSize = Flags.getByValSize(); 3300 3301 // Round up to multiples of the pointer size, except for array members, 3302 // which are always packed. 3303 if (!Flags.isInConsecutiveRegs()) 3304 ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3305 3306 return ArgSize; 3307 } 3308 3309 /// CalculateStackSlotAlignment - Calculates the alignment of this argument 3310 /// on the stack. 3311 static unsigned CalculateStackSlotAlignment(EVT ArgVT, EVT OrigVT, 3312 ISD::ArgFlagsTy Flags, 3313 unsigned PtrByteSize) { 3314 unsigned Align = PtrByteSize; 3315 3316 // Altivec parameters are padded to a 16 byte boundary. 3317 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 || 3318 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 || 3319 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 || 3320 ArgVT == MVT::v1i128 || ArgVT == MVT::f128) 3321 Align = 16; 3322 // QPX vector types stored in double-precision are padded to a 32 byte 3323 // boundary. 3324 else if (ArgVT == MVT::v4f64 || ArgVT == MVT::v4i1) 3325 Align = 32; 3326 3327 // ByVal parameters are aligned as requested. 3328 if (Flags.isByVal()) { 3329 unsigned BVAlign = Flags.getByValAlign(); 3330 if (BVAlign > PtrByteSize) { 3331 if (BVAlign % PtrByteSize != 0) 3332 llvm_unreachable( 3333 "ByVal alignment is not a multiple of the pointer size"); 3334 3335 Align = BVAlign; 3336 } 3337 } 3338 3339 // Array members are always packed to their original alignment. 3340 if (Flags.isInConsecutiveRegs()) { 3341 // If the array member was split into multiple registers, the first 3342 // needs to be aligned to the size of the full type. (Except for 3343 // ppcf128, which is only aligned as its f64 components.) 3344 if (Flags.isSplit() && OrigVT != MVT::ppcf128) 3345 Align = OrigVT.getStoreSize(); 3346 else 3347 Align = ArgVT.getStoreSize(); 3348 } 3349 3350 return Align; 3351 } 3352 3353 /// CalculateStackSlotUsed - Return whether this argument will use its 3354 /// stack slot (instead of being passed in registers). ArgOffset, 3355 /// AvailableFPRs, and AvailableVRs must hold the current argument 3356 /// position, and will be updated to account for this argument. 3357 static bool CalculateStackSlotUsed(EVT ArgVT, EVT OrigVT, 3358 ISD::ArgFlagsTy Flags, 3359 unsigned PtrByteSize, 3360 unsigned LinkageSize, 3361 unsigned ParamAreaSize, 3362 unsigned &ArgOffset, 3363 unsigned &AvailableFPRs, 3364 unsigned &AvailableVRs, bool HasQPX) { 3365 bool UseMemory = false; 3366 3367 // Respect alignment of argument on the stack. 3368 unsigned Align = 3369 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize); 3370 ArgOffset = ((ArgOffset + Align - 1) / Align) * Align; 3371 // If there's no space left in the argument save area, we must 3372 // use memory (this check also catches zero-sized arguments). 3373 if (ArgOffset >= LinkageSize + ParamAreaSize) 3374 UseMemory = true; 3375 3376 // Allocate argument on the stack. 3377 ArgOffset += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize); 3378 if (Flags.isInConsecutiveRegsLast()) 3379 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3380 // If we overran the argument save area, we must use memory 3381 // (this check catches arguments passed partially in memory) 3382 if (ArgOffset > LinkageSize + ParamAreaSize) 3383 UseMemory = true; 3384 3385 // However, if the argument is actually passed in an FPR or a VR, 3386 // we don't use memory after all. 3387 if (!Flags.isByVal()) { 3388 if (ArgVT == MVT::f32 || ArgVT == MVT::f64 || 3389 // QPX registers overlap with the scalar FP registers. 3390 (HasQPX && (ArgVT == MVT::v4f32 || 3391 ArgVT == MVT::v4f64 || 3392 ArgVT == MVT::v4i1))) 3393 if (AvailableFPRs > 0) { 3394 --AvailableFPRs; 3395 return false; 3396 } 3397 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 || 3398 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 || 3399 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 || 3400 ArgVT == MVT::v1i128 || ArgVT == MVT::f128) 3401 if (AvailableVRs > 0) { 3402 --AvailableVRs; 3403 return false; 3404 } 3405 } 3406 3407 return UseMemory; 3408 } 3409 3410 /// EnsureStackAlignment - Round stack frame size up from NumBytes to 3411 /// ensure minimum alignment required for target. 3412 static unsigned EnsureStackAlignment(const PPCFrameLowering *Lowering, 3413 unsigned NumBytes) { 3414 unsigned TargetAlign = Lowering->getStackAlignment(); 3415 unsigned AlignMask = TargetAlign - 1; 3416 NumBytes = (NumBytes + AlignMask) & ~AlignMask; 3417 return NumBytes; 3418 } 3419 3420 SDValue PPCTargetLowering::LowerFormalArguments( 3421 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3422 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3423 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3424 if (Subtarget.isAIXABI()) 3425 return LowerFormalArguments_AIX(Chain, CallConv, isVarArg, Ins, dl, DAG, 3426 InVals); 3427 if (Subtarget.is64BitELFABI()) 3428 return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins, dl, DAG, 3429 InVals); 3430 if (Subtarget.is32BitELFABI()) 3431 return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins, dl, DAG, 3432 InVals); 3433 3434 return LowerFormalArguments_Darwin(Chain, CallConv, isVarArg, Ins, dl, DAG, 3435 InVals); 3436 } 3437 3438 SDValue PPCTargetLowering::LowerFormalArguments_32SVR4( 3439 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3440 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3441 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3442 3443 // 32-bit SVR4 ABI Stack Frame Layout: 3444 // +-----------------------------------+ 3445 // +--> | Back chain | 3446 // | +-----------------------------------+ 3447 // | | Floating-point register save area | 3448 // | +-----------------------------------+ 3449 // | | General register save area | 3450 // | +-----------------------------------+ 3451 // | | CR save word | 3452 // | +-----------------------------------+ 3453 // | | VRSAVE save word | 3454 // | +-----------------------------------+ 3455 // | | Alignment padding | 3456 // | +-----------------------------------+ 3457 // | | Vector register save area | 3458 // | +-----------------------------------+ 3459 // | | Local variable space | 3460 // | +-----------------------------------+ 3461 // | | Parameter list area | 3462 // | +-----------------------------------+ 3463 // | | LR save word | 3464 // | +-----------------------------------+ 3465 // SP--> +--- | Back chain | 3466 // +-----------------------------------+ 3467 // 3468 // Specifications: 3469 // System V Application Binary Interface PowerPC Processor Supplement 3470 // AltiVec Technology Programming Interface Manual 3471 3472 MachineFunction &MF = DAG.getMachineFunction(); 3473 MachineFrameInfo &MFI = MF.getFrameInfo(); 3474 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 3475 3476 EVT PtrVT = getPointerTy(MF.getDataLayout()); 3477 // Potential tail calls could cause overwriting of argument stack slots. 3478 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt && 3479 (CallConv == CallingConv::Fast)); 3480 unsigned PtrByteSize = 4; 3481 3482 // Assign locations to all of the incoming arguments. 3483 SmallVector<CCValAssign, 16> ArgLocs; 3484 PPCCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 3485 *DAG.getContext()); 3486 3487 // Reserve space for the linkage area on the stack. 3488 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 3489 CCInfo.AllocateStack(LinkageSize, PtrByteSize); 3490 if (useSoftFloat()) 3491 CCInfo.PreAnalyzeFormalArguments(Ins); 3492 3493 CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4); 3494 CCInfo.clearWasPPCF128(); 3495 3496 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 3497 CCValAssign &VA = ArgLocs[i]; 3498 3499 // Arguments stored in registers. 3500 if (VA.isRegLoc()) { 3501 const TargetRegisterClass *RC; 3502 EVT ValVT = VA.getValVT(); 3503 3504 switch (ValVT.getSimpleVT().SimpleTy) { 3505 default: 3506 llvm_unreachable("ValVT not supported by formal arguments Lowering"); 3507 case MVT::i1: 3508 case MVT::i32: 3509 RC = &PPC::GPRCRegClass; 3510 break; 3511 case MVT::f32: 3512 if (Subtarget.hasP8Vector()) 3513 RC = &PPC::VSSRCRegClass; 3514 else if (Subtarget.hasSPE()) 3515 RC = &PPC::GPRCRegClass; 3516 else 3517 RC = &PPC::F4RCRegClass; 3518 break; 3519 case MVT::f64: 3520 if (Subtarget.hasVSX()) 3521 RC = &PPC::VSFRCRegClass; 3522 else if (Subtarget.hasSPE()) 3523 // SPE passes doubles in GPR pairs. 3524 RC = &PPC::GPRCRegClass; 3525 else 3526 RC = &PPC::F8RCRegClass; 3527 break; 3528 case MVT::v16i8: 3529 case MVT::v8i16: 3530 case MVT::v4i32: 3531 RC = &PPC::VRRCRegClass; 3532 break; 3533 case MVT::v4f32: 3534 RC = Subtarget.hasQPX() ? &PPC::QSRCRegClass : &PPC::VRRCRegClass; 3535 break; 3536 case MVT::v2f64: 3537 case MVT::v2i64: 3538 RC = &PPC::VRRCRegClass; 3539 break; 3540 case MVT::v4f64: 3541 RC = &PPC::QFRCRegClass; 3542 break; 3543 case MVT::v4i1: 3544 RC = &PPC::QBRCRegClass; 3545 break; 3546 } 3547 3548 SDValue ArgValue; 3549 // Transform the arguments stored in physical registers into 3550 // virtual ones. 3551 if (VA.getLocVT() == MVT::f64 && Subtarget.hasSPE()) { 3552 assert(i + 1 < e && "No second half of double precision argument"); 3553 unsigned RegLo = MF.addLiveIn(VA.getLocReg(), RC); 3554 unsigned RegHi = MF.addLiveIn(ArgLocs[++i].getLocReg(), RC); 3555 SDValue ArgValueLo = DAG.getCopyFromReg(Chain, dl, RegLo, MVT::i32); 3556 SDValue ArgValueHi = DAG.getCopyFromReg(Chain, dl, RegHi, MVT::i32); 3557 if (!Subtarget.isLittleEndian()) 3558 std::swap (ArgValueLo, ArgValueHi); 3559 ArgValue = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, ArgValueLo, 3560 ArgValueHi); 3561 } else { 3562 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC); 3563 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, 3564 ValVT == MVT::i1 ? MVT::i32 : ValVT); 3565 if (ValVT == MVT::i1) 3566 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue); 3567 } 3568 3569 InVals.push_back(ArgValue); 3570 } else { 3571 // Argument stored in memory. 3572 assert(VA.isMemLoc()); 3573 3574 // Get the extended size of the argument type in stack 3575 unsigned ArgSize = VA.getLocVT().getStoreSize(); 3576 // Get the actual size of the argument type 3577 unsigned ObjSize = VA.getValVT().getStoreSize(); 3578 unsigned ArgOffset = VA.getLocMemOffset(); 3579 // Stack objects in PPC32 are right justified. 3580 ArgOffset += ArgSize - ObjSize; 3581 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, isImmutable); 3582 3583 // Create load nodes to retrieve arguments from the stack. 3584 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3585 InVals.push_back( 3586 DAG.getLoad(VA.getValVT(), dl, Chain, FIN, MachinePointerInfo())); 3587 } 3588 } 3589 3590 // Assign locations to all of the incoming aggregate by value arguments. 3591 // Aggregates passed by value are stored in the local variable space of the 3592 // caller's stack frame, right above the parameter list area. 3593 SmallVector<CCValAssign, 16> ByValArgLocs; 3594 CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(), 3595 ByValArgLocs, *DAG.getContext()); 3596 3597 // Reserve stack space for the allocations in CCInfo. 3598 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize); 3599 3600 CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal); 3601 3602 // Area that is at least reserved in the caller of this function. 3603 unsigned MinReservedArea = CCByValInfo.getNextStackOffset(); 3604 MinReservedArea = std::max(MinReservedArea, LinkageSize); 3605 3606 // Set the size that is at least reserved in caller of this function. Tail 3607 // call optimized function's reserved stack space needs to be aligned so that 3608 // taking the difference between two stack areas will result in an aligned 3609 // stack. 3610 MinReservedArea = 3611 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea); 3612 FuncInfo->setMinReservedArea(MinReservedArea); 3613 3614 SmallVector<SDValue, 8> MemOps; 3615 3616 // If the function takes variable number of arguments, make a frame index for 3617 // the start of the first vararg value... for expansion of llvm.va_start. 3618 if (isVarArg) { 3619 static const MCPhysReg GPArgRegs[] = { 3620 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 3621 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 3622 }; 3623 const unsigned NumGPArgRegs = array_lengthof(GPArgRegs); 3624 3625 static const MCPhysReg FPArgRegs[] = { 3626 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7, 3627 PPC::F8 3628 }; 3629 unsigned NumFPArgRegs = array_lengthof(FPArgRegs); 3630 3631 if (useSoftFloat() || hasSPE()) 3632 NumFPArgRegs = 0; 3633 3634 FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs)); 3635 FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs)); 3636 3637 // Make room for NumGPArgRegs and NumFPArgRegs. 3638 int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 + 3639 NumFPArgRegs * MVT(MVT::f64).getSizeInBits()/8; 3640 3641 FuncInfo->setVarArgsStackOffset( 3642 MFI.CreateFixedObject(PtrVT.getSizeInBits()/8, 3643 CCInfo.getNextStackOffset(), true)); 3644 3645 FuncInfo->setVarArgsFrameIndex(MFI.CreateStackObject(Depth, 8, false)); 3646 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 3647 3648 // The fixed integer arguments of a variadic function are stored to the 3649 // VarArgsFrameIndex on the stack so that they may be loaded by 3650 // dereferencing the result of va_next. 3651 for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) { 3652 // Get an existing live-in vreg, or add a new one. 3653 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]); 3654 if (!VReg) 3655 VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass); 3656 3657 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 3658 SDValue Store = 3659 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 3660 MemOps.push_back(Store); 3661 // Increment the address by four for the next argument to store 3662 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT); 3663 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 3664 } 3665 3666 // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6 3667 // is set. 3668 // The double arguments are stored to the VarArgsFrameIndex 3669 // on the stack. 3670 for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) { 3671 // Get an existing live-in vreg, or add a new one. 3672 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]); 3673 if (!VReg) 3674 VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass); 3675 3676 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64); 3677 SDValue Store = 3678 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 3679 MemOps.push_back(Store); 3680 // Increment the address by eight for the next argument to store 3681 SDValue PtrOff = DAG.getConstant(MVT(MVT::f64).getSizeInBits()/8, dl, 3682 PtrVT); 3683 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 3684 } 3685 } 3686 3687 if (!MemOps.empty()) 3688 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 3689 3690 return Chain; 3691 } 3692 3693 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote 3694 // value to MVT::i64 and then truncate to the correct register size. 3695 SDValue PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags, 3696 EVT ObjectVT, SelectionDAG &DAG, 3697 SDValue ArgVal, 3698 const SDLoc &dl) const { 3699 if (Flags.isSExt()) 3700 ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal, 3701 DAG.getValueType(ObjectVT)); 3702 else if (Flags.isZExt()) 3703 ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal, 3704 DAG.getValueType(ObjectVT)); 3705 3706 return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal); 3707 } 3708 3709 SDValue PPCTargetLowering::LowerFormalArguments_64SVR4( 3710 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3711 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3712 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3713 // TODO: add description of PPC stack frame format, or at least some docs. 3714 // 3715 bool isELFv2ABI = Subtarget.isELFv2ABI(); 3716 bool isLittleEndian = Subtarget.isLittleEndian(); 3717 MachineFunction &MF = DAG.getMachineFunction(); 3718 MachineFrameInfo &MFI = MF.getFrameInfo(); 3719 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 3720 3721 assert(!(CallConv == CallingConv::Fast && isVarArg) && 3722 "fastcc not supported on varargs functions"); 3723 3724 EVT PtrVT = getPointerTy(MF.getDataLayout()); 3725 // Potential tail calls could cause overwriting of argument stack slots. 3726 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt && 3727 (CallConv == CallingConv::Fast)); 3728 unsigned PtrByteSize = 8; 3729 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 3730 3731 static const MCPhysReg GPR[] = { 3732 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 3733 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 3734 }; 3735 static const MCPhysReg VR[] = { 3736 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 3737 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 3738 }; 3739 3740 const unsigned Num_GPR_Regs = array_lengthof(GPR); 3741 const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13; 3742 const unsigned Num_VR_Regs = array_lengthof(VR); 3743 const unsigned Num_QFPR_Regs = Num_FPR_Regs; 3744 3745 // Do a first pass over the arguments to determine whether the ABI 3746 // guarantees that our caller has allocated the parameter save area 3747 // on its stack frame. In the ELFv1 ABI, this is always the case; 3748 // in the ELFv2 ABI, it is true if this is a vararg function or if 3749 // any parameter is located in a stack slot. 3750 3751 bool HasParameterArea = !isELFv2ABI || isVarArg; 3752 unsigned ParamAreaSize = Num_GPR_Regs * PtrByteSize; 3753 unsigned NumBytes = LinkageSize; 3754 unsigned AvailableFPRs = Num_FPR_Regs; 3755 unsigned AvailableVRs = Num_VR_Regs; 3756 for (unsigned i = 0, e = Ins.size(); i != e; ++i) { 3757 if (Ins[i].Flags.isNest()) 3758 continue; 3759 3760 if (CalculateStackSlotUsed(Ins[i].VT, Ins[i].ArgVT, Ins[i].Flags, 3761 PtrByteSize, LinkageSize, ParamAreaSize, 3762 NumBytes, AvailableFPRs, AvailableVRs, 3763 Subtarget.hasQPX())) 3764 HasParameterArea = true; 3765 } 3766 3767 // Add DAG nodes to load the arguments or copy them out of registers. On 3768 // entry to a function on PPC, the arguments start after the linkage area, 3769 // although the first ones are often in registers. 3770 3771 unsigned ArgOffset = LinkageSize; 3772 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 3773 unsigned &QFPR_idx = FPR_idx; 3774 SmallVector<SDValue, 8> MemOps; 3775 Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin(); 3776 unsigned CurArgIdx = 0; 3777 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) { 3778 SDValue ArgVal; 3779 bool needsLoad = false; 3780 EVT ObjectVT = Ins[ArgNo].VT; 3781 EVT OrigVT = Ins[ArgNo].ArgVT; 3782 unsigned ObjSize = ObjectVT.getStoreSize(); 3783 unsigned ArgSize = ObjSize; 3784 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags; 3785 if (Ins[ArgNo].isOrigArg()) { 3786 std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx); 3787 CurArgIdx = Ins[ArgNo].getOrigArgIndex(); 3788 } 3789 // We re-align the argument offset for each argument, except when using the 3790 // fast calling convention, when we need to make sure we do that only when 3791 // we'll actually use a stack slot. 3792 unsigned CurArgOffset, Align; 3793 auto ComputeArgOffset = [&]() { 3794 /* Respect alignment of argument on the stack. */ 3795 Align = CalculateStackSlotAlignment(ObjectVT, OrigVT, Flags, PtrByteSize); 3796 ArgOffset = ((ArgOffset + Align - 1) / Align) * Align; 3797 CurArgOffset = ArgOffset; 3798 }; 3799 3800 if (CallConv != CallingConv::Fast) { 3801 ComputeArgOffset(); 3802 3803 /* Compute GPR index associated with argument offset. */ 3804 GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize; 3805 GPR_idx = std::min(GPR_idx, Num_GPR_Regs); 3806 } 3807 3808 // FIXME the codegen can be much improved in some cases. 3809 // We do not have to keep everything in memory. 3810 if (Flags.isByVal()) { 3811 assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit"); 3812 3813 if (CallConv == CallingConv::Fast) 3814 ComputeArgOffset(); 3815 3816 // ObjSize is the true size, ArgSize rounded up to multiple of registers. 3817 ObjSize = Flags.getByValSize(); 3818 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3819 // Empty aggregate parameters do not take up registers. Examples: 3820 // struct { } a; 3821 // union { } b; 3822 // int c[0]; 3823 // etc. However, we have to provide a place-holder in InVals, so 3824 // pretend we have an 8-byte item at the current address for that 3825 // purpose. 3826 if (!ObjSize) { 3827 int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true); 3828 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3829 InVals.push_back(FIN); 3830 continue; 3831 } 3832 3833 // Create a stack object covering all stack doublewords occupied 3834 // by the argument. If the argument is (fully or partially) on 3835 // the stack, or if the argument is fully in registers but the 3836 // caller has allocated the parameter save anyway, we can refer 3837 // directly to the caller's stack frame. Otherwise, create a 3838 // local copy in our own frame. 3839 int FI; 3840 if (HasParameterArea || 3841 ArgSize + ArgOffset > LinkageSize + Num_GPR_Regs * PtrByteSize) 3842 FI = MFI.CreateFixedObject(ArgSize, ArgOffset, false, true); 3843 else 3844 FI = MFI.CreateStackObject(ArgSize, Align, false); 3845 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3846 3847 // Handle aggregates smaller than 8 bytes. 3848 if (ObjSize < PtrByteSize) { 3849 // The value of the object is its address, which differs from the 3850 // address of the enclosing doubleword on big-endian systems. 3851 SDValue Arg = FIN; 3852 if (!isLittleEndian) { 3853 SDValue ArgOff = DAG.getConstant(PtrByteSize - ObjSize, dl, PtrVT); 3854 Arg = DAG.getNode(ISD::ADD, dl, ArgOff.getValueType(), Arg, ArgOff); 3855 } 3856 InVals.push_back(Arg); 3857 3858 if (GPR_idx != Num_GPR_Regs) { 3859 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass); 3860 FuncInfo->addLiveInAttr(VReg, Flags); 3861 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 3862 SDValue Store; 3863 3864 if (ObjSize==1 || ObjSize==2 || ObjSize==4) { 3865 EVT ObjType = (ObjSize == 1 ? MVT::i8 : 3866 (ObjSize == 2 ? MVT::i16 : MVT::i32)); 3867 Store = DAG.getTruncStore(Val.getValue(1), dl, Val, Arg, 3868 MachinePointerInfo(&*FuncArg), ObjType); 3869 } else { 3870 // For sizes that don't fit a truncating store (3, 5, 6, 7), 3871 // store the whole register as-is to the parameter save area 3872 // slot. 3873 Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, 3874 MachinePointerInfo(&*FuncArg)); 3875 } 3876 3877 MemOps.push_back(Store); 3878 } 3879 // Whether we copied from a register or not, advance the offset 3880 // into the parameter save area by a full doubleword. 3881 ArgOffset += PtrByteSize; 3882 continue; 3883 } 3884 3885 // The value of the object is its address, which is the address of 3886 // its first stack doubleword. 3887 InVals.push_back(FIN); 3888 3889 // Store whatever pieces of the object are in registers to memory. 3890 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) { 3891 if (GPR_idx == Num_GPR_Regs) 3892 break; 3893 3894 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 3895 FuncInfo->addLiveInAttr(VReg, Flags); 3896 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 3897 SDValue Addr = FIN; 3898 if (j) { 3899 SDValue Off = DAG.getConstant(j, dl, PtrVT); 3900 Addr = DAG.getNode(ISD::ADD, dl, Off.getValueType(), Addr, Off); 3901 } 3902 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, Addr, 3903 MachinePointerInfo(&*FuncArg, j)); 3904 MemOps.push_back(Store); 3905 ++GPR_idx; 3906 } 3907 ArgOffset += ArgSize; 3908 continue; 3909 } 3910 3911 switch (ObjectVT.getSimpleVT().SimpleTy) { 3912 default: llvm_unreachable("Unhandled argument type!"); 3913 case MVT::i1: 3914 case MVT::i32: 3915 case MVT::i64: 3916 if (Flags.isNest()) { 3917 // The 'nest' parameter, if any, is passed in R11. 3918 unsigned VReg = MF.addLiveIn(PPC::X11, &PPC::G8RCRegClass); 3919 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 3920 3921 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1) 3922 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl); 3923 3924 break; 3925 } 3926 3927 // These can be scalar arguments or elements of an integer array type 3928 // passed directly. Clang may use those instead of "byval" aggregate 3929 // types to avoid forcing arguments to memory unnecessarily. 3930 if (GPR_idx != Num_GPR_Regs) { 3931 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass); 3932 FuncInfo->addLiveInAttr(VReg, Flags); 3933 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 3934 3935 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1) 3936 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote 3937 // value to MVT::i64 and then truncate to the correct register size. 3938 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl); 3939 } else { 3940 if (CallConv == CallingConv::Fast) 3941 ComputeArgOffset(); 3942 3943 needsLoad = true; 3944 ArgSize = PtrByteSize; 3945 } 3946 if (CallConv != CallingConv::Fast || needsLoad) 3947 ArgOffset += 8; 3948 break; 3949 3950 case MVT::f32: 3951 case MVT::f64: 3952 // These can be scalar arguments or elements of a float array type 3953 // passed directly. The latter are used to implement ELFv2 homogenous 3954 // float aggregates. 3955 if (FPR_idx != Num_FPR_Regs) { 3956 unsigned VReg; 3957 3958 if (ObjectVT == MVT::f32) 3959 VReg = MF.addLiveIn(FPR[FPR_idx], 3960 Subtarget.hasP8Vector() 3961 ? &PPC::VSSRCRegClass 3962 : &PPC::F4RCRegClass); 3963 else 3964 VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX() 3965 ? &PPC::VSFRCRegClass 3966 : &PPC::F8RCRegClass); 3967 3968 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 3969 ++FPR_idx; 3970 } else if (GPR_idx != Num_GPR_Regs && CallConv != CallingConv::Fast) { 3971 // FIXME: We may want to re-enable this for CallingConv::Fast on the P8 3972 // once we support fp <-> gpr moves. 3973 3974 // This can only ever happen in the presence of f32 array types, 3975 // since otherwise we never run out of FPRs before running out 3976 // of GPRs. 3977 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass); 3978 FuncInfo->addLiveInAttr(VReg, Flags); 3979 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 3980 3981 if (ObjectVT == MVT::f32) { 3982 if ((ArgOffset % PtrByteSize) == (isLittleEndian ? 4 : 0)) 3983 ArgVal = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgVal, 3984 DAG.getConstant(32, dl, MVT::i32)); 3985 ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal); 3986 } 3987 3988 ArgVal = DAG.getNode(ISD::BITCAST, dl, ObjectVT, ArgVal); 3989 } else { 3990 if (CallConv == CallingConv::Fast) 3991 ComputeArgOffset(); 3992 3993 needsLoad = true; 3994 } 3995 3996 // When passing an array of floats, the array occupies consecutive 3997 // space in the argument area; only round up to the next doubleword 3998 // at the end of the array. Otherwise, each float takes 8 bytes. 3999 if (CallConv != CallingConv::Fast || needsLoad) { 4000 ArgSize = Flags.isInConsecutiveRegs() ? ObjSize : PtrByteSize; 4001 ArgOffset += ArgSize; 4002 if (Flags.isInConsecutiveRegsLast()) 4003 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 4004 } 4005 break; 4006 case MVT::v4f32: 4007 case MVT::v4i32: 4008 case MVT::v8i16: 4009 case MVT::v16i8: 4010 case MVT::v2f64: 4011 case MVT::v2i64: 4012 case MVT::v1i128: 4013 case MVT::f128: 4014 if (!Subtarget.hasQPX()) { 4015 // These can be scalar arguments or elements of a vector array type 4016 // passed directly. The latter are used to implement ELFv2 homogenous 4017 // vector aggregates. 4018 if (VR_idx != Num_VR_Regs) { 4019 unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass); 4020 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 4021 ++VR_idx; 4022 } else { 4023 if (CallConv == CallingConv::Fast) 4024 ComputeArgOffset(); 4025 needsLoad = true; 4026 } 4027 if (CallConv != CallingConv::Fast || needsLoad) 4028 ArgOffset += 16; 4029 break; 4030 } // not QPX 4031 4032 assert(ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 && 4033 "Invalid QPX parameter type"); 4034 LLVM_FALLTHROUGH; 4035 4036 case MVT::v4f64: 4037 case MVT::v4i1: 4038 // QPX vectors are treated like their scalar floating-point subregisters 4039 // (except that they're larger). 4040 unsigned Sz = ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 ? 16 : 32; 4041 if (QFPR_idx != Num_QFPR_Regs) { 4042 const TargetRegisterClass *RC; 4043 switch (ObjectVT.getSimpleVT().SimpleTy) { 4044 case MVT::v4f64: RC = &PPC::QFRCRegClass; break; 4045 case MVT::v4f32: RC = &PPC::QSRCRegClass; break; 4046 default: RC = &PPC::QBRCRegClass; break; 4047 } 4048 4049 unsigned VReg = MF.addLiveIn(QFPR[QFPR_idx], RC); 4050 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 4051 ++QFPR_idx; 4052 } else { 4053 if (CallConv == CallingConv::Fast) 4054 ComputeArgOffset(); 4055 needsLoad = true; 4056 } 4057 if (CallConv != CallingConv::Fast || needsLoad) 4058 ArgOffset += Sz; 4059 break; 4060 } 4061 4062 // We need to load the argument to a virtual register if we determined 4063 // above that we ran out of physical registers of the appropriate type. 4064 if (needsLoad) { 4065 if (ObjSize < ArgSize && !isLittleEndian) 4066 CurArgOffset += ArgSize - ObjSize; 4067 int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, isImmutable); 4068 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4069 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo()); 4070 } 4071 4072 InVals.push_back(ArgVal); 4073 } 4074 4075 // Area that is at least reserved in the caller of this function. 4076 unsigned MinReservedArea; 4077 if (HasParameterArea) 4078 MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize); 4079 else 4080 MinReservedArea = LinkageSize; 4081 4082 // Set the size that is at least reserved in caller of this function. Tail 4083 // call optimized functions' reserved stack space needs to be aligned so that 4084 // taking the difference between two stack areas will result in an aligned 4085 // stack. 4086 MinReservedArea = 4087 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea); 4088 FuncInfo->setMinReservedArea(MinReservedArea); 4089 4090 // If the function takes variable number of arguments, make a frame index for 4091 // the start of the first vararg value... for expansion of llvm.va_start. 4092 if (isVarArg) { 4093 int Depth = ArgOffset; 4094 4095 FuncInfo->setVarArgsFrameIndex( 4096 MFI.CreateFixedObject(PtrByteSize, Depth, true)); 4097 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 4098 4099 // If this function is vararg, store any remaining integer argument regs 4100 // to their spots on the stack so that they may be loaded by dereferencing 4101 // the result of va_next. 4102 for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize; 4103 GPR_idx < Num_GPR_Regs; ++GPR_idx) { 4104 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4105 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4106 SDValue Store = 4107 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 4108 MemOps.push_back(Store); 4109 // Increment the address by four for the next argument to store 4110 SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT); 4111 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 4112 } 4113 } 4114 4115 if (!MemOps.empty()) 4116 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 4117 4118 return Chain; 4119 } 4120 4121 SDValue PPCTargetLowering::LowerFormalArguments_Darwin( 4122 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 4123 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 4124 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 4125 // TODO: add description of PPC stack frame format, or at least some docs. 4126 // 4127 MachineFunction &MF = DAG.getMachineFunction(); 4128 MachineFrameInfo &MFI = MF.getFrameInfo(); 4129 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 4130 4131 EVT PtrVT = getPointerTy(MF.getDataLayout()); 4132 bool isPPC64 = PtrVT == MVT::i64; 4133 // Potential tail calls could cause overwriting of argument stack slots. 4134 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt && 4135 (CallConv == CallingConv::Fast)); 4136 unsigned PtrByteSize = isPPC64 ? 8 : 4; 4137 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 4138 unsigned ArgOffset = LinkageSize; 4139 // Area that is at least reserved in caller of this function. 4140 unsigned MinReservedArea = ArgOffset; 4141 4142 static const MCPhysReg GPR_32[] = { // 32-bit registers. 4143 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 4144 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 4145 }; 4146 static const MCPhysReg GPR_64[] = { // 64-bit registers. 4147 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 4148 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 4149 }; 4150 static const MCPhysReg VR[] = { 4151 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 4152 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 4153 }; 4154 4155 const unsigned Num_GPR_Regs = array_lengthof(GPR_32); 4156 const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13; 4157 const unsigned Num_VR_Regs = array_lengthof( VR); 4158 4159 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 4160 4161 const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32; 4162 4163 // In 32-bit non-varargs functions, the stack space for vectors is after the 4164 // stack space for non-vectors. We do not use this space unless we have 4165 // too many vectors to fit in registers, something that only occurs in 4166 // constructed examples:), but we have to walk the arglist to figure 4167 // that out...for the pathological case, compute VecArgOffset as the 4168 // start of the vector parameter area. Computing VecArgOffset is the 4169 // entire point of the following loop. 4170 unsigned VecArgOffset = ArgOffset; 4171 if (!isVarArg && !isPPC64) { 4172 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; 4173 ++ArgNo) { 4174 EVT ObjectVT = Ins[ArgNo].VT; 4175 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags; 4176 4177 if (Flags.isByVal()) { 4178 // ObjSize is the true size, ArgSize rounded up to multiple of regs. 4179 unsigned ObjSize = Flags.getByValSize(); 4180 unsigned ArgSize = 4181 ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 4182 VecArgOffset += ArgSize; 4183 continue; 4184 } 4185 4186 switch(ObjectVT.getSimpleVT().SimpleTy) { 4187 default: llvm_unreachable("Unhandled argument type!"); 4188 case MVT::i1: 4189 case MVT::i32: 4190 case MVT::f32: 4191 VecArgOffset += 4; 4192 break; 4193 case MVT::i64: // PPC64 4194 case MVT::f64: 4195 // FIXME: We are guaranteed to be !isPPC64 at this point. 4196 // Does MVT::i64 apply? 4197 VecArgOffset += 8; 4198 break; 4199 case MVT::v4f32: 4200 case MVT::v4i32: 4201 case MVT::v8i16: 4202 case MVT::v16i8: 4203 // Nothing to do, we're only looking at Nonvector args here. 4204 break; 4205 } 4206 } 4207 } 4208 // We've found where the vector parameter area in memory is. Skip the 4209 // first 12 parameters; these don't use that memory. 4210 VecArgOffset = ((VecArgOffset+15)/16)*16; 4211 VecArgOffset += 12*16; 4212 4213 // Add DAG nodes to load the arguments or copy them out of registers. On 4214 // entry to a function on PPC, the arguments start after the linkage area, 4215 // although the first ones are often in registers. 4216 4217 SmallVector<SDValue, 8> MemOps; 4218 unsigned nAltivecParamsAtEnd = 0; 4219 Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin(); 4220 unsigned CurArgIdx = 0; 4221 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) { 4222 SDValue ArgVal; 4223 bool needsLoad = false; 4224 EVT ObjectVT = Ins[ArgNo].VT; 4225 unsigned ObjSize = ObjectVT.getSizeInBits()/8; 4226 unsigned ArgSize = ObjSize; 4227 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags; 4228 if (Ins[ArgNo].isOrigArg()) { 4229 std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx); 4230 CurArgIdx = Ins[ArgNo].getOrigArgIndex(); 4231 } 4232 unsigned CurArgOffset = ArgOffset; 4233 4234 // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary. 4235 if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 || 4236 ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) { 4237 if (isVarArg || isPPC64) { 4238 MinReservedArea = ((MinReservedArea+15)/16)*16; 4239 MinReservedArea += CalculateStackSlotSize(ObjectVT, 4240 Flags, 4241 PtrByteSize); 4242 } else nAltivecParamsAtEnd++; 4243 } else 4244 // Calculate min reserved area. 4245 MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT, 4246 Flags, 4247 PtrByteSize); 4248 4249 // FIXME the codegen can be much improved in some cases. 4250 // We do not have to keep everything in memory. 4251 if (Flags.isByVal()) { 4252 assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit"); 4253 4254 // ObjSize is the true size, ArgSize rounded up to multiple of registers. 4255 ObjSize = Flags.getByValSize(); 4256 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 4257 // Objects of size 1 and 2 are right justified, everything else is 4258 // left justified. This means the memory address is adjusted forwards. 4259 if (ObjSize==1 || ObjSize==2) { 4260 CurArgOffset = CurArgOffset + (4 - ObjSize); 4261 } 4262 // The value of the object is its address. 4263 int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, false, true); 4264 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4265 InVals.push_back(FIN); 4266 if (ObjSize==1 || ObjSize==2) { 4267 if (GPR_idx != Num_GPR_Regs) { 4268 unsigned VReg; 4269 if (isPPC64) 4270 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4271 else 4272 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 4273 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4274 EVT ObjType = ObjSize == 1 ? MVT::i8 : MVT::i16; 4275 SDValue Store = 4276 DAG.getTruncStore(Val.getValue(1), dl, Val, FIN, 4277 MachinePointerInfo(&*FuncArg), ObjType); 4278 MemOps.push_back(Store); 4279 ++GPR_idx; 4280 } 4281 4282 ArgOffset += PtrByteSize; 4283 4284 continue; 4285 } 4286 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) { 4287 // Store whatever pieces of the object are in registers 4288 // to memory. ArgOffset will be the address of the beginning 4289 // of the object. 4290 if (GPR_idx != Num_GPR_Regs) { 4291 unsigned VReg; 4292 if (isPPC64) 4293 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4294 else 4295 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 4296 int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true); 4297 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4298 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4299 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, 4300 MachinePointerInfo(&*FuncArg, j)); 4301 MemOps.push_back(Store); 4302 ++GPR_idx; 4303 ArgOffset += PtrByteSize; 4304 } else { 4305 ArgOffset += ArgSize - (ArgOffset-CurArgOffset); 4306 break; 4307 } 4308 } 4309 continue; 4310 } 4311 4312 switch (ObjectVT.getSimpleVT().SimpleTy) { 4313 default: llvm_unreachable("Unhandled argument type!"); 4314 case MVT::i1: 4315 case MVT::i32: 4316 if (!isPPC64) { 4317 if (GPR_idx != Num_GPR_Regs) { 4318 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 4319 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32); 4320 4321 if (ObjectVT == MVT::i1) 4322 ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgVal); 4323 4324 ++GPR_idx; 4325 } else { 4326 needsLoad = true; 4327 ArgSize = PtrByteSize; 4328 } 4329 // All int arguments reserve stack space in the Darwin ABI. 4330 ArgOffset += PtrByteSize; 4331 break; 4332 } 4333 LLVM_FALLTHROUGH; 4334 case MVT::i64: // PPC64 4335 if (GPR_idx != Num_GPR_Regs) { 4336 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4337 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 4338 4339 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1) 4340 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote 4341 // value to MVT::i64 and then truncate to the correct register size. 4342 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl); 4343 4344 ++GPR_idx; 4345 } else { 4346 needsLoad = true; 4347 ArgSize = PtrByteSize; 4348 } 4349 // All int arguments reserve stack space in the Darwin ABI. 4350 ArgOffset += 8; 4351 break; 4352 4353 case MVT::f32: 4354 case MVT::f64: 4355 // Every 4 bytes of argument space consumes one of the GPRs available for 4356 // argument passing. 4357 if (GPR_idx != Num_GPR_Regs) { 4358 ++GPR_idx; 4359 if (ObjSize == 8 && GPR_idx != Num_GPR_Regs && !isPPC64) 4360 ++GPR_idx; 4361 } 4362 if (FPR_idx != Num_FPR_Regs) { 4363 unsigned VReg; 4364 4365 if (ObjectVT == MVT::f32) 4366 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass); 4367 else 4368 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass); 4369 4370 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 4371 ++FPR_idx; 4372 } else { 4373 needsLoad = true; 4374 } 4375 4376 // All FP arguments reserve stack space in the Darwin ABI. 4377 ArgOffset += isPPC64 ? 8 : ObjSize; 4378 break; 4379 case MVT::v4f32: 4380 case MVT::v4i32: 4381 case MVT::v8i16: 4382 case MVT::v16i8: 4383 // Note that vector arguments in registers don't reserve stack space, 4384 // except in varargs functions. 4385 if (VR_idx != Num_VR_Regs) { 4386 unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass); 4387 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 4388 if (isVarArg) { 4389 while ((ArgOffset % 16) != 0) { 4390 ArgOffset += PtrByteSize; 4391 if (GPR_idx != Num_GPR_Regs) 4392 GPR_idx++; 4393 } 4394 ArgOffset += 16; 4395 GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64? 4396 } 4397 ++VR_idx; 4398 } else { 4399 if (!isVarArg && !isPPC64) { 4400 // Vectors go after all the nonvectors. 4401 CurArgOffset = VecArgOffset; 4402 VecArgOffset += 16; 4403 } else { 4404 // Vectors are aligned. 4405 ArgOffset = ((ArgOffset+15)/16)*16; 4406 CurArgOffset = ArgOffset; 4407 ArgOffset += 16; 4408 } 4409 needsLoad = true; 4410 } 4411 break; 4412 } 4413 4414 // We need to load the argument to a virtual register if we determined above 4415 // that we ran out of physical registers of the appropriate type. 4416 if (needsLoad) { 4417 int FI = MFI.CreateFixedObject(ObjSize, 4418 CurArgOffset + (ArgSize - ObjSize), 4419 isImmutable); 4420 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4421 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo()); 4422 } 4423 4424 InVals.push_back(ArgVal); 4425 } 4426 4427 // Allow for Altivec parameters at the end, if needed. 4428 if (nAltivecParamsAtEnd) { 4429 MinReservedArea = ((MinReservedArea+15)/16)*16; 4430 MinReservedArea += 16*nAltivecParamsAtEnd; 4431 } 4432 4433 // Area that is at least reserved in the caller of this function. 4434 MinReservedArea = std::max(MinReservedArea, LinkageSize + 8 * PtrByteSize); 4435 4436 // Set the size that is at least reserved in caller of this function. Tail 4437 // call optimized functions' reserved stack space needs to be aligned so that 4438 // taking the difference between two stack areas will result in an aligned 4439 // stack. 4440 MinReservedArea = 4441 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea); 4442 FuncInfo->setMinReservedArea(MinReservedArea); 4443 4444 // If the function takes variable number of arguments, make a frame index for 4445 // the start of the first vararg value... for expansion of llvm.va_start. 4446 if (isVarArg) { 4447 int Depth = ArgOffset; 4448 4449 FuncInfo->setVarArgsFrameIndex( 4450 MFI.CreateFixedObject(PtrVT.getSizeInBits()/8, 4451 Depth, true)); 4452 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 4453 4454 // If this function is vararg, store any remaining integer argument regs 4455 // to their spots on the stack so that they may be loaded by dereferencing 4456 // the result of va_next. 4457 for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) { 4458 unsigned VReg; 4459 4460 if (isPPC64) 4461 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4462 else 4463 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 4464 4465 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4466 SDValue Store = 4467 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 4468 MemOps.push_back(Store); 4469 // Increment the address by four for the next argument to store 4470 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT); 4471 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 4472 } 4473 } 4474 4475 if (!MemOps.empty()) 4476 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 4477 4478 return Chain; 4479 } 4480 4481 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be 4482 /// adjusted to accommodate the arguments for the tailcall. 4483 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall, 4484 unsigned ParamSize) { 4485 4486 if (!isTailCall) return 0; 4487 4488 PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>(); 4489 unsigned CallerMinReservedArea = FI->getMinReservedArea(); 4490 int SPDiff = (int)CallerMinReservedArea - (int)ParamSize; 4491 // Remember only if the new adjustment is bigger. 4492 if (SPDiff < FI->getTailCallSPDelta()) 4493 FI->setTailCallSPDelta(SPDiff); 4494 4495 return SPDiff; 4496 } 4497 4498 static bool isFunctionGlobalAddress(SDValue Callee); 4499 4500 static bool 4501 callsShareTOCBase(const Function *Caller, SDValue Callee, 4502 const TargetMachine &TM) { 4503 // Callee is either a GlobalAddress or an ExternalSymbol. ExternalSymbols 4504 // don't have enough information to determine if the caller and calle share 4505 // the same TOC base, so we have to pessimistically assume they don't for 4506 // correctness. 4507 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee); 4508 if (!G) 4509 return false; 4510 4511 const GlobalValue *GV = G->getGlobal(); 4512 // The medium and large code models are expected to provide a sufficiently 4513 // large TOC to provide all data addressing needs of a module with a 4514 // single TOC. Since each module will be addressed with a single TOC then we 4515 // only need to check that caller and callee don't cross dso boundaries. 4516 if (CodeModel::Medium == TM.getCodeModel() || 4517 CodeModel::Large == TM.getCodeModel()) 4518 return TM.shouldAssumeDSOLocal(*Caller->getParent(), GV); 4519 4520 // Otherwise we need to ensure callee and caller are in the same section, 4521 // since the linker may allocate multiple TOCs, and we don't know which 4522 // sections will belong to the same TOC base. 4523 4524 if (!GV->isStrongDefinitionForLinker()) 4525 return false; 4526 4527 // Any explicitly-specified sections and section prefixes must also match. 4528 // Also, if we're using -ffunction-sections, then each function is always in 4529 // a different section (the same is true for COMDAT functions). 4530 if (TM.getFunctionSections() || GV->hasComdat() || Caller->hasComdat() || 4531 GV->getSection() != Caller->getSection()) 4532 return false; 4533 if (const auto *F = dyn_cast<Function>(GV)) { 4534 if (F->getSectionPrefix() != Caller->getSectionPrefix()) 4535 return false; 4536 } 4537 4538 // If the callee might be interposed, then we can't assume the ultimate call 4539 // target will be in the same section. Even in cases where we can assume that 4540 // interposition won't happen, in any case where the linker might insert a 4541 // stub to allow for interposition, we must generate code as though 4542 // interposition might occur. To understand why this matters, consider a 4543 // situation where: a -> b -> c where the arrows indicate calls. b and c are 4544 // in the same section, but a is in a different module (i.e. has a different 4545 // TOC base pointer). If the linker allows for interposition between b and c, 4546 // then it will generate a stub for the call edge between b and c which will 4547 // save the TOC pointer into the designated stack slot allocated by b. If we 4548 // return true here, and therefore allow a tail call between b and c, that 4549 // stack slot won't exist and the b -> c stub will end up saving b'c TOC base 4550 // pointer into the stack slot allocated by a (where the a -> b stub saved 4551 // a's TOC base pointer). If we're not considering a tail call, but rather, 4552 // whether a nop is needed after the call instruction in b, because the linker 4553 // will insert a stub, it might complain about a missing nop if we omit it 4554 // (although many don't complain in this case). 4555 if (!TM.shouldAssumeDSOLocal(*Caller->getParent(), GV)) 4556 return false; 4557 4558 return true; 4559 } 4560 4561 static bool 4562 needStackSlotPassParameters(const PPCSubtarget &Subtarget, 4563 const SmallVectorImpl<ISD::OutputArg> &Outs) { 4564 assert(Subtarget.is64BitELFABI()); 4565 4566 const unsigned PtrByteSize = 8; 4567 const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 4568 4569 static const MCPhysReg GPR[] = { 4570 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 4571 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 4572 }; 4573 static const MCPhysReg VR[] = { 4574 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 4575 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 4576 }; 4577 4578 const unsigned NumGPRs = array_lengthof(GPR); 4579 const unsigned NumFPRs = 13; 4580 const unsigned NumVRs = array_lengthof(VR); 4581 const unsigned ParamAreaSize = NumGPRs * PtrByteSize; 4582 4583 unsigned NumBytes = LinkageSize; 4584 unsigned AvailableFPRs = NumFPRs; 4585 unsigned AvailableVRs = NumVRs; 4586 4587 for (const ISD::OutputArg& Param : Outs) { 4588 if (Param.Flags.isNest()) continue; 4589 4590 if (CalculateStackSlotUsed(Param.VT, Param.ArgVT, Param.Flags, 4591 PtrByteSize, LinkageSize, ParamAreaSize, 4592 NumBytes, AvailableFPRs, AvailableVRs, 4593 Subtarget.hasQPX())) 4594 return true; 4595 } 4596 return false; 4597 } 4598 4599 static bool 4600 hasSameArgumentList(const Function *CallerFn, ImmutableCallSite CS) { 4601 if (CS.arg_size() != CallerFn->arg_size()) 4602 return false; 4603 4604 ImmutableCallSite::arg_iterator CalleeArgIter = CS.arg_begin(); 4605 ImmutableCallSite::arg_iterator CalleeArgEnd = CS.arg_end(); 4606 Function::const_arg_iterator CallerArgIter = CallerFn->arg_begin(); 4607 4608 for (; CalleeArgIter != CalleeArgEnd; ++CalleeArgIter, ++CallerArgIter) { 4609 const Value* CalleeArg = *CalleeArgIter; 4610 const Value* CallerArg = &(*CallerArgIter); 4611 if (CalleeArg == CallerArg) 4612 continue; 4613 4614 // e.g. @caller([4 x i64] %a, [4 x i64] %b) { 4615 // tail call @callee([4 x i64] undef, [4 x i64] %b) 4616 // } 4617 // 1st argument of callee is undef and has the same type as caller. 4618 if (CalleeArg->getType() == CallerArg->getType() && 4619 isa<UndefValue>(CalleeArg)) 4620 continue; 4621 4622 return false; 4623 } 4624 4625 return true; 4626 } 4627 4628 // Returns true if TCO is possible between the callers and callees 4629 // calling conventions. 4630 static bool 4631 areCallingConvEligibleForTCO_64SVR4(CallingConv::ID CallerCC, 4632 CallingConv::ID CalleeCC) { 4633 // Tail calls are possible with fastcc and ccc. 4634 auto isTailCallableCC = [] (CallingConv::ID CC){ 4635 return CC == CallingConv::C || CC == CallingConv::Fast; 4636 }; 4637 if (!isTailCallableCC(CallerCC) || !isTailCallableCC(CalleeCC)) 4638 return false; 4639 4640 // We can safely tail call both fastcc and ccc callees from a c calling 4641 // convention caller. If the caller is fastcc, we may have less stack space 4642 // than a non-fastcc caller with the same signature so disable tail-calls in 4643 // that case. 4644 return CallerCC == CallingConv::C || CallerCC == CalleeCC; 4645 } 4646 4647 bool 4648 PPCTargetLowering::IsEligibleForTailCallOptimization_64SVR4( 4649 SDValue Callee, 4650 CallingConv::ID CalleeCC, 4651 ImmutableCallSite CS, 4652 bool isVarArg, 4653 const SmallVectorImpl<ISD::OutputArg> &Outs, 4654 const SmallVectorImpl<ISD::InputArg> &Ins, 4655 SelectionDAG& DAG) const { 4656 bool TailCallOpt = getTargetMachine().Options.GuaranteedTailCallOpt; 4657 4658 if (DisableSCO && !TailCallOpt) return false; 4659 4660 // Variadic argument functions are not supported. 4661 if (isVarArg) return false; 4662 4663 auto &Caller = DAG.getMachineFunction().getFunction(); 4664 // Check that the calling conventions are compatible for tco. 4665 if (!areCallingConvEligibleForTCO_64SVR4(Caller.getCallingConv(), CalleeCC)) 4666 return false; 4667 4668 // Caller contains any byval parameter is not supported. 4669 if (any_of(Ins, [](const ISD::InputArg &IA) { return IA.Flags.isByVal(); })) 4670 return false; 4671 4672 // Callee contains any byval parameter is not supported, too. 4673 // Note: This is a quick work around, because in some cases, e.g. 4674 // caller's stack size > callee's stack size, we are still able to apply 4675 // sibling call optimization. For example, gcc is able to do SCO for caller1 4676 // in the following example, but not for caller2. 4677 // struct test { 4678 // long int a; 4679 // char ary[56]; 4680 // } gTest; 4681 // __attribute__((noinline)) int callee(struct test v, struct test *b) { 4682 // b->a = v.a; 4683 // return 0; 4684 // } 4685 // void caller1(struct test a, struct test c, struct test *b) { 4686 // callee(gTest, b); } 4687 // void caller2(struct test *b) { callee(gTest, b); } 4688 if (any_of(Outs, [](const ISD::OutputArg& OA) { return OA.Flags.isByVal(); })) 4689 return false; 4690 4691 // If callee and caller use different calling conventions, we cannot pass 4692 // parameters on stack since offsets for the parameter area may be different. 4693 if (Caller.getCallingConv() != CalleeCC && 4694 needStackSlotPassParameters(Subtarget, Outs)) 4695 return false; 4696 4697 // No TCO/SCO on indirect call because Caller have to restore its TOC 4698 if (!isFunctionGlobalAddress(Callee) && 4699 !isa<ExternalSymbolSDNode>(Callee)) 4700 return false; 4701 4702 // If the caller and callee potentially have different TOC bases then we 4703 // cannot tail call since we need to restore the TOC pointer after the call. 4704 // ref: https://bugzilla.mozilla.org/show_bug.cgi?id=973977 4705 if (!callsShareTOCBase(&Caller, Callee, getTargetMachine())) 4706 return false; 4707 4708 // TCO allows altering callee ABI, so we don't have to check further. 4709 if (CalleeCC == CallingConv::Fast && TailCallOpt) 4710 return true; 4711 4712 if (DisableSCO) return false; 4713 4714 // If callee use the same argument list that caller is using, then we can 4715 // apply SCO on this case. If it is not, then we need to check if callee needs 4716 // stack for passing arguments. 4717 if (!hasSameArgumentList(&Caller, CS) && 4718 needStackSlotPassParameters(Subtarget, Outs)) { 4719 return false; 4720 } 4721 4722 return true; 4723 } 4724 4725 /// IsEligibleForTailCallOptimization - Check whether the call is eligible 4726 /// for tail call optimization. Targets which want to do tail call 4727 /// optimization should implement this function. 4728 bool 4729 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee, 4730 CallingConv::ID CalleeCC, 4731 bool isVarArg, 4732 const SmallVectorImpl<ISD::InputArg> &Ins, 4733 SelectionDAG& DAG) const { 4734 if (!getTargetMachine().Options.GuaranteedTailCallOpt) 4735 return false; 4736 4737 // Variable argument functions are not supported. 4738 if (isVarArg) 4739 return false; 4740 4741 MachineFunction &MF = DAG.getMachineFunction(); 4742 CallingConv::ID CallerCC = MF.getFunction().getCallingConv(); 4743 if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) { 4744 // Functions containing by val parameters are not supported. 4745 for (unsigned i = 0; i != Ins.size(); i++) { 4746 ISD::ArgFlagsTy Flags = Ins[i].Flags; 4747 if (Flags.isByVal()) return false; 4748 } 4749 4750 // Non-PIC/GOT tail calls are supported. 4751 if (getTargetMachine().getRelocationModel() != Reloc::PIC_) 4752 return true; 4753 4754 // At the moment we can only do local tail calls (in same module, hidden 4755 // or protected) if we are generating PIC. 4756 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) 4757 return G->getGlobal()->hasHiddenVisibility() 4758 || G->getGlobal()->hasProtectedVisibility(); 4759 } 4760 4761 return false; 4762 } 4763 4764 /// isCallCompatibleAddress - Return the immediate to use if the specified 4765 /// 32-bit value is representable in the immediate field of a BxA instruction. 4766 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) { 4767 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op); 4768 if (!C) return nullptr; 4769 4770 int Addr = C->getZExtValue(); 4771 if ((Addr & 3) != 0 || // Low 2 bits are implicitly zero. 4772 SignExtend32<26>(Addr) != Addr) 4773 return nullptr; // Top 6 bits have to be sext of immediate. 4774 4775 return DAG 4776 .getConstant( 4777 (int)C->getZExtValue() >> 2, SDLoc(Op), 4778 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout())) 4779 .getNode(); 4780 } 4781 4782 namespace { 4783 4784 struct TailCallArgumentInfo { 4785 SDValue Arg; 4786 SDValue FrameIdxOp; 4787 int FrameIdx = 0; 4788 4789 TailCallArgumentInfo() = default; 4790 }; 4791 4792 } // end anonymous namespace 4793 4794 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot. 4795 static void StoreTailCallArgumentsToStackSlot( 4796 SelectionDAG &DAG, SDValue Chain, 4797 const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs, 4798 SmallVectorImpl<SDValue> &MemOpChains, const SDLoc &dl) { 4799 for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) { 4800 SDValue Arg = TailCallArgs[i].Arg; 4801 SDValue FIN = TailCallArgs[i].FrameIdxOp; 4802 int FI = TailCallArgs[i].FrameIdx; 4803 // Store relative to framepointer. 4804 MemOpChains.push_back(DAG.getStore( 4805 Chain, dl, Arg, FIN, 4806 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI))); 4807 } 4808 } 4809 4810 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to 4811 /// the appropriate stack slot for the tail call optimized function call. 4812 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG, SDValue Chain, 4813 SDValue OldRetAddr, SDValue OldFP, 4814 int SPDiff, const SDLoc &dl) { 4815 if (SPDiff) { 4816 // Calculate the new stack slot for the return address. 4817 MachineFunction &MF = DAG.getMachineFunction(); 4818 const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>(); 4819 const PPCFrameLowering *FL = Subtarget.getFrameLowering(); 4820 bool isPPC64 = Subtarget.isPPC64(); 4821 int SlotSize = isPPC64 ? 8 : 4; 4822 int NewRetAddrLoc = SPDiff + FL->getReturnSaveOffset(); 4823 int NewRetAddr = MF.getFrameInfo().CreateFixedObject(SlotSize, 4824 NewRetAddrLoc, true); 4825 EVT VT = isPPC64 ? MVT::i64 : MVT::i32; 4826 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT); 4827 Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx, 4828 MachinePointerInfo::getFixedStack(MF, NewRetAddr)); 4829 } 4830 return Chain; 4831 } 4832 4833 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate 4834 /// the position of the argument. 4835 static void 4836 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64, 4837 SDValue Arg, int SPDiff, unsigned ArgOffset, 4838 SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) { 4839 int Offset = ArgOffset + SPDiff; 4840 uint32_t OpSize = (Arg.getValueSizeInBits() + 7) / 8; 4841 int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true); 4842 EVT VT = isPPC64 ? MVT::i64 : MVT::i32; 4843 SDValue FIN = DAG.getFrameIndex(FI, VT); 4844 TailCallArgumentInfo Info; 4845 Info.Arg = Arg; 4846 Info.FrameIdxOp = FIN; 4847 Info.FrameIdx = FI; 4848 TailCallArguments.push_back(Info); 4849 } 4850 4851 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address 4852 /// stack slot. Returns the chain as result and the loaded frame pointers in 4853 /// LROpOut/FPOpout. Used when tail calling. 4854 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr( 4855 SelectionDAG &DAG, int SPDiff, SDValue Chain, SDValue &LROpOut, 4856 SDValue &FPOpOut, const SDLoc &dl) const { 4857 if (SPDiff) { 4858 // Load the LR and FP stack slot for later adjusting. 4859 EVT VT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32; 4860 LROpOut = getReturnAddrFrameIndex(DAG); 4861 LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo()); 4862 Chain = SDValue(LROpOut.getNode(), 1); 4863 } 4864 return Chain; 4865 } 4866 4867 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified 4868 /// by "Src" to address "Dst" of size "Size". Alignment information is 4869 /// specified by the specific parameter attribute. The copy will be passed as 4870 /// a byval function parameter. 4871 /// Sometimes what we are copying is the end of a larger object, the part that 4872 /// does not fit in registers. 4873 static SDValue CreateCopyOfByValArgument(SDValue Src, SDValue Dst, 4874 SDValue Chain, ISD::ArgFlagsTy Flags, 4875 SelectionDAG &DAG, const SDLoc &dl) { 4876 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32); 4877 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(), 4878 false, false, false, MachinePointerInfo(), 4879 MachinePointerInfo()); 4880 } 4881 4882 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of 4883 /// tail calls. 4884 static void LowerMemOpCallTo( 4885 SelectionDAG &DAG, MachineFunction &MF, SDValue Chain, SDValue Arg, 4886 SDValue PtrOff, int SPDiff, unsigned ArgOffset, bool isPPC64, 4887 bool isTailCall, bool isVector, SmallVectorImpl<SDValue> &MemOpChains, 4888 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments, const SDLoc &dl) { 4889 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 4890 if (!isTailCall) { 4891 if (isVector) { 4892 SDValue StackPtr; 4893 if (isPPC64) 4894 StackPtr = DAG.getRegister(PPC::X1, MVT::i64); 4895 else 4896 StackPtr = DAG.getRegister(PPC::R1, MVT::i32); 4897 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, 4898 DAG.getConstant(ArgOffset, dl, PtrVT)); 4899 } 4900 MemOpChains.push_back( 4901 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo())); 4902 // Calculate and remember argument location. 4903 } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset, 4904 TailCallArguments); 4905 } 4906 4907 static void 4908 PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain, 4909 const SDLoc &dl, int SPDiff, unsigned NumBytes, SDValue LROp, 4910 SDValue FPOp, 4911 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) { 4912 // Emit a sequence of copyto/copyfrom virtual registers for arguments that 4913 // might overwrite each other in case of tail call optimization. 4914 SmallVector<SDValue, 8> MemOpChains2; 4915 // Do not flag preceding copytoreg stuff together with the following stuff. 4916 InFlag = SDValue(); 4917 StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments, 4918 MemOpChains2, dl); 4919 if (!MemOpChains2.empty()) 4920 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2); 4921 4922 // Store the return address to the appropriate stack slot. 4923 Chain = EmitTailCallStoreFPAndRetAddr(DAG, Chain, LROp, FPOp, SPDiff, dl); 4924 4925 // Emit callseq_end just before tailcall node. 4926 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true), 4927 DAG.getIntPtrConstant(0, dl, true), InFlag, dl); 4928 InFlag = Chain.getValue(1); 4929 } 4930 4931 // Is this global address that of a function that can be called by name? (as 4932 // opposed to something that must hold a descriptor for an indirect call). 4933 static bool isFunctionGlobalAddress(SDValue Callee) { 4934 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 4935 if (Callee.getOpcode() == ISD::GlobalTLSAddress || 4936 Callee.getOpcode() == ISD::TargetGlobalTLSAddress) 4937 return false; 4938 4939 return G->getGlobal()->getValueType()->isFunctionTy(); 4940 } 4941 4942 return false; 4943 } 4944 4945 SDValue PPCTargetLowering::LowerCallResult( 4946 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg, 4947 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 4948 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 4949 SmallVector<CCValAssign, 16> RVLocs; 4950 CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 4951 *DAG.getContext()); 4952 4953 CCRetInfo.AnalyzeCallResult( 4954 Ins, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold) 4955 ? RetCC_PPC_Cold 4956 : RetCC_PPC); 4957 4958 // Copy all of the result registers out of their specified physreg. 4959 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) { 4960 CCValAssign &VA = RVLocs[i]; 4961 assert(VA.isRegLoc() && "Can only return in registers!"); 4962 4963 SDValue Val; 4964 4965 if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) { 4966 SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, 4967 InFlag); 4968 Chain = Lo.getValue(1); 4969 InFlag = Lo.getValue(2); 4970 VA = RVLocs[++i]; // skip ahead to next loc 4971 SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, 4972 InFlag); 4973 Chain = Hi.getValue(1); 4974 InFlag = Hi.getValue(2); 4975 if (!Subtarget.isLittleEndian()) 4976 std::swap (Lo, Hi); 4977 Val = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, Lo, Hi); 4978 } else { 4979 Val = DAG.getCopyFromReg(Chain, dl, 4980 VA.getLocReg(), VA.getLocVT(), InFlag); 4981 Chain = Val.getValue(1); 4982 InFlag = Val.getValue(2); 4983 } 4984 4985 switch (VA.getLocInfo()) { 4986 default: llvm_unreachable("Unknown loc info!"); 4987 case CCValAssign::Full: break; 4988 case CCValAssign::AExt: 4989 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val); 4990 break; 4991 case CCValAssign::ZExt: 4992 Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val, 4993 DAG.getValueType(VA.getValVT())); 4994 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val); 4995 break; 4996 case CCValAssign::SExt: 4997 Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val, 4998 DAG.getValueType(VA.getValVT())); 4999 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val); 5000 break; 5001 } 5002 5003 InVals.push_back(Val); 5004 } 5005 5006 return Chain; 5007 } 5008 5009 static bool isIndirectCall(const SDValue &Callee, SelectionDAG &DAG, 5010 const PPCSubtarget &Subtarget, bool isPatchPoint) { 5011 // PatchPoint calls are not indirect. 5012 if (isPatchPoint) 5013 return false; 5014 5015 if (isFunctionGlobalAddress(Callee) || dyn_cast<ExternalSymbolSDNode>(Callee)) 5016 return false; 5017 5018 // Darwin, and 32-bit ELF can use a BLA. The descriptor based ABIs can not 5019 // becuase the immediate function pointer points to a descriptor instead of 5020 // a function entry point. The ELFv2 ABI cannot use a BLA because the function 5021 // pointer immediate points to the global entry point, while the BLA would 5022 // need to jump to the local entry point (see rL211174). 5023 if (!Subtarget.usesFunctionDescriptors() && !Subtarget.isELFv2ABI() && 5024 isBLACompatibleAddress(Callee, DAG)) 5025 return false; 5026 5027 return true; 5028 } 5029 5030 static unsigned getCallOpcode(bool isIndirectCall, bool isPatchPoint, 5031 bool isTailCall, const Function &Caller, 5032 const SDValue &Callee, 5033 const PPCSubtarget &Subtarget, 5034 const TargetMachine &TM) { 5035 if (isTailCall) 5036 return PPCISD::TC_RETURN; 5037 5038 // This is a call through a function pointer. 5039 if (isIndirectCall) { 5040 // AIX and the 64-bit ELF ABIs need to maintain the TOC pointer accross 5041 // indirect calls. The save of the caller's TOC pointer to the stack will be 5042 // inserted into the DAG as part of call lowering. The restore of the TOC 5043 // pointer is modeled by using a pseudo instruction for the call opcode that 5044 // represents the 2 instruction sequence of an indirect branch and link, 5045 // immediately followed by a load of the TOC pointer from the the stack save 5046 // slot into gpr2. 5047 if (Subtarget.isAIXABI() || Subtarget.is64BitELFABI()) 5048 return PPCISD::BCTRL_LOAD_TOC; 5049 5050 // An indirect call that does not need a TOC restore. 5051 return PPCISD::BCTRL; 5052 } 5053 5054 // The ABIs that maintain a TOC pointer accross calls need to have a nop 5055 // immediately following the call instruction if the caller and callee may 5056 // have different TOC bases. At link time if the linker determines the calls 5057 // may not share a TOC base, the call is redirected to a trampoline inserted 5058 // by the linker. The trampoline will (among other things) save the callers 5059 // TOC pointer at an ABI designated offset in the linkage area and the linker 5060 // will rewrite the nop to be a load of the TOC pointer from the linkage area 5061 // into gpr2. 5062 if (Subtarget.isAIXABI() || Subtarget.is64BitELFABI()) 5063 return callsShareTOCBase(&Caller, Callee, TM) ? PPCISD::CALL 5064 : PPCISD::CALL_NOP; 5065 5066 return PPCISD::CALL; 5067 } 5068 5069 static bool isValidAIXExternalSymSDNode(StringRef SymName) { 5070 return StringSwitch<bool>(SymName) 5071 .Cases("__divdi3", "__fixunsdfdi", "__floatundidf", "__floatundisf", 5072 "__moddi3", "__udivdi3", "__umoddi3", true) 5073 .Cases("ceil", "floor", "memcpy", "memmove", "memset", "round", true) 5074 .Default(false); 5075 } 5076 5077 static SDValue transformCallee(const SDValue &Callee, SelectionDAG &DAG, 5078 const SDLoc &dl, const PPCSubtarget &Subtarget) { 5079 if (!Subtarget.usesFunctionDescriptors() && !Subtarget.isELFv2ABI()) 5080 if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG)) 5081 return SDValue(Dest, 0); 5082 5083 // Returns true if the callee is local, and false otherwise. 5084 auto isLocalCallee = [&]() { 5085 const GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee); 5086 const Module *Mod = DAG.getMachineFunction().getFunction().getParent(); 5087 const GlobalValue *GV = G ? G->getGlobal() : nullptr; 5088 5089 return DAG.getTarget().shouldAssumeDSOLocal(*Mod, GV) && 5090 !dyn_cast_or_null<GlobalIFunc>(GV); 5091 }; 5092 5093 // The PLT is only used in 32-bit ELF PIC mode. Attempting to use the PLT in 5094 // a static relocation model causes some versions of GNU LD (2.17.50, at 5095 // least) to force BSS-PLT, instead of secure-PLT, even if all objects are 5096 // built with secure-PLT. 5097 bool UsePlt = 5098 Subtarget.is32BitELFABI() && !isLocalCallee() && 5099 Subtarget.getTargetMachine().getRelocationModel() == Reloc::PIC_; 5100 5101 // On AIX, direct function calls reference the symbol for the function's 5102 // entry point, which is named by prepending a "." before the function's 5103 // C-linkage name. 5104 const auto getAIXFuncEntryPointSymbolSDNode = 5105 [&](StringRef FuncName, bool IsDeclaration, 5106 const XCOFF::StorageClass &SC) { 5107 auto &Context = DAG.getMachineFunction().getMMI().getContext(); 5108 5109 MCSymbolXCOFF *S = cast<MCSymbolXCOFF>( 5110 Context.getOrCreateSymbol(Twine(".") + Twine(FuncName))); 5111 5112 if (IsDeclaration && !S->hasContainingCsect()) { 5113 // On AIX, an undefined symbol needs to be associated with a 5114 // MCSectionXCOFF to get the correct storage mapping class. 5115 // In this case, XCOFF::XMC_PR. 5116 MCSectionXCOFF *Sec = Context.getXCOFFSection( 5117 S->getName(), XCOFF::XMC_PR, XCOFF::XTY_ER, SC, 5118 SectionKind::getMetadata()); 5119 S->setContainingCsect(Sec); 5120 } 5121 5122 MVT PtrVT = 5123 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 5124 return DAG.getMCSymbol(S, PtrVT); 5125 }; 5126 5127 if (isFunctionGlobalAddress(Callee)) { 5128 const GlobalAddressSDNode *G = cast<GlobalAddressSDNode>(Callee); 5129 const GlobalValue *GV = G->getGlobal(); 5130 5131 if (!Subtarget.isAIXABI()) 5132 return DAG.getTargetGlobalAddress(GV, dl, Callee.getValueType(), 0, 5133 UsePlt ? PPCII::MO_PLT : 0); 5134 5135 assert(!isa<GlobalIFunc>(GV) && "IFunc is not supported on AIX."); 5136 const GlobalObject *GO = cast<GlobalObject>(GV); 5137 const XCOFF::StorageClass SC = 5138 TargetLoweringObjectFileXCOFF::getStorageClassForGlobal(GO); 5139 return getAIXFuncEntryPointSymbolSDNode(GO->getName(), GO->isDeclaration(), 5140 SC); 5141 } 5142 5143 if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) { 5144 const char *SymName = S->getSymbol(); 5145 if (!Subtarget.isAIXABI()) 5146 return DAG.getTargetExternalSymbol(SymName, Callee.getValueType(), 5147 UsePlt ? PPCII::MO_PLT : 0); 5148 5149 // If there exists a user-declared function whose name is the same as the 5150 // ExternalSymbol's, then we pick up the user-declared version. 5151 const Module *Mod = DAG.getMachineFunction().getFunction().getParent(); 5152 if (const Function *F = 5153 dyn_cast_or_null<Function>(Mod->getNamedValue(SymName))) { 5154 const XCOFF::StorageClass SC = 5155 TargetLoweringObjectFileXCOFF::getStorageClassForGlobal(F); 5156 return getAIXFuncEntryPointSymbolSDNode(F->getName(), F->isDeclaration(), 5157 SC); 5158 } 5159 5160 // TODO: Remove this when the support for ExternalSymbolSDNode is complete. 5161 if (isValidAIXExternalSymSDNode(SymName)) { 5162 return getAIXFuncEntryPointSymbolSDNode(SymName, true, XCOFF::C_EXT); 5163 } 5164 5165 report_fatal_error("Unexpected ExternalSymbolSDNode: " + Twine(SymName)); 5166 } 5167 5168 // No transformation needed. 5169 assert(Callee.getNode() && "What no callee?"); 5170 return Callee; 5171 } 5172 5173 static SDValue getOutputChainFromCallSeq(SDValue CallSeqStart) { 5174 assert(CallSeqStart.getOpcode() == ISD::CALLSEQ_START && 5175 "Expected a CALLSEQ_STARTSDNode."); 5176 5177 // The last operand is the chain, except when the node has glue. If the node 5178 // has glue, then the last operand is the glue, and the chain is the second 5179 // last operand. 5180 SDValue LastValue = CallSeqStart.getValue(CallSeqStart->getNumValues() - 1); 5181 if (LastValue.getValueType() != MVT::Glue) 5182 return LastValue; 5183 5184 return CallSeqStart.getValue(CallSeqStart->getNumValues() - 2); 5185 } 5186 5187 // Creates the node that moves a functions address into the count register 5188 // to prepare for an indirect call instruction. 5189 static void prepareIndirectCall(SelectionDAG &DAG, SDValue &Callee, 5190 SDValue &Glue, SDValue &Chain, 5191 const SDLoc &dl) { 5192 SDValue MTCTROps[] = {Chain, Callee, Glue}; 5193 EVT ReturnTypes[] = {MVT::Other, MVT::Glue}; 5194 Chain = DAG.getNode(PPCISD::MTCTR, dl, makeArrayRef(ReturnTypes, 2), 5195 makeArrayRef(MTCTROps, Glue.getNode() ? 3 : 2)); 5196 // The glue is the second value produced. 5197 Glue = Chain.getValue(1); 5198 } 5199 5200 static void prepareDescriptorIndirectCall(SelectionDAG &DAG, SDValue &Callee, 5201 SDValue &Glue, SDValue &Chain, 5202 SDValue CallSeqStart, 5203 ImmutableCallSite CS, const SDLoc &dl, 5204 bool hasNest, 5205 const PPCSubtarget &Subtarget) { 5206 // Function pointers in the 64-bit SVR4 ABI do not point to the function 5207 // entry point, but to the function descriptor (the function entry point 5208 // address is part of the function descriptor though). 5209 // The function descriptor is a three doubleword structure with the 5210 // following fields: function entry point, TOC base address and 5211 // environment pointer. 5212 // Thus for a call through a function pointer, the following actions need 5213 // to be performed: 5214 // 1. Save the TOC of the caller in the TOC save area of its stack 5215 // frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()). 5216 // 2. Load the address of the function entry point from the function 5217 // descriptor. 5218 // 3. Load the TOC of the callee from the function descriptor into r2. 5219 // 4. Load the environment pointer from the function descriptor into 5220 // r11. 5221 // 5. Branch to the function entry point address. 5222 // 6. On return of the callee, the TOC of the caller needs to be 5223 // restored (this is done in FinishCall()). 5224 // 5225 // The loads are scheduled at the beginning of the call sequence, and the 5226 // register copies are flagged together to ensure that no other 5227 // operations can be scheduled in between. E.g. without flagging the 5228 // copies together, a TOC access in the caller could be scheduled between 5229 // the assignment of the callee TOC and the branch to the callee, which leads 5230 // to incorrect code. 5231 5232 // Start by loading the function address from the descriptor. 5233 SDValue LDChain = getOutputChainFromCallSeq(CallSeqStart); 5234 auto MMOFlags = Subtarget.hasInvariantFunctionDescriptors() 5235 ? (MachineMemOperand::MODereferenceable | 5236 MachineMemOperand::MOInvariant) 5237 : MachineMemOperand::MONone; 5238 5239 MachinePointerInfo MPI(CS ? CS.getCalledValue() : nullptr); 5240 5241 // Registers used in building the DAG. 5242 const MCRegister EnvPtrReg = Subtarget.getEnvironmentPointerRegister(); 5243 const MCRegister TOCReg = Subtarget.getTOCPointerRegister(); 5244 5245 // Offsets of descriptor members. 5246 const unsigned TOCAnchorOffset = Subtarget.descriptorTOCAnchorOffset(); 5247 const unsigned EnvPtrOffset = Subtarget.descriptorEnvironmentPointerOffset(); 5248 5249 const MVT RegVT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32; 5250 const unsigned Alignment = Subtarget.isPPC64() ? 8 : 4; 5251 5252 // One load for the functions entry point address. 5253 SDValue LoadFuncPtr = DAG.getLoad(RegVT, dl, LDChain, Callee, MPI, 5254 Alignment, MMOFlags); 5255 5256 // One for loading the TOC anchor for the module that contains the called 5257 // function. 5258 SDValue TOCOff = DAG.getIntPtrConstant(TOCAnchorOffset, dl); 5259 SDValue AddTOC = DAG.getNode(ISD::ADD, dl, RegVT, Callee, TOCOff); 5260 SDValue TOCPtr = 5261 DAG.getLoad(RegVT, dl, LDChain, AddTOC, 5262 MPI.getWithOffset(TOCAnchorOffset), Alignment, MMOFlags); 5263 5264 // One for loading the environment pointer. 5265 SDValue PtrOff = DAG.getIntPtrConstant(EnvPtrOffset, dl); 5266 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, RegVT, Callee, PtrOff); 5267 SDValue LoadEnvPtr = 5268 DAG.getLoad(RegVT, dl, LDChain, AddPtr, 5269 MPI.getWithOffset(EnvPtrOffset), Alignment, MMOFlags); 5270 5271 5272 // Then copy the newly loaded TOC anchor to the TOC pointer. 5273 SDValue TOCVal = DAG.getCopyToReg(Chain, dl, TOCReg, TOCPtr, Glue); 5274 Chain = TOCVal.getValue(0); 5275 Glue = TOCVal.getValue(1); 5276 5277 // If the function call has an explicit 'nest' parameter, it takes the 5278 // place of the environment pointer. 5279 assert((!hasNest || !Subtarget.isAIXABI()) && 5280 "Nest parameter is not supported on AIX."); 5281 if (!hasNest) { 5282 SDValue EnvVal = DAG.getCopyToReg(Chain, dl, EnvPtrReg, LoadEnvPtr, Glue); 5283 Chain = EnvVal.getValue(0); 5284 Glue = EnvVal.getValue(1); 5285 } 5286 5287 // The rest of the indirect call sequence is the same as the non-descriptor 5288 // DAG. 5289 prepareIndirectCall(DAG, LoadFuncPtr, Glue, Chain, dl); 5290 } 5291 5292 static void 5293 buildCallOperands(SmallVectorImpl<SDValue> &Ops, CallingConv::ID CallConv, 5294 const SDLoc &dl, bool isTailCall, bool isVarArg, 5295 bool isPatchPoint, bool hasNest, SelectionDAG &DAG, 5296 SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, 5297 SDValue Glue, SDValue Chain, SDValue &Callee, int SPDiff, 5298 const PPCSubtarget &Subtarget, bool isIndirect) { 5299 const bool IsPPC64 = Subtarget.isPPC64(); 5300 // MVT for a general purpose register. 5301 const MVT RegVT = IsPPC64 ? MVT::i64 : MVT::i32; 5302 5303 // First operand is always the chain. 5304 Ops.push_back(Chain); 5305 5306 // If it's a direct call pass the callee as the second operand. 5307 if (!isIndirect) 5308 Ops.push_back(Callee); 5309 else { 5310 assert(!isPatchPoint && "Patch point call are not indirect."); 5311 5312 // For the TOC based ABIs, we have saved the TOC pointer to the linkage area 5313 // on the stack (this would have been done in `LowerCall_64SVR4` or 5314 // `LowerCall_AIX`). The call instruction is a pseudo instruction that 5315 // represents both the indirect branch and a load that restores the TOC 5316 // pointer from the linkage area. The operand for the TOC restore is an add 5317 // of the TOC save offset to the stack pointer. This must be the second 5318 // operand: after the chain input but before any other variadic arguments. 5319 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) { 5320 const MCRegister StackPtrReg = Subtarget.getStackPointerRegister(); 5321 5322 SDValue StackPtr = DAG.getRegister(StackPtrReg, RegVT); 5323 unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset(); 5324 SDValue TOCOff = DAG.getIntPtrConstant(TOCSaveOffset, dl); 5325 SDValue AddTOC = DAG.getNode(ISD::ADD, dl, RegVT, StackPtr, TOCOff); 5326 Ops.push_back(AddTOC); 5327 } 5328 5329 // Add the register used for the environment pointer. 5330 if (Subtarget.usesFunctionDescriptors() && !hasNest) 5331 Ops.push_back(DAG.getRegister(Subtarget.getEnvironmentPointerRegister(), 5332 RegVT)); 5333 5334 5335 // Add CTR register as callee so a bctr can be emitted later. 5336 if (isTailCall) 5337 Ops.push_back(DAG.getRegister(IsPPC64 ? PPC::CTR8 : PPC::CTR, RegVT)); 5338 } 5339 5340 // If this is a tail call add stack pointer delta. 5341 if (isTailCall) 5342 Ops.push_back(DAG.getConstant(SPDiff, dl, MVT::i32)); 5343 5344 // Add argument registers to the end of the list so that they are known live 5345 // into the call. 5346 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) 5347 Ops.push_back(DAG.getRegister(RegsToPass[i].first, 5348 RegsToPass[i].second.getValueType())); 5349 5350 // We cannot add R2/X2 as an operand here for PATCHPOINT, because there is 5351 // no way to mark dependencies as implicit here. 5352 // We will add the R2/X2 dependency in EmitInstrWithCustomInserter. 5353 if ((Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) && !isPatchPoint) 5354 Ops.push_back(DAG.getRegister(Subtarget.getTOCPointerRegister(), RegVT)); 5355 5356 // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls 5357 if (isVarArg && Subtarget.is32BitELFABI()) 5358 Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32)); 5359 5360 // Add a register mask operand representing the call-preserved registers. 5361 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo(); 5362 const uint32_t *Mask = 5363 TRI->getCallPreservedMask(DAG.getMachineFunction(), CallConv); 5364 assert(Mask && "Missing call preserved mask for calling convention"); 5365 Ops.push_back(DAG.getRegisterMask(Mask)); 5366 5367 // If the glue is valid, it is the last operand. 5368 if (Glue.getNode()) 5369 Ops.push_back(Glue); 5370 } 5371 5372 SDValue PPCTargetLowering::FinishCall( 5373 CallingConv::ID CallConv, const SDLoc &dl, bool isTailCall, bool isVarArg, 5374 bool isPatchPoint, bool hasNest, SelectionDAG &DAG, 5375 SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, SDValue Glue, 5376 SDValue Chain, SDValue CallSeqStart, SDValue &Callee, int SPDiff, 5377 unsigned NumBytes, const SmallVectorImpl<ISD::InputArg> &Ins, 5378 SmallVectorImpl<SDValue> &InVals, ImmutableCallSite CS) const { 5379 5380 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) 5381 setUsesTOCBasePtr(DAG); 5382 5383 const bool isIndirect = isIndirectCall(Callee, DAG, Subtarget, isPatchPoint); 5384 unsigned CallOpc = getCallOpcode(isIndirect, isPatchPoint, isTailCall, 5385 DAG.getMachineFunction().getFunction(), 5386 Callee, Subtarget, DAG.getTarget()); 5387 5388 if (!isIndirect) 5389 Callee = transformCallee(Callee, DAG, dl, Subtarget); 5390 else if (Subtarget.usesFunctionDescriptors()) 5391 prepareDescriptorIndirectCall(DAG, Callee, Glue, Chain, CallSeqStart, CS, 5392 dl, hasNest, Subtarget); 5393 else 5394 prepareIndirectCall(DAG, Callee, Glue, Chain, dl); 5395 5396 // Build the operand list for the call instruction. 5397 SmallVector<SDValue, 8> Ops; 5398 buildCallOperands(Ops, CallConv, dl, isTailCall, isVarArg, isPatchPoint, 5399 hasNest, DAG, RegsToPass, Glue, Chain, Callee, SPDiff, 5400 Subtarget, isIndirect); 5401 5402 // Emit tail call. 5403 if (isTailCall) { 5404 assert(((Callee.getOpcode() == ISD::Register && 5405 cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) || 5406 Callee.getOpcode() == ISD::TargetExternalSymbol || 5407 Callee.getOpcode() == ISD::TargetGlobalAddress || 5408 isa<ConstantSDNode>(Callee)) && 5409 "Expecting a global address, external symbol, absolute value or " 5410 "register"); 5411 assert(CallOpc == PPCISD::TC_RETURN && 5412 "Unexpected call opcode for a tail call."); 5413 DAG.getMachineFunction().getFrameInfo().setHasTailCall(); 5414 return DAG.getNode(CallOpc, dl, MVT::Other, Ops); 5415 } 5416 5417 std::array<EVT, 2> ReturnTypes = {{MVT::Other, MVT::Glue}}; 5418 Chain = DAG.getNode(CallOpc, dl, ReturnTypes, Ops); 5419 Glue = Chain.getValue(1); 5420 5421 // When performing tail call optimization the callee pops its arguments off 5422 // the stack. Account for this here so these bytes can be pushed back on in 5423 // PPCFrameLowering::eliminateCallFramePseudoInstr. 5424 int BytesCalleePops = (CallConv == CallingConv::Fast && 5425 getTargetMachine().Options.GuaranteedTailCallOpt) 5426 ? NumBytes 5427 : 0; 5428 5429 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true), 5430 DAG.getIntPtrConstant(BytesCalleePops, dl, true), 5431 Glue, dl); 5432 Glue = Chain.getValue(1); 5433 5434 return LowerCallResult(Chain, Glue, CallConv, isVarArg, Ins, dl, DAG, InVals); 5435 } 5436 5437 SDValue 5438 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI, 5439 SmallVectorImpl<SDValue> &InVals) const { 5440 SelectionDAG &DAG = CLI.DAG; 5441 SDLoc &dl = CLI.DL; 5442 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs; 5443 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals; 5444 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins; 5445 SDValue Chain = CLI.Chain; 5446 SDValue Callee = CLI.Callee; 5447 bool &isTailCall = CLI.IsTailCall; 5448 CallingConv::ID CallConv = CLI.CallConv; 5449 bool isVarArg = CLI.IsVarArg; 5450 bool isPatchPoint = CLI.IsPatchPoint; 5451 ImmutableCallSite CS = CLI.CS; 5452 5453 if (isTailCall) { 5454 if (Subtarget.useLongCalls() && !(CS && CS.isMustTailCall())) 5455 isTailCall = false; 5456 else if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) 5457 isTailCall = 5458 IsEligibleForTailCallOptimization_64SVR4(Callee, CallConv, CS, 5459 isVarArg, Outs, Ins, DAG); 5460 else 5461 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg, 5462 Ins, DAG); 5463 if (isTailCall) { 5464 ++NumTailCalls; 5465 if (!getTargetMachine().Options.GuaranteedTailCallOpt) 5466 ++NumSiblingCalls; 5467 5468 assert(isa<GlobalAddressSDNode>(Callee) && 5469 "Callee should be an llvm::Function object."); 5470 LLVM_DEBUG( 5471 const GlobalValue *GV = 5472 cast<GlobalAddressSDNode>(Callee)->getGlobal(); 5473 const unsigned Width = 5474 80 - strlen("TCO caller: ") - strlen(", callee linkage: 0, 0"); 5475 dbgs() << "TCO caller: " 5476 << left_justify(DAG.getMachineFunction().getName(), Width) 5477 << ", callee linkage: " << GV->getVisibility() << ", " 5478 << GV->getLinkage() << "\n"); 5479 } 5480 } 5481 5482 if (!isTailCall && CS && CS.isMustTailCall()) 5483 report_fatal_error("failed to perform tail call elimination on a call " 5484 "site marked musttail"); 5485 5486 // When long calls (i.e. indirect calls) are always used, calls are always 5487 // made via function pointer. If we have a function name, first translate it 5488 // into a pointer. 5489 if (Subtarget.useLongCalls() && isa<GlobalAddressSDNode>(Callee) && 5490 !isTailCall) 5491 Callee = LowerGlobalAddress(Callee, DAG); 5492 5493 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) 5494 return LowerCall_64SVR4(Chain, Callee, CallConv, isVarArg, 5495 isTailCall, isPatchPoint, Outs, OutVals, Ins, 5496 dl, DAG, InVals, CS); 5497 5498 if (Subtarget.isSVR4ABI()) 5499 return LowerCall_32SVR4(Chain, Callee, CallConv, isVarArg, 5500 isTailCall, isPatchPoint, Outs, OutVals, Ins, 5501 dl, DAG, InVals, CS); 5502 5503 if (Subtarget.isAIXABI()) 5504 return LowerCall_AIX(Chain, Callee, CallConv, isVarArg, 5505 isTailCall, isPatchPoint, Outs, OutVals, Ins, 5506 dl, DAG, InVals, CS); 5507 5508 return LowerCall_Darwin(Chain, Callee, CallConv, isVarArg, 5509 isTailCall, isPatchPoint, Outs, OutVals, Ins, 5510 dl, DAG, InVals, CS); 5511 } 5512 5513 SDValue PPCTargetLowering::LowerCall_32SVR4( 5514 SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg, 5515 bool isTailCall, bool isPatchPoint, 5516 const SmallVectorImpl<ISD::OutputArg> &Outs, 5517 const SmallVectorImpl<SDValue> &OutVals, 5518 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 5519 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 5520 ImmutableCallSite CS) const { 5521 // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description 5522 // of the 32-bit SVR4 ABI stack frame layout. 5523 5524 assert((CallConv == CallingConv::C || 5525 CallConv == CallingConv::Cold || 5526 CallConv == CallingConv::Fast) && "Unknown calling convention!"); 5527 5528 unsigned PtrByteSize = 4; 5529 5530 MachineFunction &MF = DAG.getMachineFunction(); 5531 5532 // Mark this function as potentially containing a function that contains a 5533 // tail call. As a consequence the frame pointer will be used for dynamicalloc 5534 // and restoring the callers stack pointer in this functions epilog. This is 5535 // done because by tail calling the called function might overwrite the value 5536 // in this function's (MF) stack pointer stack slot 0(SP). 5537 if (getTargetMachine().Options.GuaranteedTailCallOpt && 5538 CallConv == CallingConv::Fast) 5539 MF.getInfo<PPCFunctionInfo>()->setHasFastCall(); 5540 5541 // Count how many bytes are to be pushed on the stack, including the linkage 5542 // area, parameter list area and the part of the local variable space which 5543 // contains copies of aggregates which are passed by value. 5544 5545 // Assign locations to all of the outgoing arguments. 5546 SmallVector<CCValAssign, 16> ArgLocs; 5547 PPCCCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext()); 5548 5549 // Reserve space for the linkage area on the stack. 5550 CCInfo.AllocateStack(Subtarget.getFrameLowering()->getLinkageSize(), 5551 PtrByteSize); 5552 if (useSoftFloat()) 5553 CCInfo.PreAnalyzeCallOperands(Outs); 5554 5555 if (isVarArg) { 5556 // Handle fixed and variable vector arguments differently. 5557 // Fixed vector arguments go into registers as long as registers are 5558 // available. Variable vector arguments always go into memory. 5559 unsigned NumArgs = Outs.size(); 5560 5561 for (unsigned i = 0; i != NumArgs; ++i) { 5562 MVT ArgVT = Outs[i].VT; 5563 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 5564 bool Result; 5565 5566 if (Outs[i].IsFixed) { 5567 Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, 5568 CCInfo); 5569 } else { 5570 Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full, 5571 ArgFlags, CCInfo); 5572 } 5573 5574 if (Result) { 5575 #ifndef NDEBUG 5576 errs() << "Call operand #" << i << " has unhandled type " 5577 << EVT(ArgVT).getEVTString() << "\n"; 5578 #endif 5579 llvm_unreachable(nullptr); 5580 } 5581 } 5582 } else { 5583 // All arguments are treated the same. 5584 CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4); 5585 } 5586 CCInfo.clearWasPPCF128(); 5587 5588 // Assign locations to all of the outgoing aggregate by value arguments. 5589 SmallVector<CCValAssign, 16> ByValArgLocs; 5590 CCState CCByValInfo(CallConv, isVarArg, MF, ByValArgLocs, *DAG.getContext()); 5591 5592 // Reserve stack space for the allocations in CCInfo. 5593 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize); 5594 5595 CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal); 5596 5597 // Size of the linkage area, parameter list area and the part of the local 5598 // space variable where copies of aggregates which are passed by value are 5599 // stored. 5600 unsigned NumBytes = CCByValInfo.getNextStackOffset(); 5601 5602 // Calculate by how many bytes the stack has to be adjusted in case of tail 5603 // call optimization. 5604 int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes); 5605 5606 // Adjust the stack pointer for the new arguments... 5607 // These operations are automatically eliminated by the prolog/epilog pass 5608 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 5609 SDValue CallSeqStart = Chain; 5610 5611 // Load the return address and frame pointer so it can be moved somewhere else 5612 // later. 5613 SDValue LROp, FPOp; 5614 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl); 5615 5616 // Set up a copy of the stack pointer for use loading and storing any 5617 // arguments that may not fit in the registers available for argument 5618 // passing. 5619 SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32); 5620 5621 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 5622 SmallVector<TailCallArgumentInfo, 8> TailCallArguments; 5623 SmallVector<SDValue, 8> MemOpChains; 5624 5625 bool seenFloatArg = false; 5626 // Walk the register/memloc assignments, inserting copies/loads. 5627 // i - Tracks the index into the list of registers allocated for the call 5628 // RealArgIdx - Tracks the index into the list of actual function arguments 5629 // j - Tracks the index into the list of byval arguments 5630 for (unsigned i = 0, RealArgIdx = 0, j = 0, e = ArgLocs.size(); 5631 i != e; 5632 ++i, ++RealArgIdx) { 5633 CCValAssign &VA = ArgLocs[i]; 5634 SDValue Arg = OutVals[RealArgIdx]; 5635 ISD::ArgFlagsTy Flags = Outs[RealArgIdx].Flags; 5636 5637 if (Flags.isByVal()) { 5638 // Argument is an aggregate which is passed by value, thus we need to 5639 // create a copy of it in the local variable space of the current stack 5640 // frame (which is the stack frame of the caller) and pass the address of 5641 // this copy to the callee. 5642 assert((j < ByValArgLocs.size()) && "Index out of bounds!"); 5643 CCValAssign &ByValVA = ByValArgLocs[j++]; 5644 assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!"); 5645 5646 // Memory reserved in the local variable space of the callers stack frame. 5647 unsigned LocMemOffset = ByValVA.getLocMemOffset(); 5648 5649 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 5650 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()), 5651 StackPtr, PtrOff); 5652 5653 // Create a copy of the argument in the local area of the current 5654 // stack frame. 5655 SDValue MemcpyCall = 5656 CreateCopyOfByValArgument(Arg, PtrOff, 5657 CallSeqStart.getNode()->getOperand(0), 5658 Flags, DAG, dl); 5659 5660 // This must go outside the CALLSEQ_START..END. 5661 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, NumBytes, 0, 5662 SDLoc(MemcpyCall)); 5663 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(), 5664 NewCallSeqStart.getNode()); 5665 Chain = CallSeqStart = NewCallSeqStart; 5666 5667 // Pass the address of the aggregate copy on the stack either in a 5668 // physical register or in the parameter list area of the current stack 5669 // frame to the callee. 5670 Arg = PtrOff; 5671 } 5672 5673 // When useCRBits() is true, there can be i1 arguments. 5674 // It is because getRegisterType(MVT::i1) => MVT::i1, 5675 // and for other integer types getRegisterType() => MVT::i32. 5676 // Extend i1 and ensure callee will get i32. 5677 if (Arg.getValueType() == MVT::i1) 5678 Arg = DAG.getNode(Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, 5679 dl, MVT::i32, Arg); 5680 5681 if (VA.isRegLoc()) { 5682 seenFloatArg |= VA.getLocVT().isFloatingPoint(); 5683 // Put argument in a physical register. 5684 if (Subtarget.hasSPE() && Arg.getValueType() == MVT::f64) { 5685 bool IsLE = Subtarget.isLittleEndian(); 5686 SDValue SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg, 5687 DAG.getIntPtrConstant(IsLE ? 0 : 1, dl)); 5688 RegsToPass.push_back(std::make_pair(VA.getLocReg(), SVal.getValue(0))); 5689 SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg, 5690 DAG.getIntPtrConstant(IsLE ? 1 : 0, dl)); 5691 RegsToPass.push_back(std::make_pair(ArgLocs[++i].getLocReg(), 5692 SVal.getValue(0))); 5693 } else 5694 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 5695 } else { 5696 // Put argument in the parameter list area of the current stack frame. 5697 assert(VA.isMemLoc()); 5698 unsigned LocMemOffset = VA.getLocMemOffset(); 5699 5700 if (!isTailCall) { 5701 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 5702 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()), 5703 StackPtr, PtrOff); 5704 5705 MemOpChains.push_back( 5706 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo())); 5707 } else { 5708 // Calculate and remember argument location. 5709 CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset, 5710 TailCallArguments); 5711 } 5712 } 5713 } 5714 5715 if (!MemOpChains.empty()) 5716 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 5717 5718 // Build a sequence of copy-to-reg nodes chained together with token chain 5719 // and flag operands which copy the outgoing args into the appropriate regs. 5720 SDValue InFlag; 5721 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 5722 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 5723 RegsToPass[i].second, InFlag); 5724 InFlag = Chain.getValue(1); 5725 } 5726 5727 // Set CR bit 6 to true if this is a vararg call with floating args passed in 5728 // registers. 5729 if (isVarArg) { 5730 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue); 5731 SDValue Ops[] = { Chain, InFlag }; 5732 5733 Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET, 5734 dl, VTs, makeArrayRef(Ops, InFlag.getNode() ? 2 : 1)); 5735 5736 InFlag = Chain.getValue(1); 5737 } 5738 5739 if (isTailCall) 5740 PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp, 5741 TailCallArguments); 5742 5743 return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint, 5744 /* unused except on PPC64 ELFv1 */ false, DAG, 5745 RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff, 5746 NumBytes, Ins, InVals, CS); 5747 } 5748 5749 // Copy an argument into memory, being careful to do this outside the 5750 // call sequence for the call to which the argument belongs. 5751 SDValue PPCTargetLowering::createMemcpyOutsideCallSeq( 5752 SDValue Arg, SDValue PtrOff, SDValue CallSeqStart, ISD::ArgFlagsTy Flags, 5753 SelectionDAG &DAG, const SDLoc &dl) const { 5754 SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff, 5755 CallSeqStart.getNode()->getOperand(0), 5756 Flags, DAG, dl); 5757 // The MEMCPY must go outside the CALLSEQ_START..END. 5758 int64_t FrameSize = CallSeqStart.getConstantOperandVal(1); 5759 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, FrameSize, 0, 5760 SDLoc(MemcpyCall)); 5761 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(), 5762 NewCallSeqStart.getNode()); 5763 return NewCallSeqStart; 5764 } 5765 5766 SDValue PPCTargetLowering::LowerCall_64SVR4( 5767 SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg, 5768 bool isTailCall, bool isPatchPoint, 5769 const SmallVectorImpl<ISD::OutputArg> &Outs, 5770 const SmallVectorImpl<SDValue> &OutVals, 5771 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 5772 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 5773 ImmutableCallSite CS) const { 5774 bool isELFv2ABI = Subtarget.isELFv2ABI(); 5775 bool isLittleEndian = Subtarget.isLittleEndian(); 5776 unsigned NumOps = Outs.size(); 5777 bool hasNest = false; 5778 bool IsSibCall = false; 5779 5780 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 5781 unsigned PtrByteSize = 8; 5782 5783 MachineFunction &MF = DAG.getMachineFunction(); 5784 5785 if (isTailCall && !getTargetMachine().Options.GuaranteedTailCallOpt) 5786 IsSibCall = true; 5787 5788 // Mark this function as potentially containing a function that contains a 5789 // tail call. As a consequence the frame pointer will be used for dynamicalloc 5790 // and restoring the callers stack pointer in this functions epilog. This is 5791 // done because by tail calling the called function might overwrite the value 5792 // in this function's (MF) stack pointer stack slot 0(SP). 5793 if (getTargetMachine().Options.GuaranteedTailCallOpt && 5794 CallConv == CallingConv::Fast) 5795 MF.getInfo<PPCFunctionInfo>()->setHasFastCall(); 5796 5797 assert(!(CallConv == CallingConv::Fast && isVarArg) && 5798 "fastcc not supported on varargs functions"); 5799 5800 // Count how many bytes are to be pushed on the stack, including the linkage 5801 // area, and parameter passing area. On ELFv1, the linkage area is 48 bytes 5802 // reserved space for [SP][CR][LR][2 x unused][TOC]; on ELFv2, the linkage 5803 // area is 32 bytes reserved space for [SP][CR][LR][TOC]. 5804 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 5805 unsigned NumBytes = LinkageSize; 5806 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 5807 unsigned &QFPR_idx = FPR_idx; 5808 5809 static const MCPhysReg GPR[] = { 5810 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 5811 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 5812 }; 5813 static const MCPhysReg VR[] = { 5814 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 5815 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 5816 }; 5817 5818 const unsigned NumGPRs = array_lengthof(GPR); 5819 const unsigned NumFPRs = useSoftFloat() ? 0 : 13; 5820 const unsigned NumVRs = array_lengthof(VR); 5821 const unsigned NumQFPRs = NumFPRs; 5822 5823 // On ELFv2, we can avoid allocating the parameter area if all the arguments 5824 // can be passed to the callee in registers. 5825 // For the fast calling convention, there is another check below. 5826 // Note: We should keep consistent with LowerFormalArguments_64SVR4() 5827 bool HasParameterArea = !isELFv2ABI || isVarArg || CallConv == CallingConv::Fast; 5828 if (!HasParameterArea) { 5829 unsigned ParamAreaSize = NumGPRs * PtrByteSize; 5830 unsigned AvailableFPRs = NumFPRs; 5831 unsigned AvailableVRs = NumVRs; 5832 unsigned NumBytesTmp = NumBytes; 5833 for (unsigned i = 0; i != NumOps; ++i) { 5834 if (Outs[i].Flags.isNest()) continue; 5835 if (CalculateStackSlotUsed(Outs[i].VT, Outs[i].ArgVT, Outs[i].Flags, 5836 PtrByteSize, LinkageSize, ParamAreaSize, 5837 NumBytesTmp, AvailableFPRs, AvailableVRs, 5838 Subtarget.hasQPX())) 5839 HasParameterArea = true; 5840 } 5841 } 5842 5843 // When using the fast calling convention, we don't provide backing for 5844 // arguments that will be in registers. 5845 unsigned NumGPRsUsed = 0, NumFPRsUsed = 0, NumVRsUsed = 0; 5846 5847 // Avoid allocating parameter area for fastcc functions if all the arguments 5848 // can be passed in the registers. 5849 if (CallConv == CallingConv::Fast) 5850 HasParameterArea = false; 5851 5852 // Add up all the space actually used. 5853 for (unsigned i = 0; i != NumOps; ++i) { 5854 ISD::ArgFlagsTy Flags = Outs[i].Flags; 5855 EVT ArgVT = Outs[i].VT; 5856 EVT OrigVT = Outs[i].ArgVT; 5857 5858 if (Flags.isNest()) 5859 continue; 5860 5861 if (CallConv == CallingConv::Fast) { 5862 if (Flags.isByVal()) { 5863 NumGPRsUsed += (Flags.getByValSize()+7)/8; 5864 if (NumGPRsUsed > NumGPRs) 5865 HasParameterArea = true; 5866 } else { 5867 switch (ArgVT.getSimpleVT().SimpleTy) { 5868 default: llvm_unreachable("Unexpected ValueType for argument!"); 5869 case MVT::i1: 5870 case MVT::i32: 5871 case MVT::i64: 5872 if (++NumGPRsUsed <= NumGPRs) 5873 continue; 5874 break; 5875 case MVT::v4i32: 5876 case MVT::v8i16: 5877 case MVT::v16i8: 5878 case MVT::v2f64: 5879 case MVT::v2i64: 5880 case MVT::v1i128: 5881 case MVT::f128: 5882 if (++NumVRsUsed <= NumVRs) 5883 continue; 5884 break; 5885 case MVT::v4f32: 5886 // When using QPX, this is handled like a FP register, otherwise, it 5887 // is an Altivec register. 5888 if (Subtarget.hasQPX()) { 5889 if (++NumFPRsUsed <= NumFPRs) 5890 continue; 5891 } else { 5892 if (++NumVRsUsed <= NumVRs) 5893 continue; 5894 } 5895 break; 5896 case MVT::f32: 5897 case MVT::f64: 5898 case MVT::v4f64: // QPX 5899 case MVT::v4i1: // QPX 5900 if (++NumFPRsUsed <= NumFPRs) 5901 continue; 5902 break; 5903 } 5904 HasParameterArea = true; 5905 } 5906 } 5907 5908 /* Respect alignment of argument on the stack. */ 5909 unsigned Align = 5910 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize); 5911 NumBytes = ((NumBytes + Align - 1) / Align) * Align; 5912 5913 NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize); 5914 if (Flags.isInConsecutiveRegsLast()) 5915 NumBytes = ((NumBytes + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 5916 } 5917 5918 unsigned NumBytesActuallyUsed = NumBytes; 5919 5920 // In the old ELFv1 ABI, 5921 // the prolog code of the callee may store up to 8 GPR argument registers to 5922 // the stack, allowing va_start to index over them in memory if its varargs. 5923 // Because we cannot tell if this is needed on the caller side, we have to 5924 // conservatively assume that it is needed. As such, make sure we have at 5925 // least enough stack space for the caller to store the 8 GPRs. 5926 // In the ELFv2 ABI, we allocate the parameter area iff a callee 5927 // really requires memory operands, e.g. a vararg function. 5928 if (HasParameterArea) 5929 NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize); 5930 else 5931 NumBytes = LinkageSize; 5932 5933 // Tail call needs the stack to be aligned. 5934 if (getTargetMachine().Options.GuaranteedTailCallOpt && 5935 CallConv == CallingConv::Fast) 5936 NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes); 5937 5938 int SPDiff = 0; 5939 5940 // Calculate by how many bytes the stack has to be adjusted in case of tail 5941 // call optimization. 5942 if (!IsSibCall) 5943 SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes); 5944 5945 // To protect arguments on the stack from being clobbered in a tail call, 5946 // force all the loads to happen before doing any other lowering. 5947 if (isTailCall) 5948 Chain = DAG.getStackArgumentTokenFactor(Chain); 5949 5950 // Adjust the stack pointer for the new arguments... 5951 // These operations are automatically eliminated by the prolog/epilog pass 5952 if (!IsSibCall) 5953 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 5954 SDValue CallSeqStart = Chain; 5955 5956 // Load the return address and frame pointer so it can be move somewhere else 5957 // later. 5958 SDValue LROp, FPOp; 5959 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl); 5960 5961 // Set up a copy of the stack pointer for use loading and storing any 5962 // arguments that may not fit in the registers available for argument 5963 // passing. 5964 SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64); 5965 5966 // Figure out which arguments are going to go in registers, and which in 5967 // memory. Also, if this is a vararg function, floating point operations 5968 // must be stored to our stack, and loaded into integer regs as well, if 5969 // any integer regs are available for argument passing. 5970 unsigned ArgOffset = LinkageSize; 5971 5972 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 5973 SmallVector<TailCallArgumentInfo, 8> TailCallArguments; 5974 5975 SmallVector<SDValue, 8> MemOpChains; 5976 for (unsigned i = 0; i != NumOps; ++i) { 5977 SDValue Arg = OutVals[i]; 5978 ISD::ArgFlagsTy Flags = Outs[i].Flags; 5979 EVT ArgVT = Outs[i].VT; 5980 EVT OrigVT = Outs[i].ArgVT; 5981 5982 // PtrOff will be used to store the current argument to the stack if a 5983 // register cannot be found for it. 5984 SDValue PtrOff; 5985 5986 // We re-align the argument offset for each argument, except when using the 5987 // fast calling convention, when we need to make sure we do that only when 5988 // we'll actually use a stack slot. 5989 auto ComputePtrOff = [&]() { 5990 /* Respect alignment of argument on the stack. */ 5991 unsigned Align = 5992 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize); 5993 ArgOffset = ((ArgOffset + Align - 1) / Align) * Align; 5994 5995 PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType()); 5996 5997 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 5998 }; 5999 6000 if (CallConv != CallingConv::Fast) { 6001 ComputePtrOff(); 6002 6003 /* Compute GPR index associated with argument offset. */ 6004 GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize; 6005 GPR_idx = std::min(GPR_idx, NumGPRs); 6006 } 6007 6008 // Promote integers to 64-bit values. 6009 if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) { 6010 // FIXME: Should this use ANY_EXTEND if neither sext nor zext? 6011 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 6012 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg); 6013 } 6014 6015 // FIXME memcpy is used way more than necessary. Correctness first. 6016 // Note: "by value" is code for passing a structure by value, not 6017 // basic types. 6018 if (Flags.isByVal()) { 6019 // Note: Size includes alignment padding, so 6020 // struct x { short a; char b; } 6021 // will have Size = 4. With #pragma pack(1), it will have Size = 3. 6022 // These are the proper values we need for right-justifying the 6023 // aggregate in a parameter register. 6024 unsigned Size = Flags.getByValSize(); 6025 6026 // An empty aggregate parameter takes up no storage and no 6027 // registers. 6028 if (Size == 0) 6029 continue; 6030 6031 if (CallConv == CallingConv::Fast) 6032 ComputePtrOff(); 6033 6034 // All aggregates smaller than 8 bytes must be passed right-justified. 6035 if (Size==1 || Size==2 || Size==4) { 6036 EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32); 6037 if (GPR_idx != NumGPRs) { 6038 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg, 6039 MachinePointerInfo(), VT); 6040 MemOpChains.push_back(Load.getValue(1)); 6041 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6042 6043 ArgOffset += PtrByteSize; 6044 continue; 6045 } 6046 } 6047 6048 if (GPR_idx == NumGPRs && Size < 8) { 6049 SDValue AddPtr = PtrOff; 6050 if (!isLittleEndian) { 6051 SDValue Const = DAG.getConstant(PtrByteSize - Size, dl, 6052 PtrOff.getValueType()); 6053 AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const); 6054 } 6055 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr, 6056 CallSeqStart, 6057 Flags, DAG, dl); 6058 ArgOffset += PtrByteSize; 6059 continue; 6060 } 6061 // Copy entire object into memory. There are cases where gcc-generated 6062 // code assumes it is there, even if it could be put entirely into 6063 // registers. (This is not what the doc says.) 6064 6065 // FIXME: The above statement is likely due to a misunderstanding of the 6066 // documents. All arguments must be copied into the parameter area BY 6067 // THE CALLEE in the event that the callee takes the address of any 6068 // formal argument. That has not yet been implemented. However, it is 6069 // reasonable to use the stack area as a staging area for the register 6070 // load. 6071 6072 // Skip this for small aggregates, as we will use the same slot for a 6073 // right-justified copy, below. 6074 if (Size >= 8) 6075 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff, 6076 CallSeqStart, 6077 Flags, DAG, dl); 6078 6079 // When a register is available, pass a small aggregate right-justified. 6080 if (Size < 8 && GPR_idx != NumGPRs) { 6081 // The easiest way to get this right-justified in a register 6082 // is to copy the structure into the rightmost portion of a 6083 // local variable slot, then load the whole slot into the 6084 // register. 6085 // FIXME: The memcpy seems to produce pretty awful code for 6086 // small aggregates, particularly for packed ones. 6087 // FIXME: It would be preferable to use the slot in the 6088 // parameter save area instead of a new local variable. 6089 SDValue AddPtr = PtrOff; 6090 if (!isLittleEndian) { 6091 SDValue Const = DAG.getConstant(8 - Size, dl, PtrOff.getValueType()); 6092 AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const); 6093 } 6094 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr, 6095 CallSeqStart, 6096 Flags, DAG, dl); 6097 6098 // Load the slot into the register. 6099 SDValue Load = 6100 DAG.getLoad(PtrVT, dl, Chain, PtrOff, MachinePointerInfo()); 6101 MemOpChains.push_back(Load.getValue(1)); 6102 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6103 6104 // Done with this argument. 6105 ArgOffset += PtrByteSize; 6106 continue; 6107 } 6108 6109 // For aggregates larger than PtrByteSize, copy the pieces of the 6110 // object that fit into registers from the parameter save area. 6111 for (unsigned j=0; j<Size; j+=PtrByteSize) { 6112 SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType()); 6113 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const); 6114 if (GPR_idx != NumGPRs) { 6115 SDValue Load = 6116 DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo()); 6117 MemOpChains.push_back(Load.getValue(1)); 6118 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6119 ArgOffset += PtrByteSize; 6120 } else { 6121 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize; 6122 break; 6123 } 6124 } 6125 continue; 6126 } 6127 6128 switch (Arg.getSimpleValueType().SimpleTy) { 6129 default: llvm_unreachable("Unexpected ValueType for argument!"); 6130 case MVT::i1: 6131 case MVT::i32: 6132 case MVT::i64: 6133 if (Flags.isNest()) { 6134 // The 'nest' parameter, if any, is passed in R11. 6135 RegsToPass.push_back(std::make_pair(PPC::X11, Arg)); 6136 hasNest = true; 6137 break; 6138 } 6139 6140 // These can be scalar arguments or elements of an integer array type 6141 // passed directly. Clang may use those instead of "byval" aggregate 6142 // types to avoid forcing arguments to memory unnecessarily. 6143 if (GPR_idx != NumGPRs) { 6144 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg)); 6145 } else { 6146 if (CallConv == CallingConv::Fast) 6147 ComputePtrOff(); 6148 6149 assert(HasParameterArea && 6150 "Parameter area must exist to pass an argument in memory."); 6151 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6152 true, isTailCall, false, MemOpChains, 6153 TailCallArguments, dl); 6154 if (CallConv == CallingConv::Fast) 6155 ArgOffset += PtrByteSize; 6156 } 6157 if (CallConv != CallingConv::Fast) 6158 ArgOffset += PtrByteSize; 6159 break; 6160 case MVT::f32: 6161 case MVT::f64: { 6162 // These can be scalar arguments or elements of a float array type 6163 // passed directly. The latter are used to implement ELFv2 homogenous 6164 // float aggregates. 6165 6166 // Named arguments go into FPRs first, and once they overflow, the 6167 // remaining arguments go into GPRs and then the parameter save area. 6168 // Unnamed arguments for vararg functions always go to GPRs and 6169 // then the parameter save area. For now, put all arguments to vararg 6170 // routines always in both locations (FPR *and* GPR or stack slot). 6171 bool NeedGPROrStack = isVarArg || FPR_idx == NumFPRs; 6172 bool NeededLoad = false; 6173 6174 // First load the argument into the next available FPR. 6175 if (FPR_idx != NumFPRs) 6176 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg)); 6177 6178 // Next, load the argument into GPR or stack slot if needed. 6179 if (!NeedGPROrStack) 6180 ; 6181 else if (GPR_idx != NumGPRs && CallConv != CallingConv::Fast) { 6182 // FIXME: We may want to re-enable this for CallingConv::Fast on the P8 6183 // once we support fp <-> gpr moves. 6184 6185 // In the non-vararg case, this can only ever happen in the 6186 // presence of f32 array types, since otherwise we never run 6187 // out of FPRs before running out of GPRs. 6188 SDValue ArgVal; 6189 6190 // Double values are always passed in a single GPR. 6191 if (Arg.getValueType() != MVT::f32) { 6192 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg); 6193 6194 // Non-array float values are extended and passed in a GPR. 6195 } else if (!Flags.isInConsecutiveRegs()) { 6196 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg); 6197 ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal); 6198 6199 // If we have an array of floats, we collect every odd element 6200 // together with its predecessor into one GPR. 6201 } else if (ArgOffset % PtrByteSize != 0) { 6202 SDValue Lo, Hi; 6203 Lo = DAG.getNode(ISD::BITCAST, dl, MVT::i32, OutVals[i - 1]); 6204 Hi = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg); 6205 if (!isLittleEndian) 6206 std::swap(Lo, Hi); 6207 ArgVal = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi); 6208 6209 // The final element, if even, goes into the first half of a GPR. 6210 } else if (Flags.isInConsecutiveRegsLast()) { 6211 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg); 6212 ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal); 6213 if (!isLittleEndian) 6214 ArgVal = DAG.getNode(ISD::SHL, dl, MVT::i64, ArgVal, 6215 DAG.getConstant(32, dl, MVT::i32)); 6216 6217 // Non-final even elements are skipped; they will be handled 6218 // together the with subsequent argument on the next go-around. 6219 } else 6220 ArgVal = SDValue(); 6221 6222 if (ArgVal.getNode()) 6223 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], ArgVal)); 6224 } else { 6225 if (CallConv == CallingConv::Fast) 6226 ComputePtrOff(); 6227 6228 // Single-precision floating-point values are mapped to the 6229 // second (rightmost) word of the stack doubleword. 6230 if (Arg.getValueType() == MVT::f32 && 6231 !isLittleEndian && !Flags.isInConsecutiveRegs()) { 6232 SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType()); 6233 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour); 6234 } 6235 6236 assert(HasParameterArea && 6237 "Parameter area must exist to pass an argument in memory."); 6238 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6239 true, isTailCall, false, MemOpChains, 6240 TailCallArguments, dl); 6241 6242 NeededLoad = true; 6243 } 6244 // When passing an array of floats, the array occupies consecutive 6245 // space in the argument area; only round up to the next doubleword 6246 // at the end of the array. Otherwise, each float takes 8 bytes. 6247 if (CallConv != CallingConv::Fast || NeededLoad) { 6248 ArgOffset += (Arg.getValueType() == MVT::f32 && 6249 Flags.isInConsecutiveRegs()) ? 4 : 8; 6250 if (Flags.isInConsecutiveRegsLast()) 6251 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 6252 } 6253 break; 6254 } 6255 case MVT::v4f32: 6256 case MVT::v4i32: 6257 case MVT::v8i16: 6258 case MVT::v16i8: 6259 case MVT::v2f64: 6260 case MVT::v2i64: 6261 case MVT::v1i128: 6262 case MVT::f128: 6263 if (!Subtarget.hasQPX()) { 6264 // These can be scalar arguments or elements of a vector array type 6265 // passed directly. The latter are used to implement ELFv2 homogenous 6266 // vector aggregates. 6267 6268 // For a varargs call, named arguments go into VRs or on the stack as 6269 // usual; unnamed arguments always go to the stack or the corresponding 6270 // GPRs when within range. For now, we always put the value in both 6271 // locations (or even all three). 6272 if (isVarArg) { 6273 assert(HasParameterArea && 6274 "Parameter area must exist if we have a varargs call."); 6275 // We could elide this store in the case where the object fits 6276 // entirely in R registers. Maybe later. 6277 SDValue Store = 6278 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 6279 MemOpChains.push_back(Store); 6280 if (VR_idx != NumVRs) { 6281 SDValue Load = 6282 DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo()); 6283 MemOpChains.push_back(Load.getValue(1)); 6284 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load)); 6285 } 6286 ArgOffset += 16; 6287 for (unsigned i=0; i<16; i+=PtrByteSize) { 6288 if (GPR_idx == NumGPRs) 6289 break; 6290 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, 6291 DAG.getConstant(i, dl, PtrVT)); 6292 SDValue Load = 6293 DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo()); 6294 MemOpChains.push_back(Load.getValue(1)); 6295 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6296 } 6297 break; 6298 } 6299 6300 // Non-varargs Altivec params go into VRs or on the stack. 6301 if (VR_idx != NumVRs) { 6302 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg)); 6303 } else { 6304 if (CallConv == CallingConv::Fast) 6305 ComputePtrOff(); 6306 6307 assert(HasParameterArea && 6308 "Parameter area must exist to pass an argument in memory."); 6309 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6310 true, isTailCall, true, MemOpChains, 6311 TailCallArguments, dl); 6312 if (CallConv == CallingConv::Fast) 6313 ArgOffset += 16; 6314 } 6315 6316 if (CallConv != CallingConv::Fast) 6317 ArgOffset += 16; 6318 break; 6319 } // not QPX 6320 6321 assert(Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32 && 6322 "Invalid QPX parameter type"); 6323 6324 LLVM_FALLTHROUGH; 6325 case MVT::v4f64: 6326 case MVT::v4i1: { 6327 bool IsF32 = Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32; 6328 if (isVarArg) { 6329 assert(HasParameterArea && 6330 "Parameter area must exist if we have a varargs call."); 6331 // We could elide this store in the case where the object fits 6332 // entirely in R registers. Maybe later. 6333 SDValue Store = 6334 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 6335 MemOpChains.push_back(Store); 6336 if (QFPR_idx != NumQFPRs) { 6337 SDValue Load = DAG.getLoad(IsF32 ? MVT::v4f32 : MVT::v4f64, dl, Store, 6338 PtrOff, MachinePointerInfo()); 6339 MemOpChains.push_back(Load.getValue(1)); 6340 RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Load)); 6341 } 6342 ArgOffset += (IsF32 ? 16 : 32); 6343 for (unsigned i = 0; i < (IsF32 ? 16U : 32U); i += PtrByteSize) { 6344 if (GPR_idx == NumGPRs) 6345 break; 6346 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, 6347 DAG.getConstant(i, dl, PtrVT)); 6348 SDValue Load = 6349 DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo()); 6350 MemOpChains.push_back(Load.getValue(1)); 6351 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6352 } 6353 break; 6354 } 6355 6356 // Non-varargs QPX params go into registers or on the stack. 6357 if (QFPR_idx != NumQFPRs) { 6358 RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Arg)); 6359 } else { 6360 if (CallConv == CallingConv::Fast) 6361 ComputePtrOff(); 6362 6363 assert(HasParameterArea && 6364 "Parameter area must exist to pass an argument in memory."); 6365 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6366 true, isTailCall, true, MemOpChains, 6367 TailCallArguments, dl); 6368 if (CallConv == CallingConv::Fast) 6369 ArgOffset += (IsF32 ? 16 : 32); 6370 } 6371 6372 if (CallConv != CallingConv::Fast) 6373 ArgOffset += (IsF32 ? 16 : 32); 6374 break; 6375 } 6376 } 6377 } 6378 6379 assert((!HasParameterArea || NumBytesActuallyUsed == ArgOffset) && 6380 "mismatch in size of parameter area"); 6381 (void)NumBytesActuallyUsed; 6382 6383 if (!MemOpChains.empty()) 6384 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 6385 6386 // Check if this is an indirect call (MTCTR/BCTRL). 6387 // See prepareDescriptorIndirectCall and buildCallOperands for more 6388 // information about calls through function pointers in the 64-bit SVR4 ABI. 6389 if (!isTailCall && !isPatchPoint && 6390 !isFunctionGlobalAddress(Callee) && 6391 !isa<ExternalSymbolSDNode>(Callee)) { 6392 // Load r2 into a virtual register and store it to the TOC save area. 6393 setUsesTOCBasePtr(DAG); 6394 SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64); 6395 // TOC save area offset. 6396 unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset(); 6397 SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl); 6398 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 6399 Chain = DAG.getStore( 6400 Val.getValue(1), dl, Val, AddPtr, 6401 MachinePointerInfo::getStack(DAG.getMachineFunction(), TOCSaveOffset)); 6402 // In the ELFv2 ABI, R12 must contain the address of an indirect callee. 6403 // This does not mean the MTCTR instruction must use R12; it's easier 6404 // to model this as an extra parameter, so do that. 6405 if (isELFv2ABI && !isPatchPoint) 6406 RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee)); 6407 } 6408 6409 // Build a sequence of copy-to-reg nodes chained together with token chain 6410 // and flag operands which copy the outgoing args into the appropriate regs. 6411 SDValue InFlag; 6412 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 6413 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 6414 RegsToPass[i].second, InFlag); 6415 InFlag = Chain.getValue(1); 6416 } 6417 6418 if (isTailCall && !IsSibCall) 6419 PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp, 6420 TailCallArguments); 6421 6422 return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint, hasNest, 6423 DAG, RegsToPass, InFlag, Chain, CallSeqStart, Callee, 6424 SPDiff, NumBytes, Ins, InVals, CS); 6425 } 6426 6427 SDValue PPCTargetLowering::LowerCall_Darwin( 6428 SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg, 6429 bool isTailCall, bool isPatchPoint, 6430 const SmallVectorImpl<ISD::OutputArg> &Outs, 6431 const SmallVectorImpl<SDValue> &OutVals, 6432 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 6433 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 6434 ImmutableCallSite CS) const { 6435 unsigned NumOps = Outs.size(); 6436 6437 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 6438 bool isPPC64 = PtrVT == MVT::i64; 6439 unsigned PtrByteSize = isPPC64 ? 8 : 4; 6440 6441 MachineFunction &MF = DAG.getMachineFunction(); 6442 6443 // Mark this function as potentially containing a function that contains a 6444 // tail call. As a consequence the frame pointer will be used for dynamicalloc 6445 // and restoring the callers stack pointer in this functions epilog. This is 6446 // done because by tail calling the called function might overwrite the value 6447 // in this function's (MF) stack pointer stack slot 0(SP). 6448 if (getTargetMachine().Options.GuaranteedTailCallOpt && 6449 CallConv == CallingConv::Fast) 6450 MF.getInfo<PPCFunctionInfo>()->setHasFastCall(); 6451 6452 // Count how many bytes are to be pushed on the stack, including the linkage 6453 // area, and parameter passing area. We start with 24/48 bytes, which is 6454 // prereserved space for [SP][CR][LR][3 x unused]. 6455 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 6456 unsigned NumBytes = LinkageSize; 6457 6458 // Add up all the space actually used. 6459 // In 32-bit non-varargs calls, Altivec parameters all go at the end; usually 6460 // they all go in registers, but we must reserve stack space for them for 6461 // possible use by the caller. In varargs or 64-bit calls, parameters are 6462 // assigned stack space in order, with padding so Altivec parameters are 6463 // 16-byte aligned. 6464 unsigned nAltivecParamsAtEnd = 0; 6465 for (unsigned i = 0; i != NumOps; ++i) { 6466 ISD::ArgFlagsTy Flags = Outs[i].Flags; 6467 EVT ArgVT = Outs[i].VT; 6468 // Varargs Altivec parameters are padded to a 16 byte boundary. 6469 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 || 6470 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 || 6471 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64) { 6472 if (!isVarArg && !isPPC64) { 6473 // Non-varargs Altivec parameters go after all the non-Altivec 6474 // parameters; handle those later so we know how much padding we need. 6475 nAltivecParamsAtEnd++; 6476 continue; 6477 } 6478 // Varargs and 64-bit Altivec parameters are padded to 16 byte boundary. 6479 NumBytes = ((NumBytes+15)/16)*16; 6480 } 6481 NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize); 6482 } 6483 6484 // Allow for Altivec parameters at the end, if needed. 6485 if (nAltivecParamsAtEnd) { 6486 NumBytes = ((NumBytes+15)/16)*16; 6487 NumBytes += 16*nAltivecParamsAtEnd; 6488 } 6489 6490 // The prolog code of the callee may store up to 8 GPR argument registers to 6491 // the stack, allowing va_start to index over them in memory if its varargs. 6492 // Because we cannot tell if this is needed on the caller side, we have to 6493 // conservatively assume that it is needed. As such, make sure we have at 6494 // least enough stack space for the caller to store the 8 GPRs. 6495 NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize); 6496 6497 // Tail call needs the stack to be aligned. 6498 if (getTargetMachine().Options.GuaranteedTailCallOpt && 6499 CallConv == CallingConv::Fast) 6500 NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes); 6501 6502 // Calculate by how many bytes the stack has to be adjusted in case of tail 6503 // call optimization. 6504 int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes); 6505 6506 // To protect arguments on the stack from being clobbered in a tail call, 6507 // force all the loads to happen before doing any other lowering. 6508 if (isTailCall) 6509 Chain = DAG.getStackArgumentTokenFactor(Chain); 6510 6511 // Adjust the stack pointer for the new arguments... 6512 // These operations are automatically eliminated by the prolog/epilog pass 6513 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 6514 SDValue CallSeqStart = Chain; 6515 6516 // Load the return address and frame pointer so it can be move somewhere else 6517 // later. 6518 SDValue LROp, FPOp; 6519 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl); 6520 6521 // Set up a copy of the stack pointer for use loading and storing any 6522 // arguments that may not fit in the registers available for argument 6523 // passing. 6524 SDValue StackPtr; 6525 if (isPPC64) 6526 StackPtr = DAG.getRegister(PPC::X1, MVT::i64); 6527 else 6528 StackPtr = DAG.getRegister(PPC::R1, MVT::i32); 6529 6530 // Figure out which arguments are going to go in registers, and which in 6531 // memory. Also, if this is a vararg function, floating point operations 6532 // must be stored to our stack, and loaded into integer regs as well, if 6533 // any integer regs are available for argument passing. 6534 unsigned ArgOffset = LinkageSize; 6535 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 6536 6537 static const MCPhysReg GPR_32[] = { // 32-bit registers. 6538 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 6539 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 6540 }; 6541 static const MCPhysReg GPR_64[] = { // 64-bit registers. 6542 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 6543 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 6544 }; 6545 static const MCPhysReg VR[] = { 6546 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 6547 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 6548 }; 6549 const unsigned NumGPRs = array_lengthof(GPR_32); 6550 const unsigned NumFPRs = 13; 6551 const unsigned NumVRs = array_lengthof(VR); 6552 6553 const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32; 6554 6555 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 6556 SmallVector<TailCallArgumentInfo, 8> TailCallArguments; 6557 6558 SmallVector<SDValue, 8> MemOpChains; 6559 for (unsigned i = 0; i != NumOps; ++i) { 6560 SDValue Arg = OutVals[i]; 6561 ISD::ArgFlagsTy Flags = Outs[i].Flags; 6562 6563 // PtrOff will be used to store the current argument to the stack if a 6564 // register cannot be found for it. 6565 SDValue PtrOff; 6566 6567 PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType()); 6568 6569 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 6570 6571 // On PPC64, promote integers to 64-bit values. 6572 if (isPPC64 && Arg.getValueType() == MVT::i32) { 6573 // FIXME: Should this use ANY_EXTEND if neither sext nor zext? 6574 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 6575 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg); 6576 } 6577 6578 // FIXME memcpy is used way more than necessary. Correctness first. 6579 // Note: "by value" is code for passing a structure by value, not 6580 // basic types. 6581 if (Flags.isByVal()) { 6582 unsigned Size = Flags.getByValSize(); 6583 // Very small objects are passed right-justified. Everything else is 6584 // passed left-justified. 6585 if (Size==1 || Size==2) { 6586 EVT VT = (Size==1) ? MVT::i8 : MVT::i16; 6587 if (GPR_idx != NumGPRs) { 6588 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg, 6589 MachinePointerInfo(), VT); 6590 MemOpChains.push_back(Load.getValue(1)); 6591 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6592 6593 ArgOffset += PtrByteSize; 6594 } else { 6595 SDValue Const = DAG.getConstant(PtrByteSize - Size, dl, 6596 PtrOff.getValueType()); 6597 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const); 6598 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr, 6599 CallSeqStart, 6600 Flags, DAG, dl); 6601 ArgOffset += PtrByteSize; 6602 } 6603 continue; 6604 } 6605 // Copy entire object into memory. There are cases where gcc-generated 6606 // code assumes it is there, even if it could be put entirely into 6607 // registers. (This is not what the doc says.) 6608 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff, 6609 CallSeqStart, 6610 Flags, DAG, dl); 6611 6612 // For small aggregates (Darwin only) and aggregates >= PtrByteSize, 6613 // copy the pieces of the object that fit into registers from the 6614 // parameter save area. 6615 for (unsigned j=0; j<Size; j+=PtrByteSize) { 6616 SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType()); 6617 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const); 6618 if (GPR_idx != NumGPRs) { 6619 SDValue Load = 6620 DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo()); 6621 MemOpChains.push_back(Load.getValue(1)); 6622 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6623 ArgOffset += PtrByteSize; 6624 } else { 6625 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize; 6626 break; 6627 } 6628 } 6629 continue; 6630 } 6631 6632 switch (Arg.getSimpleValueType().SimpleTy) { 6633 default: llvm_unreachable("Unexpected ValueType for argument!"); 6634 case MVT::i1: 6635 case MVT::i32: 6636 case MVT::i64: 6637 if (GPR_idx != NumGPRs) { 6638 if (Arg.getValueType() == MVT::i1) 6639 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, PtrVT, Arg); 6640 6641 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg)); 6642 } else { 6643 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6644 isPPC64, isTailCall, false, MemOpChains, 6645 TailCallArguments, dl); 6646 } 6647 ArgOffset += PtrByteSize; 6648 break; 6649 case MVT::f32: 6650 case MVT::f64: 6651 if (FPR_idx != NumFPRs) { 6652 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg)); 6653 6654 if (isVarArg) { 6655 SDValue Store = 6656 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 6657 MemOpChains.push_back(Store); 6658 6659 // Float varargs are always shadowed in available integer registers 6660 if (GPR_idx != NumGPRs) { 6661 SDValue Load = 6662 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo()); 6663 MemOpChains.push_back(Load.getValue(1)); 6664 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6665 } 6666 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && !isPPC64){ 6667 SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType()); 6668 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour); 6669 SDValue Load = 6670 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo()); 6671 MemOpChains.push_back(Load.getValue(1)); 6672 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6673 } 6674 } else { 6675 // If we have any FPRs remaining, we may also have GPRs remaining. 6676 // Args passed in FPRs consume either 1 (f32) or 2 (f64) available 6677 // GPRs. 6678 if (GPR_idx != NumGPRs) 6679 ++GPR_idx; 6680 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && 6681 !isPPC64) // PPC64 has 64-bit GPR's obviously :) 6682 ++GPR_idx; 6683 } 6684 } else 6685 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6686 isPPC64, isTailCall, false, MemOpChains, 6687 TailCallArguments, dl); 6688 if (isPPC64) 6689 ArgOffset += 8; 6690 else 6691 ArgOffset += Arg.getValueType() == MVT::f32 ? 4 : 8; 6692 break; 6693 case MVT::v4f32: 6694 case MVT::v4i32: 6695 case MVT::v8i16: 6696 case MVT::v16i8: 6697 if (isVarArg) { 6698 // These go aligned on the stack, or in the corresponding R registers 6699 // when within range. The Darwin PPC ABI doc claims they also go in 6700 // V registers; in fact gcc does this only for arguments that are 6701 // prototyped, not for those that match the ... We do it for all 6702 // arguments, seems to work. 6703 while (ArgOffset % 16 !=0) { 6704 ArgOffset += PtrByteSize; 6705 if (GPR_idx != NumGPRs) 6706 GPR_idx++; 6707 } 6708 // We could elide this store in the case where the object fits 6709 // entirely in R registers. Maybe later. 6710 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, 6711 DAG.getConstant(ArgOffset, dl, PtrVT)); 6712 SDValue Store = 6713 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 6714 MemOpChains.push_back(Store); 6715 if (VR_idx != NumVRs) { 6716 SDValue Load = 6717 DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo()); 6718 MemOpChains.push_back(Load.getValue(1)); 6719 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load)); 6720 } 6721 ArgOffset += 16; 6722 for (unsigned i=0; i<16; i+=PtrByteSize) { 6723 if (GPR_idx == NumGPRs) 6724 break; 6725 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, 6726 DAG.getConstant(i, dl, PtrVT)); 6727 SDValue Load = 6728 DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo()); 6729 MemOpChains.push_back(Load.getValue(1)); 6730 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6731 } 6732 break; 6733 } 6734 6735 // Non-varargs Altivec params generally go in registers, but have 6736 // stack space allocated at the end. 6737 if (VR_idx != NumVRs) { 6738 // Doesn't have GPR space allocated. 6739 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg)); 6740 } else if (nAltivecParamsAtEnd==0) { 6741 // We are emitting Altivec params in order. 6742 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6743 isPPC64, isTailCall, true, MemOpChains, 6744 TailCallArguments, dl); 6745 ArgOffset += 16; 6746 } 6747 break; 6748 } 6749 } 6750 // If all Altivec parameters fit in registers, as they usually do, 6751 // they get stack space following the non-Altivec parameters. We 6752 // don't track this here because nobody below needs it. 6753 // If there are more Altivec parameters than fit in registers emit 6754 // the stores here. 6755 if (!isVarArg && nAltivecParamsAtEnd > NumVRs) { 6756 unsigned j = 0; 6757 // Offset is aligned; skip 1st 12 params which go in V registers. 6758 ArgOffset = ((ArgOffset+15)/16)*16; 6759 ArgOffset += 12*16; 6760 for (unsigned i = 0; i != NumOps; ++i) { 6761 SDValue Arg = OutVals[i]; 6762 EVT ArgType = Outs[i].VT; 6763 if (ArgType==MVT::v4f32 || ArgType==MVT::v4i32 || 6764 ArgType==MVT::v8i16 || ArgType==MVT::v16i8) { 6765 if (++j > NumVRs) { 6766 SDValue PtrOff; 6767 // We are emitting Altivec params in order. 6768 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6769 isPPC64, isTailCall, true, MemOpChains, 6770 TailCallArguments, dl); 6771 ArgOffset += 16; 6772 } 6773 } 6774 } 6775 } 6776 6777 if (!MemOpChains.empty()) 6778 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 6779 6780 // On Darwin, R12 must contain the address of an indirect callee. This does 6781 // not mean the MTCTR instruction must use R12; it's easier to model this as 6782 // an extra parameter, so do that. 6783 if (!isTailCall && 6784 !isFunctionGlobalAddress(Callee) && 6785 !isa<ExternalSymbolSDNode>(Callee) && 6786 !isBLACompatibleAddress(Callee, DAG)) 6787 RegsToPass.push_back(std::make_pair((unsigned)(isPPC64 ? PPC::X12 : 6788 PPC::R12), Callee)); 6789 6790 // Build a sequence of copy-to-reg nodes chained together with token chain 6791 // and flag operands which copy the outgoing args into the appropriate regs. 6792 SDValue InFlag; 6793 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 6794 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 6795 RegsToPass[i].second, InFlag); 6796 InFlag = Chain.getValue(1); 6797 } 6798 6799 if (isTailCall) 6800 PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp, 6801 TailCallArguments); 6802 6803 return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint, 6804 /* unused except on PPC64 ELFv1 */ false, DAG, 6805 RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff, 6806 NumBytes, Ins, InVals, CS); 6807 } 6808 6809 static bool CC_AIX(unsigned ValNo, MVT ValVT, MVT LocVT, 6810 CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags, 6811 CCState &State) { 6812 6813 if (ValVT == MVT::f128) 6814 report_fatal_error("f128 is unimplemented on AIX."); 6815 6816 if (ArgFlags.isByVal()) 6817 report_fatal_error("Passing structure by value is unimplemented."); 6818 6819 if (ArgFlags.isNest()) 6820 report_fatal_error("Nest arguments are unimplemented."); 6821 6822 if (ValVT.isVector() || LocVT.isVector()) 6823 report_fatal_error("Vector arguments are unimplemented on AIX."); 6824 6825 const PPCSubtarget &Subtarget = static_cast<const PPCSubtarget &>( 6826 State.getMachineFunction().getSubtarget()); 6827 const bool IsPPC64 = Subtarget.isPPC64(); 6828 const unsigned PtrByteSize = IsPPC64 ? 8 : 4; 6829 6830 static const MCPhysReg GPR_32[] = {// 32-bit registers. 6831 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 6832 PPC::R7, PPC::R8, PPC::R9, PPC::R10}; 6833 static const MCPhysReg GPR_64[] = {// 64-bit registers. 6834 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 6835 PPC::X7, PPC::X8, PPC::X9, PPC::X10}; 6836 6837 // Arguments always reserve parameter save area. 6838 switch (ValVT.SimpleTy) { 6839 default: 6840 report_fatal_error("Unhandled value type for argument."); 6841 case MVT::i64: 6842 // i64 arguments should have been split to i32 for PPC32. 6843 assert(IsPPC64 && "PPC32 should have split i64 values."); 6844 LLVM_FALLTHROUGH; 6845 case MVT::i1: 6846 case MVT::i32: 6847 State.AllocateStack(PtrByteSize, PtrByteSize); 6848 if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32)) { 6849 MVT RegVT = IsPPC64 ? MVT::i64 : MVT::i32; 6850 // Promote integers if needed. 6851 if (ValVT.getSizeInBits() < RegVT.getSizeInBits()) 6852 LocInfo = ArgFlags.isSExt() ? CCValAssign::LocInfo::SExt 6853 : CCValAssign::LocInfo::ZExt; 6854 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, RegVT, LocInfo)); 6855 } 6856 else 6857 report_fatal_error("Handling of placing parameters on the stack is " 6858 "unimplemented!"); 6859 return false; 6860 6861 case MVT::f32: 6862 case MVT::f64: { 6863 // Parameter save area (PSA) is reserved even if the float passes in fpr. 6864 const unsigned StoreSize = LocVT.getStoreSize(); 6865 // Floats are always 4-byte aligned in the PSA on AIX. 6866 // This includes f64 in 64-bit mode for ABI compatibility. 6867 State.AllocateStack(IsPPC64 ? 8 : StoreSize, 4); 6868 if (unsigned Reg = State.AllocateReg(FPR)) 6869 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 6870 else 6871 report_fatal_error("Handling of placing parameters on the stack is " 6872 "unimplemented!"); 6873 6874 // AIX requires that GPRs are reserved for float arguments. 6875 // Successfully reserved GPRs are only initialized for vararg calls. 6876 MVT RegVT = IsPPC64 ? MVT::i64 : MVT::i32; 6877 for (unsigned I = 0; I < StoreSize; I += PtrByteSize) { 6878 if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32)) { 6879 if (State.isVarArg()) { 6880 // Custom handling is required for: 6881 // f64 in PPC32 needs to be split into 2 GPRs. 6882 // f32 in PPC64 needs to occupy only lower 32 bits of 64-bit GPR. 6883 State.addLoc( 6884 CCValAssign::getCustomReg(ValNo, ValVT, Reg, RegVT, LocInfo)); 6885 } 6886 } else if (State.isVarArg()) { 6887 report_fatal_error("Handling of placing parameters on the stack is " 6888 "unimplemented!"); 6889 } 6890 } 6891 6892 return false; 6893 } 6894 } 6895 return true; 6896 } 6897 6898 static const TargetRegisterClass *getRegClassForSVT(MVT::SimpleValueType SVT, 6899 bool IsPPC64) { 6900 assert((IsPPC64 || SVT != MVT::i64) && 6901 "i64 should have been split for 32-bit codegen."); 6902 6903 switch (SVT) { 6904 default: 6905 report_fatal_error("Unexpected value type for formal argument"); 6906 case MVT::i1: 6907 case MVT::i32: 6908 case MVT::i64: 6909 return IsPPC64 ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 6910 case MVT::f32: 6911 return &PPC::F4RCRegClass; 6912 case MVT::f64: 6913 return &PPC::F8RCRegClass; 6914 } 6915 } 6916 6917 static SDValue truncateScalarIntegerArg(ISD::ArgFlagsTy Flags, EVT ValVT, 6918 SelectionDAG &DAG, SDValue ArgValue, 6919 MVT LocVT, const SDLoc &dl) { 6920 assert(ValVT.isScalarInteger() && LocVT.isScalarInteger()); 6921 assert(ValVT.getSizeInBits() < LocVT.getSizeInBits()); 6922 6923 if (Flags.isSExt()) 6924 ArgValue = DAG.getNode(ISD::AssertSext, dl, LocVT, ArgValue, 6925 DAG.getValueType(ValVT)); 6926 else if (Flags.isZExt()) 6927 ArgValue = DAG.getNode(ISD::AssertZext, dl, LocVT, ArgValue, 6928 DAG.getValueType(ValVT)); 6929 6930 return DAG.getNode(ISD::TRUNCATE, dl, ValVT, ArgValue); 6931 } 6932 6933 SDValue PPCTargetLowering::LowerFormalArguments_AIX( 6934 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 6935 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 6936 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 6937 6938 assert((CallConv == CallingConv::C || CallConv == CallingConv::Cold || 6939 CallConv == CallingConv::Fast) && 6940 "Unexpected calling convention!"); 6941 6942 if (isVarArg) 6943 report_fatal_error("This call type is unimplemented on AIX."); 6944 6945 if (getTargetMachine().Options.GuaranteedTailCallOpt) 6946 report_fatal_error("Tail call support is unimplemented on AIX."); 6947 6948 if (useSoftFloat()) 6949 report_fatal_error("Soft float support is unimplemented on AIX."); 6950 6951 const PPCSubtarget &Subtarget = 6952 static_cast<const PPCSubtarget &>(DAG.getSubtarget()); 6953 if (Subtarget.hasQPX()) 6954 report_fatal_error("QPX support is not supported on AIX."); 6955 6956 const bool IsPPC64 = Subtarget.isPPC64(); 6957 const unsigned PtrByteSize = IsPPC64 ? 8 : 4; 6958 6959 // Assign locations to all of the incoming arguments. 6960 SmallVector<CCValAssign, 16> ArgLocs; 6961 MachineFunction &MF = DAG.getMachineFunction(); 6962 CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext()); 6963 6964 // Reserve space for the linkage area on the stack. 6965 const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 6966 // On AIX a minimum of 8 words is saved to the parameter save area. 6967 const unsigned MinParameterSaveArea = 8 * PtrByteSize; 6968 CCInfo.AllocateStack(LinkageSize + MinParameterSaveArea, PtrByteSize); 6969 CCInfo.AnalyzeFormalArguments(Ins, CC_AIX); 6970 6971 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 6972 CCValAssign &VA = ArgLocs[i]; 6973 SDValue ArgValue; 6974 ISD::ArgFlagsTy Flags = Ins[i].Flags; 6975 if (VA.isRegLoc()) { 6976 EVT ValVT = VA.getValVT(); 6977 MVT LocVT = VA.getLocVT(); 6978 MVT::SimpleValueType SVT = ValVT.getSimpleVT().SimpleTy; 6979 unsigned VReg = 6980 MF.addLiveIn(VA.getLocReg(), getRegClassForSVT(SVT, IsPPC64)); 6981 ArgValue = DAG.getCopyFromReg(Chain, dl, VReg, LocVT); 6982 if (ValVT.isScalarInteger() && 6983 (ValVT.getSizeInBits() < LocVT.getSizeInBits())) { 6984 ArgValue = 6985 truncateScalarIntegerArg(Flags, ValVT, DAG, ArgValue, LocVT, dl); 6986 } 6987 InVals.push_back(ArgValue); 6988 } else { 6989 report_fatal_error("Handling of formal arguments on the stack is " 6990 "unimplemented!"); 6991 } 6992 } 6993 6994 // Area that is at least reserved in the caller of this function. 6995 unsigned MinReservedArea = CCInfo.getNextStackOffset(); 6996 6997 // Set the size that is at least reserved in caller of this function. Tail 6998 // call optimized function's reserved stack space needs to be aligned so 6999 // that taking the difference between two stack areas will result in an 7000 // aligned stack. 7001 MinReservedArea = 7002 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea); 7003 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 7004 FuncInfo->setMinReservedArea(MinReservedArea); 7005 7006 return Chain; 7007 } 7008 7009 SDValue PPCTargetLowering::LowerCall_AIX( 7010 SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg, 7011 bool isTailCall, bool isPatchPoint, 7012 const SmallVectorImpl<ISD::OutputArg> &Outs, 7013 const SmallVectorImpl<SDValue> &OutVals, 7014 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 7015 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 7016 ImmutableCallSite CS) const { 7017 7018 assert((CallConv == CallingConv::C || 7019 CallConv == CallingConv::Cold || 7020 CallConv == CallingConv::Fast) && "Unexpected calling convention!"); 7021 7022 if (isPatchPoint) 7023 report_fatal_error("This call type is unimplemented on AIX."); 7024 7025 const PPCSubtarget& Subtarget = 7026 static_cast<const PPCSubtarget&>(DAG.getSubtarget()); 7027 if (Subtarget.hasQPX()) 7028 report_fatal_error("QPX is not supported on AIX."); 7029 if (Subtarget.hasAltivec()) 7030 report_fatal_error("Altivec support is unimplemented on AIX."); 7031 7032 MachineFunction &MF = DAG.getMachineFunction(); 7033 SmallVector<CCValAssign, 16> ArgLocs; 7034 CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext()); 7035 7036 // Reserve space for the linkage save area (LSA) on the stack. 7037 // In both PPC32 and PPC64 there are 6 reserved slots in the LSA: 7038 // [SP][CR][LR][2 x reserved][TOC]. 7039 // The LSA is 24 bytes (6x4) in PPC32 and 48 bytes (6x8) in PPC64. 7040 const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 7041 const bool IsPPC64 = Subtarget.isPPC64(); 7042 const unsigned PtrByteSize = IsPPC64 ? 8 : 4; 7043 CCInfo.AllocateStack(LinkageSize, PtrByteSize); 7044 CCInfo.AnalyzeCallOperands(Outs, CC_AIX); 7045 7046 // The prolog code of the callee may store up to 8 GPR argument registers to 7047 // the stack, allowing va_start to index over them in memory if the callee 7048 // is variadic. 7049 // Because we cannot tell if this is needed on the caller side, we have to 7050 // conservatively assume that it is needed. As such, make sure we have at 7051 // least enough stack space for the caller to store the 8 GPRs. 7052 const unsigned MinParameterSaveAreaSize = 8 * PtrByteSize; 7053 const unsigned NumBytes = LinkageSize + MinParameterSaveAreaSize; 7054 7055 // Adjust the stack pointer for the new arguments... 7056 // These operations are automatically eliminated by the prolog/epilog pass. 7057 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 7058 SDValue CallSeqStart = Chain; 7059 7060 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 7061 7062 for (unsigned I = 0, E = ArgLocs.size(); I != E;) { 7063 CCValAssign &VA = ArgLocs[I++]; 7064 7065 if (VA.isMemLoc()) 7066 report_fatal_error("Handling of placing parameters on the stack is " 7067 "unimplemented!"); 7068 if (!VA.isRegLoc()) 7069 report_fatal_error( 7070 "Unexpected non-register location for function call argument."); 7071 7072 SDValue Arg = OutVals[VA.getValNo()]; 7073 7074 if (!VA.needsCustom()) { 7075 switch (VA.getLocInfo()) { 7076 default: 7077 report_fatal_error("Unexpected argument extension type."); 7078 case CCValAssign::Full: 7079 break; 7080 case CCValAssign::ZExt: 7081 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg); 7082 break; 7083 case CCValAssign::SExt: 7084 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg); 7085 break; 7086 } 7087 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 7088 7089 continue; 7090 } 7091 7092 // Custom handling is used for GPR initializations for vararg float 7093 // arguments. 7094 assert(isVarArg && VA.getValVT().isFloatingPoint() && 7095 VA.getLocVT().isInteger() && 7096 "Unexpected custom register handling for calling convention."); 7097 7098 SDValue ArgAsInt = 7099 DAG.getBitcast(MVT::getIntegerVT(VA.getValVT().getSizeInBits()), Arg); 7100 7101 if (Arg.getValueType().getStoreSize() == VA.getLocVT().getStoreSize()) 7102 // f32 in 32-bit GPR 7103 // f64 in 64-bit GPR 7104 RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgAsInt)); 7105 else if (Arg.getValueType().getSizeInBits() < VA.getLocVT().getSizeInBits()) 7106 // f32 in 64-bit GPR. 7107 RegsToPass.push_back(std::make_pair( 7108 VA.getLocReg(), DAG.getZExtOrTrunc(ArgAsInt, dl, VA.getLocVT()))); 7109 else { 7110 // f64 in two 32-bit GPRs 7111 // The 2 GPRs are marked custom and expected to be adjacent in ArgLocs. 7112 assert(Arg.getValueType() == MVT::f64 && isVarArg && !IsPPC64 && 7113 "Unexpected custom register for argument!"); 7114 CCValAssign &GPR1 = VA; 7115 SDValue MSWAsI64 = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgAsInt, 7116 DAG.getConstant(32, dl, MVT::i8)); 7117 RegsToPass.push_back(std::make_pair( 7118 GPR1.getLocReg(), DAG.getZExtOrTrunc(MSWAsI64, dl, MVT::i32))); 7119 assert(I != E && "A second custom GPR is expected!"); 7120 CCValAssign &GPR2 = ArgLocs[I++]; 7121 assert(GPR2.isRegLoc() && GPR2.getValNo() == GPR1.getValNo() && 7122 GPR2.needsCustom() && "A second custom GPR is expected!"); 7123 RegsToPass.push_back(std::make_pair( 7124 GPR2.getLocReg(), DAG.getZExtOrTrunc(ArgAsInt, dl, MVT::i32))); 7125 } 7126 } 7127 7128 // For indirect calls, we need to save the TOC base to the stack for 7129 // restoration after the call. 7130 if (!isTailCall && !isPatchPoint && 7131 !isFunctionGlobalAddress(Callee) && !isa<ExternalSymbolSDNode>(Callee)) { 7132 const MCRegister TOCBaseReg = Subtarget.getTOCPointerRegister(); 7133 const MCRegister StackPtrReg = Subtarget.getStackPointerRegister(); 7134 const MVT PtrVT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32; 7135 const unsigned TOCSaveOffset = 7136 Subtarget.getFrameLowering()->getTOCSaveOffset(); 7137 7138 setUsesTOCBasePtr(DAG); 7139 SDValue Val = DAG.getCopyFromReg(Chain, dl, TOCBaseReg, PtrVT); 7140 SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl); 7141 SDValue StackPtr = DAG.getRegister(StackPtrReg, PtrVT); 7142 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 7143 Chain = DAG.getStore( 7144 Val.getValue(1), dl, Val, AddPtr, 7145 MachinePointerInfo::getStack(DAG.getMachineFunction(), TOCSaveOffset)); 7146 } 7147 7148 // Build a sequence of copy-to-reg nodes chained together with token chain 7149 // and flag operands which copy the outgoing args into the appropriate regs. 7150 SDValue InFlag; 7151 for (auto Reg : RegsToPass) { 7152 Chain = DAG.getCopyToReg(Chain, dl, Reg.first, Reg.second, InFlag); 7153 InFlag = Chain.getValue(1); 7154 } 7155 7156 const int SPDiff = 0; 7157 return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint, 7158 /* unused except on PPC64 ELFv1 */ false, DAG, RegsToPass, 7159 InFlag, Chain, CallSeqStart, Callee, SPDiff, NumBytes, Ins, 7160 InVals, CS); 7161 } 7162 7163 bool 7164 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv, 7165 MachineFunction &MF, bool isVarArg, 7166 const SmallVectorImpl<ISD::OutputArg> &Outs, 7167 LLVMContext &Context) const { 7168 SmallVector<CCValAssign, 16> RVLocs; 7169 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context); 7170 return CCInfo.CheckReturn( 7171 Outs, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold) 7172 ? RetCC_PPC_Cold 7173 : RetCC_PPC); 7174 } 7175 7176 SDValue 7177 PPCTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 7178 bool isVarArg, 7179 const SmallVectorImpl<ISD::OutputArg> &Outs, 7180 const SmallVectorImpl<SDValue> &OutVals, 7181 const SDLoc &dl, SelectionDAG &DAG) const { 7182 SmallVector<CCValAssign, 16> RVLocs; 7183 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 7184 *DAG.getContext()); 7185 CCInfo.AnalyzeReturn(Outs, 7186 (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold) 7187 ? RetCC_PPC_Cold 7188 : RetCC_PPC); 7189 7190 SDValue Flag; 7191 SmallVector<SDValue, 4> RetOps(1, Chain); 7192 7193 // Copy the result values into the output registers. 7194 for (unsigned i = 0, RealResIdx = 0; i != RVLocs.size(); ++i, ++RealResIdx) { 7195 CCValAssign &VA = RVLocs[i]; 7196 assert(VA.isRegLoc() && "Can only return in registers!"); 7197 7198 SDValue Arg = OutVals[RealResIdx]; 7199 7200 switch (VA.getLocInfo()) { 7201 default: llvm_unreachable("Unknown loc info!"); 7202 case CCValAssign::Full: break; 7203 case CCValAssign::AExt: 7204 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg); 7205 break; 7206 case CCValAssign::ZExt: 7207 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg); 7208 break; 7209 case CCValAssign::SExt: 7210 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg); 7211 break; 7212 } 7213 if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) { 7214 bool isLittleEndian = Subtarget.isLittleEndian(); 7215 // Legalize ret f64 -> ret 2 x i32. 7216 SDValue SVal = 7217 DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg, 7218 DAG.getIntPtrConstant(isLittleEndian ? 0 : 1, dl)); 7219 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Flag); 7220 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 7221 SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg, 7222 DAG.getIntPtrConstant(isLittleEndian ? 1 : 0, dl)); 7223 Flag = Chain.getValue(1); 7224 VA = RVLocs[++i]; // skip ahead to next loc 7225 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Flag); 7226 } else 7227 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag); 7228 Flag = Chain.getValue(1); 7229 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 7230 } 7231 7232 const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo(); 7233 const MCPhysReg *I = 7234 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction()); 7235 if (I) { 7236 for (; *I; ++I) { 7237 7238 if (PPC::G8RCRegClass.contains(*I)) 7239 RetOps.push_back(DAG.getRegister(*I, MVT::i64)); 7240 else if (PPC::F8RCRegClass.contains(*I)) 7241 RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64))); 7242 else if (PPC::CRRCRegClass.contains(*I)) 7243 RetOps.push_back(DAG.getRegister(*I, MVT::i1)); 7244 else if (PPC::VRRCRegClass.contains(*I)) 7245 RetOps.push_back(DAG.getRegister(*I, MVT::Other)); 7246 else 7247 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 7248 } 7249 } 7250 7251 RetOps[0] = Chain; // Update chain. 7252 7253 // Add the flag if we have it. 7254 if (Flag.getNode()) 7255 RetOps.push_back(Flag); 7256 7257 return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, RetOps); 7258 } 7259 7260 SDValue 7261 PPCTargetLowering::LowerGET_DYNAMIC_AREA_OFFSET(SDValue Op, 7262 SelectionDAG &DAG) const { 7263 SDLoc dl(Op); 7264 7265 // Get the correct type for integers. 7266 EVT IntVT = Op.getValueType(); 7267 7268 // Get the inputs. 7269 SDValue Chain = Op.getOperand(0); 7270 SDValue FPSIdx = getFramePointerFrameIndex(DAG); 7271 // Build a DYNAREAOFFSET node. 7272 SDValue Ops[2] = {Chain, FPSIdx}; 7273 SDVTList VTs = DAG.getVTList(IntVT); 7274 return DAG.getNode(PPCISD::DYNAREAOFFSET, dl, VTs, Ops); 7275 } 7276 7277 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op, 7278 SelectionDAG &DAG) const { 7279 // When we pop the dynamic allocation we need to restore the SP link. 7280 SDLoc dl(Op); 7281 7282 // Get the correct type for pointers. 7283 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7284 7285 // Construct the stack pointer operand. 7286 bool isPPC64 = Subtarget.isPPC64(); 7287 unsigned SP = isPPC64 ? PPC::X1 : PPC::R1; 7288 SDValue StackPtr = DAG.getRegister(SP, PtrVT); 7289 7290 // Get the operands for the STACKRESTORE. 7291 SDValue Chain = Op.getOperand(0); 7292 SDValue SaveSP = Op.getOperand(1); 7293 7294 // Load the old link SP. 7295 SDValue LoadLinkSP = 7296 DAG.getLoad(PtrVT, dl, Chain, StackPtr, MachinePointerInfo()); 7297 7298 // Restore the stack pointer. 7299 Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP); 7300 7301 // Store the old link SP. 7302 return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo()); 7303 } 7304 7305 SDValue PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG &DAG) const { 7306 MachineFunction &MF = DAG.getMachineFunction(); 7307 bool isPPC64 = Subtarget.isPPC64(); 7308 EVT PtrVT = getPointerTy(MF.getDataLayout()); 7309 7310 // Get current frame pointer save index. The users of this index will be 7311 // primarily DYNALLOC instructions. 7312 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>(); 7313 int RASI = FI->getReturnAddrSaveIndex(); 7314 7315 // If the frame pointer save index hasn't been defined yet. 7316 if (!RASI) { 7317 // Find out what the fix offset of the frame pointer save area. 7318 int LROffset = Subtarget.getFrameLowering()->getReturnSaveOffset(); 7319 // Allocate the frame index for frame pointer save area. 7320 RASI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, LROffset, false); 7321 // Save the result. 7322 FI->setReturnAddrSaveIndex(RASI); 7323 } 7324 return DAG.getFrameIndex(RASI, PtrVT); 7325 } 7326 7327 SDValue 7328 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const { 7329 MachineFunction &MF = DAG.getMachineFunction(); 7330 bool isPPC64 = Subtarget.isPPC64(); 7331 EVT PtrVT = getPointerTy(MF.getDataLayout()); 7332 7333 // Get current frame pointer save index. The users of this index will be 7334 // primarily DYNALLOC instructions. 7335 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>(); 7336 int FPSI = FI->getFramePointerSaveIndex(); 7337 7338 // If the frame pointer save index hasn't been defined yet. 7339 if (!FPSI) { 7340 // Find out what the fix offset of the frame pointer save area. 7341 int FPOffset = Subtarget.getFrameLowering()->getFramePointerSaveOffset(); 7342 // Allocate the frame index for frame pointer save area. 7343 FPSI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, FPOffset, true); 7344 // Save the result. 7345 FI->setFramePointerSaveIndex(FPSI); 7346 } 7347 return DAG.getFrameIndex(FPSI, PtrVT); 7348 } 7349 7350 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, 7351 SelectionDAG &DAG) const { 7352 // Get the inputs. 7353 SDValue Chain = Op.getOperand(0); 7354 SDValue Size = Op.getOperand(1); 7355 SDLoc dl(Op); 7356 7357 // Get the correct type for pointers. 7358 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7359 // Negate the size. 7360 SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT, 7361 DAG.getConstant(0, dl, PtrVT), Size); 7362 // Construct a node for the frame pointer save index. 7363 SDValue FPSIdx = getFramePointerFrameIndex(DAG); 7364 // Build a DYNALLOC node. 7365 SDValue Ops[3] = { Chain, NegSize, FPSIdx }; 7366 SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other); 7367 return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops); 7368 } 7369 7370 SDValue PPCTargetLowering::LowerEH_DWARF_CFA(SDValue Op, 7371 SelectionDAG &DAG) const { 7372 MachineFunction &MF = DAG.getMachineFunction(); 7373 7374 bool isPPC64 = Subtarget.isPPC64(); 7375 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7376 7377 int FI = MF.getFrameInfo().CreateFixedObject(isPPC64 ? 8 : 4, 0, false); 7378 return DAG.getFrameIndex(FI, PtrVT); 7379 } 7380 7381 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op, 7382 SelectionDAG &DAG) const { 7383 SDLoc DL(Op); 7384 return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL, 7385 DAG.getVTList(MVT::i32, MVT::Other), 7386 Op.getOperand(0), Op.getOperand(1)); 7387 } 7388 7389 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op, 7390 SelectionDAG &DAG) const { 7391 SDLoc DL(Op); 7392 return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other, 7393 Op.getOperand(0), Op.getOperand(1)); 7394 } 7395 7396 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const { 7397 if (Op.getValueType().isVector()) 7398 return LowerVectorLoad(Op, DAG); 7399 7400 assert(Op.getValueType() == MVT::i1 && 7401 "Custom lowering only for i1 loads"); 7402 7403 // First, load 8 bits into 32 bits, then truncate to 1 bit. 7404 7405 SDLoc dl(Op); 7406 LoadSDNode *LD = cast<LoadSDNode>(Op); 7407 7408 SDValue Chain = LD->getChain(); 7409 SDValue BasePtr = LD->getBasePtr(); 7410 MachineMemOperand *MMO = LD->getMemOperand(); 7411 7412 SDValue NewLD = 7413 DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(DAG.getDataLayout()), Chain, 7414 BasePtr, MVT::i8, MMO); 7415 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD); 7416 7417 SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) }; 7418 return DAG.getMergeValues(Ops, dl); 7419 } 7420 7421 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const { 7422 if (Op.getOperand(1).getValueType().isVector()) 7423 return LowerVectorStore(Op, DAG); 7424 7425 assert(Op.getOperand(1).getValueType() == MVT::i1 && 7426 "Custom lowering only for i1 stores"); 7427 7428 // First, zero extend to 32 bits, then use a truncating store to 8 bits. 7429 7430 SDLoc dl(Op); 7431 StoreSDNode *ST = cast<StoreSDNode>(Op); 7432 7433 SDValue Chain = ST->getChain(); 7434 SDValue BasePtr = ST->getBasePtr(); 7435 SDValue Value = ST->getValue(); 7436 MachineMemOperand *MMO = ST->getMemOperand(); 7437 7438 Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(DAG.getDataLayout()), 7439 Value); 7440 return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO); 7441 } 7442 7443 // FIXME: Remove this once the ANDI glue bug is fixed: 7444 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const { 7445 assert(Op.getValueType() == MVT::i1 && 7446 "Custom lowering only for i1 results"); 7447 7448 SDLoc DL(Op); 7449 return DAG.getNode(PPCISD::ANDI_rec_1_GT_BIT, DL, MVT::i1, Op.getOperand(0)); 7450 } 7451 7452 SDValue PPCTargetLowering::LowerTRUNCATEVector(SDValue Op, 7453 SelectionDAG &DAG) const { 7454 7455 // Implements a vector truncate that fits in a vector register as a shuffle. 7456 // We want to legalize vector truncates down to where the source fits in 7457 // a vector register (and target is therefore smaller than vector register 7458 // size). At that point legalization will try to custom lower the sub-legal 7459 // result and get here - where we can contain the truncate as a single target 7460 // operation. 7461 7462 // For example a trunc <2 x i16> to <2 x i8> could be visualized as follows: 7463 // <MSB1|LSB1, MSB2|LSB2> to <LSB1, LSB2> 7464 // 7465 // We will implement it for big-endian ordering as this (where x denotes 7466 // undefined): 7467 // < MSB1|LSB1, MSB2|LSB2, uu, uu, uu, uu, uu, uu> to 7468 // < LSB1, LSB2, u, u, u, u, u, u, u, u, u, u, u, u, u, u> 7469 // 7470 // The same operation in little-endian ordering will be: 7471 // <uu, uu, uu, uu, uu, uu, LSB2|MSB2, LSB1|MSB1> to 7472 // <u, u, u, u, u, u, u, u, u, u, u, u, u, u, LSB2, LSB1> 7473 7474 assert(Op.getValueType().isVector() && "Vector type expected."); 7475 7476 SDLoc DL(Op); 7477 SDValue N1 = Op.getOperand(0); 7478 unsigned SrcSize = N1.getValueType().getSizeInBits(); 7479 assert(SrcSize <= 128 && "Source must fit in an Altivec/VSX vector"); 7480 SDValue WideSrc = SrcSize == 128 ? N1 : widenVec(DAG, N1, DL); 7481 7482 EVT TrgVT = Op.getValueType(); 7483 unsigned TrgNumElts = TrgVT.getVectorNumElements(); 7484 EVT EltVT = TrgVT.getVectorElementType(); 7485 unsigned WideNumElts = 128 / EltVT.getSizeInBits(); 7486 EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts); 7487 7488 // First list the elements we want to keep. 7489 unsigned SizeMult = SrcSize / TrgVT.getSizeInBits(); 7490 SmallVector<int, 16> ShuffV; 7491 if (Subtarget.isLittleEndian()) 7492 for (unsigned i = 0; i < TrgNumElts; ++i) 7493 ShuffV.push_back(i * SizeMult); 7494 else 7495 for (unsigned i = 1; i <= TrgNumElts; ++i) 7496 ShuffV.push_back(i * SizeMult - 1); 7497 7498 // Populate the remaining elements with undefs. 7499 for (unsigned i = TrgNumElts; i < WideNumElts; ++i) 7500 // ShuffV.push_back(i + WideNumElts); 7501 ShuffV.push_back(WideNumElts + 1); 7502 7503 SDValue Conv = DAG.getNode(ISD::BITCAST, DL, WideVT, WideSrc); 7504 return DAG.getVectorShuffle(WideVT, DL, Conv, DAG.getUNDEF(WideVT), ShuffV); 7505 } 7506 7507 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when 7508 /// possible. 7509 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const { 7510 // Not FP? Not a fsel. 7511 if (!Op.getOperand(0).getValueType().isFloatingPoint() || 7512 !Op.getOperand(2).getValueType().isFloatingPoint()) 7513 return Op; 7514 7515 bool HasNoInfs = DAG.getTarget().Options.NoInfsFPMath; 7516 bool HasNoNaNs = DAG.getTarget().Options.NoNaNsFPMath; 7517 // We might be able to do better than this under some circumstances, but in 7518 // general, fsel-based lowering of select is a finite-math-only optimization. 7519 // For more information, see section F.3 of the 2.06 ISA specification. 7520 // With ISA 3.0, we have xsmaxcdp/xsmincdp which are OK to emit even in the 7521 // presence of infinities. 7522 if (!Subtarget.hasP9Vector() && (!HasNoInfs || !HasNoNaNs)) 7523 return Op; 7524 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get(); 7525 7526 EVT ResVT = Op.getValueType(); 7527 EVT CmpVT = Op.getOperand(0).getValueType(); 7528 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 7529 SDValue TV = Op.getOperand(2), FV = Op.getOperand(3); 7530 SDLoc dl(Op); 7531 7532 if (Subtarget.hasP9Vector() && LHS == TV && RHS == FV) { 7533 switch (CC) { 7534 default: 7535 // Not a min/max but with finite math, we may still be able to use fsel. 7536 if (HasNoInfs && HasNoNaNs) 7537 break; 7538 return Op; 7539 case ISD::SETOGT: 7540 case ISD::SETGT: 7541 return DAG.getNode(PPCISD::XSMAXCDP, dl, Op.getValueType(), LHS, RHS); 7542 case ISD::SETOLT: 7543 case ISD::SETLT: 7544 return DAG.getNode(PPCISD::XSMINCDP, dl, Op.getValueType(), LHS, RHS); 7545 } 7546 } 7547 7548 // TODO: Propagate flags from the select rather than global settings. 7549 SDNodeFlags Flags; 7550 Flags.setNoInfs(true); 7551 Flags.setNoNaNs(true); 7552 7553 // If the RHS of the comparison is a 0.0, we don't need to do the 7554 // subtraction at all. 7555 SDValue Sel1; 7556 if (isFloatingPointZero(RHS)) 7557 switch (CC) { 7558 default: break; // SETUO etc aren't handled by fsel. 7559 case ISD::SETNE: 7560 std::swap(TV, FV); 7561 LLVM_FALLTHROUGH; 7562 case ISD::SETEQ: 7563 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits 7564 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); 7565 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV); 7566 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits 7567 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1); 7568 return DAG.getNode(PPCISD::FSEL, dl, ResVT, 7569 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV); 7570 case ISD::SETULT: 7571 case ISD::SETLT: 7572 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt 7573 LLVM_FALLTHROUGH; 7574 case ISD::SETOGE: 7575 case ISD::SETGE: 7576 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits 7577 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); 7578 return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV); 7579 case ISD::SETUGT: 7580 case ISD::SETGT: 7581 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt 7582 LLVM_FALLTHROUGH; 7583 case ISD::SETOLE: 7584 case ISD::SETLE: 7585 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits 7586 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); 7587 return DAG.getNode(PPCISD::FSEL, dl, ResVT, 7588 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV); 7589 } 7590 7591 SDValue Cmp; 7592 switch (CC) { 7593 default: break; // SETUO etc aren't handled by fsel. 7594 case ISD::SETNE: 7595 std::swap(TV, FV); 7596 LLVM_FALLTHROUGH; 7597 case ISD::SETEQ: 7598 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags); 7599 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 7600 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 7601 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); 7602 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits 7603 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1); 7604 return DAG.getNode(PPCISD::FSEL, dl, ResVT, 7605 DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV); 7606 case ISD::SETULT: 7607 case ISD::SETLT: 7608 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags); 7609 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 7610 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 7611 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV); 7612 case ISD::SETOGE: 7613 case ISD::SETGE: 7614 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags); 7615 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 7616 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 7617 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); 7618 case ISD::SETUGT: 7619 case ISD::SETGT: 7620 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags); 7621 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 7622 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 7623 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV); 7624 case ISD::SETOLE: 7625 case ISD::SETLE: 7626 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags); 7627 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 7628 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 7629 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); 7630 } 7631 return Op; 7632 } 7633 7634 void PPCTargetLowering::LowerFP_TO_INTForReuse(SDValue Op, ReuseLoadInfo &RLI, 7635 SelectionDAG &DAG, 7636 const SDLoc &dl) const { 7637 assert(Op.getOperand(0).getValueType().isFloatingPoint()); 7638 SDValue Src = Op.getOperand(0); 7639 if (Src.getValueType() == MVT::f32) 7640 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src); 7641 7642 SDValue Tmp; 7643 switch (Op.getSimpleValueType().SimpleTy) { 7644 default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!"); 7645 case MVT::i32: 7646 Tmp = DAG.getNode( 7647 Op.getOpcode() == ISD::FP_TO_SINT 7648 ? PPCISD::FCTIWZ 7649 : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ), 7650 dl, MVT::f64, Src); 7651 break; 7652 case MVT::i64: 7653 assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) && 7654 "i64 FP_TO_UINT is supported only with FPCVT"); 7655 Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ : 7656 PPCISD::FCTIDUZ, 7657 dl, MVT::f64, Src); 7658 break; 7659 } 7660 7661 // Convert the FP value to an int value through memory. 7662 bool i32Stack = Op.getValueType() == MVT::i32 && Subtarget.hasSTFIWX() && 7663 (Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()); 7664 SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64); 7665 int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex(); 7666 MachinePointerInfo MPI = 7667 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI); 7668 7669 // Emit a store to the stack slot. 7670 SDValue Chain; 7671 if (i32Stack) { 7672 MachineFunction &MF = DAG.getMachineFunction(); 7673 MachineMemOperand *MMO = 7674 MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, 4); 7675 SDValue Ops[] = { DAG.getEntryNode(), Tmp, FIPtr }; 7676 Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl, 7677 DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO); 7678 } else 7679 Chain = DAG.getStore(DAG.getEntryNode(), dl, Tmp, FIPtr, MPI); 7680 7681 // Result is a load from the stack slot. If loading 4 bytes, make sure to 7682 // add in a bias on big endian. 7683 if (Op.getValueType() == MVT::i32 && !i32Stack) { 7684 FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr, 7685 DAG.getConstant(4, dl, FIPtr.getValueType())); 7686 MPI = MPI.getWithOffset(Subtarget.isLittleEndian() ? 0 : 4); 7687 } 7688 7689 RLI.Chain = Chain; 7690 RLI.Ptr = FIPtr; 7691 RLI.MPI = MPI; 7692 } 7693 7694 /// Custom lowers floating point to integer conversions to use 7695 /// the direct move instructions available in ISA 2.07 to avoid the 7696 /// need for load/store combinations. 7697 SDValue PPCTargetLowering::LowerFP_TO_INTDirectMove(SDValue Op, 7698 SelectionDAG &DAG, 7699 const SDLoc &dl) const { 7700 assert(Op.getOperand(0).getValueType().isFloatingPoint()); 7701 SDValue Src = Op.getOperand(0); 7702 7703 if (Src.getValueType() == MVT::f32) 7704 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src); 7705 7706 SDValue Tmp; 7707 switch (Op.getSimpleValueType().SimpleTy) { 7708 default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!"); 7709 case MVT::i32: 7710 Tmp = DAG.getNode( 7711 Op.getOpcode() == ISD::FP_TO_SINT 7712 ? PPCISD::FCTIWZ 7713 : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ), 7714 dl, MVT::f64, Src); 7715 Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i32, Tmp); 7716 break; 7717 case MVT::i64: 7718 assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) && 7719 "i64 FP_TO_UINT is supported only with FPCVT"); 7720 Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ : 7721 PPCISD::FCTIDUZ, 7722 dl, MVT::f64, Src); 7723 Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i64, Tmp); 7724 break; 7725 } 7726 return Tmp; 7727 } 7728 7729 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG, 7730 const SDLoc &dl) const { 7731 7732 // FP to INT conversions are legal for f128. 7733 if (EnableQuadPrecision && (Op->getOperand(0).getValueType() == MVT::f128)) 7734 return Op; 7735 7736 // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on 7737 // PPC (the libcall is not available). 7738 if (Op.getOperand(0).getValueType() == MVT::ppcf128) { 7739 if (Op.getValueType() == MVT::i32) { 7740 if (Op.getOpcode() == ISD::FP_TO_SINT) { 7741 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, 7742 MVT::f64, Op.getOperand(0), 7743 DAG.getIntPtrConstant(0, dl)); 7744 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, 7745 MVT::f64, Op.getOperand(0), 7746 DAG.getIntPtrConstant(1, dl)); 7747 7748 // Add the two halves of the long double in round-to-zero mode. 7749 SDValue Res = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi); 7750 7751 // Now use a smaller FP_TO_SINT. 7752 return DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Res); 7753 } 7754 if (Op.getOpcode() == ISD::FP_TO_UINT) { 7755 const uint64_t TwoE31[] = {0x41e0000000000000LL, 0}; 7756 APFloat APF = APFloat(APFloat::PPCDoubleDouble(), APInt(128, TwoE31)); 7757 SDValue Tmp = DAG.getConstantFP(APF, dl, MVT::ppcf128); 7758 // X>=2^31 ? (int)(X-2^31)+0x80000000 : (int)X 7759 // FIXME: generated code sucks. 7760 // TODO: Are there fast-math-flags to propagate to this FSUB? 7761 SDValue True = DAG.getNode(ISD::FSUB, dl, MVT::ppcf128, 7762 Op.getOperand(0), Tmp); 7763 True = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, True); 7764 True = DAG.getNode(ISD::ADD, dl, MVT::i32, True, 7765 DAG.getConstant(0x80000000, dl, MVT::i32)); 7766 SDValue False = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, 7767 Op.getOperand(0)); 7768 return DAG.getSelectCC(dl, Op.getOperand(0), Tmp, True, False, 7769 ISD::SETGE); 7770 } 7771 } 7772 7773 return SDValue(); 7774 } 7775 7776 if (Subtarget.hasDirectMove() && Subtarget.isPPC64()) 7777 return LowerFP_TO_INTDirectMove(Op, DAG, dl); 7778 7779 ReuseLoadInfo RLI; 7780 LowerFP_TO_INTForReuse(Op, RLI, DAG, dl); 7781 7782 return DAG.getLoad(Op.getValueType(), dl, RLI.Chain, RLI.Ptr, RLI.MPI, 7783 RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges); 7784 } 7785 7786 // We're trying to insert a regular store, S, and then a load, L. If the 7787 // incoming value, O, is a load, we might just be able to have our load use the 7788 // address used by O. However, we don't know if anything else will store to 7789 // that address before we can load from it. To prevent this situation, we need 7790 // to insert our load, L, into the chain as a peer of O. To do this, we give L 7791 // the same chain operand as O, we create a token factor from the chain results 7792 // of O and L, and we replace all uses of O's chain result with that token 7793 // factor (see spliceIntoChain below for this last part). 7794 bool PPCTargetLowering::canReuseLoadAddress(SDValue Op, EVT MemVT, 7795 ReuseLoadInfo &RLI, 7796 SelectionDAG &DAG, 7797 ISD::LoadExtType ET) const { 7798 SDLoc dl(Op); 7799 if (ET == ISD::NON_EXTLOAD && 7800 (Op.getOpcode() == ISD::FP_TO_UINT || 7801 Op.getOpcode() == ISD::FP_TO_SINT) && 7802 isOperationLegalOrCustom(Op.getOpcode(), 7803 Op.getOperand(0).getValueType())) { 7804 7805 LowerFP_TO_INTForReuse(Op, RLI, DAG, dl); 7806 return true; 7807 } 7808 7809 LoadSDNode *LD = dyn_cast<LoadSDNode>(Op); 7810 if (!LD || LD->getExtensionType() != ET || LD->isVolatile() || 7811 LD->isNonTemporal()) 7812 return false; 7813 if (LD->getMemoryVT() != MemVT) 7814 return false; 7815 7816 RLI.Ptr = LD->getBasePtr(); 7817 if (LD->isIndexed() && !LD->getOffset().isUndef()) { 7818 assert(LD->getAddressingMode() == ISD::PRE_INC && 7819 "Non-pre-inc AM on PPC?"); 7820 RLI.Ptr = DAG.getNode(ISD::ADD, dl, RLI.Ptr.getValueType(), RLI.Ptr, 7821 LD->getOffset()); 7822 } 7823 7824 RLI.Chain = LD->getChain(); 7825 RLI.MPI = LD->getPointerInfo(); 7826 RLI.IsDereferenceable = LD->isDereferenceable(); 7827 RLI.IsInvariant = LD->isInvariant(); 7828 RLI.Alignment = LD->getAlignment(); 7829 RLI.AAInfo = LD->getAAInfo(); 7830 RLI.Ranges = LD->getRanges(); 7831 7832 RLI.ResChain = SDValue(LD, LD->isIndexed() ? 2 : 1); 7833 return true; 7834 } 7835 7836 // Given the head of the old chain, ResChain, insert a token factor containing 7837 // it and NewResChain, and make users of ResChain now be users of that token 7838 // factor. 7839 // TODO: Remove and use DAG::makeEquivalentMemoryOrdering() instead. 7840 void PPCTargetLowering::spliceIntoChain(SDValue ResChain, 7841 SDValue NewResChain, 7842 SelectionDAG &DAG) const { 7843 if (!ResChain) 7844 return; 7845 7846 SDLoc dl(NewResChain); 7847 7848 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 7849 NewResChain, DAG.getUNDEF(MVT::Other)); 7850 assert(TF.getNode() != NewResChain.getNode() && 7851 "A new TF really is required here"); 7852 7853 DAG.ReplaceAllUsesOfValueWith(ResChain, TF); 7854 DAG.UpdateNodeOperands(TF.getNode(), ResChain, NewResChain); 7855 } 7856 7857 /// Analyze profitability of direct move 7858 /// prefer float load to int load plus direct move 7859 /// when there is no integer use of int load 7860 bool PPCTargetLowering::directMoveIsProfitable(const SDValue &Op) const { 7861 SDNode *Origin = Op.getOperand(0).getNode(); 7862 if (Origin->getOpcode() != ISD::LOAD) 7863 return true; 7864 7865 // If there is no LXSIBZX/LXSIHZX, like Power8, 7866 // prefer direct move if the memory size is 1 or 2 bytes. 7867 MachineMemOperand *MMO = cast<LoadSDNode>(Origin)->getMemOperand(); 7868 if (!Subtarget.hasP9Vector() && MMO->getSize() <= 2) 7869 return true; 7870 7871 for (SDNode::use_iterator UI = Origin->use_begin(), 7872 UE = Origin->use_end(); 7873 UI != UE; ++UI) { 7874 7875 // Only look at the users of the loaded value. 7876 if (UI.getUse().get().getResNo() != 0) 7877 continue; 7878 7879 if (UI->getOpcode() != ISD::SINT_TO_FP && 7880 UI->getOpcode() != ISD::UINT_TO_FP) 7881 return true; 7882 } 7883 7884 return false; 7885 } 7886 7887 /// Custom lowers integer to floating point conversions to use 7888 /// the direct move instructions available in ISA 2.07 to avoid the 7889 /// need for load/store combinations. 7890 SDValue PPCTargetLowering::LowerINT_TO_FPDirectMove(SDValue Op, 7891 SelectionDAG &DAG, 7892 const SDLoc &dl) const { 7893 assert((Op.getValueType() == MVT::f32 || 7894 Op.getValueType() == MVT::f64) && 7895 "Invalid floating point type as target of conversion"); 7896 assert(Subtarget.hasFPCVT() && 7897 "Int to FP conversions with direct moves require FPCVT"); 7898 SDValue FP; 7899 SDValue Src = Op.getOperand(0); 7900 bool SinglePrec = Op.getValueType() == MVT::f32; 7901 bool WordInt = Src.getSimpleValueType().SimpleTy == MVT::i32; 7902 bool Signed = Op.getOpcode() == ISD::SINT_TO_FP; 7903 unsigned ConvOp = Signed ? (SinglePrec ? PPCISD::FCFIDS : PPCISD::FCFID) : 7904 (SinglePrec ? PPCISD::FCFIDUS : PPCISD::FCFIDU); 7905 7906 if (WordInt) { 7907 FP = DAG.getNode(Signed ? PPCISD::MTVSRA : PPCISD::MTVSRZ, 7908 dl, MVT::f64, Src); 7909 FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP); 7910 } 7911 else { 7912 FP = DAG.getNode(PPCISD::MTVSRA, dl, MVT::f64, Src); 7913 FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP); 7914 } 7915 7916 return FP; 7917 } 7918 7919 static SDValue widenVec(SelectionDAG &DAG, SDValue Vec, const SDLoc &dl) { 7920 7921 EVT VecVT = Vec.getValueType(); 7922 assert(VecVT.isVector() && "Expected a vector type."); 7923 assert(VecVT.getSizeInBits() < 128 && "Vector is already full width."); 7924 7925 EVT EltVT = VecVT.getVectorElementType(); 7926 unsigned WideNumElts = 128 / EltVT.getSizeInBits(); 7927 EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts); 7928 7929 unsigned NumConcat = WideNumElts / VecVT.getVectorNumElements(); 7930 SmallVector<SDValue, 16> Ops(NumConcat); 7931 Ops[0] = Vec; 7932 SDValue UndefVec = DAG.getUNDEF(VecVT); 7933 for (unsigned i = 1; i < NumConcat; ++i) 7934 Ops[i] = UndefVec; 7935 7936 return DAG.getNode(ISD::CONCAT_VECTORS, dl, WideVT, Ops); 7937 } 7938 7939 SDValue PPCTargetLowering::LowerINT_TO_FPVector(SDValue Op, SelectionDAG &DAG, 7940 const SDLoc &dl) const { 7941 7942 unsigned Opc = Op.getOpcode(); 7943 assert((Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP) && 7944 "Unexpected conversion type"); 7945 assert((Op.getValueType() == MVT::v2f64 || Op.getValueType() == MVT::v4f32) && 7946 "Supports conversions to v2f64/v4f32 only."); 7947 7948 bool SignedConv = Opc == ISD::SINT_TO_FP; 7949 bool FourEltRes = Op.getValueType() == MVT::v4f32; 7950 7951 SDValue Wide = widenVec(DAG, Op.getOperand(0), dl); 7952 EVT WideVT = Wide.getValueType(); 7953 unsigned WideNumElts = WideVT.getVectorNumElements(); 7954 MVT IntermediateVT = FourEltRes ? MVT::v4i32 : MVT::v2i64; 7955 7956 SmallVector<int, 16> ShuffV; 7957 for (unsigned i = 0; i < WideNumElts; ++i) 7958 ShuffV.push_back(i + WideNumElts); 7959 7960 int Stride = FourEltRes ? WideNumElts / 4 : WideNumElts / 2; 7961 int SaveElts = FourEltRes ? 4 : 2; 7962 if (Subtarget.isLittleEndian()) 7963 for (int i = 0; i < SaveElts; i++) 7964 ShuffV[i * Stride] = i; 7965 else 7966 for (int i = 1; i <= SaveElts; i++) 7967 ShuffV[i * Stride - 1] = i - 1; 7968 7969 SDValue ShuffleSrc2 = 7970 SignedConv ? DAG.getUNDEF(WideVT) : DAG.getConstant(0, dl, WideVT); 7971 SDValue Arrange = DAG.getVectorShuffle(WideVT, dl, Wide, ShuffleSrc2, ShuffV); 7972 unsigned ExtendOp = 7973 SignedConv ? (unsigned)PPCISD::SExtVElems : (unsigned)ISD::BITCAST; 7974 7975 SDValue Extend; 7976 if (!Subtarget.hasP9Altivec() && SignedConv) { 7977 Arrange = DAG.getBitcast(IntermediateVT, Arrange); 7978 Extend = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, IntermediateVT, Arrange, 7979 DAG.getValueType(Op.getOperand(0).getValueType())); 7980 } else 7981 Extend = DAG.getNode(ExtendOp, dl, IntermediateVT, Arrange); 7982 7983 return DAG.getNode(Opc, dl, Op.getValueType(), Extend); 7984 } 7985 7986 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op, 7987 SelectionDAG &DAG) const { 7988 SDLoc dl(Op); 7989 7990 EVT InVT = Op.getOperand(0).getValueType(); 7991 EVT OutVT = Op.getValueType(); 7992 if (OutVT.isVector() && OutVT.isFloatingPoint() && 7993 isOperationCustom(Op.getOpcode(), InVT)) 7994 return LowerINT_TO_FPVector(Op, DAG, dl); 7995 7996 // Conversions to f128 are legal. 7997 if (EnableQuadPrecision && (Op.getValueType() == MVT::f128)) 7998 return Op; 7999 8000 if (Subtarget.hasQPX() && Op.getOperand(0).getValueType() == MVT::v4i1) { 8001 if (Op.getValueType() != MVT::v4f32 && Op.getValueType() != MVT::v4f64) 8002 return SDValue(); 8003 8004 SDValue Value = Op.getOperand(0); 8005 // The values are now known to be -1 (false) or 1 (true). To convert this 8006 // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5). 8007 // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5 8008 Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value); 8009 8010 SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64); 8011 8012 Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs); 8013 8014 if (Op.getValueType() != MVT::v4f64) 8015 Value = DAG.getNode(ISD::FP_ROUND, dl, 8016 Op.getValueType(), Value, 8017 DAG.getIntPtrConstant(1, dl)); 8018 return Value; 8019 } 8020 8021 // Don't handle ppc_fp128 here; let it be lowered to a libcall. 8022 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64) 8023 return SDValue(); 8024 8025 if (Op.getOperand(0).getValueType() == MVT::i1) 8026 return DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Op.getOperand(0), 8027 DAG.getConstantFP(1.0, dl, Op.getValueType()), 8028 DAG.getConstantFP(0.0, dl, Op.getValueType())); 8029 8030 // If we have direct moves, we can do all the conversion, skip the store/load 8031 // however, without FPCVT we can't do most conversions. 8032 if (Subtarget.hasDirectMove() && directMoveIsProfitable(Op) && 8033 Subtarget.isPPC64() && Subtarget.hasFPCVT()) 8034 return LowerINT_TO_FPDirectMove(Op, DAG, dl); 8035 8036 assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) && 8037 "UINT_TO_FP is supported only with FPCVT"); 8038 8039 // If we have FCFIDS, then use it when converting to single-precision. 8040 // Otherwise, convert to double-precision and then round. 8041 unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 8042 ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS 8043 : PPCISD::FCFIDS) 8044 : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU 8045 : PPCISD::FCFID); 8046 MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 8047 ? MVT::f32 8048 : MVT::f64; 8049 8050 if (Op.getOperand(0).getValueType() == MVT::i64) { 8051 SDValue SINT = Op.getOperand(0); 8052 // When converting to single-precision, we actually need to convert 8053 // to double-precision first and then round to single-precision. 8054 // To avoid double-rounding effects during that operation, we have 8055 // to prepare the input operand. Bits that might be truncated when 8056 // converting to double-precision are replaced by a bit that won't 8057 // be lost at this stage, but is below the single-precision rounding 8058 // position. 8059 // 8060 // However, if -enable-unsafe-fp-math is in effect, accept double 8061 // rounding to avoid the extra overhead. 8062 if (Op.getValueType() == MVT::f32 && 8063 !Subtarget.hasFPCVT() && 8064 !DAG.getTarget().Options.UnsafeFPMath) { 8065 8066 // Twiddle input to make sure the low 11 bits are zero. (If this 8067 // is the case, we are guaranteed the value will fit into the 53 bit 8068 // mantissa of an IEEE double-precision value without rounding.) 8069 // If any of those low 11 bits were not zero originally, make sure 8070 // bit 12 (value 2048) is set instead, so that the final rounding 8071 // to single-precision gets the correct result. 8072 SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64, 8073 SINT, DAG.getConstant(2047, dl, MVT::i64)); 8074 Round = DAG.getNode(ISD::ADD, dl, MVT::i64, 8075 Round, DAG.getConstant(2047, dl, MVT::i64)); 8076 Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT); 8077 Round = DAG.getNode(ISD::AND, dl, MVT::i64, 8078 Round, DAG.getConstant(-2048, dl, MVT::i64)); 8079 8080 // However, we cannot use that value unconditionally: if the magnitude 8081 // of the input value is small, the bit-twiddling we did above might 8082 // end up visibly changing the output. Fortunately, in that case, we 8083 // don't need to twiddle bits since the original input will convert 8084 // exactly to double-precision floating-point already. Therefore, 8085 // construct a conditional to use the original value if the top 11 8086 // bits are all sign-bit copies, and use the rounded value computed 8087 // above otherwise. 8088 SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64, 8089 SINT, DAG.getConstant(53, dl, MVT::i32)); 8090 Cond = DAG.getNode(ISD::ADD, dl, MVT::i64, 8091 Cond, DAG.getConstant(1, dl, MVT::i64)); 8092 Cond = DAG.getSetCC(dl, MVT::i32, 8093 Cond, DAG.getConstant(1, dl, MVT::i64), ISD::SETUGT); 8094 8095 SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT); 8096 } 8097 8098 ReuseLoadInfo RLI; 8099 SDValue Bits; 8100 8101 MachineFunction &MF = DAG.getMachineFunction(); 8102 if (canReuseLoadAddress(SINT, MVT::i64, RLI, DAG)) { 8103 Bits = DAG.getLoad(MVT::f64, dl, RLI.Chain, RLI.Ptr, RLI.MPI, 8104 RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges); 8105 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG); 8106 } else if (Subtarget.hasLFIWAX() && 8107 canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::SEXTLOAD)) { 8108 MachineMemOperand *MMO = 8109 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 8110 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 8111 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 8112 Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWAX, dl, 8113 DAG.getVTList(MVT::f64, MVT::Other), 8114 Ops, MVT::i32, MMO); 8115 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG); 8116 } else if (Subtarget.hasFPCVT() && 8117 canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::ZEXTLOAD)) { 8118 MachineMemOperand *MMO = 8119 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 8120 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 8121 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 8122 Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWZX, dl, 8123 DAG.getVTList(MVT::f64, MVT::Other), 8124 Ops, MVT::i32, MMO); 8125 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG); 8126 } else if (((Subtarget.hasLFIWAX() && 8127 SINT.getOpcode() == ISD::SIGN_EXTEND) || 8128 (Subtarget.hasFPCVT() && 8129 SINT.getOpcode() == ISD::ZERO_EXTEND)) && 8130 SINT.getOperand(0).getValueType() == MVT::i32) { 8131 MachineFrameInfo &MFI = MF.getFrameInfo(); 8132 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 8133 8134 int FrameIdx = MFI.CreateStackObject(4, 4, false); 8135 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 8136 8137 SDValue Store = 8138 DAG.getStore(DAG.getEntryNode(), dl, SINT.getOperand(0), FIdx, 8139 MachinePointerInfo::getFixedStack( 8140 DAG.getMachineFunction(), FrameIdx)); 8141 8142 assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 && 8143 "Expected an i32 store"); 8144 8145 RLI.Ptr = FIdx; 8146 RLI.Chain = Store; 8147 RLI.MPI = 8148 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 8149 RLI.Alignment = 4; 8150 8151 MachineMemOperand *MMO = 8152 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 8153 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 8154 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 8155 Bits = DAG.getMemIntrinsicNode(SINT.getOpcode() == ISD::ZERO_EXTEND ? 8156 PPCISD::LFIWZX : PPCISD::LFIWAX, 8157 dl, DAG.getVTList(MVT::f64, MVT::Other), 8158 Ops, MVT::i32, MMO); 8159 } else 8160 Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT); 8161 8162 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Bits); 8163 8164 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) 8165 FP = DAG.getNode(ISD::FP_ROUND, dl, 8166 MVT::f32, FP, DAG.getIntPtrConstant(0, dl)); 8167 return FP; 8168 } 8169 8170 assert(Op.getOperand(0).getValueType() == MVT::i32 && 8171 "Unhandled INT_TO_FP type in custom expander!"); 8172 // Since we only generate this in 64-bit mode, we can take advantage of 8173 // 64-bit registers. In particular, sign extend the input value into the 8174 // 64-bit register with extsw, store the WHOLE 64-bit value into the stack 8175 // then lfd it and fcfid it. 8176 MachineFunction &MF = DAG.getMachineFunction(); 8177 MachineFrameInfo &MFI = MF.getFrameInfo(); 8178 EVT PtrVT = getPointerTy(MF.getDataLayout()); 8179 8180 SDValue Ld; 8181 if (Subtarget.hasLFIWAX() || Subtarget.hasFPCVT()) { 8182 ReuseLoadInfo RLI; 8183 bool ReusingLoad; 8184 if (!(ReusingLoad = canReuseLoadAddress(Op.getOperand(0), MVT::i32, RLI, 8185 DAG))) { 8186 int FrameIdx = MFI.CreateStackObject(4, 4, false); 8187 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 8188 8189 SDValue Store = 8190 DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx, 8191 MachinePointerInfo::getFixedStack( 8192 DAG.getMachineFunction(), FrameIdx)); 8193 8194 assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 && 8195 "Expected an i32 store"); 8196 8197 RLI.Ptr = FIdx; 8198 RLI.Chain = Store; 8199 RLI.MPI = 8200 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 8201 RLI.Alignment = 4; 8202 } 8203 8204 MachineMemOperand *MMO = 8205 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 8206 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 8207 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 8208 Ld = DAG.getMemIntrinsicNode(Op.getOpcode() == ISD::UINT_TO_FP ? 8209 PPCISD::LFIWZX : PPCISD::LFIWAX, 8210 dl, DAG.getVTList(MVT::f64, MVT::Other), 8211 Ops, MVT::i32, MMO); 8212 if (ReusingLoad) 8213 spliceIntoChain(RLI.ResChain, Ld.getValue(1), DAG); 8214 } else { 8215 assert(Subtarget.isPPC64() && 8216 "i32->FP without LFIWAX supported only on PPC64"); 8217 8218 int FrameIdx = MFI.CreateStackObject(8, 8, false); 8219 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 8220 8221 SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64, 8222 Op.getOperand(0)); 8223 8224 // STD the extended value into the stack slot. 8225 SDValue Store = DAG.getStore( 8226 DAG.getEntryNode(), dl, Ext64, FIdx, 8227 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx)); 8228 8229 // Load the value as a double. 8230 Ld = DAG.getLoad( 8231 MVT::f64, dl, Store, FIdx, 8232 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx)); 8233 } 8234 8235 // FCFID it and return it. 8236 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Ld); 8237 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) 8238 FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP, 8239 DAG.getIntPtrConstant(0, dl)); 8240 return FP; 8241 } 8242 8243 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op, 8244 SelectionDAG &DAG) const { 8245 SDLoc dl(Op); 8246 /* 8247 The rounding mode is in bits 30:31 of FPSR, and has the following 8248 settings: 8249 00 Round to nearest 8250 01 Round to 0 8251 10 Round to +inf 8252 11 Round to -inf 8253 8254 FLT_ROUNDS, on the other hand, expects the following: 8255 -1 Undefined 8256 0 Round to 0 8257 1 Round to nearest 8258 2 Round to +inf 8259 3 Round to -inf 8260 8261 To perform the conversion, we do: 8262 ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1)) 8263 */ 8264 8265 MachineFunction &MF = DAG.getMachineFunction(); 8266 EVT VT = Op.getValueType(); 8267 EVT PtrVT = getPointerTy(MF.getDataLayout()); 8268 8269 // Save FP Control Word to register 8270 EVT NodeTys[] = { 8271 MVT::f64, // return register 8272 MVT::Glue // unused in this context 8273 }; 8274 SDValue Chain = DAG.getNode(PPCISD::MFFS, dl, NodeTys, None); 8275 8276 // Save FP register to stack slot 8277 int SSFI = MF.getFrameInfo().CreateStackObject(8, 8, false); 8278 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT); 8279 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Chain, StackSlot, 8280 MachinePointerInfo()); 8281 8282 // Load FP Control Word from low 32 bits of stack slot. 8283 SDValue Four = DAG.getConstant(4, dl, PtrVT); 8284 SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four); 8285 SDValue CWD = DAG.getLoad(MVT::i32, dl, Store, Addr, MachinePointerInfo()); 8286 8287 // Transform as necessary 8288 SDValue CWD1 = 8289 DAG.getNode(ISD::AND, dl, MVT::i32, 8290 CWD, DAG.getConstant(3, dl, MVT::i32)); 8291 SDValue CWD2 = 8292 DAG.getNode(ISD::SRL, dl, MVT::i32, 8293 DAG.getNode(ISD::AND, dl, MVT::i32, 8294 DAG.getNode(ISD::XOR, dl, MVT::i32, 8295 CWD, DAG.getConstant(3, dl, MVT::i32)), 8296 DAG.getConstant(3, dl, MVT::i32)), 8297 DAG.getConstant(1, dl, MVT::i32)); 8298 8299 SDValue RetVal = 8300 DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2); 8301 8302 return DAG.getNode((VT.getSizeInBits() < 16 ? 8303 ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal); 8304 } 8305 8306 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const { 8307 EVT VT = Op.getValueType(); 8308 unsigned BitWidth = VT.getSizeInBits(); 8309 SDLoc dl(Op); 8310 assert(Op.getNumOperands() == 3 && 8311 VT == Op.getOperand(1).getValueType() && 8312 "Unexpected SHL!"); 8313 8314 // Expand into a bunch of logical ops. Note that these ops 8315 // depend on the PPC behavior for oversized shift amounts. 8316 SDValue Lo = Op.getOperand(0); 8317 SDValue Hi = Op.getOperand(1); 8318 SDValue Amt = Op.getOperand(2); 8319 EVT AmtVT = Amt.getValueType(); 8320 8321 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, 8322 DAG.getConstant(BitWidth, dl, AmtVT), Amt); 8323 SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt); 8324 SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1); 8325 SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3); 8326 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, 8327 DAG.getConstant(-BitWidth, dl, AmtVT)); 8328 SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5); 8329 SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6); 8330 SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt); 8331 SDValue OutOps[] = { OutLo, OutHi }; 8332 return DAG.getMergeValues(OutOps, dl); 8333 } 8334 8335 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const { 8336 EVT VT = Op.getValueType(); 8337 SDLoc dl(Op); 8338 unsigned BitWidth = VT.getSizeInBits(); 8339 assert(Op.getNumOperands() == 3 && 8340 VT == Op.getOperand(1).getValueType() && 8341 "Unexpected SRL!"); 8342 8343 // Expand into a bunch of logical ops. Note that these ops 8344 // depend on the PPC behavior for oversized shift amounts. 8345 SDValue Lo = Op.getOperand(0); 8346 SDValue Hi = Op.getOperand(1); 8347 SDValue Amt = Op.getOperand(2); 8348 EVT AmtVT = Amt.getValueType(); 8349 8350 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, 8351 DAG.getConstant(BitWidth, dl, AmtVT), Amt); 8352 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt); 8353 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1); 8354 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3); 8355 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, 8356 DAG.getConstant(-BitWidth, dl, AmtVT)); 8357 SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5); 8358 SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6); 8359 SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt); 8360 SDValue OutOps[] = { OutLo, OutHi }; 8361 return DAG.getMergeValues(OutOps, dl); 8362 } 8363 8364 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const { 8365 SDLoc dl(Op); 8366 EVT VT = Op.getValueType(); 8367 unsigned BitWidth = VT.getSizeInBits(); 8368 assert(Op.getNumOperands() == 3 && 8369 VT == Op.getOperand(1).getValueType() && 8370 "Unexpected SRA!"); 8371 8372 // Expand into a bunch of logical ops, followed by a select_cc. 8373 SDValue Lo = Op.getOperand(0); 8374 SDValue Hi = Op.getOperand(1); 8375 SDValue Amt = Op.getOperand(2); 8376 EVT AmtVT = Amt.getValueType(); 8377 8378 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, 8379 DAG.getConstant(BitWidth, dl, AmtVT), Amt); 8380 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt); 8381 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1); 8382 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3); 8383 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, 8384 DAG.getConstant(-BitWidth, dl, AmtVT)); 8385 SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5); 8386 SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt); 8387 SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, dl, AmtVT), 8388 Tmp4, Tmp6, ISD::SETLE); 8389 SDValue OutOps[] = { OutLo, OutHi }; 8390 return DAG.getMergeValues(OutOps, dl); 8391 } 8392 8393 //===----------------------------------------------------------------------===// 8394 // Vector related lowering. 8395 // 8396 8397 /// BuildSplatI - Build a canonical splati of Val with an element size of 8398 /// SplatSize. Cast the result to VT. 8399 static SDValue BuildSplatI(int Val, unsigned SplatSize, EVT VT, 8400 SelectionDAG &DAG, const SDLoc &dl) { 8401 static const MVT VTys[] = { // canonical VT to use for each size. 8402 MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32 8403 }; 8404 8405 EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1]; 8406 8407 // Force vspltis[hw] -1 to vspltisb -1 to canonicalize. 8408 if (Val == -1) 8409 SplatSize = 1; 8410 8411 EVT CanonicalVT = VTys[SplatSize-1]; 8412 8413 // Build a canonical splat for this value. 8414 return DAG.getBitcast(ReqVT, DAG.getConstant(Val, dl, CanonicalVT)); 8415 } 8416 8417 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the 8418 /// specified intrinsic ID. 8419 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op, SelectionDAG &DAG, 8420 const SDLoc &dl, EVT DestVT = MVT::Other) { 8421 if (DestVT == MVT::Other) DestVT = Op.getValueType(); 8422 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 8423 DAG.getConstant(IID, dl, MVT::i32), Op); 8424 } 8425 8426 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the 8427 /// specified intrinsic ID. 8428 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS, 8429 SelectionDAG &DAG, const SDLoc &dl, 8430 EVT DestVT = MVT::Other) { 8431 if (DestVT == MVT::Other) DestVT = LHS.getValueType(); 8432 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 8433 DAG.getConstant(IID, dl, MVT::i32), LHS, RHS); 8434 } 8435 8436 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the 8437 /// specified intrinsic ID. 8438 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1, 8439 SDValue Op2, SelectionDAG &DAG, const SDLoc &dl, 8440 EVT DestVT = MVT::Other) { 8441 if (DestVT == MVT::Other) DestVT = Op0.getValueType(); 8442 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 8443 DAG.getConstant(IID, dl, MVT::i32), Op0, Op1, Op2); 8444 } 8445 8446 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified 8447 /// amount. The result has the specified value type. 8448 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt, EVT VT, 8449 SelectionDAG &DAG, const SDLoc &dl) { 8450 // Force LHS/RHS to be the right type. 8451 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS); 8452 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS); 8453 8454 int Ops[16]; 8455 for (unsigned i = 0; i != 16; ++i) 8456 Ops[i] = i + Amt; 8457 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops); 8458 return DAG.getNode(ISD::BITCAST, dl, VT, T); 8459 } 8460 8461 /// Do we have an efficient pattern in a .td file for this node? 8462 /// 8463 /// \param V - pointer to the BuildVectorSDNode being matched 8464 /// \param HasDirectMove - does this subtarget have VSR <-> GPR direct moves? 8465 /// 8466 /// There are some patterns where it is beneficial to keep a BUILD_VECTOR 8467 /// node as a BUILD_VECTOR node rather than expanding it. The patterns where 8468 /// the opposite is true (expansion is beneficial) are: 8469 /// - The node builds a vector out of integers that are not 32 or 64-bits 8470 /// - The node builds a vector out of constants 8471 /// - The node is a "load-and-splat" 8472 /// In all other cases, we will choose to keep the BUILD_VECTOR. 8473 static bool haveEfficientBuildVectorPattern(BuildVectorSDNode *V, 8474 bool HasDirectMove, 8475 bool HasP8Vector) { 8476 EVT VecVT = V->getValueType(0); 8477 bool RightType = VecVT == MVT::v2f64 || 8478 (HasP8Vector && VecVT == MVT::v4f32) || 8479 (HasDirectMove && (VecVT == MVT::v2i64 || VecVT == MVT::v4i32)); 8480 if (!RightType) 8481 return false; 8482 8483 bool IsSplat = true; 8484 bool IsLoad = false; 8485 SDValue Op0 = V->getOperand(0); 8486 8487 // This function is called in a block that confirms the node is not a constant 8488 // splat. So a constant BUILD_VECTOR here means the vector is built out of 8489 // different constants. 8490 if (V->isConstant()) 8491 return false; 8492 for (int i = 0, e = V->getNumOperands(); i < e; ++i) { 8493 if (V->getOperand(i).isUndef()) 8494 return false; 8495 // We want to expand nodes that represent load-and-splat even if the 8496 // loaded value is a floating point truncation or conversion to int. 8497 if (V->getOperand(i).getOpcode() == ISD::LOAD || 8498 (V->getOperand(i).getOpcode() == ISD::FP_ROUND && 8499 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) || 8500 (V->getOperand(i).getOpcode() == ISD::FP_TO_SINT && 8501 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) || 8502 (V->getOperand(i).getOpcode() == ISD::FP_TO_UINT && 8503 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD)) 8504 IsLoad = true; 8505 // If the operands are different or the input is not a load and has more 8506 // uses than just this BV node, then it isn't a splat. 8507 if (V->getOperand(i) != Op0 || 8508 (!IsLoad && !V->isOnlyUserOf(V->getOperand(i).getNode()))) 8509 IsSplat = false; 8510 } 8511 return !(IsSplat && IsLoad); 8512 } 8513 8514 // Lower BITCAST(f128, (build_pair i64, i64)) to BUILD_FP128. 8515 SDValue PPCTargetLowering::LowerBITCAST(SDValue Op, SelectionDAG &DAG) const { 8516 8517 SDLoc dl(Op); 8518 SDValue Op0 = Op->getOperand(0); 8519 8520 if (!EnableQuadPrecision || 8521 (Op.getValueType() != MVT::f128 ) || 8522 (Op0.getOpcode() != ISD::BUILD_PAIR) || 8523 (Op0.getOperand(0).getValueType() != MVT::i64) || 8524 (Op0.getOperand(1).getValueType() != MVT::i64)) 8525 return SDValue(); 8526 8527 return DAG.getNode(PPCISD::BUILD_FP128, dl, MVT::f128, Op0.getOperand(0), 8528 Op0.getOperand(1)); 8529 } 8530 8531 static const SDValue *getNormalLoadInput(const SDValue &Op) { 8532 const SDValue *InputLoad = &Op; 8533 if (InputLoad->getOpcode() == ISD::BITCAST) 8534 InputLoad = &InputLoad->getOperand(0); 8535 if (InputLoad->getOpcode() == ISD::SCALAR_TO_VECTOR) 8536 InputLoad = &InputLoad->getOperand(0); 8537 if (InputLoad->getOpcode() != ISD::LOAD) 8538 return nullptr; 8539 LoadSDNode *LD = cast<LoadSDNode>(*InputLoad); 8540 return ISD::isNormalLoad(LD) ? InputLoad : nullptr; 8541 } 8542 8543 // If this is a case we can't handle, return null and let the default 8544 // expansion code take care of it. If we CAN select this case, and if it 8545 // selects to a single instruction, return Op. Otherwise, if we can codegen 8546 // this case more efficiently than a constant pool load, lower it to the 8547 // sequence of ops that should be used. 8548 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op, 8549 SelectionDAG &DAG) const { 8550 SDLoc dl(Op); 8551 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode()); 8552 assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR"); 8553 8554 if (Subtarget.hasQPX() && Op.getValueType() == MVT::v4i1) { 8555 // We first build an i32 vector, load it into a QPX register, 8556 // then convert it to a floating-point vector and compare it 8557 // to a zero vector to get the boolean result. 8558 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 8559 int FrameIdx = MFI.CreateStackObject(16, 16, false); 8560 MachinePointerInfo PtrInfo = 8561 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 8562 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 8563 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 8564 8565 assert(BVN->getNumOperands() == 4 && 8566 "BUILD_VECTOR for v4i1 does not have 4 operands"); 8567 8568 bool IsConst = true; 8569 for (unsigned i = 0; i < 4; ++i) { 8570 if (BVN->getOperand(i).isUndef()) continue; 8571 if (!isa<ConstantSDNode>(BVN->getOperand(i))) { 8572 IsConst = false; 8573 break; 8574 } 8575 } 8576 8577 if (IsConst) { 8578 Constant *One = 8579 ConstantFP::get(Type::getFloatTy(*DAG.getContext()), 1.0); 8580 Constant *NegOne = 8581 ConstantFP::get(Type::getFloatTy(*DAG.getContext()), -1.0); 8582 8583 Constant *CV[4]; 8584 for (unsigned i = 0; i < 4; ++i) { 8585 if (BVN->getOperand(i).isUndef()) 8586 CV[i] = UndefValue::get(Type::getFloatTy(*DAG.getContext())); 8587 else if (isNullConstant(BVN->getOperand(i))) 8588 CV[i] = NegOne; 8589 else 8590 CV[i] = One; 8591 } 8592 8593 Constant *CP = ConstantVector::get(CV); 8594 SDValue CPIdx = DAG.getConstantPool(CP, getPointerTy(DAG.getDataLayout()), 8595 16 /* alignment */); 8596 8597 SDValue Ops[] = {DAG.getEntryNode(), CPIdx}; 8598 SDVTList VTs = DAG.getVTList({MVT::v4i1, /*chain*/ MVT::Other}); 8599 return DAG.getMemIntrinsicNode( 8600 PPCISD::QVLFSb, dl, VTs, Ops, MVT::v4f32, 8601 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 8602 } 8603 8604 SmallVector<SDValue, 4> Stores; 8605 for (unsigned i = 0; i < 4; ++i) { 8606 if (BVN->getOperand(i).isUndef()) continue; 8607 8608 unsigned Offset = 4*i; 8609 SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType()); 8610 Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx); 8611 8612 unsigned StoreSize = BVN->getOperand(i).getValueType().getStoreSize(); 8613 if (StoreSize > 4) { 8614 Stores.push_back( 8615 DAG.getTruncStore(DAG.getEntryNode(), dl, BVN->getOperand(i), Idx, 8616 PtrInfo.getWithOffset(Offset), MVT::i32)); 8617 } else { 8618 SDValue StoreValue = BVN->getOperand(i); 8619 if (StoreSize < 4) 8620 StoreValue = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, StoreValue); 8621 8622 Stores.push_back(DAG.getStore(DAG.getEntryNode(), dl, StoreValue, Idx, 8623 PtrInfo.getWithOffset(Offset))); 8624 } 8625 } 8626 8627 SDValue StoreChain; 8628 if (!Stores.empty()) 8629 StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores); 8630 else 8631 StoreChain = DAG.getEntryNode(); 8632 8633 // Now load from v4i32 into the QPX register; this will extend it to 8634 // v4i64 but not yet convert it to a floating point. Nevertheless, this 8635 // is typed as v4f64 because the QPX register integer states are not 8636 // explicitly represented. 8637 8638 SDValue Ops[] = {StoreChain, 8639 DAG.getConstant(Intrinsic::ppc_qpx_qvlfiwz, dl, MVT::i32), 8640 FIdx}; 8641 SDVTList VTs = DAG.getVTList({MVT::v4f64, /*chain*/ MVT::Other}); 8642 8643 SDValue LoadedVect = DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, 8644 dl, VTs, Ops, MVT::v4i32, PtrInfo); 8645 LoadedVect = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64, 8646 DAG.getConstant(Intrinsic::ppc_qpx_qvfcfidu, dl, MVT::i32), 8647 LoadedVect); 8648 8649 SDValue FPZeros = DAG.getConstantFP(0.0, dl, MVT::v4f64); 8650 8651 return DAG.getSetCC(dl, MVT::v4i1, LoadedVect, FPZeros, ISD::SETEQ); 8652 } 8653 8654 // All other QPX vectors are handled by generic code. 8655 if (Subtarget.hasQPX()) 8656 return SDValue(); 8657 8658 // Check if this is a splat of a constant value. 8659 APInt APSplatBits, APSplatUndef; 8660 unsigned SplatBitSize; 8661 bool HasAnyUndefs; 8662 if (! BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize, 8663 HasAnyUndefs, 0, !Subtarget.isLittleEndian()) || 8664 SplatBitSize > 32) { 8665 8666 const SDValue *InputLoad = getNormalLoadInput(Op.getOperand(0)); 8667 // Handle load-and-splat patterns as we have instructions that will do this 8668 // in one go. 8669 if (InputLoad && DAG.isSplatValue(Op, true)) { 8670 LoadSDNode *LD = cast<LoadSDNode>(*InputLoad); 8671 8672 // We have handling for 4 and 8 byte elements. 8673 unsigned ElementSize = LD->getMemoryVT().getScalarSizeInBits(); 8674 8675 // Checking for a single use of this load, we have to check for vector 8676 // width (128 bits) / ElementSize uses (since each operand of the 8677 // BUILD_VECTOR is a separate use of the value. 8678 if (InputLoad->getNode()->hasNUsesOfValue(128 / ElementSize, 0) && 8679 ((Subtarget.hasVSX() && ElementSize == 64) || 8680 (Subtarget.hasP9Vector() && ElementSize == 32))) { 8681 SDValue Ops[] = { 8682 LD->getChain(), // Chain 8683 LD->getBasePtr(), // Ptr 8684 DAG.getValueType(Op.getValueType()) // VT 8685 }; 8686 return 8687 DAG.getMemIntrinsicNode(PPCISD::LD_SPLAT, dl, 8688 DAG.getVTList(Op.getValueType(), MVT::Other), 8689 Ops, LD->getMemoryVT(), LD->getMemOperand()); 8690 } 8691 } 8692 8693 // BUILD_VECTOR nodes that are not constant splats of up to 32-bits can be 8694 // lowered to VSX instructions under certain conditions. 8695 // Without VSX, there is no pattern more efficient than expanding the node. 8696 if (Subtarget.hasVSX() && 8697 haveEfficientBuildVectorPattern(BVN, Subtarget.hasDirectMove(), 8698 Subtarget.hasP8Vector())) 8699 return Op; 8700 return SDValue(); 8701 } 8702 8703 unsigned SplatBits = APSplatBits.getZExtValue(); 8704 unsigned SplatUndef = APSplatUndef.getZExtValue(); 8705 unsigned SplatSize = SplatBitSize / 8; 8706 8707 // First, handle single instruction cases. 8708 8709 // All zeros? 8710 if (SplatBits == 0) { 8711 // Canonicalize all zero vectors to be v4i32. 8712 if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) { 8713 SDValue Z = DAG.getConstant(0, dl, MVT::v4i32); 8714 Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z); 8715 } 8716 return Op; 8717 } 8718 8719 // We have XXSPLTIB for constant splats one byte wide 8720 // FIXME: SplatBits is an unsigned int being cast to an int while passing it 8721 // as an argument to BuildSplatiI. Given SplatSize == 1 it is okay here. 8722 if (Subtarget.hasP9Vector() && SplatSize == 1) 8723 return BuildSplatI(SplatBits, SplatSize, Op.getValueType(), DAG, dl); 8724 8725 // If the sign extended value is in the range [-16,15], use VSPLTI[bhw]. 8726 int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >> 8727 (32-SplatBitSize)); 8728 if (SextVal >= -16 && SextVal <= 15) 8729 return BuildSplatI(SextVal, SplatSize, Op.getValueType(), DAG, dl); 8730 8731 // Two instruction sequences. 8732 8733 // If this value is in the range [-32,30] and is even, use: 8734 // VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2) 8735 // If this value is in the range [17,31] and is odd, use: 8736 // VSPLTI[bhw](val-16) - VSPLTI[bhw](-16) 8737 // If this value is in the range [-31,-17] and is odd, use: 8738 // VSPLTI[bhw](val+16) + VSPLTI[bhw](-16) 8739 // Note the last two are three-instruction sequences. 8740 if (SextVal >= -32 && SextVal <= 31) { 8741 // To avoid having these optimizations undone by constant folding, 8742 // we convert to a pseudo that will be expanded later into one of 8743 // the above forms. 8744 SDValue Elt = DAG.getConstant(SextVal, dl, MVT::i32); 8745 EVT VT = (SplatSize == 1 ? MVT::v16i8 : 8746 (SplatSize == 2 ? MVT::v8i16 : MVT::v4i32)); 8747 SDValue EltSize = DAG.getConstant(SplatSize, dl, MVT::i32); 8748 SDValue RetVal = DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize); 8749 if (VT == Op.getValueType()) 8750 return RetVal; 8751 else 8752 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), RetVal); 8753 } 8754 8755 // If this is 0x8000_0000 x 4, turn into vspltisw + vslw. If it is 8756 // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000). This is important 8757 // for fneg/fabs. 8758 if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) { 8759 // Make -1 and vspltisw -1: 8760 SDValue OnesV = BuildSplatI(-1, 4, MVT::v4i32, DAG, dl); 8761 8762 // Make the VSLW intrinsic, computing 0x8000_0000. 8763 SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV, 8764 OnesV, DAG, dl); 8765 8766 // xor by OnesV to invert it. 8767 Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV); 8768 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 8769 } 8770 8771 // Check to see if this is a wide variety of vsplti*, binop self cases. 8772 static const signed char SplatCsts[] = { 8773 -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7, 8774 -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16 8775 }; 8776 8777 for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) { 8778 // Indirect through the SplatCsts array so that we favor 'vsplti -1' for 8779 // cases which are ambiguous (e.g. formation of 0x8000_0000). 'vsplti -1' 8780 int i = SplatCsts[idx]; 8781 8782 // Figure out what shift amount will be used by altivec if shifted by i in 8783 // this splat size. 8784 unsigned TypeShiftAmt = i & (SplatBitSize-1); 8785 8786 // vsplti + shl self. 8787 if (SextVal == (int)((unsigned)i << TypeShiftAmt)) { 8788 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl); 8789 static const unsigned IIDs[] = { // Intrinsic to use for each size. 8790 Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0, 8791 Intrinsic::ppc_altivec_vslw 8792 }; 8793 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 8794 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 8795 } 8796 8797 // vsplti + srl self. 8798 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) { 8799 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl); 8800 static const unsigned IIDs[] = { // Intrinsic to use for each size. 8801 Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0, 8802 Intrinsic::ppc_altivec_vsrw 8803 }; 8804 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 8805 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 8806 } 8807 8808 // vsplti + sra self. 8809 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) { 8810 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl); 8811 static const unsigned IIDs[] = { // Intrinsic to use for each size. 8812 Intrinsic::ppc_altivec_vsrab, Intrinsic::ppc_altivec_vsrah, 0, 8813 Intrinsic::ppc_altivec_vsraw 8814 }; 8815 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 8816 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 8817 } 8818 8819 // vsplti + rol self. 8820 if (SextVal == (int)(((unsigned)i << TypeShiftAmt) | 8821 ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) { 8822 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl); 8823 static const unsigned IIDs[] = { // Intrinsic to use for each size. 8824 Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0, 8825 Intrinsic::ppc_altivec_vrlw 8826 }; 8827 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 8828 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 8829 } 8830 8831 // t = vsplti c, result = vsldoi t, t, 1 8832 if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) { 8833 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl); 8834 unsigned Amt = Subtarget.isLittleEndian() ? 15 : 1; 8835 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl); 8836 } 8837 // t = vsplti c, result = vsldoi t, t, 2 8838 if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) { 8839 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl); 8840 unsigned Amt = Subtarget.isLittleEndian() ? 14 : 2; 8841 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl); 8842 } 8843 // t = vsplti c, result = vsldoi t, t, 3 8844 if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) { 8845 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl); 8846 unsigned Amt = Subtarget.isLittleEndian() ? 13 : 3; 8847 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl); 8848 } 8849 } 8850 8851 return SDValue(); 8852 } 8853 8854 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit 8855 /// the specified operations to build the shuffle. 8856 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS, 8857 SDValue RHS, SelectionDAG &DAG, 8858 const SDLoc &dl) { 8859 unsigned OpNum = (PFEntry >> 26) & 0x0F; 8860 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1); 8861 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1); 8862 8863 enum { 8864 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3> 8865 OP_VMRGHW, 8866 OP_VMRGLW, 8867 OP_VSPLTISW0, 8868 OP_VSPLTISW1, 8869 OP_VSPLTISW2, 8870 OP_VSPLTISW3, 8871 OP_VSLDOI4, 8872 OP_VSLDOI8, 8873 OP_VSLDOI12 8874 }; 8875 8876 if (OpNum == OP_COPY) { 8877 if (LHSID == (1*9+2)*9+3) return LHS; 8878 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!"); 8879 return RHS; 8880 } 8881 8882 SDValue OpLHS, OpRHS; 8883 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl); 8884 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl); 8885 8886 int ShufIdxs[16]; 8887 switch (OpNum) { 8888 default: llvm_unreachable("Unknown i32 permute!"); 8889 case OP_VMRGHW: 8890 ShufIdxs[ 0] = 0; ShufIdxs[ 1] = 1; ShufIdxs[ 2] = 2; ShufIdxs[ 3] = 3; 8891 ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19; 8892 ShufIdxs[ 8] = 4; ShufIdxs[ 9] = 5; ShufIdxs[10] = 6; ShufIdxs[11] = 7; 8893 ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23; 8894 break; 8895 case OP_VMRGLW: 8896 ShufIdxs[ 0] = 8; ShufIdxs[ 1] = 9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11; 8897 ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27; 8898 ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15; 8899 ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31; 8900 break; 8901 case OP_VSPLTISW0: 8902 for (unsigned i = 0; i != 16; ++i) 8903 ShufIdxs[i] = (i&3)+0; 8904 break; 8905 case OP_VSPLTISW1: 8906 for (unsigned i = 0; i != 16; ++i) 8907 ShufIdxs[i] = (i&3)+4; 8908 break; 8909 case OP_VSPLTISW2: 8910 for (unsigned i = 0; i != 16; ++i) 8911 ShufIdxs[i] = (i&3)+8; 8912 break; 8913 case OP_VSPLTISW3: 8914 for (unsigned i = 0; i != 16; ++i) 8915 ShufIdxs[i] = (i&3)+12; 8916 break; 8917 case OP_VSLDOI4: 8918 return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl); 8919 case OP_VSLDOI8: 8920 return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl); 8921 case OP_VSLDOI12: 8922 return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl); 8923 } 8924 EVT VT = OpLHS.getValueType(); 8925 OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS); 8926 OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS); 8927 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs); 8928 return DAG.getNode(ISD::BITCAST, dl, VT, T); 8929 } 8930 8931 /// lowerToVINSERTB - Return the SDValue if this VECTOR_SHUFFLE can be handled 8932 /// by the VINSERTB instruction introduced in ISA 3.0, else just return default 8933 /// SDValue. 8934 SDValue PPCTargetLowering::lowerToVINSERTB(ShuffleVectorSDNode *N, 8935 SelectionDAG &DAG) const { 8936 const unsigned BytesInVector = 16; 8937 bool IsLE = Subtarget.isLittleEndian(); 8938 SDLoc dl(N); 8939 SDValue V1 = N->getOperand(0); 8940 SDValue V2 = N->getOperand(1); 8941 unsigned ShiftElts = 0, InsertAtByte = 0; 8942 bool Swap = false; 8943 8944 // Shifts required to get the byte we want at element 7. 8945 unsigned LittleEndianShifts[] = {8, 7, 6, 5, 4, 3, 2, 1, 8946 0, 15, 14, 13, 12, 11, 10, 9}; 8947 unsigned BigEndianShifts[] = {9, 10, 11, 12, 13, 14, 15, 0, 8948 1, 2, 3, 4, 5, 6, 7, 8}; 8949 8950 ArrayRef<int> Mask = N->getMask(); 8951 int OriginalOrder[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}; 8952 8953 // For each mask element, find out if we're just inserting something 8954 // from V2 into V1 or vice versa. 8955 // Possible permutations inserting an element from V2 into V1: 8956 // X, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 8957 // 0, X, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 8958 // ... 8959 // 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, X 8960 // Inserting from V1 into V2 will be similar, except mask range will be 8961 // [16,31]. 8962 8963 bool FoundCandidate = false; 8964 // If both vector operands for the shuffle are the same vector, the mask 8965 // will contain only elements from the first one and the second one will be 8966 // undef. 8967 unsigned VINSERTBSrcElem = IsLE ? 8 : 7; 8968 // Go through the mask of half-words to find an element that's being moved 8969 // from one vector to the other. 8970 for (unsigned i = 0; i < BytesInVector; ++i) { 8971 unsigned CurrentElement = Mask[i]; 8972 // If 2nd operand is undefined, we should only look for element 7 in the 8973 // Mask. 8974 if (V2.isUndef() && CurrentElement != VINSERTBSrcElem) 8975 continue; 8976 8977 bool OtherElementsInOrder = true; 8978 // Examine the other elements in the Mask to see if they're in original 8979 // order. 8980 for (unsigned j = 0; j < BytesInVector; ++j) { 8981 if (j == i) 8982 continue; 8983 // If CurrentElement is from V1 [0,15], then we the rest of the Mask to be 8984 // from V2 [16,31] and vice versa. Unless the 2nd operand is undefined, 8985 // in which we always assume we're always picking from the 1st operand. 8986 int MaskOffset = 8987 (!V2.isUndef() && CurrentElement < BytesInVector) ? BytesInVector : 0; 8988 if (Mask[j] != OriginalOrder[j] + MaskOffset) { 8989 OtherElementsInOrder = false; 8990 break; 8991 } 8992 } 8993 // If other elements are in original order, we record the number of shifts 8994 // we need to get the element we want into element 7. Also record which byte 8995 // in the vector we should insert into. 8996 if (OtherElementsInOrder) { 8997 // If 2nd operand is undefined, we assume no shifts and no swapping. 8998 if (V2.isUndef()) { 8999 ShiftElts = 0; 9000 Swap = false; 9001 } else { 9002 // Only need the last 4-bits for shifts because operands will be swapped if CurrentElement is >= 2^4. 9003 ShiftElts = IsLE ? LittleEndianShifts[CurrentElement & 0xF] 9004 : BigEndianShifts[CurrentElement & 0xF]; 9005 Swap = CurrentElement < BytesInVector; 9006 } 9007 InsertAtByte = IsLE ? BytesInVector - (i + 1) : i; 9008 FoundCandidate = true; 9009 break; 9010 } 9011 } 9012 9013 if (!FoundCandidate) 9014 return SDValue(); 9015 9016 // Candidate found, construct the proper SDAG sequence with VINSERTB, 9017 // optionally with VECSHL if shift is required. 9018 if (Swap) 9019 std::swap(V1, V2); 9020 if (V2.isUndef()) 9021 V2 = V1; 9022 if (ShiftElts) { 9023 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2, 9024 DAG.getConstant(ShiftElts, dl, MVT::i32)); 9025 return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, Shl, 9026 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9027 } 9028 return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, V2, 9029 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9030 } 9031 9032 /// lowerToVINSERTH - Return the SDValue if this VECTOR_SHUFFLE can be handled 9033 /// by the VINSERTH instruction introduced in ISA 3.0, else just return default 9034 /// SDValue. 9035 SDValue PPCTargetLowering::lowerToVINSERTH(ShuffleVectorSDNode *N, 9036 SelectionDAG &DAG) const { 9037 const unsigned NumHalfWords = 8; 9038 const unsigned BytesInVector = NumHalfWords * 2; 9039 // Check that the shuffle is on half-words. 9040 if (!isNByteElemShuffleMask(N, 2, 1)) 9041 return SDValue(); 9042 9043 bool IsLE = Subtarget.isLittleEndian(); 9044 SDLoc dl(N); 9045 SDValue V1 = N->getOperand(0); 9046 SDValue V2 = N->getOperand(1); 9047 unsigned ShiftElts = 0, InsertAtByte = 0; 9048 bool Swap = false; 9049 9050 // Shifts required to get the half-word we want at element 3. 9051 unsigned LittleEndianShifts[] = {4, 3, 2, 1, 0, 7, 6, 5}; 9052 unsigned BigEndianShifts[] = {5, 6, 7, 0, 1, 2, 3, 4}; 9053 9054 uint32_t Mask = 0; 9055 uint32_t OriginalOrderLow = 0x1234567; 9056 uint32_t OriginalOrderHigh = 0x89ABCDEF; 9057 // Now we look at mask elements 0,2,4,6,8,10,12,14. Pack the mask into a 9058 // 32-bit space, only need 4-bit nibbles per element. 9059 for (unsigned i = 0; i < NumHalfWords; ++i) { 9060 unsigned MaskShift = (NumHalfWords - 1 - i) * 4; 9061 Mask |= ((uint32_t)(N->getMaskElt(i * 2) / 2) << MaskShift); 9062 } 9063 9064 // For each mask element, find out if we're just inserting something 9065 // from V2 into V1 or vice versa. Possible permutations inserting an element 9066 // from V2 into V1: 9067 // X, 1, 2, 3, 4, 5, 6, 7 9068 // 0, X, 2, 3, 4, 5, 6, 7 9069 // 0, 1, X, 3, 4, 5, 6, 7 9070 // 0, 1, 2, X, 4, 5, 6, 7 9071 // 0, 1, 2, 3, X, 5, 6, 7 9072 // 0, 1, 2, 3, 4, X, 6, 7 9073 // 0, 1, 2, 3, 4, 5, X, 7 9074 // 0, 1, 2, 3, 4, 5, 6, X 9075 // Inserting from V1 into V2 will be similar, except mask range will be [8,15]. 9076 9077 bool FoundCandidate = false; 9078 // Go through the mask of half-words to find an element that's being moved 9079 // from one vector to the other. 9080 for (unsigned i = 0; i < NumHalfWords; ++i) { 9081 unsigned MaskShift = (NumHalfWords - 1 - i) * 4; 9082 uint32_t MaskOneElt = (Mask >> MaskShift) & 0xF; 9083 uint32_t MaskOtherElts = ~(0xF << MaskShift); 9084 uint32_t TargetOrder = 0x0; 9085 9086 // If both vector operands for the shuffle are the same vector, the mask 9087 // will contain only elements from the first one and the second one will be 9088 // undef. 9089 if (V2.isUndef()) { 9090 ShiftElts = 0; 9091 unsigned VINSERTHSrcElem = IsLE ? 4 : 3; 9092 TargetOrder = OriginalOrderLow; 9093 Swap = false; 9094 // Skip if not the correct element or mask of other elements don't equal 9095 // to our expected order. 9096 if (MaskOneElt == VINSERTHSrcElem && 9097 (Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) { 9098 InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2; 9099 FoundCandidate = true; 9100 break; 9101 } 9102 } else { // If both operands are defined. 9103 // Target order is [8,15] if the current mask is between [0,7]. 9104 TargetOrder = 9105 (MaskOneElt < NumHalfWords) ? OriginalOrderHigh : OriginalOrderLow; 9106 // Skip if mask of other elements don't equal our expected order. 9107 if ((Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) { 9108 // We only need the last 3 bits for the number of shifts. 9109 ShiftElts = IsLE ? LittleEndianShifts[MaskOneElt & 0x7] 9110 : BigEndianShifts[MaskOneElt & 0x7]; 9111 InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2; 9112 Swap = MaskOneElt < NumHalfWords; 9113 FoundCandidate = true; 9114 break; 9115 } 9116 } 9117 } 9118 9119 if (!FoundCandidate) 9120 return SDValue(); 9121 9122 // Candidate found, construct the proper SDAG sequence with VINSERTH, 9123 // optionally with VECSHL if shift is required. 9124 if (Swap) 9125 std::swap(V1, V2); 9126 if (V2.isUndef()) 9127 V2 = V1; 9128 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1); 9129 if (ShiftElts) { 9130 // Double ShiftElts because we're left shifting on v16i8 type. 9131 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2, 9132 DAG.getConstant(2 * ShiftElts, dl, MVT::i32)); 9133 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, Shl); 9134 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2, 9135 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9136 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 9137 } 9138 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2); 9139 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2, 9140 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9141 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 9142 } 9143 9144 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE. If this 9145 /// is a shuffle we can handle in a single instruction, return it. Otherwise, 9146 /// return the code it can be lowered into. Worst case, it can always be 9147 /// lowered into a vperm. 9148 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, 9149 SelectionDAG &DAG) const { 9150 SDLoc dl(Op); 9151 SDValue V1 = Op.getOperand(0); 9152 SDValue V2 = Op.getOperand(1); 9153 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op); 9154 EVT VT = Op.getValueType(); 9155 bool isLittleEndian = Subtarget.isLittleEndian(); 9156 9157 unsigned ShiftElts, InsertAtByte; 9158 bool Swap = false; 9159 9160 // If this is a load-and-splat, we can do that with a single instruction 9161 // in some cases. However if the load has multiple uses, we don't want to 9162 // combine it because that will just produce multiple loads. 9163 const SDValue *InputLoad = getNormalLoadInput(V1); 9164 if (InputLoad && Subtarget.hasVSX() && V2.isUndef() && 9165 (PPC::isSplatShuffleMask(SVOp, 4) || PPC::isSplatShuffleMask(SVOp, 8)) && 9166 InputLoad->hasOneUse()) { 9167 bool IsFourByte = PPC::isSplatShuffleMask(SVOp, 4); 9168 int SplatIdx = 9169 PPC::getSplatIdxForPPCMnemonics(SVOp, IsFourByte ? 4 : 8, DAG); 9170 9171 LoadSDNode *LD = cast<LoadSDNode>(*InputLoad); 9172 // For 4-byte load-and-splat, we need Power9. 9173 if ((IsFourByte && Subtarget.hasP9Vector()) || !IsFourByte) { 9174 uint64_t Offset = 0; 9175 if (IsFourByte) 9176 Offset = isLittleEndian ? (3 - SplatIdx) * 4 : SplatIdx * 4; 9177 else 9178 Offset = isLittleEndian ? (1 - SplatIdx) * 8 : SplatIdx * 8; 9179 SDValue BasePtr = LD->getBasePtr(); 9180 if (Offset != 0) 9181 BasePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()), 9182 BasePtr, DAG.getIntPtrConstant(Offset, dl)); 9183 SDValue Ops[] = { 9184 LD->getChain(), // Chain 9185 BasePtr, // BasePtr 9186 DAG.getValueType(Op.getValueType()) // VT 9187 }; 9188 SDVTList VTL = 9189 DAG.getVTList(IsFourByte ? MVT::v4i32 : MVT::v2i64, MVT::Other); 9190 SDValue LdSplt = 9191 DAG.getMemIntrinsicNode(PPCISD::LD_SPLAT, dl, VTL, 9192 Ops, LD->getMemoryVT(), LD->getMemOperand()); 9193 if (LdSplt.getValueType() != SVOp->getValueType(0)) 9194 LdSplt = DAG.getBitcast(SVOp->getValueType(0), LdSplt); 9195 return LdSplt; 9196 } 9197 } 9198 if (Subtarget.hasP9Vector() && 9199 PPC::isXXINSERTWMask(SVOp, ShiftElts, InsertAtByte, Swap, 9200 isLittleEndian)) { 9201 if (Swap) 9202 std::swap(V1, V2); 9203 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 9204 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2); 9205 if (ShiftElts) { 9206 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv2, Conv2, 9207 DAG.getConstant(ShiftElts, dl, MVT::i32)); 9208 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Shl, 9209 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9210 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 9211 } 9212 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Conv2, 9213 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9214 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 9215 } 9216 9217 if (Subtarget.hasP9Altivec()) { 9218 SDValue NewISDNode; 9219 if ((NewISDNode = lowerToVINSERTH(SVOp, DAG))) 9220 return NewISDNode; 9221 9222 if ((NewISDNode = lowerToVINSERTB(SVOp, DAG))) 9223 return NewISDNode; 9224 } 9225 9226 if (Subtarget.hasVSX() && 9227 PPC::isXXSLDWIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) { 9228 if (Swap) 9229 std::swap(V1, V2); 9230 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 9231 SDValue Conv2 = 9232 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2.isUndef() ? V1 : V2); 9233 9234 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv1, Conv2, 9235 DAG.getConstant(ShiftElts, dl, MVT::i32)); 9236 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Shl); 9237 } 9238 9239 if (Subtarget.hasVSX() && 9240 PPC::isXXPERMDIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) { 9241 if (Swap) 9242 std::swap(V1, V2); 9243 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1); 9244 SDValue Conv2 = 9245 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2.isUndef() ? V1 : V2); 9246 9247 SDValue PermDI = DAG.getNode(PPCISD::XXPERMDI, dl, MVT::v2i64, Conv1, Conv2, 9248 DAG.getConstant(ShiftElts, dl, MVT::i32)); 9249 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, PermDI); 9250 } 9251 9252 if (Subtarget.hasP9Vector()) { 9253 if (PPC::isXXBRHShuffleMask(SVOp)) { 9254 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1); 9255 SDValue ReveHWord = DAG.getNode(ISD::BSWAP, dl, MVT::v8i16, Conv); 9256 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveHWord); 9257 } else if (PPC::isXXBRWShuffleMask(SVOp)) { 9258 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 9259 SDValue ReveWord = DAG.getNode(ISD::BSWAP, dl, MVT::v4i32, Conv); 9260 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveWord); 9261 } else if (PPC::isXXBRDShuffleMask(SVOp)) { 9262 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1); 9263 SDValue ReveDWord = DAG.getNode(ISD::BSWAP, dl, MVT::v2i64, Conv); 9264 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveDWord); 9265 } else if (PPC::isXXBRQShuffleMask(SVOp)) { 9266 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, V1); 9267 SDValue ReveQWord = DAG.getNode(ISD::BSWAP, dl, MVT::v1i128, Conv); 9268 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveQWord); 9269 } 9270 } 9271 9272 if (Subtarget.hasVSX()) { 9273 if (V2.isUndef() && PPC::isSplatShuffleMask(SVOp, 4)) { 9274 int SplatIdx = PPC::getSplatIdxForPPCMnemonics(SVOp, 4, DAG); 9275 9276 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 9277 SDValue Splat = DAG.getNode(PPCISD::XXSPLT, dl, MVT::v4i32, Conv, 9278 DAG.getConstant(SplatIdx, dl, MVT::i32)); 9279 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Splat); 9280 } 9281 9282 // Left shifts of 8 bytes are actually swaps. Convert accordingly. 9283 if (V2.isUndef() && PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) == 8) { 9284 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1); 9285 SDValue Swap = DAG.getNode(PPCISD::SWAP_NO_CHAIN, dl, MVT::v2f64, Conv); 9286 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Swap); 9287 } 9288 } 9289 9290 if (Subtarget.hasQPX()) { 9291 if (VT.getVectorNumElements() != 4) 9292 return SDValue(); 9293 9294 if (V2.isUndef()) V2 = V1; 9295 9296 int AlignIdx = PPC::isQVALIGNIShuffleMask(SVOp); 9297 if (AlignIdx != -1) { 9298 return DAG.getNode(PPCISD::QVALIGNI, dl, VT, V1, V2, 9299 DAG.getConstant(AlignIdx, dl, MVT::i32)); 9300 } else if (SVOp->isSplat()) { 9301 int SplatIdx = SVOp->getSplatIndex(); 9302 if (SplatIdx >= 4) { 9303 std::swap(V1, V2); 9304 SplatIdx -= 4; 9305 } 9306 9307 return DAG.getNode(PPCISD::QVESPLATI, dl, VT, V1, 9308 DAG.getConstant(SplatIdx, dl, MVT::i32)); 9309 } 9310 9311 // Lower this into a qvgpci/qvfperm pair. 9312 9313 // Compute the qvgpci literal 9314 unsigned idx = 0; 9315 for (unsigned i = 0; i < 4; ++i) { 9316 int m = SVOp->getMaskElt(i); 9317 unsigned mm = m >= 0 ? (unsigned) m : i; 9318 idx |= mm << (3-i)*3; 9319 } 9320 9321 SDValue V3 = DAG.getNode(PPCISD::QVGPCI, dl, MVT::v4f64, 9322 DAG.getConstant(idx, dl, MVT::i32)); 9323 return DAG.getNode(PPCISD::QVFPERM, dl, VT, V1, V2, V3); 9324 } 9325 9326 // Cases that are handled by instructions that take permute immediates 9327 // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be 9328 // selected by the instruction selector. 9329 if (V2.isUndef()) { 9330 if (PPC::isSplatShuffleMask(SVOp, 1) || 9331 PPC::isSplatShuffleMask(SVOp, 2) || 9332 PPC::isSplatShuffleMask(SVOp, 4) || 9333 PPC::isVPKUWUMShuffleMask(SVOp, 1, DAG) || 9334 PPC::isVPKUHUMShuffleMask(SVOp, 1, DAG) || 9335 PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) != -1 || 9336 PPC::isVMRGLShuffleMask(SVOp, 1, 1, DAG) || 9337 PPC::isVMRGLShuffleMask(SVOp, 2, 1, DAG) || 9338 PPC::isVMRGLShuffleMask(SVOp, 4, 1, DAG) || 9339 PPC::isVMRGHShuffleMask(SVOp, 1, 1, DAG) || 9340 PPC::isVMRGHShuffleMask(SVOp, 2, 1, DAG) || 9341 PPC::isVMRGHShuffleMask(SVOp, 4, 1, DAG) || 9342 (Subtarget.hasP8Altivec() && ( 9343 PPC::isVPKUDUMShuffleMask(SVOp, 1, DAG) || 9344 PPC::isVMRGEOShuffleMask(SVOp, true, 1, DAG) || 9345 PPC::isVMRGEOShuffleMask(SVOp, false, 1, DAG)))) { 9346 return Op; 9347 } 9348 } 9349 9350 // Altivec has a variety of "shuffle immediates" that take two vector inputs 9351 // and produce a fixed permutation. If any of these match, do not lower to 9352 // VPERM. 9353 unsigned int ShuffleKind = isLittleEndian ? 2 : 0; 9354 if (PPC::isVPKUWUMShuffleMask(SVOp, ShuffleKind, DAG) || 9355 PPC::isVPKUHUMShuffleMask(SVOp, ShuffleKind, DAG) || 9356 PPC::isVSLDOIShuffleMask(SVOp, ShuffleKind, DAG) != -1 || 9357 PPC::isVMRGLShuffleMask(SVOp, 1, ShuffleKind, DAG) || 9358 PPC::isVMRGLShuffleMask(SVOp, 2, ShuffleKind, DAG) || 9359 PPC::isVMRGLShuffleMask(SVOp, 4, ShuffleKind, DAG) || 9360 PPC::isVMRGHShuffleMask(SVOp, 1, ShuffleKind, DAG) || 9361 PPC::isVMRGHShuffleMask(SVOp, 2, ShuffleKind, DAG) || 9362 PPC::isVMRGHShuffleMask(SVOp, 4, ShuffleKind, DAG) || 9363 (Subtarget.hasP8Altivec() && ( 9364 PPC::isVPKUDUMShuffleMask(SVOp, ShuffleKind, DAG) || 9365 PPC::isVMRGEOShuffleMask(SVOp, true, ShuffleKind, DAG) || 9366 PPC::isVMRGEOShuffleMask(SVOp, false, ShuffleKind, DAG)))) 9367 return Op; 9368 9369 // Check to see if this is a shuffle of 4-byte values. If so, we can use our 9370 // perfect shuffle table to emit an optimal matching sequence. 9371 ArrayRef<int> PermMask = SVOp->getMask(); 9372 9373 unsigned PFIndexes[4]; 9374 bool isFourElementShuffle = true; 9375 for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number 9376 unsigned EltNo = 8; // Start out undef. 9377 for (unsigned j = 0; j != 4; ++j) { // Intra-element byte. 9378 if (PermMask[i*4+j] < 0) 9379 continue; // Undef, ignore it. 9380 9381 unsigned ByteSource = PermMask[i*4+j]; 9382 if ((ByteSource & 3) != j) { 9383 isFourElementShuffle = false; 9384 break; 9385 } 9386 9387 if (EltNo == 8) { 9388 EltNo = ByteSource/4; 9389 } else if (EltNo != ByteSource/4) { 9390 isFourElementShuffle = false; 9391 break; 9392 } 9393 } 9394 PFIndexes[i] = EltNo; 9395 } 9396 9397 // If this shuffle can be expressed as a shuffle of 4-byte elements, use the 9398 // perfect shuffle vector to determine if it is cost effective to do this as 9399 // discrete instructions, or whether we should use a vperm. 9400 // For now, we skip this for little endian until such time as we have a 9401 // little-endian perfect shuffle table. 9402 if (isFourElementShuffle && !isLittleEndian) { 9403 // Compute the index in the perfect shuffle table. 9404 unsigned PFTableIndex = 9405 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3]; 9406 9407 unsigned PFEntry = PerfectShuffleTable[PFTableIndex]; 9408 unsigned Cost = (PFEntry >> 30); 9409 9410 // Determining when to avoid vperm is tricky. Many things affect the cost 9411 // of vperm, particularly how many times the perm mask needs to be computed. 9412 // For example, if the perm mask can be hoisted out of a loop or is already 9413 // used (perhaps because there are multiple permutes with the same shuffle 9414 // mask?) the vperm has a cost of 1. OTOH, hoisting the permute mask out of 9415 // the loop requires an extra register. 9416 // 9417 // As a compromise, we only emit discrete instructions if the shuffle can be 9418 // generated in 3 or fewer operations. When we have loop information 9419 // available, if this block is within a loop, we should avoid using vperm 9420 // for 3-operation perms and use a constant pool load instead. 9421 if (Cost < 3) 9422 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl); 9423 } 9424 9425 // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant 9426 // vector that will get spilled to the constant pool. 9427 if (V2.isUndef()) V2 = V1; 9428 9429 // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except 9430 // that it is in input element units, not in bytes. Convert now. 9431 9432 // For little endian, the order of the input vectors is reversed, and 9433 // the permutation mask is complemented with respect to 31. This is 9434 // necessary to produce proper semantics with the big-endian-biased vperm 9435 // instruction. 9436 EVT EltVT = V1.getValueType().getVectorElementType(); 9437 unsigned BytesPerElement = EltVT.getSizeInBits()/8; 9438 9439 SmallVector<SDValue, 16> ResultMask; 9440 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) { 9441 unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i]; 9442 9443 for (unsigned j = 0; j != BytesPerElement; ++j) 9444 if (isLittleEndian) 9445 ResultMask.push_back(DAG.getConstant(31 - (SrcElt*BytesPerElement + j), 9446 dl, MVT::i32)); 9447 else 9448 ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement + j, dl, 9449 MVT::i32)); 9450 } 9451 9452 SDValue VPermMask = DAG.getBuildVector(MVT::v16i8, dl, ResultMask); 9453 if (isLittleEndian) 9454 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(), 9455 V2, V1, VPermMask); 9456 else 9457 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(), 9458 V1, V2, VPermMask); 9459 } 9460 9461 /// getVectorCompareInfo - Given an intrinsic, return false if it is not a 9462 /// vector comparison. If it is, return true and fill in Opc/isDot with 9463 /// information about the intrinsic. 9464 static bool getVectorCompareInfo(SDValue Intrin, int &CompareOpc, 9465 bool &isDot, const PPCSubtarget &Subtarget) { 9466 unsigned IntrinsicID = 9467 cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue(); 9468 CompareOpc = -1; 9469 isDot = false; 9470 switch (IntrinsicID) { 9471 default: 9472 return false; 9473 // Comparison predicates. 9474 case Intrinsic::ppc_altivec_vcmpbfp_p: 9475 CompareOpc = 966; 9476 isDot = true; 9477 break; 9478 case Intrinsic::ppc_altivec_vcmpeqfp_p: 9479 CompareOpc = 198; 9480 isDot = true; 9481 break; 9482 case Intrinsic::ppc_altivec_vcmpequb_p: 9483 CompareOpc = 6; 9484 isDot = true; 9485 break; 9486 case Intrinsic::ppc_altivec_vcmpequh_p: 9487 CompareOpc = 70; 9488 isDot = true; 9489 break; 9490 case Intrinsic::ppc_altivec_vcmpequw_p: 9491 CompareOpc = 134; 9492 isDot = true; 9493 break; 9494 case Intrinsic::ppc_altivec_vcmpequd_p: 9495 if (Subtarget.hasP8Altivec()) { 9496 CompareOpc = 199; 9497 isDot = true; 9498 } else 9499 return false; 9500 break; 9501 case Intrinsic::ppc_altivec_vcmpneb_p: 9502 case Intrinsic::ppc_altivec_vcmpneh_p: 9503 case Intrinsic::ppc_altivec_vcmpnew_p: 9504 case Intrinsic::ppc_altivec_vcmpnezb_p: 9505 case Intrinsic::ppc_altivec_vcmpnezh_p: 9506 case Intrinsic::ppc_altivec_vcmpnezw_p: 9507 if (Subtarget.hasP9Altivec()) { 9508 switch (IntrinsicID) { 9509 default: 9510 llvm_unreachable("Unknown comparison intrinsic."); 9511 case Intrinsic::ppc_altivec_vcmpneb_p: 9512 CompareOpc = 7; 9513 break; 9514 case Intrinsic::ppc_altivec_vcmpneh_p: 9515 CompareOpc = 71; 9516 break; 9517 case Intrinsic::ppc_altivec_vcmpnew_p: 9518 CompareOpc = 135; 9519 break; 9520 case Intrinsic::ppc_altivec_vcmpnezb_p: 9521 CompareOpc = 263; 9522 break; 9523 case Intrinsic::ppc_altivec_vcmpnezh_p: 9524 CompareOpc = 327; 9525 break; 9526 case Intrinsic::ppc_altivec_vcmpnezw_p: 9527 CompareOpc = 391; 9528 break; 9529 } 9530 isDot = true; 9531 } else 9532 return false; 9533 break; 9534 case Intrinsic::ppc_altivec_vcmpgefp_p: 9535 CompareOpc = 454; 9536 isDot = true; 9537 break; 9538 case Intrinsic::ppc_altivec_vcmpgtfp_p: 9539 CompareOpc = 710; 9540 isDot = true; 9541 break; 9542 case Intrinsic::ppc_altivec_vcmpgtsb_p: 9543 CompareOpc = 774; 9544 isDot = true; 9545 break; 9546 case Intrinsic::ppc_altivec_vcmpgtsh_p: 9547 CompareOpc = 838; 9548 isDot = true; 9549 break; 9550 case Intrinsic::ppc_altivec_vcmpgtsw_p: 9551 CompareOpc = 902; 9552 isDot = true; 9553 break; 9554 case Intrinsic::ppc_altivec_vcmpgtsd_p: 9555 if (Subtarget.hasP8Altivec()) { 9556 CompareOpc = 967; 9557 isDot = true; 9558 } else 9559 return false; 9560 break; 9561 case Intrinsic::ppc_altivec_vcmpgtub_p: 9562 CompareOpc = 518; 9563 isDot = true; 9564 break; 9565 case Intrinsic::ppc_altivec_vcmpgtuh_p: 9566 CompareOpc = 582; 9567 isDot = true; 9568 break; 9569 case Intrinsic::ppc_altivec_vcmpgtuw_p: 9570 CompareOpc = 646; 9571 isDot = true; 9572 break; 9573 case Intrinsic::ppc_altivec_vcmpgtud_p: 9574 if (Subtarget.hasP8Altivec()) { 9575 CompareOpc = 711; 9576 isDot = true; 9577 } else 9578 return false; 9579 break; 9580 9581 // VSX predicate comparisons use the same infrastructure 9582 case Intrinsic::ppc_vsx_xvcmpeqdp_p: 9583 case Intrinsic::ppc_vsx_xvcmpgedp_p: 9584 case Intrinsic::ppc_vsx_xvcmpgtdp_p: 9585 case Intrinsic::ppc_vsx_xvcmpeqsp_p: 9586 case Intrinsic::ppc_vsx_xvcmpgesp_p: 9587 case Intrinsic::ppc_vsx_xvcmpgtsp_p: 9588 if (Subtarget.hasVSX()) { 9589 switch (IntrinsicID) { 9590 case Intrinsic::ppc_vsx_xvcmpeqdp_p: 9591 CompareOpc = 99; 9592 break; 9593 case Intrinsic::ppc_vsx_xvcmpgedp_p: 9594 CompareOpc = 115; 9595 break; 9596 case Intrinsic::ppc_vsx_xvcmpgtdp_p: 9597 CompareOpc = 107; 9598 break; 9599 case Intrinsic::ppc_vsx_xvcmpeqsp_p: 9600 CompareOpc = 67; 9601 break; 9602 case Intrinsic::ppc_vsx_xvcmpgesp_p: 9603 CompareOpc = 83; 9604 break; 9605 case Intrinsic::ppc_vsx_xvcmpgtsp_p: 9606 CompareOpc = 75; 9607 break; 9608 } 9609 isDot = true; 9610 } else 9611 return false; 9612 break; 9613 9614 // Normal Comparisons. 9615 case Intrinsic::ppc_altivec_vcmpbfp: 9616 CompareOpc = 966; 9617 break; 9618 case Intrinsic::ppc_altivec_vcmpeqfp: 9619 CompareOpc = 198; 9620 break; 9621 case Intrinsic::ppc_altivec_vcmpequb: 9622 CompareOpc = 6; 9623 break; 9624 case Intrinsic::ppc_altivec_vcmpequh: 9625 CompareOpc = 70; 9626 break; 9627 case Intrinsic::ppc_altivec_vcmpequw: 9628 CompareOpc = 134; 9629 break; 9630 case Intrinsic::ppc_altivec_vcmpequd: 9631 if (Subtarget.hasP8Altivec()) 9632 CompareOpc = 199; 9633 else 9634 return false; 9635 break; 9636 case Intrinsic::ppc_altivec_vcmpneb: 9637 case Intrinsic::ppc_altivec_vcmpneh: 9638 case Intrinsic::ppc_altivec_vcmpnew: 9639 case Intrinsic::ppc_altivec_vcmpnezb: 9640 case Intrinsic::ppc_altivec_vcmpnezh: 9641 case Intrinsic::ppc_altivec_vcmpnezw: 9642 if (Subtarget.hasP9Altivec()) 9643 switch (IntrinsicID) { 9644 default: 9645 llvm_unreachable("Unknown comparison intrinsic."); 9646 case Intrinsic::ppc_altivec_vcmpneb: 9647 CompareOpc = 7; 9648 break; 9649 case Intrinsic::ppc_altivec_vcmpneh: 9650 CompareOpc = 71; 9651 break; 9652 case Intrinsic::ppc_altivec_vcmpnew: 9653 CompareOpc = 135; 9654 break; 9655 case Intrinsic::ppc_altivec_vcmpnezb: 9656 CompareOpc = 263; 9657 break; 9658 case Intrinsic::ppc_altivec_vcmpnezh: 9659 CompareOpc = 327; 9660 break; 9661 case Intrinsic::ppc_altivec_vcmpnezw: 9662 CompareOpc = 391; 9663 break; 9664 } 9665 else 9666 return false; 9667 break; 9668 case Intrinsic::ppc_altivec_vcmpgefp: 9669 CompareOpc = 454; 9670 break; 9671 case Intrinsic::ppc_altivec_vcmpgtfp: 9672 CompareOpc = 710; 9673 break; 9674 case Intrinsic::ppc_altivec_vcmpgtsb: 9675 CompareOpc = 774; 9676 break; 9677 case Intrinsic::ppc_altivec_vcmpgtsh: 9678 CompareOpc = 838; 9679 break; 9680 case Intrinsic::ppc_altivec_vcmpgtsw: 9681 CompareOpc = 902; 9682 break; 9683 case Intrinsic::ppc_altivec_vcmpgtsd: 9684 if (Subtarget.hasP8Altivec()) 9685 CompareOpc = 967; 9686 else 9687 return false; 9688 break; 9689 case Intrinsic::ppc_altivec_vcmpgtub: 9690 CompareOpc = 518; 9691 break; 9692 case Intrinsic::ppc_altivec_vcmpgtuh: 9693 CompareOpc = 582; 9694 break; 9695 case Intrinsic::ppc_altivec_vcmpgtuw: 9696 CompareOpc = 646; 9697 break; 9698 case Intrinsic::ppc_altivec_vcmpgtud: 9699 if (Subtarget.hasP8Altivec()) 9700 CompareOpc = 711; 9701 else 9702 return false; 9703 break; 9704 } 9705 return true; 9706 } 9707 9708 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom 9709 /// lower, do it, otherwise return null. 9710 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 9711 SelectionDAG &DAG) const { 9712 unsigned IntrinsicID = 9713 cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 9714 9715 SDLoc dl(Op); 9716 9717 if (IntrinsicID == Intrinsic::thread_pointer) { 9718 // Reads the thread pointer register, used for __builtin_thread_pointer. 9719 if (Subtarget.isPPC64()) 9720 return DAG.getRegister(PPC::X13, MVT::i64); 9721 return DAG.getRegister(PPC::R2, MVT::i32); 9722 } 9723 9724 // If this is a lowered altivec predicate compare, CompareOpc is set to the 9725 // opcode number of the comparison. 9726 int CompareOpc; 9727 bool isDot; 9728 if (!getVectorCompareInfo(Op, CompareOpc, isDot, Subtarget)) 9729 return SDValue(); // Don't custom lower most intrinsics. 9730 9731 // If this is a non-dot comparison, make the VCMP node and we are done. 9732 if (!isDot) { 9733 SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(), 9734 Op.getOperand(1), Op.getOperand(2), 9735 DAG.getConstant(CompareOpc, dl, MVT::i32)); 9736 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp); 9737 } 9738 9739 // Create the PPCISD altivec 'dot' comparison node. 9740 SDValue Ops[] = { 9741 Op.getOperand(2), // LHS 9742 Op.getOperand(3), // RHS 9743 DAG.getConstant(CompareOpc, dl, MVT::i32) 9744 }; 9745 EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue }; 9746 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops); 9747 9748 // Now that we have the comparison, emit a copy from the CR to a GPR. 9749 // This is flagged to the above dot comparison. 9750 SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32, 9751 DAG.getRegister(PPC::CR6, MVT::i32), 9752 CompNode.getValue(1)); 9753 9754 // Unpack the result based on how the target uses it. 9755 unsigned BitNo; // Bit # of CR6. 9756 bool InvertBit; // Invert result? 9757 switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) { 9758 default: // Can't happen, don't crash on invalid number though. 9759 case 0: // Return the value of the EQ bit of CR6. 9760 BitNo = 0; InvertBit = false; 9761 break; 9762 case 1: // Return the inverted value of the EQ bit of CR6. 9763 BitNo = 0; InvertBit = true; 9764 break; 9765 case 2: // Return the value of the LT bit of CR6. 9766 BitNo = 2; InvertBit = false; 9767 break; 9768 case 3: // Return the inverted value of the LT bit of CR6. 9769 BitNo = 2; InvertBit = true; 9770 break; 9771 } 9772 9773 // Shift the bit into the low position. 9774 Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags, 9775 DAG.getConstant(8 - (3 - BitNo), dl, MVT::i32)); 9776 // Isolate the bit. 9777 Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags, 9778 DAG.getConstant(1, dl, MVT::i32)); 9779 9780 // If we are supposed to, toggle the bit. 9781 if (InvertBit) 9782 Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags, 9783 DAG.getConstant(1, dl, MVT::i32)); 9784 return Flags; 9785 } 9786 9787 SDValue PPCTargetLowering::LowerINTRINSIC_VOID(SDValue Op, 9788 SelectionDAG &DAG) const { 9789 // SelectionDAGBuilder::visitTargetIntrinsic may insert one extra chain to 9790 // the beginning of the argument list. 9791 int ArgStart = isa<ConstantSDNode>(Op.getOperand(0)) ? 0 : 1; 9792 SDLoc DL(Op); 9793 switch (cast<ConstantSDNode>(Op.getOperand(ArgStart))->getZExtValue()) { 9794 case Intrinsic::ppc_cfence: { 9795 assert(ArgStart == 1 && "llvm.ppc.cfence must carry a chain argument."); 9796 assert(Subtarget.isPPC64() && "Only 64-bit is supported for now."); 9797 return SDValue(DAG.getMachineNode(PPC::CFENCE8, DL, MVT::Other, 9798 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, 9799 Op.getOperand(ArgStart + 1)), 9800 Op.getOperand(0)), 9801 0); 9802 } 9803 default: 9804 break; 9805 } 9806 return SDValue(); 9807 } 9808 9809 SDValue PPCTargetLowering::LowerREM(SDValue Op, SelectionDAG &DAG) const { 9810 // Check for a DIV with the same operands as this REM. 9811 for (auto UI : Op.getOperand(1)->uses()) { 9812 if ((Op.getOpcode() == ISD::SREM && UI->getOpcode() == ISD::SDIV) || 9813 (Op.getOpcode() == ISD::UREM && UI->getOpcode() == ISD::UDIV)) 9814 if (UI->getOperand(0) == Op.getOperand(0) && 9815 UI->getOperand(1) == Op.getOperand(1)) 9816 return SDValue(); 9817 } 9818 return Op; 9819 } 9820 9821 // Lower scalar BSWAP64 to xxbrd. 9822 SDValue PPCTargetLowering::LowerBSWAP(SDValue Op, SelectionDAG &DAG) const { 9823 SDLoc dl(Op); 9824 // MTVSRDD 9825 Op = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i64, Op.getOperand(0), 9826 Op.getOperand(0)); 9827 // XXBRD 9828 Op = DAG.getNode(ISD::BSWAP, dl, MVT::v2i64, Op); 9829 // MFVSRD 9830 int VectorIndex = 0; 9831 if (Subtarget.isLittleEndian()) 9832 VectorIndex = 1; 9833 Op = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Op, 9834 DAG.getTargetConstant(VectorIndex, dl, MVT::i32)); 9835 return Op; 9836 } 9837 9838 // ATOMIC_CMP_SWAP for i8/i16 needs to zero-extend its input since it will be 9839 // compared to a value that is atomically loaded (atomic loads zero-extend). 9840 SDValue PPCTargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, 9841 SelectionDAG &DAG) const { 9842 assert(Op.getOpcode() == ISD::ATOMIC_CMP_SWAP && 9843 "Expecting an atomic compare-and-swap here."); 9844 SDLoc dl(Op); 9845 auto *AtomicNode = cast<AtomicSDNode>(Op.getNode()); 9846 EVT MemVT = AtomicNode->getMemoryVT(); 9847 if (MemVT.getSizeInBits() >= 32) 9848 return Op; 9849 9850 SDValue CmpOp = Op.getOperand(2); 9851 // If this is already correctly zero-extended, leave it alone. 9852 auto HighBits = APInt::getHighBitsSet(32, 32 - MemVT.getSizeInBits()); 9853 if (DAG.MaskedValueIsZero(CmpOp, HighBits)) 9854 return Op; 9855 9856 // Clear the high bits of the compare operand. 9857 unsigned MaskVal = (1 << MemVT.getSizeInBits()) - 1; 9858 SDValue NewCmpOp = 9859 DAG.getNode(ISD::AND, dl, MVT::i32, CmpOp, 9860 DAG.getConstant(MaskVal, dl, MVT::i32)); 9861 9862 // Replace the existing compare operand with the properly zero-extended one. 9863 SmallVector<SDValue, 4> Ops; 9864 for (int i = 0, e = AtomicNode->getNumOperands(); i < e; i++) 9865 Ops.push_back(AtomicNode->getOperand(i)); 9866 Ops[2] = NewCmpOp; 9867 MachineMemOperand *MMO = AtomicNode->getMemOperand(); 9868 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::Other); 9869 auto NodeTy = 9870 (MemVT == MVT::i8) ? PPCISD::ATOMIC_CMP_SWAP_8 : PPCISD::ATOMIC_CMP_SWAP_16; 9871 return DAG.getMemIntrinsicNode(NodeTy, dl, Tys, Ops, MemVT, MMO); 9872 } 9873 9874 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, 9875 SelectionDAG &DAG) const { 9876 SDLoc dl(Op); 9877 // Create a stack slot that is 16-byte aligned. 9878 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 9879 int FrameIdx = MFI.CreateStackObject(16, 16, false); 9880 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 9881 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 9882 9883 // Store the input value into Value#0 of the stack slot. 9884 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx, 9885 MachinePointerInfo()); 9886 // Load it out. 9887 return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo()); 9888 } 9889 9890 SDValue PPCTargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, 9891 SelectionDAG &DAG) const { 9892 assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && 9893 "Should only be called for ISD::INSERT_VECTOR_ELT"); 9894 9895 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(2)); 9896 // We have legal lowering for constant indices but not for variable ones. 9897 if (!C) 9898 return SDValue(); 9899 9900 EVT VT = Op.getValueType(); 9901 SDLoc dl(Op); 9902 SDValue V1 = Op.getOperand(0); 9903 SDValue V2 = Op.getOperand(1); 9904 // We can use MTVSRZ + VECINSERT for v8i16 and v16i8 types. 9905 if (VT == MVT::v8i16 || VT == MVT::v16i8) { 9906 SDValue Mtvsrz = DAG.getNode(PPCISD::MTVSRZ, dl, VT, V2); 9907 unsigned BytesInEachElement = VT.getVectorElementType().getSizeInBits() / 8; 9908 unsigned InsertAtElement = C->getZExtValue(); 9909 unsigned InsertAtByte = InsertAtElement * BytesInEachElement; 9910 if (Subtarget.isLittleEndian()) { 9911 InsertAtByte = (16 - BytesInEachElement) - InsertAtByte; 9912 } 9913 return DAG.getNode(PPCISD::VECINSERT, dl, VT, V1, Mtvsrz, 9914 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9915 } 9916 return Op; 9917 } 9918 9919 SDValue PPCTargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op, 9920 SelectionDAG &DAG) const { 9921 SDLoc dl(Op); 9922 SDNode *N = Op.getNode(); 9923 9924 assert(N->getOperand(0).getValueType() == MVT::v4i1 && 9925 "Unknown extract_vector_elt type"); 9926 9927 SDValue Value = N->getOperand(0); 9928 9929 // The first part of this is like the store lowering except that we don't 9930 // need to track the chain. 9931 9932 // The values are now known to be -1 (false) or 1 (true). To convert this 9933 // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5). 9934 // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5 9935 Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value); 9936 9937 // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to 9938 // understand how to form the extending load. 9939 SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64); 9940 9941 Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs); 9942 9943 // Now convert to an integer and store. 9944 Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64, 9945 DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32), 9946 Value); 9947 9948 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 9949 int FrameIdx = MFI.CreateStackObject(16, 16, false); 9950 MachinePointerInfo PtrInfo = 9951 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 9952 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 9953 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 9954 9955 SDValue StoreChain = DAG.getEntryNode(); 9956 SDValue Ops[] = {StoreChain, 9957 DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32), 9958 Value, FIdx}; 9959 SDVTList VTs = DAG.getVTList(/*chain*/ MVT::Other); 9960 9961 StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, 9962 dl, VTs, Ops, MVT::v4i32, PtrInfo); 9963 9964 // Extract the value requested. 9965 unsigned Offset = 4*cast<ConstantSDNode>(N->getOperand(1))->getZExtValue(); 9966 SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType()); 9967 Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx); 9968 9969 SDValue IntVal = 9970 DAG.getLoad(MVT::i32, dl, StoreChain, Idx, PtrInfo.getWithOffset(Offset)); 9971 9972 if (!Subtarget.useCRBits()) 9973 return IntVal; 9974 9975 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, IntVal); 9976 } 9977 9978 /// Lowering for QPX v4i1 loads 9979 SDValue PPCTargetLowering::LowerVectorLoad(SDValue Op, 9980 SelectionDAG &DAG) const { 9981 SDLoc dl(Op); 9982 LoadSDNode *LN = cast<LoadSDNode>(Op.getNode()); 9983 SDValue LoadChain = LN->getChain(); 9984 SDValue BasePtr = LN->getBasePtr(); 9985 9986 if (Op.getValueType() == MVT::v4f64 || 9987 Op.getValueType() == MVT::v4f32) { 9988 EVT MemVT = LN->getMemoryVT(); 9989 unsigned Alignment = LN->getAlignment(); 9990 9991 // If this load is properly aligned, then it is legal. 9992 if (Alignment >= MemVT.getStoreSize()) 9993 return Op; 9994 9995 EVT ScalarVT = Op.getValueType().getScalarType(), 9996 ScalarMemVT = MemVT.getScalarType(); 9997 unsigned Stride = ScalarMemVT.getStoreSize(); 9998 9999 SDValue Vals[4], LoadChains[4]; 10000 for (unsigned Idx = 0; Idx < 4; ++Idx) { 10001 SDValue Load; 10002 if (ScalarVT != ScalarMemVT) 10003 Load = DAG.getExtLoad(LN->getExtensionType(), dl, ScalarVT, LoadChain, 10004 BasePtr, 10005 LN->getPointerInfo().getWithOffset(Idx * Stride), 10006 ScalarMemVT, MinAlign(Alignment, Idx * Stride), 10007 LN->getMemOperand()->getFlags(), LN->getAAInfo()); 10008 else 10009 Load = DAG.getLoad(ScalarVT, dl, LoadChain, BasePtr, 10010 LN->getPointerInfo().getWithOffset(Idx * Stride), 10011 MinAlign(Alignment, Idx * Stride), 10012 LN->getMemOperand()->getFlags(), LN->getAAInfo()); 10013 10014 if (Idx == 0 && LN->isIndexed()) { 10015 assert(LN->getAddressingMode() == ISD::PRE_INC && 10016 "Unknown addressing mode on vector load"); 10017 Load = DAG.getIndexedLoad(Load, dl, BasePtr, LN->getOffset(), 10018 LN->getAddressingMode()); 10019 } 10020 10021 Vals[Idx] = Load; 10022 LoadChains[Idx] = Load.getValue(1); 10023 10024 BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, 10025 DAG.getConstant(Stride, dl, 10026 BasePtr.getValueType())); 10027 } 10028 10029 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains); 10030 SDValue Value = DAG.getBuildVector(Op.getValueType(), dl, Vals); 10031 10032 if (LN->isIndexed()) { 10033 SDValue RetOps[] = { Value, Vals[0].getValue(1), TF }; 10034 return DAG.getMergeValues(RetOps, dl); 10035 } 10036 10037 SDValue RetOps[] = { Value, TF }; 10038 return DAG.getMergeValues(RetOps, dl); 10039 } 10040 10041 assert(Op.getValueType() == MVT::v4i1 && "Unknown load to lower"); 10042 assert(LN->isUnindexed() && "Indexed v4i1 loads are not supported"); 10043 10044 // To lower v4i1 from a byte array, we load the byte elements of the 10045 // vector and then reuse the BUILD_VECTOR logic. 10046 10047 SDValue VectElmts[4], VectElmtChains[4]; 10048 for (unsigned i = 0; i < 4; ++i) { 10049 SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType()); 10050 Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx); 10051 10052 VectElmts[i] = DAG.getExtLoad( 10053 ISD::EXTLOAD, dl, MVT::i32, LoadChain, Idx, 10054 LN->getPointerInfo().getWithOffset(i), MVT::i8, 10055 /* Alignment = */ 1, LN->getMemOperand()->getFlags(), LN->getAAInfo()); 10056 VectElmtChains[i] = VectElmts[i].getValue(1); 10057 } 10058 10059 LoadChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, VectElmtChains); 10060 SDValue Value = DAG.getBuildVector(MVT::v4i1, dl, VectElmts); 10061 10062 SDValue RVals[] = { Value, LoadChain }; 10063 return DAG.getMergeValues(RVals, dl); 10064 } 10065 10066 /// Lowering for QPX v4i1 stores 10067 SDValue PPCTargetLowering::LowerVectorStore(SDValue Op, 10068 SelectionDAG &DAG) const { 10069 SDLoc dl(Op); 10070 StoreSDNode *SN = cast<StoreSDNode>(Op.getNode()); 10071 SDValue StoreChain = SN->getChain(); 10072 SDValue BasePtr = SN->getBasePtr(); 10073 SDValue Value = SN->getValue(); 10074 10075 if (Value.getValueType() == MVT::v4f64 || 10076 Value.getValueType() == MVT::v4f32) { 10077 EVT MemVT = SN->getMemoryVT(); 10078 unsigned Alignment = SN->getAlignment(); 10079 10080 // If this store is properly aligned, then it is legal. 10081 if (Alignment >= MemVT.getStoreSize()) 10082 return Op; 10083 10084 EVT ScalarVT = Value.getValueType().getScalarType(), 10085 ScalarMemVT = MemVT.getScalarType(); 10086 unsigned Stride = ScalarMemVT.getStoreSize(); 10087 10088 SDValue Stores[4]; 10089 for (unsigned Idx = 0; Idx < 4; ++Idx) { 10090 SDValue Ex = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, Value, 10091 DAG.getVectorIdxConstant(Idx, dl)); 10092 SDValue Store; 10093 if (ScalarVT != ScalarMemVT) 10094 Store = 10095 DAG.getTruncStore(StoreChain, dl, Ex, BasePtr, 10096 SN->getPointerInfo().getWithOffset(Idx * Stride), 10097 ScalarMemVT, MinAlign(Alignment, Idx * Stride), 10098 SN->getMemOperand()->getFlags(), SN->getAAInfo()); 10099 else 10100 Store = DAG.getStore(StoreChain, dl, Ex, BasePtr, 10101 SN->getPointerInfo().getWithOffset(Idx * Stride), 10102 MinAlign(Alignment, Idx * Stride), 10103 SN->getMemOperand()->getFlags(), SN->getAAInfo()); 10104 10105 if (Idx == 0 && SN->isIndexed()) { 10106 assert(SN->getAddressingMode() == ISD::PRE_INC && 10107 "Unknown addressing mode on vector store"); 10108 Store = DAG.getIndexedStore(Store, dl, BasePtr, SN->getOffset(), 10109 SN->getAddressingMode()); 10110 } 10111 10112 BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, 10113 DAG.getConstant(Stride, dl, 10114 BasePtr.getValueType())); 10115 Stores[Idx] = Store; 10116 } 10117 10118 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores); 10119 10120 if (SN->isIndexed()) { 10121 SDValue RetOps[] = { TF, Stores[0].getValue(1) }; 10122 return DAG.getMergeValues(RetOps, dl); 10123 } 10124 10125 return TF; 10126 } 10127 10128 assert(SN->isUnindexed() && "Indexed v4i1 stores are not supported"); 10129 assert(Value.getValueType() == MVT::v4i1 && "Unknown store to lower"); 10130 10131 // The values are now known to be -1 (false) or 1 (true). To convert this 10132 // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5). 10133 // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5 10134 Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value); 10135 10136 // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to 10137 // understand how to form the extending load. 10138 SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64); 10139 10140 Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs); 10141 10142 // Now convert to an integer and store. 10143 Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64, 10144 DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32), 10145 Value); 10146 10147 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 10148 int FrameIdx = MFI.CreateStackObject(16, 16, false); 10149 MachinePointerInfo PtrInfo = 10150 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 10151 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 10152 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 10153 10154 SDValue Ops[] = {StoreChain, 10155 DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32), 10156 Value, FIdx}; 10157 SDVTList VTs = DAG.getVTList(/*chain*/ MVT::Other); 10158 10159 StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, 10160 dl, VTs, Ops, MVT::v4i32, PtrInfo); 10161 10162 // Move data into the byte array. 10163 SDValue Loads[4], LoadChains[4]; 10164 for (unsigned i = 0; i < 4; ++i) { 10165 unsigned Offset = 4*i; 10166 SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType()); 10167 Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx); 10168 10169 Loads[i] = DAG.getLoad(MVT::i32, dl, StoreChain, Idx, 10170 PtrInfo.getWithOffset(Offset)); 10171 LoadChains[i] = Loads[i].getValue(1); 10172 } 10173 10174 StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains); 10175 10176 SDValue Stores[4]; 10177 for (unsigned i = 0; i < 4; ++i) { 10178 SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType()); 10179 Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx); 10180 10181 Stores[i] = DAG.getTruncStore( 10182 StoreChain, dl, Loads[i], Idx, SN->getPointerInfo().getWithOffset(i), 10183 MVT::i8, /* Alignment = */ 1, SN->getMemOperand()->getFlags(), 10184 SN->getAAInfo()); 10185 } 10186 10187 StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores); 10188 10189 return StoreChain; 10190 } 10191 10192 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const { 10193 SDLoc dl(Op); 10194 if (Op.getValueType() == MVT::v4i32) { 10195 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 10196 10197 SDValue Zero = BuildSplatI( 0, 1, MVT::v4i32, DAG, dl); 10198 SDValue Neg16 = BuildSplatI(-16, 4, MVT::v4i32, DAG, dl);//+16 as shift amt. 10199 10200 SDValue RHSSwap = // = vrlw RHS, 16 10201 BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl); 10202 10203 // Shrinkify inputs to v8i16. 10204 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS); 10205 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS); 10206 RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap); 10207 10208 // Low parts multiplied together, generating 32-bit results (we ignore the 10209 // top parts). 10210 SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh, 10211 LHS, RHS, DAG, dl, MVT::v4i32); 10212 10213 SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm, 10214 LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32); 10215 // Shift the high parts up 16 bits. 10216 HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd, 10217 Neg16, DAG, dl); 10218 return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd); 10219 } else if (Op.getValueType() == MVT::v8i16) { 10220 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 10221 10222 SDValue Zero = BuildSplatI(0, 1, MVT::v8i16, DAG, dl); 10223 10224 return BuildIntrinsicOp(Intrinsic::ppc_altivec_vmladduhm, 10225 LHS, RHS, Zero, DAG, dl); 10226 } else if (Op.getValueType() == MVT::v16i8) { 10227 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 10228 bool isLittleEndian = Subtarget.isLittleEndian(); 10229 10230 // Multiply the even 8-bit parts, producing 16-bit sums. 10231 SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub, 10232 LHS, RHS, DAG, dl, MVT::v8i16); 10233 EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts); 10234 10235 // Multiply the odd 8-bit parts, producing 16-bit sums. 10236 SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub, 10237 LHS, RHS, DAG, dl, MVT::v8i16); 10238 OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts); 10239 10240 // Merge the results together. Because vmuleub and vmuloub are 10241 // instructions with a big-endian bias, we must reverse the 10242 // element numbering and reverse the meaning of "odd" and "even" 10243 // when generating little endian code. 10244 int Ops[16]; 10245 for (unsigned i = 0; i != 8; ++i) { 10246 if (isLittleEndian) { 10247 Ops[i*2 ] = 2*i; 10248 Ops[i*2+1] = 2*i+16; 10249 } else { 10250 Ops[i*2 ] = 2*i+1; 10251 Ops[i*2+1] = 2*i+1+16; 10252 } 10253 } 10254 if (isLittleEndian) 10255 return DAG.getVectorShuffle(MVT::v16i8, dl, OddParts, EvenParts, Ops); 10256 else 10257 return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops); 10258 } else { 10259 llvm_unreachable("Unknown mul to lower!"); 10260 } 10261 } 10262 10263 SDValue PPCTargetLowering::LowerABS(SDValue Op, SelectionDAG &DAG) const { 10264 10265 assert(Op.getOpcode() == ISD::ABS && "Should only be called for ISD::ABS"); 10266 10267 EVT VT = Op.getValueType(); 10268 assert(VT.isVector() && 10269 "Only set vector abs as custom, scalar abs shouldn't reach here!"); 10270 assert((VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 || 10271 VT == MVT::v16i8) && 10272 "Unexpected vector element type!"); 10273 assert((VT != MVT::v2i64 || Subtarget.hasP8Altivec()) && 10274 "Current subtarget doesn't support smax v2i64!"); 10275 10276 // For vector abs, it can be lowered to: 10277 // abs x 10278 // ==> 10279 // y = -x 10280 // smax(x, y) 10281 10282 SDLoc dl(Op); 10283 SDValue X = Op.getOperand(0); 10284 SDValue Zero = DAG.getConstant(0, dl, VT); 10285 SDValue Y = DAG.getNode(ISD::SUB, dl, VT, Zero, X); 10286 10287 // SMAX patch https://reviews.llvm.org/D47332 10288 // hasn't landed yet, so use intrinsic first here. 10289 // TODO: Should use SMAX directly once SMAX patch landed 10290 Intrinsic::ID BifID = Intrinsic::ppc_altivec_vmaxsw; 10291 if (VT == MVT::v2i64) 10292 BifID = Intrinsic::ppc_altivec_vmaxsd; 10293 else if (VT == MVT::v8i16) 10294 BifID = Intrinsic::ppc_altivec_vmaxsh; 10295 else if (VT == MVT::v16i8) 10296 BifID = Intrinsic::ppc_altivec_vmaxsb; 10297 10298 return BuildIntrinsicOp(BifID, X, Y, DAG, dl, VT); 10299 } 10300 10301 // Custom lowering for fpext vf32 to v2f64 10302 SDValue PPCTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const { 10303 10304 assert(Op.getOpcode() == ISD::FP_EXTEND && 10305 "Should only be called for ISD::FP_EXTEND"); 10306 10307 // We only want to custom lower an extend from v2f32 to v2f64. 10308 if (Op.getValueType() != MVT::v2f64 || 10309 Op.getOperand(0).getValueType() != MVT::v2f32) 10310 return SDValue(); 10311 10312 SDLoc dl(Op); 10313 SDValue Op0 = Op.getOperand(0); 10314 10315 switch (Op0.getOpcode()) { 10316 default: 10317 return SDValue(); 10318 case ISD::EXTRACT_SUBVECTOR: { 10319 assert(Op0.getNumOperands() == 2 && 10320 isa<ConstantSDNode>(Op0->getOperand(1)) && 10321 "Node should have 2 operands with second one being a constant!"); 10322 10323 if (Op0.getOperand(0).getValueType() != MVT::v4f32) 10324 return SDValue(); 10325 10326 // Custom lower is only done for high or low doubleword. 10327 int Idx = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue(); 10328 if (Idx % 2 != 0) 10329 return SDValue(); 10330 10331 // Since input is v4f32, at this point Idx is either 0 or 2. 10332 // Shift to get the doubleword position we want. 10333 int DWord = Idx >> 1; 10334 10335 // High and low word positions are different on little endian. 10336 if (Subtarget.isLittleEndian()) 10337 DWord ^= 0x1; 10338 10339 return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, 10340 Op0.getOperand(0), DAG.getConstant(DWord, dl, MVT::i32)); 10341 } 10342 case ISD::FADD: 10343 case ISD::FMUL: 10344 case ISD::FSUB: { 10345 SDValue NewLoad[2]; 10346 for (unsigned i = 0, ie = Op0.getNumOperands(); i != ie; ++i) { 10347 // Ensure both input are loads. 10348 SDValue LdOp = Op0.getOperand(i); 10349 if (LdOp.getOpcode() != ISD::LOAD) 10350 return SDValue(); 10351 // Generate new load node. 10352 LoadSDNode *LD = cast<LoadSDNode>(LdOp); 10353 SDValue LoadOps[] = {LD->getChain(), LD->getBasePtr()}; 10354 NewLoad[i] = DAG.getMemIntrinsicNode( 10355 PPCISD::LD_VSX_LH, dl, DAG.getVTList(MVT::v4f32, MVT::Other), LoadOps, 10356 LD->getMemoryVT(), LD->getMemOperand()); 10357 } 10358 SDValue NewOp = 10359 DAG.getNode(Op0.getOpcode(), SDLoc(Op0), MVT::v4f32, NewLoad[0], 10360 NewLoad[1], Op0.getNode()->getFlags()); 10361 return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, NewOp, 10362 DAG.getConstant(0, dl, MVT::i32)); 10363 } 10364 case ISD::LOAD: { 10365 LoadSDNode *LD = cast<LoadSDNode>(Op0); 10366 SDValue LoadOps[] = {LD->getChain(), LD->getBasePtr()}; 10367 SDValue NewLd = DAG.getMemIntrinsicNode( 10368 PPCISD::LD_VSX_LH, dl, DAG.getVTList(MVT::v4f32, MVT::Other), LoadOps, 10369 LD->getMemoryVT(), LD->getMemOperand()); 10370 return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, NewLd, 10371 DAG.getConstant(0, dl, MVT::i32)); 10372 } 10373 } 10374 llvm_unreachable("ERROR:Should return for all cases within swtich."); 10375 } 10376 10377 /// LowerOperation - Provide custom lowering hooks for some operations. 10378 /// 10379 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 10380 switch (Op.getOpcode()) { 10381 default: llvm_unreachable("Wasn't expecting to be able to lower this!"); 10382 case ISD::ConstantPool: return LowerConstantPool(Op, DAG); 10383 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG); 10384 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG); 10385 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG); 10386 case ISD::JumpTable: return LowerJumpTable(Op, DAG); 10387 case ISD::SETCC: return LowerSETCC(Op, DAG); 10388 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG); 10389 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG); 10390 10391 // Variable argument lowering. 10392 case ISD::VASTART: return LowerVASTART(Op, DAG); 10393 case ISD::VAARG: return LowerVAARG(Op, DAG); 10394 case ISD::VACOPY: return LowerVACOPY(Op, DAG); 10395 10396 case ISD::STACKRESTORE: return LowerSTACKRESTORE(Op, DAG); 10397 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG); 10398 case ISD::GET_DYNAMIC_AREA_OFFSET: 10399 return LowerGET_DYNAMIC_AREA_OFFSET(Op, DAG); 10400 10401 // Exception handling lowering. 10402 case ISD::EH_DWARF_CFA: return LowerEH_DWARF_CFA(Op, DAG); 10403 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG); 10404 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG); 10405 10406 case ISD::LOAD: return LowerLOAD(Op, DAG); 10407 case ISD::STORE: return LowerSTORE(Op, DAG); 10408 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG); 10409 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG); 10410 case ISD::FP_TO_UINT: 10411 case ISD::FP_TO_SINT: return LowerFP_TO_INT(Op, DAG, SDLoc(Op)); 10412 case ISD::UINT_TO_FP: 10413 case ISD::SINT_TO_FP: return LowerINT_TO_FP(Op, DAG); 10414 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG); 10415 10416 // Lower 64-bit shifts. 10417 case ISD::SHL_PARTS: return LowerSHL_PARTS(Op, DAG); 10418 case ISD::SRL_PARTS: return LowerSRL_PARTS(Op, DAG); 10419 case ISD::SRA_PARTS: return LowerSRA_PARTS(Op, DAG); 10420 10421 // Vector-related lowering. 10422 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG); 10423 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG); 10424 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG); 10425 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG); 10426 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG); 10427 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG); 10428 case ISD::MUL: return LowerMUL(Op, DAG); 10429 case ISD::ABS: return LowerABS(Op, DAG); 10430 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG); 10431 10432 // For counter-based loop handling. 10433 case ISD::INTRINSIC_W_CHAIN: return SDValue(); 10434 10435 case ISD::BITCAST: return LowerBITCAST(Op, DAG); 10436 10437 // Frame & Return address. 10438 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG); 10439 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG); 10440 10441 case ISD::INTRINSIC_VOID: 10442 return LowerINTRINSIC_VOID(Op, DAG); 10443 case ISD::SREM: 10444 case ISD::UREM: 10445 return LowerREM(Op, DAG); 10446 case ISD::BSWAP: 10447 return LowerBSWAP(Op, DAG); 10448 case ISD::ATOMIC_CMP_SWAP: 10449 return LowerATOMIC_CMP_SWAP(Op, DAG); 10450 } 10451 } 10452 10453 void PPCTargetLowering::ReplaceNodeResults(SDNode *N, 10454 SmallVectorImpl<SDValue>&Results, 10455 SelectionDAG &DAG) const { 10456 SDLoc dl(N); 10457 switch (N->getOpcode()) { 10458 default: 10459 llvm_unreachable("Do not know how to custom type legalize this operation!"); 10460 case ISD::READCYCLECOUNTER: { 10461 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other); 10462 SDValue RTB = DAG.getNode(PPCISD::READ_TIME_BASE, dl, VTs, N->getOperand(0)); 10463 10464 Results.push_back(RTB); 10465 Results.push_back(RTB.getValue(1)); 10466 Results.push_back(RTB.getValue(2)); 10467 break; 10468 } 10469 case ISD::INTRINSIC_W_CHAIN: { 10470 if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 10471 Intrinsic::loop_decrement) 10472 break; 10473 10474 assert(N->getValueType(0) == MVT::i1 && 10475 "Unexpected result type for CTR decrement intrinsic"); 10476 EVT SVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 10477 N->getValueType(0)); 10478 SDVTList VTs = DAG.getVTList(SVT, MVT::Other); 10479 SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0), 10480 N->getOperand(1)); 10481 10482 Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewInt)); 10483 Results.push_back(NewInt.getValue(1)); 10484 break; 10485 } 10486 case ISD::VAARG: { 10487 if (!Subtarget.isSVR4ABI() || Subtarget.isPPC64()) 10488 return; 10489 10490 EVT VT = N->getValueType(0); 10491 10492 if (VT == MVT::i64) { 10493 SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG); 10494 10495 Results.push_back(NewNode); 10496 Results.push_back(NewNode.getValue(1)); 10497 } 10498 return; 10499 } 10500 case ISD::FP_TO_SINT: 10501 case ISD::FP_TO_UINT: 10502 // LowerFP_TO_INT() can only handle f32 and f64. 10503 if (N->getOperand(0).getValueType() == MVT::ppcf128) 10504 return; 10505 Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl)); 10506 return; 10507 case ISD::TRUNCATE: { 10508 EVT TrgVT = N->getValueType(0); 10509 EVT OpVT = N->getOperand(0).getValueType(); 10510 if (TrgVT.isVector() && 10511 isOperationCustom(N->getOpcode(), TrgVT) && 10512 OpVT.getSizeInBits() <= 128 && 10513 isPowerOf2_32(OpVT.getVectorElementType().getSizeInBits())) 10514 Results.push_back(LowerTRUNCATEVector(SDValue(N, 0), DAG)); 10515 return; 10516 } 10517 case ISD::BITCAST: 10518 // Don't handle bitcast here. 10519 return; 10520 } 10521 } 10522 10523 //===----------------------------------------------------------------------===// 10524 // Other Lowering Code 10525 //===----------------------------------------------------------------------===// 10526 10527 static Instruction* callIntrinsic(IRBuilder<> &Builder, Intrinsic::ID Id) { 10528 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 10529 Function *Func = Intrinsic::getDeclaration(M, Id); 10530 return Builder.CreateCall(Func, {}); 10531 } 10532 10533 // The mappings for emitLeading/TrailingFence is taken from 10534 // http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html 10535 Instruction *PPCTargetLowering::emitLeadingFence(IRBuilder<> &Builder, 10536 Instruction *Inst, 10537 AtomicOrdering Ord) const { 10538 if (Ord == AtomicOrdering::SequentiallyConsistent) 10539 return callIntrinsic(Builder, Intrinsic::ppc_sync); 10540 if (isReleaseOrStronger(Ord)) 10541 return callIntrinsic(Builder, Intrinsic::ppc_lwsync); 10542 return nullptr; 10543 } 10544 10545 Instruction *PPCTargetLowering::emitTrailingFence(IRBuilder<> &Builder, 10546 Instruction *Inst, 10547 AtomicOrdering Ord) const { 10548 if (Inst->hasAtomicLoad() && isAcquireOrStronger(Ord)) { 10549 // See http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html and 10550 // http://www.rdrop.com/users/paulmck/scalability/paper/N2745r.2011.03.04a.html 10551 // and http://www.cl.cam.ac.uk/~pes20/cppppc/ for justification. 10552 if (isa<LoadInst>(Inst) && Subtarget.isPPC64()) 10553 return Builder.CreateCall( 10554 Intrinsic::getDeclaration( 10555 Builder.GetInsertBlock()->getParent()->getParent(), 10556 Intrinsic::ppc_cfence, {Inst->getType()}), 10557 {Inst}); 10558 // FIXME: Can use isync for rmw operation. 10559 return callIntrinsic(Builder, Intrinsic::ppc_lwsync); 10560 } 10561 return nullptr; 10562 } 10563 10564 MachineBasicBlock * 10565 PPCTargetLowering::EmitAtomicBinary(MachineInstr &MI, MachineBasicBlock *BB, 10566 unsigned AtomicSize, 10567 unsigned BinOpcode, 10568 unsigned CmpOpcode, 10569 unsigned CmpPred) const { 10570 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0. 10571 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 10572 10573 auto LoadMnemonic = PPC::LDARX; 10574 auto StoreMnemonic = PPC::STDCX; 10575 switch (AtomicSize) { 10576 default: 10577 llvm_unreachable("Unexpected size of atomic entity"); 10578 case 1: 10579 LoadMnemonic = PPC::LBARX; 10580 StoreMnemonic = PPC::STBCX; 10581 assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4"); 10582 break; 10583 case 2: 10584 LoadMnemonic = PPC::LHARX; 10585 StoreMnemonic = PPC::STHCX; 10586 assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4"); 10587 break; 10588 case 4: 10589 LoadMnemonic = PPC::LWARX; 10590 StoreMnemonic = PPC::STWCX; 10591 break; 10592 case 8: 10593 LoadMnemonic = PPC::LDARX; 10594 StoreMnemonic = PPC::STDCX; 10595 break; 10596 } 10597 10598 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 10599 MachineFunction *F = BB->getParent(); 10600 MachineFunction::iterator It = ++BB->getIterator(); 10601 10602 Register dest = MI.getOperand(0).getReg(); 10603 Register ptrA = MI.getOperand(1).getReg(); 10604 Register ptrB = MI.getOperand(2).getReg(); 10605 Register incr = MI.getOperand(3).getReg(); 10606 DebugLoc dl = MI.getDebugLoc(); 10607 10608 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB); 10609 MachineBasicBlock *loop2MBB = 10610 CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr; 10611 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 10612 F->insert(It, loopMBB); 10613 if (CmpOpcode) 10614 F->insert(It, loop2MBB); 10615 F->insert(It, exitMBB); 10616 exitMBB->splice(exitMBB->begin(), BB, 10617 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 10618 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 10619 10620 MachineRegisterInfo &RegInfo = F->getRegInfo(); 10621 Register TmpReg = (!BinOpcode) ? incr : 10622 RegInfo.createVirtualRegister( AtomicSize == 8 ? &PPC::G8RCRegClass 10623 : &PPC::GPRCRegClass); 10624 10625 // thisMBB: 10626 // ... 10627 // fallthrough --> loopMBB 10628 BB->addSuccessor(loopMBB); 10629 10630 // loopMBB: 10631 // l[wd]arx dest, ptr 10632 // add r0, dest, incr 10633 // st[wd]cx. r0, ptr 10634 // bne- loopMBB 10635 // fallthrough --> exitMBB 10636 10637 // For max/min... 10638 // loopMBB: 10639 // l[wd]arx dest, ptr 10640 // cmpl?[wd] incr, dest 10641 // bgt exitMBB 10642 // loop2MBB: 10643 // st[wd]cx. dest, ptr 10644 // bne- loopMBB 10645 // fallthrough --> exitMBB 10646 10647 BB = loopMBB; 10648 BuildMI(BB, dl, TII->get(LoadMnemonic), dest) 10649 .addReg(ptrA).addReg(ptrB); 10650 if (BinOpcode) 10651 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest); 10652 if (CmpOpcode) { 10653 // Signed comparisons of byte or halfword values must be sign-extended. 10654 if (CmpOpcode == PPC::CMPW && AtomicSize < 4) { 10655 Register ExtReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass); 10656 BuildMI(BB, dl, TII->get(AtomicSize == 1 ? PPC::EXTSB : PPC::EXTSH), 10657 ExtReg).addReg(dest); 10658 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0) 10659 .addReg(incr).addReg(ExtReg); 10660 } else 10661 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0) 10662 .addReg(incr).addReg(dest); 10663 10664 BuildMI(BB, dl, TII->get(PPC::BCC)) 10665 .addImm(CmpPred).addReg(PPC::CR0).addMBB(exitMBB); 10666 BB->addSuccessor(loop2MBB); 10667 BB->addSuccessor(exitMBB); 10668 BB = loop2MBB; 10669 } 10670 BuildMI(BB, dl, TII->get(StoreMnemonic)) 10671 .addReg(TmpReg).addReg(ptrA).addReg(ptrB); 10672 BuildMI(BB, dl, TII->get(PPC::BCC)) 10673 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB); 10674 BB->addSuccessor(loopMBB); 10675 BB->addSuccessor(exitMBB); 10676 10677 // exitMBB: 10678 // ... 10679 BB = exitMBB; 10680 return BB; 10681 } 10682 10683 MachineBasicBlock *PPCTargetLowering::EmitPartwordAtomicBinary( 10684 MachineInstr &MI, MachineBasicBlock *BB, 10685 bool is8bit, // operation 10686 unsigned BinOpcode, unsigned CmpOpcode, unsigned CmpPred) const { 10687 // If we support part-word atomic mnemonics, just use them 10688 if (Subtarget.hasPartwordAtomics()) 10689 return EmitAtomicBinary(MI, BB, is8bit ? 1 : 2, BinOpcode, CmpOpcode, 10690 CmpPred); 10691 10692 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0. 10693 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 10694 // In 64 bit mode we have to use 64 bits for addresses, even though the 10695 // lwarx/stwcx are 32 bits. With the 32-bit atomics we can use address 10696 // registers without caring whether they're 32 or 64, but here we're 10697 // doing actual arithmetic on the addresses. 10698 bool is64bit = Subtarget.isPPC64(); 10699 bool isLittleEndian = Subtarget.isLittleEndian(); 10700 unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO; 10701 10702 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 10703 MachineFunction *F = BB->getParent(); 10704 MachineFunction::iterator It = ++BB->getIterator(); 10705 10706 Register dest = MI.getOperand(0).getReg(); 10707 Register ptrA = MI.getOperand(1).getReg(); 10708 Register ptrB = MI.getOperand(2).getReg(); 10709 Register incr = MI.getOperand(3).getReg(); 10710 DebugLoc dl = MI.getDebugLoc(); 10711 10712 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB); 10713 MachineBasicBlock *loop2MBB = 10714 CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr; 10715 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 10716 F->insert(It, loopMBB); 10717 if (CmpOpcode) 10718 F->insert(It, loop2MBB); 10719 F->insert(It, exitMBB); 10720 exitMBB->splice(exitMBB->begin(), BB, 10721 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 10722 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 10723 10724 MachineRegisterInfo &RegInfo = F->getRegInfo(); 10725 const TargetRegisterClass *RC = 10726 is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 10727 const TargetRegisterClass *GPRC = &PPC::GPRCRegClass; 10728 10729 Register PtrReg = RegInfo.createVirtualRegister(RC); 10730 Register Shift1Reg = RegInfo.createVirtualRegister(GPRC); 10731 Register ShiftReg = 10732 isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC); 10733 Register Incr2Reg = RegInfo.createVirtualRegister(GPRC); 10734 Register MaskReg = RegInfo.createVirtualRegister(GPRC); 10735 Register Mask2Reg = RegInfo.createVirtualRegister(GPRC); 10736 Register Mask3Reg = RegInfo.createVirtualRegister(GPRC); 10737 Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC); 10738 Register Tmp3Reg = RegInfo.createVirtualRegister(GPRC); 10739 Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC); 10740 Register TmpDestReg = RegInfo.createVirtualRegister(GPRC); 10741 Register Ptr1Reg; 10742 Register TmpReg = 10743 (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(GPRC); 10744 10745 // thisMBB: 10746 // ... 10747 // fallthrough --> loopMBB 10748 BB->addSuccessor(loopMBB); 10749 10750 // The 4-byte load must be aligned, while a char or short may be 10751 // anywhere in the word. Hence all this nasty bookkeeping code. 10752 // add ptr1, ptrA, ptrB [copy if ptrA==0] 10753 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27] 10754 // xori shift, shift1, 24 [16] 10755 // rlwinm ptr, ptr1, 0, 0, 29 10756 // slw incr2, incr, shift 10757 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535] 10758 // slw mask, mask2, shift 10759 // loopMBB: 10760 // lwarx tmpDest, ptr 10761 // add tmp, tmpDest, incr2 10762 // andc tmp2, tmpDest, mask 10763 // and tmp3, tmp, mask 10764 // or tmp4, tmp3, tmp2 10765 // stwcx. tmp4, ptr 10766 // bne- loopMBB 10767 // fallthrough --> exitMBB 10768 // srw dest, tmpDest, shift 10769 if (ptrA != ZeroReg) { 10770 Ptr1Reg = RegInfo.createVirtualRegister(RC); 10771 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg) 10772 .addReg(ptrA) 10773 .addReg(ptrB); 10774 } else { 10775 Ptr1Reg = ptrB; 10776 } 10777 // We need use 32-bit subregister to avoid mismatch register class in 64-bit 10778 // mode. 10779 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg) 10780 .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0) 10781 .addImm(3) 10782 .addImm(27) 10783 .addImm(is8bit ? 28 : 27); 10784 if (!isLittleEndian) 10785 BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg) 10786 .addReg(Shift1Reg) 10787 .addImm(is8bit ? 24 : 16); 10788 if (is64bit) 10789 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg) 10790 .addReg(Ptr1Reg) 10791 .addImm(0) 10792 .addImm(61); 10793 else 10794 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg) 10795 .addReg(Ptr1Reg) 10796 .addImm(0) 10797 .addImm(0) 10798 .addImm(29); 10799 BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg).addReg(incr).addReg(ShiftReg); 10800 if (is8bit) 10801 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255); 10802 else { 10803 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0); 10804 BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg) 10805 .addReg(Mask3Reg) 10806 .addImm(65535); 10807 } 10808 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg) 10809 .addReg(Mask2Reg) 10810 .addReg(ShiftReg); 10811 10812 BB = loopMBB; 10813 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg) 10814 .addReg(ZeroReg) 10815 .addReg(PtrReg); 10816 if (BinOpcode) 10817 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg) 10818 .addReg(Incr2Reg) 10819 .addReg(TmpDestReg); 10820 BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg) 10821 .addReg(TmpDestReg) 10822 .addReg(MaskReg); 10823 BuildMI(BB, dl, TII->get(PPC::AND), Tmp3Reg).addReg(TmpReg).addReg(MaskReg); 10824 if (CmpOpcode) { 10825 // For unsigned comparisons, we can directly compare the shifted values. 10826 // For signed comparisons we shift and sign extend. 10827 Register SReg = RegInfo.createVirtualRegister(GPRC); 10828 BuildMI(BB, dl, TII->get(PPC::AND), SReg) 10829 .addReg(TmpDestReg) 10830 .addReg(MaskReg); 10831 unsigned ValueReg = SReg; 10832 unsigned CmpReg = Incr2Reg; 10833 if (CmpOpcode == PPC::CMPW) { 10834 ValueReg = RegInfo.createVirtualRegister(GPRC); 10835 BuildMI(BB, dl, TII->get(PPC::SRW), ValueReg) 10836 .addReg(SReg) 10837 .addReg(ShiftReg); 10838 Register ValueSReg = RegInfo.createVirtualRegister(GPRC); 10839 BuildMI(BB, dl, TII->get(is8bit ? PPC::EXTSB : PPC::EXTSH), ValueSReg) 10840 .addReg(ValueReg); 10841 ValueReg = ValueSReg; 10842 CmpReg = incr; 10843 } 10844 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0) 10845 .addReg(CmpReg) 10846 .addReg(ValueReg); 10847 BuildMI(BB, dl, TII->get(PPC::BCC)) 10848 .addImm(CmpPred) 10849 .addReg(PPC::CR0) 10850 .addMBB(exitMBB); 10851 BB->addSuccessor(loop2MBB); 10852 BB->addSuccessor(exitMBB); 10853 BB = loop2MBB; 10854 } 10855 BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg).addReg(Tmp3Reg).addReg(Tmp2Reg); 10856 BuildMI(BB, dl, TII->get(PPC::STWCX)) 10857 .addReg(Tmp4Reg) 10858 .addReg(ZeroReg) 10859 .addReg(PtrReg); 10860 BuildMI(BB, dl, TII->get(PPC::BCC)) 10861 .addImm(PPC::PRED_NE) 10862 .addReg(PPC::CR0) 10863 .addMBB(loopMBB); 10864 BB->addSuccessor(loopMBB); 10865 BB->addSuccessor(exitMBB); 10866 10867 // exitMBB: 10868 // ... 10869 BB = exitMBB; 10870 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest) 10871 .addReg(TmpDestReg) 10872 .addReg(ShiftReg); 10873 return BB; 10874 } 10875 10876 llvm::MachineBasicBlock * 10877 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr &MI, 10878 MachineBasicBlock *MBB) const { 10879 DebugLoc DL = MI.getDebugLoc(); 10880 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 10881 const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo(); 10882 10883 MachineFunction *MF = MBB->getParent(); 10884 MachineRegisterInfo &MRI = MF->getRegInfo(); 10885 10886 const BasicBlock *BB = MBB->getBasicBlock(); 10887 MachineFunction::iterator I = ++MBB->getIterator(); 10888 10889 Register DstReg = MI.getOperand(0).getReg(); 10890 const TargetRegisterClass *RC = MRI.getRegClass(DstReg); 10891 assert(TRI->isTypeLegalForClass(*RC, MVT::i32) && "Invalid destination!"); 10892 Register mainDstReg = MRI.createVirtualRegister(RC); 10893 Register restoreDstReg = MRI.createVirtualRegister(RC); 10894 10895 MVT PVT = getPointerTy(MF->getDataLayout()); 10896 assert((PVT == MVT::i64 || PVT == MVT::i32) && 10897 "Invalid Pointer Size!"); 10898 // For v = setjmp(buf), we generate 10899 // 10900 // thisMBB: 10901 // SjLjSetup mainMBB 10902 // bl mainMBB 10903 // v_restore = 1 10904 // b sinkMBB 10905 // 10906 // mainMBB: 10907 // buf[LabelOffset] = LR 10908 // v_main = 0 10909 // 10910 // sinkMBB: 10911 // v = phi(main, restore) 10912 // 10913 10914 MachineBasicBlock *thisMBB = MBB; 10915 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB); 10916 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB); 10917 MF->insert(I, mainMBB); 10918 MF->insert(I, sinkMBB); 10919 10920 MachineInstrBuilder MIB; 10921 10922 // Transfer the remainder of BB and its successor edges to sinkMBB. 10923 sinkMBB->splice(sinkMBB->begin(), MBB, 10924 std::next(MachineBasicBlock::iterator(MI)), MBB->end()); 10925 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB); 10926 10927 // Note that the structure of the jmp_buf used here is not compatible 10928 // with that used by libc, and is not designed to be. Specifically, it 10929 // stores only those 'reserved' registers that LLVM does not otherwise 10930 // understand how to spill. Also, by convention, by the time this 10931 // intrinsic is called, Clang has already stored the frame address in the 10932 // first slot of the buffer and stack address in the third. Following the 10933 // X86 target code, we'll store the jump address in the second slot. We also 10934 // need to save the TOC pointer (R2) to handle jumps between shared 10935 // libraries, and that will be stored in the fourth slot. The thread 10936 // identifier (R13) is not affected. 10937 10938 // thisMBB: 10939 const int64_t LabelOffset = 1 * PVT.getStoreSize(); 10940 const int64_t TOCOffset = 3 * PVT.getStoreSize(); 10941 const int64_t BPOffset = 4 * PVT.getStoreSize(); 10942 10943 // Prepare IP either in reg. 10944 const TargetRegisterClass *PtrRC = getRegClassFor(PVT); 10945 Register LabelReg = MRI.createVirtualRegister(PtrRC); 10946 Register BufReg = MI.getOperand(1).getReg(); 10947 10948 if (Subtarget.is64BitELFABI()) { 10949 setUsesTOCBasePtr(*MBB->getParent()); 10950 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD)) 10951 .addReg(PPC::X2) 10952 .addImm(TOCOffset) 10953 .addReg(BufReg) 10954 .cloneMemRefs(MI); 10955 } 10956 10957 // Naked functions never have a base pointer, and so we use r1. For all 10958 // other functions, this decision must be delayed until during PEI. 10959 unsigned BaseReg; 10960 if (MF->getFunction().hasFnAttribute(Attribute::Naked)) 10961 BaseReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1; 10962 else 10963 BaseReg = Subtarget.isPPC64() ? PPC::BP8 : PPC::BP; 10964 10965 MIB = BuildMI(*thisMBB, MI, DL, 10966 TII->get(Subtarget.isPPC64() ? PPC::STD : PPC::STW)) 10967 .addReg(BaseReg) 10968 .addImm(BPOffset) 10969 .addReg(BufReg) 10970 .cloneMemRefs(MI); 10971 10972 // Setup 10973 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB); 10974 MIB.addRegMask(TRI->getNoPreservedMask()); 10975 10976 BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1); 10977 10978 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup)) 10979 .addMBB(mainMBB); 10980 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB); 10981 10982 thisMBB->addSuccessor(mainMBB, BranchProbability::getZero()); 10983 thisMBB->addSuccessor(sinkMBB, BranchProbability::getOne()); 10984 10985 // mainMBB: 10986 // mainDstReg = 0 10987 MIB = 10988 BuildMI(mainMBB, DL, 10989 TII->get(Subtarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg); 10990 10991 // Store IP 10992 if (Subtarget.isPPC64()) { 10993 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD)) 10994 .addReg(LabelReg) 10995 .addImm(LabelOffset) 10996 .addReg(BufReg); 10997 } else { 10998 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW)) 10999 .addReg(LabelReg) 11000 .addImm(LabelOffset) 11001 .addReg(BufReg); 11002 } 11003 MIB.cloneMemRefs(MI); 11004 11005 BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0); 11006 mainMBB->addSuccessor(sinkMBB); 11007 11008 // sinkMBB: 11009 BuildMI(*sinkMBB, sinkMBB->begin(), DL, 11010 TII->get(PPC::PHI), DstReg) 11011 .addReg(mainDstReg).addMBB(mainMBB) 11012 .addReg(restoreDstReg).addMBB(thisMBB); 11013 11014 MI.eraseFromParent(); 11015 return sinkMBB; 11016 } 11017 11018 MachineBasicBlock * 11019 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr &MI, 11020 MachineBasicBlock *MBB) const { 11021 DebugLoc DL = MI.getDebugLoc(); 11022 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 11023 11024 MachineFunction *MF = MBB->getParent(); 11025 MachineRegisterInfo &MRI = MF->getRegInfo(); 11026 11027 MVT PVT = getPointerTy(MF->getDataLayout()); 11028 assert((PVT == MVT::i64 || PVT == MVT::i32) && 11029 "Invalid Pointer Size!"); 11030 11031 const TargetRegisterClass *RC = 11032 (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 11033 Register Tmp = MRI.createVirtualRegister(RC); 11034 // Since FP is only updated here but NOT referenced, it's treated as GPR. 11035 unsigned FP = (PVT == MVT::i64) ? PPC::X31 : PPC::R31; 11036 unsigned SP = (PVT == MVT::i64) ? PPC::X1 : PPC::R1; 11037 unsigned BP = 11038 (PVT == MVT::i64) 11039 ? PPC::X30 11040 : (Subtarget.isSVR4ABI() && isPositionIndependent() ? PPC::R29 11041 : PPC::R30); 11042 11043 MachineInstrBuilder MIB; 11044 11045 const int64_t LabelOffset = 1 * PVT.getStoreSize(); 11046 const int64_t SPOffset = 2 * PVT.getStoreSize(); 11047 const int64_t TOCOffset = 3 * PVT.getStoreSize(); 11048 const int64_t BPOffset = 4 * PVT.getStoreSize(); 11049 11050 Register BufReg = MI.getOperand(0).getReg(); 11051 11052 // Reload FP (the jumped-to function may not have had a 11053 // frame pointer, and if so, then its r31 will be restored 11054 // as necessary). 11055 if (PVT == MVT::i64) { 11056 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP) 11057 .addImm(0) 11058 .addReg(BufReg); 11059 } else { 11060 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP) 11061 .addImm(0) 11062 .addReg(BufReg); 11063 } 11064 MIB.cloneMemRefs(MI); 11065 11066 // Reload IP 11067 if (PVT == MVT::i64) { 11068 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp) 11069 .addImm(LabelOffset) 11070 .addReg(BufReg); 11071 } else { 11072 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp) 11073 .addImm(LabelOffset) 11074 .addReg(BufReg); 11075 } 11076 MIB.cloneMemRefs(MI); 11077 11078 // Reload SP 11079 if (PVT == MVT::i64) { 11080 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP) 11081 .addImm(SPOffset) 11082 .addReg(BufReg); 11083 } else { 11084 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP) 11085 .addImm(SPOffset) 11086 .addReg(BufReg); 11087 } 11088 MIB.cloneMemRefs(MI); 11089 11090 // Reload BP 11091 if (PVT == MVT::i64) { 11092 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP) 11093 .addImm(BPOffset) 11094 .addReg(BufReg); 11095 } else { 11096 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP) 11097 .addImm(BPOffset) 11098 .addReg(BufReg); 11099 } 11100 MIB.cloneMemRefs(MI); 11101 11102 // Reload TOC 11103 if (PVT == MVT::i64 && Subtarget.isSVR4ABI()) { 11104 setUsesTOCBasePtr(*MBB->getParent()); 11105 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2) 11106 .addImm(TOCOffset) 11107 .addReg(BufReg) 11108 .cloneMemRefs(MI); 11109 } 11110 11111 // Jump 11112 BuildMI(*MBB, MI, DL, 11113 TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp); 11114 BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR)); 11115 11116 MI.eraseFromParent(); 11117 return MBB; 11118 } 11119 11120 MachineBasicBlock * 11121 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI, 11122 MachineBasicBlock *BB) const { 11123 if (MI.getOpcode() == TargetOpcode::STACKMAP || 11124 MI.getOpcode() == TargetOpcode::PATCHPOINT) { 11125 if (Subtarget.is64BitELFABI() && 11126 MI.getOpcode() == TargetOpcode::PATCHPOINT) { 11127 // Call lowering should have added an r2 operand to indicate a dependence 11128 // on the TOC base pointer value. It can't however, because there is no 11129 // way to mark the dependence as implicit there, and so the stackmap code 11130 // will confuse it with a regular operand. Instead, add the dependence 11131 // here. 11132 MI.addOperand(MachineOperand::CreateReg(PPC::X2, false, true)); 11133 } 11134 11135 return emitPatchPoint(MI, BB); 11136 } 11137 11138 if (MI.getOpcode() == PPC::EH_SjLj_SetJmp32 || 11139 MI.getOpcode() == PPC::EH_SjLj_SetJmp64) { 11140 return emitEHSjLjSetJmp(MI, BB); 11141 } else if (MI.getOpcode() == PPC::EH_SjLj_LongJmp32 || 11142 MI.getOpcode() == PPC::EH_SjLj_LongJmp64) { 11143 return emitEHSjLjLongJmp(MI, BB); 11144 } 11145 11146 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 11147 11148 // To "insert" these instructions we actually have to insert their 11149 // control-flow patterns. 11150 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 11151 MachineFunction::iterator It = ++BB->getIterator(); 11152 11153 MachineFunction *F = BB->getParent(); 11154 11155 if (MI.getOpcode() == PPC::SELECT_CC_I4 || 11156 MI.getOpcode() == PPC::SELECT_CC_I8 || MI.getOpcode() == PPC::SELECT_I4 || 11157 MI.getOpcode() == PPC::SELECT_I8) { 11158 SmallVector<MachineOperand, 2> Cond; 11159 if (MI.getOpcode() == PPC::SELECT_CC_I4 || 11160 MI.getOpcode() == PPC::SELECT_CC_I8) 11161 Cond.push_back(MI.getOperand(4)); 11162 else 11163 Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET)); 11164 Cond.push_back(MI.getOperand(1)); 11165 11166 DebugLoc dl = MI.getDebugLoc(); 11167 TII->insertSelect(*BB, MI, dl, MI.getOperand(0).getReg(), Cond, 11168 MI.getOperand(2).getReg(), MI.getOperand(3).getReg()); 11169 } else if (MI.getOpcode() == PPC::SELECT_CC_F4 || 11170 MI.getOpcode() == PPC::SELECT_CC_F8 || 11171 MI.getOpcode() == PPC::SELECT_CC_F16 || 11172 MI.getOpcode() == PPC::SELECT_CC_QFRC || 11173 MI.getOpcode() == PPC::SELECT_CC_QSRC || 11174 MI.getOpcode() == PPC::SELECT_CC_QBRC || 11175 MI.getOpcode() == PPC::SELECT_CC_VRRC || 11176 MI.getOpcode() == PPC::SELECT_CC_VSFRC || 11177 MI.getOpcode() == PPC::SELECT_CC_VSSRC || 11178 MI.getOpcode() == PPC::SELECT_CC_VSRC || 11179 MI.getOpcode() == PPC::SELECT_CC_SPE4 || 11180 MI.getOpcode() == PPC::SELECT_CC_SPE || 11181 MI.getOpcode() == PPC::SELECT_F4 || 11182 MI.getOpcode() == PPC::SELECT_F8 || 11183 MI.getOpcode() == PPC::SELECT_F16 || 11184 MI.getOpcode() == PPC::SELECT_QFRC || 11185 MI.getOpcode() == PPC::SELECT_QSRC || 11186 MI.getOpcode() == PPC::SELECT_QBRC || 11187 MI.getOpcode() == PPC::SELECT_SPE || 11188 MI.getOpcode() == PPC::SELECT_SPE4 || 11189 MI.getOpcode() == PPC::SELECT_VRRC || 11190 MI.getOpcode() == PPC::SELECT_VSFRC || 11191 MI.getOpcode() == PPC::SELECT_VSSRC || 11192 MI.getOpcode() == PPC::SELECT_VSRC) { 11193 // The incoming instruction knows the destination vreg to set, the 11194 // condition code register to branch on, the true/false values to 11195 // select between, and a branch opcode to use. 11196 11197 // thisMBB: 11198 // ... 11199 // TrueVal = ... 11200 // cmpTY ccX, r1, r2 11201 // bCC copy1MBB 11202 // fallthrough --> copy0MBB 11203 MachineBasicBlock *thisMBB = BB; 11204 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB); 11205 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 11206 DebugLoc dl = MI.getDebugLoc(); 11207 F->insert(It, copy0MBB); 11208 F->insert(It, sinkMBB); 11209 11210 // Transfer the remainder of BB and its successor edges to sinkMBB. 11211 sinkMBB->splice(sinkMBB->begin(), BB, 11212 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 11213 sinkMBB->transferSuccessorsAndUpdatePHIs(BB); 11214 11215 // Next, add the true and fallthrough blocks as its successors. 11216 BB->addSuccessor(copy0MBB); 11217 BB->addSuccessor(sinkMBB); 11218 11219 if (MI.getOpcode() == PPC::SELECT_I4 || MI.getOpcode() == PPC::SELECT_I8 || 11220 MI.getOpcode() == PPC::SELECT_F4 || MI.getOpcode() == PPC::SELECT_F8 || 11221 MI.getOpcode() == PPC::SELECT_F16 || 11222 MI.getOpcode() == PPC::SELECT_SPE4 || 11223 MI.getOpcode() == PPC::SELECT_SPE || 11224 MI.getOpcode() == PPC::SELECT_QFRC || 11225 MI.getOpcode() == PPC::SELECT_QSRC || 11226 MI.getOpcode() == PPC::SELECT_QBRC || 11227 MI.getOpcode() == PPC::SELECT_VRRC || 11228 MI.getOpcode() == PPC::SELECT_VSFRC || 11229 MI.getOpcode() == PPC::SELECT_VSSRC || 11230 MI.getOpcode() == PPC::SELECT_VSRC) { 11231 BuildMI(BB, dl, TII->get(PPC::BC)) 11232 .addReg(MI.getOperand(1).getReg()) 11233 .addMBB(sinkMBB); 11234 } else { 11235 unsigned SelectPred = MI.getOperand(4).getImm(); 11236 BuildMI(BB, dl, TII->get(PPC::BCC)) 11237 .addImm(SelectPred) 11238 .addReg(MI.getOperand(1).getReg()) 11239 .addMBB(sinkMBB); 11240 } 11241 11242 // copy0MBB: 11243 // %FalseValue = ... 11244 // # fallthrough to sinkMBB 11245 BB = copy0MBB; 11246 11247 // Update machine-CFG edges 11248 BB->addSuccessor(sinkMBB); 11249 11250 // sinkMBB: 11251 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ] 11252 // ... 11253 BB = sinkMBB; 11254 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::PHI), MI.getOperand(0).getReg()) 11255 .addReg(MI.getOperand(3).getReg()) 11256 .addMBB(copy0MBB) 11257 .addReg(MI.getOperand(2).getReg()) 11258 .addMBB(thisMBB); 11259 } else if (MI.getOpcode() == PPC::ReadTB) { 11260 // To read the 64-bit time-base register on a 32-bit target, we read the 11261 // two halves. Should the counter have wrapped while it was being read, we 11262 // need to try again. 11263 // ... 11264 // readLoop: 11265 // mfspr Rx,TBU # load from TBU 11266 // mfspr Ry,TB # load from TB 11267 // mfspr Rz,TBU # load from TBU 11268 // cmpw crX,Rx,Rz # check if 'old'='new' 11269 // bne readLoop # branch if they're not equal 11270 // ... 11271 11272 MachineBasicBlock *readMBB = F->CreateMachineBasicBlock(LLVM_BB); 11273 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 11274 DebugLoc dl = MI.getDebugLoc(); 11275 F->insert(It, readMBB); 11276 F->insert(It, sinkMBB); 11277 11278 // Transfer the remainder of BB and its successor edges to sinkMBB. 11279 sinkMBB->splice(sinkMBB->begin(), BB, 11280 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 11281 sinkMBB->transferSuccessorsAndUpdatePHIs(BB); 11282 11283 BB->addSuccessor(readMBB); 11284 BB = readMBB; 11285 11286 MachineRegisterInfo &RegInfo = F->getRegInfo(); 11287 Register ReadAgainReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass); 11288 Register LoReg = MI.getOperand(0).getReg(); 11289 Register HiReg = MI.getOperand(1).getReg(); 11290 11291 BuildMI(BB, dl, TII->get(PPC::MFSPR), HiReg).addImm(269); 11292 BuildMI(BB, dl, TII->get(PPC::MFSPR), LoReg).addImm(268); 11293 BuildMI(BB, dl, TII->get(PPC::MFSPR), ReadAgainReg).addImm(269); 11294 11295 Register CmpReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass); 11296 11297 BuildMI(BB, dl, TII->get(PPC::CMPW), CmpReg) 11298 .addReg(HiReg) 11299 .addReg(ReadAgainReg); 11300 BuildMI(BB, dl, TII->get(PPC::BCC)) 11301 .addImm(PPC::PRED_NE) 11302 .addReg(CmpReg) 11303 .addMBB(readMBB); 11304 11305 BB->addSuccessor(readMBB); 11306 BB->addSuccessor(sinkMBB); 11307 } else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I8) 11308 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4); 11309 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I16) 11310 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4); 11311 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I32) 11312 BB = EmitAtomicBinary(MI, BB, 4, PPC::ADD4); 11313 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I64) 11314 BB = EmitAtomicBinary(MI, BB, 8, PPC::ADD8); 11315 11316 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I8) 11317 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND); 11318 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I16) 11319 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND); 11320 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I32) 11321 BB = EmitAtomicBinary(MI, BB, 4, PPC::AND); 11322 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I64) 11323 BB = EmitAtomicBinary(MI, BB, 8, PPC::AND8); 11324 11325 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I8) 11326 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR); 11327 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I16) 11328 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR); 11329 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I32) 11330 BB = EmitAtomicBinary(MI, BB, 4, PPC::OR); 11331 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I64) 11332 BB = EmitAtomicBinary(MI, BB, 8, PPC::OR8); 11333 11334 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I8) 11335 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR); 11336 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I16) 11337 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR); 11338 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I32) 11339 BB = EmitAtomicBinary(MI, BB, 4, PPC::XOR); 11340 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I64) 11341 BB = EmitAtomicBinary(MI, BB, 8, PPC::XOR8); 11342 11343 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I8) 11344 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::NAND); 11345 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I16) 11346 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::NAND); 11347 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I32) 11348 BB = EmitAtomicBinary(MI, BB, 4, PPC::NAND); 11349 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I64) 11350 BB = EmitAtomicBinary(MI, BB, 8, PPC::NAND8); 11351 11352 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I8) 11353 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF); 11354 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I16) 11355 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF); 11356 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I32) 11357 BB = EmitAtomicBinary(MI, BB, 4, PPC::SUBF); 11358 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I64) 11359 BB = EmitAtomicBinary(MI, BB, 8, PPC::SUBF8); 11360 11361 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I8) 11362 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_GE); 11363 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I16) 11364 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_GE); 11365 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I32) 11366 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_GE); 11367 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I64) 11368 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_GE); 11369 11370 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I8) 11371 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_LE); 11372 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I16) 11373 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_LE); 11374 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I32) 11375 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_LE); 11376 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I64) 11377 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_LE); 11378 11379 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I8) 11380 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_GE); 11381 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I16) 11382 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_GE); 11383 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I32) 11384 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_GE); 11385 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I64) 11386 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_GE); 11387 11388 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I8) 11389 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_LE); 11390 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I16) 11391 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_LE); 11392 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I32) 11393 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_LE); 11394 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I64) 11395 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_LE); 11396 11397 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I8) 11398 BB = EmitPartwordAtomicBinary(MI, BB, true, 0); 11399 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I16) 11400 BB = EmitPartwordAtomicBinary(MI, BB, false, 0); 11401 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I32) 11402 BB = EmitAtomicBinary(MI, BB, 4, 0); 11403 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I64) 11404 BB = EmitAtomicBinary(MI, BB, 8, 0); 11405 else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 || 11406 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64 || 11407 (Subtarget.hasPartwordAtomics() && 11408 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8) || 11409 (Subtarget.hasPartwordAtomics() && 11410 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16)) { 11411 bool is64bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64; 11412 11413 auto LoadMnemonic = PPC::LDARX; 11414 auto StoreMnemonic = PPC::STDCX; 11415 switch (MI.getOpcode()) { 11416 default: 11417 llvm_unreachable("Compare and swap of unknown size"); 11418 case PPC::ATOMIC_CMP_SWAP_I8: 11419 LoadMnemonic = PPC::LBARX; 11420 StoreMnemonic = PPC::STBCX; 11421 assert(Subtarget.hasPartwordAtomics() && "No support partword atomics."); 11422 break; 11423 case PPC::ATOMIC_CMP_SWAP_I16: 11424 LoadMnemonic = PPC::LHARX; 11425 StoreMnemonic = PPC::STHCX; 11426 assert(Subtarget.hasPartwordAtomics() && "No support partword atomics."); 11427 break; 11428 case PPC::ATOMIC_CMP_SWAP_I32: 11429 LoadMnemonic = PPC::LWARX; 11430 StoreMnemonic = PPC::STWCX; 11431 break; 11432 case PPC::ATOMIC_CMP_SWAP_I64: 11433 LoadMnemonic = PPC::LDARX; 11434 StoreMnemonic = PPC::STDCX; 11435 break; 11436 } 11437 Register dest = MI.getOperand(0).getReg(); 11438 Register ptrA = MI.getOperand(1).getReg(); 11439 Register ptrB = MI.getOperand(2).getReg(); 11440 Register oldval = MI.getOperand(3).getReg(); 11441 Register newval = MI.getOperand(4).getReg(); 11442 DebugLoc dl = MI.getDebugLoc(); 11443 11444 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB); 11445 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB); 11446 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB); 11447 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 11448 F->insert(It, loop1MBB); 11449 F->insert(It, loop2MBB); 11450 F->insert(It, midMBB); 11451 F->insert(It, exitMBB); 11452 exitMBB->splice(exitMBB->begin(), BB, 11453 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 11454 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 11455 11456 // thisMBB: 11457 // ... 11458 // fallthrough --> loopMBB 11459 BB->addSuccessor(loop1MBB); 11460 11461 // loop1MBB: 11462 // l[bhwd]arx dest, ptr 11463 // cmp[wd] dest, oldval 11464 // bne- midMBB 11465 // loop2MBB: 11466 // st[bhwd]cx. newval, ptr 11467 // bne- loopMBB 11468 // b exitBB 11469 // midMBB: 11470 // st[bhwd]cx. dest, ptr 11471 // exitBB: 11472 BB = loop1MBB; 11473 BuildMI(BB, dl, TII->get(LoadMnemonic), dest).addReg(ptrA).addReg(ptrB); 11474 BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0) 11475 .addReg(oldval) 11476 .addReg(dest); 11477 BuildMI(BB, dl, TII->get(PPC::BCC)) 11478 .addImm(PPC::PRED_NE) 11479 .addReg(PPC::CR0) 11480 .addMBB(midMBB); 11481 BB->addSuccessor(loop2MBB); 11482 BB->addSuccessor(midMBB); 11483 11484 BB = loop2MBB; 11485 BuildMI(BB, dl, TII->get(StoreMnemonic)) 11486 .addReg(newval) 11487 .addReg(ptrA) 11488 .addReg(ptrB); 11489 BuildMI(BB, dl, TII->get(PPC::BCC)) 11490 .addImm(PPC::PRED_NE) 11491 .addReg(PPC::CR0) 11492 .addMBB(loop1MBB); 11493 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB); 11494 BB->addSuccessor(loop1MBB); 11495 BB->addSuccessor(exitMBB); 11496 11497 BB = midMBB; 11498 BuildMI(BB, dl, TII->get(StoreMnemonic)) 11499 .addReg(dest) 11500 .addReg(ptrA) 11501 .addReg(ptrB); 11502 BB->addSuccessor(exitMBB); 11503 11504 // exitMBB: 11505 // ... 11506 BB = exitMBB; 11507 } else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 || 11508 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) { 11509 // We must use 64-bit registers for addresses when targeting 64-bit, 11510 // since we're actually doing arithmetic on them. Other registers 11511 // can be 32-bit. 11512 bool is64bit = Subtarget.isPPC64(); 11513 bool isLittleEndian = Subtarget.isLittleEndian(); 11514 bool is8bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8; 11515 11516 Register dest = MI.getOperand(0).getReg(); 11517 Register ptrA = MI.getOperand(1).getReg(); 11518 Register ptrB = MI.getOperand(2).getReg(); 11519 Register oldval = MI.getOperand(3).getReg(); 11520 Register newval = MI.getOperand(4).getReg(); 11521 DebugLoc dl = MI.getDebugLoc(); 11522 11523 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB); 11524 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB); 11525 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB); 11526 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 11527 F->insert(It, loop1MBB); 11528 F->insert(It, loop2MBB); 11529 F->insert(It, midMBB); 11530 F->insert(It, exitMBB); 11531 exitMBB->splice(exitMBB->begin(), BB, 11532 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 11533 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 11534 11535 MachineRegisterInfo &RegInfo = F->getRegInfo(); 11536 const TargetRegisterClass *RC = 11537 is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 11538 const TargetRegisterClass *GPRC = &PPC::GPRCRegClass; 11539 11540 Register PtrReg = RegInfo.createVirtualRegister(RC); 11541 Register Shift1Reg = RegInfo.createVirtualRegister(GPRC); 11542 Register ShiftReg = 11543 isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC); 11544 Register NewVal2Reg = RegInfo.createVirtualRegister(GPRC); 11545 Register NewVal3Reg = RegInfo.createVirtualRegister(GPRC); 11546 Register OldVal2Reg = RegInfo.createVirtualRegister(GPRC); 11547 Register OldVal3Reg = RegInfo.createVirtualRegister(GPRC); 11548 Register MaskReg = RegInfo.createVirtualRegister(GPRC); 11549 Register Mask2Reg = RegInfo.createVirtualRegister(GPRC); 11550 Register Mask3Reg = RegInfo.createVirtualRegister(GPRC); 11551 Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC); 11552 Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC); 11553 Register TmpDestReg = RegInfo.createVirtualRegister(GPRC); 11554 Register Ptr1Reg; 11555 Register TmpReg = RegInfo.createVirtualRegister(GPRC); 11556 Register ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO; 11557 // thisMBB: 11558 // ... 11559 // fallthrough --> loopMBB 11560 BB->addSuccessor(loop1MBB); 11561 11562 // The 4-byte load must be aligned, while a char or short may be 11563 // anywhere in the word. Hence all this nasty bookkeeping code. 11564 // add ptr1, ptrA, ptrB [copy if ptrA==0] 11565 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27] 11566 // xori shift, shift1, 24 [16] 11567 // rlwinm ptr, ptr1, 0, 0, 29 11568 // slw newval2, newval, shift 11569 // slw oldval2, oldval,shift 11570 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535] 11571 // slw mask, mask2, shift 11572 // and newval3, newval2, mask 11573 // and oldval3, oldval2, mask 11574 // loop1MBB: 11575 // lwarx tmpDest, ptr 11576 // and tmp, tmpDest, mask 11577 // cmpw tmp, oldval3 11578 // bne- midMBB 11579 // loop2MBB: 11580 // andc tmp2, tmpDest, mask 11581 // or tmp4, tmp2, newval3 11582 // stwcx. tmp4, ptr 11583 // bne- loop1MBB 11584 // b exitBB 11585 // midMBB: 11586 // stwcx. tmpDest, ptr 11587 // exitBB: 11588 // srw dest, tmpDest, shift 11589 if (ptrA != ZeroReg) { 11590 Ptr1Reg = RegInfo.createVirtualRegister(RC); 11591 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg) 11592 .addReg(ptrA) 11593 .addReg(ptrB); 11594 } else { 11595 Ptr1Reg = ptrB; 11596 } 11597 11598 // We need use 32-bit subregister to avoid mismatch register class in 64-bit 11599 // mode. 11600 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg) 11601 .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0) 11602 .addImm(3) 11603 .addImm(27) 11604 .addImm(is8bit ? 28 : 27); 11605 if (!isLittleEndian) 11606 BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg) 11607 .addReg(Shift1Reg) 11608 .addImm(is8bit ? 24 : 16); 11609 if (is64bit) 11610 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg) 11611 .addReg(Ptr1Reg) 11612 .addImm(0) 11613 .addImm(61); 11614 else 11615 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg) 11616 .addReg(Ptr1Reg) 11617 .addImm(0) 11618 .addImm(0) 11619 .addImm(29); 11620 BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg) 11621 .addReg(newval) 11622 .addReg(ShiftReg); 11623 BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg) 11624 .addReg(oldval) 11625 .addReg(ShiftReg); 11626 if (is8bit) 11627 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255); 11628 else { 11629 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0); 11630 BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg) 11631 .addReg(Mask3Reg) 11632 .addImm(65535); 11633 } 11634 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg) 11635 .addReg(Mask2Reg) 11636 .addReg(ShiftReg); 11637 BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg) 11638 .addReg(NewVal2Reg) 11639 .addReg(MaskReg); 11640 BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg) 11641 .addReg(OldVal2Reg) 11642 .addReg(MaskReg); 11643 11644 BB = loop1MBB; 11645 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg) 11646 .addReg(ZeroReg) 11647 .addReg(PtrReg); 11648 BuildMI(BB, dl, TII->get(PPC::AND), TmpReg) 11649 .addReg(TmpDestReg) 11650 .addReg(MaskReg); 11651 BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0) 11652 .addReg(TmpReg) 11653 .addReg(OldVal3Reg); 11654 BuildMI(BB, dl, TII->get(PPC::BCC)) 11655 .addImm(PPC::PRED_NE) 11656 .addReg(PPC::CR0) 11657 .addMBB(midMBB); 11658 BB->addSuccessor(loop2MBB); 11659 BB->addSuccessor(midMBB); 11660 11661 BB = loop2MBB; 11662 BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg) 11663 .addReg(TmpDestReg) 11664 .addReg(MaskReg); 11665 BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg) 11666 .addReg(Tmp2Reg) 11667 .addReg(NewVal3Reg); 11668 BuildMI(BB, dl, TII->get(PPC::STWCX)) 11669 .addReg(Tmp4Reg) 11670 .addReg(ZeroReg) 11671 .addReg(PtrReg); 11672 BuildMI(BB, dl, TII->get(PPC::BCC)) 11673 .addImm(PPC::PRED_NE) 11674 .addReg(PPC::CR0) 11675 .addMBB(loop1MBB); 11676 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB); 11677 BB->addSuccessor(loop1MBB); 11678 BB->addSuccessor(exitMBB); 11679 11680 BB = midMBB; 11681 BuildMI(BB, dl, TII->get(PPC::STWCX)) 11682 .addReg(TmpDestReg) 11683 .addReg(ZeroReg) 11684 .addReg(PtrReg); 11685 BB->addSuccessor(exitMBB); 11686 11687 // exitMBB: 11688 // ... 11689 BB = exitMBB; 11690 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest) 11691 .addReg(TmpReg) 11692 .addReg(ShiftReg); 11693 } else if (MI.getOpcode() == PPC::FADDrtz) { 11694 // This pseudo performs an FADD with rounding mode temporarily forced 11695 // to round-to-zero. We emit this via custom inserter since the FPSCR 11696 // is not modeled at the SelectionDAG level. 11697 Register Dest = MI.getOperand(0).getReg(); 11698 Register Src1 = MI.getOperand(1).getReg(); 11699 Register Src2 = MI.getOperand(2).getReg(); 11700 DebugLoc dl = MI.getDebugLoc(); 11701 11702 MachineRegisterInfo &RegInfo = F->getRegInfo(); 11703 Register MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass); 11704 11705 // Save FPSCR value. 11706 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg); 11707 11708 // Set rounding mode to round-to-zero. 11709 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1)).addImm(31); 11710 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0)).addImm(30); 11711 11712 // Perform addition. 11713 BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest).addReg(Src1).addReg(Src2); 11714 11715 // Restore FPSCR value. 11716 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSFb)).addImm(1).addReg(MFFSReg); 11717 } else if (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT || 11718 MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT || 11719 MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8 || 11720 MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT8) { 11721 unsigned Opcode = (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8 || 11722 MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT8) 11723 ? PPC::ANDI8_rec 11724 : PPC::ANDI_rec; 11725 bool IsEQ = (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT || 11726 MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8); 11727 11728 MachineRegisterInfo &RegInfo = F->getRegInfo(); 11729 Register Dest = RegInfo.createVirtualRegister( 11730 Opcode == PPC::ANDI_rec ? &PPC::GPRCRegClass : &PPC::G8RCRegClass); 11731 11732 DebugLoc Dl = MI.getDebugLoc(); 11733 BuildMI(*BB, MI, Dl, TII->get(Opcode), Dest) 11734 .addReg(MI.getOperand(1).getReg()) 11735 .addImm(1); 11736 BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY), 11737 MI.getOperand(0).getReg()) 11738 .addReg(IsEQ ? PPC::CR0EQ : PPC::CR0GT); 11739 } else if (MI.getOpcode() == PPC::TCHECK_RET) { 11740 DebugLoc Dl = MI.getDebugLoc(); 11741 MachineRegisterInfo &RegInfo = F->getRegInfo(); 11742 Register CRReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass); 11743 BuildMI(*BB, MI, Dl, TII->get(PPC::TCHECK), CRReg); 11744 BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY), 11745 MI.getOperand(0).getReg()) 11746 .addReg(CRReg); 11747 } else if (MI.getOpcode() == PPC::TBEGIN_RET) { 11748 DebugLoc Dl = MI.getDebugLoc(); 11749 unsigned Imm = MI.getOperand(1).getImm(); 11750 BuildMI(*BB, MI, Dl, TII->get(PPC::TBEGIN)).addImm(Imm); 11751 BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY), 11752 MI.getOperand(0).getReg()) 11753 .addReg(PPC::CR0EQ); 11754 } else if (MI.getOpcode() == PPC::SETRNDi) { 11755 DebugLoc dl = MI.getDebugLoc(); 11756 Register OldFPSCRReg = MI.getOperand(0).getReg(); 11757 11758 // Save FPSCR value. 11759 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg); 11760 11761 // The floating point rounding mode is in the bits 62:63 of FPCSR, and has 11762 // the following settings: 11763 // 00 Round to nearest 11764 // 01 Round to 0 11765 // 10 Round to +inf 11766 // 11 Round to -inf 11767 11768 // When the operand is immediate, using the two least significant bits of 11769 // the immediate to set the bits 62:63 of FPSCR. 11770 unsigned Mode = MI.getOperand(1).getImm(); 11771 BuildMI(*BB, MI, dl, TII->get((Mode & 1) ? PPC::MTFSB1 : PPC::MTFSB0)) 11772 .addImm(31); 11773 11774 BuildMI(*BB, MI, dl, TII->get((Mode & 2) ? PPC::MTFSB1 : PPC::MTFSB0)) 11775 .addImm(30); 11776 } else if (MI.getOpcode() == PPC::SETRND) { 11777 DebugLoc dl = MI.getDebugLoc(); 11778 11779 // Copy register from F8RCRegClass::SrcReg to G8RCRegClass::DestReg 11780 // or copy register from G8RCRegClass::SrcReg to F8RCRegClass::DestReg. 11781 // If the target doesn't have DirectMove, we should use stack to do the 11782 // conversion, because the target doesn't have the instructions like mtvsrd 11783 // or mfvsrd to do this conversion directly. 11784 auto copyRegFromG8RCOrF8RC = [&] (unsigned DestReg, unsigned SrcReg) { 11785 if (Subtarget.hasDirectMove()) { 11786 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), DestReg) 11787 .addReg(SrcReg); 11788 } else { 11789 // Use stack to do the register copy. 11790 unsigned StoreOp = PPC::STD, LoadOp = PPC::LFD; 11791 MachineRegisterInfo &RegInfo = F->getRegInfo(); 11792 const TargetRegisterClass *RC = RegInfo.getRegClass(SrcReg); 11793 if (RC == &PPC::F8RCRegClass) { 11794 // Copy register from F8RCRegClass to G8RCRegclass. 11795 assert((RegInfo.getRegClass(DestReg) == &PPC::G8RCRegClass) && 11796 "Unsupported RegClass."); 11797 11798 StoreOp = PPC::STFD; 11799 LoadOp = PPC::LD; 11800 } else { 11801 // Copy register from G8RCRegClass to F8RCRegclass. 11802 assert((RegInfo.getRegClass(SrcReg) == &PPC::G8RCRegClass) && 11803 (RegInfo.getRegClass(DestReg) == &PPC::F8RCRegClass) && 11804 "Unsupported RegClass."); 11805 } 11806 11807 MachineFrameInfo &MFI = F->getFrameInfo(); 11808 int FrameIdx = MFI.CreateStackObject(8, 8, false); 11809 11810 MachineMemOperand *MMOStore = F->getMachineMemOperand( 11811 MachinePointerInfo::getFixedStack(*F, FrameIdx, 0), 11812 MachineMemOperand::MOStore, MFI.getObjectSize(FrameIdx), 11813 MFI.getObjectAlignment(FrameIdx)); 11814 11815 // Store the SrcReg into the stack. 11816 BuildMI(*BB, MI, dl, TII->get(StoreOp)) 11817 .addReg(SrcReg) 11818 .addImm(0) 11819 .addFrameIndex(FrameIdx) 11820 .addMemOperand(MMOStore); 11821 11822 MachineMemOperand *MMOLoad = F->getMachineMemOperand( 11823 MachinePointerInfo::getFixedStack(*F, FrameIdx, 0), 11824 MachineMemOperand::MOLoad, MFI.getObjectSize(FrameIdx), 11825 MFI.getObjectAlignment(FrameIdx)); 11826 11827 // Load from the stack where SrcReg is stored, and save to DestReg, 11828 // so we have done the RegClass conversion from RegClass::SrcReg to 11829 // RegClass::DestReg. 11830 BuildMI(*BB, MI, dl, TII->get(LoadOp), DestReg) 11831 .addImm(0) 11832 .addFrameIndex(FrameIdx) 11833 .addMemOperand(MMOLoad); 11834 } 11835 }; 11836 11837 Register OldFPSCRReg = MI.getOperand(0).getReg(); 11838 11839 // Save FPSCR value. 11840 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg); 11841 11842 // When the operand is gprc register, use two least significant bits of the 11843 // register and mtfsf instruction to set the bits 62:63 of FPSCR. 11844 // 11845 // copy OldFPSCRTmpReg, OldFPSCRReg 11846 // (INSERT_SUBREG ExtSrcReg, (IMPLICIT_DEF ImDefReg), SrcOp, 1) 11847 // rldimi NewFPSCRTmpReg, ExtSrcReg, OldFPSCRReg, 0, 62 11848 // copy NewFPSCRReg, NewFPSCRTmpReg 11849 // mtfsf 255, NewFPSCRReg 11850 MachineOperand SrcOp = MI.getOperand(1); 11851 MachineRegisterInfo &RegInfo = F->getRegInfo(); 11852 Register OldFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 11853 11854 copyRegFromG8RCOrF8RC(OldFPSCRTmpReg, OldFPSCRReg); 11855 11856 Register ImDefReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 11857 Register ExtSrcReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 11858 11859 // The first operand of INSERT_SUBREG should be a register which has 11860 // subregisters, we only care about its RegClass, so we should use an 11861 // IMPLICIT_DEF register. 11862 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::IMPLICIT_DEF), ImDefReg); 11863 BuildMI(*BB, MI, dl, TII->get(PPC::INSERT_SUBREG), ExtSrcReg) 11864 .addReg(ImDefReg) 11865 .add(SrcOp) 11866 .addImm(1); 11867 11868 Register NewFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 11869 BuildMI(*BB, MI, dl, TII->get(PPC::RLDIMI), NewFPSCRTmpReg) 11870 .addReg(OldFPSCRTmpReg) 11871 .addReg(ExtSrcReg) 11872 .addImm(0) 11873 .addImm(62); 11874 11875 Register NewFPSCRReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass); 11876 copyRegFromG8RCOrF8RC(NewFPSCRReg, NewFPSCRTmpReg); 11877 11878 // The mask 255 means that put the 32:63 bits of NewFPSCRReg to the 32:63 11879 // bits of FPSCR. 11880 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSF)) 11881 .addImm(255) 11882 .addReg(NewFPSCRReg) 11883 .addImm(0) 11884 .addImm(0); 11885 } else { 11886 llvm_unreachable("Unexpected instr type to insert"); 11887 } 11888 11889 MI.eraseFromParent(); // The pseudo instruction is gone now. 11890 return BB; 11891 } 11892 11893 //===----------------------------------------------------------------------===// 11894 // Target Optimization Hooks 11895 //===----------------------------------------------------------------------===// 11896 11897 static int getEstimateRefinementSteps(EVT VT, const PPCSubtarget &Subtarget) { 11898 // For the estimates, convergence is quadratic, so we essentially double the 11899 // number of digits correct after every iteration. For both FRE and FRSQRTE, 11900 // the minimum architected relative accuracy is 2^-5. When hasRecipPrec(), 11901 // this is 2^-14. IEEE float has 23 digits and double has 52 digits. 11902 int RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3; 11903 if (VT.getScalarType() == MVT::f64) 11904 RefinementSteps++; 11905 return RefinementSteps; 11906 } 11907 11908 SDValue PPCTargetLowering::getSqrtEstimate(SDValue Operand, SelectionDAG &DAG, 11909 int Enabled, int &RefinementSteps, 11910 bool &UseOneConstNR, 11911 bool Reciprocal) const { 11912 EVT VT = Operand.getValueType(); 11913 if ((VT == MVT::f32 && Subtarget.hasFRSQRTES()) || 11914 (VT == MVT::f64 && Subtarget.hasFRSQRTE()) || 11915 (VT == MVT::v4f32 && Subtarget.hasAltivec()) || 11916 (VT == MVT::v2f64 && Subtarget.hasVSX()) || 11917 (VT == MVT::v4f32 && Subtarget.hasQPX()) || 11918 (VT == MVT::v4f64 && Subtarget.hasQPX())) { 11919 if (RefinementSteps == ReciprocalEstimate::Unspecified) 11920 RefinementSteps = getEstimateRefinementSteps(VT, Subtarget); 11921 11922 // The Newton-Raphson computation with a single constant does not provide 11923 // enough accuracy on some CPUs. 11924 UseOneConstNR = !Subtarget.needsTwoConstNR(); 11925 return DAG.getNode(PPCISD::FRSQRTE, SDLoc(Operand), VT, Operand); 11926 } 11927 return SDValue(); 11928 } 11929 11930 SDValue PPCTargetLowering::getRecipEstimate(SDValue Operand, SelectionDAG &DAG, 11931 int Enabled, 11932 int &RefinementSteps) const { 11933 EVT VT = Operand.getValueType(); 11934 if ((VT == MVT::f32 && Subtarget.hasFRES()) || 11935 (VT == MVT::f64 && Subtarget.hasFRE()) || 11936 (VT == MVT::v4f32 && Subtarget.hasAltivec()) || 11937 (VT == MVT::v2f64 && Subtarget.hasVSX()) || 11938 (VT == MVT::v4f32 && Subtarget.hasQPX()) || 11939 (VT == MVT::v4f64 && Subtarget.hasQPX())) { 11940 if (RefinementSteps == ReciprocalEstimate::Unspecified) 11941 RefinementSteps = getEstimateRefinementSteps(VT, Subtarget); 11942 return DAG.getNode(PPCISD::FRE, SDLoc(Operand), VT, Operand); 11943 } 11944 return SDValue(); 11945 } 11946 11947 unsigned PPCTargetLowering::combineRepeatedFPDivisors() const { 11948 // Note: This functionality is used only when unsafe-fp-math is enabled, and 11949 // on cores with reciprocal estimates (which are used when unsafe-fp-math is 11950 // enabled for division), this functionality is redundant with the default 11951 // combiner logic (once the division -> reciprocal/multiply transformation 11952 // has taken place). As a result, this matters more for older cores than for 11953 // newer ones. 11954 11955 // Combine multiple FDIVs with the same divisor into multiple FMULs by the 11956 // reciprocal if there are two or more FDIVs (for embedded cores with only 11957 // one FP pipeline) for three or more FDIVs (for generic OOO cores). 11958 switch (Subtarget.getCPUDirective()) { 11959 default: 11960 return 3; 11961 case PPC::DIR_440: 11962 case PPC::DIR_A2: 11963 case PPC::DIR_E500: 11964 case PPC::DIR_E500mc: 11965 case PPC::DIR_E5500: 11966 return 2; 11967 } 11968 } 11969 11970 // isConsecutiveLSLoc needs to work even if all adds have not yet been 11971 // collapsed, and so we need to look through chains of them. 11972 static void getBaseWithConstantOffset(SDValue Loc, SDValue &Base, 11973 int64_t& Offset, SelectionDAG &DAG) { 11974 if (DAG.isBaseWithConstantOffset(Loc)) { 11975 Base = Loc.getOperand(0); 11976 Offset += cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue(); 11977 11978 // The base might itself be a base plus an offset, and if so, accumulate 11979 // that as well. 11980 getBaseWithConstantOffset(Loc.getOperand(0), Base, Offset, DAG); 11981 } 11982 } 11983 11984 static bool isConsecutiveLSLoc(SDValue Loc, EVT VT, LSBaseSDNode *Base, 11985 unsigned Bytes, int Dist, 11986 SelectionDAG &DAG) { 11987 if (VT.getSizeInBits() / 8 != Bytes) 11988 return false; 11989 11990 SDValue BaseLoc = Base->getBasePtr(); 11991 if (Loc.getOpcode() == ISD::FrameIndex) { 11992 if (BaseLoc.getOpcode() != ISD::FrameIndex) 11993 return false; 11994 const MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 11995 int FI = cast<FrameIndexSDNode>(Loc)->getIndex(); 11996 int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex(); 11997 int FS = MFI.getObjectSize(FI); 11998 int BFS = MFI.getObjectSize(BFI); 11999 if (FS != BFS || FS != (int)Bytes) return false; 12000 return MFI.getObjectOffset(FI) == (MFI.getObjectOffset(BFI) + Dist*Bytes); 12001 } 12002 12003 SDValue Base1 = Loc, Base2 = BaseLoc; 12004 int64_t Offset1 = 0, Offset2 = 0; 12005 getBaseWithConstantOffset(Loc, Base1, Offset1, DAG); 12006 getBaseWithConstantOffset(BaseLoc, Base2, Offset2, DAG); 12007 if (Base1 == Base2 && Offset1 == (Offset2 + Dist * Bytes)) 12008 return true; 12009 12010 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 12011 const GlobalValue *GV1 = nullptr; 12012 const GlobalValue *GV2 = nullptr; 12013 Offset1 = 0; 12014 Offset2 = 0; 12015 bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1); 12016 bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2); 12017 if (isGA1 && isGA2 && GV1 == GV2) 12018 return Offset1 == (Offset2 + Dist*Bytes); 12019 return false; 12020 } 12021 12022 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does 12023 // not enforce equality of the chain operands. 12024 static bool isConsecutiveLS(SDNode *N, LSBaseSDNode *Base, 12025 unsigned Bytes, int Dist, 12026 SelectionDAG &DAG) { 12027 if (LSBaseSDNode *LS = dyn_cast<LSBaseSDNode>(N)) { 12028 EVT VT = LS->getMemoryVT(); 12029 SDValue Loc = LS->getBasePtr(); 12030 return isConsecutiveLSLoc(Loc, VT, Base, Bytes, Dist, DAG); 12031 } 12032 12033 if (N->getOpcode() == ISD::INTRINSIC_W_CHAIN) { 12034 EVT VT; 12035 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 12036 default: return false; 12037 case Intrinsic::ppc_qpx_qvlfd: 12038 case Intrinsic::ppc_qpx_qvlfda: 12039 VT = MVT::v4f64; 12040 break; 12041 case Intrinsic::ppc_qpx_qvlfs: 12042 case Intrinsic::ppc_qpx_qvlfsa: 12043 VT = MVT::v4f32; 12044 break; 12045 case Intrinsic::ppc_qpx_qvlfcd: 12046 case Intrinsic::ppc_qpx_qvlfcda: 12047 VT = MVT::v2f64; 12048 break; 12049 case Intrinsic::ppc_qpx_qvlfcs: 12050 case Intrinsic::ppc_qpx_qvlfcsa: 12051 VT = MVT::v2f32; 12052 break; 12053 case Intrinsic::ppc_qpx_qvlfiwa: 12054 case Intrinsic::ppc_qpx_qvlfiwz: 12055 case Intrinsic::ppc_altivec_lvx: 12056 case Intrinsic::ppc_altivec_lvxl: 12057 case Intrinsic::ppc_vsx_lxvw4x: 12058 case Intrinsic::ppc_vsx_lxvw4x_be: 12059 VT = MVT::v4i32; 12060 break; 12061 case Intrinsic::ppc_vsx_lxvd2x: 12062 case Intrinsic::ppc_vsx_lxvd2x_be: 12063 VT = MVT::v2f64; 12064 break; 12065 case Intrinsic::ppc_altivec_lvebx: 12066 VT = MVT::i8; 12067 break; 12068 case Intrinsic::ppc_altivec_lvehx: 12069 VT = MVT::i16; 12070 break; 12071 case Intrinsic::ppc_altivec_lvewx: 12072 VT = MVT::i32; 12073 break; 12074 } 12075 12076 return isConsecutiveLSLoc(N->getOperand(2), VT, Base, Bytes, Dist, DAG); 12077 } 12078 12079 if (N->getOpcode() == ISD::INTRINSIC_VOID) { 12080 EVT VT; 12081 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 12082 default: return false; 12083 case Intrinsic::ppc_qpx_qvstfd: 12084 case Intrinsic::ppc_qpx_qvstfda: 12085 VT = MVT::v4f64; 12086 break; 12087 case Intrinsic::ppc_qpx_qvstfs: 12088 case Intrinsic::ppc_qpx_qvstfsa: 12089 VT = MVT::v4f32; 12090 break; 12091 case Intrinsic::ppc_qpx_qvstfcd: 12092 case Intrinsic::ppc_qpx_qvstfcda: 12093 VT = MVT::v2f64; 12094 break; 12095 case Intrinsic::ppc_qpx_qvstfcs: 12096 case Intrinsic::ppc_qpx_qvstfcsa: 12097 VT = MVT::v2f32; 12098 break; 12099 case Intrinsic::ppc_qpx_qvstfiw: 12100 case Intrinsic::ppc_qpx_qvstfiwa: 12101 case Intrinsic::ppc_altivec_stvx: 12102 case Intrinsic::ppc_altivec_stvxl: 12103 case Intrinsic::ppc_vsx_stxvw4x: 12104 VT = MVT::v4i32; 12105 break; 12106 case Intrinsic::ppc_vsx_stxvd2x: 12107 VT = MVT::v2f64; 12108 break; 12109 case Intrinsic::ppc_vsx_stxvw4x_be: 12110 VT = MVT::v4i32; 12111 break; 12112 case Intrinsic::ppc_vsx_stxvd2x_be: 12113 VT = MVT::v2f64; 12114 break; 12115 case Intrinsic::ppc_altivec_stvebx: 12116 VT = MVT::i8; 12117 break; 12118 case Intrinsic::ppc_altivec_stvehx: 12119 VT = MVT::i16; 12120 break; 12121 case Intrinsic::ppc_altivec_stvewx: 12122 VT = MVT::i32; 12123 break; 12124 } 12125 12126 return isConsecutiveLSLoc(N->getOperand(3), VT, Base, Bytes, Dist, DAG); 12127 } 12128 12129 return false; 12130 } 12131 12132 // Return true is there is a nearyby consecutive load to the one provided 12133 // (regardless of alignment). We search up and down the chain, looking though 12134 // token factors and other loads (but nothing else). As a result, a true result 12135 // indicates that it is safe to create a new consecutive load adjacent to the 12136 // load provided. 12137 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) { 12138 SDValue Chain = LD->getChain(); 12139 EVT VT = LD->getMemoryVT(); 12140 12141 SmallSet<SDNode *, 16> LoadRoots; 12142 SmallVector<SDNode *, 8> Queue(1, Chain.getNode()); 12143 SmallSet<SDNode *, 16> Visited; 12144 12145 // First, search up the chain, branching to follow all token-factor operands. 12146 // If we find a consecutive load, then we're done, otherwise, record all 12147 // nodes just above the top-level loads and token factors. 12148 while (!Queue.empty()) { 12149 SDNode *ChainNext = Queue.pop_back_val(); 12150 if (!Visited.insert(ChainNext).second) 12151 continue; 12152 12153 if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(ChainNext)) { 12154 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG)) 12155 return true; 12156 12157 if (!Visited.count(ChainLD->getChain().getNode())) 12158 Queue.push_back(ChainLD->getChain().getNode()); 12159 } else if (ChainNext->getOpcode() == ISD::TokenFactor) { 12160 for (const SDUse &O : ChainNext->ops()) 12161 if (!Visited.count(O.getNode())) 12162 Queue.push_back(O.getNode()); 12163 } else 12164 LoadRoots.insert(ChainNext); 12165 } 12166 12167 // Second, search down the chain, starting from the top-level nodes recorded 12168 // in the first phase. These top-level nodes are the nodes just above all 12169 // loads and token factors. Starting with their uses, recursively look though 12170 // all loads (just the chain uses) and token factors to find a consecutive 12171 // load. 12172 Visited.clear(); 12173 Queue.clear(); 12174 12175 for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(), 12176 IE = LoadRoots.end(); I != IE; ++I) { 12177 Queue.push_back(*I); 12178 12179 while (!Queue.empty()) { 12180 SDNode *LoadRoot = Queue.pop_back_val(); 12181 if (!Visited.insert(LoadRoot).second) 12182 continue; 12183 12184 if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(LoadRoot)) 12185 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG)) 12186 return true; 12187 12188 for (SDNode::use_iterator UI = LoadRoot->use_begin(), 12189 UE = LoadRoot->use_end(); UI != UE; ++UI) 12190 if (((isa<MemSDNode>(*UI) && 12191 cast<MemSDNode>(*UI)->getChain().getNode() == LoadRoot) || 12192 UI->getOpcode() == ISD::TokenFactor) && !Visited.count(*UI)) 12193 Queue.push_back(*UI); 12194 } 12195 } 12196 12197 return false; 12198 } 12199 12200 /// This function is called when we have proved that a SETCC node can be replaced 12201 /// by subtraction (and other supporting instructions) so that the result of 12202 /// comparison is kept in a GPR instead of CR. This function is purely for 12203 /// codegen purposes and has some flags to guide the codegen process. 12204 static SDValue generateEquivalentSub(SDNode *N, int Size, bool Complement, 12205 bool Swap, SDLoc &DL, SelectionDAG &DAG) { 12206 assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected."); 12207 12208 // Zero extend the operands to the largest legal integer. Originally, they 12209 // must be of a strictly smaller size. 12210 auto Op0 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(0), 12211 DAG.getConstant(Size, DL, MVT::i32)); 12212 auto Op1 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1), 12213 DAG.getConstant(Size, DL, MVT::i32)); 12214 12215 // Swap if needed. Depends on the condition code. 12216 if (Swap) 12217 std::swap(Op0, Op1); 12218 12219 // Subtract extended integers. 12220 auto SubNode = DAG.getNode(ISD::SUB, DL, MVT::i64, Op0, Op1); 12221 12222 // Move the sign bit to the least significant position and zero out the rest. 12223 // Now the least significant bit carries the result of original comparison. 12224 auto Shifted = DAG.getNode(ISD::SRL, DL, MVT::i64, SubNode, 12225 DAG.getConstant(Size - 1, DL, MVT::i32)); 12226 auto Final = Shifted; 12227 12228 // Complement the result if needed. Based on the condition code. 12229 if (Complement) 12230 Final = DAG.getNode(ISD::XOR, DL, MVT::i64, Shifted, 12231 DAG.getConstant(1, DL, MVT::i64)); 12232 12233 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Final); 12234 } 12235 12236 SDValue PPCTargetLowering::ConvertSETCCToSubtract(SDNode *N, 12237 DAGCombinerInfo &DCI) const { 12238 assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected."); 12239 12240 SelectionDAG &DAG = DCI.DAG; 12241 SDLoc DL(N); 12242 12243 // Size of integers being compared has a critical role in the following 12244 // analysis, so we prefer to do this when all types are legal. 12245 if (!DCI.isAfterLegalizeDAG()) 12246 return SDValue(); 12247 12248 // If all users of SETCC extend its value to a legal integer type 12249 // then we replace SETCC with a subtraction 12250 for (SDNode::use_iterator UI = N->use_begin(), 12251 UE = N->use_end(); UI != UE; ++UI) { 12252 if (UI->getOpcode() != ISD::ZERO_EXTEND) 12253 return SDValue(); 12254 } 12255 12256 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 12257 auto OpSize = N->getOperand(0).getValueSizeInBits(); 12258 12259 unsigned Size = DAG.getDataLayout().getLargestLegalIntTypeSizeInBits(); 12260 12261 if (OpSize < Size) { 12262 switch (CC) { 12263 default: break; 12264 case ISD::SETULT: 12265 return generateEquivalentSub(N, Size, false, false, DL, DAG); 12266 case ISD::SETULE: 12267 return generateEquivalentSub(N, Size, true, true, DL, DAG); 12268 case ISD::SETUGT: 12269 return generateEquivalentSub(N, Size, false, true, DL, DAG); 12270 case ISD::SETUGE: 12271 return generateEquivalentSub(N, Size, true, false, DL, DAG); 12272 } 12273 } 12274 12275 return SDValue(); 12276 } 12277 12278 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N, 12279 DAGCombinerInfo &DCI) const { 12280 SelectionDAG &DAG = DCI.DAG; 12281 SDLoc dl(N); 12282 12283 assert(Subtarget.useCRBits() && "Expecting to be tracking CR bits"); 12284 // If we're tracking CR bits, we need to be careful that we don't have: 12285 // trunc(binary-ops(zext(x), zext(y))) 12286 // or 12287 // trunc(binary-ops(binary-ops(zext(x), zext(y)), ...) 12288 // such that we're unnecessarily moving things into GPRs when it would be 12289 // better to keep them in CR bits. 12290 12291 // Note that trunc here can be an actual i1 trunc, or can be the effective 12292 // truncation that comes from a setcc or select_cc. 12293 if (N->getOpcode() == ISD::TRUNCATE && 12294 N->getValueType(0) != MVT::i1) 12295 return SDValue(); 12296 12297 if (N->getOperand(0).getValueType() != MVT::i32 && 12298 N->getOperand(0).getValueType() != MVT::i64) 12299 return SDValue(); 12300 12301 if (N->getOpcode() == ISD::SETCC || 12302 N->getOpcode() == ISD::SELECT_CC) { 12303 // If we're looking at a comparison, then we need to make sure that the 12304 // high bits (all except for the first) don't matter the result. 12305 ISD::CondCode CC = 12306 cast<CondCodeSDNode>(N->getOperand( 12307 N->getOpcode() == ISD::SETCC ? 2 : 4))->get(); 12308 unsigned OpBits = N->getOperand(0).getValueSizeInBits(); 12309 12310 if (ISD::isSignedIntSetCC(CC)) { 12311 if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits || 12312 DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits) 12313 return SDValue(); 12314 } else if (ISD::isUnsignedIntSetCC(CC)) { 12315 if (!DAG.MaskedValueIsZero(N->getOperand(0), 12316 APInt::getHighBitsSet(OpBits, OpBits-1)) || 12317 !DAG.MaskedValueIsZero(N->getOperand(1), 12318 APInt::getHighBitsSet(OpBits, OpBits-1))) 12319 return (N->getOpcode() == ISD::SETCC ? ConvertSETCCToSubtract(N, DCI) 12320 : SDValue()); 12321 } else { 12322 // This is neither a signed nor an unsigned comparison, just make sure 12323 // that the high bits are equal. 12324 KnownBits Op1Known = DAG.computeKnownBits(N->getOperand(0)); 12325 KnownBits Op2Known = DAG.computeKnownBits(N->getOperand(1)); 12326 12327 // We don't really care about what is known about the first bit (if 12328 // anything), so clear it in all masks prior to comparing them. 12329 Op1Known.Zero.clearBit(0); Op1Known.One.clearBit(0); 12330 Op2Known.Zero.clearBit(0); Op2Known.One.clearBit(0); 12331 12332 if (Op1Known.Zero != Op2Known.Zero || Op1Known.One != Op2Known.One) 12333 return SDValue(); 12334 } 12335 } 12336 12337 // We now know that the higher-order bits are irrelevant, we just need to 12338 // make sure that all of the intermediate operations are bit operations, and 12339 // all inputs are extensions. 12340 if (N->getOperand(0).getOpcode() != ISD::AND && 12341 N->getOperand(0).getOpcode() != ISD::OR && 12342 N->getOperand(0).getOpcode() != ISD::XOR && 12343 N->getOperand(0).getOpcode() != ISD::SELECT && 12344 N->getOperand(0).getOpcode() != ISD::SELECT_CC && 12345 N->getOperand(0).getOpcode() != ISD::TRUNCATE && 12346 N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND && 12347 N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND && 12348 N->getOperand(0).getOpcode() != ISD::ANY_EXTEND) 12349 return SDValue(); 12350 12351 if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) && 12352 N->getOperand(1).getOpcode() != ISD::AND && 12353 N->getOperand(1).getOpcode() != ISD::OR && 12354 N->getOperand(1).getOpcode() != ISD::XOR && 12355 N->getOperand(1).getOpcode() != ISD::SELECT && 12356 N->getOperand(1).getOpcode() != ISD::SELECT_CC && 12357 N->getOperand(1).getOpcode() != ISD::TRUNCATE && 12358 N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND && 12359 N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND && 12360 N->getOperand(1).getOpcode() != ISD::ANY_EXTEND) 12361 return SDValue(); 12362 12363 SmallVector<SDValue, 4> Inputs; 12364 SmallVector<SDValue, 8> BinOps, PromOps; 12365 SmallPtrSet<SDNode *, 16> Visited; 12366 12367 for (unsigned i = 0; i < 2; ++i) { 12368 if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND || 12369 N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND || 12370 N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) && 12371 N->getOperand(i).getOperand(0).getValueType() == MVT::i1) || 12372 isa<ConstantSDNode>(N->getOperand(i))) 12373 Inputs.push_back(N->getOperand(i)); 12374 else 12375 BinOps.push_back(N->getOperand(i)); 12376 12377 if (N->getOpcode() == ISD::TRUNCATE) 12378 break; 12379 } 12380 12381 // Visit all inputs, collect all binary operations (and, or, xor and 12382 // select) that are all fed by extensions. 12383 while (!BinOps.empty()) { 12384 SDValue BinOp = BinOps.back(); 12385 BinOps.pop_back(); 12386 12387 if (!Visited.insert(BinOp.getNode()).second) 12388 continue; 12389 12390 PromOps.push_back(BinOp); 12391 12392 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) { 12393 // The condition of the select is not promoted. 12394 if (BinOp.getOpcode() == ISD::SELECT && i == 0) 12395 continue; 12396 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3) 12397 continue; 12398 12399 if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND || 12400 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND || 12401 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) && 12402 BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) || 12403 isa<ConstantSDNode>(BinOp.getOperand(i))) { 12404 Inputs.push_back(BinOp.getOperand(i)); 12405 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND || 12406 BinOp.getOperand(i).getOpcode() == ISD::OR || 12407 BinOp.getOperand(i).getOpcode() == ISD::XOR || 12408 BinOp.getOperand(i).getOpcode() == ISD::SELECT || 12409 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC || 12410 BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE || 12411 BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND || 12412 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND || 12413 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) { 12414 BinOps.push_back(BinOp.getOperand(i)); 12415 } else { 12416 // We have an input that is not an extension or another binary 12417 // operation; we'll abort this transformation. 12418 return SDValue(); 12419 } 12420 } 12421 } 12422 12423 // Make sure that this is a self-contained cluster of operations (which 12424 // is not quite the same thing as saying that everything has only one 12425 // use). 12426 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 12427 if (isa<ConstantSDNode>(Inputs[i])) 12428 continue; 12429 12430 for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(), 12431 UE = Inputs[i].getNode()->use_end(); 12432 UI != UE; ++UI) { 12433 SDNode *User = *UI; 12434 if (User != N && !Visited.count(User)) 12435 return SDValue(); 12436 12437 // Make sure that we're not going to promote the non-output-value 12438 // operand(s) or SELECT or SELECT_CC. 12439 // FIXME: Although we could sometimes handle this, and it does occur in 12440 // practice that one of the condition inputs to the select is also one of 12441 // the outputs, we currently can't deal with this. 12442 if (User->getOpcode() == ISD::SELECT) { 12443 if (User->getOperand(0) == Inputs[i]) 12444 return SDValue(); 12445 } else if (User->getOpcode() == ISD::SELECT_CC) { 12446 if (User->getOperand(0) == Inputs[i] || 12447 User->getOperand(1) == Inputs[i]) 12448 return SDValue(); 12449 } 12450 } 12451 } 12452 12453 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) { 12454 for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(), 12455 UE = PromOps[i].getNode()->use_end(); 12456 UI != UE; ++UI) { 12457 SDNode *User = *UI; 12458 if (User != N && !Visited.count(User)) 12459 return SDValue(); 12460 12461 // Make sure that we're not going to promote the non-output-value 12462 // operand(s) or SELECT or SELECT_CC. 12463 // FIXME: Although we could sometimes handle this, and it does occur in 12464 // practice that one of the condition inputs to the select is also one of 12465 // the outputs, we currently can't deal with this. 12466 if (User->getOpcode() == ISD::SELECT) { 12467 if (User->getOperand(0) == PromOps[i]) 12468 return SDValue(); 12469 } else if (User->getOpcode() == ISD::SELECT_CC) { 12470 if (User->getOperand(0) == PromOps[i] || 12471 User->getOperand(1) == PromOps[i]) 12472 return SDValue(); 12473 } 12474 } 12475 } 12476 12477 // Replace all inputs with the extension operand. 12478 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 12479 // Constants may have users outside the cluster of to-be-promoted nodes, 12480 // and so we need to replace those as we do the promotions. 12481 if (isa<ConstantSDNode>(Inputs[i])) 12482 continue; 12483 else 12484 DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0)); 12485 } 12486 12487 std::list<HandleSDNode> PromOpHandles; 12488 for (auto &PromOp : PromOps) 12489 PromOpHandles.emplace_back(PromOp); 12490 12491 // Replace all operations (these are all the same, but have a different 12492 // (i1) return type). DAG.getNode will validate that the types of 12493 // a binary operator match, so go through the list in reverse so that 12494 // we've likely promoted both operands first. Any intermediate truncations or 12495 // extensions disappear. 12496 while (!PromOpHandles.empty()) { 12497 SDValue PromOp = PromOpHandles.back().getValue(); 12498 PromOpHandles.pop_back(); 12499 12500 if (PromOp.getOpcode() == ISD::TRUNCATE || 12501 PromOp.getOpcode() == ISD::SIGN_EXTEND || 12502 PromOp.getOpcode() == ISD::ZERO_EXTEND || 12503 PromOp.getOpcode() == ISD::ANY_EXTEND) { 12504 if (!isa<ConstantSDNode>(PromOp.getOperand(0)) && 12505 PromOp.getOperand(0).getValueType() != MVT::i1) { 12506 // The operand is not yet ready (see comment below). 12507 PromOpHandles.emplace_front(PromOp); 12508 continue; 12509 } 12510 12511 SDValue RepValue = PromOp.getOperand(0); 12512 if (isa<ConstantSDNode>(RepValue)) 12513 RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue); 12514 12515 DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue); 12516 continue; 12517 } 12518 12519 unsigned C; 12520 switch (PromOp.getOpcode()) { 12521 default: C = 0; break; 12522 case ISD::SELECT: C = 1; break; 12523 case ISD::SELECT_CC: C = 2; break; 12524 } 12525 12526 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) && 12527 PromOp.getOperand(C).getValueType() != MVT::i1) || 12528 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) && 12529 PromOp.getOperand(C+1).getValueType() != MVT::i1)) { 12530 // The to-be-promoted operands of this node have not yet been 12531 // promoted (this should be rare because we're going through the 12532 // list backward, but if one of the operands has several users in 12533 // this cluster of to-be-promoted nodes, it is possible). 12534 PromOpHandles.emplace_front(PromOp); 12535 continue; 12536 } 12537 12538 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(), 12539 PromOp.getNode()->op_end()); 12540 12541 // If there are any constant inputs, make sure they're replaced now. 12542 for (unsigned i = 0; i < 2; ++i) 12543 if (isa<ConstantSDNode>(Ops[C+i])) 12544 Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]); 12545 12546 DAG.ReplaceAllUsesOfValueWith(PromOp, 12547 DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops)); 12548 } 12549 12550 // Now we're left with the initial truncation itself. 12551 if (N->getOpcode() == ISD::TRUNCATE) 12552 return N->getOperand(0); 12553 12554 // Otherwise, this is a comparison. The operands to be compared have just 12555 // changed type (to i1), but everything else is the same. 12556 return SDValue(N, 0); 12557 } 12558 12559 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N, 12560 DAGCombinerInfo &DCI) const { 12561 SelectionDAG &DAG = DCI.DAG; 12562 SDLoc dl(N); 12563 12564 // If we're tracking CR bits, we need to be careful that we don't have: 12565 // zext(binary-ops(trunc(x), trunc(y))) 12566 // or 12567 // zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...) 12568 // such that we're unnecessarily moving things into CR bits that can more 12569 // efficiently stay in GPRs. Note that if we're not certain that the high 12570 // bits are set as required by the final extension, we still may need to do 12571 // some masking to get the proper behavior. 12572 12573 // This same functionality is important on PPC64 when dealing with 12574 // 32-to-64-bit extensions; these occur often when 32-bit values are used as 12575 // the return values of functions. Because it is so similar, it is handled 12576 // here as well. 12577 12578 if (N->getValueType(0) != MVT::i32 && 12579 N->getValueType(0) != MVT::i64) 12580 return SDValue(); 12581 12582 if (!((N->getOperand(0).getValueType() == MVT::i1 && Subtarget.useCRBits()) || 12583 (N->getOperand(0).getValueType() == MVT::i32 && Subtarget.isPPC64()))) 12584 return SDValue(); 12585 12586 if (N->getOperand(0).getOpcode() != ISD::AND && 12587 N->getOperand(0).getOpcode() != ISD::OR && 12588 N->getOperand(0).getOpcode() != ISD::XOR && 12589 N->getOperand(0).getOpcode() != ISD::SELECT && 12590 N->getOperand(0).getOpcode() != ISD::SELECT_CC) 12591 return SDValue(); 12592 12593 SmallVector<SDValue, 4> Inputs; 12594 SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps; 12595 SmallPtrSet<SDNode *, 16> Visited; 12596 12597 // Visit all inputs, collect all binary operations (and, or, xor and 12598 // select) that are all fed by truncations. 12599 while (!BinOps.empty()) { 12600 SDValue BinOp = BinOps.back(); 12601 BinOps.pop_back(); 12602 12603 if (!Visited.insert(BinOp.getNode()).second) 12604 continue; 12605 12606 PromOps.push_back(BinOp); 12607 12608 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) { 12609 // The condition of the select is not promoted. 12610 if (BinOp.getOpcode() == ISD::SELECT && i == 0) 12611 continue; 12612 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3) 12613 continue; 12614 12615 if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE || 12616 isa<ConstantSDNode>(BinOp.getOperand(i))) { 12617 Inputs.push_back(BinOp.getOperand(i)); 12618 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND || 12619 BinOp.getOperand(i).getOpcode() == ISD::OR || 12620 BinOp.getOperand(i).getOpcode() == ISD::XOR || 12621 BinOp.getOperand(i).getOpcode() == ISD::SELECT || 12622 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) { 12623 BinOps.push_back(BinOp.getOperand(i)); 12624 } else { 12625 // We have an input that is not a truncation or another binary 12626 // operation; we'll abort this transformation. 12627 return SDValue(); 12628 } 12629 } 12630 } 12631 12632 // The operands of a select that must be truncated when the select is 12633 // promoted because the operand is actually part of the to-be-promoted set. 12634 DenseMap<SDNode *, EVT> SelectTruncOp[2]; 12635 12636 // Make sure that this is a self-contained cluster of operations (which 12637 // is not quite the same thing as saying that everything has only one 12638 // use). 12639 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 12640 if (isa<ConstantSDNode>(Inputs[i])) 12641 continue; 12642 12643 for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(), 12644 UE = Inputs[i].getNode()->use_end(); 12645 UI != UE; ++UI) { 12646 SDNode *User = *UI; 12647 if (User != N && !Visited.count(User)) 12648 return SDValue(); 12649 12650 // If we're going to promote the non-output-value operand(s) or SELECT or 12651 // SELECT_CC, record them for truncation. 12652 if (User->getOpcode() == ISD::SELECT) { 12653 if (User->getOperand(0) == Inputs[i]) 12654 SelectTruncOp[0].insert(std::make_pair(User, 12655 User->getOperand(0).getValueType())); 12656 } else if (User->getOpcode() == ISD::SELECT_CC) { 12657 if (User->getOperand(0) == Inputs[i]) 12658 SelectTruncOp[0].insert(std::make_pair(User, 12659 User->getOperand(0).getValueType())); 12660 if (User->getOperand(1) == Inputs[i]) 12661 SelectTruncOp[1].insert(std::make_pair(User, 12662 User->getOperand(1).getValueType())); 12663 } 12664 } 12665 } 12666 12667 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) { 12668 for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(), 12669 UE = PromOps[i].getNode()->use_end(); 12670 UI != UE; ++UI) { 12671 SDNode *User = *UI; 12672 if (User != N && !Visited.count(User)) 12673 return SDValue(); 12674 12675 // If we're going to promote the non-output-value operand(s) or SELECT or 12676 // SELECT_CC, record them for truncation. 12677 if (User->getOpcode() == ISD::SELECT) { 12678 if (User->getOperand(0) == PromOps[i]) 12679 SelectTruncOp[0].insert(std::make_pair(User, 12680 User->getOperand(0).getValueType())); 12681 } else if (User->getOpcode() == ISD::SELECT_CC) { 12682 if (User->getOperand(0) == PromOps[i]) 12683 SelectTruncOp[0].insert(std::make_pair(User, 12684 User->getOperand(0).getValueType())); 12685 if (User->getOperand(1) == PromOps[i]) 12686 SelectTruncOp[1].insert(std::make_pair(User, 12687 User->getOperand(1).getValueType())); 12688 } 12689 } 12690 } 12691 12692 unsigned PromBits = N->getOperand(0).getValueSizeInBits(); 12693 bool ReallyNeedsExt = false; 12694 if (N->getOpcode() != ISD::ANY_EXTEND) { 12695 // If all of the inputs are not already sign/zero extended, then 12696 // we'll still need to do that at the end. 12697 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 12698 if (isa<ConstantSDNode>(Inputs[i])) 12699 continue; 12700 12701 unsigned OpBits = 12702 Inputs[i].getOperand(0).getValueSizeInBits(); 12703 assert(PromBits < OpBits && "Truncation not to a smaller bit count?"); 12704 12705 if ((N->getOpcode() == ISD::ZERO_EXTEND && 12706 !DAG.MaskedValueIsZero(Inputs[i].getOperand(0), 12707 APInt::getHighBitsSet(OpBits, 12708 OpBits-PromBits))) || 12709 (N->getOpcode() == ISD::SIGN_EXTEND && 12710 DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) < 12711 (OpBits-(PromBits-1)))) { 12712 ReallyNeedsExt = true; 12713 break; 12714 } 12715 } 12716 } 12717 12718 // Replace all inputs, either with the truncation operand, or a 12719 // truncation or extension to the final output type. 12720 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 12721 // Constant inputs need to be replaced with the to-be-promoted nodes that 12722 // use them because they might have users outside of the cluster of 12723 // promoted nodes. 12724 if (isa<ConstantSDNode>(Inputs[i])) 12725 continue; 12726 12727 SDValue InSrc = Inputs[i].getOperand(0); 12728 if (Inputs[i].getValueType() == N->getValueType(0)) 12729 DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc); 12730 else if (N->getOpcode() == ISD::SIGN_EXTEND) 12731 DAG.ReplaceAllUsesOfValueWith(Inputs[i], 12732 DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0))); 12733 else if (N->getOpcode() == ISD::ZERO_EXTEND) 12734 DAG.ReplaceAllUsesOfValueWith(Inputs[i], 12735 DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0))); 12736 else 12737 DAG.ReplaceAllUsesOfValueWith(Inputs[i], 12738 DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0))); 12739 } 12740 12741 std::list<HandleSDNode> PromOpHandles; 12742 for (auto &PromOp : PromOps) 12743 PromOpHandles.emplace_back(PromOp); 12744 12745 // Replace all operations (these are all the same, but have a different 12746 // (promoted) return type). DAG.getNode will validate that the types of 12747 // a binary operator match, so go through the list in reverse so that 12748 // we've likely promoted both operands first. 12749 while (!PromOpHandles.empty()) { 12750 SDValue PromOp = PromOpHandles.back().getValue(); 12751 PromOpHandles.pop_back(); 12752 12753 unsigned C; 12754 switch (PromOp.getOpcode()) { 12755 default: C = 0; break; 12756 case ISD::SELECT: C = 1; break; 12757 case ISD::SELECT_CC: C = 2; break; 12758 } 12759 12760 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) && 12761 PromOp.getOperand(C).getValueType() != N->getValueType(0)) || 12762 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) && 12763 PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) { 12764 // The to-be-promoted operands of this node have not yet been 12765 // promoted (this should be rare because we're going through the 12766 // list backward, but if one of the operands has several users in 12767 // this cluster of to-be-promoted nodes, it is possible). 12768 PromOpHandles.emplace_front(PromOp); 12769 continue; 12770 } 12771 12772 // For SELECT and SELECT_CC nodes, we do a similar check for any 12773 // to-be-promoted comparison inputs. 12774 if (PromOp.getOpcode() == ISD::SELECT || 12775 PromOp.getOpcode() == ISD::SELECT_CC) { 12776 if ((SelectTruncOp[0].count(PromOp.getNode()) && 12777 PromOp.getOperand(0).getValueType() != N->getValueType(0)) || 12778 (SelectTruncOp[1].count(PromOp.getNode()) && 12779 PromOp.getOperand(1).getValueType() != N->getValueType(0))) { 12780 PromOpHandles.emplace_front(PromOp); 12781 continue; 12782 } 12783 } 12784 12785 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(), 12786 PromOp.getNode()->op_end()); 12787 12788 // If this node has constant inputs, then they'll need to be promoted here. 12789 for (unsigned i = 0; i < 2; ++i) { 12790 if (!isa<ConstantSDNode>(Ops[C+i])) 12791 continue; 12792 if (Ops[C+i].getValueType() == N->getValueType(0)) 12793 continue; 12794 12795 if (N->getOpcode() == ISD::SIGN_EXTEND) 12796 Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); 12797 else if (N->getOpcode() == ISD::ZERO_EXTEND) 12798 Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); 12799 else 12800 Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); 12801 } 12802 12803 // If we've promoted the comparison inputs of a SELECT or SELECT_CC, 12804 // truncate them again to the original value type. 12805 if (PromOp.getOpcode() == ISD::SELECT || 12806 PromOp.getOpcode() == ISD::SELECT_CC) { 12807 auto SI0 = SelectTruncOp[0].find(PromOp.getNode()); 12808 if (SI0 != SelectTruncOp[0].end()) 12809 Ops[0] = DAG.getNode(ISD::TRUNCATE, dl, SI0->second, Ops[0]); 12810 auto SI1 = SelectTruncOp[1].find(PromOp.getNode()); 12811 if (SI1 != SelectTruncOp[1].end()) 12812 Ops[1] = DAG.getNode(ISD::TRUNCATE, dl, SI1->second, Ops[1]); 12813 } 12814 12815 DAG.ReplaceAllUsesOfValueWith(PromOp, 12816 DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops)); 12817 } 12818 12819 // Now we're left with the initial extension itself. 12820 if (!ReallyNeedsExt) 12821 return N->getOperand(0); 12822 12823 // To zero extend, just mask off everything except for the first bit (in the 12824 // i1 case). 12825 if (N->getOpcode() == ISD::ZERO_EXTEND) 12826 return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0), 12827 DAG.getConstant(APInt::getLowBitsSet( 12828 N->getValueSizeInBits(0), PromBits), 12829 dl, N->getValueType(0))); 12830 12831 assert(N->getOpcode() == ISD::SIGN_EXTEND && 12832 "Invalid extension type"); 12833 EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0), DAG.getDataLayout()); 12834 SDValue ShiftCst = 12835 DAG.getConstant(N->getValueSizeInBits(0) - PromBits, dl, ShiftAmountTy); 12836 return DAG.getNode( 12837 ISD::SRA, dl, N->getValueType(0), 12838 DAG.getNode(ISD::SHL, dl, N->getValueType(0), N->getOperand(0), ShiftCst), 12839 ShiftCst); 12840 } 12841 12842 SDValue PPCTargetLowering::combineSetCC(SDNode *N, 12843 DAGCombinerInfo &DCI) const { 12844 assert(N->getOpcode() == ISD::SETCC && 12845 "Should be called with a SETCC node"); 12846 12847 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 12848 if (CC == ISD::SETNE || CC == ISD::SETEQ) { 12849 SDValue LHS = N->getOperand(0); 12850 SDValue RHS = N->getOperand(1); 12851 12852 // If there is a '0 - y' pattern, canonicalize the pattern to the RHS. 12853 if (LHS.getOpcode() == ISD::SUB && isNullConstant(LHS.getOperand(0)) && 12854 LHS.hasOneUse()) 12855 std::swap(LHS, RHS); 12856 12857 // x == 0-y --> x+y == 0 12858 // x != 0-y --> x+y != 0 12859 if (RHS.getOpcode() == ISD::SUB && isNullConstant(RHS.getOperand(0)) && 12860 RHS.hasOneUse()) { 12861 SDLoc DL(N); 12862 SelectionDAG &DAG = DCI.DAG; 12863 EVT VT = N->getValueType(0); 12864 EVT OpVT = LHS.getValueType(); 12865 SDValue Add = DAG.getNode(ISD::ADD, DL, OpVT, LHS, RHS.getOperand(1)); 12866 return DAG.getSetCC(DL, VT, Add, DAG.getConstant(0, DL, OpVT), CC); 12867 } 12868 } 12869 12870 return DAGCombineTruncBoolExt(N, DCI); 12871 } 12872 12873 // Is this an extending load from an f32 to an f64? 12874 static bool isFPExtLoad(SDValue Op) { 12875 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op.getNode())) 12876 return LD->getExtensionType() == ISD::EXTLOAD && 12877 Op.getValueType() == MVT::f64; 12878 return false; 12879 } 12880 12881 /// Reduces the number of fp-to-int conversion when building a vector. 12882 /// 12883 /// If this vector is built out of floating to integer conversions, 12884 /// transform it to a vector built out of floating point values followed by a 12885 /// single floating to integer conversion of the vector. 12886 /// Namely (build_vector (fptosi $A), (fptosi $B), ...) 12887 /// becomes (fptosi (build_vector ($A, $B, ...))) 12888 SDValue PPCTargetLowering:: 12889 combineElementTruncationToVectorTruncation(SDNode *N, 12890 DAGCombinerInfo &DCI) const { 12891 assert(N->getOpcode() == ISD::BUILD_VECTOR && 12892 "Should be called with a BUILD_VECTOR node"); 12893 12894 SelectionDAG &DAG = DCI.DAG; 12895 SDLoc dl(N); 12896 12897 SDValue FirstInput = N->getOperand(0); 12898 assert(FirstInput.getOpcode() == PPCISD::MFVSR && 12899 "The input operand must be an fp-to-int conversion."); 12900 12901 // This combine happens after legalization so the fp_to_[su]i nodes are 12902 // already converted to PPCSISD nodes. 12903 unsigned FirstConversion = FirstInput.getOperand(0).getOpcode(); 12904 if (FirstConversion == PPCISD::FCTIDZ || 12905 FirstConversion == PPCISD::FCTIDUZ || 12906 FirstConversion == PPCISD::FCTIWZ || 12907 FirstConversion == PPCISD::FCTIWUZ) { 12908 bool IsSplat = true; 12909 bool Is32Bit = FirstConversion == PPCISD::FCTIWZ || 12910 FirstConversion == PPCISD::FCTIWUZ; 12911 EVT SrcVT = FirstInput.getOperand(0).getValueType(); 12912 SmallVector<SDValue, 4> Ops; 12913 EVT TargetVT = N->getValueType(0); 12914 for (int i = 0, e = N->getNumOperands(); i < e; ++i) { 12915 SDValue NextOp = N->getOperand(i); 12916 if (NextOp.getOpcode() != PPCISD::MFVSR) 12917 return SDValue(); 12918 unsigned NextConversion = NextOp.getOperand(0).getOpcode(); 12919 if (NextConversion != FirstConversion) 12920 return SDValue(); 12921 // If we are converting to 32-bit integers, we need to add an FP_ROUND. 12922 // This is not valid if the input was originally double precision. It is 12923 // also not profitable to do unless this is an extending load in which 12924 // case doing this combine will allow us to combine consecutive loads. 12925 if (Is32Bit && !isFPExtLoad(NextOp.getOperand(0).getOperand(0))) 12926 return SDValue(); 12927 if (N->getOperand(i) != FirstInput) 12928 IsSplat = false; 12929 } 12930 12931 // If this is a splat, we leave it as-is since there will be only a single 12932 // fp-to-int conversion followed by a splat of the integer. This is better 12933 // for 32-bit and smaller ints and neutral for 64-bit ints. 12934 if (IsSplat) 12935 return SDValue(); 12936 12937 // Now that we know we have the right type of node, get its operands 12938 for (int i = 0, e = N->getNumOperands(); i < e; ++i) { 12939 SDValue In = N->getOperand(i).getOperand(0); 12940 if (Is32Bit) { 12941 // For 32-bit values, we need to add an FP_ROUND node (if we made it 12942 // here, we know that all inputs are extending loads so this is safe). 12943 if (In.isUndef()) 12944 Ops.push_back(DAG.getUNDEF(SrcVT)); 12945 else { 12946 SDValue Trunc = DAG.getNode(ISD::FP_ROUND, dl, 12947 MVT::f32, In.getOperand(0), 12948 DAG.getIntPtrConstant(1, dl)); 12949 Ops.push_back(Trunc); 12950 } 12951 } else 12952 Ops.push_back(In.isUndef() ? DAG.getUNDEF(SrcVT) : In.getOperand(0)); 12953 } 12954 12955 unsigned Opcode; 12956 if (FirstConversion == PPCISD::FCTIDZ || 12957 FirstConversion == PPCISD::FCTIWZ) 12958 Opcode = ISD::FP_TO_SINT; 12959 else 12960 Opcode = ISD::FP_TO_UINT; 12961 12962 EVT NewVT = TargetVT == MVT::v2i64 ? MVT::v2f64 : MVT::v4f32; 12963 SDValue BV = DAG.getBuildVector(NewVT, dl, Ops); 12964 return DAG.getNode(Opcode, dl, TargetVT, BV); 12965 } 12966 return SDValue(); 12967 } 12968 12969 /// Reduce the number of loads when building a vector. 12970 /// 12971 /// Building a vector out of multiple loads can be converted to a load 12972 /// of the vector type if the loads are consecutive. If the loads are 12973 /// consecutive but in descending order, a shuffle is added at the end 12974 /// to reorder the vector. 12975 static SDValue combineBVOfConsecutiveLoads(SDNode *N, SelectionDAG &DAG) { 12976 assert(N->getOpcode() == ISD::BUILD_VECTOR && 12977 "Should be called with a BUILD_VECTOR node"); 12978 12979 SDLoc dl(N); 12980 12981 // Return early for non byte-sized type, as they can't be consecutive. 12982 if (!N->getValueType(0).getVectorElementType().isByteSized()) 12983 return SDValue(); 12984 12985 bool InputsAreConsecutiveLoads = true; 12986 bool InputsAreReverseConsecutive = true; 12987 unsigned ElemSize = N->getValueType(0).getScalarType().getStoreSize(); 12988 SDValue FirstInput = N->getOperand(0); 12989 bool IsRoundOfExtLoad = false; 12990 12991 if (FirstInput.getOpcode() == ISD::FP_ROUND && 12992 FirstInput.getOperand(0).getOpcode() == ISD::LOAD) { 12993 LoadSDNode *LD = dyn_cast<LoadSDNode>(FirstInput.getOperand(0)); 12994 IsRoundOfExtLoad = LD->getExtensionType() == ISD::EXTLOAD; 12995 } 12996 // Not a build vector of (possibly fp_rounded) loads. 12997 if ((!IsRoundOfExtLoad && FirstInput.getOpcode() != ISD::LOAD) || 12998 N->getNumOperands() == 1) 12999 return SDValue(); 13000 13001 for (int i = 1, e = N->getNumOperands(); i < e; ++i) { 13002 // If any inputs are fp_round(extload), they all must be. 13003 if (IsRoundOfExtLoad && N->getOperand(i).getOpcode() != ISD::FP_ROUND) 13004 return SDValue(); 13005 13006 SDValue NextInput = IsRoundOfExtLoad ? N->getOperand(i).getOperand(0) : 13007 N->getOperand(i); 13008 if (NextInput.getOpcode() != ISD::LOAD) 13009 return SDValue(); 13010 13011 SDValue PreviousInput = 13012 IsRoundOfExtLoad ? N->getOperand(i-1).getOperand(0) : N->getOperand(i-1); 13013 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(PreviousInput); 13014 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(NextInput); 13015 13016 // If any inputs are fp_round(extload), they all must be. 13017 if (IsRoundOfExtLoad && LD2->getExtensionType() != ISD::EXTLOAD) 13018 return SDValue(); 13019 13020 if (!isConsecutiveLS(LD2, LD1, ElemSize, 1, DAG)) 13021 InputsAreConsecutiveLoads = false; 13022 if (!isConsecutiveLS(LD1, LD2, ElemSize, 1, DAG)) 13023 InputsAreReverseConsecutive = false; 13024 13025 // Exit early if the loads are neither consecutive nor reverse consecutive. 13026 if (!InputsAreConsecutiveLoads && !InputsAreReverseConsecutive) 13027 return SDValue(); 13028 } 13029 13030 assert(!(InputsAreConsecutiveLoads && InputsAreReverseConsecutive) && 13031 "The loads cannot be both consecutive and reverse consecutive."); 13032 13033 SDValue FirstLoadOp = 13034 IsRoundOfExtLoad ? FirstInput.getOperand(0) : FirstInput; 13035 SDValue LastLoadOp = 13036 IsRoundOfExtLoad ? N->getOperand(N->getNumOperands()-1).getOperand(0) : 13037 N->getOperand(N->getNumOperands()-1); 13038 13039 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(FirstLoadOp); 13040 LoadSDNode *LDL = dyn_cast<LoadSDNode>(LastLoadOp); 13041 if (InputsAreConsecutiveLoads) { 13042 assert(LD1 && "Input needs to be a LoadSDNode."); 13043 return DAG.getLoad(N->getValueType(0), dl, LD1->getChain(), 13044 LD1->getBasePtr(), LD1->getPointerInfo(), 13045 LD1->getAlignment()); 13046 } 13047 if (InputsAreReverseConsecutive) { 13048 assert(LDL && "Input needs to be a LoadSDNode."); 13049 SDValue Load = DAG.getLoad(N->getValueType(0), dl, LDL->getChain(), 13050 LDL->getBasePtr(), LDL->getPointerInfo(), 13051 LDL->getAlignment()); 13052 SmallVector<int, 16> Ops; 13053 for (int i = N->getNumOperands() - 1; i >= 0; i--) 13054 Ops.push_back(i); 13055 13056 return DAG.getVectorShuffle(N->getValueType(0), dl, Load, 13057 DAG.getUNDEF(N->getValueType(0)), Ops); 13058 } 13059 return SDValue(); 13060 } 13061 13062 // This function adds the required vector_shuffle needed to get 13063 // the elements of the vector extract in the correct position 13064 // as specified by the CorrectElems encoding. 13065 static SDValue addShuffleForVecExtend(SDNode *N, SelectionDAG &DAG, 13066 SDValue Input, uint64_t Elems, 13067 uint64_t CorrectElems) { 13068 SDLoc dl(N); 13069 13070 unsigned NumElems = Input.getValueType().getVectorNumElements(); 13071 SmallVector<int, 16> ShuffleMask(NumElems, -1); 13072 13073 // Knowing the element indices being extracted from the original 13074 // vector and the order in which they're being inserted, just put 13075 // them at element indices required for the instruction. 13076 for (unsigned i = 0; i < N->getNumOperands(); i++) { 13077 if (DAG.getDataLayout().isLittleEndian()) 13078 ShuffleMask[CorrectElems & 0xF] = Elems & 0xF; 13079 else 13080 ShuffleMask[(CorrectElems & 0xF0) >> 4] = (Elems & 0xF0) >> 4; 13081 CorrectElems = CorrectElems >> 8; 13082 Elems = Elems >> 8; 13083 } 13084 13085 SDValue Shuffle = 13086 DAG.getVectorShuffle(Input.getValueType(), dl, Input, 13087 DAG.getUNDEF(Input.getValueType()), ShuffleMask); 13088 13089 EVT Ty = N->getValueType(0); 13090 SDValue BV = DAG.getNode(PPCISD::SExtVElems, dl, Ty, Shuffle); 13091 return BV; 13092 } 13093 13094 // Look for build vector patterns where input operands come from sign 13095 // extended vector_extract elements of specific indices. If the correct indices 13096 // aren't used, add a vector shuffle to fix up the indices and create a new 13097 // PPCISD:SExtVElems node which selects the vector sign extend instructions 13098 // during instruction selection. 13099 static SDValue combineBVOfVecSExt(SDNode *N, SelectionDAG &DAG) { 13100 // This array encodes the indices that the vector sign extend instructions 13101 // extract from when extending from one type to another for both BE and LE. 13102 // The right nibble of each byte corresponds to the LE incides. 13103 // and the left nibble of each byte corresponds to the BE incides. 13104 // For example: 0x3074B8FC byte->word 13105 // For LE: the allowed indices are: 0x0,0x4,0x8,0xC 13106 // For BE: the allowed indices are: 0x3,0x7,0xB,0xF 13107 // For example: 0x000070F8 byte->double word 13108 // For LE: the allowed indices are: 0x0,0x8 13109 // For BE: the allowed indices are: 0x7,0xF 13110 uint64_t TargetElems[] = { 13111 0x3074B8FC, // b->w 13112 0x000070F8, // b->d 13113 0x10325476, // h->w 13114 0x00003074, // h->d 13115 0x00001032, // w->d 13116 }; 13117 13118 uint64_t Elems = 0; 13119 int Index; 13120 SDValue Input; 13121 13122 auto isSExtOfVecExtract = [&](SDValue Op) -> bool { 13123 if (!Op) 13124 return false; 13125 if (Op.getOpcode() != ISD::SIGN_EXTEND && 13126 Op.getOpcode() != ISD::SIGN_EXTEND_INREG) 13127 return false; 13128 13129 // A SIGN_EXTEND_INREG might be fed by an ANY_EXTEND to produce a value 13130 // of the right width. 13131 SDValue Extract = Op.getOperand(0); 13132 if (Extract.getOpcode() == ISD::ANY_EXTEND) 13133 Extract = Extract.getOperand(0); 13134 if (Extract.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 13135 return false; 13136 13137 ConstantSDNode *ExtOp = dyn_cast<ConstantSDNode>(Extract.getOperand(1)); 13138 if (!ExtOp) 13139 return false; 13140 13141 Index = ExtOp->getZExtValue(); 13142 if (Input && Input != Extract.getOperand(0)) 13143 return false; 13144 13145 if (!Input) 13146 Input = Extract.getOperand(0); 13147 13148 Elems = Elems << 8; 13149 Index = DAG.getDataLayout().isLittleEndian() ? Index : Index << 4; 13150 Elems |= Index; 13151 13152 return true; 13153 }; 13154 13155 // If the build vector operands aren't sign extended vector extracts, 13156 // of the same input vector, then return. 13157 for (unsigned i = 0; i < N->getNumOperands(); i++) { 13158 if (!isSExtOfVecExtract(N->getOperand(i))) { 13159 return SDValue(); 13160 } 13161 } 13162 13163 // If the vector extract indicies are not correct, add the appropriate 13164 // vector_shuffle. 13165 int TgtElemArrayIdx; 13166 int InputSize = Input.getValueType().getScalarSizeInBits(); 13167 int OutputSize = N->getValueType(0).getScalarSizeInBits(); 13168 if (InputSize + OutputSize == 40) 13169 TgtElemArrayIdx = 0; 13170 else if (InputSize + OutputSize == 72) 13171 TgtElemArrayIdx = 1; 13172 else if (InputSize + OutputSize == 48) 13173 TgtElemArrayIdx = 2; 13174 else if (InputSize + OutputSize == 80) 13175 TgtElemArrayIdx = 3; 13176 else if (InputSize + OutputSize == 96) 13177 TgtElemArrayIdx = 4; 13178 else 13179 return SDValue(); 13180 13181 uint64_t CorrectElems = TargetElems[TgtElemArrayIdx]; 13182 CorrectElems = DAG.getDataLayout().isLittleEndian() 13183 ? CorrectElems & 0x0F0F0F0F0F0F0F0F 13184 : CorrectElems & 0xF0F0F0F0F0F0F0F0; 13185 if (Elems != CorrectElems) { 13186 return addShuffleForVecExtend(N, DAG, Input, Elems, CorrectElems); 13187 } 13188 13189 // Regular lowering will catch cases where a shuffle is not needed. 13190 return SDValue(); 13191 } 13192 13193 SDValue PPCTargetLowering::DAGCombineBuildVector(SDNode *N, 13194 DAGCombinerInfo &DCI) const { 13195 assert(N->getOpcode() == ISD::BUILD_VECTOR && 13196 "Should be called with a BUILD_VECTOR node"); 13197 13198 SelectionDAG &DAG = DCI.DAG; 13199 SDLoc dl(N); 13200 13201 if (!Subtarget.hasVSX()) 13202 return SDValue(); 13203 13204 // The target independent DAG combiner will leave a build_vector of 13205 // float-to-int conversions intact. We can generate MUCH better code for 13206 // a float-to-int conversion of a vector of floats. 13207 SDValue FirstInput = N->getOperand(0); 13208 if (FirstInput.getOpcode() == PPCISD::MFVSR) { 13209 SDValue Reduced = combineElementTruncationToVectorTruncation(N, DCI); 13210 if (Reduced) 13211 return Reduced; 13212 } 13213 13214 // If we're building a vector out of consecutive loads, just load that 13215 // vector type. 13216 SDValue Reduced = combineBVOfConsecutiveLoads(N, DAG); 13217 if (Reduced) 13218 return Reduced; 13219 13220 // If we're building a vector out of extended elements from another vector 13221 // we have P9 vector integer extend instructions. The code assumes legal 13222 // input types (i.e. it can't handle things like v4i16) so do not run before 13223 // legalization. 13224 if (Subtarget.hasP9Altivec() && !DCI.isBeforeLegalize()) { 13225 Reduced = combineBVOfVecSExt(N, DAG); 13226 if (Reduced) 13227 return Reduced; 13228 } 13229 13230 13231 if (N->getValueType(0) != MVT::v2f64) 13232 return SDValue(); 13233 13234 // Looking for: 13235 // (build_vector ([su]int_to_fp (extractelt 0)), [su]int_to_fp (extractelt 1)) 13236 if (FirstInput.getOpcode() != ISD::SINT_TO_FP && 13237 FirstInput.getOpcode() != ISD::UINT_TO_FP) 13238 return SDValue(); 13239 if (N->getOperand(1).getOpcode() != ISD::SINT_TO_FP && 13240 N->getOperand(1).getOpcode() != ISD::UINT_TO_FP) 13241 return SDValue(); 13242 if (FirstInput.getOpcode() != N->getOperand(1).getOpcode()) 13243 return SDValue(); 13244 13245 SDValue Ext1 = FirstInput.getOperand(0); 13246 SDValue Ext2 = N->getOperand(1).getOperand(0); 13247 if(Ext1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 13248 Ext2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 13249 return SDValue(); 13250 13251 ConstantSDNode *Ext1Op = dyn_cast<ConstantSDNode>(Ext1.getOperand(1)); 13252 ConstantSDNode *Ext2Op = dyn_cast<ConstantSDNode>(Ext2.getOperand(1)); 13253 if (!Ext1Op || !Ext2Op) 13254 return SDValue(); 13255 if (Ext1.getOperand(0).getValueType() != MVT::v4i32 || 13256 Ext1.getOperand(0) != Ext2.getOperand(0)) 13257 return SDValue(); 13258 13259 int FirstElem = Ext1Op->getZExtValue(); 13260 int SecondElem = Ext2Op->getZExtValue(); 13261 int SubvecIdx; 13262 if (FirstElem == 0 && SecondElem == 1) 13263 SubvecIdx = Subtarget.isLittleEndian() ? 1 : 0; 13264 else if (FirstElem == 2 && SecondElem == 3) 13265 SubvecIdx = Subtarget.isLittleEndian() ? 0 : 1; 13266 else 13267 return SDValue(); 13268 13269 SDValue SrcVec = Ext1.getOperand(0); 13270 auto NodeType = (N->getOperand(1).getOpcode() == ISD::SINT_TO_FP) ? 13271 PPCISD::SINT_VEC_TO_FP : PPCISD::UINT_VEC_TO_FP; 13272 return DAG.getNode(NodeType, dl, MVT::v2f64, 13273 SrcVec, DAG.getIntPtrConstant(SubvecIdx, dl)); 13274 } 13275 13276 SDValue PPCTargetLowering::combineFPToIntToFP(SDNode *N, 13277 DAGCombinerInfo &DCI) const { 13278 assert((N->getOpcode() == ISD::SINT_TO_FP || 13279 N->getOpcode() == ISD::UINT_TO_FP) && 13280 "Need an int -> FP conversion node here"); 13281 13282 if (useSoftFloat() || !Subtarget.has64BitSupport()) 13283 return SDValue(); 13284 13285 SelectionDAG &DAG = DCI.DAG; 13286 SDLoc dl(N); 13287 SDValue Op(N, 0); 13288 13289 // Don't handle ppc_fp128 here or conversions that are out-of-range capable 13290 // from the hardware. 13291 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64) 13292 return SDValue(); 13293 if (Op.getOperand(0).getValueType().getSimpleVT() <= MVT(MVT::i1) || 13294 Op.getOperand(0).getValueType().getSimpleVT() > MVT(MVT::i64)) 13295 return SDValue(); 13296 13297 SDValue FirstOperand(Op.getOperand(0)); 13298 bool SubWordLoad = FirstOperand.getOpcode() == ISD::LOAD && 13299 (FirstOperand.getValueType() == MVT::i8 || 13300 FirstOperand.getValueType() == MVT::i16); 13301 if (Subtarget.hasP9Vector() && Subtarget.hasP9Altivec() && SubWordLoad) { 13302 bool Signed = N->getOpcode() == ISD::SINT_TO_FP; 13303 bool DstDouble = Op.getValueType() == MVT::f64; 13304 unsigned ConvOp = Signed ? 13305 (DstDouble ? PPCISD::FCFID : PPCISD::FCFIDS) : 13306 (DstDouble ? PPCISD::FCFIDU : PPCISD::FCFIDUS); 13307 SDValue WidthConst = 13308 DAG.getIntPtrConstant(FirstOperand.getValueType() == MVT::i8 ? 1 : 2, 13309 dl, false); 13310 LoadSDNode *LDN = cast<LoadSDNode>(FirstOperand.getNode()); 13311 SDValue Ops[] = { LDN->getChain(), LDN->getBasePtr(), WidthConst }; 13312 SDValue Ld = DAG.getMemIntrinsicNode(PPCISD::LXSIZX, dl, 13313 DAG.getVTList(MVT::f64, MVT::Other), 13314 Ops, MVT::i8, LDN->getMemOperand()); 13315 13316 // For signed conversion, we need to sign-extend the value in the VSR 13317 if (Signed) { 13318 SDValue ExtOps[] = { Ld, WidthConst }; 13319 SDValue Ext = DAG.getNode(PPCISD::VEXTS, dl, MVT::f64, ExtOps); 13320 return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ext); 13321 } else 13322 return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ld); 13323 } 13324 13325 13326 // For i32 intermediate values, unfortunately, the conversion functions 13327 // leave the upper 32 bits of the value are undefined. Within the set of 13328 // scalar instructions, we have no method for zero- or sign-extending the 13329 // value. Thus, we cannot handle i32 intermediate values here. 13330 if (Op.getOperand(0).getValueType() == MVT::i32) 13331 return SDValue(); 13332 13333 assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) && 13334 "UINT_TO_FP is supported only with FPCVT"); 13335 13336 // If we have FCFIDS, then use it when converting to single-precision. 13337 // Otherwise, convert to double-precision and then round. 13338 unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 13339 ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS 13340 : PPCISD::FCFIDS) 13341 : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU 13342 : PPCISD::FCFID); 13343 MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 13344 ? MVT::f32 13345 : MVT::f64; 13346 13347 // If we're converting from a float, to an int, and back to a float again, 13348 // then we don't need the store/load pair at all. 13349 if ((Op.getOperand(0).getOpcode() == ISD::FP_TO_UINT && 13350 Subtarget.hasFPCVT()) || 13351 (Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT)) { 13352 SDValue Src = Op.getOperand(0).getOperand(0); 13353 if (Src.getValueType() == MVT::f32) { 13354 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src); 13355 DCI.AddToWorklist(Src.getNode()); 13356 } else if (Src.getValueType() != MVT::f64) { 13357 // Make sure that we don't pick up a ppc_fp128 source value. 13358 return SDValue(); 13359 } 13360 13361 unsigned FCTOp = 13362 Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT ? PPCISD::FCTIDZ : 13363 PPCISD::FCTIDUZ; 13364 13365 SDValue Tmp = DAG.getNode(FCTOp, dl, MVT::f64, Src); 13366 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Tmp); 13367 13368 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) { 13369 FP = DAG.getNode(ISD::FP_ROUND, dl, 13370 MVT::f32, FP, DAG.getIntPtrConstant(0, dl)); 13371 DCI.AddToWorklist(FP.getNode()); 13372 } 13373 13374 return FP; 13375 } 13376 13377 return SDValue(); 13378 } 13379 13380 // expandVSXLoadForLE - Convert VSX loads (which may be intrinsics for 13381 // builtins) into loads with swaps. 13382 SDValue PPCTargetLowering::expandVSXLoadForLE(SDNode *N, 13383 DAGCombinerInfo &DCI) const { 13384 SelectionDAG &DAG = DCI.DAG; 13385 SDLoc dl(N); 13386 SDValue Chain; 13387 SDValue Base; 13388 MachineMemOperand *MMO; 13389 13390 switch (N->getOpcode()) { 13391 default: 13392 llvm_unreachable("Unexpected opcode for little endian VSX load"); 13393 case ISD::LOAD: { 13394 LoadSDNode *LD = cast<LoadSDNode>(N); 13395 Chain = LD->getChain(); 13396 Base = LD->getBasePtr(); 13397 MMO = LD->getMemOperand(); 13398 // If the MMO suggests this isn't a load of a full vector, leave 13399 // things alone. For a built-in, we have to make the change for 13400 // correctness, so if there is a size problem that will be a bug. 13401 if (MMO->getSize() < 16) 13402 return SDValue(); 13403 break; 13404 } 13405 case ISD::INTRINSIC_W_CHAIN: { 13406 MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N); 13407 Chain = Intrin->getChain(); 13408 // Similarly to the store case below, Intrin->getBasePtr() doesn't get 13409 // us what we want. Get operand 2 instead. 13410 Base = Intrin->getOperand(2); 13411 MMO = Intrin->getMemOperand(); 13412 break; 13413 } 13414 } 13415 13416 MVT VecTy = N->getValueType(0).getSimpleVT(); 13417 13418 // Do not expand to PPCISD::LXVD2X + PPCISD::XXSWAPD when the load is 13419 // aligned and the type is a vector with elements up to 4 bytes 13420 if (Subtarget.needsSwapsForVSXMemOps() && !(MMO->getAlignment()%16) 13421 && VecTy.getScalarSizeInBits() <= 32 ) { 13422 return SDValue(); 13423 } 13424 13425 SDValue LoadOps[] = { Chain, Base }; 13426 SDValue Load = DAG.getMemIntrinsicNode(PPCISD::LXVD2X, dl, 13427 DAG.getVTList(MVT::v2f64, MVT::Other), 13428 LoadOps, MVT::v2f64, MMO); 13429 13430 DCI.AddToWorklist(Load.getNode()); 13431 Chain = Load.getValue(1); 13432 SDValue Swap = DAG.getNode( 13433 PPCISD::XXSWAPD, dl, DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Load); 13434 DCI.AddToWorklist(Swap.getNode()); 13435 13436 // Add a bitcast if the resulting load type doesn't match v2f64. 13437 if (VecTy != MVT::v2f64) { 13438 SDValue N = DAG.getNode(ISD::BITCAST, dl, VecTy, Swap); 13439 DCI.AddToWorklist(N.getNode()); 13440 // Package {bitcast value, swap's chain} to match Load's shape. 13441 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VecTy, MVT::Other), 13442 N, Swap.getValue(1)); 13443 } 13444 13445 return Swap; 13446 } 13447 13448 // expandVSXStoreForLE - Convert VSX stores (which may be intrinsics for 13449 // builtins) into stores with swaps. 13450 SDValue PPCTargetLowering::expandVSXStoreForLE(SDNode *N, 13451 DAGCombinerInfo &DCI) const { 13452 SelectionDAG &DAG = DCI.DAG; 13453 SDLoc dl(N); 13454 SDValue Chain; 13455 SDValue Base; 13456 unsigned SrcOpnd; 13457 MachineMemOperand *MMO; 13458 13459 switch (N->getOpcode()) { 13460 default: 13461 llvm_unreachable("Unexpected opcode for little endian VSX store"); 13462 case ISD::STORE: { 13463 StoreSDNode *ST = cast<StoreSDNode>(N); 13464 Chain = ST->getChain(); 13465 Base = ST->getBasePtr(); 13466 MMO = ST->getMemOperand(); 13467 SrcOpnd = 1; 13468 // If the MMO suggests this isn't a store of a full vector, leave 13469 // things alone. For a built-in, we have to make the change for 13470 // correctness, so if there is a size problem that will be a bug. 13471 if (MMO->getSize() < 16) 13472 return SDValue(); 13473 break; 13474 } 13475 case ISD::INTRINSIC_VOID: { 13476 MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N); 13477 Chain = Intrin->getChain(); 13478 // Intrin->getBasePtr() oddly does not get what we want. 13479 Base = Intrin->getOperand(3); 13480 MMO = Intrin->getMemOperand(); 13481 SrcOpnd = 2; 13482 break; 13483 } 13484 } 13485 13486 SDValue Src = N->getOperand(SrcOpnd); 13487 MVT VecTy = Src.getValueType().getSimpleVT(); 13488 13489 // Do not expand to PPCISD::XXSWAPD and PPCISD::STXVD2X when the load is 13490 // aligned and the type is a vector with elements up to 4 bytes 13491 if (Subtarget.needsSwapsForVSXMemOps() && !(MMO->getAlignment()%16) 13492 && VecTy.getScalarSizeInBits() <= 32 ) { 13493 return SDValue(); 13494 } 13495 13496 // All stores are done as v2f64 and possible bit cast. 13497 if (VecTy != MVT::v2f64) { 13498 Src = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Src); 13499 DCI.AddToWorklist(Src.getNode()); 13500 } 13501 13502 SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl, 13503 DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Src); 13504 DCI.AddToWorklist(Swap.getNode()); 13505 Chain = Swap.getValue(1); 13506 SDValue StoreOps[] = { Chain, Swap, Base }; 13507 SDValue Store = DAG.getMemIntrinsicNode(PPCISD::STXVD2X, dl, 13508 DAG.getVTList(MVT::Other), 13509 StoreOps, VecTy, MMO); 13510 DCI.AddToWorklist(Store.getNode()); 13511 return Store; 13512 } 13513 13514 // Handle DAG combine for STORE (FP_TO_INT F). 13515 SDValue PPCTargetLowering::combineStoreFPToInt(SDNode *N, 13516 DAGCombinerInfo &DCI) const { 13517 13518 SelectionDAG &DAG = DCI.DAG; 13519 SDLoc dl(N); 13520 unsigned Opcode = N->getOperand(1).getOpcode(); 13521 13522 assert((Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT) 13523 && "Not a FP_TO_INT Instruction!"); 13524 13525 SDValue Val = N->getOperand(1).getOperand(0); 13526 EVT Op1VT = N->getOperand(1).getValueType(); 13527 EVT ResVT = Val.getValueType(); 13528 13529 // Floating point types smaller than 32 bits are not legal on Power. 13530 if (ResVT.getScalarSizeInBits() < 32) 13531 return SDValue(); 13532 13533 // Only perform combine for conversion to i64/i32 or power9 i16/i8. 13534 bool ValidTypeForStoreFltAsInt = 13535 (Op1VT == MVT::i32 || Op1VT == MVT::i64 || 13536 (Subtarget.hasP9Vector() && (Op1VT == MVT::i16 || Op1VT == MVT::i8))); 13537 13538 if (ResVT == MVT::ppcf128 || !Subtarget.hasP8Altivec() || 13539 cast<StoreSDNode>(N)->isTruncatingStore() || !ValidTypeForStoreFltAsInt) 13540 return SDValue(); 13541 13542 // Extend f32 values to f64 13543 if (ResVT.getScalarSizeInBits() == 32) { 13544 Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val); 13545 DCI.AddToWorklist(Val.getNode()); 13546 } 13547 13548 // Set signed or unsigned conversion opcode. 13549 unsigned ConvOpcode = (Opcode == ISD::FP_TO_SINT) ? 13550 PPCISD::FP_TO_SINT_IN_VSR : 13551 PPCISD::FP_TO_UINT_IN_VSR; 13552 13553 Val = DAG.getNode(ConvOpcode, 13554 dl, ResVT == MVT::f128 ? MVT::f128 : MVT::f64, Val); 13555 DCI.AddToWorklist(Val.getNode()); 13556 13557 // Set number of bytes being converted. 13558 unsigned ByteSize = Op1VT.getScalarSizeInBits() / 8; 13559 SDValue Ops[] = { N->getOperand(0), Val, N->getOperand(2), 13560 DAG.getIntPtrConstant(ByteSize, dl, false), 13561 DAG.getValueType(Op1VT) }; 13562 13563 Val = DAG.getMemIntrinsicNode(PPCISD::ST_VSR_SCAL_INT, dl, 13564 DAG.getVTList(MVT::Other), Ops, 13565 cast<StoreSDNode>(N)->getMemoryVT(), 13566 cast<StoreSDNode>(N)->getMemOperand()); 13567 13568 DCI.AddToWorklist(Val.getNode()); 13569 return Val; 13570 } 13571 13572 SDValue PPCTargetLowering::combineVReverseMemOP(ShuffleVectorSDNode *SVN, 13573 LSBaseSDNode *LSBase, 13574 DAGCombinerInfo &DCI) const { 13575 assert((ISD::isNormalLoad(LSBase) || ISD::isNormalStore(LSBase)) && 13576 "Not a reverse memop pattern!"); 13577 13578 auto IsElementReverse = [](const ShuffleVectorSDNode *SVN) -> bool { 13579 auto Mask = SVN->getMask(); 13580 int i = 0; 13581 auto I = Mask.rbegin(); 13582 auto E = Mask.rend(); 13583 13584 for (; I != E; ++I) { 13585 if (*I != i) 13586 return false; 13587 i++; 13588 } 13589 return true; 13590 }; 13591 13592 SelectionDAG &DAG = DCI.DAG; 13593 EVT VT = SVN->getValueType(0); 13594 13595 if (!isTypeLegal(VT) || !Subtarget.isLittleEndian() || !Subtarget.hasVSX()) 13596 return SDValue(); 13597 13598 // Before P9, we have PPCVSXSwapRemoval pass to hack the element order. 13599 // See comment in PPCVSXSwapRemoval.cpp. 13600 // It is conflict with PPCVSXSwapRemoval opt. So we don't do it. 13601 if (!Subtarget.hasP9Vector()) 13602 return SDValue(); 13603 13604 if(!IsElementReverse(SVN)) 13605 return SDValue(); 13606 13607 if (LSBase->getOpcode() == ISD::LOAD) { 13608 SDLoc dl(SVN); 13609 SDValue LoadOps[] = {LSBase->getChain(), LSBase->getBasePtr()}; 13610 return DAG.getMemIntrinsicNode( 13611 PPCISD::LOAD_VEC_BE, dl, DAG.getVTList(VT, MVT::Other), LoadOps, 13612 LSBase->getMemoryVT(), LSBase->getMemOperand()); 13613 } 13614 13615 if (LSBase->getOpcode() == ISD::STORE) { 13616 SDLoc dl(LSBase); 13617 SDValue StoreOps[] = {LSBase->getChain(), SVN->getOperand(0), 13618 LSBase->getBasePtr()}; 13619 return DAG.getMemIntrinsicNode( 13620 PPCISD::STORE_VEC_BE, dl, DAG.getVTList(MVT::Other), StoreOps, 13621 LSBase->getMemoryVT(), LSBase->getMemOperand()); 13622 } 13623 13624 llvm_unreachable("Expected a load or store node here"); 13625 } 13626 13627 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N, 13628 DAGCombinerInfo &DCI) const { 13629 SelectionDAG &DAG = DCI.DAG; 13630 SDLoc dl(N); 13631 switch (N->getOpcode()) { 13632 default: break; 13633 case ISD::ADD: 13634 return combineADD(N, DCI); 13635 case ISD::SHL: 13636 return combineSHL(N, DCI); 13637 case ISD::SRA: 13638 return combineSRA(N, DCI); 13639 case ISD::SRL: 13640 return combineSRL(N, DCI); 13641 case ISD::MUL: 13642 return combineMUL(N, DCI); 13643 case PPCISD::SHL: 13644 if (isNullConstant(N->getOperand(0))) // 0 << V -> 0. 13645 return N->getOperand(0); 13646 break; 13647 case PPCISD::SRL: 13648 if (isNullConstant(N->getOperand(0))) // 0 >>u V -> 0. 13649 return N->getOperand(0); 13650 break; 13651 case PPCISD::SRA: 13652 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) { 13653 if (C->isNullValue() || // 0 >>s V -> 0. 13654 C->isAllOnesValue()) // -1 >>s V -> -1. 13655 return N->getOperand(0); 13656 } 13657 break; 13658 case ISD::SIGN_EXTEND: 13659 case ISD::ZERO_EXTEND: 13660 case ISD::ANY_EXTEND: 13661 return DAGCombineExtBoolTrunc(N, DCI); 13662 case ISD::TRUNCATE: 13663 return combineTRUNCATE(N, DCI); 13664 case ISD::SETCC: 13665 if (SDValue CSCC = combineSetCC(N, DCI)) 13666 return CSCC; 13667 LLVM_FALLTHROUGH; 13668 case ISD::SELECT_CC: 13669 return DAGCombineTruncBoolExt(N, DCI); 13670 case ISD::SINT_TO_FP: 13671 case ISD::UINT_TO_FP: 13672 return combineFPToIntToFP(N, DCI); 13673 case ISD::VECTOR_SHUFFLE: 13674 if (ISD::isNormalLoad(N->getOperand(0).getNode())) { 13675 LSBaseSDNode* LSBase = cast<LSBaseSDNode>(N->getOperand(0)); 13676 return combineVReverseMemOP(cast<ShuffleVectorSDNode>(N), LSBase, DCI); 13677 } 13678 break; 13679 case ISD::STORE: { 13680 13681 EVT Op1VT = N->getOperand(1).getValueType(); 13682 unsigned Opcode = N->getOperand(1).getOpcode(); 13683 13684 if (Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT) { 13685 SDValue Val= combineStoreFPToInt(N, DCI); 13686 if (Val) 13687 return Val; 13688 } 13689 13690 if (Opcode == ISD::VECTOR_SHUFFLE && ISD::isNormalStore(N)) { 13691 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N->getOperand(1)); 13692 SDValue Val= combineVReverseMemOP(SVN, cast<LSBaseSDNode>(N), DCI); 13693 if (Val) 13694 return Val; 13695 } 13696 13697 // Turn STORE (BSWAP) -> sthbrx/stwbrx. 13698 if (cast<StoreSDNode>(N)->isUnindexed() && Opcode == ISD::BSWAP && 13699 N->getOperand(1).getNode()->hasOneUse() && 13700 (Op1VT == MVT::i32 || Op1VT == MVT::i16 || 13701 (Subtarget.hasLDBRX() && Subtarget.isPPC64() && Op1VT == MVT::i64))) { 13702 13703 // STBRX can only handle simple types and it makes no sense to store less 13704 // two bytes in byte-reversed order. 13705 EVT mVT = cast<StoreSDNode>(N)->getMemoryVT(); 13706 if (mVT.isExtended() || mVT.getSizeInBits() < 16) 13707 break; 13708 13709 SDValue BSwapOp = N->getOperand(1).getOperand(0); 13710 // Do an any-extend to 32-bits if this is a half-word input. 13711 if (BSwapOp.getValueType() == MVT::i16) 13712 BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp); 13713 13714 // If the type of BSWAP operand is wider than stored memory width 13715 // it need to be shifted to the right side before STBRX. 13716 if (Op1VT.bitsGT(mVT)) { 13717 int Shift = Op1VT.getSizeInBits() - mVT.getSizeInBits(); 13718 BSwapOp = DAG.getNode(ISD::SRL, dl, Op1VT, BSwapOp, 13719 DAG.getConstant(Shift, dl, MVT::i32)); 13720 // Need to truncate if this is a bswap of i64 stored as i32/i16. 13721 if (Op1VT == MVT::i64) 13722 BSwapOp = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BSwapOp); 13723 } 13724 13725 SDValue Ops[] = { 13726 N->getOperand(0), BSwapOp, N->getOperand(2), DAG.getValueType(mVT) 13727 }; 13728 return 13729 DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other), 13730 Ops, cast<StoreSDNode>(N)->getMemoryVT(), 13731 cast<StoreSDNode>(N)->getMemOperand()); 13732 } 13733 13734 // STORE Constant:i32<0> -> STORE<trunc to i32> Constant:i64<0> 13735 // So it can increase the chance of CSE constant construction. 13736 if (Subtarget.isPPC64() && !DCI.isBeforeLegalize() && 13737 isa<ConstantSDNode>(N->getOperand(1)) && Op1VT == MVT::i32) { 13738 // Need to sign-extended to 64-bits to handle negative values. 13739 EVT MemVT = cast<StoreSDNode>(N)->getMemoryVT(); 13740 uint64_t Val64 = SignExtend64(N->getConstantOperandVal(1), 13741 MemVT.getSizeInBits()); 13742 SDValue Const64 = DAG.getConstant(Val64, dl, MVT::i64); 13743 13744 // DAG.getTruncStore() can't be used here because it doesn't accept 13745 // the general (base + offset) addressing mode. 13746 // So we use UpdateNodeOperands and setTruncatingStore instead. 13747 DAG.UpdateNodeOperands(N, N->getOperand(0), Const64, N->getOperand(2), 13748 N->getOperand(3)); 13749 cast<StoreSDNode>(N)->setTruncatingStore(true); 13750 return SDValue(N, 0); 13751 } 13752 13753 // For little endian, VSX stores require generating xxswapd/lxvd2x. 13754 // Not needed on ISA 3.0 based CPUs since we have a non-permuting store. 13755 if (Op1VT.isSimple()) { 13756 MVT StoreVT = Op1VT.getSimpleVT(); 13757 if (Subtarget.needsSwapsForVSXMemOps() && 13758 (StoreVT == MVT::v2f64 || StoreVT == MVT::v2i64 || 13759 StoreVT == MVT::v4f32 || StoreVT == MVT::v4i32)) 13760 return expandVSXStoreForLE(N, DCI); 13761 } 13762 break; 13763 } 13764 case ISD::LOAD: { 13765 LoadSDNode *LD = cast<LoadSDNode>(N); 13766 EVT VT = LD->getValueType(0); 13767 13768 // For little endian, VSX loads require generating lxvd2x/xxswapd. 13769 // Not needed on ISA 3.0 based CPUs since we have a non-permuting load. 13770 if (VT.isSimple()) { 13771 MVT LoadVT = VT.getSimpleVT(); 13772 if (Subtarget.needsSwapsForVSXMemOps() && 13773 (LoadVT == MVT::v2f64 || LoadVT == MVT::v2i64 || 13774 LoadVT == MVT::v4f32 || LoadVT == MVT::v4i32)) 13775 return expandVSXLoadForLE(N, DCI); 13776 } 13777 13778 // We sometimes end up with a 64-bit integer load, from which we extract 13779 // two single-precision floating-point numbers. This happens with 13780 // std::complex<float>, and other similar structures, because of the way we 13781 // canonicalize structure copies. However, if we lack direct moves, 13782 // then the final bitcasts from the extracted integer values to the 13783 // floating-point numbers turn into store/load pairs. Even with direct moves, 13784 // just loading the two floating-point numbers is likely better. 13785 auto ReplaceTwoFloatLoad = [&]() { 13786 if (VT != MVT::i64) 13787 return false; 13788 13789 if (LD->getExtensionType() != ISD::NON_EXTLOAD || 13790 LD->isVolatile()) 13791 return false; 13792 13793 // We're looking for a sequence like this: 13794 // t13: i64,ch = load<LD8[%ref.tmp]> t0, t6, undef:i64 13795 // t16: i64 = srl t13, Constant:i32<32> 13796 // t17: i32 = truncate t16 13797 // t18: f32 = bitcast t17 13798 // t19: i32 = truncate t13 13799 // t20: f32 = bitcast t19 13800 13801 if (!LD->hasNUsesOfValue(2, 0)) 13802 return false; 13803 13804 auto UI = LD->use_begin(); 13805 while (UI.getUse().getResNo() != 0) ++UI; 13806 SDNode *Trunc = *UI++; 13807 while (UI.getUse().getResNo() != 0) ++UI; 13808 SDNode *RightShift = *UI; 13809 if (Trunc->getOpcode() != ISD::TRUNCATE) 13810 std::swap(Trunc, RightShift); 13811 13812 if (Trunc->getOpcode() != ISD::TRUNCATE || 13813 Trunc->getValueType(0) != MVT::i32 || 13814 !Trunc->hasOneUse()) 13815 return false; 13816 if (RightShift->getOpcode() != ISD::SRL || 13817 !isa<ConstantSDNode>(RightShift->getOperand(1)) || 13818 RightShift->getConstantOperandVal(1) != 32 || 13819 !RightShift->hasOneUse()) 13820 return false; 13821 13822 SDNode *Trunc2 = *RightShift->use_begin(); 13823 if (Trunc2->getOpcode() != ISD::TRUNCATE || 13824 Trunc2->getValueType(0) != MVT::i32 || 13825 !Trunc2->hasOneUse()) 13826 return false; 13827 13828 SDNode *Bitcast = *Trunc->use_begin(); 13829 SDNode *Bitcast2 = *Trunc2->use_begin(); 13830 13831 if (Bitcast->getOpcode() != ISD::BITCAST || 13832 Bitcast->getValueType(0) != MVT::f32) 13833 return false; 13834 if (Bitcast2->getOpcode() != ISD::BITCAST || 13835 Bitcast2->getValueType(0) != MVT::f32) 13836 return false; 13837 13838 if (Subtarget.isLittleEndian()) 13839 std::swap(Bitcast, Bitcast2); 13840 13841 // Bitcast has the second float (in memory-layout order) and Bitcast2 13842 // has the first one. 13843 13844 SDValue BasePtr = LD->getBasePtr(); 13845 if (LD->isIndexed()) { 13846 assert(LD->getAddressingMode() == ISD::PRE_INC && 13847 "Non-pre-inc AM on PPC?"); 13848 BasePtr = 13849 DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, 13850 LD->getOffset()); 13851 } 13852 13853 auto MMOFlags = 13854 LD->getMemOperand()->getFlags() & ~MachineMemOperand::MOVolatile; 13855 SDValue FloatLoad = DAG.getLoad(MVT::f32, dl, LD->getChain(), BasePtr, 13856 LD->getPointerInfo(), LD->getAlignment(), 13857 MMOFlags, LD->getAAInfo()); 13858 SDValue AddPtr = 13859 DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), 13860 BasePtr, DAG.getIntPtrConstant(4, dl)); 13861 SDValue FloatLoad2 = DAG.getLoad( 13862 MVT::f32, dl, SDValue(FloatLoad.getNode(), 1), AddPtr, 13863 LD->getPointerInfo().getWithOffset(4), 13864 MinAlign(LD->getAlignment(), 4), MMOFlags, LD->getAAInfo()); 13865 13866 if (LD->isIndexed()) { 13867 // Note that DAGCombine should re-form any pre-increment load(s) from 13868 // what is produced here if that makes sense. 13869 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), BasePtr); 13870 } 13871 13872 DCI.CombineTo(Bitcast2, FloatLoad); 13873 DCI.CombineTo(Bitcast, FloatLoad2); 13874 13875 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, LD->isIndexed() ? 2 : 1), 13876 SDValue(FloatLoad2.getNode(), 1)); 13877 return true; 13878 }; 13879 13880 if (ReplaceTwoFloatLoad()) 13881 return SDValue(N, 0); 13882 13883 EVT MemVT = LD->getMemoryVT(); 13884 Type *Ty = MemVT.getTypeForEVT(*DAG.getContext()); 13885 unsigned ABIAlignment = DAG.getDataLayout().getABITypeAlignment(Ty); 13886 Type *STy = MemVT.getScalarType().getTypeForEVT(*DAG.getContext()); 13887 unsigned ScalarABIAlignment = DAG.getDataLayout().getABITypeAlignment(STy); 13888 if (LD->isUnindexed() && VT.isVector() && 13889 ((Subtarget.hasAltivec() && ISD::isNON_EXTLoad(N) && 13890 // P8 and later hardware should just use LOAD. 13891 !Subtarget.hasP8Vector() && (VT == MVT::v16i8 || VT == MVT::v8i16 || 13892 VT == MVT::v4i32 || VT == MVT::v4f32)) || 13893 (Subtarget.hasQPX() && (VT == MVT::v4f64 || VT == MVT::v4f32) && 13894 LD->getAlignment() >= ScalarABIAlignment)) && 13895 LD->getAlignment() < ABIAlignment) { 13896 // This is a type-legal unaligned Altivec or QPX load. 13897 SDValue Chain = LD->getChain(); 13898 SDValue Ptr = LD->getBasePtr(); 13899 bool isLittleEndian = Subtarget.isLittleEndian(); 13900 13901 // This implements the loading of unaligned vectors as described in 13902 // the venerable Apple Velocity Engine overview. Specifically: 13903 // https://developer.apple.com/hardwaredrivers/ve/alignment.html 13904 // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html 13905 // 13906 // The general idea is to expand a sequence of one or more unaligned 13907 // loads into an alignment-based permutation-control instruction (lvsl 13908 // or lvsr), a series of regular vector loads (which always truncate 13909 // their input address to an aligned address), and a series of 13910 // permutations. The results of these permutations are the requested 13911 // loaded values. The trick is that the last "extra" load is not taken 13912 // from the address you might suspect (sizeof(vector) bytes after the 13913 // last requested load), but rather sizeof(vector) - 1 bytes after the 13914 // last requested vector. The point of this is to avoid a page fault if 13915 // the base address happened to be aligned. This works because if the 13916 // base address is aligned, then adding less than a full vector length 13917 // will cause the last vector in the sequence to be (re)loaded. 13918 // Otherwise, the next vector will be fetched as you might suspect was 13919 // necessary. 13920 13921 // We might be able to reuse the permutation generation from 13922 // a different base address offset from this one by an aligned amount. 13923 // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this 13924 // optimization later. 13925 Intrinsic::ID Intr, IntrLD, IntrPerm; 13926 MVT PermCntlTy, PermTy, LDTy; 13927 if (Subtarget.hasAltivec()) { 13928 Intr = isLittleEndian ? Intrinsic::ppc_altivec_lvsr : 13929 Intrinsic::ppc_altivec_lvsl; 13930 IntrLD = Intrinsic::ppc_altivec_lvx; 13931 IntrPerm = Intrinsic::ppc_altivec_vperm; 13932 PermCntlTy = MVT::v16i8; 13933 PermTy = MVT::v4i32; 13934 LDTy = MVT::v4i32; 13935 } else { 13936 Intr = MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlpcld : 13937 Intrinsic::ppc_qpx_qvlpcls; 13938 IntrLD = MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlfd : 13939 Intrinsic::ppc_qpx_qvlfs; 13940 IntrPerm = Intrinsic::ppc_qpx_qvfperm; 13941 PermCntlTy = MVT::v4f64; 13942 PermTy = MVT::v4f64; 13943 LDTy = MemVT.getSimpleVT(); 13944 } 13945 13946 SDValue PermCntl = BuildIntrinsicOp(Intr, Ptr, DAG, dl, PermCntlTy); 13947 13948 // Create the new MMO for the new base load. It is like the original MMO, 13949 // but represents an area in memory almost twice the vector size centered 13950 // on the original address. If the address is unaligned, we might start 13951 // reading up to (sizeof(vector)-1) bytes below the address of the 13952 // original unaligned load. 13953 MachineFunction &MF = DAG.getMachineFunction(); 13954 MachineMemOperand *BaseMMO = 13955 MF.getMachineMemOperand(LD->getMemOperand(), 13956 -(long)MemVT.getStoreSize()+1, 13957 2*MemVT.getStoreSize()-1); 13958 13959 // Create the new base load. 13960 SDValue LDXIntID = 13961 DAG.getTargetConstant(IntrLD, dl, getPointerTy(MF.getDataLayout())); 13962 SDValue BaseLoadOps[] = { Chain, LDXIntID, Ptr }; 13963 SDValue BaseLoad = 13964 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl, 13965 DAG.getVTList(PermTy, MVT::Other), 13966 BaseLoadOps, LDTy, BaseMMO); 13967 13968 // Note that the value of IncOffset (which is provided to the next 13969 // load's pointer info offset value, and thus used to calculate the 13970 // alignment), and the value of IncValue (which is actually used to 13971 // increment the pointer value) are different! This is because we 13972 // require the next load to appear to be aligned, even though it 13973 // is actually offset from the base pointer by a lesser amount. 13974 int IncOffset = VT.getSizeInBits() / 8; 13975 int IncValue = IncOffset; 13976 13977 // Walk (both up and down) the chain looking for another load at the real 13978 // (aligned) offset (the alignment of the other load does not matter in 13979 // this case). If found, then do not use the offset reduction trick, as 13980 // that will prevent the loads from being later combined (as they would 13981 // otherwise be duplicates). 13982 if (!findConsecutiveLoad(LD, DAG)) 13983 --IncValue; 13984 13985 SDValue Increment = 13986 DAG.getConstant(IncValue, dl, getPointerTy(MF.getDataLayout())); 13987 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment); 13988 13989 MachineMemOperand *ExtraMMO = 13990 MF.getMachineMemOperand(LD->getMemOperand(), 13991 1, 2*MemVT.getStoreSize()-1); 13992 SDValue ExtraLoadOps[] = { Chain, LDXIntID, Ptr }; 13993 SDValue ExtraLoad = 13994 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl, 13995 DAG.getVTList(PermTy, MVT::Other), 13996 ExtraLoadOps, LDTy, ExtraMMO); 13997 13998 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 13999 BaseLoad.getValue(1), ExtraLoad.getValue(1)); 14000 14001 // Because vperm has a big-endian bias, we must reverse the order 14002 // of the input vectors and complement the permute control vector 14003 // when generating little endian code. We have already handled the 14004 // latter by using lvsr instead of lvsl, so just reverse BaseLoad 14005 // and ExtraLoad here. 14006 SDValue Perm; 14007 if (isLittleEndian) 14008 Perm = BuildIntrinsicOp(IntrPerm, 14009 ExtraLoad, BaseLoad, PermCntl, DAG, dl); 14010 else 14011 Perm = BuildIntrinsicOp(IntrPerm, 14012 BaseLoad, ExtraLoad, PermCntl, DAG, dl); 14013 14014 if (VT != PermTy) 14015 Perm = Subtarget.hasAltivec() ? 14016 DAG.getNode(ISD::BITCAST, dl, VT, Perm) : 14017 DAG.getNode(ISD::FP_ROUND, dl, VT, Perm, // QPX 14018 DAG.getTargetConstant(1, dl, MVT::i64)); 14019 // second argument is 1 because this rounding 14020 // is always exact. 14021 14022 // The output of the permutation is our loaded result, the TokenFactor is 14023 // our new chain. 14024 DCI.CombineTo(N, Perm, TF); 14025 return SDValue(N, 0); 14026 } 14027 } 14028 break; 14029 case ISD::INTRINSIC_WO_CHAIN: { 14030 bool isLittleEndian = Subtarget.isLittleEndian(); 14031 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 14032 Intrinsic::ID Intr = (isLittleEndian ? Intrinsic::ppc_altivec_lvsr 14033 : Intrinsic::ppc_altivec_lvsl); 14034 if ((IID == Intr || 14035 IID == Intrinsic::ppc_qpx_qvlpcld || 14036 IID == Intrinsic::ppc_qpx_qvlpcls) && 14037 N->getOperand(1)->getOpcode() == ISD::ADD) { 14038 SDValue Add = N->getOperand(1); 14039 14040 int Bits = IID == Intrinsic::ppc_qpx_qvlpcld ? 14041 5 /* 32 byte alignment */ : 4 /* 16 byte alignment */; 14042 14043 if (DAG.MaskedValueIsZero(Add->getOperand(1), 14044 APInt::getAllOnesValue(Bits /* alignment */) 14045 .zext(Add.getScalarValueSizeInBits()))) { 14046 SDNode *BasePtr = Add->getOperand(0).getNode(); 14047 for (SDNode::use_iterator UI = BasePtr->use_begin(), 14048 UE = BasePtr->use_end(); 14049 UI != UE; ++UI) { 14050 if (UI->getOpcode() == ISD::INTRINSIC_WO_CHAIN && 14051 cast<ConstantSDNode>(UI->getOperand(0))->getZExtValue() == IID) { 14052 // We've found another LVSL/LVSR, and this address is an aligned 14053 // multiple of that one. The results will be the same, so use the 14054 // one we've just found instead. 14055 14056 return SDValue(*UI, 0); 14057 } 14058 } 14059 } 14060 14061 if (isa<ConstantSDNode>(Add->getOperand(1))) { 14062 SDNode *BasePtr = Add->getOperand(0).getNode(); 14063 for (SDNode::use_iterator UI = BasePtr->use_begin(), 14064 UE = BasePtr->use_end(); UI != UE; ++UI) { 14065 if (UI->getOpcode() == ISD::ADD && 14066 isa<ConstantSDNode>(UI->getOperand(1)) && 14067 (cast<ConstantSDNode>(Add->getOperand(1))->getZExtValue() - 14068 cast<ConstantSDNode>(UI->getOperand(1))->getZExtValue()) % 14069 (1ULL << Bits) == 0) { 14070 SDNode *OtherAdd = *UI; 14071 for (SDNode::use_iterator VI = OtherAdd->use_begin(), 14072 VE = OtherAdd->use_end(); VI != VE; ++VI) { 14073 if (VI->getOpcode() == ISD::INTRINSIC_WO_CHAIN && 14074 cast<ConstantSDNode>(VI->getOperand(0))->getZExtValue() == IID) { 14075 return SDValue(*VI, 0); 14076 } 14077 } 14078 } 14079 } 14080 } 14081 } 14082 14083 // Combine vmaxsw/h/b(a, a's negation) to abs(a) 14084 // Expose the vabsduw/h/b opportunity for down stream 14085 if (!DCI.isAfterLegalizeDAG() && Subtarget.hasP9Altivec() && 14086 (IID == Intrinsic::ppc_altivec_vmaxsw || 14087 IID == Intrinsic::ppc_altivec_vmaxsh || 14088 IID == Intrinsic::ppc_altivec_vmaxsb)) { 14089 SDValue V1 = N->getOperand(1); 14090 SDValue V2 = N->getOperand(2); 14091 if ((V1.getSimpleValueType() == MVT::v4i32 || 14092 V1.getSimpleValueType() == MVT::v8i16 || 14093 V1.getSimpleValueType() == MVT::v16i8) && 14094 V1.getSimpleValueType() == V2.getSimpleValueType()) { 14095 // (0-a, a) 14096 if (V1.getOpcode() == ISD::SUB && 14097 ISD::isBuildVectorAllZeros(V1.getOperand(0).getNode()) && 14098 V1.getOperand(1) == V2) { 14099 return DAG.getNode(ISD::ABS, dl, V2.getValueType(), V2); 14100 } 14101 // (a, 0-a) 14102 if (V2.getOpcode() == ISD::SUB && 14103 ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()) && 14104 V2.getOperand(1) == V1) { 14105 return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1); 14106 } 14107 // (x-y, y-x) 14108 if (V1.getOpcode() == ISD::SUB && V2.getOpcode() == ISD::SUB && 14109 V1.getOperand(0) == V2.getOperand(1) && 14110 V1.getOperand(1) == V2.getOperand(0)) { 14111 return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1); 14112 } 14113 } 14114 } 14115 } 14116 14117 break; 14118 case ISD::INTRINSIC_W_CHAIN: 14119 // For little endian, VSX loads require generating lxvd2x/xxswapd. 14120 // Not needed on ISA 3.0 based CPUs since we have a non-permuting load. 14121 if (Subtarget.needsSwapsForVSXMemOps()) { 14122 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 14123 default: 14124 break; 14125 case Intrinsic::ppc_vsx_lxvw4x: 14126 case Intrinsic::ppc_vsx_lxvd2x: 14127 return expandVSXLoadForLE(N, DCI); 14128 } 14129 } 14130 break; 14131 case ISD::INTRINSIC_VOID: 14132 // For little endian, VSX stores require generating xxswapd/stxvd2x. 14133 // Not needed on ISA 3.0 based CPUs since we have a non-permuting store. 14134 if (Subtarget.needsSwapsForVSXMemOps()) { 14135 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 14136 default: 14137 break; 14138 case Intrinsic::ppc_vsx_stxvw4x: 14139 case Intrinsic::ppc_vsx_stxvd2x: 14140 return expandVSXStoreForLE(N, DCI); 14141 } 14142 } 14143 break; 14144 case ISD::BSWAP: 14145 // Turn BSWAP (LOAD) -> lhbrx/lwbrx. 14146 if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) && 14147 N->getOperand(0).hasOneUse() && 14148 (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 || 14149 (Subtarget.hasLDBRX() && Subtarget.isPPC64() && 14150 N->getValueType(0) == MVT::i64))) { 14151 SDValue Load = N->getOperand(0); 14152 LoadSDNode *LD = cast<LoadSDNode>(Load); 14153 // Create the byte-swapping load. 14154 SDValue Ops[] = { 14155 LD->getChain(), // Chain 14156 LD->getBasePtr(), // Ptr 14157 DAG.getValueType(N->getValueType(0)) // VT 14158 }; 14159 SDValue BSLoad = 14160 DAG.getMemIntrinsicNode(PPCISD::LBRX, dl, 14161 DAG.getVTList(N->getValueType(0) == MVT::i64 ? 14162 MVT::i64 : MVT::i32, MVT::Other), 14163 Ops, LD->getMemoryVT(), LD->getMemOperand()); 14164 14165 // If this is an i16 load, insert the truncate. 14166 SDValue ResVal = BSLoad; 14167 if (N->getValueType(0) == MVT::i16) 14168 ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad); 14169 14170 // First, combine the bswap away. This makes the value produced by the 14171 // load dead. 14172 DCI.CombineTo(N, ResVal); 14173 14174 // Next, combine the load away, we give it a bogus result value but a real 14175 // chain result. The result value is dead because the bswap is dead. 14176 DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1)); 14177 14178 // Return N so it doesn't get rechecked! 14179 return SDValue(N, 0); 14180 } 14181 break; 14182 case PPCISD::VCMP: 14183 // If a VCMPo node already exists with exactly the same operands as this 14184 // node, use its result instead of this node (VCMPo computes both a CR6 and 14185 // a normal output). 14186 // 14187 if (!N->getOperand(0).hasOneUse() && 14188 !N->getOperand(1).hasOneUse() && 14189 !N->getOperand(2).hasOneUse()) { 14190 14191 // Scan all of the users of the LHS, looking for VCMPo's that match. 14192 SDNode *VCMPoNode = nullptr; 14193 14194 SDNode *LHSN = N->getOperand(0).getNode(); 14195 for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end(); 14196 UI != E; ++UI) 14197 if (UI->getOpcode() == PPCISD::VCMPo && 14198 UI->getOperand(1) == N->getOperand(1) && 14199 UI->getOperand(2) == N->getOperand(2) && 14200 UI->getOperand(0) == N->getOperand(0)) { 14201 VCMPoNode = *UI; 14202 break; 14203 } 14204 14205 // If there is no VCMPo node, or if the flag value has a single use, don't 14206 // transform this. 14207 if (!VCMPoNode || VCMPoNode->hasNUsesOfValue(0, 1)) 14208 break; 14209 14210 // Look at the (necessarily single) use of the flag value. If it has a 14211 // chain, this transformation is more complex. Note that multiple things 14212 // could use the value result, which we should ignore. 14213 SDNode *FlagUser = nullptr; 14214 for (SDNode::use_iterator UI = VCMPoNode->use_begin(); 14215 FlagUser == nullptr; ++UI) { 14216 assert(UI != VCMPoNode->use_end() && "Didn't find user!"); 14217 SDNode *User = *UI; 14218 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) { 14219 if (User->getOperand(i) == SDValue(VCMPoNode, 1)) { 14220 FlagUser = User; 14221 break; 14222 } 14223 } 14224 } 14225 14226 // If the user is a MFOCRF instruction, we know this is safe. 14227 // Otherwise we give up for right now. 14228 if (FlagUser->getOpcode() == PPCISD::MFOCRF) 14229 return SDValue(VCMPoNode, 0); 14230 } 14231 break; 14232 case ISD::BRCOND: { 14233 SDValue Cond = N->getOperand(1); 14234 SDValue Target = N->getOperand(2); 14235 14236 if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN && 14237 cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() == 14238 Intrinsic::loop_decrement) { 14239 14240 // We now need to make the intrinsic dead (it cannot be instruction 14241 // selected). 14242 DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0)); 14243 assert(Cond.getNode()->hasOneUse() && 14244 "Counter decrement has more than one use"); 14245 14246 return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other, 14247 N->getOperand(0), Target); 14248 } 14249 } 14250 break; 14251 case ISD::BR_CC: { 14252 // If this is a branch on an altivec predicate comparison, lower this so 14253 // that we don't have to do a MFOCRF: instead, branch directly on CR6. This 14254 // lowering is done pre-legalize, because the legalizer lowers the predicate 14255 // compare down to code that is difficult to reassemble. 14256 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get(); 14257 SDValue LHS = N->getOperand(2), RHS = N->getOperand(3); 14258 14259 // Sometimes the promoted value of the intrinsic is ANDed by some non-zero 14260 // value. If so, pass-through the AND to get to the intrinsic. 14261 if (LHS.getOpcode() == ISD::AND && 14262 LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN && 14263 cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() == 14264 Intrinsic::loop_decrement && 14265 isa<ConstantSDNode>(LHS.getOperand(1)) && 14266 !isNullConstant(LHS.getOperand(1))) 14267 LHS = LHS.getOperand(0); 14268 14269 if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN && 14270 cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() == 14271 Intrinsic::loop_decrement && 14272 isa<ConstantSDNode>(RHS)) { 14273 assert((CC == ISD::SETEQ || CC == ISD::SETNE) && 14274 "Counter decrement comparison is not EQ or NE"); 14275 14276 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue(); 14277 bool isBDNZ = (CC == ISD::SETEQ && Val) || 14278 (CC == ISD::SETNE && !Val); 14279 14280 // We now need to make the intrinsic dead (it cannot be instruction 14281 // selected). 14282 DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0)); 14283 assert(LHS.getNode()->hasOneUse() && 14284 "Counter decrement has more than one use"); 14285 14286 return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other, 14287 N->getOperand(0), N->getOperand(4)); 14288 } 14289 14290 int CompareOpc; 14291 bool isDot; 14292 14293 if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN && 14294 isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) && 14295 getVectorCompareInfo(LHS, CompareOpc, isDot, Subtarget)) { 14296 assert(isDot && "Can't compare against a vector result!"); 14297 14298 // If this is a comparison against something other than 0/1, then we know 14299 // that the condition is never/always true. 14300 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue(); 14301 if (Val != 0 && Val != 1) { 14302 if (CC == ISD::SETEQ) // Cond never true, remove branch. 14303 return N->getOperand(0); 14304 // Always !=, turn it into an unconditional branch. 14305 return DAG.getNode(ISD::BR, dl, MVT::Other, 14306 N->getOperand(0), N->getOperand(4)); 14307 } 14308 14309 bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0); 14310 14311 // Create the PPCISD altivec 'dot' comparison node. 14312 SDValue Ops[] = { 14313 LHS.getOperand(2), // LHS of compare 14314 LHS.getOperand(3), // RHS of compare 14315 DAG.getConstant(CompareOpc, dl, MVT::i32) 14316 }; 14317 EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue }; 14318 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops); 14319 14320 // Unpack the result based on how the target uses it. 14321 PPC::Predicate CompOpc; 14322 switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) { 14323 default: // Can't happen, don't crash on invalid number though. 14324 case 0: // Branch on the value of the EQ bit of CR6. 14325 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE; 14326 break; 14327 case 1: // Branch on the inverted value of the EQ bit of CR6. 14328 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ; 14329 break; 14330 case 2: // Branch on the value of the LT bit of CR6. 14331 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE; 14332 break; 14333 case 3: // Branch on the inverted value of the LT bit of CR6. 14334 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT; 14335 break; 14336 } 14337 14338 return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0), 14339 DAG.getConstant(CompOpc, dl, MVT::i32), 14340 DAG.getRegister(PPC::CR6, MVT::i32), 14341 N->getOperand(4), CompNode.getValue(1)); 14342 } 14343 break; 14344 } 14345 case ISD::BUILD_VECTOR: 14346 return DAGCombineBuildVector(N, DCI); 14347 case ISD::ABS: 14348 return combineABS(N, DCI); 14349 case ISD::VSELECT: 14350 return combineVSelect(N, DCI); 14351 } 14352 14353 return SDValue(); 14354 } 14355 14356 SDValue 14357 PPCTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor, 14358 SelectionDAG &DAG, 14359 SmallVectorImpl<SDNode *> &Created) const { 14360 // fold (sdiv X, pow2) 14361 EVT VT = N->getValueType(0); 14362 if (VT == MVT::i64 && !Subtarget.isPPC64()) 14363 return SDValue(); 14364 if ((VT != MVT::i32 && VT != MVT::i64) || 14365 !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2())) 14366 return SDValue(); 14367 14368 SDLoc DL(N); 14369 SDValue N0 = N->getOperand(0); 14370 14371 bool IsNegPow2 = (-Divisor).isPowerOf2(); 14372 unsigned Lg2 = (IsNegPow2 ? -Divisor : Divisor).countTrailingZeros(); 14373 SDValue ShiftAmt = DAG.getConstant(Lg2, DL, VT); 14374 14375 SDValue Op = DAG.getNode(PPCISD::SRA_ADDZE, DL, VT, N0, ShiftAmt); 14376 Created.push_back(Op.getNode()); 14377 14378 if (IsNegPow2) { 14379 Op = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Op); 14380 Created.push_back(Op.getNode()); 14381 } 14382 14383 return Op; 14384 } 14385 14386 //===----------------------------------------------------------------------===// 14387 // Inline Assembly Support 14388 //===----------------------------------------------------------------------===// 14389 14390 void PPCTargetLowering::computeKnownBitsForTargetNode(const SDValue Op, 14391 KnownBits &Known, 14392 const APInt &DemandedElts, 14393 const SelectionDAG &DAG, 14394 unsigned Depth) const { 14395 Known.resetAll(); 14396 switch (Op.getOpcode()) { 14397 default: break; 14398 case PPCISD::LBRX: { 14399 // lhbrx is known to have the top bits cleared out. 14400 if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16) 14401 Known.Zero = 0xFFFF0000; 14402 break; 14403 } 14404 case ISD::INTRINSIC_WO_CHAIN: { 14405 switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) { 14406 default: break; 14407 case Intrinsic::ppc_altivec_vcmpbfp_p: 14408 case Intrinsic::ppc_altivec_vcmpeqfp_p: 14409 case Intrinsic::ppc_altivec_vcmpequb_p: 14410 case Intrinsic::ppc_altivec_vcmpequh_p: 14411 case Intrinsic::ppc_altivec_vcmpequw_p: 14412 case Intrinsic::ppc_altivec_vcmpequd_p: 14413 case Intrinsic::ppc_altivec_vcmpgefp_p: 14414 case Intrinsic::ppc_altivec_vcmpgtfp_p: 14415 case Intrinsic::ppc_altivec_vcmpgtsb_p: 14416 case Intrinsic::ppc_altivec_vcmpgtsh_p: 14417 case Intrinsic::ppc_altivec_vcmpgtsw_p: 14418 case Intrinsic::ppc_altivec_vcmpgtsd_p: 14419 case Intrinsic::ppc_altivec_vcmpgtub_p: 14420 case Intrinsic::ppc_altivec_vcmpgtuh_p: 14421 case Intrinsic::ppc_altivec_vcmpgtuw_p: 14422 case Intrinsic::ppc_altivec_vcmpgtud_p: 14423 Known.Zero = ~1U; // All bits but the low one are known to be zero. 14424 break; 14425 } 14426 } 14427 } 14428 } 14429 14430 Align PPCTargetLowering::getPrefLoopAlignment(MachineLoop *ML) const { 14431 switch (Subtarget.getCPUDirective()) { 14432 default: break; 14433 case PPC::DIR_970: 14434 case PPC::DIR_PWR4: 14435 case PPC::DIR_PWR5: 14436 case PPC::DIR_PWR5X: 14437 case PPC::DIR_PWR6: 14438 case PPC::DIR_PWR6X: 14439 case PPC::DIR_PWR7: 14440 case PPC::DIR_PWR8: 14441 case PPC::DIR_PWR9: 14442 case PPC::DIR_PWR_FUTURE: { 14443 if (!ML) 14444 break; 14445 14446 if (!DisableInnermostLoopAlign32) { 14447 // If the nested loop is an innermost loop, prefer to a 32-byte alignment, 14448 // so that we can decrease cache misses and branch-prediction misses. 14449 // Actual alignment of the loop will depend on the hotness check and other 14450 // logic in alignBlocks. 14451 if (ML->getLoopDepth() > 1 && ML->getSubLoops().empty()) 14452 return Align(32); 14453 } 14454 14455 const PPCInstrInfo *TII = Subtarget.getInstrInfo(); 14456 14457 // For small loops (between 5 and 8 instructions), align to a 32-byte 14458 // boundary so that the entire loop fits in one instruction-cache line. 14459 uint64_t LoopSize = 0; 14460 for (auto I = ML->block_begin(), IE = ML->block_end(); I != IE; ++I) 14461 for (auto J = (*I)->begin(), JE = (*I)->end(); J != JE; ++J) { 14462 LoopSize += TII->getInstSizeInBytes(*J); 14463 if (LoopSize > 32) 14464 break; 14465 } 14466 14467 if (LoopSize > 16 && LoopSize <= 32) 14468 return Align(32); 14469 14470 break; 14471 } 14472 } 14473 14474 return TargetLowering::getPrefLoopAlignment(ML); 14475 } 14476 14477 /// getConstraintType - Given a constraint, return the type of 14478 /// constraint it is for this target. 14479 PPCTargetLowering::ConstraintType 14480 PPCTargetLowering::getConstraintType(StringRef Constraint) const { 14481 if (Constraint.size() == 1) { 14482 switch (Constraint[0]) { 14483 default: break; 14484 case 'b': 14485 case 'r': 14486 case 'f': 14487 case 'd': 14488 case 'v': 14489 case 'y': 14490 return C_RegisterClass; 14491 case 'Z': 14492 // FIXME: While Z does indicate a memory constraint, it specifically 14493 // indicates an r+r address (used in conjunction with the 'y' modifier 14494 // in the replacement string). Currently, we're forcing the base 14495 // register to be r0 in the asm printer (which is interpreted as zero) 14496 // and forming the complete address in the second register. This is 14497 // suboptimal. 14498 return C_Memory; 14499 } 14500 } else if (Constraint == "wc") { // individual CR bits. 14501 return C_RegisterClass; 14502 } else if (Constraint == "wa" || Constraint == "wd" || 14503 Constraint == "wf" || Constraint == "ws" || 14504 Constraint == "wi" || Constraint == "ww") { 14505 return C_RegisterClass; // VSX registers. 14506 } 14507 return TargetLowering::getConstraintType(Constraint); 14508 } 14509 14510 /// Examine constraint type and operand type and determine a weight value. 14511 /// This object must already have been set up with the operand type 14512 /// and the current alternative constraint selected. 14513 TargetLowering::ConstraintWeight 14514 PPCTargetLowering::getSingleConstraintMatchWeight( 14515 AsmOperandInfo &info, const char *constraint) const { 14516 ConstraintWeight weight = CW_Invalid; 14517 Value *CallOperandVal = info.CallOperandVal; 14518 // If we don't have a value, we can't do a match, 14519 // but allow it at the lowest weight. 14520 if (!CallOperandVal) 14521 return CW_Default; 14522 Type *type = CallOperandVal->getType(); 14523 14524 // Look at the constraint type. 14525 if (StringRef(constraint) == "wc" && type->isIntegerTy(1)) 14526 return CW_Register; // an individual CR bit. 14527 else if ((StringRef(constraint) == "wa" || 14528 StringRef(constraint) == "wd" || 14529 StringRef(constraint) == "wf") && 14530 type->isVectorTy()) 14531 return CW_Register; 14532 else if (StringRef(constraint) == "wi" && type->isIntegerTy(64)) 14533 return CW_Register; // just hold 64-bit integers data. 14534 else if (StringRef(constraint) == "ws" && type->isDoubleTy()) 14535 return CW_Register; 14536 else if (StringRef(constraint) == "ww" && type->isFloatTy()) 14537 return CW_Register; 14538 14539 switch (*constraint) { 14540 default: 14541 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint); 14542 break; 14543 case 'b': 14544 if (type->isIntegerTy()) 14545 weight = CW_Register; 14546 break; 14547 case 'f': 14548 if (type->isFloatTy()) 14549 weight = CW_Register; 14550 break; 14551 case 'd': 14552 if (type->isDoubleTy()) 14553 weight = CW_Register; 14554 break; 14555 case 'v': 14556 if (type->isVectorTy()) 14557 weight = CW_Register; 14558 break; 14559 case 'y': 14560 weight = CW_Register; 14561 break; 14562 case 'Z': 14563 weight = CW_Memory; 14564 break; 14565 } 14566 return weight; 14567 } 14568 14569 std::pair<unsigned, const TargetRegisterClass *> 14570 PPCTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, 14571 StringRef Constraint, 14572 MVT VT) const { 14573 if (Constraint.size() == 1) { 14574 // GCC RS6000 Constraint Letters 14575 switch (Constraint[0]) { 14576 case 'b': // R1-R31 14577 if (VT == MVT::i64 && Subtarget.isPPC64()) 14578 return std::make_pair(0U, &PPC::G8RC_NOX0RegClass); 14579 return std::make_pair(0U, &PPC::GPRC_NOR0RegClass); 14580 case 'r': // R0-R31 14581 if (VT == MVT::i64 && Subtarget.isPPC64()) 14582 return std::make_pair(0U, &PPC::G8RCRegClass); 14583 return std::make_pair(0U, &PPC::GPRCRegClass); 14584 // 'd' and 'f' constraints are both defined to be "the floating point 14585 // registers", where one is for 32-bit and the other for 64-bit. We don't 14586 // really care overly much here so just give them all the same reg classes. 14587 case 'd': 14588 case 'f': 14589 if (Subtarget.hasSPE()) { 14590 if (VT == MVT::f32 || VT == MVT::i32) 14591 return std::make_pair(0U, &PPC::GPRCRegClass); 14592 if (VT == MVT::f64 || VT == MVT::i64) 14593 return std::make_pair(0U, &PPC::SPERCRegClass); 14594 } else { 14595 if (VT == MVT::f32 || VT == MVT::i32) 14596 return std::make_pair(0U, &PPC::F4RCRegClass); 14597 if (VT == MVT::f64 || VT == MVT::i64) 14598 return std::make_pair(0U, &PPC::F8RCRegClass); 14599 if (VT == MVT::v4f64 && Subtarget.hasQPX()) 14600 return std::make_pair(0U, &PPC::QFRCRegClass); 14601 if (VT == MVT::v4f32 && Subtarget.hasQPX()) 14602 return std::make_pair(0U, &PPC::QSRCRegClass); 14603 } 14604 break; 14605 case 'v': 14606 if (VT == MVT::v4f64 && Subtarget.hasQPX()) 14607 return std::make_pair(0U, &PPC::QFRCRegClass); 14608 if (VT == MVT::v4f32 && Subtarget.hasQPX()) 14609 return std::make_pair(0U, &PPC::QSRCRegClass); 14610 if (Subtarget.hasAltivec()) 14611 return std::make_pair(0U, &PPC::VRRCRegClass); 14612 break; 14613 case 'y': // crrc 14614 return std::make_pair(0U, &PPC::CRRCRegClass); 14615 } 14616 } else if (Constraint == "wc" && Subtarget.useCRBits()) { 14617 // An individual CR bit. 14618 return std::make_pair(0U, &PPC::CRBITRCRegClass); 14619 } else if ((Constraint == "wa" || Constraint == "wd" || 14620 Constraint == "wf" || Constraint == "wi") && 14621 Subtarget.hasVSX()) { 14622 return std::make_pair(0U, &PPC::VSRCRegClass); 14623 } else if ((Constraint == "ws" || Constraint == "ww") && Subtarget.hasVSX()) { 14624 if (VT == MVT::f32 && Subtarget.hasP8Vector()) 14625 return std::make_pair(0U, &PPC::VSSRCRegClass); 14626 else 14627 return std::make_pair(0U, &PPC::VSFRCRegClass); 14628 } 14629 14630 // If we name a VSX register, we can't defer to the base class because it 14631 // will not recognize the correct register (their names will be VSL{0-31} 14632 // and V{0-31} so they won't match). So we match them here. 14633 if (Constraint.size() > 3 && Constraint[1] == 'v' && Constraint[2] == 's') { 14634 int VSNum = atoi(Constraint.data() + 3); 14635 assert(VSNum >= 0 && VSNum <= 63 && 14636 "Attempted to access a vsr out of range"); 14637 if (VSNum < 32) 14638 return std::make_pair(PPC::VSL0 + VSNum, &PPC::VSRCRegClass); 14639 return std::make_pair(PPC::V0 + VSNum - 32, &PPC::VSRCRegClass); 14640 } 14641 std::pair<unsigned, const TargetRegisterClass *> R = 14642 TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 14643 14644 // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers 14645 // (which we call X[0-9]+). If a 64-bit value has been requested, and a 14646 // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent 14647 // register. 14648 // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use 14649 // the AsmName field from *RegisterInfo.td, then this would not be necessary. 14650 if (R.first && VT == MVT::i64 && Subtarget.isPPC64() && 14651 PPC::GPRCRegClass.contains(R.first)) 14652 return std::make_pair(TRI->getMatchingSuperReg(R.first, 14653 PPC::sub_32, &PPC::G8RCRegClass), 14654 &PPC::G8RCRegClass); 14655 14656 // GCC accepts 'cc' as an alias for 'cr0', and we need to do the same. 14657 if (!R.second && StringRef("{cc}").equals_lower(Constraint)) { 14658 R.first = PPC::CR0; 14659 R.second = &PPC::CRRCRegClass; 14660 } 14661 14662 return R; 14663 } 14664 14665 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops 14666 /// vector. If it is invalid, don't add anything to Ops. 14667 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op, 14668 std::string &Constraint, 14669 std::vector<SDValue>&Ops, 14670 SelectionDAG &DAG) const { 14671 SDValue Result; 14672 14673 // Only support length 1 constraints. 14674 if (Constraint.length() > 1) return; 14675 14676 char Letter = Constraint[0]; 14677 switch (Letter) { 14678 default: break; 14679 case 'I': 14680 case 'J': 14681 case 'K': 14682 case 'L': 14683 case 'M': 14684 case 'N': 14685 case 'O': 14686 case 'P': { 14687 ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op); 14688 if (!CST) return; // Must be an immediate to match. 14689 SDLoc dl(Op); 14690 int64_t Value = CST->getSExtValue(); 14691 EVT TCVT = MVT::i64; // All constants taken to be 64 bits so that negative 14692 // numbers are printed as such. 14693 switch (Letter) { 14694 default: llvm_unreachable("Unknown constraint letter!"); 14695 case 'I': // "I" is a signed 16-bit constant. 14696 if (isInt<16>(Value)) 14697 Result = DAG.getTargetConstant(Value, dl, TCVT); 14698 break; 14699 case 'J': // "J" is a constant with only the high-order 16 bits nonzero. 14700 if (isShiftedUInt<16, 16>(Value)) 14701 Result = DAG.getTargetConstant(Value, dl, TCVT); 14702 break; 14703 case 'L': // "L" is a signed 16-bit constant shifted left 16 bits. 14704 if (isShiftedInt<16, 16>(Value)) 14705 Result = DAG.getTargetConstant(Value, dl, TCVT); 14706 break; 14707 case 'K': // "K" is a constant with only the low-order 16 bits nonzero. 14708 if (isUInt<16>(Value)) 14709 Result = DAG.getTargetConstant(Value, dl, TCVT); 14710 break; 14711 case 'M': // "M" is a constant that is greater than 31. 14712 if (Value > 31) 14713 Result = DAG.getTargetConstant(Value, dl, TCVT); 14714 break; 14715 case 'N': // "N" is a positive constant that is an exact power of two. 14716 if (Value > 0 && isPowerOf2_64(Value)) 14717 Result = DAG.getTargetConstant(Value, dl, TCVT); 14718 break; 14719 case 'O': // "O" is the constant zero. 14720 if (Value == 0) 14721 Result = DAG.getTargetConstant(Value, dl, TCVT); 14722 break; 14723 case 'P': // "P" is a constant whose negation is a signed 16-bit constant. 14724 if (isInt<16>(-Value)) 14725 Result = DAG.getTargetConstant(Value, dl, TCVT); 14726 break; 14727 } 14728 break; 14729 } 14730 } 14731 14732 if (Result.getNode()) { 14733 Ops.push_back(Result); 14734 return; 14735 } 14736 14737 // Handle standard constraint letters. 14738 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 14739 } 14740 14741 // isLegalAddressingMode - Return true if the addressing mode represented 14742 // by AM is legal for this target, for a load/store of the specified type. 14743 bool PPCTargetLowering::isLegalAddressingMode(const DataLayout &DL, 14744 const AddrMode &AM, Type *Ty, 14745 unsigned AS, Instruction *I) const { 14746 // PPC does not allow r+i addressing modes for vectors! 14747 if (Ty->isVectorTy() && AM.BaseOffs != 0) 14748 return false; 14749 14750 // PPC allows a sign-extended 16-bit immediate field. 14751 if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1) 14752 return false; 14753 14754 // No global is ever allowed as a base. 14755 if (AM.BaseGV) 14756 return false; 14757 14758 // PPC only support r+r, 14759 switch (AM.Scale) { 14760 case 0: // "r+i" or just "i", depending on HasBaseReg. 14761 break; 14762 case 1: 14763 if (AM.HasBaseReg && AM.BaseOffs) // "r+r+i" is not allowed. 14764 return false; 14765 // Otherwise we have r+r or r+i. 14766 break; 14767 case 2: 14768 if (AM.HasBaseReg || AM.BaseOffs) // 2*r+r or 2*r+i is not allowed. 14769 return false; 14770 // Allow 2*r as r+r. 14771 break; 14772 default: 14773 // No other scales are supported. 14774 return false; 14775 } 14776 14777 return true; 14778 } 14779 14780 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op, 14781 SelectionDAG &DAG) const { 14782 MachineFunction &MF = DAG.getMachineFunction(); 14783 MachineFrameInfo &MFI = MF.getFrameInfo(); 14784 MFI.setReturnAddressIsTaken(true); 14785 14786 if (verifyReturnAddressArgumentIsConstant(Op, DAG)) 14787 return SDValue(); 14788 14789 SDLoc dl(Op); 14790 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 14791 14792 // Make sure the function does not optimize away the store of the RA to 14793 // the stack. 14794 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 14795 FuncInfo->setLRStoreRequired(); 14796 bool isPPC64 = Subtarget.isPPC64(); 14797 auto PtrVT = getPointerTy(MF.getDataLayout()); 14798 14799 if (Depth > 0) { 14800 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG); 14801 SDValue Offset = 14802 DAG.getConstant(Subtarget.getFrameLowering()->getReturnSaveOffset(), dl, 14803 isPPC64 ? MVT::i64 : MVT::i32); 14804 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), 14805 DAG.getNode(ISD::ADD, dl, PtrVT, FrameAddr, Offset), 14806 MachinePointerInfo()); 14807 } 14808 14809 // Just load the return address off the stack. 14810 SDValue RetAddrFI = getReturnAddrFrameIndex(DAG); 14811 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), RetAddrFI, 14812 MachinePointerInfo()); 14813 } 14814 14815 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op, 14816 SelectionDAG &DAG) const { 14817 SDLoc dl(Op); 14818 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 14819 14820 MachineFunction &MF = DAG.getMachineFunction(); 14821 MachineFrameInfo &MFI = MF.getFrameInfo(); 14822 MFI.setFrameAddressIsTaken(true); 14823 14824 EVT PtrVT = getPointerTy(MF.getDataLayout()); 14825 bool isPPC64 = PtrVT == MVT::i64; 14826 14827 // Naked functions never have a frame pointer, and so we use r1. For all 14828 // other functions, this decision must be delayed until during PEI. 14829 unsigned FrameReg; 14830 if (MF.getFunction().hasFnAttribute(Attribute::Naked)) 14831 FrameReg = isPPC64 ? PPC::X1 : PPC::R1; 14832 else 14833 FrameReg = isPPC64 ? PPC::FP8 : PPC::FP; 14834 14835 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, 14836 PtrVT); 14837 while (Depth--) 14838 FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(), 14839 FrameAddr, MachinePointerInfo()); 14840 return FrameAddr; 14841 } 14842 14843 // FIXME? Maybe this could be a TableGen attribute on some registers and 14844 // this table could be generated automatically from RegInfo. 14845 Register PPCTargetLowering::getRegisterByName(const char* RegName, LLT VT, 14846 const MachineFunction &MF) const { 14847 bool isPPC64 = Subtarget.isPPC64(); 14848 14849 bool is64Bit = isPPC64 && VT == LLT::scalar(64); 14850 if (!is64Bit && VT != LLT::scalar(32)) 14851 report_fatal_error("Invalid register global variable type"); 14852 14853 Register Reg = StringSwitch<Register>(RegName) 14854 .Case("r1", is64Bit ? PPC::X1 : PPC::R1) 14855 .Case("r2", isPPC64 ? Register() : PPC::R2) 14856 .Case("r13", (is64Bit ? PPC::X13 : PPC::R13)) 14857 .Default(Register()); 14858 14859 if (Reg) 14860 return Reg; 14861 report_fatal_error("Invalid register name global variable"); 14862 } 14863 14864 bool PPCTargetLowering::isAccessedAsGotIndirect(SDValue GA) const { 14865 // 32-bit SVR4 ABI access everything as got-indirect. 14866 if (Subtarget.is32BitELFABI()) 14867 return true; 14868 14869 // AIX accesses everything indirectly through the TOC, which is similar to 14870 // the GOT. 14871 if (Subtarget.isAIXABI()) 14872 return true; 14873 14874 CodeModel::Model CModel = getTargetMachine().getCodeModel(); 14875 // If it is small or large code model, module locals are accessed 14876 // indirectly by loading their address from .toc/.got. 14877 if (CModel == CodeModel::Small || CModel == CodeModel::Large) 14878 return true; 14879 14880 // JumpTable and BlockAddress are accessed as got-indirect. 14881 if (isa<JumpTableSDNode>(GA) || isa<BlockAddressSDNode>(GA)) 14882 return true; 14883 14884 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(GA)) 14885 return Subtarget.isGVIndirectSymbol(G->getGlobal()); 14886 14887 return false; 14888 } 14889 14890 bool 14891 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 14892 // The PowerPC target isn't yet aware of offsets. 14893 return false; 14894 } 14895 14896 bool PPCTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 14897 const CallInst &I, 14898 MachineFunction &MF, 14899 unsigned Intrinsic) const { 14900 switch (Intrinsic) { 14901 case Intrinsic::ppc_qpx_qvlfd: 14902 case Intrinsic::ppc_qpx_qvlfs: 14903 case Intrinsic::ppc_qpx_qvlfcd: 14904 case Intrinsic::ppc_qpx_qvlfcs: 14905 case Intrinsic::ppc_qpx_qvlfiwa: 14906 case Intrinsic::ppc_qpx_qvlfiwz: 14907 case Intrinsic::ppc_altivec_lvx: 14908 case Intrinsic::ppc_altivec_lvxl: 14909 case Intrinsic::ppc_altivec_lvebx: 14910 case Intrinsic::ppc_altivec_lvehx: 14911 case Intrinsic::ppc_altivec_lvewx: 14912 case Intrinsic::ppc_vsx_lxvd2x: 14913 case Intrinsic::ppc_vsx_lxvw4x: { 14914 EVT VT; 14915 switch (Intrinsic) { 14916 case Intrinsic::ppc_altivec_lvebx: 14917 VT = MVT::i8; 14918 break; 14919 case Intrinsic::ppc_altivec_lvehx: 14920 VT = MVT::i16; 14921 break; 14922 case Intrinsic::ppc_altivec_lvewx: 14923 VT = MVT::i32; 14924 break; 14925 case Intrinsic::ppc_vsx_lxvd2x: 14926 VT = MVT::v2f64; 14927 break; 14928 case Intrinsic::ppc_qpx_qvlfd: 14929 VT = MVT::v4f64; 14930 break; 14931 case Intrinsic::ppc_qpx_qvlfs: 14932 VT = MVT::v4f32; 14933 break; 14934 case Intrinsic::ppc_qpx_qvlfcd: 14935 VT = MVT::v2f64; 14936 break; 14937 case Intrinsic::ppc_qpx_qvlfcs: 14938 VT = MVT::v2f32; 14939 break; 14940 default: 14941 VT = MVT::v4i32; 14942 break; 14943 } 14944 14945 Info.opc = ISD::INTRINSIC_W_CHAIN; 14946 Info.memVT = VT; 14947 Info.ptrVal = I.getArgOperand(0); 14948 Info.offset = -VT.getStoreSize()+1; 14949 Info.size = 2*VT.getStoreSize()-1; 14950 Info.align = Align::None(); 14951 Info.flags = MachineMemOperand::MOLoad; 14952 return true; 14953 } 14954 case Intrinsic::ppc_qpx_qvlfda: 14955 case Intrinsic::ppc_qpx_qvlfsa: 14956 case Intrinsic::ppc_qpx_qvlfcda: 14957 case Intrinsic::ppc_qpx_qvlfcsa: 14958 case Intrinsic::ppc_qpx_qvlfiwaa: 14959 case Intrinsic::ppc_qpx_qvlfiwza: { 14960 EVT VT; 14961 switch (Intrinsic) { 14962 case Intrinsic::ppc_qpx_qvlfda: 14963 VT = MVT::v4f64; 14964 break; 14965 case Intrinsic::ppc_qpx_qvlfsa: 14966 VT = MVT::v4f32; 14967 break; 14968 case Intrinsic::ppc_qpx_qvlfcda: 14969 VT = MVT::v2f64; 14970 break; 14971 case Intrinsic::ppc_qpx_qvlfcsa: 14972 VT = MVT::v2f32; 14973 break; 14974 default: 14975 VT = MVT::v4i32; 14976 break; 14977 } 14978 14979 Info.opc = ISD::INTRINSIC_W_CHAIN; 14980 Info.memVT = VT; 14981 Info.ptrVal = I.getArgOperand(0); 14982 Info.offset = 0; 14983 Info.size = VT.getStoreSize(); 14984 Info.align = Align::None(); 14985 Info.flags = MachineMemOperand::MOLoad; 14986 return true; 14987 } 14988 case Intrinsic::ppc_qpx_qvstfd: 14989 case Intrinsic::ppc_qpx_qvstfs: 14990 case Intrinsic::ppc_qpx_qvstfcd: 14991 case Intrinsic::ppc_qpx_qvstfcs: 14992 case Intrinsic::ppc_qpx_qvstfiw: 14993 case Intrinsic::ppc_altivec_stvx: 14994 case Intrinsic::ppc_altivec_stvxl: 14995 case Intrinsic::ppc_altivec_stvebx: 14996 case Intrinsic::ppc_altivec_stvehx: 14997 case Intrinsic::ppc_altivec_stvewx: 14998 case Intrinsic::ppc_vsx_stxvd2x: 14999 case Intrinsic::ppc_vsx_stxvw4x: { 15000 EVT VT; 15001 switch (Intrinsic) { 15002 case Intrinsic::ppc_altivec_stvebx: 15003 VT = MVT::i8; 15004 break; 15005 case Intrinsic::ppc_altivec_stvehx: 15006 VT = MVT::i16; 15007 break; 15008 case Intrinsic::ppc_altivec_stvewx: 15009 VT = MVT::i32; 15010 break; 15011 case Intrinsic::ppc_vsx_stxvd2x: 15012 VT = MVT::v2f64; 15013 break; 15014 case Intrinsic::ppc_qpx_qvstfd: 15015 VT = MVT::v4f64; 15016 break; 15017 case Intrinsic::ppc_qpx_qvstfs: 15018 VT = MVT::v4f32; 15019 break; 15020 case Intrinsic::ppc_qpx_qvstfcd: 15021 VT = MVT::v2f64; 15022 break; 15023 case Intrinsic::ppc_qpx_qvstfcs: 15024 VT = MVT::v2f32; 15025 break; 15026 default: 15027 VT = MVT::v4i32; 15028 break; 15029 } 15030 15031 Info.opc = ISD::INTRINSIC_VOID; 15032 Info.memVT = VT; 15033 Info.ptrVal = I.getArgOperand(1); 15034 Info.offset = -VT.getStoreSize()+1; 15035 Info.size = 2*VT.getStoreSize()-1; 15036 Info.align = Align::None(); 15037 Info.flags = MachineMemOperand::MOStore; 15038 return true; 15039 } 15040 case Intrinsic::ppc_qpx_qvstfda: 15041 case Intrinsic::ppc_qpx_qvstfsa: 15042 case Intrinsic::ppc_qpx_qvstfcda: 15043 case Intrinsic::ppc_qpx_qvstfcsa: 15044 case Intrinsic::ppc_qpx_qvstfiwa: { 15045 EVT VT; 15046 switch (Intrinsic) { 15047 case Intrinsic::ppc_qpx_qvstfda: 15048 VT = MVT::v4f64; 15049 break; 15050 case Intrinsic::ppc_qpx_qvstfsa: 15051 VT = MVT::v4f32; 15052 break; 15053 case Intrinsic::ppc_qpx_qvstfcda: 15054 VT = MVT::v2f64; 15055 break; 15056 case Intrinsic::ppc_qpx_qvstfcsa: 15057 VT = MVT::v2f32; 15058 break; 15059 default: 15060 VT = MVT::v4i32; 15061 break; 15062 } 15063 15064 Info.opc = ISD::INTRINSIC_VOID; 15065 Info.memVT = VT; 15066 Info.ptrVal = I.getArgOperand(1); 15067 Info.offset = 0; 15068 Info.size = VT.getStoreSize(); 15069 Info.align = Align::None(); 15070 Info.flags = MachineMemOperand::MOStore; 15071 return true; 15072 } 15073 default: 15074 break; 15075 } 15076 15077 return false; 15078 } 15079 15080 /// getOptimalMemOpType - Returns the target specific optimal type for load 15081 /// and store operations as a result of memset, memcpy, and memmove 15082 /// lowering. If DstAlign is zero that means it's safe to destination 15083 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it 15084 /// means there isn't a need to check it against alignment requirement, 15085 /// probably because the source does not need to be loaded. If 'IsMemset' is 15086 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that 15087 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy 15088 /// source is constant so it does not need to be loaded. 15089 /// It returns EVT::Other if the type should be determined using generic 15090 /// target-independent logic. 15091 EVT PPCTargetLowering::getOptimalMemOpType( 15092 uint64_t Size, unsigned DstAlign, unsigned SrcAlign, bool IsMemset, 15093 bool ZeroMemset, bool MemcpyStrSrc, 15094 const AttributeList &FuncAttributes) const { 15095 if (getTargetMachine().getOptLevel() != CodeGenOpt::None) { 15096 // When expanding a memset, require at least two QPX instructions to cover 15097 // the cost of loading the value to be stored from the constant pool. 15098 if (Subtarget.hasQPX() && Size >= 32 && (!IsMemset || Size >= 64) && 15099 (!SrcAlign || SrcAlign >= 32) && (!DstAlign || DstAlign >= 32) && 15100 !FuncAttributes.hasFnAttribute(Attribute::NoImplicitFloat)) { 15101 return MVT::v4f64; 15102 } 15103 15104 // We should use Altivec/VSX loads and stores when available. For unaligned 15105 // addresses, unaligned VSX loads are only fast starting with the P8. 15106 if (Subtarget.hasAltivec() && Size >= 16 && 15107 (((!SrcAlign || SrcAlign >= 16) && (!DstAlign || DstAlign >= 16)) || 15108 ((IsMemset && Subtarget.hasVSX()) || Subtarget.hasP8Vector()))) 15109 return MVT::v4i32; 15110 } 15111 15112 if (Subtarget.isPPC64()) { 15113 return MVT::i64; 15114 } 15115 15116 return MVT::i32; 15117 } 15118 15119 /// Returns true if it is beneficial to convert a load of a constant 15120 /// to just the constant itself. 15121 bool PPCTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 15122 Type *Ty) const { 15123 assert(Ty->isIntegerTy()); 15124 15125 unsigned BitSize = Ty->getPrimitiveSizeInBits(); 15126 return !(BitSize == 0 || BitSize > 64); 15127 } 15128 15129 bool PPCTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const { 15130 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy()) 15131 return false; 15132 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits(); 15133 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits(); 15134 return NumBits1 == 64 && NumBits2 == 32; 15135 } 15136 15137 bool PPCTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const { 15138 if (!VT1.isInteger() || !VT2.isInteger()) 15139 return false; 15140 unsigned NumBits1 = VT1.getSizeInBits(); 15141 unsigned NumBits2 = VT2.getSizeInBits(); 15142 return NumBits1 == 64 && NumBits2 == 32; 15143 } 15144 15145 bool PPCTargetLowering::isZExtFree(SDValue Val, EVT VT2) const { 15146 // Generally speaking, zexts are not free, but they are free when they can be 15147 // folded with other operations. 15148 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Val)) { 15149 EVT MemVT = LD->getMemoryVT(); 15150 if ((MemVT == MVT::i1 || MemVT == MVT::i8 || MemVT == MVT::i16 || 15151 (Subtarget.isPPC64() && MemVT == MVT::i32)) && 15152 (LD->getExtensionType() == ISD::NON_EXTLOAD || 15153 LD->getExtensionType() == ISD::ZEXTLOAD)) 15154 return true; 15155 } 15156 15157 // FIXME: Add other cases... 15158 // - 32-bit shifts with a zext to i64 15159 // - zext after ctlz, bswap, etc. 15160 // - zext after and by a constant mask 15161 15162 return TargetLowering::isZExtFree(Val, VT2); 15163 } 15164 15165 bool PPCTargetLowering::isFPExtFree(EVT DestVT, EVT SrcVT) const { 15166 assert(DestVT.isFloatingPoint() && SrcVT.isFloatingPoint() && 15167 "invalid fpext types"); 15168 // Extending to float128 is not free. 15169 if (DestVT == MVT::f128) 15170 return false; 15171 return true; 15172 } 15173 15174 bool PPCTargetLowering::isLegalICmpImmediate(int64_t Imm) const { 15175 return isInt<16>(Imm) || isUInt<16>(Imm); 15176 } 15177 15178 bool PPCTargetLowering::isLegalAddImmediate(int64_t Imm) const { 15179 return isInt<16>(Imm) || isUInt<16>(Imm); 15180 } 15181 15182 bool PPCTargetLowering::allowsMisalignedMemoryAccesses(EVT VT, 15183 unsigned, 15184 unsigned, 15185 MachineMemOperand::Flags, 15186 bool *Fast) const { 15187 if (DisablePPCUnaligned) 15188 return false; 15189 15190 // PowerPC supports unaligned memory access for simple non-vector types. 15191 // Although accessing unaligned addresses is not as efficient as accessing 15192 // aligned addresses, it is generally more efficient than manual expansion, 15193 // and generally only traps for software emulation when crossing page 15194 // boundaries. 15195 15196 if (!VT.isSimple()) 15197 return false; 15198 15199 if (VT.isFloatingPoint() && !Subtarget.allowsUnalignedFPAccess()) 15200 return false; 15201 15202 if (VT.getSimpleVT().isVector()) { 15203 if (Subtarget.hasVSX()) { 15204 if (VT != MVT::v2f64 && VT != MVT::v2i64 && 15205 VT != MVT::v4f32 && VT != MVT::v4i32) 15206 return false; 15207 } else { 15208 return false; 15209 } 15210 } 15211 15212 if (VT == MVT::ppcf128) 15213 return false; 15214 15215 if (Fast) 15216 *Fast = true; 15217 15218 return true; 15219 } 15220 15221 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, 15222 EVT VT) const { 15223 VT = VT.getScalarType(); 15224 15225 if (!VT.isSimple()) 15226 return false; 15227 15228 switch (VT.getSimpleVT().SimpleTy) { 15229 case MVT::f32: 15230 case MVT::f64: 15231 return true; 15232 case MVT::f128: 15233 return (EnableQuadPrecision && Subtarget.hasP9Vector()); 15234 default: 15235 break; 15236 } 15237 15238 return false; 15239 } 15240 15241 const MCPhysReg * 15242 PPCTargetLowering::getScratchRegisters(CallingConv::ID) const { 15243 // LR is a callee-save register, but we must treat it as clobbered by any call 15244 // site. Hence we include LR in the scratch registers, which are in turn added 15245 // as implicit-defs for stackmaps and patchpoints. The same reasoning applies 15246 // to CTR, which is used by any indirect call. 15247 static const MCPhysReg ScratchRegs[] = { 15248 PPC::X12, PPC::LR8, PPC::CTR8, 0 15249 }; 15250 15251 return ScratchRegs; 15252 } 15253 15254 unsigned PPCTargetLowering::getExceptionPointerRegister( 15255 const Constant *PersonalityFn) const { 15256 return Subtarget.isPPC64() ? PPC::X3 : PPC::R3; 15257 } 15258 15259 unsigned PPCTargetLowering::getExceptionSelectorRegister( 15260 const Constant *PersonalityFn) const { 15261 return Subtarget.isPPC64() ? PPC::X4 : PPC::R4; 15262 } 15263 15264 bool 15265 PPCTargetLowering::shouldExpandBuildVectorWithShuffles( 15266 EVT VT , unsigned DefinedValues) const { 15267 if (VT == MVT::v2i64) 15268 return Subtarget.hasDirectMove(); // Don't need stack ops with direct moves 15269 15270 if (Subtarget.hasVSX() || Subtarget.hasQPX()) 15271 return true; 15272 15273 return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues); 15274 } 15275 15276 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const { 15277 if (DisableILPPref || Subtarget.enableMachineScheduler()) 15278 return TargetLowering::getSchedulingPreference(N); 15279 15280 return Sched::ILP; 15281 } 15282 15283 // Create a fast isel object. 15284 FastISel * 15285 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo, 15286 const TargetLibraryInfo *LibInfo) const { 15287 return PPC::createFastISel(FuncInfo, LibInfo); 15288 } 15289 15290 void PPCTargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const { 15291 if (!Subtarget.isPPC64()) return; 15292 15293 // Update IsSplitCSR in PPCFunctionInfo 15294 PPCFunctionInfo *PFI = Entry->getParent()->getInfo<PPCFunctionInfo>(); 15295 PFI->setIsSplitCSR(true); 15296 } 15297 15298 void PPCTargetLowering::insertCopiesSplitCSR( 15299 MachineBasicBlock *Entry, 15300 const SmallVectorImpl<MachineBasicBlock *> &Exits) const { 15301 const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo(); 15302 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent()); 15303 if (!IStart) 15304 return; 15305 15306 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 15307 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo(); 15308 MachineBasicBlock::iterator MBBI = Entry->begin(); 15309 for (const MCPhysReg *I = IStart; *I; ++I) { 15310 const TargetRegisterClass *RC = nullptr; 15311 if (PPC::G8RCRegClass.contains(*I)) 15312 RC = &PPC::G8RCRegClass; 15313 else if (PPC::F8RCRegClass.contains(*I)) 15314 RC = &PPC::F8RCRegClass; 15315 else if (PPC::CRRCRegClass.contains(*I)) 15316 RC = &PPC::CRRCRegClass; 15317 else if (PPC::VRRCRegClass.contains(*I)) 15318 RC = &PPC::VRRCRegClass; 15319 else 15320 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 15321 15322 Register NewVR = MRI->createVirtualRegister(RC); 15323 // Create copy from CSR to a virtual register. 15324 // FIXME: this currently does not emit CFI pseudo-instructions, it works 15325 // fine for CXX_FAST_TLS since the C++-style TLS access functions should be 15326 // nounwind. If we want to generalize this later, we may need to emit 15327 // CFI pseudo-instructions. 15328 assert(Entry->getParent()->getFunction().hasFnAttribute( 15329 Attribute::NoUnwind) && 15330 "Function should be nounwind in insertCopiesSplitCSR!"); 15331 Entry->addLiveIn(*I); 15332 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR) 15333 .addReg(*I); 15334 15335 // Insert the copy-back instructions right before the terminator. 15336 for (auto *Exit : Exits) 15337 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(), 15338 TII->get(TargetOpcode::COPY), *I) 15339 .addReg(NewVR); 15340 } 15341 } 15342 15343 // Override to enable LOAD_STACK_GUARD lowering on Linux. 15344 bool PPCTargetLowering::useLoadStackGuardNode() const { 15345 if (!Subtarget.isTargetLinux()) 15346 return TargetLowering::useLoadStackGuardNode(); 15347 return true; 15348 } 15349 15350 // Override to disable global variable loading on Linux. 15351 void PPCTargetLowering::insertSSPDeclarations(Module &M) const { 15352 if (!Subtarget.isTargetLinux()) 15353 return TargetLowering::insertSSPDeclarations(M); 15354 } 15355 15356 bool PPCTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT, 15357 bool ForCodeSize) const { 15358 if (!VT.isSimple() || !Subtarget.hasVSX()) 15359 return false; 15360 15361 switch(VT.getSimpleVT().SimpleTy) { 15362 default: 15363 // For FP types that are currently not supported by PPC backend, return 15364 // false. Examples: f16, f80. 15365 return false; 15366 case MVT::f32: 15367 case MVT::f64: 15368 case MVT::ppcf128: 15369 return Imm.isPosZero(); 15370 } 15371 } 15372 15373 // For vector shift operation op, fold 15374 // (op x, (and y, ((1 << numbits(x)) - 1))) -> (target op x, y) 15375 static SDValue stripModuloOnShift(const TargetLowering &TLI, SDNode *N, 15376 SelectionDAG &DAG) { 15377 SDValue N0 = N->getOperand(0); 15378 SDValue N1 = N->getOperand(1); 15379 EVT VT = N0.getValueType(); 15380 unsigned OpSizeInBits = VT.getScalarSizeInBits(); 15381 unsigned Opcode = N->getOpcode(); 15382 unsigned TargetOpcode; 15383 15384 switch (Opcode) { 15385 default: 15386 llvm_unreachable("Unexpected shift operation"); 15387 case ISD::SHL: 15388 TargetOpcode = PPCISD::SHL; 15389 break; 15390 case ISD::SRL: 15391 TargetOpcode = PPCISD::SRL; 15392 break; 15393 case ISD::SRA: 15394 TargetOpcode = PPCISD::SRA; 15395 break; 15396 } 15397 15398 if (VT.isVector() && TLI.isOperationLegal(Opcode, VT) && 15399 N1->getOpcode() == ISD::AND) 15400 if (ConstantSDNode *Mask = isConstOrConstSplat(N1->getOperand(1))) 15401 if (Mask->getZExtValue() == OpSizeInBits - 1) 15402 return DAG.getNode(TargetOpcode, SDLoc(N), VT, N0, N1->getOperand(0)); 15403 15404 return SDValue(); 15405 } 15406 15407 SDValue PPCTargetLowering::combineSHL(SDNode *N, DAGCombinerInfo &DCI) const { 15408 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG)) 15409 return Value; 15410 15411 SDValue N0 = N->getOperand(0); 15412 ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N->getOperand(1)); 15413 if (!Subtarget.isISA3_0() || 15414 N0.getOpcode() != ISD::SIGN_EXTEND || 15415 N0.getOperand(0).getValueType() != MVT::i32 || 15416 CN1 == nullptr || N->getValueType(0) != MVT::i64) 15417 return SDValue(); 15418 15419 // We can't save an operation here if the value is already extended, and 15420 // the existing shift is easier to combine. 15421 SDValue ExtsSrc = N0.getOperand(0); 15422 if (ExtsSrc.getOpcode() == ISD::TRUNCATE && 15423 ExtsSrc.getOperand(0).getOpcode() == ISD::AssertSext) 15424 return SDValue(); 15425 15426 SDLoc DL(N0); 15427 SDValue ShiftBy = SDValue(CN1, 0); 15428 // We want the shift amount to be i32 on the extswli, but the shift could 15429 // have an i64. 15430 if (ShiftBy.getValueType() == MVT::i64) 15431 ShiftBy = DCI.DAG.getConstant(CN1->getZExtValue(), DL, MVT::i32); 15432 15433 return DCI.DAG.getNode(PPCISD::EXTSWSLI, DL, MVT::i64, N0->getOperand(0), 15434 ShiftBy); 15435 } 15436 15437 SDValue PPCTargetLowering::combineSRA(SDNode *N, DAGCombinerInfo &DCI) const { 15438 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG)) 15439 return Value; 15440 15441 return SDValue(); 15442 } 15443 15444 SDValue PPCTargetLowering::combineSRL(SDNode *N, DAGCombinerInfo &DCI) const { 15445 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG)) 15446 return Value; 15447 15448 return SDValue(); 15449 } 15450 15451 // Transform (add X, (zext(setne Z, C))) -> (addze X, (addic (addi Z, -C), -1)) 15452 // Transform (add X, (zext(sete Z, C))) -> (addze X, (subfic (addi Z, -C), 0)) 15453 // When C is zero, the equation (addi Z, -C) can be simplified to Z 15454 // Requirement: -C in [-32768, 32767], X and Z are MVT::i64 types 15455 static SDValue combineADDToADDZE(SDNode *N, SelectionDAG &DAG, 15456 const PPCSubtarget &Subtarget) { 15457 if (!Subtarget.isPPC64()) 15458 return SDValue(); 15459 15460 SDValue LHS = N->getOperand(0); 15461 SDValue RHS = N->getOperand(1); 15462 15463 auto isZextOfCompareWithConstant = [](SDValue Op) { 15464 if (Op.getOpcode() != ISD::ZERO_EXTEND || !Op.hasOneUse() || 15465 Op.getValueType() != MVT::i64) 15466 return false; 15467 15468 SDValue Cmp = Op.getOperand(0); 15469 if (Cmp.getOpcode() != ISD::SETCC || !Cmp.hasOneUse() || 15470 Cmp.getOperand(0).getValueType() != MVT::i64) 15471 return false; 15472 15473 if (auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1))) { 15474 int64_t NegConstant = 0 - Constant->getSExtValue(); 15475 // Due to the limitations of the addi instruction, 15476 // -C is required to be [-32768, 32767]. 15477 return isInt<16>(NegConstant); 15478 } 15479 15480 return false; 15481 }; 15482 15483 bool LHSHasPattern = isZextOfCompareWithConstant(LHS); 15484 bool RHSHasPattern = isZextOfCompareWithConstant(RHS); 15485 15486 // If there is a pattern, canonicalize a zext operand to the RHS. 15487 if (LHSHasPattern && !RHSHasPattern) 15488 std::swap(LHS, RHS); 15489 else if (!LHSHasPattern && !RHSHasPattern) 15490 return SDValue(); 15491 15492 SDLoc DL(N); 15493 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Glue); 15494 SDValue Cmp = RHS.getOperand(0); 15495 SDValue Z = Cmp.getOperand(0); 15496 auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1)); 15497 15498 assert(Constant && "Constant Should not be a null pointer."); 15499 int64_t NegConstant = 0 - Constant->getSExtValue(); 15500 15501 switch(cast<CondCodeSDNode>(Cmp.getOperand(2))->get()) { 15502 default: break; 15503 case ISD::SETNE: { 15504 // when C == 0 15505 // --> addze X, (addic Z, -1).carry 15506 // / 15507 // add X, (zext(setne Z, C))-- 15508 // \ when -32768 <= -C <= 32767 && C != 0 15509 // --> addze X, (addic (addi Z, -C), -1).carry 15510 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z, 15511 DAG.getConstant(NegConstant, DL, MVT::i64)); 15512 SDValue AddOrZ = NegConstant != 0 ? Add : Z; 15513 SDValue Addc = DAG.getNode(ISD::ADDC, DL, DAG.getVTList(MVT::i64, MVT::Glue), 15514 AddOrZ, DAG.getConstant(-1ULL, DL, MVT::i64)); 15515 return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64), 15516 SDValue(Addc.getNode(), 1)); 15517 } 15518 case ISD::SETEQ: { 15519 // when C == 0 15520 // --> addze X, (subfic Z, 0).carry 15521 // / 15522 // add X, (zext(sete Z, C))-- 15523 // \ when -32768 <= -C <= 32767 && C != 0 15524 // --> addze X, (subfic (addi Z, -C), 0).carry 15525 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z, 15526 DAG.getConstant(NegConstant, DL, MVT::i64)); 15527 SDValue AddOrZ = NegConstant != 0 ? Add : Z; 15528 SDValue Subc = DAG.getNode(ISD::SUBC, DL, DAG.getVTList(MVT::i64, MVT::Glue), 15529 DAG.getConstant(0, DL, MVT::i64), AddOrZ); 15530 return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64), 15531 SDValue(Subc.getNode(), 1)); 15532 } 15533 } 15534 15535 return SDValue(); 15536 } 15537 15538 SDValue PPCTargetLowering::combineADD(SDNode *N, DAGCombinerInfo &DCI) const { 15539 if (auto Value = combineADDToADDZE(N, DCI.DAG, Subtarget)) 15540 return Value; 15541 15542 return SDValue(); 15543 } 15544 15545 // Detect TRUNCATE operations on bitcasts of float128 values. 15546 // What we are looking for here is the situtation where we extract a subset 15547 // of bits from a 128 bit float. 15548 // This can be of two forms: 15549 // 1) BITCAST of f128 feeding TRUNCATE 15550 // 2) BITCAST of f128 feeding SRL (a shift) feeding TRUNCATE 15551 // The reason this is required is because we do not have a legal i128 type 15552 // and so we want to prevent having to store the f128 and then reload part 15553 // of it. 15554 SDValue PPCTargetLowering::combineTRUNCATE(SDNode *N, 15555 DAGCombinerInfo &DCI) const { 15556 // If we are using CRBits then try that first. 15557 if (Subtarget.useCRBits()) { 15558 // Check if CRBits did anything and return that if it did. 15559 if (SDValue CRTruncValue = DAGCombineTruncBoolExt(N, DCI)) 15560 return CRTruncValue; 15561 } 15562 15563 SDLoc dl(N); 15564 SDValue Op0 = N->getOperand(0); 15565 15566 // Looking for a truncate of i128 to i64. 15567 if (Op0.getValueType() != MVT::i128 || N->getValueType(0) != MVT::i64) 15568 return SDValue(); 15569 15570 int EltToExtract = DCI.DAG.getDataLayout().isBigEndian() ? 1 : 0; 15571 15572 // SRL feeding TRUNCATE. 15573 if (Op0.getOpcode() == ISD::SRL) { 15574 ConstantSDNode *ConstNode = dyn_cast<ConstantSDNode>(Op0.getOperand(1)); 15575 // The right shift has to be by 64 bits. 15576 if (!ConstNode || ConstNode->getZExtValue() != 64) 15577 return SDValue(); 15578 15579 // Switch the element number to extract. 15580 EltToExtract = EltToExtract ? 0 : 1; 15581 // Update Op0 past the SRL. 15582 Op0 = Op0.getOperand(0); 15583 } 15584 15585 // BITCAST feeding a TRUNCATE possibly via SRL. 15586 if (Op0.getOpcode() == ISD::BITCAST && 15587 Op0.getValueType() == MVT::i128 && 15588 Op0.getOperand(0).getValueType() == MVT::f128) { 15589 SDValue Bitcast = DCI.DAG.getBitcast(MVT::v2i64, Op0.getOperand(0)); 15590 return DCI.DAG.getNode( 15591 ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Bitcast, 15592 DCI.DAG.getTargetConstant(EltToExtract, dl, MVT::i32)); 15593 } 15594 return SDValue(); 15595 } 15596 15597 SDValue PPCTargetLowering::combineMUL(SDNode *N, DAGCombinerInfo &DCI) const { 15598 SelectionDAG &DAG = DCI.DAG; 15599 15600 ConstantSDNode *ConstOpOrElement = isConstOrConstSplat(N->getOperand(1)); 15601 if (!ConstOpOrElement) 15602 return SDValue(); 15603 15604 // An imul is usually smaller than the alternative sequence for legal type. 15605 if (DAG.getMachineFunction().getFunction().hasMinSize() && 15606 isOperationLegal(ISD::MUL, N->getValueType(0))) 15607 return SDValue(); 15608 15609 auto IsProfitable = [this](bool IsNeg, bool IsAddOne, EVT VT) -> bool { 15610 switch (this->Subtarget.getCPUDirective()) { 15611 default: 15612 // TODO: enhance the condition for subtarget before pwr8 15613 return false; 15614 case PPC::DIR_PWR8: 15615 // type mul add shl 15616 // scalar 4 1 1 15617 // vector 7 2 2 15618 return true; 15619 case PPC::DIR_PWR9: 15620 case PPC::DIR_PWR_FUTURE: 15621 // type mul add shl 15622 // scalar 5 2 2 15623 // vector 7 2 2 15624 15625 // The cycle RATIO of related operations are showed as a table above. 15626 // Because mul is 5(scalar)/7(vector), add/sub/shl are all 2 for both 15627 // scalar and vector type. For 2 instrs patterns, add/sub + shl 15628 // are 4, it is always profitable; but for 3 instrs patterns 15629 // (mul x, -(2^N + 1)) => -(add (shl x, N), x), sub + add + shl are 6. 15630 // So we should only do it for vector type. 15631 return IsAddOne && IsNeg ? VT.isVector() : true; 15632 } 15633 }; 15634 15635 EVT VT = N->getValueType(0); 15636 SDLoc DL(N); 15637 15638 const APInt &MulAmt = ConstOpOrElement->getAPIntValue(); 15639 bool IsNeg = MulAmt.isNegative(); 15640 APInt MulAmtAbs = MulAmt.abs(); 15641 15642 if ((MulAmtAbs - 1).isPowerOf2()) { 15643 // (mul x, 2^N + 1) => (add (shl x, N), x) 15644 // (mul x, -(2^N + 1)) => -(add (shl x, N), x) 15645 15646 if (!IsProfitable(IsNeg, true, VT)) 15647 return SDValue(); 15648 15649 SDValue Op0 = N->getOperand(0); 15650 SDValue Op1 = 15651 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0), 15652 DAG.getConstant((MulAmtAbs - 1).logBase2(), DL, VT)); 15653 SDValue Res = DAG.getNode(ISD::ADD, DL, VT, Op0, Op1); 15654 15655 if (!IsNeg) 15656 return Res; 15657 15658 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Res); 15659 } else if ((MulAmtAbs + 1).isPowerOf2()) { 15660 // (mul x, 2^N - 1) => (sub (shl x, N), x) 15661 // (mul x, -(2^N - 1)) => (sub x, (shl x, N)) 15662 15663 if (!IsProfitable(IsNeg, false, VT)) 15664 return SDValue(); 15665 15666 SDValue Op0 = N->getOperand(0); 15667 SDValue Op1 = 15668 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0), 15669 DAG.getConstant((MulAmtAbs + 1).logBase2(), DL, VT)); 15670 15671 if (!IsNeg) 15672 return DAG.getNode(ISD::SUB, DL, VT, Op1, Op0); 15673 else 15674 return DAG.getNode(ISD::SUB, DL, VT, Op0, Op1); 15675 15676 } else { 15677 return SDValue(); 15678 } 15679 } 15680 15681 bool PPCTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 15682 // Only duplicate to increase tail-calls for the 64bit SysV ABIs. 15683 if (!Subtarget.is64BitELFABI()) 15684 return false; 15685 15686 // If not a tail call then no need to proceed. 15687 if (!CI->isTailCall()) 15688 return false; 15689 15690 // If sibling calls have been disabled and tail-calls aren't guaranteed 15691 // there is no reason to duplicate. 15692 auto &TM = getTargetMachine(); 15693 if (!TM.Options.GuaranteedTailCallOpt && DisableSCO) 15694 return false; 15695 15696 // Can't tail call a function called indirectly, or if it has variadic args. 15697 const Function *Callee = CI->getCalledFunction(); 15698 if (!Callee || Callee->isVarArg()) 15699 return false; 15700 15701 // Make sure the callee and caller calling conventions are eligible for tco. 15702 const Function *Caller = CI->getParent()->getParent(); 15703 if (!areCallingConvEligibleForTCO_64SVR4(Caller->getCallingConv(), 15704 CI->getCallingConv())) 15705 return false; 15706 15707 // If the function is local then we have a good chance at tail-calling it 15708 return getTargetMachine().shouldAssumeDSOLocal(*Caller->getParent(), Callee); 15709 } 15710 15711 bool PPCTargetLowering::hasBitPreservingFPLogic(EVT VT) const { 15712 if (!Subtarget.hasVSX()) 15713 return false; 15714 if (Subtarget.hasP9Vector() && VT == MVT::f128) 15715 return true; 15716 return VT == MVT::f32 || VT == MVT::f64 || 15717 VT == MVT::v4f32 || VT == MVT::v2f64; 15718 } 15719 15720 bool PPCTargetLowering:: 15721 isMaskAndCmp0FoldingBeneficial(const Instruction &AndI) const { 15722 const Value *Mask = AndI.getOperand(1); 15723 // If the mask is suitable for andi. or andis. we should sink the and. 15724 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Mask)) { 15725 // Can't handle constants wider than 64-bits. 15726 if (CI->getBitWidth() > 64) 15727 return false; 15728 int64_t ConstVal = CI->getZExtValue(); 15729 return isUInt<16>(ConstVal) || 15730 (isUInt<16>(ConstVal >> 16) && !(ConstVal & 0xFFFF)); 15731 } 15732 15733 // For non-constant masks, we can always use the record-form and. 15734 return true; 15735 } 15736 15737 // Transform (abs (sub (zext a), (zext b))) to (vabsd a b 0) 15738 // Transform (abs (sub (zext a), (zext_invec b))) to (vabsd a b 0) 15739 // Transform (abs (sub (zext_invec a), (zext_invec b))) to (vabsd a b 0) 15740 // Transform (abs (sub (zext_invec a), (zext b))) to (vabsd a b 0) 15741 // Transform (abs (sub a, b) to (vabsd a b 1)) if a & b of type v4i32 15742 SDValue PPCTargetLowering::combineABS(SDNode *N, DAGCombinerInfo &DCI) const { 15743 assert((N->getOpcode() == ISD::ABS) && "Need ABS node here"); 15744 assert(Subtarget.hasP9Altivec() && 15745 "Only combine this when P9 altivec supported!"); 15746 EVT VT = N->getValueType(0); 15747 if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8) 15748 return SDValue(); 15749 15750 SelectionDAG &DAG = DCI.DAG; 15751 SDLoc dl(N); 15752 if (N->getOperand(0).getOpcode() == ISD::SUB) { 15753 // Even for signed integers, if it's known to be positive (as signed 15754 // integer) due to zero-extended inputs. 15755 unsigned SubOpcd0 = N->getOperand(0)->getOperand(0).getOpcode(); 15756 unsigned SubOpcd1 = N->getOperand(0)->getOperand(1).getOpcode(); 15757 if ((SubOpcd0 == ISD::ZERO_EXTEND || 15758 SubOpcd0 == ISD::ZERO_EXTEND_VECTOR_INREG) && 15759 (SubOpcd1 == ISD::ZERO_EXTEND || 15760 SubOpcd1 == ISD::ZERO_EXTEND_VECTOR_INREG)) { 15761 return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(), 15762 N->getOperand(0)->getOperand(0), 15763 N->getOperand(0)->getOperand(1), 15764 DAG.getTargetConstant(0, dl, MVT::i32)); 15765 } 15766 15767 // For type v4i32, it can be optimized with xvnegsp + vabsduw 15768 if (N->getOperand(0).getValueType() == MVT::v4i32 && 15769 N->getOperand(0).hasOneUse()) { 15770 return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(), 15771 N->getOperand(0)->getOperand(0), 15772 N->getOperand(0)->getOperand(1), 15773 DAG.getTargetConstant(1, dl, MVT::i32)); 15774 } 15775 } 15776 15777 return SDValue(); 15778 } 15779 15780 // For type v4i32/v8ii16/v16i8, transform 15781 // from (vselect (setcc a, b, setugt), (sub a, b), (sub b, a)) to (vabsd a, b) 15782 // from (vselect (setcc a, b, setuge), (sub a, b), (sub b, a)) to (vabsd a, b) 15783 // from (vselect (setcc a, b, setult), (sub b, a), (sub a, b)) to (vabsd a, b) 15784 // from (vselect (setcc a, b, setule), (sub b, a), (sub a, b)) to (vabsd a, b) 15785 SDValue PPCTargetLowering::combineVSelect(SDNode *N, 15786 DAGCombinerInfo &DCI) const { 15787 assert((N->getOpcode() == ISD::VSELECT) && "Need VSELECT node here"); 15788 assert(Subtarget.hasP9Altivec() && 15789 "Only combine this when P9 altivec supported!"); 15790 15791 SelectionDAG &DAG = DCI.DAG; 15792 SDLoc dl(N); 15793 SDValue Cond = N->getOperand(0); 15794 SDValue TrueOpnd = N->getOperand(1); 15795 SDValue FalseOpnd = N->getOperand(2); 15796 EVT VT = N->getOperand(1).getValueType(); 15797 15798 if (Cond.getOpcode() != ISD::SETCC || TrueOpnd.getOpcode() != ISD::SUB || 15799 FalseOpnd.getOpcode() != ISD::SUB) 15800 return SDValue(); 15801 15802 // ABSD only available for type v4i32/v8i16/v16i8 15803 if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8) 15804 return SDValue(); 15805 15806 // At least to save one more dependent computation 15807 if (!(Cond.hasOneUse() || TrueOpnd.hasOneUse() || FalseOpnd.hasOneUse())) 15808 return SDValue(); 15809 15810 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get(); 15811 15812 // Can only handle unsigned comparison here 15813 switch (CC) { 15814 default: 15815 return SDValue(); 15816 case ISD::SETUGT: 15817 case ISD::SETUGE: 15818 break; 15819 case ISD::SETULT: 15820 case ISD::SETULE: 15821 std::swap(TrueOpnd, FalseOpnd); 15822 break; 15823 } 15824 15825 SDValue CmpOpnd1 = Cond.getOperand(0); 15826 SDValue CmpOpnd2 = Cond.getOperand(1); 15827 15828 // SETCC CmpOpnd1 CmpOpnd2 cond 15829 // TrueOpnd = CmpOpnd1 - CmpOpnd2 15830 // FalseOpnd = CmpOpnd2 - CmpOpnd1 15831 if (TrueOpnd.getOperand(0) == CmpOpnd1 && 15832 TrueOpnd.getOperand(1) == CmpOpnd2 && 15833 FalseOpnd.getOperand(0) == CmpOpnd2 && 15834 FalseOpnd.getOperand(1) == CmpOpnd1) { 15835 return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(1).getValueType(), 15836 CmpOpnd1, CmpOpnd2, 15837 DAG.getTargetConstant(0, dl, MVT::i32)); 15838 } 15839 15840 return SDValue(); 15841 } 15842