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::FRINT, MVT::v2f64, Legal); 803 setOperationAction(ISD::FROUND, MVT::v2f64, Legal); 804 setOperationAction(ISD::FROUND, MVT::f64, Legal); 805 setOperationAction(ISD::FRINT, MVT::f64, Legal); 806 807 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal); 808 setOperationAction(ISD::FRINT, MVT::v4f32, Legal); 809 setOperationAction(ISD::FROUND, MVT::v4f32, Legal); 810 setOperationAction(ISD::FROUND, MVT::f32, Legal); 811 setOperationAction(ISD::FRINT, MVT::f32, Legal); 812 813 setOperationAction(ISD::MUL, MVT::v2f64, Legal); 814 setOperationAction(ISD::FMA, MVT::v2f64, Legal); 815 816 setOperationAction(ISD::FDIV, MVT::v2f64, Legal); 817 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal); 818 819 // Share the Altivec comparison restrictions. 820 setCondCodeAction(ISD::SETUO, MVT::v2f64, Expand); 821 setCondCodeAction(ISD::SETUEQ, MVT::v2f64, Expand); 822 setCondCodeAction(ISD::SETO, MVT::v2f64, Expand); 823 setCondCodeAction(ISD::SETONE, MVT::v2f64, Expand); 824 825 setOperationAction(ISD::LOAD, MVT::v2f64, Legal); 826 setOperationAction(ISD::STORE, MVT::v2f64, Legal); 827 828 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Legal); 829 830 if (Subtarget.hasP8Vector()) 831 addRegisterClass(MVT::f32, &PPC::VSSRCRegClass); 832 833 addRegisterClass(MVT::f64, &PPC::VSFRCRegClass); 834 835 addRegisterClass(MVT::v4i32, &PPC::VSRCRegClass); 836 addRegisterClass(MVT::v4f32, &PPC::VSRCRegClass); 837 addRegisterClass(MVT::v2f64, &PPC::VSRCRegClass); 838 839 if (Subtarget.hasP8Altivec()) { 840 setOperationAction(ISD::SHL, MVT::v2i64, Legal); 841 setOperationAction(ISD::SRA, MVT::v2i64, Legal); 842 setOperationAction(ISD::SRL, MVT::v2i64, Legal); 843 844 // 128 bit shifts can be accomplished via 3 instructions for SHL and 845 // SRL, but not for SRA because of the instructions available: 846 // VS{RL} and VS{RL}O. However due to direct move costs, it's not worth 847 // doing 848 setOperationAction(ISD::SHL, MVT::v1i128, Expand); 849 setOperationAction(ISD::SRL, MVT::v1i128, Expand); 850 setOperationAction(ISD::SRA, MVT::v1i128, Expand); 851 852 setOperationAction(ISD::SETCC, MVT::v2i64, Legal); 853 } 854 else { 855 setOperationAction(ISD::SHL, MVT::v2i64, Expand); 856 setOperationAction(ISD::SRA, MVT::v2i64, Expand); 857 setOperationAction(ISD::SRL, MVT::v2i64, Expand); 858 859 setOperationAction(ISD::SETCC, MVT::v2i64, Custom); 860 861 // VSX v2i64 only supports non-arithmetic operations. 862 setOperationAction(ISD::ADD, MVT::v2i64, Expand); 863 setOperationAction(ISD::SUB, MVT::v2i64, Expand); 864 } 865 866 setOperationAction(ISD::LOAD, MVT::v2i64, Promote); 867 AddPromotedToType (ISD::LOAD, MVT::v2i64, MVT::v2f64); 868 setOperationAction(ISD::STORE, MVT::v2i64, Promote); 869 AddPromotedToType (ISD::STORE, MVT::v2i64, MVT::v2f64); 870 871 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Legal); 872 873 setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal); 874 setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal); 875 setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal); 876 setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal); 877 878 // Custom handling for partial vectors of integers converted to 879 // floating point. We already have optimal handling for v2i32 through 880 // the DAG combine, so those aren't necessary. 881 setOperationAction(ISD::UINT_TO_FP, MVT::v2i8, Custom); 882 setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Custom); 883 setOperationAction(ISD::UINT_TO_FP, MVT::v2i16, Custom); 884 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom); 885 setOperationAction(ISD::SINT_TO_FP, MVT::v2i8, Custom); 886 setOperationAction(ISD::SINT_TO_FP, MVT::v4i8, Custom); 887 setOperationAction(ISD::SINT_TO_FP, MVT::v2i16, Custom); 888 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom); 889 890 setOperationAction(ISD::FNEG, MVT::v4f32, Legal); 891 setOperationAction(ISD::FNEG, MVT::v2f64, Legal); 892 setOperationAction(ISD::FABS, MVT::v4f32, Legal); 893 setOperationAction(ISD::FABS, MVT::v2f64, Legal); 894 setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Legal); 895 setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Legal); 896 897 if (Subtarget.hasDirectMove()) 898 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom); 899 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom); 900 901 addRegisterClass(MVT::v2i64, &PPC::VSRCRegClass); 902 } 903 904 if (Subtarget.hasP8Altivec()) { 905 addRegisterClass(MVT::v2i64, &PPC::VRRCRegClass); 906 addRegisterClass(MVT::v1i128, &PPC::VRRCRegClass); 907 } 908 909 if (Subtarget.hasP9Vector()) { 910 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom); 911 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom); 912 913 // 128 bit shifts can be accomplished via 3 instructions for SHL and 914 // SRL, but not for SRA because of the instructions available: 915 // VS{RL} and VS{RL}O. 916 setOperationAction(ISD::SHL, MVT::v1i128, Legal); 917 setOperationAction(ISD::SRL, MVT::v1i128, Legal); 918 setOperationAction(ISD::SRA, MVT::v1i128, Expand); 919 920 if (EnableQuadPrecision) { 921 addRegisterClass(MVT::f128, &PPC::VRRCRegClass); 922 setOperationAction(ISD::FADD, MVT::f128, Legal); 923 setOperationAction(ISD::FSUB, MVT::f128, Legal); 924 setOperationAction(ISD::FDIV, MVT::f128, Legal); 925 setOperationAction(ISD::FMUL, MVT::f128, Legal); 926 setOperationAction(ISD::FP_EXTEND, MVT::f128, Legal); 927 // No extending loads to f128 on PPC. 928 for (MVT FPT : MVT::fp_valuetypes()) 929 setLoadExtAction(ISD::EXTLOAD, MVT::f128, FPT, Expand); 930 setOperationAction(ISD::FMA, MVT::f128, Legal); 931 setCondCodeAction(ISD::SETULT, MVT::f128, Expand); 932 setCondCodeAction(ISD::SETUGT, MVT::f128, Expand); 933 setCondCodeAction(ISD::SETUEQ, MVT::f128, Expand); 934 setCondCodeAction(ISD::SETOGE, MVT::f128, Expand); 935 setCondCodeAction(ISD::SETOLE, MVT::f128, Expand); 936 setCondCodeAction(ISD::SETONE, MVT::f128, Expand); 937 938 setOperationAction(ISD::FTRUNC, MVT::f128, Legal); 939 setOperationAction(ISD::FRINT, MVT::f128, Legal); 940 setOperationAction(ISD::FFLOOR, MVT::f128, Legal); 941 setOperationAction(ISD::FCEIL, MVT::f128, Legal); 942 setOperationAction(ISD::FNEARBYINT, MVT::f128, Legal); 943 setOperationAction(ISD::FROUND, MVT::f128, Legal); 944 945 setOperationAction(ISD::SELECT, MVT::f128, Expand); 946 setOperationAction(ISD::FP_ROUND, MVT::f64, Legal); 947 setOperationAction(ISD::FP_ROUND, MVT::f32, Legal); 948 setTruncStoreAction(MVT::f128, MVT::f64, Expand); 949 setTruncStoreAction(MVT::f128, MVT::f32, Expand); 950 setOperationAction(ISD::BITCAST, MVT::i128, Custom); 951 // No implementation for these ops for PowerPC. 952 setOperationAction(ISD::FSIN , MVT::f128, Expand); 953 setOperationAction(ISD::FCOS , MVT::f128, Expand); 954 setOperationAction(ISD::FPOW, MVT::f128, Expand); 955 setOperationAction(ISD::FPOWI, MVT::f128, Expand); 956 setOperationAction(ISD::FREM, MVT::f128, Expand); 957 } 958 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom); 959 setOperationAction(ISD::BSWAP, MVT::v8i16, Legal); 960 setOperationAction(ISD::BSWAP, MVT::v4i32, Legal); 961 setOperationAction(ISD::BSWAP, MVT::v2i64, Legal); 962 setOperationAction(ISD::BSWAP, MVT::v1i128, Legal); 963 } 964 965 if (Subtarget.hasP9Altivec()) { 966 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom); 967 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom); 968 969 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Legal); 970 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Legal); 971 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i32, Legal); 972 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Legal); 973 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Legal); 974 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i32, Legal); 975 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i64, Legal); 976 } 977 } 978 979 if (Subtarget.hasQPX()) { 980 setOperationAction(ISD::FADD, MVT::v4f64, Legal); 981 setOperationAction(ISD::FSUB, MVT::v4f64, Legal); 982 setOperationAction(ISD::FMUL, MVT::v4f64, Legal); 983 setOperationAction(ISD::FREM, MVT::v4f64, Expand); 984 985 setOperationAction(ISD::FCOPYSIGN, MVT::v4f64, Legal); 986 setOperationAction(ISD::FGETSIGN, MVT::v4f64, Expand); 987 988 setOperationAction(ISD::LOAD , MVT::v4f64, Custom); 989 setOperationAction(ISD::STORE , MVT::v4f64, Custom); 990 991 setTruncStoreAction(MVT::v4f64, MVT::v4f32, Custom); 992 setLoadExtAction(ISD::EXTLOAD, MVT::v4f64, MVT::v4f32, Custom); 993 994 if (!Subtarget.useCRBits()) 995 setOperationAction(ISD::SELECT, MVT::v4f64, Expand); 996 setOperationAction(ISD::VSELECT, MVT::v4f64, Legal); 997 998 setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f64, Legal); 999 setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f64, Expand); 1000 setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f64, Expand); 1001 setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f64, Expand); 1002 setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f64, Custom); 1003 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f64, Legal); 1004 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f64, Custom); 1005 1006 setOperationAction(ISD::FP_TO_SINT , MVT::v4f64, Legal); 1007 setOperationAction(ISD::FP_TO_UINT , MVT::v4f64, Expand); 1008 1009 setOperationAction(ISD::FP_ROUND , MVT::v4f32, Legal); 1010 setOperationAction(ISD::FP_EXTEND, MVT::v4f64, Legal); 1011 1012 setOperationAction(ISD::FNEG , MVT::v4f64, Legal); 1013 setOperationAction(ISD::FABS , MVT::v4f64, Legal); 1014 setOperationAction(ISD::FSIN , MVT::v4f64, Expand); 1015 setOperationAction(ISD::FCOS , MVT::v4f64, Expand); 1016 setOperationAction(ISD::FPOW , MVT::v4f64, Expand); 1017 setOperationAction(ISD::FLOG , MVT::v4f64, Expand); 1018 setOperationAction(ISD::FLOG2 , MVT::v4f64, Expand); 1019 setOperationAction(ISD::FLOG10 , MVT::v4f64, Expand); 1020 setOperationAction(ISD::FEXP , MVT::v4f64, Expand); 1021 setOperationAction(ISD::FEXP2 , MVT::v4f64, Expand); 1022 1023 setOperationAction(ISD::FMINNUM, MVT::v4f64, Legal); 1024 setOperationAction(ISD::FMAXNUM, MVT::v4f64, Legal); 1025 1026 setIndexedLoadAction(ISD::PRE_INC, MVT::v4f64, Legal); 1027 setIndexedStoreAction(ISD::PRE_INC, MVT::v4f64, Legal); 1028 1029 addRegisterClass(MVT::v4f64, &PPC::QFRCRegClass); 1030 1031 setOperationAction(ISD::FADD, MVT::v4f32, Legal); 1032 setOperationAction(ISD::FSUB, MVT::v4f32, Legal); 1033 setOperationAction(ISD::FMUL, MVT::v4f32, Legal); 1034 setOperationAction(ISD::FREM, MVT::v4f32, Expand); 1035 1036 setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Legal); 1037 setOperationAction(ISD::FGETSIGN, MVT::v4f32, Expand); 1038 1039 setOperationAction(ISD::LOAD , MVT::v4f32, Custom); 1040 setOperationAction(ISD::STORE , MVT::v4f32, Custom); 1041 1042 if (!Subtarget.useCRBits()) 1043 setOperationAction(ISD::SELECT, MVT::v4f32, Expand); 1044 setOperationAction(ISD::VSELECT, MVT::v4f32, Legal); 1045 1046 setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f32, Legal); 1047 setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f32, Expand); 1048 setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f32, Expand); 1049 setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f32, Expand); 1050 setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f32, Custom); 1051 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal); 1052 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom); 1053 1054 setOperationAction(ISD::FP_TO_SINT , MVT::v4f32, Legal); 1055 setOperationAction(ISD::FP_TO_UINT , MVT::v4f32, Expand); 1056 1057 setOperationAction(ISD::FNEG , MVT::v4f32, Legal); 1058 setOperationAction(ISD::FABS , MVT::v4f32, Legal); 1059 setOperationAction(ISD::FSIN , MVT::v4f32, Expand); 1060 setOperationAction(ISD::FCOS , MVT::v4f32, Expand); 1061 setOperationAction(ISD::FPOW , MVT::v4f32, Expand); 1062 setOperationAction(ISD::FLOG , MVT::v4f32, Expand); 1063 setOperationAction(ISD::FLOG2 , MVT::v4f32, Expand); 1064 setOperationAction(ISD::FLOG10 , MVT::v4f32, Expand); 1065 setOperationAction(ISD::FEXP , MVT::v4f32, Expand); 1066 setOperationAction(ISD::FEXP2 , MVT::v4f32, Expand); 1067 1068 setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal); 1069 setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal); 1070 1071 setIndexedLoadAction(ISD::PRE_INC, MVT::v4f32, Legal); 1072 setIndexedStoreAction(ISD::PRE_INC, MVT::v4f32, Legal); 1073 1074 addRegisterClass(MVT::v4f32, &PPC::QSRCRegClass); 1075 1076 setOperationAction(ISD::AND , MVT::v4i1, Legal); 1077 setOperationAction(ISD::OR , MVT::v4i1, Legal); 1078 setOperationAction(ISD::XOR , MVT::v4i1, Legal); 1079 1080 if (!Subtarget.useCRBits()) 1081 setOperationAction(ISD::SELECT, MVT::v4i1, Expand); 1082 setOperationAction(ISD::VSELECT, MVT::v4i1, Legal); 1083 1084 setOperationAction(ISD::LOAD , MVT::v4i1, Custom); 1085 setOperationAction(ISD::STORE , MVT::v4i1, Custom); 1086 1087 setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4i1, Custom); 1088 setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4i1, Expand); 1089 setOperationAction(ISD::CONCAT_VECTORS , MVT::v4i1, Expand); 1090 setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4i1, Expand); 1091 setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4i1, Custom); 1092 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i1, Expand); 1093 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i1, Custom); 1094 1095 setOperationAction(ISD::SINT_TO_FP, MVT::v4i1, Custom); 1096 setOperationAction(ISD::UINT_TO_FP, MVT::v4i1, Custom); 1097 1098 addRegisterClass(MVT::v4i1, &PPC::QBRCRegClass); 1099 1100 setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal); 1101 setOperationAction(ISD::FCEIL, MVT::v4f64, Legal); 1102 setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal); 1103 setOperationAction(ISD::FROUND, MVT::v4f64, Legal); 1104 1105 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal); 1106 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal); 1107 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal); 1108 setOperationAction(ISD::FROUND, MVT::v4f32, Legal); 1109 1110 setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Expand); 1111 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand); 1112 1113 // These need to set FE_INEXACT, and so cannot be vectorized here. 1114 setOperationAction(ISD::FRINT, MVT::v4f64, Expand); 1115 setOperationAction(ISD::FRINT, MVT::v4f32, Expand); 1116 1117 if (TM.Options.UnsafeFPMath) { 1118 setOperationAction(ISD::FDIV, MVT::v4f64, Legal); 1119 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal); 1120 1121 setOperationAction(ISD::FDIV, MVT::v4f32, Legal); 1122 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal); 1123 } else { 1124 setOperationAction(ISD::FDIV, MVT::v4f64, Expand); 1125 setOperationAction(ISD::FSQRT, MVT::v4f64, Expand); 1126 1127 setOperationAction(ISD::FDIV, MVT::v4f32, Expand); 1128 setOperationAction(ISD::FSQRT, MVT::v4f32, Expand); 1129 } 1130 } 1131 1132 if (Subtarget.has64BitSupport()) 1133 setOperationAction(ISD::PREFETCH, MVT::Other, Legal); 1134 1135 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, isPPC64 ? Legal : Custom); 1136 1137 if (!isPPC64) { 1138 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Expand); 1139 setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand); 1140 } 1141 1142 setBooleanContents(ZeroOrOneBooleanContent); 1143 1144 if (Subtarget.hasAltivec()) { 1145 // Altivec instructions set fields to all zeros or all ones. 1146 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent); 1147 } 1148 1149 if (!isPPC64) { 1150 // These libcalls are not available in 32-bit. 1151 setLibcallName(RTLIB::SHL_I128, nullptr); 1152 setLibcallName(RTLIB::SRL_I128, nullptr); 1153 setLibcallName(RTLIB::SRA_I128, nullptr); 1154 } 1155 1156 setStackPointerRegisterToSaveRestore(isPPC64 ? PPC::X1 : PPC::R1); 1157 1158 // We have target-specific dag combine patterns for the following nodes: 1159 setTargetDAGCombine(ISD::ADD); 1160 setTargetDAGCombine(ISD::SHL); 1161 setTargetDAGCombine(ISD::SRA); 1162 setTargetDAGCombine(ISD::SRL); 1163 setTargetDAGCombine(ISD::MUL); 1164 setTargetDAGCombine(ISD::SINT_TO_FP); 1165 setTargetDAGCombine(ISD::BUILD_VECTOR); 1166 if (Subtarget.hasFPCVT()) 1167 setTargetDAGCombine(ISD::UINT_TO_FP); 1168 setTargetDAGCombine(ISD::LOAD); 1169 setTargetDAGCombine(ISD::STORE); 1170 setTargetDAGCombine(ISD::BR_CC); 1171 if (Subtarget.useCRBits()) 1172 setTargetDAGCombine(ISD::BRCOND); 1173 setTargetDAGCombine(ISD::BSWAP); 1174 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN); 1175 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN); 1176 setTargetDAGCombine(ISD::INTRINSIC_VOID); 1177 1178 setTargetDAGCombine(ISD::SIGN_EXTEND); 1179 setTargetDAGCombine(ISD::ZERO_EXTEND); 1180 setTargetDAGCombine(ISD::ANY_EXTEND); 1181 1182 setTargetDAGCombine(ISD::TRUNCATE); 1183 setTargetDAGCombine(ISD::VECTOR_SHUFFLE); 1184 1185 1186 if (Subtarget.useCRBits()) { 1187 setTargetDAGCombine(ISD::TRUNCATE); 1188 setTargetDAGCombine(ISD::SETCC); 1189 setTargetDAGCombine(ISD::SELECT_CC); 1190 } 1191 1192 // Use reciprocal estimates. 1193 if (TM.Options.UnsafeFPMath) { 1194 setTargetDAGCombine(ISD::FDIV); 1195 setTargetDAGCombine(ISD::FSQRT); 1196 } 1197 1198 if (Subtarget.hasP9Altivec()) { 1199 setTargetDAGCombine(ISD::ABS); 1200 setTargetDAGCombine(ISD::VSELECT); 1201 } 1202 1203 if (EnableQuadPrecision) { 1204 setLibcallName(RTLIB::LOG_F128, "logf128"); 1205 setLibcallName(RTLIB::LOG2_F128, "log2f128"); 1206 setLibcallName(RTLIB::LOG10_F128, "log10f128"); 1207 setLibcallName(RTLIB::EXP_F128, "expf128"); 1208 setLibcallName(RTLIB::EXP2_F128, "exp2f128"); 1209 setLibcallName(RTLIB::SIN_F128, "sinf128"); 1210 setLibcallName(RTLIB::COS_F128, "cosf128"); 1211 setLibcallName(RTLIB::POW_F128, "powf128"); 1212 setLibcallName(RTLIB::FMIN_F128, "fminf128"); 1213 setLibcallName(RTLIB::FMAX_F128, "fmaxf128"); 1214 setLibcallName(RTLIB::POWI_F128, "__powikf2"); 1215 setLibcallName(RTLIB::REM_F128, "fmodf128"); 1216 } 1217 1218 // With 32 condition bits, we don't need to sink (and duplicate) compares 1219 // aggressively in CodeGenPrep. 1220 if (Subtarget.useCRBits()) { 1221 setHasMultipleConditionRegisters(); 1222 setJumpIsExpensive(); 1223 } 1224 1225 setMinFunctionAlignment(Align(4)); 1226 1227 switch (Subtarget.getCPUDirective()) { 1228 default: break; 1229 case PPC::DIR_970: 1230 case PPC::DIR_A2: 1231 case PPC::DIR_E500: 1232 case PPC::DIR_E500mc: 1233 case PPC::DIR_E5500: 1234 case PPC::DIR_PWR4: 1235 case PPC::DIR_PWR5: 1236 case PPC::DIR_PWR5X: 1237 case PPC::DIR_PWR6: 1238 case PPC::DIR_PWR6X: 1239 case PPC::DIR_PWR7: 1240 case PPC::DIR_PWR8: 1241 case PPC::DIR_PWR9: 1242 case PPC::DIR_PWR_FUTURE: 1243 setPrefLoopAlignment(Align(16)); 1244 setPrefFunctionAlignment(Align(16)); 1245 break; 1246 } 1247 1248 if (Subtarget.enableMachineScheduler()) 1249 setSchedulingPreference(Sched::Source); 1250 else 1251 setSchedulingPreference(Sched::Hybrid); 1252 1253 computeRegisterProperties(STI.getRegisterInfo()); 1254 1255 // The Freescale cores do better with aggressive inlining of memcpy and 1256 // friends. GCC uses same threshold of 128 bytes (= 32 word stores). 1257 if (Subtarget.getCPUDirective() == PPC::DIR_E500mc || 1258 Subtarget.getCPUDirective() == PPC::DIR_E5500) { 1259 MaxStoresPerMemset = 32; 1260 MaxStoresPerMemsetOptSize = 16; 1261 MaxStoresPerMemcpy = 32; 1262 MaxStoresPerMemcpyOptSize = 8; 1263 MaxStoresPerMemmove = 32; 1264 MaxStoresPerMemmoveOptSize = 8; 1265 } else if (Subtarget.getCPUDirective() == PPC::DIR_A2) { 1266 // The A2 also benefits from (very) aggressive inlining of memcpy and 1267 // friends. The overhead of a the function call, even when warm, can be 1268 // over one hundred cycles. 1269 MaxStoresPerMemset = 128; 1270 MaxStoresPerMemcpy = 128; 1271 MaxStoresPerMemmove = 128; 1272 MaxLoadsPerMemcmp = 128; 1273 } else { 1274 MaxLoadsPerMemcmp = 8; 1275 MaxLoadsPerMemcmpOptSize = 4; 1276 } 1277 } 1278 1279 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine 1280 /// the desired ByVal argument alignment. 1281 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign, 1282 unsigned MaxMaxAlign) { 1283 if (MaxAlign == MaxMaxAlign) 1284 return; 1285 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) { 1286 if (MaxMaxAlign >= 32 && VTy->getBitWidth() >= 256) 1287 MaxAlign = 32; 1288 else if (VTy->getBitWidth() >= 128 && MaxAlign < 16) 1289 MaxAlign = 16; 1290 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) { 1291 unsigned EltAlign = 0; 1292 getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign); 1293 if (EltAlign > MaxAlign) 1294 MaxAlign = EltAlign; 1295 } else if (StructType *STy = dyn_cast<StructType>(Ty)) { 1296 for (auto *EltTy : STy->elements()) { 1297 unsigned EltAlign = 0; 1298 getMaxByValAlign(EltTy, EltAlign, MaxMaxAlign); 1299 if (EltAlign > MaxAlign) 1300 MaxAlign = EltAlign; 1301 if (MaxAlign == MaxMaxAlign) 1302 break; 1303 } 1304 } 1305 } 1306 1307 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate 1308 /// function arguments in the caller parameter area. 1309 unsigned PPCTargetLowering::getByValTypeAlignment(Type *Ty, 1310 const DataLayout &DL) const { 1311 // 16byte and wider vectors are passed on 16byte boundary. 1312 // The rest is 8 on PPC64 and 4 on PPC32 boundary. 1313 unsigned Align = Subtarget.isPPC64() ? 8 : 4; 1314 if (Subtarget.hasAltivec() || Subtarget.hasQPX()) 1315 getMaxByValAlign(Ty, Align, Subtarget.hasQPX() ? 32 : 16); 1316 return Align; 1317 } 1318 1319 bool PPCTargetLowering::useSoftFloat() const { 1320 return Subtarget.useSoftFloat(); 1321 } 1322 1323 bool PPCTargetLowering::hasSPE() const { 1324 return Subtarget.hasSPE(); 1325 } 1326 1327 bool PPCTargetLowering::preferIncOfAddToSubOfNot(EVT VT) const { 1328 return VT.isScalarInteger(); 1329 } 1330 1331 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const { 1332 switch ((PPCISD::NodeType)Opcode) { 1333 case PPCISD::FIRST_NUMBER: break; 1334 case PPCISD::FSEL: return "PPCISD::FSEL"; 1335 case PPCISD::XSMAXCDP: return "PPCISD::XSMAXCDP"; 1336 case PPCISD::XSMINCDP: return "PPCISD::XSMINCDP"; 1337 case PPCISD::FCFID: return "PPCISD::FCFID"; 1338 case PPCISD::FCFIDU: return "PPCISD::FCFIDU"; 1339 case PPCISD::FCFIDS: return "PPCISD::FCFIDS"; 1340 case PPCISD::FCFIDUS: return "PPCISD::FCFIDUS"; 1341 case PPCISD::FCTIDZ: return "PPCISD::FCTIDZ"; 1342 case PPCISD::FCTIWZ: return "PPCISD::FCTIWZ"; 1343 case PPCISD::FCTIDUZ: return "PPCISD::FCTIDUZ"; 1344 case PPCISD::FCTIWUZ: return "PPCISD::FCTIWUZ"; 1345 case PPCISD::FP_TO_UINT_IN_VSR: 1346 return "PPCISD::FP_TO_UINT_IN_VSR,"; 1347 case PPCISD::FP_TO_SINT_IN_VSR: 1348 return "PPCISD::FP_TO_SINT_IN_VSR"; 1349 case PPCISD::FRE: return "PPCISD::FRE"; 1350 case PPCISD::FRSQRTE: return "PPCISD::FRSQRTE"; 1351 case PPCISD::STFIWX: return "PPCISD::STFIWX"; 1352 case PPCISD::VMADDFP: return "PPCISD::VMADDFP"; 1353 case PPCISD::VNMSUBFP: return "PPCISD::VNMSUBFP"; 1354 case PPCISD::VPERM: return "PPCISD::VPERM"; 1355 case PPCISD::XXSPLT: return "PPCISD::XXSPLT"; 1356 case PPCISD::VECINSERT: return "PPCISD::VECINSERT"; 1357 case PPCISD::XXPERMDI: return "PPCISD::XXPERMDI"; 1358 case PPCISD::VECSHL: return "PPCISD::VECSHL"; 1359 case PPCISD::CMPB: return "PPCISD::CMPB"; 1360 case PPCISD::Hi: return "PPCISD::Hi"; 1361 case PPCISD::Lo: return "PPCISD::Lo"; 1362 case PPCISD::TOC_ENTRY: return "PPCISD::TOC_ENTRY"; 1363 case PPCISD::ATOMIC_CMP_SWAP_8: return "PPCISD::ATOMIC_CMP_SWAP_8"; 1364 case PPCISD::ATOMIC_CMP_SWAP_16: return "PPCISD::ATOMIC_CMP_SWAP_16"; 1365 case PPCISD::DYNALLOC: return "PPCISD::DYNALLOC"; 1366 case PPCISD::DYNAREAOFFSET: return "PPCISD::DYNAREAOFFSET"; 1367 case PPCISD::GlobalBaseReg: return "PPCISD::GlobalBaseReg"; 1368 case PPCISD::SRL: return "PPCISD::SRL"; 1369 case PPCISD::SRA: return "PPCISD::SRA"; 1370 case PPCISD::SHL: return "PPCISD::SHL"; 1371 case PPCISD::SRA_ADDZE: return "PPCISD::SRA_ADDZE"; 1372 case PPCISD::CALL: return "PPCISD::CALL"; 1373 case PPCISD::CALL_NOP: return "PPCISD::CALL_NOP"; 1374 case PPCISD::MTCTR: return "PPCISD::MTCTR"; 1375 case PPCISD::BCTRL: return "PPCISD::BCTRL"; 1376 case PPCISD::BCTRL_LOAD_TOC: return "PPCISD::BCTRL_LOAD_TOC"; 1377 case PPCISD::RET_FLAG: return "PPCISD::RET_FLAG"; 1378 case PPCISD::READ_TIME_BASE: return "PPCISD::READ_TIME_BASE"; 1379 case PPCISD::EH_SJLJ_SETJMP: return "PPCISD::EH_SJLJ_SETJMP"; 1380 case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP"; 1381 case PPCISD::MFOCRF: return "PPCISD::MFOCRF"; 1382 case PPCISD::MFVSR: return "PPCISD::MFVSR"; 1383 case PPCISD::MTVSRA: return "PPCISD::MTVSRA"; 1384 case PPCISD::MTVSRZ: return "PPCISD::MTVSRZ"; 1385 case PPCISD::SINT_VEC_TO_FP: return "PPCISD::SINT_VEC_TO_FP"; 1386 case PPCISD::UINT_VEC_TO_FP: return "PPCISD::UINT_VEC_TO_FP"; 1387 case PPCISD::ANDI_rec_1_EQ_BIT: 1388 return "PPCISD::ANDI_rec_1_EQ_BIT"; 1389 case PPCISD::ANDI_rec_1_GT_BIT: 1390 return "PPCISD::ANDI_rec_1_GT_BIT"; 1391 case PPCISD::VCMP: return "PPCISD::VCMP"; 1392 case PPCISD::VCMPo: return "PPCISD::VCMPo"; 1393 case PPCISD::LBRX: return "PPCISD::LBRX"; 1394 case PPCISD::STBRX: return "PPCISD::STBRX"; 1395 case PPCISD::LFIWAX: return "PPCISD::LFIWAX"; 1396 case PPCISD::LFIWZX: return "PPCISD::LFIWZX"; 1397 case PPCISD::LXSIZX: return "PPCISD::LXSIZX"; 1398 case PPCISD::STXSIX: return "PPCISD::STXSIX"; 1399 case PPCISD::VEXTS: return "PPCISD::VEXTS"; 1400 case PPCISD::SExtVElems: return "PPCISD::SExtVElems"; 1401 case PPCISD::LXVD2X: return "PPCISD::LXVD2X"; 1402 case PPCISD::STXVD2X: return "PPCISD::STXVD2X"; 1403 case PPCISD::LOAD_VEC_BE: return "PPCISD::LOAD_VEC_BE"; 1404 case PPCISD::STORE_VEC_BE: return "PPCISD::STORE_VEC_BE"; 1405 case PPCISD::ST_VSR_SCAL_INT: 1406 return "PPCISD::ST_VSR_SCAL_INT"; 1407 case PPCISD::COND_BRANCH: return "PPCISD::COND_BRANCH"; 1408 case PPCISD::BDNZ: return "PPCISD::BDNZ"; 1409 case PPCISD::BDZ: return "PPCISD::BDZ"; 1410 case PPCISD::MFFS: return "PPCISD::MFFS"; 1411 case PPCISD::FADDRTZ: return "PPCISD::FADDRTZ"; 1412 case PPCISD::TC_RETURN: return "PPCISD::TC_RETURN"; 1413 case PPCISD::CR6SET: return "PPCISD::CR6SET"; 1414 case PPCISD::CR6UNSET: return "PPCISD::CR6UNSET"; 1415 case PPCISD::PPC32_GOT: return "PPCISD::PPC32_GOT"; 1416 case PPCISD::PPC32_PICGOT: return "PPCISD::PPC32_PICGOT"; 1417 case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA"; 1418 case PPCISD::LD_GOT_TPREL_L: return "PPCISD::LD_GOT_TPREL_L"; 1419 case PPCISD::ADD_TLS: return "PPCISD::ADD_TLS"; 1420 case PPCISD::ADDIS_TLSGD_HA: return "PPCISD::ADDIS_TLSGD_HA"; 1421 case PPCISD::ADDI_TLSGD_L: return "PPCISD::ADDI_TLSGD_L"; 1422 case PPCISD::GET_TLS_ADDR: return "PPCISD::GET_TLS_ADDR"; 1423 case PPCISD::ADDI_TLSGD_L_ADDR: return "PPCISD::ADDI_TLSGD_L_ADDR"; 1424 case PPCISD::ADDIS_TLSLD_HA: return "PPCISD::ADDIS_TLSLD_HA"; 1425 case PPCISD::ADDI_TLSLD_L: return "PPCISD::ADDI_TLSLD_L"; 1426 case PPCISD::GET_TLSLD_ADDR: return "PPCISD::GET_TLSLD_ADDR"; 1427 case PPCISD::ADDI_TLSLD_L_ADDR: return "PPCISD::ADDI_TLSLD_L_ADDR"; 1428 case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA"; 1429 case PPCISD::ADDI_DTPREL_L: return "PPCISD::ADDI_DTPREL_L"; 1430 case PPCISD::VADD_SPLAT: return "PPCISD::VADD_SPLAT"; 1431 case PPCISD::SC: return "PPCISD::SC"; 1432 case PPCISD::CLRBHRB: return "PPCISD::CLRBHRB"; 1433 case PPCISD::MFBHRBE: return "PPCISD::MFBHRBE"; 1434 case PPCISD::RFEBB: return "PPCISD::RFEBB"; 1435 case PPCISD::XXSWAPD: return "PPCISD::XXSWAPD"; 1436 case PPCISD::SWAP_NO_CHAIN: return "PPCISD::SWAP_NO_CHAIN"; 1437 case PPCISD::VABSD: return "PPCISD::VABSD"; 1438 case PPCISD::QVFPERM: return "PPCISD::QVFPERM"; 1439 case PPCISD::QVGPCI: return "PPCISD::QVGPCI"; 1440 case PPCISD::QVALIGNI: return "PPCISD::QVALIGNI"; 1441 case PPCISD::QVESPLATI: return "PPCISD::QVESPLATI"; 1442 case PPCISD::QBFLT: return "PPCISD::QBFLT"; 1443 case PPCISD::QVLFSb: return "PPCISD::QVLFSb"; 1444 case PPCISD::BUILD_FP128: return "PPCISD::BUILD_FP128"; 1445 case PPCISD::BUILD_SPE64: return "PPCISD::BUILD_SPE64"; 1446 case PPCISD::EXTRACT_SPE: return "PPCISD::EXTRACT_SPE"; 1447 case PPCISD::EXTSWSLI: return "PPCISD::EXTSWSLI"; 1448 case PPCISD::LD_VSX_LH: return "PPCISD::LD_VSX_LH"; 1449 case PPCISD::FP_EXTEND_HALF: return "PPCISD::FP_EXTEND_HALF"; 1450 case PPCISD::LD_SPLAT: return "PPCISD::LD_SPLAT"; 1451 } 1452 return nullptr; 1453 } 1454 1455 EVT PPCTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &C, 1456 EVT VT) const { 1457 if (!VT.isVector()) 1458 return Subtarget.useCRBits() ? MVT::i1 : MVT::i32; 1459 1460 if (Subtarget.hasQPX()) 1461 return EVT::getVectorVT(C, MVT::i1, VT.getVectorNumElements()); 1462 1463 return VT.changeVectorElementTypeToInteger(); 1464 } 1465 1466 bool PPCTargetLowering::enableAggressiveFMAFusion(EVT VT) const { 1467 assert(VT.isFloatingPoint() && "Non-floating-point FMA?"); 1468 return true; 1469 } 1470 1471 //===----------------------------------------------------------------------===// 1472 // Node matching predicates, for use by the tblgen matching code. 1473 //===----------------------------------------------------------------------===// 1474 1475 /// isFloatingPointZero - Return true if this is 0.0 or -0.0. 1476 static bool isFloatingPointZero(SDValue Op) { 1477 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) 1478 return CFP->getValueAPF().isZero(); 1479 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) { 1480 // Maybe this has already been legalized into the constant pool? 1481 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1))) 1482 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal())) 1483 return CFP->getValueAPF().isZero(); 1484 } 1485 return false; 1486 } 1487 1488 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode. Return 1489 /// true if Op is undef or if it matches the specified value. 1490 static bool isConstantOrUndef(int Op, int Val) { 1491 return Op < 0 || Op == Val; 1492 } 1493 1494 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a 1495 /// VPKUHUM instruction. 1496 /// The ShuffleKind distinguishes between big-endian operations with 1497 /// two different inputs (0), either-endian operations with two identical 1498 /// inputs (1), and little-endian operations with two different inputs (2). 1499 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td). 1500 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind, 1501 SelectionDAG &DAG) { 1502 bool IsLE = DAG.getDataLayout().isLittleEndian(); 1503 if (ShuffleKind == 0) { 1504 if (IsLE) 1505 return false; 1506 for (unsigned i = 0; i != 16; ++i) 1507 if (!isConstantOrUndef(N->getMaskElt(i), i*2+1)) 1508 return false; 1509 } else if (ShuffleKind == 2) { 1510 if (!IsLE) 1511 return false; 1512 for (unsigned i = 0; i != 16; ++i) 1513 if (!isConstantOrUndef(N->getMaskElt(i), i*2)) 1514 return false; 1515 } else if (ShuffleKind == 1) { 1516 unsigned j = IsLE ? 0 : 1; 1517 for (unsigned i = 0; i != 8; ++i) 1518 if (!isConstantOrUndef(N->getMaskElt(i), i*2+j) || 1519 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j)) 1520 return false; 1521 } 1522 return true; 1523 } 1524 1525 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a 1526 /// VPKUWUM instruction. 1527 /// The ShuffleKind distinguishes between big-endian operations with 1528 /// two different inputs (0), either-endian operations with two identical 1529 /// inputs (1), and little-endian operations with two different inputs (2). 1530 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td). 1531 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind, 1532 SelectionDAG &DAG) { 1533 bool IsLE = DAG.getDataLayout().isLittleEndian(); 1534 if (ShuffleKind == 0) { 1535 if (IsLE) 1536 return false; 1537 for (unsigned i = 0; i != 16; i += 2) 1538 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+2) || 1539 !isConstantOrUndef(N->getMaskElt(i+1), i*2+3)) 1540 return false; 1541 } else if (ShuffleKind == 2) { 1542 if (!IsLE) 1543 return false; 1544 for (unsigned i = 0; i != 16; i += 2) 1545 if (!isConstantOrUndef(N->getMaskElt(i ), i*2) || 1546 !isConstantOrUndef(N->getMaskElt(i+1), i*2+1)) 1547 return false; 1548 } else if (ShuffleKind == 1) { 1549 unsigned j = IsLE ? 0 : 2; 1550 for (unsigned i = 0; i != 8; i += 2) 1551 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+j) || 1552 !isConstantOrUndef(N->getMaskElt(i+1), i*2+j+1) || 1553 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j) || 1554 !isConstantOrUndef(N->getMaskElt(i+9), i*2+j+1)) 1555 return false; 1556 } 1557 return true; 1558 } 1559 1560 /// isVPKUDUMShuffleMask - Return true if this is the shuffle mask for a 1561 /// VPKUDUM instruction, AND the VPKUDUM instruction exists for the 1562 /// current subtarget. 1563 /// 1564 /// The ShuffleKind distinguishes between big-endian operations with 1565 /// two different inputs (0), either-endian operations with two identical 1566 /// inputs (1), and little-endian operations with two different inputs (2). 1567 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td). 1568 bool PPC::isVPKUDUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind, 1569 SelectionDAG &DAG) { 1570 const PPCSubtarget& Subtarget = 1571 static_cast<const PPCSubtarget&>(DAG.getSubtarget()); 1572 if (!Subtarget.hasP8Vector()) 1573 return false; 1574 1575 bool IsLE = DAG.getDataLayout().isLittleEndian(); 1576 if (ShuffleKind == 0) { 1577 if (IsLE) 1578 return false; 1579 for (unsigned i = 0; i != 16; i += 4) 1580 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+4) || 1581 !isConstantOrUndef(N->getMaskElt(i+1), i*2+5) || 1582 !isConstantOrUndef(N->getMaskElt(i+2), i*2+6) || 1583 !isConstantOrUndef(N->getMaskElt(i+3), i*2+7)) 1584 return false; 1585 } else if (ShuffleKind == 2) { 1586 if (!IsLE) 1587 return false; 1588 for (unsigned i = 0; i != 16; i += 4) 1589 if (!isConstantOrUndef(N->getMaskElt(i ), i*2) || 1590 !isConstantOrUndef(N->getMaskElt(i+1), i*2+1) || 1591 !isConstantOrUndef(N->getMaskElt(i+2), i*2+2) || 1592 !isConstantOrUndef(N->getMaskElt(i+3), i*2+3)) 1593 return false; 1594 } else if (ShuffleKind == 1) { 1595 unsigned j = IsLE ? 0 : 4; 1596 for (unsigned i = 0; i != 8; i += 4) 1597 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+j) || 1598 !isConstantOrUndef(N->getMaskElt(i+1), i*2+j+1) || 1599 !isConstantOrUndef(N->getMaskElt(i+2), i*2+j+2) || 1600 !isConstantOrUndef(N->getMaskElt(i+3), i*2+j+3) || 1601 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j) || 1602 !isConstantOrUndef(N->getMaskElt(i+9), i*2+j+1) || 1603 !isConstantOrUndef(N->getMaskElt(i+10), i*2+j+2) || 1604 !isConstantOrUndef(N->getMaskElt(i+11), i*2+j+3)) 1605 return false; 1606 } 1607 return true; 1608 } 1609 1610 /// isVMerge - Common function, used to match vmrg* shuffles. 1611 /// 1612 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize, 1613 unsigned LHSStart, unsigned RHSStart) { 1614 if (N->getValueType(0) != MVT::v16i8) 1615 return false; 1616 assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) && 1617 "Unsupported merge size!"); 1618 1619 for (unsigned i = 0; i != 8/UnitSize; ++i) // Step over units 1620 for (unsigned j = 0; j != UnitSize; ++j) { // Step over bytes within unit 1621 if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j), 1622 LHSStart+j+i*UnitSize) || 1623 !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j), 1624 RHSStart+j+i*UnitSize)) 1625 return false; 1626 } 1627 return true; 1628 } 1629 1630 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for 1631 /// a VMRGL* instruction with the specified unit size (1,2 or 4 bytes). 1632 /// The ShuffleKind distinguishes between big-endian merges with two 1633 /// different inputs (0), either-endian merges with two identical inputs (1), 1634 /// and little-endian merges with two different inputs (2). For the latter, 1635 /// the input operands are swapped (see PPCInstrAltivec.td). 1636 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize, 1637 unsigned ShuffleKind, SelectionDAG &DAG) { 1638 if (DAG.getDataLayout().isLittleEndian()) { 1639 if (ShuffleKind == 1) // unary 1640 return isVMerge(N, UnitSize, 0, 0); 1641 else if (ShuffleKind == 2) // swapped 1642 return isVMerge(N, UnitSize, 0, 16); 1643 else 1644 return false; 1645 } else { 1646 if (ShuffleKind == 1) // unary 1647 return isVMerge(N, UnitSize, 8, 8); 1648 else if (ShuffleKind == 0) // normal 1649 return isVMerge(N, UnitSize, 8, 24); 1650 else 1651 return false; 1652 } 1653 } 1654 1655 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for 1656 /// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes). 1657 /// The ShuffleKind distinguishes between big-endian merges with two 1658 /// different inputs (0), either-endian merges with two identical inputs (1), 1659 /// and little-endian merges with two different inputs (2). For the latter, 1660 /// the input operands are swapped (see PPCInstrAltivec.td). 1661 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize, 1662 unsigned ShuffleKind, SelectionDAG &DAG) { 1663 if (DAG.getDataLayout().isLittleEndian()) { 1664 if (ShuffleKind == 1) // unary 1665 return isVMerge(N, UnitSize, 8, 8); 1666 else if (ShuffleKind == 2) // swapped 1667 return isVMerge(N, UnitSize, 8, 24); 1668 else 1669 return false; 1670 } else { 1671 if (ShuffleKind == 1) // unary 1672 return isVMerge(N, UnitSize, 0, 0); 1673 else if (ShuffleKind == 0) // normal 1674 return isVMerge(N, UnitSize, 0, 16); 1675 else 1676 return false; 1677 } 1678 } 1679 1680 /** 1681 * Common function used to match vmrgew and vmrgow shuffles 1682 * 1683 * The indexOffset determines whether to look for even or odd words in 1684 * the shuffle mask. This is based on the of the endianness of the target 1685 * machine. 1686 * - Little Endian: 1687 * - Use offset of 0 to check for odd elements 1688 * - Use offset of 4 to check for even elements 1689 * - Big Endian: 1690 * - Use offset of 0 to check for even elements 1691 * - Use offset of 4 to check for odd elements 1692 * A detailed description of the vector element ordering for little endian and 1693 * big endian can be found at 1694 * http://www.ibm.com/developerworks/library/l-ibm-xl-c-cpp-compiler/index.html 1695 * Targeting your applications - what little endian and big endian IBM XL C/C++ 1696 * compiler differences mean to you 1697 * 1698 * The mask to the shuffle vector instruction specifies the indices of the 1699 * elements from the two input vectors to place in the result. The elements are 1700 * numbered in array-access order, starting with the first vector. These vectors 1701 * are always of type v16i8, thus each vector will contain 16 elements of size 1702 * 8. More info on the shuffle vector can be found in the 1703 * http://llvm.org/docs/LangRef.html#shufflevector-instruction 1704 * Language Reference. 1705 * 1706 * The RHSStartValue indicates whether the same input vectors are used (unary) 1707 * or two different input vectors are used, based on the following: 1708 * - If the instruction uses the same vector for both inputs, the range of the 1709 * indices will be 0 to 15. In this case, the RHSStart value passed should 1710 * be 0. 1711 * - If the instruction has two different vectors then the range of the 1712 * indices will be 0 to 31. In this case, the RHSStart value passed should 1713 * be 16 (indices 0-15 specify elements in the first vector while indices 16 1714 * to 31 specify elements in the second vector). 1715 * 1716 * \param[in] N The shuffle vector SD Node to analyze 1717 * \param[in] IndexOffset Specifies whether to look for even or odd elements 1718 * \param[in] RHSStartValue Specifies the starting index for the righthand input 1719 * vector to the shuffle_vector instruction 1720 * \return true iff this shuffle vector represents an even or odd word merge 1721 */ 1722 static bool isVMerge(ShuffleVectorSDNode *N, unsigned IndexOffset, 1723 unsigned RHSStartValue) { 1724 if (N->getValueType(0) != MVT::v16i8) 1725 return false; 1726 1727 for (unsigned i = 0; i < 2; ++i) 1728 for (unsigned j = 0; j < 4; ++j) 1729 if (!isConstantOrUndef(N->getMaskElt(i*4+j), 1730 i*RHSStartValue+j+IndexOffset) || 1731 !isConstantOrUndef(N->getMaskElt(i*4+j+8), 1732 i*RHSStartValue+j+IndexOffset+8)) 1733 return false; 1734 return true; 1735 } 1736 1737 /** 1738 * Determine if the specified shuffle mask is suitable for the vmrgew or 1739 * vmrgow instructions. 1740 * 1741 * \param[in] N The shuffle vector SD Node to analyze 1742 * \param[in] CheckEven Check for an even merge (true) or an odd merge (false) 1743 * \param[in] ShuffleKind Identify the type of merge: 1744 * - 0 = big-endian merge with two different inputs; 1745 * - 1 = either-endian merge with two identical inputs; 1746 * - 2 = little-endian merge with two different inputs (inputs are swapped for 1747 * little-endian merges). 1748 * \param[in] DAG The current SelectionDAG 1749 * \return true iff this shuffle mask 1750 */ 1751 bool PPC::isVMRGEOShuffleMask(ShuffleVectorSDNode *N, bool CheckEven, 1752 unsigned ShuffleKind, SelectionDAG &DAG) { 1753 if (DAG.getDataLayout().isLittleEndian()) { 1754 unsigned indexOffset = CheckEven ? 4 : 0; 1755 if (ShuffleKind == 1) // Unary 1756 return isVMerge(N, indexOffset, 0); 1757 else if (ShuffleKind == 2) // swapped 1758 return isVMerge(N, indexOffset, 16); 1759 else 1760 return false; 1761 } 1762 else { 1763 unsigned indexOffset = CheckEven ? 0 : 4; 1764 if (ShuffleKind == 1) // Unary 1765 return isVMerge(N, indexOffset, 0); 1766 else if (ShuffleKind == 0) // Normal 1767 return isVMerge(N, indexOffset, 16); 1768 else 1769 return false; 1770 } 1771 return false; 1772 } 1773 1774 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift 1775 /// amount, otherwise return -1. 1776 /// The ShuffleKind distinguishes between big-endian operations with two 1777 /// different inputs (0), either-endian operations with two identical inputs 1778 /// (1), and little-endian operations with two different inputs (2). For the 1779 /// latter, the input operands are swapped (see PPCInstrAltivec.td). 1780 int PPC::isVSLDOIShuffleMask(SDNode *N, unsigned ShuffleKind, 1781 SelectionDAG &DAG) { 1782 if (N->getValueType(0) != MVT::v16i8) 1783 return -1; 1784 1785 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 1786 1787 // Find the first non-undef value in the shuffle mask. 1788 unsigned i; 1789 for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i) 1790 /*search*/; 1791 1792 if (i == 16) return -1; // all undef. 1793 1794 // Otherwise, check to see if the rest of the elements are consecutively 1795 // numbered from this value. 1796 unsigned ShiftAmt = SVOp->getMaskElt(i); 1797 if (ShiftAmt < i) return -1; 1798 1799 ShiftAmt -= i; 1800 bool isLE = DAG.getDataLayout().isLittleEndian(); 1801 1802 if ((ShuffleKind == 0 && !isLE) || (ShuffleKind == 2 && isLE)) { 1803 // Check the rest of the elements to see if they are consecutive. 1804 for (++i; i != 16; ++i) 1805 if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i)) 1806 return -1; 1807 } else if (ShuffleKind == 1) { 1808 // Check the rest of the elements to see if they are consecutive. 1809 for (++i; i != 16; ++i) 1810 if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15)) 1811 return -1; 1812 } else 1813 return -1; 1814 1815 if (isLE) 1816 ShiftAmt = 16 - ShiftAmt; 1817 1818 return ShiftAmt; 1819 } 1820 1821 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand 1822 /// specifies a splat of a single element that is suitable for input to 1823 /// one of the splat operations (VSPLTB/VSPLTH/VSPLTW/XXSPLTW/LXVDSX/etc.). 1824 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) { 1825 assert(N->getValueType(0) == MVT::v16i8 && isPowerOf2_32(EltSize) && 1826 EltSize <= 8 && "Can only handle 1,2,4,8 byte element sizes"); 1827 1828 // The consecutive indices need to specify an element, not part of two 1829 // different elements. So abandon ship early if this isn't the case. 1830 if (N->getMaskElt(0) % EltSize != 0) 1831 return false; 1832 1833 // This is a splat operation if each element of the permute is the same, and 1834 // if the value doesn't reference the second vector. 1835 unsigned ElementBase = N->getMaskElt(0); 1836 1837 // FIXME: Handle UNDEF elements too! 1838 if (ElementBase >= 16) 1839 return false; 1840 1841 // Check that the indices are consecutive, in the case of a multi-byte element 1842 // splatted with a v16i8 mask. 1843 for (unsigned i = 1; i != EltSize; ++i) 1844 if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase)) 1845 return false; 1846 1847 for (unsigned i = EltSize, e = 16; i != e; i += EltSize) { 1848 if (N->getMaskElt(i) < 0) continue; 1849 for (unsigned j = 0; j != EltSize; ++j) 1850 if (N->getMaskElt(i+j) != N->getMaskElt(j)) 1851 return false; 1852 } 1853 return true; 1854 } 1855 1856 /// Check that the mask is shuffling N byte elements. Within each N byte 1857 /// element of the mask, the indices could be either in increasing or 1858 /// decreasing order as long as they are consecutive. 1859 /// \param[in] N the shuffle vector SD Node to analyze 1860 /// \param[in] Width the element width in bytes, could be 2/4/8/16 (HalfWord/ 1861 /// Word/DoubleWord/QuadWord). 1862 /// \param[in] StepLen the delta indices number among the N byte element, if 1863 /// the mask is in increasing/decreasing order then it is 1/-1. 1864 /// \return true iff the mask is shuffling N byte elements. 1865 static bool isNByteElemShuffleMask(ShuffleVectorSDNode *N, unsigned Width, 1866 int StepLen) { 1867 assert((Width == 2 || Width == 4 || Width == 8 || Width == 16) && 1868 "Unexpected element width."); 1869 assert((StepLen == 1 || StepLen == -1) && "Unexpected element width."); 1870 1871 unsigned NumOfElem = 16 / Width; 1872 unsigned MaskVal[16]; // Width is never greater than 16 1873 for (unsigned i = 0; i < NumOfElem; ++i) { 1874 MaskVal[0] = N->getMaskElt(i * Width); 1875 if ((StepLen == 1) && (MaskVal[0] % Width)) { 1876 return false; 1877 } else if ((StepLen == -1) && ((MaskVal[0] + 1) % Width)) { 1878 return false; 1879 } 1880 1881 for (unsigned int j = 1; j < Width; ++j) { 1882 MaskVal[j] = N->getMaskElt(i * Width + j); 1883 if (MaskVal[j] != MaskVal[j-1] + StepLen) { 1884 return false; 1885 } 1886 } 1887 } 1888 1889 return true; 1890 } 1891 1892 bool PPC::isXXINSERTWMask(ShuffleVectorSDNode *N, unsigned &ShiftElts, 1893 unsigned &InsertAtByte, bool &Swap, bool IsLE) { 1894 if (!isNByteElemShuffleMask(N, 4, 1)) 1895 return false; 1896 1897 // Now we look at mask elements 0,4,8,12 1898 unsigned M0 = N->getMaskElt(0) / 4; 1899 unsigned M1 = N->getMaskElt(4) / 4; 1900 unsigned M2 = N->getMaskElt(8) / 4; 1901 unsigned M3 = N->getMaskElt(12) / 4; 1902 unsigned LittleEndianShifts[] = { 2, 1, 0, 3 }; 1903 unsigned BigEndianShifts[] = { 3, 0, 1, 2 }; 1904 1905 // Below, let H and L be arbitrary elements of the shuffle mask 1906 // where H is in the range [4,7] and L is in the range [0,3]. 1907 // H, 1, 2, 3 or L, 5, 6, 7 1908 if ((M0 > 3 && M1 == 1 && M2 == 2 && M3 == 3) || 1909 (M0 < 4 && M1 == 5 && M2 == 6 && M3 == 7)) { 1910 ShiftElts = IsLE ? LittleEndianShifts[M0 & 0x3] : BigEndianShifts[M0 & 0x3]; 1911 InsertAtByte = IsLE ? 12 : 0; 1912 Swap = M0 < 4; 1913 return true; 1914 } 1915 // 0, H, 2, 3 or 4, L, 6, 7 1916 if ((M1 > 3 && M0 == 0 && M2 == 2 && M3 == 3) || 1917 (M1 < 4 && M0 == 4 && M2 == 6 && M3 == 7)) { 1918 ShiftElts = IsLE ? LittleEndianShifts[M1 & 0x3] : BigEndianShifts[M1 & 0x3]; 1919 InsertAtByte = IsLE ? 8 : 4; 1920 Swap = M1 < 4; 1921 return true; 1922 } 1923 // 0, 1, H, 3 or 4, 5, L, 7 1924 if ((M2 > 3 && M0 == 0 && M1 == 1 && M3 == 3) || 1925 (M2 < 4 && M0 == 4 && M1 == 5 && M3 == 7)) { 1926 ShiftElts = IsLE ? LittleEndianShifts[M2 & 0x3] : BigEndianShifts[M2 & 0x3]; 1927 InsertAtByte = IsLE ? 4 : 8; 1928 Swap = M2 < 4; 1929 return true; 1930 } 1931 // 0, 1, 2, H or 4, 5, 6, L 1932 if ((M3 > 3 && M0 == 0 && M1 == 1 && M2 == 2) || 1933 (M3 < 4 && M0 == 4 && M1 == 5 && M2 == 6)) { 1934 ShiftElts = IsLE ? LittleEndianShifts[M3 & 0x3] : BigEndianShifts[M3 & 0x3]; 1935 InsertAtByte = IsLE ? 0 : 12; 1936 Swap = M3 < 4; 1937 return true; 1938 } 1939 1940 // If both vector operands for the shuffle are the same vector, the mask will 1941 // contain only elements from the first one and the second one will be undef. 1942 if (N->getOperand(1).isUndef()) { 1943 ShiftElts = 0; 1944 Swap = true; 1945 unsigned XXINSERTWSrcElem = IsLE ? 2 : 1; 1946 if (M0 == XXINSERTWSrcElem && M1 == 1 && M2 == 2 && M3 == 3) { 1947 InsertAtByte = IsLE ? 12 : 0; 1948 return true; 1949 } 1950 if (M0 == 0 && M1 == XXINSERTWSrcElem && M2 == 2 && M3 == 3) { 1951 InsertAtByte = IsLE ? 8 : 4; 1952 return true; 1953 } 1954 if (M0 == 0 && M1 == 1 && M2 == XXINSERTWSrcElem && M3 == 3) { 1955 InsertAtByte = IsLE ? 4 : 8; 1956 return true; 1957 } 1958 if (M0 == 0 && M1 == 1 && M2 == 2 && M3 == XXINSERTWSrcElem) { 1959 InsertAtByte = IsLE ? 0 : 12; 1960 return true; 1961 } 1962 } 1963 1964 return false; 1965 } 1966 1967 bool PPC::isXXSLDWIShuffleMask(ShuffleVectorSDNode *N, unsigned &ShiftElts, 1968 bool &Swap, bool IsLE) { 1969 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8"); 1970 // Ensure each byte index of the word is consecutive. 1971 if (!isNByteElemShuffleMask(N, 4, 1)) 1972 return false; 1973 1974 // Now we look at mask elements 0,4,8,12, which are the beginning of words. 1975 unsigned M0 = N->getMaskElt(0) / 4; 1976 unsigned M1 = N->getMaskElt(4) / 4; 1977 unsigned M2 = N->getMaskElt(8) / 4; 1978 unsigned M3 = N->getMaskElt(12) / 4; 1979 1980 // If both vector operands for the shuffle are the same vector, the mask will 1981 // contain only elements from the first one and the second one will be undef. 1982 if (N->getOperand(1).isUndef()) { 1983 assert(M0 < 4 && "Indexing into an undef vector?"); 1984 if (M1 != (M0 + 1) % 4 || M2 != (M1 + 1) % 4 || M3 != (M2 + 1) % 4) 1985 return false; 1986 1987 ShiftElts = IsLE ? (4 - M0) % 4 : M0; 1988 Swap = false; 1989 return true; 1990 } 1991 1992 // Ensure each word index of the ShuffleVector Mask is consecutive. 1993 if (M1 != (M0 + 1) % 8 || M2 != (M1 + 1) % 8 || M3 != (M2 + 1) % 8) 1994 return false; 1995 1996 if (IsLE) { 1997 if (M0 == 0 || M0 == 7 || M0 == 6 || M0 == 5) { 1998 // Input vectors don't need to be swapped if the leading element 1999 // of the result is one of the 3 left elements of the second vector 2000 // (or if there is no shift to be done at all). 2001 Swap = false; 2002 ShiftElts = (8 - M0) % 8; 2003 } else if (M0 == 4 || M0 == 3 || M0 == 2 || M0 == 1) { 2004 // Input vectors need to be swapped if the leading element 2005 // of the result is one of the 3 left elements of the first vector 2006 // (or if we're shifting by 4 - thereby simply swapping the vectors). 2007 Swap = true; 2008 ShiftElts = (4 - M0) % 4; 2009 } 2010 2011 return true; 2012 } else { // BE 2013 if (M0 == 0 || M0 == 1 || M0 == 2 || M0 == 3) { 2014 // Input vectors don't need to be swapped if the leading element 2015 // of the result is one of the 4 elements of the first vector. 2016 Swap = false; 2017 ShiftElts = M0; 2018 } else if (M0 == 4 || M0 == 5 || M0 == 6 || M0 == 7) { 2019 // Input vectors need to be swapped if the leading element 2020 // of the result is one of the 4 elements of the right vector. 2021 Swap = true; 2022 ShiftElts = M0 - 4; 2023 } 2024 2025 return true; 2026 } 2027 } 2028 2029 bool static isXXBRShuffleMaskHelper(ShuffleVectorSDNode *N, int Width) { 2030 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8"); 2031 2032 if (!isNByteElemShuffleMask(N, Width, -1)) 2033 return false; 2034 2035 for (int i = 0; i < 16; i += Width) 2036 if (N->getMaskElt(i) != i + Width - 1) 2037 return false; 2038 2039 return true; 2040 } 2041 2042 bool PPC::isXXBRHShuffleMask(ShuffleVectorSDNode *N) { 2043 return isXXBRShuffleMaskHelper(N, 2); 2044 } 2045 2046 bool PPC::isXXBRWShuffleMask(ShuffleVectorSDNode *N) { 2047 return isXXBRShuffleMaskHelper(N, 4); 2048 } 2049 2050 bool PPC::isXXBRDShuffleMask(ShuffleVectorSDNode *N) { 2051 return isXXBRShuffleMaskHelper(N, 8); 2052 } 2053 2054 bool PPC::isXXBRQShuffleMask(ShuffleVectorSDNode *N) { 2055 return isXXBRShuffleMaskHelper(N, 16); 2056 } 2057 2058 /// Can node \p N be lowered to an XXPERMDI instruction? If so, set \p Swap 2059 /// if the inputs to the instruction should be swapped and set \p DM to the 2060 /// value for the immediate. 2061 /// Specifically, set \p Swap to true only if \p N can be lowered to XXPERMDI 2062 /// AND element 0 of the result comes from the first input (LE) or second input 2063 /// (BE). Set \p DM to the calculated result (0-3) only if \p N can be lowered. 2064 /// \return true iff the given mask of shuffle node \p N is a XXPERMDI shuffle 2065 /// mask. 2066 bool PPC::isXXPERMDIShuffleMask(ShuffleVectorSDNode *N, unsigned &DM, 2067 bool &Swap, bool IsLE) { 2068 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8"); 2069 2070 // Ensure each byte index of the double word is consecutive. 2071 if (!isNByteElemShuffleMask(N, 8, 1)) 2072 return false; 2073 2074 unsigned M0 = N->getMaskElt(0) / 8; 2075 unsigned M1 = N->getMaskElt(8) / 8; 2076 assert(((M0 | M1) < 4) && "A mask element out of bounds?"); 2077 2078 // If both vector operands for the shuffle are the same vector, the mask will 2079 // contain only elements from the first one and the second one will be undef. 2080 if (N->getOperand(1).isUndef()) { 2081 if ((M0 | M1) < 2) { 2082 DM = IsLE ? (((~M1) & 1) << 1) + ((~M0) & 1) : (M0 << 1) + (M1 & 1); 2083 Swap = false; 2084 return true; 2085 } else 2086 return false; 2087 } 2088 2089 if (IsLE) { 2090 if (M0 > 1 && M1 < 2) { 2091 Swap = false; 2092 } else if (M0 < 2 && M1 > 1) { 2093 M0 = (M0 + 2) % 4; 2094 M1 = (M1 + 2) % 4; 2095 Swap = true; 2096 } else 2097 return false; 2098 2099 // Note: if control flow comes here that means Swap is already set above 2100 DM = (((~M1) & 1) << 1) + ((~M0) & 1); 2101 return true; 2102 } else { // BE 2103 if (M0 < 2 && M1 > 1) { 2104 Swap = false; 2105 } else if (M0 > 1 && M1 < 2) { 2106 M0 = (M0 + 2) % 4; 2107 M1 = (M1 + 2) % 4; 2108 Swap = true; 2109 } else 2110 return false; 2111 2112 // Note: if control flow comes here that means Swap is already set above 2113 DM = (M0 << 1) + (M1 & 1); 2114 return true; 2115 } 2116 } 2117 2118 2119 /// getSplatIdxForPPCMnemonics - Return the splat index as a value that is 2120 /// appropriate for PPC mnemonics (which have a big endian bias - namely 2121 /// elements are counted from the left of the vector register). 2122 unsigned PPC::getSplatIdxForPPCMnemonics(SDNode *N, unsigned EltSize, 2123 SelectionDAG &DAG) { 2124 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 2125 assert(isSplatShuffleMask(SVOp, EltSize)); 2126 if (DAG.getDataLayout().isLittleEndian()) 2127 return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize); 2128 else 2129 return SVOp->getMaskElt(0) / EltSize; 2130 } 2131 2132 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed 2133 /// by using a vspltis[bhw] instruction of the specified element size, return 2134 /// the constant being splatted. The ByteSize field indicates the number of 2135 /// bytes of each element [124] -> [bhw]. 2136 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) { 2137 SDValue OpVal(nullptr, 0); 2138 2139 // If ByteSize of the splat is bigger than the element size of the 2140 // build_vector, then we have a case where we are checking for a splat where 2141 // multiple elements of the buildvector are folded together into a single 2142 // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8). 2143 unsigned EltSize = 16/N->getNumOperands(); 2144 if (EltSize < ByteSize) { 2145 unsigned Multiple = ByteSize/EltSize; // Number of BV entries per spltval. 2146 SDValue UniquedVals[4]; 2147 assert(Multiple > 1 && Multiple <= 4 && "How can this happen?"); 2148 2149 // See if all of the elements in the buildvector agree across. 2150 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 2151 if (N->getOperand(i).isUndef()) continue; 2152 // If the element isn't a constant, bail fully out. 2153 if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue(); 2154 2155 if (!UniquedVals[i&(Multiple-1)].getNode()) 2156 UniquedVals[i&(Multiple-1)] = N->getOperand(i); 2157 else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i)) 2158 return SDValue(); // no match. 2159 } 2160 2161 // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains 2162 // either constant or undef values that are identical for each chunk. See 2163 // if these chunks can form into a larger vspltis*. 2164 2165 // Check to see if all of the leading entries are either 0 or -1. If 2166 // neither, then this won't fit into the immediate field. 2167 bool LeadingZero = true; 2168 bool LeadingOnes = true; 2169 for (unsigned i = 0; i != Multiple-1; ++i) { 2170 if (!UniquedVals[i].getNode()) continue; // Must have been undefs. 2171 2172 LeadingZero &= isNullConstant(UniquedVals[i]); 2173 LeadingOnes &= isAllOnesConstant(UniquedVals[i]); 2174 } 2175 // Finally, check the least significant entry. 2176 if (LeadingZero) { 2177 if (!UniquedVals[Multiple-1].getNode()) 2178 return DAG.getTargetConstant(0, SDLoc(N), MVT::i32); // 0,0,0,undef 2179 int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue(); 2180 if (Val < 16) // 0,0,0,4 -> vspltisw(4) 2181 return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32); 2182 } 2183 if (LeadingOnes) { 2184 if (!UniquedVals[Multiple-1].getNode()) 2185 return DAG.getTargetConstant(~0U, SDLoc(N), MVT::i32); // -1,-1,-1,undef 2186 int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue(); 2187 if (Val >= -16) // -1,-1,-1,-2 -> vspltisw(-2) 2188 return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32); 2189 } 2190 2191 return SDValue(); 2192 } 2193 2194 // Check to see if this buildvec has a single non-undef value in its elements. 2195 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 2196 if (N->getOperand(i).isUndef()) continue; 2197 if (!OpVal.getNode()) 2198 OpVal = N->getOperand(i); 2199 else if (OpVal != N->getOperand(i)) 2200 return SDValue(); 2201 } 2202 2203 if (!OpVal.getNode()) return SDValue(); // All UNDEF: use implicit def. 2204 2205 unsigned ValSizeInBytes = EltSize; 2206 uint64_t Value = 0; 2207 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) { 2208 Value = CN->getZExtValue(); 2209 } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) { 2210 assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!"); 2211 Value = FloatToBits(CN->getValueAPF().convertToFloat()); 2212 } 2213 2214 // If the splat value is larger than the element value, then we can never do 2215 // this splat. The only case that we could fit the replicated bits into our 2216 // immediate field for would be zero, and we prefer to use vxor for it. 2217 if (ValSizeInBytes < ByteSize) return SDValue(); 2218 2219 // If the element value is larger than the splat value, check if it consists 2220 // of a repeated bit pattern of size ByteSize. 2221 if (!APInt(ValSizeInBytes * 8, Value).isSplat(ByteSize * 8)) 2222 return SDValue(); 2223 2224 // Properly sign extend the value. 2225 int MaskVal = SignExtend32(Value, ByteSize * 8); 2226 2227 // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros. 2228 if (MaskVal == 0) return SDValue(); 2229 2230 // Finally, if this value fits in a 5 bit sext field, return it 2231 if (SignExtend32<5>(MaskVal) == MaskVal) 2232 return DAG.getTargetConstant(MaskVal, SDLoc(N), MVT::i32); 2233 return SDValue(); 2234 } 2235 2236 /// isQVALIGNIShuffleMask - If this is a qvaligni shuffle mask, return the shift 2237 /// amount, otherwise return -1. 2238 int PPC::isQVALIGNIShuffleMask(SDNode *N) { 2239 EVT VT = N->getValueType(0); 2240 if (VT != MVT::v4f64 && VT != MVT::v4f32 && VT != MVT::v4i1) 2241 return -1; 2242 2243 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 2244 2245 // Find the first non-undef value in the shuffle mask. 2246 unsigned i; 2247 for (i = 0; i != 4 && SVOp->getMaskElt(i) < 0; ++i) 2248 /*search*/; 2249 2250 if (i == 4) return -1; // all undef. 2251 2252 // Otherwise, check to see if the rest of the elements are consecutively 2253 // numbered from this value. 2254 unsigned ShiftAmt = SVOp->getMaskElt(i); 2255 if (ShiftAmt < i) return -1; 2256 ShiftAmt -= i; 2257 2258 // Check the rest of the elements to see if they are consecutive. 2259 for (++i; i != 4; ++i) 2260 if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i)) 2261 return -1; 2262 2263 return ShiftAmt; 2264 } 2265 2266 //===----------------------------------------------------------------------===// 2267 // Addressing Mode Selection 2268 //===----------------------------------------------------------------------===// 2269 2270 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit 2271 /// or 64-bit immediate, and if the value can be accurately represented as a 2272 /// sign extension from a 16-bit value. If so, this returns true and the 2273 /// immediate. 2274 bool llvm::isIntS16Immediate(SDNode *N, int16_t &Imm) { 2275 if (!isa<ConstantSDNode>(N)) 2276 return false; 2277 2278 Imm = (int16_t)cast<ConstantSDNode>(N)->getZExtValue(); 2279 if (N->getValueType(0) == MVT::i32) 2280 return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue(); 2281 else 2282 return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue(); 2283 } 2284 bool llvm::isIntS16Immediate(SDValue Op, int16_t &Imm) { 2285 return isIntS16Immediate(Op.getNode(), Imm); 2286 } 2287 2288 2289 /// SelectAddressEVXRegReg - Given the specified address, check to see if it can 2290 /// be represented as an indexed [r+r] operation. 2291 bool PPCTargetLowering::SelectAddressEVXRegReg(SDValue N, SDValue &Base, 2292 SDValue &Index, 2293 SelectionDAG &DAG) const { 2294 for (SDNode::use_iterator UI = N->use_begin(), E = N->use_end(); 2295 UI != E; ++UI) { 2296 if (MemSDNode *Memop = dyn_cast<MemSDNode>(*UI)) { 2297 if (Memop->getMemoryVT() == MVT::f64) { 2298 Base = N.getOperand(0); 2299 Index = N.getOperand(1); 2300 return true; 2301 } 2302 } 2303 } 2304 return false; 2305 } 2306 2307 /// SelectAddressRegReg - Given the specified addressed, check to see if it 2308 /// can be represented as an indexed [r+r] operation. Returns false if it 2309 /// can be more efficiently represented as [r+imm]. If \p EncodingAlignment is 2310 /// non-zero and N can be represented by a base register plus a signed 16-bit 2311 /// displacement, make a more precise judgement by checking (displacement % \p 2312 /// EncodingAlignment). 2313 bool PPCTargetLowering::SelectAddressRegReg(SDValue N, SDValue &Base, 2314 SDValue &Index, SelectionDAG &DAG, 2315 unsigned EncodingAlignment) const { 2316 int16_t imm = 0; 2317 if (N.getOpcode() == ISD::ADD) { 2318 // Is there any SPE load/store (f64), which can't handle 16bit offset? 2319 // SPE load/store can only handle 8-bit offsets. 2320 if (hasSPE() && SelectAddressEVXRegReg(N, Base, Index, DAG)) 2321 return true; 2322 if (isIntS16Immediate(N.getOperand(1), imm) && 2323 (!EncodingAlignment || !(imm % EncodingAlignment))) 2324 return false; // r+i 2325 if (N.getOperand(1).getOpcode() == PPCISD::Lo) 2326 return false; // r+i 2327 2328 Base = N.getOperand(0); 2329 Index = N.getOperand(1); 2330 return true; 2331 } else if (N.getOpcode() == ISD::OR) { 2332 if (isIntS16Immediate(N.getOperand(1), imm) && 2333 (!EncodingAlignment || !(imm % EncodingAlignment))) 2334 return false; // r+i can fold it if we can. 2335 2336 // If this is an or of disjoint bitfields, we can codegen this as an add 2337 // (for better address arithmetic) if the LHS and RHS of the OR are provably 2338 // disjoint. 2339 KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0)); 2340 2341 if (LHSKnown.Zero.getBoolValue()) { 2342 KnownBits RHSKnown = DAG.computeKnownBits(N.getOperand(1)); 2343 // If all of the bits are known zero on the LHS or RHS, the add won't 2344 // carry. 2345 if (~(LHSKnown.Zero | RHSKnown.Zero) == 0) { 2346 Base = N.getOperand(0); 2347 Index = N.getOperand(1); 2348 return true; 2349 } 2350 } 2351 } 2352 2353 return false; 2354 } 2355 2356 // If we happen to be doing an i64 load or store into a stack slot that has 2357 // less than a 4-byte alignment, then the frame-index elimination may need to 2358 // use an indexed load or store instruction (because the offset may not be a 2359 // multiple of 4). The extra register needed to hold the offset comes from the 2360 // register scavenger, and it is possible that the scavenger will need to use 2361 // an emergency spill slot. As a result, we need to make sure that a spill slot 2362 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned 2363 // stack slot. 2364 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) { 2365 // FIXME: This does not handle the LWA case. 2366 if (VT != MVT::i64) 2367 return; 2368 2369 // NOTE: We'll exclude negative FIs here, which come from argument 2370 // lowering, because there are no known test cases triggering this problem 2371 // using packed structures (or similar). We can remove this exclusion if 2372 // we find such a test case. The reason why this is so test-case driven is 2373 // because this entire 'fixup' is only to prevent crashes (from the 2374 // register scavenger) on not-really-valid inputs. For example, if we have: 2375 // %a = alloca i1 2376 // %b = bitcast i1* %a to i64* 2377 // store i64* a, i64 b 2378 // then the store should really be marked as 'align 1', but is not. If it 2379 // were marked as 'align 1' then the indexed form would have been 2380 // instruction-selected initially, and the problem this 'fixup' is preventing 2381 // won't happen regardless. 2382 if (FrameIdx < 0) 2383 return; 2384 2385 MachineFunction &MF = DAG.getMachineFunction(); 2386 MachineFrameInfo &MFI = MF.getFrameInfo(); 2387 2388 unsigned Align = MFI.getObjectAlignment(FrameIdx); 2389 if (Align >= 4) 2390 return; 2391 2392 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 2393 FuncInfo->setHasNonRISpills(); 2394 } 2395 2396 /// Returns true if the address N can be represented by a base register plus 2397 /// a signed 16-bit displacement [r+imm], and if it is not better 2398 /// represented as reg+reg. If \p EncodingAlignment is non-zero, only accept 2399 /// displacements that are multiples of that value. 2400 bool PPCTargetLowering::SelectAddressRegImm(SDValue N, SDValue &Disp, 2401 SDValue &Base, 2402 SelectionDAG &DAG, 2403 unsigned EncodingAlignment) const { 2404 // FIXME dl should come from parent load or store, not from address 2405 SDLoc dl(N); 2406 // If this can be more profitably realized as r+r, fail. 2407 if (SelectAddressRegReg(N, Disp, Base, DAG, EncodingAlignment)) 2408 return false; 2409 2410 if (N.getOpcode() == ISD::ADD) { 2411 int16_t imm = 0; 2412 if (isIntS16Immediate(N.getOperand(1), imm) && 2413 (!EncodingAlignment || (imm % EncodingAlignment) == 0)) { 2414 Disp = DAG.getTargetConstant(imm, dl, N.getValueType()); 2415 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) { 2416 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2417 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 2418 } else { 2419 Base = N.getOperand(0); 2420 } 2421 return true; // [r+i] 2422 } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) { 2423 // Match LOAD (ADD (X, Lo(G))). 2424 assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue() 2425 && "Cannot handle constant offsets yet!"); 2426 Disp = N.getOperand(1).getOperand(0); // The global address. 2427 assert(Disp.getOpcode() == ISD::TargetGlobalAddress || 2428 Disp.getOpcode() == ISD::TargetGlobalTLSAddress || 2429 Disp.getOpcode() == ISD::TargetConstantPool || 2430 Disp.getOpcode() == ISD::TargetJumpTable); 2431 Base = N.getOperand(0); 2432 return true; // [&g+r] 2433 } 2434 } else if (N.getOpcode() == ISD::OR) { 2435 int16_t imm = 0; 2436 if (isIntS16Immediate(N.getOperand(1), imm) && 2437 (!EncodingAlignment || (imm % EncodingAlignment) == 0)) { 2438 // If this is an or of disjoint bitfields, we can codegen this as an add 2439 // (for better address arithmetic) if the LHS and RHS of the OR are 2440 // provably disjoint. 2441 KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0)); 2442 2443 if ((LHSKnown.Zero.getZExtValue()|~(uint64_t)imm) == ~0ULL) { 2444 // If all of the bits are known zero on the LHS or RHS, the add won't 2445 // carry. 2446 if (FrameIndexSDNode *FI = 2447 dyn_cast<FrameIndexSDNode>(N.getOperand(0))) { 2448 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2449 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 2450 } else { 2451 Base = N.getOperand(0); 2452 } 2453 Disp = DAG.getTargetConstant(imm, dl, N.getValueType()); 2454 return true; 2455 } 2456 } 2457 } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) { 2458 // Loading from a constant address. 2459 2460 // If this address fits entirely in a 16-bit sext immediate field, codegen 2461 // this as "d, 0" 2462 int16_t Imm; 2463 if (isIntS16Immediate(CN, Imm) && 2464 (!EncodingAlignment || (Imm % EncodingAlignment) == 0)) { 2465 Disp = DAG.getTargetConstant(Imm, dl, CN->getValueType(0)); 2466 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO, 2467 CN->getValueType(0)); 2468 return true; 2469 } 2470 2471 // Handle 32-bit sext immediates with LIS + addr mode. 2472 if ((CN->getValueType(0) == MVT::i32 || 2473 (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) && 2474 (!EncodingAlignment || (CN->getZExtValue() % EncodingAlignment) == 0)) { 2475 int Addr = (int)CN->getZExtValue(); 2476 2477 // Otherwise, break this down into an LIS + disp. 2478 Disp = DAG.getTargetConstant((short)Addr, dl, MVT::i32); 2479 2480 Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, dl, 2481 MVT::i32); 2482 unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8; 2483 Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0); 2484 return true; 2485 } 2486 } 2487 2488 Disp = DAG.getTargetConstant(0, dl, getPointerTy(DAG.getDataLayout())); 2489 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) { 2490 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2491 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 2492 } else 2493 Base = N; 2494 return true; // [r+0] 2495 } 2496 2497 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be 2498 /// represented as an indexed [r+r] operation. 2499 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base, 2500 SDValue &Index, 2501 SelectionDAG &DAG) const { 2502 // Check to see if we can easily represent this as an [r+r] address. This 2503 // will fail if it thinks that the address is more profitably represented as 2504 // reg+imm, e.g. where imm = 0. 2505 if (SelectAddressRegReg(N, Base, Index, DAG)) 2506 return true; 2507 2508 // If the address is the result of an add, we will utilize the fact that the 2509 // address calculation includes an implicit add. However, we can reduce 2510 // register pressure if we do not materialize a constant just for use as the 2511 // index register. We only get rid of the add if it is not an add of a 2512 // value and a 16-bit signed constant and both have a single use. 2513 int16_t imm = 0; 2514 if (N.getOpcode() == ISD::ADD && 2515 (!isIntS16Immediate(N.getOperand(1), imm) || 2516 !N.getOperand(1).hasOneUse() || !N.getOperand(0).hasOneUse())) { 2517 Base = N.getOperand(0); 2518 Index = N.getOperand(1); 2519 return true; 2520 } 2521 2522 // Otherwise, do it the hard way, using R0 as the base register. 2523 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO, 2524 N.getValueType()); 2525 Index = N; 2526 return true; 2527 } 2528 2529 /// Returns true if we should use a direct load into vector instruction 2530 /// (such as lxsd or lfd), instead of a load into gpr + direct move sequence. 2531 static bool usePartialVectorLoads(SDNode *N, const PPCSubtarget& ST) { 2532 2533 // If there are any other uses other than scalar to vector, then we should 2534 // keep it as a scalar load -> direct move pattern to prevent multiple 2535 // loads. 2536 LoadSDNode *LD = dyn_cast<LoadSDNode>(N); 2537 if (!LD) 2538 return false; 2539 2540 EVT MemVT = LD->getMemoryVT(); 2541 if (!MemVT.isSimple()) 2542 return false; 2543 switch(MemVT.getSimpleVT().SimpleTy) { 2544 case MVT::i64: 2545 break; 2546 case MVT::i32: 2547 if (!ST.hasP8Vector()) 2548 return false; 2549 break; 2550 case MVT::i16: 2551 case MVT::i8: 2552 if (!ST.hasP9Vector()) 2553 return false; 2554 break; 2555 default: 2556 return false; 2557 } 2558 2559 SDValue LoadedVal(N, 0); 2560 if (!LoadedVal.hasOneUse()) 2561 return false; 2562 2563 for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end(); 2564 UI != UE; ++UI) 2565 if (UI.getUse().get().getResNo() == 0 && 2566 UI->getOpcode() != ISD::SCALAR_TO_VECTOR) 2567 return false; 2568 2569 return true; 2570 } 2571 2572 /// getPreIndexedAddressParts - returns true by value, base pointer and 2573 /// offset pointer and addressing mode by reference if the node's address 2574 /// can be legally represented as pre-indexed load / store address. 2575 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base, 2576 SDValue &Offset, 2577 ISD::MemIndexedMode &AM, 2578 SelectionDAG &DAG) const { 2579 if (DisablePPCPreinc) return false; 2580 2581 bool isLoad = true; 2582 SDValue Ptr; 2583 EVT VT; 2584 unsigned Alignment; 2585 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 2586 Ptr = LD->getBasePtr(); 2587 VT = LD->getMemoryVT(); 2588 Alignment = LD->getAlignment(); 2589 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 2590 Ptr = ST->getBasePtr(); 2591 VT = ST->getMemoryVT(); 2592 Alignment = ST->getAlignment(); 2593 isLoad = false; 2594 } else 2595 return false; 2596 2597 // Do not generate pre-inc forms for specific loads that feed scalar_to_vector 2598 // instructions because we can fold these into a more efficient instruction 2599 // instead, (such as LXSD). 2600 if (isLoad && usePartialVectorLoads(N, Subtarget)) { 2601 return false; 2602 } 2603 2604 // PowerPC doesn't have preinc load/store instructions for vectors (except 2605 // for QPX, which does have preinc r+r forms). 2606 if (VT.isVector()) { 2607 if (!Subtarget.hasQPX() || (VT != MVT::v4f64 && VT != MVT::v4f32)) { 2608 return false; 2609 } else if (SelectAddressRegRegOnly(Ptr, Offset, Base, DAG)) { 2610 AM = ISD::PRE_INC; 2611 return true; 2612 } 2613 } 2614 2615 if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) { 2616 // Common code will reject creating a pre-inc form if the base pointer 2617 // is a frame index, or if N is a store and the base pointer is either 2618 // the same as or a predecessor of the value being stored. Check for 2619 // those situations here, and try with swapped Base/Offset instead. 2620 bool Swap = false; 2621 2622 if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base)) 2623 Swap = true; 2624 else if (!isLoad) { 2625 SDValue Val = cast<StoreSDNode>(N)->getValue(); 2626 if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode())) 2627 Swap = true; 2628 } 2629 2630 if (Swap) 2631 std::swap(Base, Offset); 2632 2633 AM = ISD::PRE_INC; 2634 return true; 2635 } 2636 2637 // LDU/STU can only handle immediates that are a multiple of 4. 2638 if (VT != MVT::i64) { 2639 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, 0)) 2640 return false; 2641 } else { 2642 // LDU/STU need an address with at least 4-byte alignment. 2643 if (Alignment < 4) 2644 return false; 2645 2646 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, 4)) 2647 return false; 2648 } 2649 2650 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 2651 // PPC64 doesn't have lwau, but it does have lwaux. Reject preinc load of 2652 // sext i32 to i64 when addr mode is r+i. 2653 if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 && 2654 LD->getExtensionType() == ISD::SEXTLOAD && 2655 isa<ConstantSDNode>(Offset)) 2656 return false; 2657 } 2658 2659 AM = ISD::PRE_INC; 2660 return true; 2661 } 2662 2663 //===----------------------------------------------------------------------===// 2664 // LowerOperation implementation 2665 //===----------------------------------------------------------------------===// 2666 2667 /// Return true if we should reference labels using a PICBase, set the HiOpFlags 2668 /// and LoOpFlags to the target MO flags. 2669 static void getLabelAccessInfo(bool IsPIC, const PPCSubtarget &Subtarget, 2670 unsigned &HiOpFlags, unsigned &LoOpFlags, 2671 const GlobalValue *GV = nullptr) { 2672 HiOpFlags = PPCII::MO_HA; 2673 LoOpFlags = PPCII::MO_LO; 2674 2675 // Don't use the pic base if not in PIC relocation model. 2676 if (IsPIC) { 2677 HiOpFlags |= PPCII::MO_PIC_FLAG; 2678 LoOpFlags |= PPCII::MO_PIC_FLAG; 2679 } 2680 } 2681 2682 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC, 2683 SelectionDAG &DAG) { 2684 SDLoc DL(HiPart); 2685 EVT PtrVT = HiPart.getValueType(); 2686 SDValue Zero = DAG.getConstant(0, DL, PtrVT); 2687 2688 SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero); 2689 SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero); 2690 2691 // With PIC, the first instruction is actually "GR+hi(&G)". 2692 if (isPIC) 2693 Hi = DAG.getNode(ISD::ADD, DL, PtrVT, 2694 DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi); 2695 2696 // Generate non-pic code that has direct accesses to the constant pool. 2697 // The address of the global is just (hi(&g)+lo(&g)). 2698 return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo); 2699 } 2700 2701 static void setUsesTOCBasePtr(MachineFunction &MF) { 2702 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 2703 FuncInfo->setUsesTOCBasePtr(); 2704 } 2705 2706 static void setUsesTOCBasePtr(SelectionDAG &DAG) { 2707 setUsesTOCBasePtr(DAG.getMachineFunction()); 2708 } 2709 2710 SDValue PPCTargetLowering::getTOCEntry(SelectionDAG &DAG, const SDLoc &dl, 2711 SDValue GA) const { 2712 const bool Is64Bit = Subtarget.isPPC64(); 2713 EVT VT = Is64Bit ? MVT::i64 : MVT::i32; 2714 SDValue Reg = Is64Bit ? DAG.getRegister(PPC::X2, VT) 2715 : Subtarget.isAIXABI() 2716 ? DAG.getRegister(PPC::R2, VT) 2717 : DAG.getNode(PPCISD::GlobalBaseReg, dl, VT); 2718 SDValue Ops[] = { GA, Reg }; 2719 return DAG.getMemIntrinsicNode( 2720 PPCISD::TOC_ENTRY, dl, DAG.getVTList(VT, MVT::Other), Ops, VT, 2721 MachinePointerInfo::getGOT(DAG.getMachineFunction()), 0, 2722 MachineMemOperand::MOLoad); 2723 } 2724 2725 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op, 2726 SelectionDAG &DAG) const { 2727 EVT PtrVT = Op.getValueType(); 2728 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op); 2729 const Constant *C = CP->getConstVal(); 2730 2731 // 64-bit SVR4 ABI and AIX ABI code are always position-independent. 2732 // The actual address of the GlobalValue is stored in the TOC. 2733 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) { 2734 setUsesTOCBasePtr(DAG); 2735 SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0); 2736 return getTOCEntry(DAG, SDLoc(CP), GA); 2737 } 2738 2739 unsigned MOHiFlag, MOLoFlag; 2740 bool IsPIC = isPositionIndependent(); 2741 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag); 2742 2743 if (IsPIC && Subtarget.isSVR4ABI()) { 2744 SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 2745 PPCII::MO_PIC_FLAG); 2746 return getTOCEntry(DAG, SDLoc(CP), GA); 2747 } 2748 2749 SDValue CPIHi = 2750 DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOHiFlag); 2751 SDValue CPILo = 2752 DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOLoFlag); 2753 return LowerLabelRef(CPIHi, CPILo, IsPIC, DAG); 2754 } 2755 2756 // For 64-bit PowerPC, prefer the more compact relative encodings. 2757 // This trades 32 bits per jump table entry for one or two instructions 2758 // on the jump site. 2759 unsigned PPCTargetLowering::getJumpTableEncoding() const { 2760 if (isJumpTableRelative()) 2761 return MachineJumpTableInfo::EK_LabelDifference32; 2762 2763 return TargetLowering::getJumpTableEncoding(); 2764 } 2765 2766 bool PPCTargetLowering::isJumpTableRelative() const { 2767 if (UseAbsoluteJumpTables) 2768 return false; 2769 if (Subtarget.isPPC64() || Subtarget.isAIXABI()) 2770 return true; 2771 return TargetLowering::isJumpTableRelative(); 2772 } 2773 2774 SDValue PPCTargetLowering::getPICJumpTableRelocBase(SDValue Table, 2775 SelectionDAG &DAG) const { 2776 if (!Subtarget.isPPC64() || Subtarget.isAIXABI()) 2777 return TargetLowering::getPICJumpTableRelocBase(Table, DAG); 2778 2779 switch (getTargetMachine().getCodeModel()) { 2780 case CodeModel::Small: 2781 case CodeModel::Medium: 2782 return TargetLowering::getPICJumpTableRelocBase(Table, DAG); 2783 default: 2784 return DAG.getNode(PPCISD::GlobalBaseReg, SDLoc(), 2785 getPointerTy(DAG.getDataLayout())); 2786 } 2787 } 2788 2789 const MCExpr * 2790 PPCTargetLowering::getPICJumpTableRelocBaseExpr(const MachineFunction *MF, 2791 unsigned JTI, 2792 MCContext &Ctx) const { 2793 if (!Subtarget.isPPC64() || Subtarget.isAIXABI()) 2794 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx); 2795 2796 switch (getTargetMachine().getCodeModel()) { 2797 case CodeModel::Small: 2798 case CodeModel::Medium: 2799 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx); 2800 default: 2801 return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx); 2802 } 2803 } 2804 2805 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const { 2806 EVT PtrVT = Op.getValueType(); 2807 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op); 2808 2809 // 64-bit SVR4 ABI and AIX ABI code are always position-independent. 2810 // The actual address of the GlobalValue is stored in the TOC. 2811 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) { 2812 setUsesTOCBasePtr(DAG); 2813 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT); 2814 return getTOCEntry(DAG, SDLoc(JT), GA); 2815 } 2816 2817 unsigned MOHiFlag, MOLoFlag; 2818 bool IsPIC = isPositionIndependent(); 2819 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag); 2820 2821 if (IsPIC && Subtarget.isSVR4ABI()) { 2822 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, 2823 PPCII::MO_PIC_FLAG); 2824 return getTOCEntry(DAG, SDLoc(GA), GA); 2825 } 2826 2827 SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag); 2828 SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag); 2829 return LowerLabelRef(JTIHi, JTILo, IsPIC, DAG); 2830 } 2831 2832 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op, 2833 SelectionDAG &DAG) const { 2834 EVT PtrVT = Op.getValueType(); 2835 BlockAddressSDNode *BASDN = cast<BlockAddressSDNode>(Op); 2836 const BlockAddress *BA = BASDN->getBlockAddress(); 2837 2838 // 64-bit SVR4 ABI and AIX ABI code are always position-independent. 2839 // The actual BlockAddress is stored in the TOC. 2840 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) { 2841 setUsesTOCBasePtr(DAG); 2842 SDValue GA = DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset()); 2843 return getTOCEntry(DAG, SDLoc(BASDN), GA); 2844 } 2845 2846 // 32-bit position-independent ELF stores the BlockAddress in the .got. 2847 if (Subtarget.is32BitELFABI() && isPositionIndependent()) 2848 return getTOCEntry( 2849 DAG, SDLoc(BASDN), 2850 DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset())); 2851 2852 unsigned MOHiFlag, MOLoFlag; 2853 bool IsPIC = isPositionIndependent(); 2854 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag); 2855 SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag); 2856 SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag); 2857 return LowerLabelRef(TgtBAHi, TgtBALo, IsPIC, DAG); 2858 } 2859 2860 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op, 2861 SelectionDAG &DAG) const { 2862 // FIXME: TLS addresses currently use medium model code sequences, 2863 // which is the most useful form. Eventually support for small and 2864 // large models could be added if users need it, at the cost of 2865 // additional complexity. 2866 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op); 2867 if (DAG.getTarget().useEmulatedTLS()) 2868 return LowerToTLSEmulatedModel(GA, DAG); 2869 2870 SDLoc dl(GA); 2871 const GlobalValue *GV = GA->getGlobal(); 2872 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2873 bool is64bit = Subtarget.isPPC64(); 2874 const Module *M = DAG.getMachineFunction().getFunction().getParent(); 2875 PICLevel::Level picLevel = M->getPICLevel(); 2876 2877 const TargetMachine &TM = getTargetMachine(); 2878 TLSModel::Model Model = TM.getTLSModel(GV); 2879 2880 if (Model == TLSModel::LocalExec) { 2881 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 2882 PPCII::MO_TPREL_HA); 2883 SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 2884 PPCII::MO_TPREL_LO); 2885 SDValue TLSReg = is64bit ? DAG.getRegister(PPC::X13, MVT::i64) 2886 : DAG.getRegister(PPC::R2, MVT::i32); 2887 2888 SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg); 2889 return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi); 2890 } 2891 2892 if (Model == TLSModel::InitialExec) { 2893 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0); 2894 SDValue TGATLS = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 2895 PPCII::MO_TLS); 2896 SDValue GOTPtr; 2897 if (is64bit) { 2898 setUsesTOCBasePtr(DAG); 2899 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64); 2900 GOTPtr = DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl, 2901 PtrVT, GOTReg, TGA); 2902 } else { 2903 if (!TM.isPositionIndependent()) 2904 GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT); 2905 else if (picLevel == PICLevel::SmallPIC) 2906 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT); 2907 else 2908 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT); 2909 } 2910 SDValue TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl, 2911 PtrVT, TGA, GOTPtr); 2912 return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS); 2913 } 2914 2915 if (Model == TLSModel::GeneralDynamic) { 2916 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0); 2917 SDValue GOTPtr; 2918 if (is64bit) { 2919 setUsesTOCBasePtr(DAG); 2920 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64); 2921 GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT, 2922 GOTReg, TGA); 2923 } else { 2924 if (picLevel == PICLevel::SmallPIC) 2925 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT); 2926 else 2927 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT); 2928 } 2929 return DAG.getNode(PPCISD::ADDI_TLSGD_L_ADDR, dl, PtrVT, 2930 GOTPtr, TGA, TGA); 2931 } 2932 2933 if (Model == TLSModel::LocalDynamic) { 2934 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0); 2935 SDValue GOTPtr; 2936 if (is64bit) { 2937 setUsesTOCBasePtr(DAG); 2938 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64); 2939 GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT, 2940 GOTReg, TGA); 2941 } else { 2942 if (picLevel == PICLevel::SmallPIC) 2943 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT); 2944 else 2945 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT); 2946 } 2947 SDValue TLSAddr = DAG.getNode(PPCISD::ADDI_TLSLD_L_ADDR, dl, 2948 PtrVT, GOTPtr, TGA, TGA); 2949 SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl, 2950 PtrVT, TLSAddr, TGA); 2951 return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA); 2952 } 2953 2954 llvm_unreachable("Unknown TLS model!"); 2955 } 2956 2957 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op, 2958 SelectionDAG &DAG) const { 2959 EVT PtrVT = Op.getValueType(); 2960 GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op); 2961 SDLoc DL(GSDN); 2962 const GlobalValue *GV = GSDN->getGlobal(); 2963 2964 // 64-bit SVR4 ABI & AIX ABI code is always position-independent. 2965 // The actual address of the GlobalValue is stored in the TOC. 2966 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) { 2967 setUsesTOCBasePtr(DAG); 2968 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset()); 2969 return getTOCEntry(DAG, DL, GA); 2970 } 2971 2972 unsigned MOHiFlag, MOLoFlag; 2973 bool IsPIC = isPositionIndependent(); 2974 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag, GV); 2975 2976 if (IsPIC && Subtarget.isSVR4ABI()) { 2977 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 2978 GSDN->getOffset(), 2979 PPCII::MO_PIC_FLAG); 2980 return getTOCEntry(DAG, DL, GA); 2981 } 2982 2983 SDValue GAHi = 2984 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag); 2985 SDValue GALo = 2986 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag); 2987 2988 return LowerLabelRef(GAHi, GALo, IsPIC, DAG); 2989 } 2990 2991 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const { 2992 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get(); 2993 SDLoc dl(Op); 2994 2995 if (Op.getValueType() == MVT::v2i64) { 2996 // When the operands themselves are v2i64 values, we need to do something 2997 // special because VSX has no underlying comparison operations for these. 2998 if (Op.getOperand(0).getValueType() == MVT::v2i64) { 2999 // Equality can be handled by casting to the legal type for Altivec 3000 // comparisons, everything else needs to be expanded. 3001 if (CC == ISD::SETEQ || CC == ISD::SETNE) { 3002 return DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, 3003 DAG.getSetCC(dl, MVT::v4i32, 3004 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0)), 3005 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(1)), 3006 CC)); 3007 } 3008 3009 return SDValue(); 3010 } 3011 3012 // We handle most of these in the usual way. 3013 return Op; 3014 } 3015 3016 // If we're comparing for equality to zero, expose the fact that this is 3017 // implemented as a ctlz/srl pair on ppc, so that the dag combiner can 3018 // fold the new nodes. 3019 if (SDValue V = lowerCmpEqZeroToCtlzSrl(Op, DAG)) 3020 return V; 3021 3022 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 3023 // Leave comparisons against 0 and -1 alone for now, since they're usually 3024 // optimized. FIXME: revisit this when we can custom lower all setcc 3025 // optimizations. 3026 if (C->isAllOnesValue() || C->isNullValue()) 3027 return SDValue(); 3028 } 3029 3030 // If we have an integer seteq/setne, turn it into a compare against zero 3031 // by xor'ing the rhs with the lhs, which is faster than setting a 3032 // condition register, reading it back out, and masking the correct bit. The 3033 // normal approach here uses sub to do this instead of xor. Using xor exposes 3034 // the result to other bit-twiddling opportunities. 3035 EVT LHSVT = Op.getOperand(0).getValueType(); 3036 if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) { 3037 EVT VT = Op.getValueType(); 3038 SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0), 3039 Op.getOperand(1)); 3040 return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, dl, LHSVT), CC); 3041 } 3042 return SDValue(); 3043 } 3044 3045 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const { 3046 SDNode *Node = Op.getNode(); 3047 EVT VT = Node->getValueType(0); 3048 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3049 SDValue InChain = Node->getOperand(0); 3050 SDValue VAListPtr = Node->getOperand(1); 3051 const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue(); 3052 SDLoc dl(Node); 3053 3054 assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only"); 3055 3056 // gpr_index 3057 SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain, 3058 VAListPtr, MachinePointerInfo(SV), MVT::i8); 3059 InChain = GprIndex.getValue(1); 3060 3061 if (VT == MVT::i64) { 3062 // Check if GprIndex is even 3063 SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex, 3064 DAG.getConstant(1, dl, MVT::i32)); 3065 SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd, 3066 DAG.getConstant(0, dl, MVT::i32), ISD::SETNE); 3067 SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex, 3068 DAG.getConstant(1, dl, MVT::i32)); 3069 // Align GprIndex to be even if it isn't 3070 GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne, 3071 GprIndex); 3072 } 3073 3074 // fpr index is 1 byte after gpr 3075 SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, 3076 DAG.getConstant(1, dl, MVT::i32)); 3077 3078 // fpr 3079 SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain, 3080 FprPtr, MachinePointerInfo(SV), MVT::i8); 3081 InChain = FprIndex.getValue(1); 3082 3083 SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, 3084 DAG.getConstant(8, dl, MVT::i32)); 3085 3086 SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, 3087 DAG.getConstant(4, dl, MVT::i32)); 3088 3089 // areas 3090 SDValue OverflowArea = 3091 DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr, MachinePointerInfo()); 3092 InChain = OverflowArea.getValue(1); 3093 3094 SDValue RegSaveArea = 3095 DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr, MachinePointerInfo()); 3096 InChain = RegSaveArea.getValue(1); 3097 3098 // select overflow_area if index > 8 3099 SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex, 3100 DAG.getConstant(8, dl, MVT::i32), ISD::SETLT); 3101 3102 // adjustment constant gpr_index * 4/8 3103 SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32, 3104 VT.isInteger() ? GprIndex : FprIndex, 3105 DAG.getConstant(VT.isInteger() ? 4 : 8, dl, 3106 MVT::i32)); 3107 3108 // OurReg = RegSaveArea + RegConstant 3109 SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea, 3110 RegConstant); 3111 3112 // Floating types are 32 bytes into RegSaveArea 3113 if (VT.isFloatingPoint()) 3114 OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg, 3115 DAG.getConstant(32, dl, MVT::i32)); 3116 3117 // increase {f,g}pr_index by 1 (or 2 if VT is i64) 3118 SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32, 3119 VT.isInteger() ? GprIndex : FprIndex, 3120 DAG.getConstant(VT == MVT::i64 ? 2 : 1, dl, 3121 MVT::i32)); 3122 3123 InChain = DAG.getTruncStore(InChain, dl, IndexPlus1, 3124 VT.isInteger() ? VAListPtr : FprPtr, 3125 MachinePointerInfo(SV), MVT::i8); 3126 3127 // determine if we should load from reg_save_area or overflow_area 3128 SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea); 3129 3130 // increase overflow_area by 4/8 if gpr/fpr > 8 3131 SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea, 3132 DAG.getConstant(VT.isInteger() ? 4 : 8, 3133 dl, MVT::i32)); 3134 3135 OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea, 3136 OverflowAreaPlusN); 3137 3138 InChain = DAG.getTruncStore(InChain, dl, OverflowArea, OverflowAreaPtr, 3139 MachinePointerInfo(), MVT::i32); 3140 3141 return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo()); 3142 } 3143 3144 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const { 3145 assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only"); 3146 3147 // We have to copy the entire va_list struct: 3148 // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte 3149 return DAG.getMemcpy(Op.getOperand(0), Op, Op.getOperand(1), Op.getOperand(2), 3150 DAG.getConstant(12, SDLoc(Op), MVT::i32), Align(8), 3151 false, true, false, MachinePointerInfo(), 3152 MachinePointerInfo()); 3153 } 3154 3155 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op, 3156 SelectionDAG &DAG) const { 3157 if (Subtarget.isAIXABI()) 3158 report_fatal_error("ADJUST_TRAMPOLINE operation is not supported on AIX."); 3159 3160 return Op.getOperand(0); 3161 } 3162 3163 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op, 3164 SelectionDAG &DAG) const { 3165 if (Subtarget.isAIXABI()) 3166 report_fatal_error("INIT_TRAMPOLINE operation is not supported on AIX."); 3167 3168 SDValue Chain = Op.getOperand(0); 3169 SDValue Trmp = Op.getOperand(1); // trampoline 3170 SDValue FPtr = Op.getOperand(2); // nested function 3171 SDValue Nest = Op.getOperand(3); // 'nest' parameter value 3172 SDLoc dl(Op); 3173 3174 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3175 bool isPPC64 = (PtrVT == MVT::i64); 3176 Type *IntPtrTy = DAG.getDataLayout().getIntPtrType(*DAG.getContext()); 3177 3178 TargetLowering::ArgListTy Args; 3179 TargetLowering::ArgListEntry Entry; 3180 3181 Entry.Ty = IntPtrTy; 3182 Entry.Node = Trmp; Args.push_back(Entry); 3183 3184 // TrampSize == (isPPC64 ? 48 : 40); 3185 Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40, dl, 3186 isPPC64 ? MVT::i64 : MVT::i32); 3187 Args.push_back(Entry); 3188 3189 Entry.Node = FPtr; Args.push_back(Entry); 3190 Entry.Node = Nest; Args.push_back(Entry); 3191 3192 // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg) 3193 TargetLowering::CallLoweringInfo CLI(DAG); 3194 CLI.setDebugLoc(dl).setChain(Chain).setLibCallee( 3195 CallingConv::C, Type::getVoidTy(*DAG.getContext()), 3196 DAG.getExternalSymbol("__trampoline_setup", PtrVT), std::move(Args)); 3197 3198 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 3199 return CallResult.second; 3200 } 3201 3202 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const { 3203 MachineFunction &MF = DAG.getMachineFunction(); 3204 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 3205 EVT PtrVT = getPointerTy(MF.getDataLayout()); 3206 3207 SDLoc dl(Op); 3208 3209 if (Subtarget.isPPC64()) { 3210 // vastart just stores the address of the VarArgsFrameIndex slot into the 3211 // memory location argument. 3212 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 3213 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 3214 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1), 3215 MachinePointerInfo(SV)); 3216 } 3217 3218 // For the 32-bit SVR4 ABI we follow the layout of the va_list struct. 3219 // We suppose the given va_list is already allocated. 3220 // 3221 // typedef struct { 3222 // char gpr; /* index into the array of 8 GPRs 3223 // * stored in the register save area 3224 // * gpr=0 corresponds to r3, 3225 // * gpr=1 to r4, etc. 3226 // */ 3227 // char fpr; /* index into the array of 8 FPRs 3228 // * stored in the register save area 3229 // * fpr=0 corresponds to f1, 3230 // * fpr=1 to f2, etc. 3231 // */ 3232 // char *overflow_arg_area; 3233 // /* location on stack that holds 3234 // * the next overflow argument 3235 // */ 3236 // char *reg_save_area; 3237 // /* where r3:r10 and f1:f8 (if saved) 3238 // * are stored 3239 // */ 3240 // } va_list[1]; 3241 3242 SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), dl, MVT::i32); 3243 SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), dl, MVT::i32); 3244 SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(), 3245 PtrVT); 3246 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), 3247 PtrVT); 3248 3249 uint64_t FrameOffset = PtrVT.getSizeInBits()/8; 3250 SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, dl, PtrVT); 3251 3252 uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1; 3253 SDValue ConstStackOffset = DAG.getConstant(StackOffset, dl, PtrVT); 3254 3255 uint64_t FPROffset = 1; 3256 SDValue ConstFPROffset = DAG.getConstant(FPROffset, dl, PtrVT); 3257 3258 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 3259 3260 // Store first byte : number of int regs 3261 SDValue firstStore = 3262 DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR, Op.getOperand(1), 3263 MachinePointerInfo(SV), MVT::i8); 3264 uint64_t nextOffset = FPROffset; 3265 SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1), 3266 ConstFPROffset); 3267 3268 // Store second byte : number of float regs 3269 SDValue secondStore = 3270 DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr, 3271 MachinePointerInfo(SV, nextOffset), MVT::i8); 3272 nextOffset += StackOffset; 3273 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset); 3274 3275 // Store second word : arguments given on stack 3276 SDValue thirdStore = DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr, 3277 MachinePointerInfo(SV, nextOffset)); 3278 nextOffset += FrameOffset; 3279 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset); 3280 3281 // Store third word : arguments given in registers 3282 return DAG.getStore(thirdStore, dl, FR, nextPtr, 3283 MachinePointerInfo(SV, nextOffset)); 3284 } 3285 3286 /// FPR - The set of FP registers that should be allocated for arguments 3287 /// on Darwin and AIX. 3288 static const MCPhysReg FPR[] = {PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, 3289 PPC::F6, PPC::F7, PPC::F8, PPC::F9, PPC::F10, 3290 PPC::F11, PPC::F12, PPC::F13}; 3291 3292 /// QFPR - The set of QPX registers that should be allocated for arguments. 3293 static const MCPhysReg QFPR[] = { 3294 PPC::QF1, PPC::QF2, PPC::QF3, PPC::QF4, PPC::QF5, PPC::QF6, PPC::QF7, 3295 PPC::QF8, PPC::QF9, PPC::QF10, PPC::QF11, PPC::QF12, PPC::QF13}; 3296 3297 /// CalculateStackSlotSize - Calculates the size reserved for this argument on 3298 /// the stack. 3299 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags, 3300 unsigned PtrByteSize) { 3301 unsigned ArgSize = ArgVT.getStoreSize(); 3302 if (Flags.isByVal()) 3303 ArgSize = Flags.getByValSize(); 3304 3305 // Round up to multiples of the pointer size, except for array members, 3306 // which are always packed. 3307 if (!Flags.isInConsecutiveRegs()) 3308 ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3309 3310 return ArgSize; 3311 } 3312 3313 /// CalculateStackSlotAlignment - Calculates the alignment of this argument 3314 /// on the stack. 3315 static Align CalculateStackSlotAlignment(EVT ArgVT, EVT OrigVT, 3316 ISD::ArgFlagsTy Flags, 3317 unsigned PtrByteSize) { 3318 Align Alignment(PtrByteSize); 3319 3320 // Altivec parameters are padded to a 16 byte boundary. 3321 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 || 3322 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 || 3323 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 || 3324 ArgVT == MVT::v1i128 || ArgVT == MVT::f128) 3325 Alignment = Align(16); 3326 // QPX vector types stored in double-precision are padded to a 32 byte 3327 // boundary. 3328 else if (ArgVT == MVT::v4f64 || ArgVT == MVT::v4i1) 3329 Alignment = Align(32); 3330 3331 // ByVal parameters are aligned as requested. 3332 if (Flags.isByVal()) { 3333 auto BVAlign = Flags.getNonZeroByValAlign(); 3334 if (BVAlign > PtrByteSize) { 3335 if (BVAlign.value() % PtrByteSize != 0) 3336 llvm_unreachable( 3337 "ByVal alignment is not a multiple of the pointer size"); 3338 3339 Alignment = BVAlign; 3340 } 3341 } 3342 3343 // Array members are always packed to their original alignment. 3344 if (Flags.isInConsecutiveRegs()) { 3345 // If the array member was split into multiple registers, the first 3346 // needs to be aligned to the size of the full type. (Except for 3347 // ppcf128, which is only aligned as its f64 components.) 3348 if (Flags.isSplit() && OrigVT != MVT::ppcf128) 3349 Alignment = Align(OrigVT.getStoreSize()); 3350 else 3351 Alignment = Align(ArgVT.getStoreSize()); 3352 } 3353 3354 return Alignment; 3355 } 3356 3357 /// CalculateStackSlotUsed - Return whether this argument will use its 3358 /// stack slot (instead of being passed in registers). ArgOffset, 3359 /// AvailableFPRs, and AvailableVRs must hold the current argument 3360 /// position, and will be updated to account for this argument. 3361 static bool CalculateStackSlotUsed(EVT ArgVT, EVT OrigVT, 3362 ISD::ArgFlagsTy Flags, 3363 unsigned PtrByteSize, 3364 unsigned LinkageSize, 3365 unsigned ParamAreaSize, 3366 unsigned &ArgOffset, 3367 unsigned &AvailableFPRs, 3368 unsigned &AvailableVRs, bool HasQPX) { 3369 bool UseMemory = false; 3370 3371 // Respect alignment of argument on the stack. 3372 Align Alignment = 3373 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize); 3374 ArgOffset = alignTo(ArgOffset, Alignment); 3375 // If there's no space left in the argument save area, we must 3376 // use memory (this check also catches zero-sized arguments). 3377 if (ArgOffset >= LinkageSize + ParamAreaSize) 3378 UseMemory = true; 3379 3380 // Allocate argument on the stack. 3381 ArgOffset += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize); 3382 if (Flags.isInConsecutiveRegsLast()) 3383 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3384 // If we overran the argument save area, we must use memory 3385 // (this check catches arguments passed partially in memory) 3386 if (ArgOffset > LinkageSize + ParamAreaSize) 3387 UseMemory = true; 3388 3389 // However, if the argument is actually passed in an FPR or a VR, 3390 // we don't use memory after all. 3391 if (!Flags.isByVal()) { 3392 if (ArgVT == MVT::f32 || ArgVT == MVT::f64 || 3393 // QPX registers overlap with the scalar FP registers. 3394 (HasQPX && (ArgVT == MVT::v4f32 || 3395 ArgVT == MVT::v4f64 || 3396 ArgVT == MVT::v4i1))) 3397 if (AvailableFPRs > 0) { 3398 --AvailableFPRs; 3399 return false; 3400 } 3401 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 || 3402 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 || 3403 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 || 3404 ArgVT == MVT::v1i128 || ArgVT == MVT::f128) 3405 if (AvailableVRs > 0) { 3406 --AvailableVRs; 3407 return false; 3408 } 3409 } 3410 3411 return UseMemory; 3412 } 3413 3414 /// EnsureStackAlignment - Round stack frame size up from NumBytes to 3415 /// ensure minimum alignment required for target. 3416 static unsigned EnsureStackAlignment(const PPCFrameLowering *Lowering, 3417 unsigned NumBytes) { 3418 unsigned TargetAlign = Lowering->getStackAlignment(); 3419 unsigned AlignMask = TargetAlign - 1; 3420 NumBytes = (NumBytes + AlignMask) & ~AlignMask; 3421 return NumBytes; 3422 } 3423 3424 SDValue PPCTargetLowering::LowerFormalArguments( 3425 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3426 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3427 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3428 if (Subtarget.isAIXABI()) 3429 return LowerFormalArguments_AIX(Chain, CallConv, isVarArg, Ins, dl, DAG, 3430 InVals); 3431 if (Subtarget.is64BitELFABI()) 3432 return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins, dl, DAG, 3433 InVals); 3434 if (Subtarget.is32BitELFABI()) 3435 return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins, dl, DAG, 3436 InVals); 3437 3438 return LowerFormalArguments_Darwin(Chain, CallConv, isVarArg, Ins, dl, DAG, 3439 InVals); 3440 } 3441 3442 SDValue PPCTargetLowering::LowerFormalArguments_32SVR4( 3443 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3444 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3445 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3446 3447 // 32-bit SVR4 ABI Stack Frame Layout: 3448 // +-----------------------------------+ 3449 // +--> | Back chain | 3450 // | +-----------------------------------+ 3451 // | | Floating-point register save area | 3452 // | +-----------------------------------+ 3453 // | | General register save area | 3454 // | +-----------------------------------+ 3455 // | | CR save word | 3456 // | +-----------------------------------+ 3457 // | | VRSAVE save word | 3458 // | +-----------------------------------+ 3459 // | | Alignment padding | 3460 // | +-----------------------------------+ 3461 // | | Vector register save area | 3462 // | +-----------------------------------+ 3463 // | | Local variable space | 3464 // | +-----------------------------------+ 3465 // | | Parameter list area | 3466 // | +-----------------------------------+ 3467 // | | LR save word | 3468 // | +-----------------------------------+ 3469 // SP--> +--- | Back chain | 3470 // +-----------------------------------+ 3471 // 3472 // Specifications: 3473 // System V Application Binary Interface PowerPC Processor Supplement 3474 // AltiVec Technology Programming Interface Manual 3475 3476 MachineFunction &MF = DAG.getMachineFunction(); 3477 MachineFrameInfo &MFI = MF.getFrameInfo(); 3478 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 3479 3480 EVT PtrVT = getPointerTy(MF.getDataLayout()); 3481 // Potential tail calls could cause overwriting of argument stack slots. 3482 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt && 3483 (CallConv == CallingConv::Fast)); 3484 unsigned PtrByteSize = 4; 3485 3486 // Assign locations to all of the incoming arguments. 3487 SmallVector<CCValAssign, 16> ArgLocs; 3488 PPCCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 3489 *DAG.getContext()); 3490 3491 // Reserve space for the linkage area on the stack. 3492 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 3493 CCInfo.AllocateStack(LinkageSize, PtrByteSize); 3494 if (useSoftFloat()) 3495 CCInfo.PreAnalyzeFormalArguments(Ins); 3496 3497 CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4); 3498 CCInfo.clearWasPPCF128(); 3499 3500 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 3501 CCValAssign &VA = ArgLocs[i]; 3502 3503 // Arguments stored in registers. 3504 if (VA.isRegLoc()) { 3505 const TargetRegisterClass *RC; 3506 EVT ValVT = VA.getValVT(); 3507 3508 switch (ValVT.getSimpleVT().SimpleTy) { 3509 default: 3510 llvm_unreachable("ValVT not supported by formal arguments Lowering"); 3511 case MVT::i1: 3512 case MVT::i32: 3513 RC = &PPC::GPRCRegClass; 3514 break; 3515 case MVT::f32: 3516 if (Subtarget.hasP8Vector()) 3517 RC = &PPC::VSSRCRegClass; 3518 else if (Subtarget.hasSPE()) 3519 RC = &PPC::GPRCRegClass; 3520 else 3521 RC = &PPC::F4RCRegClass; 3522 break; 3523 case MVT::f64: 3524 if (Subtarget.hasVSX()) 3525 RC = &PPC::VSFRCRegClass; 3526 else if (Subtarget.hasSPE()) 3527 // SPE passes doubles in GPR pairs. 3528 RC = &PPC::GPRCRegClass; 3529 else 3530 RC = &PPC::F8RCRegClass; 3531 break; 3532 case MVT::v16i8: 3533 case MVT::v8i16: 3534 case MVT::v4i32: 3535 RC = &PPC::VRRCRegClass; 3536 break; 3537 case MVT::v4f32: 3538 RC = Subtarget.hasQPX() ? &PPC::QSRCRegClass : &PPC::VRRCRegClass; 3539 break; 3540 case MVT::v2f64: 3541 case MVT::v2i64: 3542 RC = &PPC::VRRCRegClass; 3543 break; 3544 case MVT::v4f64: 3545 RC = &PPC::QFRCRegClass; 3546 break; 3547 case MVT::v4i1: 3548 RC = &PPC::QBRCRegClass; 3549 break; 3550 } 3551 3552 SDValue ArgValue; 3553 // Transform the arguments stored in physical registers into 3554 // virtual ones. 3555 if (VA.getLocVT() == MVT::f64 && Subtarget.hasSPE()) { 3556 assert(i + 1 < e && "No second half of double precision argument"); 3557 unsigned RegLo = MF.addLiveIn(VA.getLocReg(), RC); 3558 unsigned RegHi = MF.addLiveIn(ArgLocs[++i].getLocReg(), RC); 3559 SDValue ArgValueLo = DAG.getCopyFromReg(Chain, dl, RegLo, MVT::i32); 3560 SDValue ArgValueHi = DAG.getCopyFromReg(Chain, dl, RegHi, MVT::i32); 3561 if (!Subtarget.isLittleEndian()) 3562 std::swap (ArgValueLo, ArgValueHi); 3563 ArgValue = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, ArgValueLo, 3564 ArgValueHi); 3565 } else { 3566 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC); 3567 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, 3568 ValVT == MVT::i1 ? MVT::i32 : ValVT); 3569 if (ValVT == MVT::i1) 3570 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue); 3571 } 3572 3573 InVals.push_back(ArgValue); 3574 } else { 3575 // Argument stored in memory. 3576 assert(VA.isMemLoc()); 3577 3578 // Get the extended size of the argument type in stack 3579 unsigned ArgSize = VA.getLocVT().getStoreSize(); 3580 // Get the actual size of the argument type 3581 unsigned ObjSize = VA.getValVT().getStoreSize(); 3582 unsigned ArgOffset = VA.getLocMemOffset(); 3583 // Stack objects in PPC32 are right justified. 3584 ArgOffset += ArgSize - ObjSize; 3585 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, isImmutable); 3586 3587 // Create load nodes to retrieve arguments from the stack. 3588 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3589 InVals.push_back( 3590 DAG.getLoad(VA.getValVT(), dl, Chain, FIN, MachinePointerInfo())); 3591 } 3592 } 3593 3594 // Assign locations to all of the incoming aggregate by value arguments. 3595 // Aggregates passed by value are stored in the local variable space of the 3596 // caller's stack frame, right above the parameter list area. 3597 SmallVector<CCValAssign, 16> ByValArgLocs; 3598 CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(), 3599 ByValArgLocs, *DAG.getContext()); 3600 3601 // Reserve stack space for the allocations in CCInfo. 3602 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize); 3603 3604 CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal); 3605 3606 // Area that is at least reserved in the caller of this function. 3607 unsigned MinReservedArea = CCByValInfo.getNextStackOffset(); 3608 MinReservedArea = std::max(MinReservedArea, LinkageSize); 3609 3610 // Set the size that is at least reserved in caller of this function. Tail 3611 // call optimized function's reserved stack space needs to be aligned so that 3612 // taking the difference between two stack areas will result in an aligned 3613 // stack. 3614 MinReservedArea = 3615 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea); 3616 FuncInfo->setMinReservedArea(MinReservedArea); 3617 3618 SmallVector<SDValue, 8> MemOps; 3619 3620 // If the function takes variable number of arguments, make a frame index for 3621 // the start of the first vararg value... for expansion of llvm.va_start. 3622 if (isVarArg) { 3623 static const MCPhysReg GPArgRegs[] = { 3624 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 3625 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 3626 }; 3627 const unsigned NumGPArgRegs = array_lengthof(GPArgRegs); 3628 3629 static const MCPhysReg FPArgRegs[] = { 3630 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7, 3631 PPC::F8 3632 }; 3633 unsigned NumFPArgRegs = array_lengthof(FPArgRegs); 3634 3635 if (useSoftFloat() || hasSPE()) 3636 NumFPArgRegs = 0; 3637 3638 FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs)); 3639 FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs)); 3640 3641 // Make room for NumGPArgRegs and NumFPArgRegs. 3642 int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 + 3643 NumFPArgRegs * MVT(MVT::f64).getSizeInBits()/8; 3644 3645 FuncInfo->setVarArgsStackOffset( 3646 MFI.CreateFixedObject(PtrVT.getSizeInBits()/8, 3647 CCInfo.getNextStackOffset(), true)); 3648 3649 FuncInfo->setVarArgsFrameIndex(MFI.CreateStackObject(Depth, 8, false)); 3650 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 3651 3652 // The fixed integer arguments of a variadic function are stored to the 3653 // VarArgsFrameIndex on the stack so that they may be loaded by 3654 // dereferencing the result of va_next. 3655 for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) { 3656 // Get an existing live-in vreg, or add a new one. 3657 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]); 3658 if (!VReg) 3659 VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass); 3660 3661 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 3662 SDValue Store = 3663 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 3664 MemOps.push_back(Store); 3665 // Increment the address by four for the next argument to store 3666 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT); 3667 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 3668 } 3669 3670 // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6 3671 // is set. 3672 // The double arguments are stored to the VarArgsFrameIndex 3673 // on the stack. 3674 for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) { 3675 // Get an existing live-in vreg, or add a new one. 3676 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]); 3677 if (!VReg) 3678 VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass); 3679 3680 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64); 3681 SDValue Store = 3682 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 3683 MemOps.push_back(Store); 3684 // Increment the address by eight for the next argument to store 3685 SDValue PtrOff = DAG.getConstant(MVT(MVT::f64).getSizeInBits()/8, dl, 3686 PtrVT); 3687 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 3688 } 3689 } 3690 3691 if (!MemOps.empty()) 3692 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 3693 3694 return Chain; 3695 } 3696 3697 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote 3698 // value to MVT::i64 and then truncate to the correct register size. 3699 SDValue PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags, 3700 EVT ObjectVT, SelectionDAG &DAG, 3701 SDValue ArgVal, 3702 const SDLoc &dl) const { 3703 if (Flags.isSExt()) 3704 ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal, 3705 DAG.getValueType(ObjectVT)); 3706 else if (Flags.isZExt()) 3707 ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal, 3708 DAG.getValueType(ObjectVT)); 3709 3710 return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal); 3711 } 3712 3713 SDValue PPCTargetLowering::LowerFormalArguments_64SVR4( 3714 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3715 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3716 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3717 // TODO: add description of PPC stack frame format, or at least some docs. 3718 // 3719 bool isELFv2ABI = Subtarget.isELFv2ABI(); 3720 bool isLittleEndian = Subtarget.isLittleEndian(); 3721 MachineFunction &MF = DAG.getMachineFunction(); 3722 MachineFrameInfo &MFI = MF.getFrameInfo(); 3723 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 3724 3725 assert(!(CallConv == CallingConv::Fast && isVarArg) && 3726 "fastcc not supported on varargs functions"); 3727 3728 EVT PtrVT = getPointerTy(MF.getDataLayout()); 3729 // Potential tail calls could cause overwriting of argument stack slots. 3730 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt && 3731 (CallConv == CallingConv::Fast)); 3732 unsigned PtrByteSize = 8; 3733 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 3734 3735 static const MCPhysReg GPR[] = { 3736 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 3737 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 3738 }; 3739 static const MCPhysReg VR[] = { 3740 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 3741 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 3742 }; 3743 3744 const unsigned Num_GPR_Regs = array_lengthof(GPR); 3745 const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13; 3746 const unsigned Num_VR_Regs = array_lengthof(VR); 3747 const unsigned Num_QFPR_Regs = Num_FPR_Regs; 3748 3749 // Do a first pass over the arguments to determine whether the ABI 3750 // guarantees that our caller has allocated the parameter save area 3751 // on its stack frame. In the ELFv1 ABI, this is always the case; 3752 // in the ELFv2 ABI, it is true if this is a vararg function or if 3753 // any parameter is located in a stack slot. 3754 3755 bool HasParameterArea = !isELFv2ABI || isVarArg; 3756 unsigned ParamAreaSize = Num_GPR_Regs * PtrByteSize; 3757 unsigned NumBytes = LinkageSize; 3758 unsigned AvailableFPRs = Num_FPR_Regs; 3759 unsigned AvailableVRs = Num_VR_Regs; 3760 for (unsigned i = 0, e = Ins.size(); i != e; ++i) { 3761 if (Ins[i].Flags.isNest()) 3762 continue; 3763 3764 if (CalculateStackSlotUsed(Ins[i].VT, Ins[i].ArgVT, Ins[i].Flags, 3765 PtrByteSize, LinkageSize, ParamAreaSize, 3766 NumBytes, AvailableFPRs, AvailableVRs, 3767 Subtarget.hasQPX())) 3768 HasParameterArea = true; 3769 } 3770 3771 // Add DAG nodes to load the arguments or copy them out of registers. On 3772 // entry to a function on PPC, the arguments start after the linkage area, 3773 // although the first ones are often in registers. 3774 3775 unsigned ArgOffset = LinkageSize; 3776 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 3777 unsigned &QFPR_idx = FPR_idx; 3778 SmallVector<SDValue, 8> MemOps; 3779 Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin(); 3780 unsigned CurArgIdx = 0; 3781 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) { 3782 SDValue ArgVal; 3783 bool needsLoad = false; 3784 EVT ObjectVT = Ins[ArgNo].VT; 3785 EVT OrigVT = Ins[ArgNo].ArgVT; 3786 unsigned ObjSize = ObjectVT.getStoreSize(); 3787 unsigned ArgSize = ObjSize; 3788 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags; 3789 if (Ins[ArgNo].isOrigArg()) { 3790 std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx); 3791 CurArgIdx = Ins[ArgNo].getOrigArgIndex(); 3792 } 3793 // We re-align the argument offset for each argument, except when using the 3794 // fast calling convention, when we need to make sure we do that only when 3795 // we'll actually use a stack slot. 3796 unsigned CurArgOffset; 3797 Align Alignment; 3798 auto ComputeArgOffset = [&]() { 3799 /* Respect alignment of argument on the stack. */ 3800 Alignment = 3801 CalculateStackSlotAlignment(ObjectVT, OrigVT, Flags, PtrByteSize); 3802 ArgOffset = alignTo(ArgOffset, Alignment); 3803 CurArgOffset = ArgOffset; 3804 }; 3805 3806 if (CallConv != CallingConv::Fast) { 3807 ComputeArgOffset(); 3808 3809 /* Compute GPR index associated with argument offset. */ 3810 GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize; 3811 GPR_idx = std::min(GPR_idx, Num_GPR_Regs); 3812 } 3813 3814 // FIXME the codegen can be much improved in some cases. 3815 // We do not have to keep everything in memory. 3816 if (Flags.isByVal()) { 3817 assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit"); 3818 3819 if (CallConv == CallingConv::Fast) 3820 ComputeArgOffset(); 3821 3822 // ObjSize is the true size, ArgSize rounded up to multiple of registers. 3823 ObjSize = Flags.getByValSize(); 3824 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3825 // Empty aggregate parameters do not take up registers. Examples: 3826 // struct { } a; 3827 // union { } b; 3828 // int c[0]; 3829 // etc. However, we have to provide a place-holder in InVals, so 3830 // pretend we have an 8-byte item at the current address for that 3831 // purpose. 3832 if (!ObjSize) { 3833 int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true); 3834 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3835 InVals.push_back(FIN); 3836 continue; 3837 } 3838 3839 // Create a stack object covering all stack doublewords occupied 3840 // by the argument. If the argument is (fully or partially) on 3841 // the stack, or if the argument is fully in registers but the 3842 // caller has allocated the parameter save anyway, we can refer 3843 // directly to the caller's stack frame. Otherwise, create a 3844 // local copy in our own frame. 3845 int FI; 3846 if (HasParameterArea || 3847 ArgSize + ArgOffset > LinkageSize + Num_GPR_Regs * PtrByteSize) 3848 FI = MFI.CreateFixedObject(ArgSize, ArgOffset, false, true); 3849 else 3850 FI = MFI.CreateStackObject(ArgSize, Alignment, false); 3851 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3852 3853 // Handle aggregates smaller than 8 bytes. 3854 if (ObjSize < PtrByteSize) { 3855 // The value of the object is its address, which differs from the 3856 // address of the enclosing doubleword on big-endian systems. 3857 SDValue Arg = FIN; 3858 if (!isLittleEndian) { 3859 SDValue ArgOff = DAG.getConstant(PtrByteSize - ObjSize, dl, PtrVT); 3860 Arg = DAG.getNode(ISD::ADD, dl, ArgOff.getValueType(), Arg, ArgOff); 3861 } 3862 InVals.push_back(Arg); 3863 3864 if (GPR_idx != Num_GPR_Regs) { 3865 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass); 3866 FuncInfo->addLiveInAttr(VReg, Flags); 3867 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 3868 SDValue Store; 3869 3870 if (ObjSize==1 || ObjSize==2 || ObjSize==4) { 3871 EVT ObjType = (ObjSize == 1 ? MVT::i8 : 3872 (ObjSize == 2 ? MVT::i16 : MVT::i32)); 3873 Store = DAG.getTruncStore(Val.getValue(1), dl, Val, Arg, 3874 MachinePointerInfo(&*FuncArg), ObjType); 3875 } else { 3876 // For sizes that don't fit a truncating store (3, 5, 6, 7), 3877 // store the whole register as-is to the parameter save area 3878 // slot. 3879 Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, 3880 MachinePointerInfo(&*FuncArg)); 3881 } 3882 3883 MemOps.push_back(Store); 3884 } 3885 // Whether we copied from a register or not, advance the offset 3886 // into the parameter save area by a full doubleword. 3887 ArgOffset += PtrByteSize; 3888 continue; 3889 } 3890 3891 // The value of the object is its address, which is the address of 3892 // its first stack doubleword. 3893 InVals.push_back(FIN); 3894 3895 // Store whatever pieces of the object are in registers to memory. 3896 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) { 3897 if (GPR_idx == Num_GPR_Regs) 3898 break; 3899 3900 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 3901 FuncInfo->addLiveInAttr(VReg, Flags); 3902 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 3903 SDValue Addr = FIN; 3904 if (j) { 3905 SDValue Off = DAG.getConstant(j, dl, PtrVT); 3906 Addr = DAG.getNode(ISD::ADD, dl, Off.getValueType(), Addr, Off); 3907 } 3908 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, Addr, 3909 MachinePointerInfo(&*FuncArg, j)); 3910 MemOps.push_back(Store); 3911 ++GPR_idx; 3912 } 3913 ArgOffset += ArgSize; 3914 continue; 3915 } 3916 3917 switch (ObjectVT.getSimpleVT().SimpleTy) { 3918 default: llvm_unreachable("Unhandled argument type!"); 3919 case MVT::i1: 3920 case MVT::i32: 3921 case MVT::i64: 3922 if (Flags.isNest()) { 3923 // The 'nest' parameter, if any, is passed in R11. 3924 unsigned VReg = MF.addLiveIn(PPC::X11, &PPC::G8RCRegClass); 3925 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 3926 3927 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1) 3928 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl); 3929 3930 break; 3931 } 3932 3933 // These can be scalar arguments or elements of an integer array type 3934 // passed directly. Clang may use those instead of "byval" aggregate 3935 // types to avoid forcing arguments to memory unnecessarily. 3936 if (GPR_idx != Num_GPR_Regs) { 3937 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass); 3938 FuncInfo->addLiveInAttr(VReg, Flags); 3939 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 3940 3941 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1) 3942 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote 3943 // value to MVT::i64 and then truncate to the correct register size. 3944 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl); 3945 } else { 3946 if (CallConv == CallingConv::Fast) 3947 ComputeArgOffset(); 3948 3949 needsLoad = true; 3950 ArgSize = PtrByteSize; 3951 } 3952 if (CallConv != CallingConv::Fast || needsLoad) 3953 ArgOffset += 8; 3954 break; 3955 3956 case MVT::f32: 3957 case MVT::f64: 3958 // These can be scalar arguments or elements of a float array type 3959 // passed directly. The latter are used to implement ELFv2 homogenous 3960 // float aggregates. 3961 if (FPR_idx != Num_FPR_Regs) { 3962 unsigned VReg; 3963 3964 if (ObjectVT == MVT::f32) 3965 VReg = MF.addLiveIn(FPR[FPR_idx], 3966 Subtarget.hasP8Vector() 3967 ? &PPC::VSSRCRegClass 3968 : &PPC::F4RCRegClass); 3969 else 3970 VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX() 3971 ? &PPC::VSFRCRegClass 3972 : &PPC::F8RCRegClass); 3973 3974 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 3975 ++FPR_idx; 3976 } else if (GPR_idx != Num_GPR_Regs && CallConv != CallingConv::Fast) { 3977 // FIXME: We may want to re-enable this for CallingConv::Fast on the P8 3978 // once we support fp <-> gpr moves. 3979 3980 // This can only ever happen in the presence of f32 array types, 3981 // since otherwise we never run out of FPRs before running out 3982 // of GPRs. 3983 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass); 3984 FuncInfo->addLiveInAttr(VReg, Flags); 3985 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 3986 3987 if (ObjectVT == MVT::f32) { 3988 if ((ArgOffset % PtrByteSize) == (isLittleEndian ? 4 : 0)) 3989 ArgVal = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgVal, 3990 DAG.getConstant(32, dl, MVT::i32)); 3991 ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal); 3992 } 3993 3994 ArgVal = DAG.getNode(ISD::BITCAST, dl, ObjectVT, ArgVal); 3995 } else { 3996 if (CallConv == CallingConv::Fast) 3997 ComputeArgOffset(); 3998 3999 needsLoad = true; 4000 } 4001 4002 // When passing an array of floats, the array occupies consecutive 4003 // space in the argument area; only round up to the next doubleword 4004 // at the end of the array. Otherwise, each float takes 8 bytes. 4005 if (CallConv != CallingConv::Fast || needsLoad) { 4006 ArgSize = Flags.isInConsecutiveRegs() ? ObjSize : PtrByteSize; 4007 ArgOffset += ArgSize; 4008 if (Flags.isInConsecutiveRegsLast()) 4009 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 4010 } 4011 break; 4012 case MVT::v4f32: 4013 case MVT::v4i32: 4014 case MVT::v8i16: 4015 case MVT::v16i8: 4016 case MVT::v2f64: 4017 case MVT::v2i64: 4018 case MVT::v1i128: 4019 case MVT::f128: 4020 if (!Subtarget.hasQPX()) { 4021 // These can be scalar arguments or elements of a vector array type 4022 // passed directly. The latter are used to implement ELFv2 homogenous 4023 // vector aggregates. 4024 if (VR_idx != Num_VR_Regs) { 4025 unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass); 4026 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 4027 ++VR_idx; 4028 } else { 4029 if (CallConv == CallingConv::Fast) 4030 ComputeArgOffset(); 4031 needsLoad = true; 4032 } 4033 if (CallConv != CallingConv::Fast || needsLoad) 4034 ArgOffset += 16; 4035 break; 4036 } // not QPX 4037 4038 assert(ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 && 4039 "Invalid QPX parameter type"); 4040 LLVM_FALLTHROUGH; 4041 4042 case MVT::v4f64: 4043 case MVT::v4i1: 4044 // QPX vectors are treated like their scalar floating-point subregisters 4045 // (except that they're larger). 4046 unsigned Sz = ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 ? 16 : 32; 4047 if (QFPR_idx != Num_QFPR_Regs) { 4048 const TargetRegisterClass *RC; 4049 switch (ObjectVT.getSimpleVT().SimpleTy) { 4050 case MVT::v4f64: RC = &PPC::QFRCRegClass; break; 4051 case MVT::v4f32: RC = &PPC::QSRCRegClass; break; 4052 default: RC = &PPC::QBRCRegClass; break; 4053 } 4054 4055 unsigned VReg = MF.addLiveIn(QFPR[QFPR_idx], RC); 4056 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 4057 ++QFPR_idx; 4058 } else { 4059 if (CallConv == CallingConv::Fast) 4060 ComputeArgOffset(); 4061 needsLoad = true; 4062 } 4063 if (CallConv != CallingConv::Fast || needsLoad) 4064 ArgOffset += Sz; 4065 break; 4066 } 4067 4068 // We need to load the argument to a virtual register if we determined 4069 // above that we ran out of physical registers of the appropriate type. 4070 if (needsLoad) { 4071 if (ObjSize < ArgSize && !isLittleEndian) 4072 CurArgOffset += ArgSize - ObjSize; 4073 int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, isImmutable); 4074 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4075 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo()); 4076 } 4077 4078 InVals.push_back(ArgVal); 4079 } 4080 4081 // Area that is at least reserved in the caller of this function. 4082 unsigned MinReservedArea; 4083 if (HasParameterArea) 4084 MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize); 4085 else 4086 MinReservedArea = LinkageSize; 4087 4088 // Set the size that is at least reserved in caller of this function. Tail 4089 // call optimized functions' reserved stack space needs to be aligned so that 4090 // taking the difference between two stack areas will result in an aligned 4091 // stack. 4092 MinReservedArea = 4093 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea); 4094 FuncInfo->setMinReservedArea(MinReservedArea); 4095 4096 // If the function takes variable number of arguments, make a frame index for 4097 // the start of the first vararg value... for expansion of llvm.va_start. 4098 if (isVarArg) { 4099 int Depth = ArgOffset; 4100 4101 FuncInfo->setVarArgsFrameIndex( 4102 MFI.CreateFixedObject(PtrByteSize, Depth, true)); 4103 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 4104 4105 // If this function is vararg, store any remaining integer argument regs 4106 // to their spots on the stack so that they may be loaded by dereferencing 4107 // the result of va_next. 4108 for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize; 4109 GPR_idx < Num_GPR_Regs; ++GPR_idx) { 4110 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4111 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4112 SDValue Store = 4113 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 4114 MemOps.push_back(Store); 4115 // Increment the address by four for the next argument to store 4116 SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT); 4117 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 4118 } 4119 } 4120 4121 if (!MemOps.empty()) 4122 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 4123 4124 return Chain; 4125 } 4126 4127 SDValue PPCTargetLowering::LowerFormalArguments_Darwin( 4128 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 4129 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 4130 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 4131 // TODO: add description of PPC stack frame format, or at least some docs. 4132 // 4133 MachineFunction &MF = DAG.getMachineFunction(); 4134 MachineFrameInfo &MFI = MF.getFrameInfo(); 4135 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 4136 4137 EVT PtrVT = getPointerTy(MF.getDataLayout()); 4138 bool isPPC64 = PtrVT == MVT::i64; 4139 // Potential tail calls could cause overwriting of argument stack slots. 4140 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt && 4141 (CallConv == CallingConv::Fast)); 4142 unsigned PtrByteSize = isPPC64 ? 8 : 4; 4143 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 4144 unsigned ArgOffset = LinkageSize; 4145 // Area that is at least reserved in caller of this function. 4146 unsigned MinReservedArea = ArgOffset; 4147 4148 static const MCPhysReg GPR_32[] = { // 32-bit registers. 4149 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 4150 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 4151 }; 4152 static const MCPhysReg GPR_64[] = { // 64-bit registers. 4153 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 4154 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 4155 }; 4156 static const MCPhysReg VR[] = { 4157 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 4158 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 4159 }; 4160 4161 const unsigned Num_GPR_Regs = array_lengthof(GPR_32); 4162 const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13; 4163 const unsigned Num_VR_Regs = array_lengthof( VR); 4164 4165 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 4166 4167 const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32; 4168 4169 // In 32-bit non-varargs functions, the stack space for vectors is after the 4170 // stack space for non-vectors. We do not use this space unless we have 4171 // too many vectors to fit in registers, something that only occurs in 4172 // constructed examples:), but we have to walk the arglist to figure 4173 // that out...for the pathological case, compute VecArgOffset as the 4174 // start of the vector parameter area. Computing VecArgOffset is the 4175 // entire point of the following loop. 4176 unsigned VecArgOffset = ArgOffset; 4177 if (!isVarArg && !isPPC64) { 4178 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; 4179 ++ArgNo) { 4180 EVT ObjectVT = Ins[ArgNo].VT; 4181 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags; 4182 4183 if (Flags.isByVal()) { 4184 // ObjSize is the true size, ArgSize rounded up to multiple of regs. 4185 unsigned ObjSize = Flags.getByValSize(); 4186 unsigned ArgSize = 4187 ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 4188 VecArgOffset += ArgSize; 4189 continue; 4190 } 4191 4192 switch(ObjectVT.getSimpleVT().SimpleTy) { 4193 default: llvm_unreachable("Unhandled argument type!"); 4194 case MVT::i1: 4195 case MVT::i32: 4196 case MVT::f32: 4197 VecArgOffset += 4; 4198 break; 4199 case MVT::i64: // PPC64 4200 case MVT::f64: 4201 // FIXME: We are guaranteed to be !isPPC64 at this point. 4202 // Does MVT::i64 apply? 4203 VecArgOffset += 8; 4204 break; 4205 case MVT::v4f32: 4206 case MVT::v4i32: 4207 case MVT::v8i16: 4208 case MVT::v16i8: 4209 // Nothing to do, we're only looking at Nonvector args here. 4210 break; 4211 } 4212 } 4213 } 4214 // We've found where the vector parameter area in memory is. Skip the 4215 // first 12 parameters; these don't use that memory. 4216 VecArgOffset = ((VecArgOffset+15)/16)*16; 4217 VecArgOffset += 12*16; 4218 4219 // Add DAG nodes to load the arguments or copy them out of registers. On 4220 // entry to a function on PPC, the arguments start after the linkage area, 4221 // although the first ones are often in registers. 4222 4223 SmallVector<SDValue, 8> MemOps; 4224 unsigned nAltivecParamsAtEnd = 0; 4225 Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin(); 4226 unsigned CurArgIdx = 0; 4227 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) { 4228 SDValue ArgVal; 4229 bool needsLoad = false; 4230 EVT ObjectVT = Ins[ArgNo].VT; 4231 unsigned ObjSize = ObjectVT.getSizeInBits()/8; 4232 unsigned ArgSize = ObjSize; 4233 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags; 4234 if (Ins[ArgNo].isOrigArg()) { 4235 std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx); 4236 CurArgIdx = Ins[ArgNo].getOrigArgIndex(); 4237 } 4238 unsigned CurArgOffset = ArgOffset; 4239 4240 // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary. 4241 if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 || 4242 ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) { 4243 if (isVarArg || isPPC64) { 4244 MinReservedArea = ((MinReservedArea+15)/16)*16; 4245 MinReservedArea += CalculateStackSlotSize(ObjectVT, 4246 Flags, 4247 PtrByteSize); 4248 } else nAltivecParamsAtEnd++; 4249 } else 4250 // Calculate min reserved area. 4251 MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT, 4252 Flags, 4253 PtrByteSize); 4254 4255 // FIXME the codegen can be much improved in some cases. 4256 // We do not have to keep everything in memory. 4257 if (Flags.isByVal()) { 4258 assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit"); 4259 4260 // ObjSize is the true size, ArgSize rounded up to multiple of registers. 4261 ObjSize = Flags.getByValSize(); 4262 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 4263 // Objects of size 1 and 2 are right justified, everything else is 4264 // left justified. This means the memory address is adjusted forwards. 4265 if (ObjSize==1 || ObjSize==2) { 4266 CurArgOffset = CurArgOffset + (4 - ObjSize); 4267 } 4268 // The value of the object is its address. 4269 int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, false, true); 4270 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4271 InVals.push_back(FIN); 4272 if (ObjSize==1 || ObjSize==2) { 4273 if (GPR_idx != Num_GPR_Regs) { 4274 unsigned VReg; 4275 if (isPPC64) 4276 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4277 else 4278 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 4279 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4280 EVT ObjType = ObjSize == 1 ? MVT::i8 : MVT::i16; 4281 SDValue Store = 4282 DAG.getTruncStore(Val.getValue(1), dl, Val, FIN, 4283 MachinePointerInfo(&*FuncArg), ObjType); 4284 MemOps.push_back(Store); 4285 ++GPR_idx; 4286 } 4287 4288 ArgOffset += PtrByteSize; 4289 4290 continue; 4291 } 4292 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) { 4293 // Store whatever pieces of the object are in registers 4294 // to memory. ArgOffset will be the address of the beginning 4295 // of the object. 4296 if (GPR_idx != Num_GPR_Regs) { 4297 unsigned VReg; 4298 if (isPPC64) 4299 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4300 else 4301 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 4302 int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true); 4303 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4304 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4305 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, 4306 MachinePointerInfo(&*FuncArg, j)); 4307 MemOps.push_back(Store); 4308 ++GPR_idx; 4309 ArgOffset += PtrByteSize; 4310 } else { 4311 ArgOffset += ArgSize - (ArgOffset-CurArgOffset); 4312 break; 4313 } 4314 } 4315 continue; 4316 } 4317 4318 switch (ObjectVT.getSimpleVT().SimpleTy) { 4319 default: llvm_unreachable("Unhandled argument type!"); 4320 case MVT::i1: 4321 case MVT::i32: 4322 if (!isPPC64) { 4323 if (GPR_idx != Num_GPR_Regs) { 4324 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 4325 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32); 4326 4327 if (ObjectVT == MVT::i1) 4328 ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgVal); 4329 4330 ++GPR_idx; 4331 } else { 4332 needsLoad = true; 4333 ArgSize = PtrByteSize; 4334 } 4335 // All int arguments reserve stack space in the Darwin ABI. 4336 ArgOffset += PtrByteSize; 4337 break; 4338 } 4339 LLVM_FALLTHROUGH; 4340 case MVT::i64: // PPC64 4341 if (GPR_idx != Num_GPR_Regs) { 4342 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4343 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 4344 4345 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1) 4346 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote 4347 // value to MVT::i64 and then truncate to the correct register size. 4348 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl); 4349 4350 ++GPR_idx; 4351 } else { 4352 needsLoad = true; 4353 ArgSize = PtrByteSize; 4354 } 4355 // All int arguments reserve stack space in the Darwin ABI. 4356 ArgOffset += 8; 4357 break; 4358 4359 case MVT::f32: 4360 case MVT::f64: 4361 // Every 4 bytes of argument space consumes one of the GPRs available for 4362 // argument passing. 4363 if (GPR_idx != Num_GPR_Regs) { 4364 ++GPR_idx; 4365 if (ObjSize == 8 && GPR_idx != Num_GPR_Regs && !isPPC64) 4366 ++GPR_idx; 4367 } 4368 if (FPR_idx != Num_FPR_Regs) { 4369 unsigned VReg; 4370 4371 if (ObjectVT == MVT::f32) 4372 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass); 4373 else 4374 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass); 4375 4376 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 4377 ++FPR_idx; 4378 } else { 4379 needsLoad = true; 4380 } 4381 4382 // All FP arguments reserve stack space in the Darwin ABI. 4383 ArgOffset += isPPC64 ? 8 : ObjSize; 4384 break; 4385 case MVT::v4f32: 4386 case MVT::v4i32: 4387 case MVT::v8i16: 4388 case MVT::v16i8: 4389 // Note that vector arguments in registers don't reserve stack space, 4390 // except in varargs functions. 4391 if (VR_idx != Num_VR_Regs) { 4392 unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass); 4393 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 4394 if (isVarArg) { 4395 while ((ArgOffset % 16) != 0) { 4396 ArgOffset += PtrByteSize; 4397 if (GPR_idx != Num_GPR_Regs) 4398 GPR_idx++; 4399 } 4400 ArgOffset += 16; 4401 GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64? 4402 } 4403 ++VR_idx; 4404 } else { 4405 if (!isVarArg && !isPPC64) { 4406 // Vectors go after all the nonvectors. 4407 CurArgOffset = VecArgOffset; 4408 VecArgOffset += 16; 4409 } else { 4410 // Vectors are aligned. 4411 ArgOffset = ((ArgOffset+15)/16)*16; 4412 CurArgOffset = ArgOffset; 4413 ArgOffset += 16; 4414 } 4415 needsLoad = true; 4416 } 4417 break; 4418 } 4419 4420 // We need to load the argument to a virtual register if we determined above 4421 // that we ran out of physical registers of the appropriate type. 4422 if (needsLoad) { 4423 int FI = MFI.CreateFixedObject(ObjSize, 4424 CurArgOffset + (ArgSize - ObjSize), 4425 isImmutable); 4426 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4427 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo()); 4428 } 4429 4430 InVals.push_back(ArgVal); 4431 } 4432 4433 // Allow for Altivec parameters at the end, if needed. 4434 if (nAltivecParamsAtEnd) { 4435 MinReservedArea = ((MinReservedArea+15)/16)*16; 4436 MinReservedArea += 16*nAltivecParamsAtEnd; 4437 } 4438 4439 // Area that is at least reserved in the caller of this function. 4440 MinReservedArea = std::max(MinReservedArea, LinkageSize + 8 * PtrByteSize); 4441 4442 // Set the size that is at least reserved in caller of this function. Tail 4443 // call optimized functions' reserved stack space needs to be aligned so that 4444 // taking the difference between two stack areas will result in an aligned 4445 // stack. 4446 MinReservedArea = 4447 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea); 4448 FuncInfo->setMinReservedArea(MinReservedArea); 4449 4450 // If the function takes variable number of arguments, make a frame index for 4451 // the start of the first vararg value... for expansion of llvm.va_start. 4452 if (isVarArg) { 4453 int Depth = ArgOffset; 4454 4455 FuncInfo->setVarArgsFrameIndex( 4456 MFI.CreateFixedObject(PtrVT.getSizeInBits()/8, 4457 Depth, true)); 4458 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 4459 4460 // If this function is vararg, store any remaining integer argument regs 4461 // to their spots on the stack so that they may be loaded by dereferencing 4462 // the result of va_next. 4463 for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) { 4464 unsigned VReg; 4465 4466 if (isPPC64) 4467 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4468 else 4469 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 4470 4471 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4472 SDValue Store = 4473 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 4474 MemOps.push_back(Store); 4475 // Increment the address by four for the next argument to store 4476 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT); 4477 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 4478 } 4479 } 4480 4481 if (!MemOps.empty()) 4482 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 4483 4484 return Chain; 4485 } 4486 4487 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be 4488 /// adjusted to accommodate the arguments for the tailcall. 4489 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall, 4490 unsigned ParamSize) { 4491 4492 if (!isTailCall) return 0; 4493 4494 PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>(); 4495 unsigned CallerMinReservedArea = FI->getMinReservedArea(); 4496 int SPDiff = (int)CallerMinReservedArea - (int)ParamSize; 4497 // Remember only if the new adjustment is bigger. 4498 if (SPDiff < FI->getTailCallSPDelta()) 4499 FI->setTailCallSPDelta(SPDiff); 4500 4501 return SPDiff; 4502 } 4503 4504 static bool isFunctionGlobalAddress(SDValue Callee); 4505 4506 static bool 4507 callsShareTOCBase(const Function *Caller, SDValue Callee, 4508 const TargetMachine &TM) { 4509 // Callee is either a GlobalAddress or an ExternalSymbol. ExternalSymbols 4510 // don't have enough information to determine if the caller and calle share 4511 // the same TOC base, so we have to pessimistically assume they don't for 4512 // correctness. 4513 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee); 4514 if (!G) 4515 return false; 4516 4517 const GlobalValue *GV = G->getGlobal(); 4518 // The medium and large code models are expected to provide a sufficiently 4519 // large TOC to provide all data addressing needs of a module with a 4520 // single TOC. Since each module will be addressed with a single TOC then we 4521 // only need to check that caller and callee don't cross dso boundaries. 4522 if (CodeModel::Medium == TM.getCodeModel() || 4523 CodeModel::Large == TM.getCodeModel()) 4524 return TM.shouldAssumeDSOLocal(*Caller->getParent(), GV); 4525 4526 // Otherwise we need to ensure callee and caller are in the same section, 4527 // since the linker may allocate multiple TOCs, and we don't know which 4528 // sections will belong to the same TOC base. 4529 4530 if (!GV->isStrongDefinitionForLinker()) 4531 return false; 4532 4533 // Any explicitly-specified sections and section prefixes must also match. 4534 // Also, if we're using -ffunction-sections, then each function is always in 4535 // a different section (the same is true for COMDAT functions). 4536 if (TM.getFunctionSections() || GV->hasComdat() || Caller->hasComdat() || 4537 GV->getSection() != Caller->getSection()) 4538 return false; 4539 if (const auto *F = dyn_cast<Function>(GV)) { 4540 if (F->getSectionPrefix() != Caller->getSectionPrefix()) 4541 return false; 4542 } 4543 4544 // If the callee might be interposed, then we can't assume the ultimate call 4545 // target will be in the same section. Even in cases where we can assume that 4546 // interposition won't happen, in any case where the linker might insert a 4547 // stub to allow for interposition, we must generate code as though 4548 // interposition might occur. To understand why this matters, consider a 4549 // situation where: a -> b -> c where the arrows indicate calls. b and c are 4550 // in the same section, but a is in a different module (i.e. has a different 4551 // TOC base pointer). If the linker allows for interposition between b and c, 4552 // then it will generate a stub for the call edge between b and c which will 4553 // save the TOC pointer into the designated stack slot allocated by b. If we 4554 // return true here, and therefore allow a tail call between b and c, that 4555 // stack slot won't exist and the b -> c stub will end up saving b'c TOC base 4556 // pointer into the stack slot allocated by a (where the a -> b stub saved 4557 // a's TOC base pointer). If we're not considering a tail call, but rather, 4558 // whether a nop is needed after the call instruction in b, because the linker 4559 // will insert a stub, it might complain about a missing nop if we omit it 4560 // (although many don't complain in this case). 4561 if (!TM.shouldAssumeDSOLocal(*Caller->getParent(), GV)) 4562 return false; 4563 4564 return true; 4565 } 4566 4567 static bool 4568 needStackSlotPassParameters(const PPCSubtarget &Subtarget, 4569 const SmallVectorImpl<ISD::OutputArg> &Outs) { 4570 assert(Subtarget.is64BitELFABI()); 4571 4572 const unsigned PtrByteSize = 8; 4573 const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 4574 4575 static const MCPhysReg GPR[] = { 4576 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 4577 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 4578 }; 4579 static const MCPhysReg VR[] = { 4580 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 4581 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 4582 }; 4583 4584 const unsigned NumGPRs = array_lengthof(GPR); 4585 const unsigned NumFPRs = 13; 4586 const unsigned NumVRs = array_lengthof(VR); 4587 const unsigned ParamAreaSize = NumGPRs * PtrByteSize; 4588 4589 unsigned NumBytes = LinkageSize; 4590 unsigned AvailableFPRs = NumFPRs; 4591 unsigned AvailableVRs = NumVRs; 4592 4593 for (const ISD::OutputArg& Param : Outs) { 4594 if (Param.Flags.isNest()) continue; 4595 4596 if (CalculateStackSlotUsed(Param.VT, Param.ArgVT, Param.Flags, 4597 PtrByteSize, LinkageSize, ParamAreaSize, 4598 NumBytes, AvailableFPRs, AvailableVRs, 4599 Subtarget.hasQPX())) 4600 return true; 4601 } 4602 return false; 4603 } 4604 4605 static bool 4606 hasSameArgumentList(const Function *CallerFn, ImmutableCallSite CS) { 4607 if (CS.arg_size() != CallerFn->arg_size()) 4608 return false; 4609 4610 ImmutableCallSite::arg_iterator CalleeArgIter = CS.arg_begin(); 4611 ImmutableCallSite::arg_iterator CalleeArgEnd = CS.arg_end(); 4612 Function::const_arg_iterator CallerArgIter = CallerFn->arg_begin(); 4613 4614 for (; CalleeArgIter != CalleeArgEnd; ++CalleeArgIter, ++CallerArgIter) { 4615 const Value* CalleeArg = *CalleeArgIter; 4616 const Value* CallerArg = &(*CallerArgIter); 4617 if (CalleeArg == CallerArg) 4618 continue; 4619 4620 // e.g. @caller([4 x i64] %a, [4 x i64] %b) { 4621 // tail call @callee([4 x i64] undef, [4 x i64] %b) 4622 // } 4623 // 1st argument of callee is undef and has the same type as caller. 4624 if (CalleeArg->getType() == CallerArg->getType() && 4625 isa<UndefValue>(CalleeArg)) 4626 continue; 4627 4628 return false; 4629 } 4630 4631 return true; 4632 } 4633 4634 // Returns true if TCO is possible between the callers and callees 4635 // calling conventions. 4636 static bool 4637 areCallingConvEligibleForTCO_64SVR4(CallingConv::ID CallerCC, 4638 CallingConv::ID CalleeCC) { 4639 // Tail calls are possible with fastcc and ccc. 4640 auto isTailCallableCC = [] (CallingConv::ID CC){ 4641 return CC == CallingConv::C || CC == CallingConv::Fast; 4642 }; 4643 if (!isTailCallableCC(CallerCC) || !isTailCallableCC(CalleeCC)) 4644 return false; 4645 4646 // We can safely tail call both fastcc and ccc callees from a c calling 4647 // convention caller. If the caller is fastcc, we may have less stack space 4648 // than a non-fastcc caller with the same signature so disable tail-calls in 4649 // that case. 4650 return CallerCC == CallingConv::C || CallerCC == CalleeCC; 4651 } 4652 4653 bool 4654 PPCTargetLowering::IsEligibleForTailCallOptimization_64SVR4( 4655 SDValue Callee, 4656 CallingConv::ID CalleeCC, 4657 ImmutableCallSite CS, 4658 bool isVarArg, 4659 const SmallVectorImpl<ISD::OutputArg> &Outs, 4660 const SmallVectorImpl<ISD::InputArg> &Ins, 4661 SelectionDAG& DAG) const { 4662 bool TailCallOpt = getTargetMachine().Options.GuaranteedTailCallOpt; 4663 4664 if (DisableSCO && !TailCallOpt) return false; 4665 4666 // Variadic argument functions are not supported. 4667 if (isVarArg) return false; 4668 4669 auto &Caller = DAG.getMachineFunction().getFunction(); 4670 // Check that the calling conventions are compatible for tco. 4671 if (!areCallingConvEligibleForTCO_64SVR4(Caller.getCallingConv(), CalleeCC)) 4672 return false; 4673 4674 // Caller contains any byval parameter is not supported. 4675 if (any_of(Ins, [](const ISD::InputArg &IA) { return IA.Flags.isByVal(); })) 4676 return false; 4677 4678 // Callee contains any byval parameter is not supported, too. 4679 // Note: This is a quick work around, because in some cases, e.g. 4680 // caller's stack size > callee's stack size, we are still able to apply 4681 // sibling call optimization. For example, gcc is able to do SCO for caller1 4682 // in the following example, but not for caller2. 4683 // struct test { 4684 // long int a; 4685 // char ary[56]; 4686 // } gTest; 4687 // __attribute__((noinline)) int callee(struct test v, struct test *b) { 4688 // b->a = v.a; 4689 // return 0; 4690 // } 4691 // void caller1(struct test a, struct test c, struct test *b) { 4692 // callee(gTest, b); } 4693 // void caller2(struct test *b) { callee(gTest, b); } 4694 if (any_of(Outs, [](const ISD::OutputArg& OA) { return OA.Flags.isByVal(); })) 4695 return false; 4696 4697 // If callee and caller use different calling conventions, we cannot pass 4698 // parameters on stack since offsets for the parameter area may be different. 4699 if (Caller.getCallingConv() != CalleeCC && 4700 needStackSlotPassParameters(Subtarget, Outs)) 4701 return false; 4702 4703 // No TCO/SCO on indirect call because Caller have to restore its TOC 4704 if (!isFunctionGlobalAddress(Callee) && 4705 !isa<ExternalSymbolSDNode>(Callee)) 4706 return false; 4707 4708 // If the caller and callee potentially have different TOC bases then we 4709 // cannot tail call since we need to restore the TOC pointer after the call. 4710 // ref: https://bugzilla.mozilla.org/show_bug.cgi?id=973977 4711 if (!callsShareTOCBase(&Caller, Callee, getTargetMachine())) 4712 return false; 4713 4714 // TCO allows altering callee ABI, so we don't have to check further. 4715 if (CalleeCC == CallingConv::Fast && TailCallOpt) 4716 return true; 4717 4718 if (DisableSCO) return false; 4719 4720 // If callee use the same argument list that caller is using, then we can 4721 // apply SCO on this case. If it is not, then we need to check if callee needs 4722 // stack for passing arguments. 4723 if (!hasSameArgumentList(&Caller, CS) && 4724 needStackSlotPassParameters(Subtarget, Outs)) { 4725 return false; 4726 } 4727 4728 return true; 4729 } 4730 4731 /// IsEligibleForTailCallOptimization - Check whether the call is eligible 4732 /// for tail call optimization. Targets which want to do tail call 4733 /// optimization should implement this function. 4734 bool 4735 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee, 4736 CallingConv::ID CalleeCC, 4737 bool isVarArg, 4738 const SmallVectorImpl<ISD::InputArg> &Ins, 4739 SelectionDAG& DAG) const { 4740 if (!getTargetMachine().Options.GuaranteedTailCallOpt) 4741 return false; 4742 4743 // Variable argument functions are not supported. 4744 if (isVarArg) 4745 return false; 4746 4747 MachineFunction &MF = DAG.getMachineFunction(); 4748 CallingConv::ID CallerCC = MF.getFunction().getCallingConv(); 4749 if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) { 4750 // Functions containing by val parameters are not supported. 4751 for (unsigned i = 0; i != Ins.size(); i++) { 4752 ISD::ArgFlagsTy Flags = Ins[i].Flags; 4753 if (Flags.isByVal()) return false; 4754 } 4755 4756 // Non-PIC/GOT tail calls are supported. 4757 if (getTargetMachine().getRelocationModel() != Reloc::PIC_) 4758 return true; 4759 4760 // At the moment we can only do local tail calls (in same module, hidden 4761 // or protected) if we are generating PIC. 4762 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) 4763 return G->getGlobal()->hasHiddenVisibility() 4764 || G->getGlobal()->hasProtectedVisibility(); 4765 } 4766 4767 return false; 4768 } 4769 4770 /// isCallCompatibleAddress - Return the immediate to use if the specified 4771 /// 32-bit value is representable in the immediate field of a BxA instruction. 4772 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) { 4773 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op); 4774 if (!C) return nullptr; 4775 4776 int Addr = C->getZExtValue(); 4777 if ((Addr & 3) != 0 || // Low 2 bits are implicitly zero. 4778 SignExtend32<26>(Addr) != Addr) 4779 return nullptr; // Top 6 bits have to be sext of immediate. 4780 4781 return DAG 4782 .getConstant( 4783 (int)C->getZExtValue() >> 2, SDLoc(Op), 4784 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout())) 4785 .getNode(); 4786 } 4787 4788 namespace { 4789 4790 struct TailCallArgumentInfo { 4791 SDValue Arg; 4792 SDValue FrameIdxOp; 4793 int FrameIdx = 0; 4794 4795 TailCallArgumentInfo() = default; 4796 }; 4797 4798 } // end anonymous namespace 4799 4800 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot. 4801 static void StoreTailCallArgumentsToStackSlot( 4802 SelectionDAG &DAG, SDValue Chain, 4803 const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs, 4804 SmallVectorImpl<SDValue> &MemOpChains, const SDLoc &dl) { 4805 for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) { 4806 SDValue Arg = TailCallArgs[i].Arg; 4807 SDValue FIN = TailCallArgs[i].FrameIdxOp; 4808 int FI = TailCallArgs[i].FrameIdx; 4809 // Store relative to framepointer. 4810 MemOpChains.push_back(DAG.getStore( 4811 Chain, dl, Arg, FIN, 4812 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI))); 4813 } 4814 } 4815 4816 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to 4817 /// the appropriate stack slot for the tail call optimized function call. 4818 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG, SDValue Chain, 4819 SDValue OldRetAddr, SDValue OldFP, 4820 int SPDiff, const SDLoc &dl) { 4821 if (SPDiff) { 4822 // Calculate the new stack slot for the return address. 4823 MachineFunction &MF = DAG.getMachineFunction(); 4824 const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>(); 4825 const PPCFrameLowering *FL = Subtarget.getFrameLowering(); 4826 bool isPPC64 = Subtarget.isPPC64(); 4827 int SlotSize = isPPC64 ? 8 : 4; 4828 int NewRetAddrLoc = SPDiff + FL->getReturnSaveOffset(); 4829 int NewRetAddr = MF.getFrameInfo().CreateFixedObject(SlotSize, 4830 NewRetAddrLoc, true); 4831 EVT VT = isPPC64 ? MVT::i64 : MVT::i32; 4832 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT); 4833 Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx, 4834 MachinePointerInfo::getFixedStack(MF, NewRetAddr)); 4835 } 4836 return Chain; 4837 } 4838 4839 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate 4840 /// the position of the argument. 4841 static void 4842 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64, 4843 SDValue Arg, int SPDiff, unsigned ArgOffset, 4844 SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) { 4845 int Offset = ArgOffset + SPDiff; 4846 uint32_t OpSize = (Arg.getValueSizeInBits() + 7) / 8; 4847 int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true); 4848 EVT VT = isPPC64 ? MVT::i64 : MVT::i32; 4849 SDValue FIN = DAG.getFrameIndex(FI, VT); 4850 TailCallArgumentInfo Info; 4851 Info.Arg = Arg; 4852 Info.FrameIdxOp = FIN; 4853 Info.FrameIdx = FI; 4854 TailCallArguments.push_back(Info); 4855 } 4856 4857 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address 4858 /// stack slot. Returns the chain as result and the loaded frame pointers in 4859 /// LROpOut/FPOpout. Used when tail calling. 4860 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr( 4861 SelectionDAG &DAG, int SPDiff, SDValue Chain, SDValue &LROpOut, 4862 SDValue &FPOpOut, const SDLoc &dl) const { 4863 if (SPDiff) { 4864 // Load the LR and FP stack slot for later adjusting. 4865 EVT VT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32; 4866 LROpOut = getReturnAddrFrameIndex(DAG); 4867 LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo()); 4868 Chain = SDValue(LROpOut.getNode(), 1); 4869 } 4870 return Chain; 4871 } 4872 4873 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified 4874 /// by "Src" to address "Dst" of size "Size". Alignment information is 4875 /// specified by the specific parameter attribute. The copy will be passed as 4876 /// a byval function parameter. 4877 /// Sometimes what we are copying is the end of a larger object, the part that 4878 /// does not fit in registers. 4879 static SDValue CreateCopyOfByValArgument(SDValue Src, SDValue Dst, 4880 SDValue Chain, ISD::ArgFlagsTy Flags, 4881 SelectionDAG &DAG, const SDLoc &dl) { 4882 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32); 4883 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, 4884 Flags.getNonZeroByValAlign(), false, false, false, 4885 MachinePointerInfo(), MachinePointerInfo()); 4886 } 4887 4888 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of 4889 /// tail calls. 4890 static void LowerMemOpCallTo( 4891 SelectionDAG &DAG, MachineFunction &MF, SDValue Chain, SDValue Arg, 4892 SDValue PtrOff, int SPDiff, unsigned ArgOffset, bool isPPC64, 4893 bool isTailCall, bool isVector, SmallVectorImpl<SDValue> &MemOpChains, 4894 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments, const SDLoc &dl) { 4895 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 4896 if (!isTailCall) { 4897 if (isVector) { 4898 SDValue StackPtr; 4899 if (isPPC64) 4900 StackPtr = DAG.getRegister(PPC::X1, MVT::i64); 4901 else 4902 StackPtr = DAG.getRegister(PPC::R1, MVT::i32); 4903 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, 4904 DAG.getConstant(ArgOffset, dl, PtrVT)); 4905 } 4906 MemOpChains.push_back( 4907 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo())); 4908 // Calculate and remember argument location. 4909 } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset, 4910 TailCallArguments); 4911 } 4912 4913 static void 4914 PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain, 4915 const SDLoc &dl, int SPDiff, unsigned NumBytes, SDValue LROp, 4916 SDValue FPOp, 4917 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) { 4918 // Emit a sequence of copyto/copyfrom virtual registers for arguments that 4919 // might overwrite each other in case of tail call optimization. 4920 SmallVector<SDValue, 8> MemOpChains2; 4921 // Do not flag preceding copytoreg stuff together with the following stuff. 4922 InFlag = SDValue(); 4923 StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments, 4924 MemOpChains2, dl); 4925 if (!MemOpChains2.empty()) 4926 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2); 4927 4928 // Store the return address to the appropriate stack slot. 4929 Chain = EmitTailCallStoreFPAndRetAddr(DAG, Chain, LROp, FPOp, SPDiff, dl); 4930 4931 // Emit callseq_end just before tailcall node. 4932 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true), 4933 DAG.getIntPtrConstant(0, dl, true), InFlag, dl); 4934 InFlag = Chain.getValue(1); 4935 } 4936 4937 // Is this global address that of a function that can be called by name? (as 4938 // opposed to something that must hold a descriptor for an indirect call). 4939 static bool isFunctionGlobalAddress(SDValue Callee) { 4940 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 4941 if (Callee.getOpcode() == ISD::GlobalTLSAddress || 4942 Callee.getOpcode() == ISD::TargetGlobalTLSAddress) 4943 return false; 4944 4945 return G->getGlobal()->getValueType()->isFunctionTy(); 4946 } 4947 4948 return false; 4949 } 4950 4951 SDValue PPCTargetLowering::LowerCallResult( 4952 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg, 4953 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 4954 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 4955 SmallVector<CCValAssign, 16> RVLocs; 4956 CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 4957 *DAG.getContext()); 4958 4959 CCRetInfo.AnalyzeCallResult( 4960 Ins, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold) 4961 ? RetCC_PPC_Cold 4962 : RetCC_PPC); 4963 4964 // Copy all of the result registers out of their specified physreg. 4965 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) { 4966 CCValAssign &VA = RVLocs[i]; 4967 assert(VA.isRegLoc() && "Can only return in registers!"); 4968 4969 SDValue Val; 4970 4971 if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) { 4972 SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, 4973 InFlag); 4974 Chain = Lo.getValue(1); 4975 InFlag = Lo.getValue(2); 4976 VA = RVLocs[++i]; // skip ahead to next loc 4977 SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, 4978 InFlag); 4979 Chain = Hi.getValue(1); 4980 InFlag = Hi.getValue(2); 4981 if (!Subtarget.isLittleEndian()) 4982 std::swap (Lo, Hi); 4983 Val = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, Lo, Hi); 4984 } else { 4985 Val = DAG.getCopyFromReg(Chain, dl, 4986 VA.getLocReg(), VA.getLocVT(), InFlag); 4987 Chain = Val.getValue(1); 4988 InFlag = Val.getValue(2); 4989 } 4990 4991 switch (VA.getLocInfo()) { 4992 default: llvm_unreachable("Unknown loc info!"); 4993 case CCValAssign::Full: break; 4994 case CCValAssign::AExt: 4995 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val); 4996 break; 4997 case CCValAssign::ZExt: 4998 Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val, 4999 DAG.getValueType(VA.getValVT())); 5000 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val); 5001 break; 5002 case CCValAssign::SExt: 5003 Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val, 5004 DAG.getValueType(VA.getValVT())); 5005 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val); 5006 break; 5007 } 5008 5009 InVals.push_back(Val); 5010 } 5011 5012 return Chain; 5013 } 5014 5015 static bool isIndirectCall(const SDValue &Callee, SelectionDAG &DAG, 5016 const PPCSubtarget &Subtarget, bool isPatchPoint) { 5017 // PatchPoint calls are not indirect. 5018 if (isPatchPoint) 5019 return false; 5020 5021 if (isFunctionGlobalAddress(Callee) || dyn_cast<ExternalSymbolSDNode>(Callee)) 5022 return false; 5023 5024 // Darwin, and 32-bit ELF can use a BLA. The descriptor based ABIs can not 5025 // becuase the immediate function pointer points to a descriptor instead of 5026 // a function entry point. The ELFv2 ABI cannot use a BLA because the function 5027 // pointer immediate points to the global entry point, while the BLA would 5028 // need to jump to the local entry point (see rL211174). 5029 if (!Subtarget.usesFunctionDescriptors() && !Subtarget.isELFv2ABI() && 5030 isBLACompatibleAddress(Callee, DAG)) 5031 return false; 5032 5033 return true; 5034 } 5035 5036 static unsigned getCallOpcode(PPCTargetLowering::CallFlags CFlags, 5037 const Function &Caller, 5038 const SDValue &Callee, 5039 const PPCSubtarget &Subtarget, 5040 const TargetMachine &TM) { 5041 if (CFlags.IsTailCall) 5042 return PPCISD::TC_RETURN; 5043 5044 // This is a call through a function pointer. 5045 if (CFlags.IsIndirect) { 5046 // AIX and the 64-bit ELF ABIs need to maintain the TOC pointer accross 5047 // indirect calls. The save of the caller's TOC pointer to the stack will be 5048 // inserted into the DAG as part of call lowering. The restore of the TOC 5049 // pointer is modeled by using a pseudo instruction for the call opcode that 5050 // represents the 2 instruction sequence of an indirect branch and link, 5051 // immediately followed by a load of the TOC pointer from the the stack save 5052 // slot into gpr2. 5053 if (Subtarget.isAIXABI() || Subtarget.is64BitELFABI()) 5054 return PPCISD::BCTRL_LOAD_TOC; 5055 5056 // An indirect call that does not need a TOC restore. 5057 return PPCISD::BCTRL; 5058 } 5059 5060 // The ABIs that maintain a TOC pointer accross calls need to have a nop 5061 // immediately following the call instruction if the caller and callee may 5062 // have different TOC bases. At link time if the linker determines the calls 5063 // may not share a TOC base, the call is redirected to a trampoline inserted 5064 // by the linker. The trampoline will (among other things) save the callers 5065 // TOC pointer at an ABI designated offset in the linkage area and the linker 5066 // will rewrite the nop to be a load of the TOC pointer from the linkage area 5067 // into gpr2. 5068 if (Subtarget.isAIXABI() || Subtarget.is64BitELFABI()) 5069 return callsShareTOCBase(&Caller, Callee, TM) ? PPCISD::CALL 5070 : PPCISD::CALL_NOP; 5071 5072 return PPCISD::CALL; 5073 } 5074 5075 static SDValue transformCallee(const SDValue &Callee, SelectionDAG &DAG, 5076 const SDLoc &dl, const PPCSubtarget &Subtarget) { 5077 if (!Subtarget.usesFunctionDescriptors() && !Subtarget.isELFv2ABI()) 5078 if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG)) 5079 return SDValue(Dest, 0); 5080 5081 // Returns true if the callee is local, and false otherwise. 5082 auto isLocalCallee = [&]() { 5083 const GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee); 5084 const Module *Mod = DAG.getMachineFunction().getFunction().getParent(); 5085 const GlobalValue *GV = G ? G->getGlobal() : nullptr; 5086 5087 return DAG.getTarget().shouldAssumeDSOLocal(*Mod, GV) && 5088 !dyn_cast_or_null<GlobalIFunc>(GV); 5089 }; 5090 5091 // The PLT is only used in 32-bit ELF PIC mode. Attempting to use the PLT in 5092 // a static relocation model causes some versions of GNU LD (2.17.50, at 5093 // least) to force BSS-PLT, instead of secure-PLT, even if all objects are 5094 // built with secure-PLT. 5095 bool UsePlt = 5096 Subtarget.is32BitELFABI() && !isLocalCallee() && 5097 Subtarget.getTargetMachine().getRelocationModel() == Reloc::PIC_; 5098 5099 // On AIX, direct function calls reference the symbol for the function's 5100 // entry point, which is named by prepending a "." before the function's 5101 // C-linkage name. 5102 const auto getAIXFuncEntryPointSymbolSDNode = 5103 [&](StringRef FuncName, bool IsDeclaration, 5104 const XCOFF::StorageClass &SC) { 5105 auto &Context = DAG.getMachineFunction().getMMI().getContext(); 5106 5107 MCSymbolXCOFF *S = cast<MCSymbolXCOFF>( 5108 Context.getOrCreateSymbol(Twine(".") + Twine(FuncName))); 5109 5110 if (IsDeclaration && !S->hasContainingCsect()) { 5111 // On AIX, an undefined symbol needs to be associated with a 5112 // MCSectionXCOFF to get the correct storage mapping class. 5113 // In this case, XCOFF::XMC_PR. 5114 MCSectionXCOFF *Sec = Context.getXCOFFSection( 5115 S->getName(), XCOFF::XMC_PR, XCOFF::XTY_ER, SC, 5116 SectionKind::getMetadata()); 5117 S->setContainingCsect(Sec); 5118 } 5119 5120 MVT PtrVT = 5121 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 5122 return DAG.getMCSymbol(S, PtrVT); 5123 }; 5124 5125 if (isFunctionGlobalAddress(Callee)) { 5126 const GlobalAddressSDNode *G = cast<GlobalAddressSDNode>(Callee); 5127 const GlobalValue *GV = G->getGlobal(); 5128 5129 if (!Subtarget.isAIXABI()) 5130 return DAG.getTargetGlobalAddress(GV, dl, Callee.getValueType(), 0, 5131 UsePlt ? PPCII::MO_PLT : 0); 5132 5133 assert(!isa<GlobalIFunc>(GV) && "IFunc is not supported on AIX."); 5134 const GlobalObject *GO = cast<GlobalObject>(GV); 5135 const XCOFF::StorageClass SC = 5136 TargetLoweringObjectFileXCOFF::getStorageClassForGlobal(GO); 5137 return getAIXFuncEntryPointSymbolSDNode(GO->getName(), GO->isDeclaration(), 5138 SC); 5139 } 5140 5141 if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) { 5142 const char *SymName = S->getSymbol(); 5143 if (!Subtarget.isAIXABI()) 5144 return DAG.getTargetExternalSymbol(SymName, Callee.getValueType(), 5145 UsePlt ? PPCII::MO_PLT : 0); 5146 5147 // If there exists a user-declared function whose name is the same as the 5148 // ExternalSymbol's, then we pick up the user-declared version. 5149 const Module *Mod = DAG.getMachineFunction().getFunction().getParent(); 5150 if (const Function *F = 5151 dyn_cast_or_null<Function>(Mod->getNamedValue(SymName))) { 5152 const XCOFF::StorageClass SC = 5153 TargetLoweringObjectFileXCOFF::getStorageClassForGlobal(F); 5154 return getAIXFuncEntryPointSymbolSDNode(F->getName(), F->isDeclaration(), 5155 SC); 5156 } 5157 5158 return getAIXFuncEntryPointSymbolSDNode(SymName, true, XCOFF::C_EXT); 5159 } 5160 5161 // No transformation needed. 5162 assert(Callee.getNode() && "What no callee?"); 5163 return Callee; 5164 } 5165 5166 static SDValue getOutputChainFromCallSeq(SDValue CallSeqStart) { 5167 assert(CallSeqStart.getOpcode() == ISD::CALLSEQ_START && 5168 "Expected a CALLSEQ_STARTSDNode."); 5169 5170 // The last operand is the chain, except when the node has glue. If the node 5171 // has glue, then the last operand is the glue, and the chain is the second 5172 // last operand. 5173 SDValue LastValue = CallSeqStart.getValue(CallSeqStart->getNumValues() - 1); 5174 if (LastValue.getValueType() != MVT::Glue) 5175 return LastValue; 5176 5177 return CallSeqStart.getValue(CallSeqStart->getNumValues() - 2); 5178 } 5179 5180 // Creates the node that moves a functions address into the count register 5181 // to prepare for an indirect call instruction. 5182 static void prepareIndirectCall(SelectionDAG &DAG, SDValue &Callee, 5183 SDValue &Glue, SDValue &Chain, 5184 const SDLoc &dl) { 5185 SDValue MTCTROps[] = {Chain, Callee, Glue}; 5186 EVT ReturnTypes[] = {MVT::Other, MVT::Glue}; 5187 Chain = DAG.getNode(PPCISD::MTCTR, dl, makeArrayRef(ReturnTypes, 2), 5188 makeArrayRef(MTCTROps, Glue.getNode() ? 3 : 2)); 5189 // The glue is the second value produced. 5190 Glue = Chain.getValue(1); 5191 } 5192 5193 static void prepareDescriptorIndirectCall(SelectionDAG &DAG, SDValue &Callee, 5194 SDValue &Glue, SDValue &Chain, 5195 SDValue CallSeqStart, 5196 ImmutableCallSite CS, const SDLoc &dl, 5197 bool hasNest, 5198 const PPCSubtarget &Subtarget) { 5199 // Function pointers in the 64-bit SVR4 ABI do not point to the function 5200 // entry point, but to the function descriptor (the function entry point 5201 // address is part of the function descriptor though). 5202 // The function descriptor is a three doubleword structure with the 5203 // following fields: function entry point, TOC base address and 5204 // environment pointer. 5205 // Thus for a call through a function pointer, the following actions need 5206 // to be performed: 5207 // 1. Save the TOC of the caller in the TOC save area of its stack 5208 // frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()). 5209 // 2. Load the address of the function entry point from the function 5210 // descriptor. 5211 // 3. Load the TOC of the callee from the function descriptor into r2. 5212 // 4. Load the environment pointer from the function descriptor into 5213 // r11. 5214 // 5. Branch to the function entry point address. 5215 // 6. On return of the callee, the TOC of the caller needs to be 5216 // restored (this is done in FinishCall()). 5217 // 5218 // The loads are scheduled at the beginning of the call sequence, and the 5219 // register copies are flagged together to ensure that no other 5220 // operations can be scheduled in between. E.g. without flagging the 5221 // copies together, a TOC access in the caller could be scheduled between 5222 // the assignment of the callee TOC and the branch to the callee, which leads 5223 // to incorrect code. 5224 5225 // Start by loading the function address from the descriptor. 5226 SDValue LDChain = getOutputChainFromCallSeq(CallSeqStart); 5227 auto MMOFlags = Subtarget.hasInvariantFunctionDescriptors() 5228 ? (MachineMemOperand::MODereferenceable | 5229 MachineMemOperand::MOInvariant) 5230 : MachineMemOperand::MONone; 5231 5232 MachinePointerInfo MPI(CS ? CS.getCalledValue() : nullptr); 5233 5234 // Registers used in building the DAG. 5235 const MCRegister EnvPtrReg = Subtarget.getEnvironmentPointerRegister(); 5236 const MCRegister TOCReg = Subtarget.getTOCPointerRegister(); 5237 5238 // Offsets of descriptor members. 5239 const unsigned TOCAnchorOffset = Subtarget.descriptorTOCAnchorOffset(); 5240 const unsigned EnvPtrOffset = Subtarget.descriptorEnvironmentPointerOffset(); 5241 5242 const MVT RegVT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32; 5243 const unsigned Alignment = Subtarget.isPPC64() ? 8 : 4; 5244 5245 // One load for the functions entry point address. 5246 SDValue LoadFuncPtr = DAG.getLoad(RegVT, dl, LDChain, Callee, MPI, 5247 Alignment, MMOFlags); 5248 5249 // One for loading the TOC anchor for the module that contains the called 5250 // function. 5251 SDValue TOCOff = DAG.getIntPtrConstant(TOCAnchorOffset, dl); 5252 SDValue AddTOC = DAG.getNode(ISD::ADD, dl, RegVT, Callee, TOCOff); 5253 SDValue TOCPtr = 5254 DAG.getLoad(RegVT, dl, LDChain, AddTOC, 5255 MPI.getWithOffset(TOCAnchorOffset), Alignment, MMOFlags); 5256 5257 // One for loading the environment pointer. 5258 SDValue PtrOff = DAG.getIntPtrConstant(EnvPtrOffset, dl); 5259 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, RegVT, Callee, PtrOff); 5260 SDValue LoadEnvPtr = 5261 DAG.getLoad(RegVT, dl, LDChain, AddPtr, 5262 MPI.getWithOffset(EnvPtrOffset), Alignment, MMOFlags); 5263 5264 5265 // Then copy the newly loaded TOC anchor to the TOC pointer. 5266 SDValue TOCVal = DAG.getCopyToReg(Chain, dl, TOCReg, TOCPtr, Glue); 5267 Chain = TOCVal.getValue(0); 5268 Glue = TOCVal.getValue(1); 5269 5270 // If the function call has an explicit 'nest' parameter, it takes the 5271 // place of the environment pointer. 5272 assert((!hasNest || !Subtarget.isAIXABI()) && 5273 "Nest parameter is not supported on AIX."); 5274 if (!hasNest) { 5275 SDValue EnvVal = DAG.getCopyToReg(Chain, dl, EnvPtrReg, LoadEnvPtr, Glue); 5276 Chain = EnvVal.getValue(0); 5277 Glue = EnvVal.getValue(1); 5278 } 5279 5280 // The rest of the indirect call sequence is the same as the non-descriptor 5281 // DAG. 5282 prepareIndirectCall(DAG, LoadFuncPtr, Glue, Chain, dl); 5283 } 5284 5285 static void 5286 buildCallOperands(SmallVectorImpl<SDValue> &Ops, 5287 PPCTargetLowering::CallFlags CFlags, const SDLoc &dl, 5288 SelectionDAG &DAG, 5289 SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, 5290 SDValue Glue, SDValue Chain, SDValue &Callee, int SPDiff, 5291 const PPCSubtarget &Subtarget) { 5292 const bool IsPPC64 = Subtarget.isPPC64(); 5293 // MVT for a general purpose register. 5294 const MVT RegVT = IsPPC64 ? MVT::i64 : MVT::i32; 5295 5296 // First operand is always the chain. 5297 Ops.push_back(Chain); 5298 5299 // If it's a direct call pass the callee as the second operand. 5300 if (!CFlags.IsIndirect) 5301 Ops.push_back(Callee); 5302 else { 5303 assert(!CFlags.IsPatchPoint && "Patch point calls are not indirect."); 5304 5305 // For the TOC based ABIs, we have saved the TOC pointer to the linkage area 5306 // on the stack (this would have been done in `LowerCall_64SVR4` or 5307 // `LowerCall_AIX`). The call instruction is a pseudo instruction that 5308 // represents both the indirect branch and a load that restores the TOC 5309 // pointer from the linkage area. The operand for the TOC restore is an add 5310 // of the TOC save offset to the stack pointer. This must be the second 5311 // operand: after the chain input but before any other variadic arguments. 5312 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) { 5313 const MCRegister StackPtrReg = Subtarget.getStackPointerRegister(); 5314 5315 SDValue StackPtr = DAG.getRegister(StackPtrReg, RegVT); 5316 unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset(); 5317 SDValue TOCOff = DAG.getIntPtrConstant(TOCSaveOffset, dl); 5318 SDValue AddTOC = DAG.getNode(ISD::ADD, dl, RegVT, StackPtr, TOCOff); 5319 Ops.push_back(AddTOC); 5320 } 5321 5322 // Add the register used for the environment pointer. 5323 if (Subtarget.usesFunctionDescriptors() && !CFlags.HasNest) 5324 Ops.push_back(DAG.getRegister(Subtarget.getEnvironmentPointerRegister(), 5325 RegVT)); 5326 5327 5328 // Add CTR register as callee so a bctr can be emitted later. 5329 if (CFlags.IsTailCall) 5330 Ops.push_back(DAG.getRegister(IsPPC64 ? PPC::CTR8 : PPC::CTR, RegVT)); 5331 } 5332 5333 // If this is a tail call add stack pointer delta. 5334 if (CFlags.IsTailCall) 5335 Ops.push_back(DAG.getConstant(SPDiff, dl, MVT::i32)); 5336 5337 // Add argument registers to the end of the list so that they are known live 5338 // into the call. 5339 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) 5340 Ops.push_back(DAG.getRegister(RegsToPass[i].first, 5341 RegsToPass[i].second.getValueType())); 5342 5343 // We cannot add R2/X2 as an operand here for PATCHPOINT, because there is 5344 // no way to mark dependencies as implicit here. 5345 // We will add the R2/X2 dependency in EmitInstrWithCustomInserter. 5346 if ((Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) && 5347 !CFlags.IsPatchPoint) 5348 Ops.push_back(DAG.getRegister(Subtarget.getTOCPointerRegister(), RegVT)); 5349 5350 // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls 5351 if (CFlags.IsVarArg && Subtarget.is32BitELFABI()) 5352 Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32)); 5353 5354 // Add a register mask operand representing the call-preserved registers. 5355 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo(); 5356 const uint32_t *Mask = 5357 TRI->getCallPreservedMask(DAG.getMachineFunction(), CFlags.CallConv); 5358 assert(Mask && "Missing call preserved mask for calling convention"); 5359 Ops.push_back(DAG.getRegisterMask(Mask)); 5360 5361 // If the glue is valid, it is the last operand. 5362 if (Glue.getNode()) 5363 Ops.push_back(Glue); 5364 } 5365 5366 SDValue PPCTargetLowering::FinishCall( 5367 CallFlags CFlags, const SDLoc &dl, SelectionDAG &DAG, 5368 SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, SDValue Glue, 5369 SDValue Chain, SDValue CallSeqStart, SDValue &Callee, int SPDiff, 5370 unsigned NumBytes, const SmallVectorImpl<ISD::InputArg> &Ins, 5371 SmallVectorImpl<SDValue> &InVals, ImmutableCallSite CS) const { 5372 5373 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) 5374 setUsesTOCBasePtr(DAG); 5375 5376 unsigned CallOpc = 5377 getCallOpcode(CFlags, DAG.getMachineFunction().getFunction(), Callee, 5378 Subtarget, DAG.getTarget()); 5379 5380 if (!CFlags.IsIndirect) 5381 Callee = transformCallee(Callee, DAG, dl, Subtarget); 5382 else if (Subtarget.usesFunctionDescriptors()) 5383 prepareDescriptorIndirectCall(DAG, Callee, Glue, Chain, CallSeqStart, CS, 5384 dl, CFlags.HasNest, Subtarget); 5385 else 5386 prepareIndirectCall(DAG, Callee, Glue, Chain, dl); 5387 5388 // Build the operand list for the call instruction. 5389 SmallVector<SDValue, 8> Ops; 5390 buildCallOperands(Ops, CFlags, dl, DAG, RegsToPass, Glue, Chain, Callee, 5391 SPDiff, Subtarget); 5392 5393 // Emit tail call. 5394 if (CFlags.IsTailCall) { 5395 assert(((Callee.getOpcode() == ISD::Register && 5396 cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) || 5397 Callee.getOpcode() == ISD::TargetExternalSymbol || 5398 Callee.getOpcode() == ISD::TargetGlobalAddress || 5399 isa<ConstantSDNode>(Callee)) && 5400 "Expecting a global address, external symbol, absolute value or " 5401 "register"); 5402 assert(CallOpc == PPCISD::TC_RETURN && 5403 "Unexpected call opcode for a tail call."); 5404 DAG.getMachineFunction().getFrameInfo().setHasTailCall(); 5405 return DAG.getNode(CallOpc, dl, MVT::Other, Ops); 5406 } 5407 5408 std::array<EVT, 2> ReturnTypes = {{MVT::Other, MVT::Glue}}; 5409 Chain = DAG.getNode(CallOpc, dl, ReturnTypes, Ops); 5410 Glue = Chain.getValue(1); 5411 5412 // When performing tail call optimization the callee pops its arguments off 5413 // the stack. Account for this here so these bytes can be pushed back on in 5414 // PPCFrameLowering::eliminateCallFramePseudoInstr. 5415 int BytesCalleePops = (CFlags.CallConv == CallingConv::Fast && 5416 getTargetMachine().Options.GuaranteedTailCallOpt) 5417 ? NumBytes 5418 : 0; 5419 5420 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true), 5421 DAG.getIntPtrConstant(BytesCalleePops, dl, true), 5422 Glue, dl); 5423 Glue = Chain.getValue(1); 5424 5425 return LowerCallResult(Chain, Glue, CFlags.CallConv, CFlags.IsVarArg, Ins, dl, 5426 DAG, InVals); 5427 } 5428 5429 SDValue 5430 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI, 5431 SmallVectorImpl<SDValue> &InVals) const { 5432 SelectionDAG &DAG = CLI.DAG; 5433 SDLoc &dl = CLI.DL; 5434 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs; 5435 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals; 5436 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins; 5437 SDValue Chain = CLI.Chain; 5438 SDValue Callee = CLI.Callee; 5439 bool &isTailCall = CLI.IsTailCall; 5440 CallingConv::ID CallConv = CLI.CallConv; 5441 bool isVarArg = CLI.IsVarArg; 5442 bool isPatchPoint = CLI.IsPatchPoint; 5443 ImmutableCallSite CS = CLI.CS; 5444 5445 if (isTailCall) { 5446 if (Subtarget.useLongCalls() && !(CS && CS.isMustTailCall())) 5447 isTailCall = false; 5448 else if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) 5449 isTailCall = 5450 IsEligibleForTailCallOptimization_64SVR4(Callee, CallConv, CS, 5451 isVarArg, Outs, Ins, DAG); 5452 else 5453 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg, 5454 Ins, DAG); 5455 if (isTailCall) { 5456 ++NumTailCalls; 5457 if (!getTargetMachine().Options.GuaranteedTailCallOpt) 5458 ++NumSiblingCalls; 5459 5460 assert(isa<GlobalAddressSDNode>(Callee) && 5461 "Callee should be an llvm::Function object."); 5462 LLVM_DEBUG( 5463 const GlobalValue *GV = 5464 cast<GlobalAddressSDNode>(Callee)->getGlobal(); 5465 const unsigned Width = 5466 80 - strlen("TCO caller: ") - strlen(", callee linkage: 0, 0"); 5467 dbgs() << "TCO caller: " 5468 << left_justify(DAG.getMachineFunction().getName(), Width) 5469 << ", callee linkage: " << GV->getVisibility() << ", " 5470 << GV->getLinkage() << "\n"); 5471 } 5472 } 5473 5474 if (!isTailCall && CS && CS.isMustTailCall()) 5475 report_fatal_error("failed to perform tail call elimination on a call " 5476 "site marked musttail"); 5477 5478 // When long calls (i.e. indirect calls) are always used, calls are always 5479 // made via function pointer. If we have a function name, first translate it 5480 // into a pointer. 5481 if (Subtarget.useLongCalls() && isa<GlobalAddressSDNode>(Callee) && 5482 !isTailCall) 5483 Callee = LowerGlobalAddress(Callee, DAG); 5484 5485 CallFlags CFlags( 5486 CallConv, isTailCall, isVarArg, isPatchPoint, 5487 isIndirectCall(Callee, DAG, Subtarget, isPatchPoint), 5488 // hasNest 5489 Subtarget.is64BitELFABI() && 5490 any_of(Outs, [](ISD::OutputArg Arg) { return Arg.Flags.isNest(); })); 5491 5492 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) 5493 return LowerCall_64SVR4(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG, 5494 InVals, CS); 5495 5496 if (Subtarget.isSVR4ABI()) 5497 return LowerCall_32SVR4(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG, 5498 InVals, CS); 5499 5500 if (Subtarget.isAIXABI()) 5501 return LowerCall_AIX(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG, 5502 InVals, CS); 5503 5504 return LowerCall_Darwin(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG, 5505 InVals, CS); 5506 } 5507 5508 SDValue PPCTargetLowering::LowerCall_32SVR4( 5509 SDValue Chain, SDValue Callee, CallFlags CFlags, 5510 const SmallVectorImpl<ISD::OutputArg> &Outs, 5511 const SmallVectorImpl<SDValue> &OutVals, 5512 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 5513 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 5514 ImmutableCallSite CS) const { 5515 // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description 5516 // of the 32-bit SVR4 ABI stack frame layout. 5517 5518 const CallingConv::ID CallConv = CFlags.CallConv; 5519 const bool IsVarArg = CFlags.IsVarArg; 5520 const bool IsTailCall = CFlags.IsTailCall; 5521 5522 assert((CallConv == CallingConv::C || 5523 CallConv == CallingConv::Cold || 5524 CallConv == CallingConv::Fast) && "Unknown calling convention!"); 5525 5526 unsigned PtrByteSize = 4; 5527 5528 MachineFunction &MF = DAG.getMachineFunction(); 5529 5530 // Mark this function as potentially containing a function that contains a 5531 // tail call. As a consequence the frame pointer will be used for dynamicalloc 5532 // and restoring the callers stack pointer in this functions epilog. This is 5533 // done because by tail calling the called function might overwrite the value 5534 // in this function's (MF) stack pointer stack slot 0(SP). 5535 if (getTargetMachine().Options.GuaranteedTailCallOpt && 5536 CallConv == CallingConv::Fast) 5537 MF.getInfo<PPCFunctionInfo>()->setHasFastCall(); 5538 5539 // Count how many bytes are to be pushed on the stack, including the linkage 5540 // area, parameter list area and the part of the local variable space which 5541 // contains copies of aggregates which are passed by value. 5542 5543 // Assign locations to all of the outgoing arguments. 5544 SmallVector<CCValAssign, 16> ArgLocs; 5545 PPCCCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 5546 5547 // Reserve space for the linkage area on the stack. 5548 CCInfo.AllocateStack(Subtarget.getFrameLowering()->getLinkageSize(), 5549 PtrByteSize); 5550 if (useSoftFloat()) 5551 CCInfo.PreAnalyzeCallOperands(Outs); 5552 5553 if (IsVarArg) { 5554 // Handle fixed and variable vector arguments differently. 5555 // Fixed vector arguments go into registers as long as registers are 5556 // available. Variable vector arguments always go into memory. 5557 unsigned NumArgs = Outs.size(); 5558 5559 for (unsigned i = 0; i != NumArgs; ++i) { 5560 MVT ArgVT = Outs[i].VT; 5561 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 5562 bool Result; 5563 5564 if (Outs[i].IsFixed) { 5565 Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, 5566 CCInfo); 5567 } else { 5568 Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full, 5569 ArgFlags, CCInfo); 5570 } 5571 5572 if (Result) { 5573 #ifndef NDEBUG 5574 errs() << "Call operand #" << i << " has unhandled type " 5575 << EVT(ArgVT).getEVTString() << "\n"; 5576 #endif 5577 llvm_unreachable(nullptr); 5578 } 5579 } 5580 } else { 5581 // All arguments are treated the same. 5582 CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4); 5583 } 5584 CCInfo.clearWasPPCF128(); 5585 5586 // Assign locations to all of the outgoing aggregate by value arguments. 5587 SmallVector<CCValAssign, 16> ByValArgLocs; 5588 CCState CCByValInfo(CallConv, IsVarArg, MF, ByValArgLocs, *DAG.getContext()); 5589 5590 // Reserve stack space for the allocations in CCInfo. 5591 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize); 5592 5593 CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal); 5594 5595 // Size of the linkage area, parameter list area and the part of the local 5596 // space variable where copies of aggregates which are passed by value are 5597 // stored. 5598 unsigned NumBytes = CCByValInfo.getNextStackOffset(); 5599 5600 // Calculate by how many bytes the stack has to be adjusted in case of tail 5601 // call optimization. 5602 int SPDiff = CalculateTailCallSPDiff(DAG, IsTailCall, NumBytes); 5603 5604 // Adjust the stack pointer for the new arguments... 5605 // These operations are automatically eliminated by the prolog/epilog pass 5606 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 5607 SDValue CallSeqStart = Chain; 5608 5609 // Load the return address and frame pointer so it can be moved somewhere else 5610 // later. 5611 SDValue LROp, FPOp; 5612 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl); 5613 5614 // Set up a copy of the stack pointer for use loading and storing any 5615 // arguments that may not fit in the registers available for argument 5616 // passing. 5617 SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32); 5618 5619 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 5620 SmallVector<TailCallArgumentInfo, 8> TailCallArguments; 5621 SmallVector<SDValue, 8> MemOpChains; 5622 5623 bool seenFloatArg = false; 5624 // Walk the register/memloc assignments, inserting copies/loads. 5625 // i - Tracks the index into the list of registers allocated for the call 5626 // RealArgIdx - Tracks the index into the list of actual function arguments 5627 // j - Tracks the index into the list of byval arguments 5628 for (unsigned i = 0, RealArgIdx = 0, j = 0, e = ArgLocs.size(); 5629 i != e; 5630 ++i, ++RealArgIdx) { 5631 CCValAssign &VA = ArgLocs[i]; 5632 SDValue Arg = OutVals[RealArgIdx]; 5633 ISD::ArgFlagsTy Flags = Outs[RealArgIdx].Flags; 5634 5635 if (Flags.isByVal()) { 5636 // Argument is an aggregate which is passed by value, thus we need to 5637 // create a copy of it in the local variable space of the current stack 5638 // frame (which is the stack frame of the caller) and pass the address of 5639 // this copy to the callee. 5640 assert((j < ByValArgLocs.size()) && "Index out of bounds!"); 5641 CCValAssign &ByValVA = ByValArgLocs[j++]; 5642 assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!"); 5643 5644 // Memory reserved in the local variable space of the callers stack frame. 5645 unsigned LocMemOffset = ByValVA.getLocMemOffset(); 5646 5647 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 5648 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()), 5649 StackPtr, PtrOff); 5650 5651 // Create a copy of the argument in the local area of the current 5652 // stack frame. 5653 SDValue MemcpyCall = 5654 CreateCopyOfByValArgument(Arg, PtrOff, 5655 CallSeqStart.getNode()->getOperand(0), 5656 Flags, DAG, dl); 5657 5658 // This must go outside the CALLSEQ_START..END. 5659 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, NumBytes, 0, 5660 SDLoc(MemcpyCall)); 5661 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(), 5662 NewCallSeqStart.getNode()); 5663 Chain = CallSeqStart = NewCallSeqStart; 5664 5665 // Pass the address of the aggregate copy on the stack either in a 5666 // physical register or in the parameter list area of the current stack 5667 // frame to the callee. 5668 Arg = PtrOff; 5669 } 5670 5671 // When useCRBits() is true, there can be i1 arguments. 5672 // It is because getRegisterType(MVT::i1) => MVT::i1, 5673 // and for other integer types getRegisterType() => MVT::i32. 5674 // Extend i1 and ensure callee will get i32. 5675 if (Arg.getValueType() == MVT::i1) 5676 Arg = DAG.getNode(Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, 5677 dl, MVT::i32, Arg); 5678 5679 if (VA.isRegLoc()) { 5680 seenFloatArg |= VA.getLocVT().isFloatingPoint(); 5681 // Put argument in a physical register. 5682 if (Subtarget.hasSPE() && Arg.getValueType() == MVT::f64) { 5683 bool IsLE = Subtarget.isLittleEndian(); 5684 SDValue SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg, 5685 DAG.getIntPtrConstant(IsLE ? 0 : 1, dl)); 5686 RegsToPass.push_back(std::make_pair(VA.getLocReg(), SVal.getValue(0))); 5687 SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg, 5688 DAG.getIntPtrConstant(IsLE ? 1 : 0, dl)); 5689 RegsToPass.push_back(std::make_pair(ArgLocs[++i].getLocReg(), 5690 SVal.getValue(0))); 5691 } else 5692 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 5693 } else { 5694 // Put argument in the parameter list area of the current stack frame. 5695 assert(VA.isMemLoc()); 5696 unsigned LocMemOffset = VA.getLocMemOffset(); 5697 5698 if (!IsTailCall) { 5699 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 5700 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()), 5701 StackPtr, PtrOff); 5702 5703 MemOpChains.push_back( 5704 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo())); 5705 } else { 5706 // Calculate and remember argument location. 5707 CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset, 5708 TailCallArguments); 5709 } 5710 } 5711 } 5712 5713 if (!MemOpChains.empty()) 5714 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 5715 5716 // Build a sequence of copy-to-reg nodes chained together with token chain 5717 // and flag operands which copy the outgoing args into the appropriate regs. 5718 SDValue InFlag; 5719 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 5720 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 5721 RegsToPass[i].second, InFlag); 5722 InFlag = Chain.getValue(1); 5723 } 5724 5725 // Set CR bit 6 to true if this is a vararg call with floating args passed in 5726 // registers. 5727 if (IsVarArg) { 5728 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue); 5729 SDValue Ops[] = { Chain, InFlag }; 5730 5731 Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET, 5732 dl, VTs, makeArrayRef(Ops, InFlag.getNode() ? 2 : 1)); 5733 5734 InFlag = Chain.getValue(1); 5735 } 5736 5737 if (IsTailCall) 5738 PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp, 5739 TailCallArguments); 5740 5741 return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart, 5742 Callee, SPDiff, NumBytes, Ins, InVals, CS); 5743 } 5744 5745 // Copy an argument into memory, being careful to do this outside the 5746 // call sequence for the call to which the argument belongs. 5747 SDValue PPCTargetLowering::createMemcpyOutsideCallSeq( 5748 SDValue Arg, SDValue PtrOff, SDValue CallSeqStart, ISD::ArgFlagsTy Flags, 5749 SelectionDAG &DAG, const SDLoc &dl) const { 5750 SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff, 5751 CallSeqStart.getNode()->getOperand(0), 5752 Flags, DAG, dl); 5753 // The MEMCPY must go outside the CALLSEQ_START..END. 5754 int64_t FrameSize = CallSeqStart.getConstantOperandVal(1); 5755 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, FrameSize, 0, 5756 SDLoc(MemcpyCall)); 5757 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(), 5758 NewCallSeqStart.getNode()); 5759 return NewCallSeqStart; 5760 } 5761 5762 SDValue PPCTargetLowering::LowerCall_64SVR4( 5763 SDValue Chain, SDValue Callee, CallFlags CFlags, 5764 const SmallVectorImpl<ISD::OutputArg> &Outs, 5765 const SmallVectorImpl<SDValue> &OutVals, 5766 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 5767 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 5768 ImmutableCallSite CS) const { 5769 bool isELFv2ABI = Subtarget.isELFv2ABI(); 5770 bool isLittleEndian = Subtarget.isLittleEndian(); 5771 unsigned NumOps = Outs.size(); 5772 bool IsSibCall = false; 5773 bool IsFastCall = CFlags.CallConv == CallingConv::Fast; 5774 5775 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 5776 unsigned PtrByteSize = 8; 5777 5778 MachineFunction &MF = DAG.getMachineFunction(); 5779 5780 if (CFlags.IsTailCall && !getTargetMachine().Options.GuaranteedTailCallOpt) 5781 IsSibCall = true; 5782 5783 // Mark this function as potentially containing a function that contains a 5784 // tail call. As a consequence the frame pointer will be used for dynamicalloc 5785 // and restoring the callers stack pointer in this functions epilog. This is 5786 // done because by tail calling the called function might overwrite the value 5787 // in this function's (MF) stack pointer stack slot 0(SP). 5788 if (getTargetMachine().Options.GuaranteedTailCallOpt && IsFastCall) 5789 MF.getInfo<PPCFunctionInfo>()->setHasFastCall(); 5790 5791 assert(!(IsFastCall && CFlags.IsVarArg) && 5792 "fastcc not supported on varargs functions"); 5793 5794 // Count how many bytes are to be pushed on the stack, including the linkage 5795 // area, and parameter passing area. On ELFv1, the linkage area is 48 bytes 5796 // reserved space for [SP][CR][LR][2 x unused][TOC]; on ELFv2, the linkage 5797 // area is 32 bytes reserved space for [SP][CR][LR][TOC]. 5798 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 5799 unsigned NumBytes = LinkageSize; 5800 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 5801 unsigned &QFPR_idx = FPR_idx; 5802 5803 static const MCPhysReg GPR[] = { 5804 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 5805 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 5806 }; 5807 static const MCPhysReg VR[] = { 5808 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 5809 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 5810 }; 5811 5812 const unsigned NumGPRs = array_lengthof(GPR); 5813 const unsigned NumFPRs = useSoftFloat() ? 0 : 13; 5814 const unsigned NumVRs = array_lengthof(VR); 5815 const unsigned NumQFPRs = NumFPRs; 5816 5817 // On ELFv2, we can avoid allocating the parameter area if all the arguments 5818 // can be passed to the callee in registers. 5819 // For the fast calling convention, there is another check below. 5820 // Note: We should keep consistent with LowerFormalArguments_64SVR4() 5821 bool HasParameterArea = !isELFv2ABI || CFlags.IsVarArg || IsFastCall; 5822 if (!HasParameterArea) { 5823 unsigned ParamAreaSize = NumGPRs * PtrByteSize; 5824 unsigned AvailableFPRs = NumFPRs; 5825 unsigned AvailableVRs = NumVRs; 5826 unsigned NumBytesTmp = NumBytes; 5827 for (unsigned i = 0; i != NumOps; ++i) { 5828 if (Outs[i].Flags.isNest()) continue; 5829 if (CalculateStackSlotUsed(Outs[i].VT, Outs[i].ArgVT, Outs[i].Flags, 5830 PtrByteSize, LinkageSize, ParamAreaSize, 5831 NumBytesTmp, AvailableFPRs, AvailableVRs, 5832 Subtarget.hasQPX())) 5833 HasParameterArea = true; 5834 } 5835 } 5836 5837 // When using the fast calling convention, we don't provide backing for 5838 // arguments that will be in registers. 5839 unsigned NumGPRsUsed = 0, NumFPRsUsed = 0, NumVRsUsed = 0; 5840 5841 // Avoid allocating parameter area for fastcc functions if all the arguments 5842 // can be passed in the registers. 5843 if (IsFastCall) 5844 HasParameterArea = false; 5845 5846 // Add up all the space actually used. 5847 for (unsigned i = 0; i != NumOps; ++i) { 5848 ISD::ArgFlagsTy Flags = Outs[i].Flags; 5849 EVT ArgVT = Outs[i].VT; 5850 EVT OrigVT = Outs[i].ArgVT; 5851 5852 if (Flags.isNest()) 5853 continue; 5854 5855 if (IsFastCall) { 5856 if (Flags.isByVal()) { 5857 NumGPRsUsed += (Flags.getByValSize()+7)/8; 5858 if (NumGPRsUsed > NumGPRs) 5859 HasParameterArea = true; 5860 } else { 5861 switch (ArgVT.getSimpleVT().SimpleTy) { 5862 default: llvm_unreachable("Unexpected ValueType for argument!"); 5863 case MVT::i1: 5864 case MVT::i32: 5865 case MVT::i64: 5866 if (++NumGPRsUsed <= NumGPRs) 5867 continue; 5868 break; 5869 case MVT::v4i32: 5870 case MVT::v8i16: 5871 case MVT::v16i8: 5872 case MVT::v2f64: 5873 case MVT::v2i64: 5874 case MVT::v1i128: 5875 case MVT::f128: 5876 if (++NumVRsUsed <= NumVRs) 5877 continue; 5878 break; 5879 case MVT::v4f32: 5880 // When using QPX, this is handled like a FP register, otherwise, it 5881 // is an Altivec register. 5882 if (Subtarget.hasQPX()) { 5883 if (++NumFPRsUsed <= NumFPRs) 5884 continue; 5885 } else { 5886 if (++NumVRsUsed <= NumVRs) 5887 continue; 5888 } 5889 break; 5890 case MVT::f32: 5891 case MVT::f64: 5892 case MVT::v4f64: // QPX 5893 case MVT::v4i1: // QPX 5894 if (++NumFPRsUsed <= NumFPRs) 5895 continue; 5896 break; 5897 } 5898 HasParameterArea = true; 5899 } 5900 } 5901 5902 /* Respect alignment of argument on the stack. */ 5903 auto Alignement = 5904 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize); 5905 NumBytes = alignTo(NumBytes, Alignement); 5906 5907 NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize); 5908 if (Flags.isInConsecutiveRegsLast()) 5909 NumBytes = ((NumBytes + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 5910 } 5911 5912 unsigned NumBytesActuallyUsed = NumBytes; 5913 5914 // In the old ELFv1 ABI, 5915 // the prolog code of the callee may store up to 8 GPR argument registers to 5916 // the stack, allowing va_start to index over them in memory if its varargs. 5917 // Because we cannot tell if this is needed on the caller side, we have to 5918 // conservatively assume that it is needed. As such, make sure we have at 5919 // least enough stack space for the caller to store the 8 GPRs. 5920 // In the ELFv2 ABI, we allocate the parameter area iff a callee 5921 // really requires memory operands, e.g. a vararg function. 5922 if (HasParameterArea) 5923 NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize); 5924 else 5925 NumBytes = LinkageSize; 5926 5927 // Tail call needs the stack to be aligned. 5928 if (getTargetMachine().Options.GuaranteedTailCallOpt && IsFastCall) 5929 NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes); 5930 5931 int SPDiff = 0; 5932 5933 // Calculate by how many bytes the stack has to be adjusted in case of tail 5934 // call optimization. 5935 if (!IsSibCall) 5936 SPDiff = CalculateTailCallSPDiff(DAG, CFlags.IsTailCall, NumBytes); 5937 5938 // To protect arguments on the stack from being clobbered in a tail call, 5939 // force all the loads to happen before doing any other lowering. 5940 if (CFlags.IsTailCall) 5941 Chain = DAG.getStackArgumentTokenFactor(Chain); 5942 5943 // Adjust the stack pointer for the new arguments... 5944 // These operations are automatically eliminated by the prolog/epilog pass 5945 if (!IsSibCall) 5946 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 5947 SDValue CallSeqStart = Chain; 5948 5949 // Load the return address and frame pointer so it can be move somewhere else 5950 // later. 5951 SDValue LROp, FPOp; 5952 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl); 5953 5954 // Set up a copy of the stack pointer for use loading and storing any 5955 // arguments that may not fit in the registers available for argument 5956 // passing. 5957 SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64); 5958 5959 // Figure out which arguments are going to go in registers, and which in 5960 // memory. Also, if this is a vararg function, floating point operations 5961 // must be stored to our stack, and loaded into integer regs as well, if 5962 // any integer regs are available for argument passing. 5963 unsigned ArgOffset = LinkageSize; 5964 5965 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 5966 SmallVector<TailCallArgumentInfo, 8> TailCallArguments; 5967 5968 SmallVector<SDValue, 8> MemOpChains; 5969 for (unsigned i = 0; i != NumOps; ++i) { 5970 SDValue Arg = OutVals[i]; 5971 ISD::ArgFlagsTy Flags = Outs[i].Flags; 5972 EVT ArgVT = Outs[i].VT; 5973 EVT OrigVT = Outs[i].ArgVT; 5974 5975 // PtrOff will be used to store the current argument to the stack if a 5976 // register cannot be found for it. 5977 SDValue PtrOff; 5978 5979 // We re-align the argument offset for each argument, except when using the 5980 // fast calling convention, when we need to make sure we do that only when 5981 // we'll actually use a stack slot. 5982 auto ComputePtrOff = [&]() { 5983 /* Respect alignment of argument on the stack. */ 5984 auto Alignment = 5985 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize); 5986 ArgOffset = alignTo(ArgOffset, Alignment); 5987 5988 PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType()); 5989 5990 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 5991 }; 5992 5993 if (!IsFastCall) { 5994 ComputePtrOff(); 5995 5996 /* Compute GPR index associated with argument offset. */ 5997 GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize; 5998 GPR_idx = std::min(GPR_idx, NumGPRs); 5999 } 6000 6001 // Promote integers to 64-bit values. 6002 if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) { 6003 // FIXME: Should this use ANY_EXTEND if neither sext nor zext? 6004 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 6005 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg); 6006 } 6007 6008 // FIXME memcpy is used way more than necessary. Correctness first. 6009 // Note: "by value" is code for passing a structure by value, not 6010 // basic types. 6011 if (Flags.isByVal()) { 6012 // Note: Size includes alignment padding, so 6013 // struct x { short a; char b; } 6014 // will have Size = 4. With #pragma pack(1), it will have Size = 3. 6015 // These are the proper values we need for right-justifying the 6016 // aggregate in a parameter register. 6017 unsigned Size = Flags.getByValSize(); 6018 6019 // An empty aggregate parameter takes up no storage and no 6020 // registers. 6021 if (Size == 0) 6022 continue; 6023 6024 if (IsFastCall) 6025 ComputePtrOff(); 6026 6027 // All aggregates smaller than 8 bytes must be passed right-justified. 6028 if (Size==1 || Size==2 || Size==4) { 6029 EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32); 6030 if (GPR_idx != NumGPRs) { 6031 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg, 6032 MachinePointerInfo(), VT); 6033 MemOpChains.push_back(Load.getValue(1)); 6034 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6035 6036 ArgOffset += PtrByteSize; 6037 continue; 6038 } 6039 } 6040 6041 if (GPR_idx == NumGPRs && Size < 8) { 6042 SDValue AddPtr = PtrOff; 6043 if (!isLittleEndian) { 6044 SDValue Const = DAG.getConstant(PtrByteSize - Size, dl, 6045 PtrOff.getValueType()); 6046 AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const); 6047 } 6048 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr, 6049 CallSeqStart, 6050 Flags, DAG, dl); 6051 ArgOffset += PtrByteSize; 6052 continue; 6053 } 6054 // Copy entire object into memory. There are cases where gcc-generated 6055 // code assumes it is there, even if it could be put entirely into 6056 // registers. (This is not what the doc says.) 6057 6058 // FIXME: The above statement is likely due to a misunderstanding of the 6059 // documents. All arguments must be copied into the parameter area BY 6060 // THE CALLEE in the event that the callee takes the address of any 6061 // formal argument. That has not yet been implemented. However, it is 6062 // reasonable to use the stack area as a staging area for the register 6063 // load. 6064 6065 // Skip this for small aggregates, as we will use the same slot for a 6066 // right-justified copy, below. 6067 if (Size >= 8) 6068 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff, 6069 CallSeqStart, 6070 Flags, DAG, dl); 6071 6072 // When a register is available, pass a small aggregate right-justified. 6073 if (Size < 8 && GPR_idx != NumGPRs) { 6074 // The easiest way to get this right-justified in a register 6075 // is to copy the structure into the rightmost portion of a 6076 // local variable slot, then load the whole slot into the 6077 // register. 6078 // FIXME: The memcpy seems to produce pretty awful code for 6079 // small aggregates, particularly for packed ones. 6080 // FIXME: It would be preferable to use the slot in the 6081 // parameter save area instead of a new local variable. 6082 SDValue AddPtr = PtrOff; 6083 if (!isLittleEndian) { 6084 SDValue Const = DAG.getConstant(8 - Size, dl, PtrOff.getValueType()); 6085 AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const); 6086 } 6087 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr, 6088 CallSeqStart, 6089 Flags, DAG, dl); 6090 6091 // Load the slot into the register. 6092 SDValue Load = 6093 DAG.getLoad(PtrVT, dl, Chain, PtrOff, MachinePointerInfo()); 6094 MemOpChains.push_back(Load.getValue(1)); 6095 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6096 6097 // Done with this argument. 6098 ArgOffset += PtrByteSize; 6099 continue; 6100 } 6101 6102 // For aggregates larger than PtrByteSize, copy the pieces of the 6103 // object that fit into registers from the parameter save area. 6104 for (unsigned j=0; j<Size; j+=PtrByteSize) { 6105 SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType()); 6106 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const); 6107 if (GPR_idx != NumGPRs) { 6108 SDValue Load = 6109 DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo()); 6110 MemOpChains.push_back(Load.getValue(1)); 6111 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6112 ArgOffset += PtrByteSize; 6113 } else { 6114 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize; 6115 break; 6116 } 6117 } 6118 continue; 6119 } 6120 6121 switch (Arg.getSimpleValueType().SimpleTy) { 6122 default: llvm_unreachable("Unexpected ValueType for argument!"); 6123 case MVT::i1: 6124 case MVT::i32: 6125 case MVT::i64: 6126 if (Flags.isNest()) { 6127 // The 'nest' parameter, if any, is passed in R11. 6128 RegsToPass.push_back(std::make_pair(PPC::X11, Arg)); 6129 break; 6130 } 6131 6132 // These can be scalar arguments or elements of an integer array type 6133 // passed directly. Clang may use those instead of "byval" aggregate 6134 // types to avoid forcing arguments to memory unnecessarily. 6135 if (GPR_idx != NumGPRs) { 6136 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg)); 6137 } else { 6138 if (IsFastCall) 6139 ComputePtrOff(); 6140 6141 assert(HasParameterArea && 6142 "Parameter area must exist to pass an argument in memory."); 6143 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6144 true, CFlags.IsTailCall, false, MemOpChains, 6145 TailCallArguments, dl); 6146 if (IsFastCall) 6147 ArgOffset += PtrByteSize; 6148 } 6149 if (!IsFastCall) 6150 ArgOffset += PtrByteSize; 6151 break; 6152 case MVT::f32: 6153 case MVT::f64: { 6154 // These can be scalar arguments or elements of a float array type 6155 // passed directly. The latter are used to implement ELFv2 homogenous 6156 // float aggregates. 6157 6158 // Named arguments go into FPRs first, and once they overflow, the 6159 // remaining arguments go into GPRs and then the parameter save area. 6160 // Unnamed arguments for vararg functions always go to GPRs and 6161 // then the parameter save area. For now, put all arguments to vararg 6162 // routines always in both locations (FPR *and* GPR or stack slot). 6163 bool NeedGPROrStack = CFlags.IsVarArg || FPR_idx == NumFPRs; 6164 bool NeededLoad = false; 6165 6166 // First load the argument into the next available FPR. 6167 if (FPR_idx != NumFPRs) 6168 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg)); 6169 6170 // Next, load the argument into GPR or stack slot if needed. 6171 if (!NeedGPROrStack) 6172 ; 6173 else if (GPR_idx != NumGPRs && !IsFastCall) { 6174 // FIXME: We may want to re-enable this for CallingConv::Fast on the P8 6175 // once we support fp <-> gpr moves. 6176 6177 // In the non-vararg case, this can only ever happen in the 6178 // presence of f32 array types, since otherwise we never run 6179 // out of FPRs before running out of GPRs. 6180 SDValue ArgVal; 6181 6182 // Double values are always passed in a single GPR. 6183 if (Arg.getValueType() != MVT::f32) { 6184 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg); 6185 6186 // Non-array float values are extended and passed in a GPR. 6187 } else if (!Flags.isInConsecutiveRegs()) { 6188 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg); 6189 ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal); 6190 6191 // If we have an array of floats, we collect every odd element 6192 // together with its predecessor into one GPR. 6193 } else if (ArgOffset % PtrByteSize != 0) { 6194 SDValue Lo, Hi; 6195 Lo = DAG.getNode(ISD::BITCAST, dl, MVT::i32, OutVals[i - 1]); 6196 Hi = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg); 6197 if (!isLittleEndian) 6198 std::swap(Lo, Hi); 6199 ArgVal = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi); 6200 6201 // The final element, if even, goes into the first half of a GPR. 6202 } else if (Flags.isInConsecutiveRegsLast()) { 6203 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg); 6204 ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal); 6205 if (!isLittleEndian) 6206 ArgVal = DAG.getNode(ISD::SHL, dl, MVT::i64, ArgVal, 6207 DAG.getConstant(32, dl, MVT::i32)); 6208 6209 // Non-final even elements are skipped; they will be handled 6210 // together the with subsequent argument on the next go-around. 6211 } else 6212 ArgVal = SDValue(); 6213 6214 if (ArgVal.getNode()) 6215 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], ArgVal)); 6216 } else { 6217 if (IsFastCall) 6218 ComputePtrOff(); 6219 6220 // Single-precision floating-point values are mapped to the 6221 // second (rightmost) word of the stack doubleword. 6222 if (Arg.getValueType() == MVT::f32 && 6223 !isLittleEndian && !Flags.isInConsecutiveRegs()) { 6224 SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType()); 6225 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour); 6226 } 6227 6228 assert(HasParameterArea && 6229 "Parameter area must exist to pass an argument in memory."); 6230 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6231 true, CFlags.IsTailCall, false, MemOpChains, 6232 TailCallArguments, dl); 6233 6234 NeededLoad = true; 6235 } 6236 // When passing an array of floats, the array occupies consecutive 6237 // space in the argument area; only round up to the next doubleword 6238 // at the end of the array. Otherwise, each float takes 8 bytes. 6239 if (!IsFastCall || NeededLoad) { 6240 ArgOffset += (Arg.getValueType() == MVT::f32 && 6241 Flags.isInConsecutiveRegs()) ? 4 : 8; 6242 if (Flags.isInConsecutiveRegsLast()) 6243 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 6244 } 6245 break; 6246 } 6247 case MVT::v4f32: 6248 case MVT::v4i32: 6249 case MVT::v8i16: 6250 case MVT::v16i8: 6251 case MVT::v2f64: 6252 case MVT::v2i64: 6253 case MVT::v1i128: 6254 case MVT::f128: 6255 if (!Subtarget.hasQPX()) { 6256 // These can be scalar arguments or elements of a vector array type 6257 // passed directly. The latter are used to implement ELFv2 homogenous 6258 // vector aggregates. 6259 6260 // For a varargs call, named arguments go into VRs or on the stack as 6261 // usual; unnamed arguments always go to the stack or the corresponding 6262 // GPRs when within range. For now, we always put the value in both 6263 // locations (or even all three). 6264 if (CFlags.IsVarArg) { 6265 assert(HasParameterArea && 6266 "Parameter area must exist if we have a varargs call."); 6267 // We could elide this store in the case where the object fits 6268 // entirely in R registers. Maybe later. 6269 SDValue Store = 6270 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 6271 MemOpChains.push_back(Store); 6272 if (VR_idx != NumVRs) { 6273 SDValue Load = 6274 DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo()); 6275 MemOpChains.push_back(Load.getValue(1)); 6276 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load)); 6277 } 6278 ArgOffset += 16; 6279 for (unsigned i=0; i<16; i+=PtrByteSize) { 6280 if (GPR_idx == NumGPRs) 6281 break; 6282 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, 6283 DAG.getConstant(i, dl, PtrVT)); 6284 SDValue Load = 6285 DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo()); 6286 MemOpChains.push_back(Load.getValue(1)); 6287 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6288 } 6289 break; 6290 } 6291 6292 // Non-varargs Altivec params go into VRs or on the stack. 6293 if (VR_idx != NumVRs) { 6294 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg)); 6295 } else { 6296 if (IsFastCall) 6297 ComputePtrOff(); 6298 6299 assert(HasParameterArea && 6300 "Parameter area must exist to pass an argument in memory."); 6301 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6302 true, CFlags.IsTailCall, true, MemOpChains, 6303 TailCallArguments, dl); 6304 if (IsFastCall) 6305 ArgOffset += 16; 6306 } 6307 6308 if (!IsFastCall) 6309 ArgOffset += 16; 6310 break; 6311 } // not QPX 6312 6313 assert(Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32 && 6314 "Invalid QPX parameter type"); 6315 6316 LLVM_FALLTHROUGH; 6317 case MVT::v4f64: 6318 case MVT::v4i1: { 6319 bool IsF32 = Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32; 6320 if (CFlags.IsVarArg) { 6321 assert(HasParameterArea && 6322 "Parameter area must exist if we have a varargs call."); 6323 // We could elide this store in the case where the object fits 6324 // entirely in R registers. Maybe later. 6325 SDValue Store = 6326 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 6327 MemOpChains.push_back(Store); 6328 if (QFPR_idx != NumQFPRs) { 6329 SDValue Load = DAG.getLoad(IsF32 ? MVT::v4f32 : MVT::v4f64, dl, Store, 6330 PtrOff, MachinePointerInfo()); 6331 MemOpChains.push_back(Load.getValue(1)); 6332 RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Load)); 6333 } 6334 ArgOffset += (IsF32 ? 16 : 32); 6335 for (unsigned i = 0; i < (IsF32 ? 16U : 32U); i += PtrByteSize) { 6336 if (GPR_idx == NumGPRs) 6337 break; 6338 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, 6339 DAG.getConstant(i, dl, PtrVT)); 6340 SDValue Load = 6341 DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo()); 6342 MemOpChains.push_back(Load.getValue(1)); 6343 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6344 } 6345 break; 6346 } 6347 6348 // Non-varargs QPX params go into registers or on the stack. 6349 if (QFPR_idx != NumQFPRs) { 6350 RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Arg)); 6351 } else { 6352 if (IsFastCall) 6353 ComputePtrOff(); 6354 6355 assert(HasParameterArea && 6356 "Parameter area must exist to pass an argument in memory."); 6357 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6358 true, CFlags.IsTailCall, true, MemOpChains, 6359 TailCallArguments, dl); 6360 if (IsFastCall) 6361 ArgOffset += (IsF32 ? 16 : 32); 6362 } 6363 6364 if (!IsFastCall) 6365 ArgOffset += (IsF32 ? 16 : 32); 6366 break; 6367 } 6368 } 6369 } 6370 6371 assert((!HasParameterArea || NumBytesActuallyUsed == ArgOffset) && 6372 "mismatch in size of parameter area"); 6373 (void)NumBytesActuallyUsed; 6374 6375 if (!MemOpChains.empty()) 6376 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 6377 6378 // Check if this is an indirect call (MTCTR/BCTRL). 6379 // See prepareDescriptorIndirectCall and buildCallOperands for more 6380 // information about calls through function pointers in the 64-bit SVR4 ABI. 6381 if (CFlags.IsIndirect) { 6382 assert(!CFlags.IsTailCall && "Indirect tails calls not supported"); 6383 // Load r2 into a virtual register and store it to the TOC save area. 6384 setUsesTOCBasePtr(DAG); 6385 SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64); 6386 // TOC save area offset. 6387 unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset(); 6388 SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl); 6389 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 6390 Chain = DAG.getStore( 6391 Val.getValue(1), dl, Val, AddPtr, 6392 MachinePointerInfo::getStack(DAG.getMachineFunction(), TOCSaveOffset)); 6393 // In the ELFv2 ABI, R12 must contain the address of an indirect callee. 6394 // This does not mean the MTCTR instruction must use R12; it's easier 6395 // to model this as an extra parameter, so do that. 6396 if (isELFv2ABI && !CFlags.IsPatchPoint) 6397 RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee)); 6398 } 6399 6400 // Build a sequence of copy-to-reg nodes chained together with token chain 6401 // and flag operands which copy the outgoing args into the appropriate regs. 6402 SDValue InFlag; 6403 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 6404 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 6405 RegsToPass[i].second, InFlag); 6406 InFlag = Chain.getValue(1); 6407 } 6408 6409 if (CFlags.IsTailCall && !IsSibCall) 6410 PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp, 6411 TailCallArguments); 6412 6413 return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart, 6414 Callee, SPDiff, NumBytes, Ins, InVals, CS); 6415 } 6416 6417 SDValue PPCTargetLowering::LowerCall_Darwin( 6418 SDValue Chain, SDValue Callee, CallFlags CFlags, 6419 const SmallVectorImpl<ISD::OutputArg> &Outs, 6420 const SmallVectorImpl<SDValue> &OutVals, 6421 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 6422 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 6423 ImmutableCallSite CS) const { 6424 unsigned NumOps = Outs.size(); 6425 6426 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 6427 bool isPPC64 = PtrVT == MVT::i64; 6428 unsigned PtrByteSize = isPPC64 ? 8 : 4; 6429 6430 MachineFunction &MF = DAG.getMachineFunction(); 6431 6432 // Mark this function as potentially containing a function that contains a 6433 // tail call. As a consequence the frame pointer will be used for dynamicalloc 6434 // and restoring the callers stack pointer in this functions epilog. This is 6435 // done because by tail calling the called function might overwrite the value 6436 // in this function's (MF) stack pointer stack slot 0(SP). 6437 if (getTargetMachine().Options.GuaranteedTailCallOpt && 6438 CFlags.CallConv == CallingConv::Fast) 6439 MF.getInfo<PPCFunctionInfo>()->setHasFastCall(); 6440 6441 // Count how many bytes are to be pushed on the stack, including the linkage 6442 // area, and parameter passing area. We start with 24/48 bytes, which is 6443 // prereserved space for [SP][CR][LR][3 x unused]. 6444 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 6445 unsigned NumBytes = LinkageSize; 6446 6447 // Add up all the space actually used. 6448 // In 32-bit non-varargs calls, Altivec parameters all go at the end; usually 6449 // they all go in registers, but we must reserve stack space for them for 6450 // possible use by the caller. In varargs or 64-bit calls, parameters are 6451 // assigned stack space in order, with padding so Altivec parameters are 6452 // 16-byte aligned. 6453 unsigned nAltivecParamsAtEnd = 0; 6454 for (unsigned i = 0; i != NumOps; ++i) { 6455 ISD::ArgFlagsTy Flags = Outs[i].Flags; 6456 EVT ArgVT = Outs[i].VT; 6457 // Varargs Altivec parameters are padded to a 16 byte boundary. 6458 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 || 6459 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 || 6460 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64) { 6461 if (!CFlags.IsVarArg && !isPPC64) { 6462 // Non-varargs Altivec parameters go after all the non-Altivec 6463 // parameters; handle those later so we know how much padding we need. 6464 nAltivecParamsAtEnd++; 6465 continue; 6466 } 6467 // Varargs and 64-bit Altivec parameters are padded to 16 byte boundary. 6468 NumBytes = ((NumBytes+15)/16)*16; 6469 } 6470 NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize); 6471 } 6472 6473 // Allow for Altivec parameters at the end, if needed. 6474 if (nAltivecParamsAtEnd) { 6475 NumBytes = ((NumBytes+15)/16)*16; 6476 NumBytes += 16*nAltivecParamsAtEnd; 6477 } 6478 6479 // The prolog code of the callee may store up to 8 GPR argument registers to 6480 // the stack, allowing va_start to index over them in memory if its varargs. 6481 // Because we cannot tell if this is needed on the caller side, we have to 6482 // conservatively assume that it is needed. As such, make sure we have at 6483 // least enough stack space for the caller to store the 8 GPRs. 6484 NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize); 6485 6486 // Tail call needs the stack to be aligned. 6487 if (getTargetMachine().Options.GuaranteedTailCallOpt && 6488 CFlags.CallConv == CallingConv::Fast) 6489 NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes); 6490 6491 // Calculate by how many bytes the stack has to be adjusted in case of tail 6492 // call optimization. 6493 int SPDiff = CalculateTailCallSPDiff(DAG, CFlags.IsTailCall, NumBytes); 6494 6495 // To protect arguments on the stack from being clobbered in a tail call, 6496 // force all the loads to happen before doing any other lowering. 6497 if (CFlags.IsTailCall) 6498 Chain = DAG.getStackArgumentTokenFactor(Chain); 6499 6500 // Adjust the stack pointer for the new arguments... 6501 // These operations are automatically eliminated by the prolog/epilog pass 6502 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 6503 SDValue CallSeqStart = Chain; 6504 6505 // Load the return address and frame pointer so it can be move somewhere else 6506 // later. 6507 SDValue LROp, FPOp; 6508 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl); 6509 6510 // Set up a copy of the stack pointer for use loading and storing any 6511 // arguments that may not fit in the registers available for argument 6512 // passing. 6513 SDValue StackPtr; 6514 if (isPPC64) 6515 StackPtr = DAG.getRegister(PPC::X1, MVT::i64); 6516 else 6517 StackPtr = DAG.getRegister(PPC::R1, MVT::i32); 6518 6519 // Figure out which arguments are going to go in registers, and which in 6520 // memory. Also, if this is a vararg function, floating point operations 6521 // must be stored to our stack, and loaded into integer regs as well, if 6522 // any integer regs are available for argument passing. 6523 unsigned ArgOffset = LinkageSize; 6524 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 6525 6526 static const MCPhysReg GPR_32[] = { // 32-bit registers. 6527 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 6528 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 6529 }; 6530 static const MCPhysReg GPR_64[] = { // 64-bit registers. 6531 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 6532 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 6533 }; 6534 static const MCPhysReg VR[] = { 6535 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 6536 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 6537 }; 6538 const unsigned NumGPRs = array_lengthof(GPR_32); 6539 const unsigned NumFPRs = 13; 6540 const unsigned NumVRs = array_lengthof(VR); 6541 6542 const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32; 6543 6544 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 6545 SmallVector<TailCallArgumentInfo, 8> TailCallArguments; 6546 6547 SmallVector<SDValue, 8> MemOpChains; 6548 for (unsigned i = 0; i != NumOps; ++i) { 6549 SDValue Arg = OutVals[i]; 6550 ISD::ArgFlagsTy Flags = Outs[i].Flags; 6551 6552 // PtrOff will be used to store the current argument to the stack if a 6553 // register cannot be found for it. 6554 SDValue PtrOff; 6555 6556 PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType()); 6557 6558 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 6559 6560 // On PPC64, promote integers to 64-bit values. 6561 if (isPPC64 && Arg.getValueType() == MVT::i32) { 6562 // FIXME: Should this use ANY_EXTEND if neither sext nor zext? 6563 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 6564 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg); 6565 } 6566 6567 // FIXME memcpy is used way more than necessary. Correctness first. 6568 // Note: "by value" is code for passing a structure by value, not 6569 // basic types. 6570 if (Flags.isByVal()) { 6571 unsigned Size = Flags.getByValSize(); 6572 // Very small objects are passed right-justified. Everything else is 6573 // passed left-justified. 6574 if (Size==1 || Size==2) { 6575 EVT VT = (Size==1) ? MVT::i8 : MVT::i16; 6576 if (GPR_idx != NumGPRs) { 6577 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg, 6578 MachinePointerInfo(), VT); 6579 MemOpChains.push_back(Load.getValue(1)); 6580 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6581 6582 ArgOffset += PtrByteSize; 6583 } else { 6584 SDValue Const = DAG.getConstant(PtrByteSize - Size, dl, 6585 PtrOff.getValueType()); 6586 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const); 6587 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr, 6588 CallSeqStart, 6589 Flags, DAG, dl); 6590 ArgOffset += PtrByteSize; 6591 } 6592 continue; 6593 } 6594 // Copy entire object into memory. There are cases where gcc-generated 6595 // code assumes it is there, even if it could be put entirely into 6596 // registers. (This is not what the doc says.) 6597 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff, 6598 CallSeqStart, 6599 Flags, DAG, dl); 6600 6601 // For small aggregates (Darwin only) and aggregates >= PtrByteSize, 6602 // copy the pieces of the object that fit into registers from the 6603 // parameter save area. 6604 for (unsigned j=0; j<Size; j+=PtrByteSize) { 6605 SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType()); 6606 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const); 6607 if (GPR_idx != NumGPRs) { 6608 SDValue Load = 6609 DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo()); 6610 MemOpChains.push_back(Load.getValue(1)); 6611 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6612 ArgOffset += PtrByteSize; 6613 } else { 6614 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize; 6615 break; 6616 } 6617 } 6618 continue; 6619 } 6620 6621 switch (Arg.getSimpleValueType().SimpleTy) { 6622 default: llvm_unreachable("Unexpected ValueType for argument!"); 6623 case MVT::i1: 6624 case MVT::i32: 6625 case MVT::i64: 6626 if (GPR_idx != NumGPRs) { 6627 if (Arg.getValueType() == MVT::i1) 6628 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, PtrVT, Arg); 6629 6630 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg)); 6631 } else { 6632 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6633 isPPC64, CFlags.IsTailCall, false, MemOpChains, 6634 TailCallArguments, dl); 6635 } 6636 ArgOffset += PtrByteSize; 6637 break; 6638 case MVT::f32: 6639 case MVT::f64: 6640 if (FPR_idx != NumFPRs) { 6641 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg)); 6642 6643 if (CFlags.IsVarArg) { 6644 SDValue Store = 6645 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 6646 MemOpChains.push_back(Store); 6647 6648 // Float varargs are always shadowed in available integer registers 6649 if (GPR_idx != NumGPRs) { 6650 SDValue Load = 6651 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo()); 6652 MemOpChains.push_back(Load.getValue(1)); 6653 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6654 } 6655 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && !isPPC64){ 6656 SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType()); 6657 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour); 6658 SDValue Load = 6659 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo()); 6660 MemOpChains.push_back(Load.getValue(1)); 6661 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6662 } 6663 } else { 6664 // If we have any FPRs remaining, we may also have GPRs remaining. 6665 // Args passed in FPRs consume either 1 (f32) or 2 (f64) available 6666 // GPRs. 6667 if (GPR_idx != NumGPRs) 6668 ++GPR_idx; 6669 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && 6670 !isPPC64) // PPC64 has 64-bit GPR's obviously :) 6671 ++GPR_idx; 6672 } 6673 } else 6674 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6675 isPPC64, CFlags.IsTailCall, false, MemOpChains, 6676 TailCallArguments, dl); 6677 if (isPPC64) 6678 ArgOffset += 8; 6679 else 6680 ArgOffset += Arg.getValueType() == MVT::f32 ? 4 : 8; 6681 break; 6682 case MVT::v4f32: 6683 case MVT::v4i32: 6684 case MVT::v8i16: 6685 case MVT::v16i8: 6686 if (CFlags.IsVarArg) { 6687 // These go aligned on the stack, or in the corresponding R registers 6688 // when within range. The Darwin PPC ABI doc claims they also go in 6689 // V registers; in fact gcc does this only for arguments that are 6690 // prototyped, not for those that match the ... We do it for all 6691 // arguments, seems to work. 6692 while (ArgOffset % 16 !=0) { 6693 ArgOffset += PtrByteSize; 6694 if (GPR_idx != NumGPRs) 6695 GPR_idx++; 6696 } 6697 // We could elide this store in the case where the object fits 6698 // entirely in R registers. Maybe later. 6699 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, 6700 DAG.getConstant(ArgOffset, dl, PtrVT)); 6701 SDValue Store = 6702 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 6703 MemOpChains.push_back(Store); 6704 if (VR_idx != NumVRs) { 6705 SDValue Load = 6706 DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo()); 6707 MemOpChains.push_back(Load.getValue(1)); 6708 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load)); 6709 } 6710 ArgOffset += 16; 6711 for (unsigned i=0; i<16; i+=PtrByteSize) { 6712 if (GPR_idx == NumGPRs) 6713 break; 6714 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, 6715 DAG.getConstant(i, dl, PtrVT)); 6716 SDValue Load = 6717 DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo()); 6718 MemOpChains.push_back(Load.getValue(1)); 6719 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6720 } 6721 break; 6722 } 6723 6724 // Non-varargs Altivec params generally go in registers, but have 6725 // stack space allocated at the end. 6726 if (VR_idx != NumVRs) { 6727 // Doesn't have GPR space allocated. 6728 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg)); 6729 } else if (nAltivecParamsAtEnd==0) { 6730 // We are emitting Altivec params in order. 6731 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6732 isPPC64, CFlags.IsTailCall, true, MemOpChains, 6733 TailCallArguments, dl); 6734 ArgOffset += 16; 6735 } 6736 break; 6737 } 6738 } 6739 // If all Altivec parameters fit in registers, as they usually do, 6740 // they get stack space following the non-Altivec parameters. We 6741 // don't track this here because nobody below needs it. 6742 // If there are more Altivec parameters than fit in registers emit 6743 // the stores here. 6744 if (!CFlags.IsVarArg && nAltivecParamsAtEnd > NumVRs) { 6745 unsigned j = 0; 6746 // Offset is aligned; skip 1st 12 params which go in V registers. 6747 ArgOffset = ((ArgOffset+15)/16)*16; 6748 ArgOffset += 12*16; 6749 for (unsigned i = 0; i != NumOps; ++i) { 6750 SDValue Arg = OutVals[i]; 6751 EVT ArgType = Outs[i].VT; 6752 if (ArgType==MVT::v4f32 || ArgType==MVT::v4i32 || 6753 ArgType==MVT::v8i16 || ArgType==MVT::v16i8) { 6754 if (++j > NumVRs) { 6755 SDValue PtrOff; 6756 // We are emitting Altivec params in order. 6757 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6758 isPPC64, CFlags.IsTailCall, true, MemOpChains, 6759 TailCallArguments, dl); 6760 ArgOffset += 16; 6761 } 6762 } 6763 } 6764 } 6765 6766 if (!MemOpChains.empty()) 6767 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 6768 6769 // On Darwin, R12 must contain the address of an indirect callee. This does 6770 // not mean the MTCTR instruction must use R12; it's easier to model this as 6771 // an extra parameter, so do that. 6772 if (CFlags.IsIndirect) { 6773 assert(!CFlags.IsTailCall && "Indirect tail-calls not supported."); 6774 RegsToPass.push_back(std::make_pair((unsigned)(isPPC64 ? PPC::X12 : 6775 PPC::R12), Callee)); 6776 } 6777 6778 // Build a sequence of copy-to-reg nodes chained together with token chain 6779 // and flag operands which copy the outgoing args into the appropriate regs. 6780 SDValue InFlag; 6781 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 6782 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 6783 RegsToPass[i].second, InFlag); 6784 InFlag = Chain.getValue(1); 6785 } 6786 6787 if (CFlags.IsTailCall) 6788 PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp, 6789 TailCallArguments); 6790 6791 return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart, 6792 Callee, SPDiff, NumBytes, Ins, InVals, CS); 6793 } 6794 6795 static bool CC_AIX(unsigned ValNo, MVT ValVT, MVT LocVT, 6796 CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags, 6797 CCState &State) { 6798 6799 if (ValVT == MVT::f128) 6800 report_fatal_error("f128 is unimplemented on AIX."); 6801 6802 if (ArgFlags.isByVal()) 6803 report_fatal_error("Passing structure by value is unimplemented."); 6804 6805 if (ArgFlags.isNest()) 6806 report_fatal_error("Nest arguments are unimplemented."); 6807 6808 if (ValVT.isVector() || LocVT.isVector()) 6809 report_fatal_error("Vector arguments are unimplemented on AIX."); 6810 6811 const PPCSubtarget &Subtarget = static_cast<const PPCSubtarget &>( 6812 State.getMachineFunction().getSubtarget()); 6813 const bool IsPPC64 = Subtarget.isPPC64(); 6814 const unsigned PtrByteSize = IsPPC64 ? 8 : 4; 6815 6816 static const MCPhysReg GPR_32[] = {// 32-bit registers. 6817 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 6818 PPC::R7, PPC::R8, PPC::R9, PPC::R10}; 6819 static const MCPhysReg GPR_64[] = {// 64-bit registers. 6820 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 6821 PPC::X7, PPC::X8, PPC::X9, PPC::X10}; 6822 6823 // Arguments always reserve parameter save area. 6824 switch (ValVT.SimpleTy) { 6825 default: 6826 report_fatal_error("Unhandled value type for argument."); 6827 case MVT::i64: 6828 // i64 arguments should have been split to i32 for PPC32. 6829 assert(IsPPC64 && "PPC32 should have split i64 values."); 6830 LLVM_FALLTHROUGH; 6831 case MVT::i1: 6832 case MVT::i32: { 6833 const unsigned Offset = State.AllocateStack(PtrByteSize, PtrByteSize); 6834 const MVT RegVT = IsPPC64 ? MVT::i64 : MVT::i32; 6835 if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32)) { 6836 // Promote integers if needed. 6837 if (ValVT.getSizeInBits() < RegVT.getSizeInBits()) 6838 LocInfo = ArgFlags.isSExt() ? CCValAssign::LocInfo::SExt 6839 : CCValAssign::LocInfo::ZExt; 6840 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, RegVT, LocInfo)); 6841 } 6842 else 6843 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, RegVT, LocInfo)); 6844 6845 return false; 6846 } 6847 case MVT::f32: 6848 case MVT::f64: { 6849 // Parameter save area (PSA) is reserved even if the float passes in fpr. 6850 const unsigned StoreSize = LocVT.getStoreSize(); 6851 // Floats are always 4-byte aligned in the PSA on AIX. 6852 // This includes f64 in 64-bit mode for ABI compatibility. 6853 const unsigned Offset = State.AllocateStack(IsPPC64 ? 8 : StoreSize, 4); 6854 unsigned FReg = State.AllocateReg(FPR); 6855 if (FReg) 6856 State.addLoc(CCValAssign::getReg(ValNo, ValVT, FReg, LocVT, LocInfo)); 6857 6858 // Reserve and initialize GPRs or initialize the PSA as required. 6859 const MVT RegVT = IsPPC64 ? MVT::i64 : MVT::i32; 6860 for (unsigned I = 0; I < StoreSize; I += PtrByteSize) { 6861 if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32)) { 6862 assert(FReg && "An FPR should be available when a GPR is reserved."); 6863 if (State.isVarArg()) { 6864 // Successfully reserved GPRs are only initialized for vararg calls. 6865 // Custom handling is required for: 6866 // f64 in PPC32 needs to be split into 2 GPRs. 6867 // f32 in PPC64 needs to occupy only lower 32 bits of 64-bit GPR. 6868 State.addLoc( 6869 CCValAssign::getCustomReg(ValNo, ValVT, Reg, RegVT, LocInfo)); 6870 } 6871 } else { 6872 // If there are insufficient GPRs, the PSA needs to be initialized. 6873 // Initialization occurs even if an FPR was initialized for 6874 // compatibility with the AIX XL compiler. The full memory for the 6875 // argument will be initialized even if a prior word is saved in GPR. 6876 // A custom memLoc is used when the argument also passes in FPR so 6877 // that the callee handling can skip over it easily. 6878 State.addLoc( 6879 FReg ? CCValAssign::getCustomMem(ValNo, ValVT, Offset, LocVT, 6880 LocInfo) 6881 : CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo)); 6882 break; 6883 } 6884 } 6885 6886 return false; 6887 } 6888 } 6889 return true; 6890 } 6891 6892 static const TargetRegisterClass *getRegClassForSVT(MVT::SimpleValueType SVT, 6893 bool IsPPC64) { 6894 assert((IsPPC64 || SVT != MVT::i64) && 6895 "i64 should have been split for 32-bit codegen."); 6896 6897 switch (SVT) { 6898 default: 6899 report_fatal_error("Unexpected value type for formal argument"); 6900 case MVT::i1: 6901 case MVT::i32: 6902 case MVT::i64: 6903 return IsPPC64 ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 6904 case MVT::f32: 6905 return &PPC::F4RCRegClass; 6906 case MVT::f64: 6907 return &PPC::F8RCRegClass; 6908 } 6909 } 6910 6911 static SDValue truncateScalarIntegerArg(ISD::ArgFlagsTy Flags, EVT ValVT, 6912 SelectionDAG &DAG, SDValue ArgValue, 6913 MVT LocVT, const SDLoc &dl) { 6914 assert(ValVT.isScalarInteger() && LocVT.isScalarInteger()); 6915 assert(ValVT.getSizeInBits() < LocVT.getSizeInBits()); 6916 6917 if (Flags.isSExt()) 6918 ArgValue = DAG.getNode(ISD::AssertSext, dl, LocVT, ArgValue, 6919 DAG.getValueType(ValVT)); 6920 else if (Flags.isZExt()) 6921 ArgValue = DAG.getNode(ISD::AssertZext, dl, LocVT, ArgValue, 6922 DAG.getValueType(ValVT)); 6923 6924 return DAG.getNode(ISD::TRUNCATE, dl, ValVT, ArgValue); 6925 } 6926 6927 SDValue PPCTargetLowering::LowerFormalArguments_AIX( 6928 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 6929 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 6930 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 6931 6932 assert((CallConv == CallingConv::C || CallConv == CallingConv::Cold || 6933 CallConv == CallingConv::Fast) && 6934 "Unexpected calling convention!"); 6935 6936 if (isVarArg) 6937 report_fatal_error("This call type is unimplemented on AIX."); 6938 6939 if (getTargetMachine().Options.GuaranteedTailCallOpt) 6940 report_fatal_error("Tail call support is unimplemented on AIX."); 6941 6942 if (useSoftFloat()) 6943 report_fatal_error("Soft float support is unimplemented on AIX."); 6944 6945 const PPCSubtarget &Subtarget = 6946 static_cast<const PPCSubtarget &>(DAG.getSubtarget()); 6947 if (Subtarget.hasQPX()) 6948 report_fatal_error("QPX support is not supported on AIX."); 6949 6950 const bool IsPPC64 = Subtarget.isPPC64(); 6951 const unsigned PtrByteSize = IsPPC64 ? 8 : 4; 6952 6953 // Assign locations to all of the incoming arguments. 6954 SmallVector<CCValAssign, 16> ArgLocs; 6955 MachineFunction &MF = DAG.getMachineFunction(); 6956 CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext()); 6957 6958 // Reserve space for the linkage area on the stack. 6959 const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 6960 // On AIX a minimum of 8 words is saved to the parameter save area. 6961 const unsigned MinParameterSaveArea = 8 * PtrByteSize; 6962 CCInfo.AllocateStack(LinkageSize + MinParameterSaveArea, PtrByteSize); 6963 CCInfo.AnalyzeFormalArguments(Ins, CC_AIX); 6964 6965 for (CCValAssign &VA : ArgLocs) { 6966 6967 if (VA.isMemLoc()) { 6968 // For compatibility with the AIX XL compiler, the float args in the 6969 // parameter save area are initialized even if the argument is available 6970 // in register. The caller is required to initialize both the register 6971 // and memory, however, the callee can choose to expect it in either. The 6972 // memloc is dismissed here because the argument is retrieved from the 6973 // register. 6974 if (VA.needsCustom()) 6975 continue; 6976 report_fatal_error( 6977 "Handling of formal arguments on the stack is unimplemented!"); 6978 } 6979 6980 assert(VA.isRegLoc() && "Unexpected argument location."); 6981 6982 EVT ValVT = VA.getValVT(); 6983 MVT LocVT = VA.getLocVT(); 6984 MVT::SimpleValueType SVT = ValVT.getSimpleVT().SimpleTy; 6985 unsigned VReg = 6986 MF.addLiveIn(VA.getLocReg(), getRegClassForSVT(SVT, IsPPC64)); 6987 SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, VReg, LocVT); 6988 if (ValVT.isScalarInteger() && 6989 (ValVT.getSizeInBits() < LocVT.getSizeInBits())) { 6990 ISD::ArgFlagsTy Flags = Ins[VA.getValNo()].Flags; 6991 ArgValue = 6992 truncateScalarIntegerArg(Flags, ValVT, DAG, ArgValue, LocVT, dl); 6993 } 6994 InVals.push_back(ArgValue); 6995 } 6996 6997 // Area that is at least reserved in the caller of this function. 6998 unsigned MinReservedArea = CCInfo.getNextStackOffset(); 6999 7000 // Set the size that is at least reserved in caller of this function. Tail 7001 // call optimized function's reserved stack space needs to be aligned so 7002 // that taking the difference between two stack areas will result in an 7003 // aligned stack. 7004 MinReservedArea = 7005 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea); 7006 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 7007 FuncInfo->setMinReservedArea(MinReservedArea); 7008 7009 return Chain; 7010 } 7011 7012 SDValue PPCTargetLowering::LowerCall_AIX( 7013 SDValue Chain, SDValue Callee, CallFlags CFlags, 7014 const SmallVectorImpl<ISD::OutputArg> &Outs, 7015 const SmallVectorImpl<SDValue> &OutVals, 7016 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 7017 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 7018 ImmutableCallSite CS) const { 7019 7020 assert((CFlags.CallConv == CallingConv::C || 7021 CFlags.CallConv == CallingConv::Cold || 7022 CFlags.CallConv == CallingConv::Fast) && 7023 "Unexpected calling convention!"); 7024 7025 if (CFlags.IsPatchPoint) 7026 report_fatal_error("This call type is unimplemented on AIX."); 7027 7028 const PPCSubtarget& Subtarget = 7029 static_cast<const PPCSubtarget&>(DAG.getSubtarget()); 7030 if (Subtarget.hasQPX()) 7031 report_fatal_error("QPX is not supported on AIX."); 7032 if (Subtarget.hasAltivec()) 7033 report_fatal_error("Altivec support is unimplemented on AIX."); 7034 7035 MachineFunction &MF = DAG.getMachineFunction(); 7036 SmallVector<CCValAssign, 16> ArgLocs; 7037 CCState CCInfo(CFlags.CallConv, CFlags.IsVarArg, MF, ArgLocs, 7038 *DAG.getContext()); 7039 7040 // Reserve space for the linkage save area (LSA) on the stack. 7041 // In both PPC32 and PPC64 there are 6 reserved slots in the LSA: 7042 // [SP][CR][LR][2 x reserved][TOC]. 7043 // The LSA is 24 bytes (6x4) in PPC32 and 48 bytes (6x8) in PPC64. 7044 const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 7045 const bool IsPPC64 = Subtarget.isPPC64(); 7046 const EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7047 const unsigned PtrByteSize = IsPPC64 ? 8 : 4; 7048 CCInfo.AllocateStack(LinkageSize, PtrByteSize); 7049 CCInfo.AnalyzeCallOperands(Outs, CC_AIX); 7050 7051 // The prolog code of the callee may store up to 8 GPR argument registers to 7052 // the stack, allowing va_start to index over them in memory if the callee 7053 // is variadic. 7054 // Because we cannot tell if this is needed on the caller side, we have to 7055 // conservatively assume that it is needed. As such, make sure we have at 7056 // least enough stack space for the caller to store the 8 GPRs. 7057 const unsigned MinParameterSaveAreaSize = 8 * PtrByteSize; 7058 const unsigned NumBytes = std::max(LinkageSize + MinParameterSaveAreaSize, 7059 CCInfo.getNextStackOffset()); 7060 7061 // Adjust the stack pointer for the new arguments... 7062 // These operations are automatically eliminated by the prolog/epilog pass. 7063 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 7064 SDValue CallSeqStart = Chain; 7065 7066 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 7067 SmallVector<SDValue, 8> MemOpChains; 7068 7069 // Set up a copy of the stack pointer for loading and storing any 7070 // arguments that may not fit in the registers available for argument 7071 // passing. 7072 const SDValue StackPtr = IsPPC64 ? DAG.getRegister(PPC::X1, MVT::i64) 7073 : DAG.getRegister(PPC::R1, MVT::i32); 7074 7075 for (unsigned I = 0, E = ArgLocs.size(); I != E;) { 7076 CCValAssign &VA = ArgLocs[I++]; 7077 7078 SDValue Arg = OutVals[VA.getValNo()]; 7079 7080 if (!VA.isRegLoc() && !VA.isMemLoc()) 7081 report_fatal_error("Unexpected location for function call argument."); 7082 7083 if (VA.isRegLoc() && !VA.needsCustom()) { 7084 switch (VA.getLocInfo()) { 7085 default: 7086 report_fatal_error("Unexpected argument extension type."); 7087 case CCValAssign::Full: 7088 break; 7089 case CCValAssign::ZExt: 7090 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg); 7091 break; 7092 case CCValAssign::SExt: 7093 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg); 7094 break; 7095 } 7096 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 7097 7098 continue; 7099 } 7100 7101 if (VA.isMemLoc()) { 7102 SDValue PtrOff = 7103 DAG.getConstant(VA.getLocMemOffset(), dl, StackPtr.getValueType()); 7104 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 7105 MemOpChains.push_back( 7106 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo())); 7107 7108 continue; 7109 } 7110 7111 // Custom handling is used for GPR initializations for vararg float 7112 // arguments. 7113 assert(VA.isRegLoc() && VA.needsCustom() && CFlags.IsVarArg && 7114 VA.getValVT().isFloatingPoint() && VA.getLocVT().isInteger() && 7115 "Unexpected register handling for calling convention."); 7116 7117 SDValue ArgAsInt = 7118 DAG.getBitcast(MVT::getIntegerVT(VA.getValVT().getSizeInBits()), Arg); 7119 7120 if (Arg.getValueType().getStoreSize() == VA.getLocVT().getStoreSize()) 7121 // f32 in 32-bit GPR 7122 // f64 in 64-bit GPR 7123 RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgAsInt)); 7124 else if (Arg.getValueType().getSizeInBits() < VA.getLocVT().getSizeInBits()) 7125 // f32 in 64-bit GPR. 7126 RegsToPass.push_back(std::make_pair( 7127 VA.getLocReg(), DAG.getZExtOrTrunc(ArgAsInt, dl, VA.getLocVT()))); 7128 else { 7129 // f64 in two 32-bit GPRs 7130 // The 2 GPRs are marked custom and expected to be adjacent in ArgLocs. 7131 assert(Arg.getValueType() == MVT::f64 && CFlags.IsVarArg && !IsPPC64 && 7132 "Unexpected custom register for argument!"); 7133 CCValAssign &GPR1 = VA; 7134 SDValue MSWAsI64 = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgAsInt, 7135 DAG.getConstant(32, dl, MVT::i8)); 7136 RegsToPass.push_back(std::make_pair( 7137 GPR1.getLocReg(), DAG.getZExtOrTrunc(MSWAsI64, dl, MVT::i32))); 7138 7139 if (I != E) { 7140 // If only 1 GPR was available, there will only be one custom GPR and 7141 // the argument will also pass in memory. 7142 CCValAssign &PeekArg = ArgLocs[I]; 7143 if (PeekArg.isRegLoc() && PeekArg.getValNo() == PeekArg.getValNo()) { 7144 assert(PeekArg.needsCustom() && "A second custom GPR is expected."); 7145 CCValAssign &GPR2 = ArgLocs[I++]; 7146 RegsToPass.push_back(std::make_pair( 7147 GPR2.getLocReg(), DAG.getZExtOrTrunc(ArgAsInt, dl, MVT::i32))); 7148 } 7149 } 7150 } 7151 } 7152 7153 if (!MemOpChains.empty()) 7154 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 7155 7156 // For indirect calls, we need to save the TOC base to the stack for 7157 // restoration after the call. 7158 if (CFlags.IsIndirect) { 7159 assert(!CFlags.IsTailCall && "Indirect tail-calls not supported."); 7160 const MCRegister TOCBaseReg = Subtarget.getTOCPointerRegister(); 7161 const MCRegister StackPtrReg = Subtarget.getStackPointerRegister(); 7162 const MVT PtrVT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32; 7163 const unsigned TOCSaveOffset = 7164 Subtarget.getFrameLowering()->getTOCSaveOffset(); 7165 7166 setUsesTOCBasePtr(DAG); 7167 SDValue Val = DAG.getCopyFromReg(Chain, dl, TOCBaseReg, PtrVT); 7168 SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl); 7169 SDValue StackPtr = DAG.getRegister(StackPtrReg, PtrVT); 7170 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 7171 Chain = DAG.getStore( 7172 Val.getValue(1), dl, Val, AddPtr, 7173 MachinePointerInfo::getStack(DAG.getMachineFunction(), TOCSaveOffset)); 7174 } 7175 7176 // Build a sequence of copy-to-reg nodes chained together with token chain 7177 // and flag operands which copy the outgoing args into the appropriate regs. 7178 SDValue InFlag; 7179 for (auto Reg : RegsToPass) { 7180 Chain = DAG.getCopyToReg(Chain, dl, Reg.first, Reg.second, InFlag); 7181 InFlag = Chain.getValue(1); 7182 } 7183 7184 const int SPDiff = 0; 7185 return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart, 7186 Callee, SPDiff, NumBytes, Ins, InVals, CS); 7187 } 7188 7189 bool 7190 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv, 7191 MachineFunction &MF, bool isVarArg, 7192 const SmallVectorImpl<ISD::OutputArg> &Outs, 7193 LLVMContext &Context) const { 7194 SmallVector<CCValAssign, 16> RVLocs; 7195 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context); 7196 return CCInfo.CheckReturn( 7197 Outs, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold) 7198 ? RetCC_PPC_Cold 7199 : RetCC_PPC); 7200 } 7201 7202 SDValue 7203 PPCTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 7204 bool isVarArg, 7205 const SmallVectorImpl<ISD::OutputArg> &Outs, 7206 const SmallVectorImpl<SDValue> &OutVals, 7207 const SDLoc &dl, SelectionDAG &DAG) const { 7208 SmallVector<CCValAssign, 16> RVLocs; 7209 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 7210 *DAG.getContext()); 7211 CCInfo.AnalyzeReturn(Outs, 7212 (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold) 7213 ? RetCC_PPC_Cold 7214 : RetCC_PPC); 7215 7216 SDValue Flag; 7217 SmallVector<SDValue, 4> RetOps(1, Chain); 7218 7219 // Copy the result values into the output registers. 7220 for (unsigned i = 0, RealResIdx = 0; i != RVLocs.size(); ++i, ++RealResIdx) { 7221 CCValAssign &VA = RVLocs[i]; 7222 assert(VA.isRegLoc() && "Can only return in registers!"); 7223 7224 SDValue Arg = OutVals[RealResIdx]; 7225 7226 switch (VA.getLocInfo()) { 7227 default: llvm_unreachable("Unknown loc info!"); 7228 case CCValAssign::Full: break; 7229 case CCValAssign::AExt: 7230 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg); 7231 break; 7232 case CCValAssign::ZExt: 7233 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg); 7234 break; 7235 case CCValAssign::SExt: 7236 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg); 7237 break; 7238 } 7239 if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) { 7240 bool isLittleEndian = Subtarget.isLittleEndian(); 7241 // Legalize ret f64 -> ret 2 x i32. 7242 SDValue SVal = 7243 DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg, 7244 DAG.getIntPtrConstant(isLittleEndian ? 0 : 1, dl)); 7245 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Flag); 7246 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 7247 SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg, 7248 DAG.getIntPtrConstant(isLittleEndian ? 1 : 0, dl)); 7249 Flag = Chain.getValue(1); 7250 VA = RVLocs[++i]; // skip ahead to next loc 7251 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Flag); 7252 } else 7253 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag); 7254 Flag = Chain.getValue(1); 7255 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 7256 } 7257 7258 const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo(); 7259 const MCPhysReg *I = 7260 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction()); 7261 if (I) { 7262 for (; *I; ++I) { 7263 7264 if (PPC::G8RCRegClass.contains(*I)) 7265 RetOps.push_back(DAG.getRegister(*I, MVT::i64)); 7266 else if (PPC::F8RCRegClass.contains(*I)) 7267 RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64))); 7268 else if (PPC::CRRCRegClass.contains(*I)) 7269 RetOps.push_back(DAG.getRegister(*I, MVT::i1)); 7270 else if (PPC::VRRCRegClass.contains(*I)) 7271 RetOps.push_back(DAG.getRegister(*I, MVT::Other)); 7272 else 7273 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 7274 } 7275 } 7276 7277 RetOps[0] = Chain; // Update chain. 7278 7279 // Add the flag if we have it. 7280 if (Flag.getNode()) 7281 RetOps.push_back(Flag); 7282 7283 return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, RetOps); 7284 } 7285 7286 SDValue 7287 PPCTargetLowering::LowerGET_DYNAMIC_AREA_OFFSET(SDValue Op, 7288 SelectionDAG &DAG) const { 7289 SDLoc dl(Op); 7290 7291 // Get the correct type for integers. 7292 EVT IntVT = Op.getValueType(); 7293 7294 // Get the inputs. 7295 SDValue Chain = Op.getOperand(0); 7296 SDValue FPSIdx = getFramePointerFrameIndex(DAG); 7297 // Build a DYNAREAOFFSET node. 7298 SDValue Ops[2] = {Chain, FPSIdx}; 7299 SDVTList VTs = DAG.getVTList(IntVT); 7300 return DAG.getNode(PPCISD::DYNAREAOFFSET, dl, VTs, Ops); 7301 } 7302 7303 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op, 7304 SelectionDAG &DAG) const { 7305 // When we pop the dynamic allocation we need to restore the SP link. 7306 SDLoc dl(Op); 7307 7308 // Get the correct type for pointers. 7309 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7310 7311 // Construct the stack pointer operand. 7312 bool isPPC64 = Subtarget.isPPC64(); 7313 unsigned SP = isPPC64 ? PPC::X1 : PPC::R1; 7314 SDValue StackPtr = DAG.getRegister(SP, PtrVT); 7315 7316 // Get the operands for the STACKRESTORE. 7317 SDValue Chain = Op.getOperand(0); 7318 SDValue SaveSP = Op.getOperand(1); 7319 7320 // Load the old link SP. 7321 SDValue LoadLinkSP = 7322 DAG.getLoad(PtrVT, dl, Chain, StackPtr, MachinePointerInfo()); 7323 7324 // Restore the stack pointer. 7325 Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP); 7326 7327 // Store the old link SP. 7328 return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo()); 7329 } 7330 7331 SDValue PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG &DAG) const { 7332 MachineFunction &MF = DAG.getMachineFunction(); 7333 bool isPPC64 = Subtarget.isPPC64(); 7334 EVT PtrVT = getPointerTy(MF.getDataLayout()); 7335 7336 // Get current frame pointer save index. The users of this index will be 7337 // primarily DYNALLOC instructions. 7338 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>(); 7339 int RASI = FI->getReturnAddrSaveIndex(); 7340 7341 // If the frame pointer save index hasn't been defined yet. 7342 if (!RASI) { 7343 // Find out what the fix offset of the frame pointer save area. 7344 int LROffset = Subtarget.getFrameLowering()->getReturnSaveOffset(); 7345 // Allocate the frame index for frame pointer save area. 7346 RASI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, LROffset, false); 7347 // Save the result. 7348 FI->setReturnAddrSaveIndex(RASI); 7349 } 7350 return DAG.getFrameIndex(RASI, PtrVT); 7351 } 7352 7353 SDValue 7354 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const { 7355 MachineFunction &MF = DAG.getMachineFunction(); 7356 bool isPPC64 = Subtarget.isPPC64(); 7357 EVT PtrVT = getPointerTy(MF.getDataLayout()); 7358 7359 // Get current frame pointer save index. The users of this index will be 7360 // primarily DYNALLOC instructions. 7361 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>(); 7362 int FPSI = FI->getFramePointerSaveIndex(); 7363 7364 // If the frame pointer save index hasn't been defined yet. 7365 if (!FPSI) { 7366 // Find out what the fix offset of the frame pointer save area. 7367 int FPOffset = Subtarget.getFrameLowering()->getFramePointerSaveOffset(); 7368 // Allocate the frame index for frame pointer save area. 7369 FPSI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, FPOffset, true); 7370 // Save the result. 7371 FI->setFramePointerSaveIndex(FPSI); 7372 } 7373 return DAG.getFrameIndex(FPSI, PtrVT); 7374 } 7375 7376 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, 7377 SelectionDAG &DAG) const { 7378 // Get the inputs. 7379 SDValue Chain = Op.getOperand(0); 7380 SDValue Size = Op.getOperand(1); 7381 SDLoc dl(Op); 7382 7383 // Get the correct type for pointers. 7384 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7385 // Negate the size. 7386 SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT, 7387 DAG.getConstant(0, dl, PtrVT), Size); 7388 // Construct a node for the frame pointer save index. 7389 SDValue FPSIdx = getFramePointerFrameIndex(DAG); 7390 // Build a DYNALLOC node. 7391 SDValue Ops[3] = { Chain, NegSize, FPSIdx }; 7392 SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other); 7393 return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops); 7394 } 7395 7396 SDValue PPCTargetLowering::LowerEH_DWARF_CFA(SDValue Op, 7397 SelectionDAG &DAG) const { 7398 MachineFunction &MF = DAG.getMachineFunction(); 7399 7400 bool isPPC64 = Subtarget.isPPC64(); 7401 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7402 7403 int FI = MF.getFrameInfo().CreateFixedObject(isPPC64 ? 8 : 4, 0, false); 7404 return DAG.getFrameIndex(FI, PtrVT); 7405 } 7406 7407 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op, 7408 SelectionDAG &DAG) const { 7409 SDLoc DL(Op); 7410 return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL, 7411 DAG.getVTList(MVT::i32, MVT::Other), 7412 Op.getOperand(0), Op.getOperand(1)); 7413 } 7414 7415 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op, 7416 SelectionDAG &DAG) const { 7417 SDLoc DL(Op); 7418 return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other, 7419 Op.getOperand(0), Op.getOperand(1)); 7420 } 7421 7422 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const { 7423 if (Op.getValueType().isVector()) 7424 return LowerVectorLoad(Op, DAG); 7425 7426 assert(Op.getValueType() == MVT::i1 && 7427 "Custom lowering only for i1 loads"); 7428 7429 // First, load 8 bits into 32 bits, then truncate to 1 bit. 7430 7431 SDLoc dl(Op); 7432 LoadSDNode *LD = cast<LoadSDNode>(Op); 7433 7434 SDValue Chain = LD->getChain(); 7435 SDValue BasePtr = LD->getBasePtr(); 7436 MachineMemOperand *MMO = LD->getMemOperand(); 7437 7438 SDValue NewLD = 7439 DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(DAG.getDataLayout()), Chain, 7440 BasePtr, MVT::i8, MMO); 7441 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD); 7442 7443 SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) }; 7444 return DAG.getMergeValues(Ops, dl); 7445 } 7446 7447 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const { 7448 if (Op.getOperand(1).getValueType().isVector()) 7449 return LowerVectorStore(Op, DAG); 7450 7451 assert(Op.getOperand(1).getValueType() == MVT::i1 && 7452 "Custom lowering only for i1 stores"); 7453 7454 // First, zero extend to 32 bits, then use a truncating store to 8 bits. 7455 7456 SDLoc dl(Op); 7457 StoreSDNode *ST = cast<StoreSDNode>(Op); 7458 7459 SDValue Chain = ST->getChain(); 7460 SDValue BasePtr = ST->getBasePtr(); 7461 SDValue Value = ST->getValue(); 7462 MachineMemOperand *MMO = ST->getMemOperand(); 7463 7464 Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(DAG.getDataLayout()), 7465 Value); 7466 return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO); 7467 } 7468 7469 // FIXME: Remove this once the ANDI glue bug is fixed: 7470 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const { 7471 assert(Op.getValueType() == MVT::i1 && 7472 "Custom lowering only for i1 results"); 7473 7474 SDLoc DL(Op); 7475 return DAG.getNode(PPCISD::ANDI_rec_1_GT_BIT, DL, MVT::i1, Op.getOperand(0)); 7476 } 7477 7478 SDValue PPCTargetLowering::LowerTRUNCATEVector(SDValue Op, 7479 SelectionDAG &DAG) const { 7480 7481 // Implements a vector truncate that fits in a vector register as a shuffle. 7482 // We want to legalize vector truncates down to where the source fits in 7483 // a vector register (and target is therefore smaller than vector register 7484 // size). At that point legalization will try to custom lower the sub-legal 7485 // result and get here - where we can contain the truncate as a single target 7486 // operation. 7487 7488 // For example a trunc <2 x i16> to <2 x i8> could be visualized as follows: 7489 // <MSB1|LSB1, MSB2|LSB2> to <LSB1, LSB2> 7490 // 7491 // We will implement it for big-endian ordering as this (where x denotes 7492 // undefined): 7493 // < MSB1|LSB1, MSB2|LSB2, uu, uu, uu, uu, uu, uu> to 7494 // < LSB1, LSB2, u, u, u, u, u, u, u, u, u, u, u, u, u, u> 7495 // 7496 // The same operation in little-endian ordering will be: 7497 // <uu, uu, uu, uu, uu, uu, LSB2|MSB2, LSB1|MSB1> to 7498 // <u, u, u, u, u, u, u, u, u, u, u, u, u, u, LSB2, LSB1> 7499 7500 assert(Op.getValueType().isVector() && "Vector type expected."); 7501 7502 SDLoc DL(Op); 7503 SDValue N1 = Op.getOperand(0); 7504 unsigned SrcSize = N1.getValueType().getSizeInBits(); 7505 assert(SrcSize <= 128 && "Source must fit in an Altivec/VSX vector"); 7506 SDValue WideSrc = SrcSize == 128 ? N1 : widenVec(DAG, N1, DL); 7507 7508 EVT TrgVT = Op.getValueType(); 7509 unsigned TrgNumElts = TrgVT.getVectorNumElements(); 7510 EVT EltVT = TrgVT.getVectorElementType(); 7511 unsigned WideNumElts = 128 / EltVT.getSizeInBits(); 7512 EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts); 7513 7514 // First list the elements we want to keep. 7515 unsigned SizeMult = SrcSize / TrgVT.getSizeInBits(); 7516 SmallVector<int, 16> ShuffV; 7517 if (Subtarget.isLittleEndian()) 7518 for (unsigned i = 0; i < TrgNumElts; ++i) 7519 ShuffV.push_back(i * SizeMult); 7520 else 7521 for (unsigned i = 1; i <= TrgNumElts; ++i) 7522 ShuffV.push_back(i * SizeMult - 1); 7523 7524 // Populate the remaining elements with undefs. 7525 for (unsigned i = TrgNumElts; i < WideNumElts; ++i) 7526 // ShuffV.push_back(i + WideNumElts); 7527 ShuffV.push_back(WideNumElts + 1); 7528 7529 SDValue Conv = DAG.getNode(ISD::BITCAST, DL, WideVT, WideSrc); 7530 return DAG.getVectorShuffle(WideVT, DL, Conv, DAG.getUNDEF(WideVT), ShuffV); 7531 } 7532 7533 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when 7534 /// possible. 7535 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const { 7536 // Not FP? Not a fsel. 7537 if (!Op.getOperand(0).getValueType().isFloatingPoint() || 7538 !Op.getOperand(2).getValueType().isFloatingPoint()) 7539 return Op; 7540 7541 bool HasNoInfs = DAG.getTarget().Options.NoInfsFPMath; 7542 bool HasNoNaNs = DAG.getTarget().Options.NoNaNsFPMath; 7543 // We might be able to do better than this under some circumstances, but in 7544 // general, fsel-based lowering of select is a finite-math-only optimization. 7545 // For more information, see section F.3 of the 2.06 ISA specification. 7546 // With ISA 3.0, we have xsmaxcdp/xsmincdp which are OK to emit even in the 7547 // presence of infinities. 7548 if (!Subtarget.hasP9Vector() && (!HasNoInfs || !HasNoNaNs)) 7549 return Op; 7550 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get(); 7551 7552 EVT ResVT = Op.getValueType(); 7553 EVT CmpVT = Op.getOperand(0).getValueType(); 7554 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 7555 SDValue TV = Op.getOperand(2), FV = Op.getOperand(3); 7556 SDLoc dl(Op); 7557 7558 if (Subtarget.hasP9Vector() && LHS == TV && RHS == FV) { 7559 switch (CC) { 7560 default: 7561 // Not a min/max but with finite math, we may still be able to use fsel. 7562 if (HasNoInfs && HasNoNaNs) 7563 break; 7564 return Op; 7565 case ISD::SETOGT: 7566 case ISD::SETGT: 7567 return DAG.getNode(PPCISD::XSMAXCDP, dl, Op.getValueType(), LHS, RHS); 7568 case ISD::SETOLT: 7569 case ISD::SETLT: 7570 return DAG.getNode(PPCISD::XSMINCDP, dl, Op.getValueType(), LHS, RHS); 7571 } 7572 } else if (!HasNoInfs || !HasNoNaNs) 7573 return Op; 7574 7575 // TODO: Propagate flags from the select rather than global settings. 7576 SDNodeFlags Flags; 7577 Flags.setNoInfs(true); 7578 Flags.setNoNaNs(true); 7579 7580 // If the RHS of the comparison is a 0.0, we don't need to do the 7581 // subtraction at all. 7582 SDValue Sel1; 7583 if (isFloatingPointZero(RHS)) 7584 switch (CC) { 7585 default: break; // SETUO etc aren't handled by fsel. 7586 case ISD::SETNE: 7587 std::swap(TV, FV); 7588 LLVM_FALLTHROUGH; 7589 case ISD::SETEQ: 7590 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits 7591 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); 7592 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV); 7593 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits 7594 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1); 7595 return DAG.getNode(PPCISD::FSEL, dl, ResVT, 7596 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV); 7597 case ISD::SETULT: 7598 case ISD::SETLT: 7599 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt 7600 LLVM_FALLTHROUGH; 7601 case ISD::SETOGE: 7602 case ISD::SETGE: 7603 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits 7604 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); 7605 return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV); 7606 case ISD::SETUGT: 7607 case ISD::SETGT: 7608 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt 7609 LLVM_FALLTHROUGH; 7610 case ISD::SETOLE: 7611 case ISD::SETLE: 7612 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits 7613 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); 7614 return DAG.getNode(PPCISD::FSEL, dl, ResVT, 7615 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV); 7616 } 7617 7618 SDValue Cmp; 7619 switch (CC) { 7620 default: break; // SETUO etc aren't handled by fsel. 7621 case ISD::SETNE: 7622 std::swap(TV, FV); 7623 LLVM_FALLTHROUGH; 7624 case ISD::SETEQ: 7625 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags); 7626 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 7627 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 7628 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); 7629 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits 7630 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1); 7631 return DAG.getNode(PPCISD::FSEL, dl, ResVT, 7632 DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV); 7633 case ISD::SETULT: 7634 case ISD::SETLT: 7635 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags); 7636 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 7637 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 7638 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV); 7639 case ISD::SETOGE: 7640 case ISD::SETGE: 7641 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags); 7642 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 7643 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 7644 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); 7645 case ISD::SETUGT: 7646 case ISD::SETGT: 7647 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags); 7648 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 7649 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 7650 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV); 7651 case ISD::SETOLE: 7652 case ISD::SETLE: 7653 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags); 7654 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 7655 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 7656 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); 7657 } 7658 return Op; 7659 } 7660 7661 void PPCTargetLowering::LowerFP_TO_INTForReuse(SDValue Op, ReuseLoadInfo &RLI, 7662 SelectionDAG &DAG, 7663 const SDLoc &dl) const { 7664 assert(Op.getOperand(0).getValueType().isFloatingPoint()); 7665 SDValue Src = Op.getOperand(0); 7666 if (Src.getValueType() == MVT::f32) 7667 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src); 7668 7669 SDValue Tmp; 7670 switch (Op.getSimpleValueType().SimpleTy) { 7671 default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!"); 7672 case MVT::i32: 7673 Tmp = DAG.getNode( 7674 Op.getOpcode() == ISD::FP_TO_SINT 7675 ? PPCISD::FCTIWZ 7676 : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ), 7677 dl, MVT::f64, Src); 7678 break; 7679 case MVT::i64: 7680 assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) && 7681 "i64 FP_TO_UINT is supported only with FPCVT"); 7682 Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ : 7683 PPCISD::FCTIDUZ, 7684 dl, MVT::f64, Src); 7685 break; 7686 } 7687 7688 // Convert the FP value to an int value through memory. 7689 bool i32Stack = Op.getValueType() == MVT::i32 && Subtarget.hasSTFIWX() && 7690 (Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()); 7691 SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64); 7692 int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex(); 7693 MachinePointerInfo MPI = 7694 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI); 7695 7696 // Emit a store to the stack slot. 7697 SDValue Chain; 7698 if (i32Stack) { 7699 MachineFunction &MF = DAG.getMachineFunction(); 7700 MachineMemOperand *MMO = 7701 MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, 4); 7702 SDValue Ops[] = { DAG.getEntryNode(), Tmp, FIPtr }; 7703 Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl, 7704 DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO); 7705 } else 7706 Chain = DAG.getStore(DAG.getEntryNode(), dl, Tmp, FIPtr, MPI); 7707 7708 // Result is a load from the stack slot. If loading 4 bytes, make sure to 7709 // add in a bias on big endian. 7710 if (Op.getValueType() == MVT::i32 && !i32Stack) { 7711 FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr, 7712 DAG.getConstant(4, dl, FIPtr.getValueType())); 7713 MPI = MPI.getWithOffset(Subtarget.isLittleEndian() ? 0 : 4); 7714 } 7715 7716 RLI.Chain = Chain; 7717 RLI.Ptr = FIPtr; 7718 RLI.MPI = MPI; 7719 } 7720 7721 /// Custom lowers floating point to integer conversions to use 7722 /// the direct move instructions available in ISA 2.07 to avoid the 7723 /// need for load/store combinations. 7724 SDValue PPCTargetLowering::LowerFP_TO_INTDirectMove(SDValue Op, 7725 SelectionDAG &DAG, 7726 const SDLoc &dl) const { 7727 assert(Op.getOperand(0).getValueType().isFloatingPoint()); 7728 SDValue Src = Op.getOperand(0); 7729 7730 if (Src.getValueType() == MVT::f32) 7731 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src); 7732 7733 SDValue Tmp; 7734 switch (Op.getSimpleValueType().SimpleTy) { 7735 default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!"); 7736 case MVT::i32: 7737 Tmp = DAG.getNode( 7738 Op.getOpcode() == ISD::FP_TO_SINT 7739 ? PPCISD::FCTIWZ 7740 : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ), 7741 dl, MVT::f64, Src); 7742 Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i32, Tmp); 7743 break; 7744 case MVT::i64: 7745 assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) && 7746 "i64 FP_TO_UINT is supported only with FPCVT"); 7747 Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ : 7748 PPCISD::FCTIDUZ, 7749 dl, MVT::f64, Src); 7750 Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i64, Tmp); 7751 break; 7752 } 7753 return Tmp; 7754 } 7755 7756 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG, 7757 const SDLoc &dl) const { 7758 7759 // FP to INT conversions are legal for f128. 7760 if (EnableQuadPrecision && (Op->getOperand(0).getValueType() == MVT::f128)) 7761 return Op; 7762 7763 // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on 7764 // PPC (the libcall is not available). 7765 if (Op.getOperand(0).getValueType() == MVT::ppcf128) { 7766 if (Op.getValueType() == MVT::i32) { 7767 if (Op.getOpcode() == ISD::FP_TO_SINT) { 7768 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, 7769 MVT::f64, Op.getOperand(0), 7770 DAG.getIntPtrConstant(0, dl)); 7771 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, 7772 MVT::f64, Op.getOperand(0), 7773 DAG.getIntPtrConstant(1, dl)); 7774 7775 // Add the two halves of the long double in round-to-zero mode. 7776 SDValue Res = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi); 7777 7778 // Now use a smaller FP_TO_SINT. 7779 return DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Res); 7780 } 7781 if (Op.getOpcode() == ISD::FP_TO_UINT) { 7782 const uint64_t TwoE31[] = {0x41e0000000000000LL, 0}; 7783 APFloat APF = APFloat(APFloat::PPCDoubleDouble(), APInt(128, TwoE31)); 7784 SDValue Tmp = DAG.getConstantFP(APF, dl, MVT::ppcf128); 7785 // X>=2^31 ? (int)(X-2^31)+0x80000000 : (int)X 7786 // FIXME: generated code sucks. 7787 // TODO: Are there fast-math-flags to propagate to this FSUB? 7788 SDValue True = DAG.getNode(ISD::FSUB, dl, MVT::ppcf128, 7789 Op.getOperand(0), Tmp); 7790 True = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, True); 7791 True = DAG.getNode(ISD::ADD, dl, MVT::i32, True, 7792 DAG.getConstant(0x80000000, dl, MVT::i32)); 7793 SDValue False = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, 7794 Op.getOperand(0)); 7795 return DAG.getSelectCC(dl, Op.getOperand(0), Tmp, True, False, 7796 ISD::SETGE); 7797 } 7798 } 7799 7800 return SDValue(); 7801 } 7802 7803 if (Subtarget.hasDirectMove() && Subtarget.isPPC64()) 7804 return LowerFP_TO_INTDirectMove(Op, DAG, dl); 7805 7806 ReuseLoadInfo RLI; 7807 LowerFP_TO_INTForReuse(Op, RLI, DAG, dl); 7808 7809 return DAG.getLoad(Op.getValueType(), dl, RLI.Chain, RLI.Ptr, RLI.MPI, 7810 RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges); 7811 } 7812 7813 // We're trying to insert a regular store, S, and then a load, L. If the 7814 // incoming value, O, is a load, we might just be able to have our load use the 7815 // address used by O. However, we don't know if anything else will store to 7816 // that address before we can load from it. To prevent this situation, we need 7817 // to insert our load, L, into the chain as a peer of O. To do this, we give L 7818 // the same chain operand as O, we create a token factor from the chain results 7819 // of O and L, and we replace all uses of O's chain result with that token 7820 // factor (see spliceIntoChain below for this last part). 7821 bool PPCTargetLowering::canReuseLoadAddress(SDValue Op, EVT MemVT, 7822 ReuseLoadInfo &RLI, 7823 SelectionDAG &DAG, 7824 ISD::LoadExtType ET) const { 7825 SDLoc dl(Op); 7826 if (ET == ISD::NON_EXTLOAD && 7827 (Op.getOpcode() == ISD::FP_TO_UINT || 7828 Op.getOpcode() == ISD::FP_TO_SINT) && 7829 isOperationLegalOrCustom(Op.getOpcode(), 7830 Op.getOperand(0).getValueType())) { 7831 7832 LowerFP_TO_INTForReuse(Op, RLI, DAG, dl); 7833 return true; 7834 } 7835 7836 LoadSDNode *LD = dyn_cast<LoadSDNode>(Op); 7837 if (!LD || LD->getExtensionType() != ET || LD->isVolatile() || 7838 LD->isNonTemporal()) 7839 return false; 7840 if (LD->getMemoryVT() != MemVT) 7841 return false; 7842 7843 RLI.Ptr = LD->getBasePtr(); 7844 if (LD->isIndexed() && !LD->getOffset().isUndef()) { 7845 assert(LD->getAddressingMode() == ISD::PRE_INC && 7846 "Non-pre-inc AM on PPC?"); 7847 RLI.Ptr = DAG.getNode(ISD::ADD, dl, RLI.Ptr.getValueType(), RLI.Ptr, 7848 LD->getOffset()); 7849 } 7850 7851 RLI.Chain = LD->getChain(); 7852 RLI.MPI = LD->getPointerInfo(); 7853 RLI.IsDereferenceable = LD->isDereferenceable(); 7854 RLI.IsInvariant = LD->isInvariant(); 7855 RLI.Alignment = LD->getAlignment(); 7856 RLI.AAInfo = LD->getAAInfo(); 7857 RLI.Ranges = LD->getRanges(); 7858 7859 RLI.ResChain = SDValue(LD, LD->isIndexed() ? 2 : 1); 7860 return true; 7861 } 7862 7863 // Given the head of the old chain, ResChain, insert a token factor containing 7864 // it and NewResChain, and make users of ResChain now be users of that token 7865 // factor. 7866 // TODO: Remove and use DAG::makeEquivalentMemoryOrdering() instead. 7867 void PPCTargetLowering::spliceIntoChain(SDValue ResChain, 7868 SDValue NewResChain, 7869 SelectionDAG &DAG) const { 7870 if (!ResChain) 7871 return; 7872 7873 SDLoc dl(NewResChain); 7874 7875 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 7876 NewResChain, DAG.getUNDEF(MVT::Other)); 7877 assert(TF.getNode() != NewResChain.getNode() && 7878 "A new TF really is required here"); 7879 7880 DAG.ReplaceAllUsesOfValueWith(ResChain, TF); 7881 DAG.UpdateNodeOperands(TF.getNode(), ResChain, NewResChain); 7882 } 7883 7884 /// Analyze profitability of direct move 7885 /// prefer float load to int load plus direct move 7886 /// when there is no integer use of int load 7887 bool PPCTargetLowering::directMoveIsProfitable(const SDValue &Op) const { 7888 SDNode *Origin = Op.getOperand(0).getNode(); 7889 if (Origin->getOpcode() != ISD::LOAD) 7890 return true; 7891 7892 // If there is no LXSIBZX/LXSIHZX, like Power8, 7893 // prefer direct move if the memory size is 1 or 2 bytes. 7894 MachineMemOperand *MMO = cast<LoadSDNode>(Origin)->getMemOperand(); 7895 if (!Subtarget.hasP9Vector() && MMO->getSize() <= 2) 7896 return true; 7897 7898 for (SDNode::use_iterator UI = Origin->use_begin(), 7899 UE = Origin->use_end(); 7900 UI != UE; ++UI) { 7901 7902 // Only look at the users of the loaded value. 7903 if (UI.getUse().get().getResNo() != 0) 7904 continue; 7905 7906 if (UI->getOpcode() != ISD::SINT_TO_FP && 7907 UI->getOpcode() != ISD::UINT_TO_FP) 7908 return true; 7909 } 7910 7911 return false; 7912 } 7913 7914 /// Custom lowers integer to floating point conversions to use 7915 /// the direct move instructions available in ISA 2.07 to avoid the 7916 /// need for load/store combinations. 7917 SDValue PPCTargetLowering::LowerINT_TO_FPDirectMove(SDValue Op, 7918 SelectionDAG &DAG, 7919 const SDLoc &dl) const { 7920 assert((Op.getValueType() == MVT::f32 || 7921 Op.getValueType() == MVT::f64) && 7922 "Invalid floating point type as target of conversion"); 7923 assert(Subtarget.hasFPCVT() && 7924 "Int to FP conversions with direct moves require FPCVT"); 7925 SDValue FP; 7926 SDValue Src = Op.getOperand(0); 7927 bool SinglePrec = Op.getValueType() == MVT::f32; 7928 bool WordInt = Src.getSimpleValueType().SimpleTy == MVT::i32; 7929 bool Signed = Op.getOpcode() == ISD::SINT_TO_FP; 7930 unsigned ConvOp = Signed ? (SinglePrec ? PPCISD::FCFIDS : PPCISD::FCFID) : 7931 (SinglePrec ? PPCISD::FCFIDUS : PPCISD::FCFIDU); 7932 7933 if (WordInt) { 7934 FP = DAG.getNode(Signed ? PPCISD::MTVSRA : PPCISD::MTVSRZ, 7935 dl, MVT::f64, Src); 7936 FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP); 7937 } 7938 else { 7939 FP = DAG.getNode(PPCISD::MTVSRA, dl, MVT::f64, Src); 7940 FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP); 7941 } 7942 7943 return FP; 7944 } 7945 7946 static SDValue widenVec(SelectionDAG &DAG, SDValue Vec, const SDLoc &dl) { 7947 7948 EVT VecVT = Vec.getValueType(); 7949 assert(VecVT.isVector() && "Expected a vector type."); 7950 assert(VecVT.getSizeInBits() < 128 && "Vector is already full width."); 7951 7952 EVT EltVT = VecVT.getVectorElementType(); 7953 unsigned WideNumElts = 128 / EltVT.getSizeInBits(); 7954 EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts); 7955 7956 unsigned NumConcat = WideNumElts / VecVT.getVectorNumElements(); 7957 SmallVector<SDValue, 16> Ops(NumConcat); 7958 Ops[0] = Vec; 7959 SDValue UndefVec = DAG.getUNDEF(VecVT); 7960 for (unsigned i = 1; i < NumConcat; ++i) 7961 Ops[i] = UndefVec; 7962 7963 return DAG.getNode(ISD::CONCAT_VECTORS, dl, WideVT, Ops); 7964 } 7965 7966 SDValue PPCTargetLowering::LowerINT_TO_FPVector(SDValue Op, SelectionDAG &DAG, 7967 const SDLoc &dl) const { 7968 7969 unsigned Opc = Op.getOpcode(); 7970 assert((Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP) && 7971 "Unexpected conversion type"); 7972 assert((Op.getValueType() == MVT::v2f64 || Op.getValueType() == MVT::v4f32) && 7973 "Supports conversions to v2f64/v4f32 only."); 7974 7975 bool SignedConv = Opc == ISD::SINT_TO_FP; 7976 bool FourEltRes = Op.getValueType() == MVT::v4f32; 7977 7978 SDValue Wide = widenVec(DAG, Op.getOperand(0), dl); 7979 EVT WideVT = Wide.getValueType(); 7980 unsigned WideNumElts = WideVT.getVectorNumElements(); 7981 MVT IntermediateVT = FourEltRes ? MVT::v4i32 : MVT::v2i64; 7982 7983 SmallVector<int, 16> ShuffV; 7984 for (unsigned i = 0; i < WideNumElts; ++i) 7985 ShuffV.push_back(i + WideNumElts); 7986 7987 int Stride = FourEltRes ? WideNumElts / 4 : WideNumElts / 2; 7988 int SaveElts = FourEltRes ? 4 : 2; 7989 if (Subtarget.isLittleEndian()) 7990 for (int i = 0; i < SaveElts; i++) 7991 ShuffV[i * Stride] = i; 7992 else 7993 for (int i = 1; i <= SaveElts; i++) 7994 ShuffV[i * Stride - 1] = i - 1; 7995 7996 SDValue ShuffleSrc2 = 7997 SignedConv ? DAG.getUNDEF(WideVT) : DAG.getConstant(0, dl, WideVT); 7998 SDValue Arrange = DAG.getVectorShuffle(WideVT, dl, Wide, ShuffleSrc2, ShuffV); 7999 unsigned ExtendOp = 8000 SignedConv ? (unsigned)PPCISD::SExtVElems : (unsigned)ISD::BITCAST; 8001 8002 SDValue Extend; 8003 if (!Subtarget.hasP9Altivec() && SignedConv) { 8004 Arrange = DAG.getBitcast(IntermediateVT, Arrange); 8005 Extend = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, IntermediateVT, Arrange, 8006 DAG.getValueType(Op.getOperand(0).getValueType())); 8007 } else 8008 Extend = DAG.getNode(ExtendOp, dl, IntermediateVT, Arrange); 8009 8010 return DAG.getNode(Opc, dl, Op.getValueType(), Extend); 8011 } 8012 8013 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op, 8014 SelectionDAG &DAG) const { 8015 SDLoc dl(Op); 8016 8017 EVT InVT = Op.getOperand(0).getValueType(); 8018 EVT OutVT = Op.getValueType(); 8019 if (OutVT.isVector() && OutVT.isFloatingPoint() && 8020 isOperationCustom(Op.getOpcode(), InVT)) 8021 return LowerINT_TO_FPVector(Op, DAG, dl); 8022 8023 // Conversions to f128 are legal. 8024 if (EnableQuadPrecision && (Op.getValueType() == MVT::f128)) 8025 return Op; 8026 8027 if (Subtarget.hasQPX() && Op.getOperand(0).getValueType() == MVT::v4i1) { 8028 if (Op.getValueType() != MVT::v4f32 && Op.getValueType() != MVT::v4f64) 8029 return SDValue(); 8030 8031 SDValue Value = Op.getOperand(0); 8032 // The values are now known to be -1 (false) or 1 (true). To convert this 8033 // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5). 8034 // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5 8035 Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value); 8036 8037 SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64); 8038 8039 Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs); 8040 8041 if (Op.getValueType() != MVT::v4f64) 8042 Value = DAG.getNode(ISD::FP_ROUND, dl, 8043 Op.getValueType(), Value, 8044 DAG.getIntPtrConstant(1, dl)); 8045 return Value; 8046 } 8047 8048 // Don't handle ppc_fp128 here; let it be lowered to a libcall. 8049 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64) 8050 return SDValue(); 8051 8052 if (Op.getOperand(0).getValueType() == MVT::i1) 8053 return DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Op.getOperand(0), 8054 DAG.getConstantFP(1.0, dl, Op.getValueType()), 8055 DAG.getConstantFP(0.0, dl, Op.getValueType())); 8056 8057 // If we have direct moves, we can do all the conversion, skip the store/load 8058 // however, without FPCVT we can't do most conversions. 8059 if (Subtarget.hasDirectMove() && directMoveIsProfitable(Op) && 8060 Subtarget.isPPC64() && Subtarget.hasFPCVT()) 8061 return LowerINT_TO_FPDirectMove(Op, DAG, dl); 8062 8063 assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) && 8064 "UINT_TO_FP is supported only with FPCVT"); 8065 8066 // If we have FCFIDS, then use it when converting to single-precision. 8067 // Otherwise, convert to double-precision and then round. 8068 unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 8069 ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS 8070 : PPCISD::FCFIDS) 8071 : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU 8072 : PPCISD::FCFID); 8073 MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 8074 ? MVT::f32 8075 : MVT::f64; 8076 8077 if (Op.getOperand(0).getValueType() == MVT::i64) { 8078 SDValue SINT = Op.getOperand(0); 8079 // When converting to single-precision, we actually need to convert 8080 // to double-precision first and then round to single-precision. 8081 // To avoid double-rounding effects during that operation, we have 8082 // to prepare the input operand. Bits that might be truncated when 8083 // converting to double-precision are replaced by a bit that won't 8084 // be lost at this stage, but is below the single-precision rounding 8085 // position. 8086 // 8087 // However, if -enable-unsafe-fp-math is in effect, accept double 8088 // rounding to avoid the extra overhead. 8089 if (Op.getValueType() == MVT::f32 && 8090 !Subtarget.hasFPCVT() && 8091 !DAG.getTarget().Options.UnsafeFPMath) { 8092 8093 // Twiddle input to make sure the low 11 bits are zero. (If this 8094 // is the case, we are guaranteed the value will fit into the 53 bit 8095 // mantissa of an IEEE double-precision value without rounding.) 8096 // If any of those low 11 bits were not zero originally, make sure 8097 // bit 12 (value 2048) is set instead, so that the final rounding 8098 // to single-precision gets the correct result. 8099 SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64, 8100 SINT, DAG.getConstant(2047, dl, MVT::i64)); 8101 Round = DAG.getNode(ISD::ADD, dl, MVT::i64, 8102 Round, DAG.getConstant(2047, dl, MVT::i64)); 8103 Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT); 8104 Round = DAG.getNode(ISD::AND, dl, MVT::i64, 8105 Round, DAG.getConstant(-2048, dl, MVT::i64)); 8106 8107 // However, we cannot use that value unconditionally: if the magnitude 8108 // of the input value is small, the bit-twiddling we did above might 8109 // end up visibly changing the output. Fortunately, in that case, we 8110 // don't need to twiddle bits since the original input will convert 8111 // exactly to double-precision floating-point already. Therefore, 8112 // construct a conditional to use the original value if the top 11 8113 // bits are all sign-bit copies, and use the rounded value computed 8114 // above otherwise. 8115 SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64, 8116 SINT, DAG.getConstant(53, dl, MVT::i32)); 8117 Cond = DAG.getNode(ISD::ADD, dl, MVT::i64, 8118 Cond, DAG.getConstant(1, dl, MVT::i64)); 8119 Cond = DAG.getSetCC(dl, MVT::i32, 8120 Cond, DAG.getConstant(1, dl, MVT::i64), ISD::SETUGT); 8121 8122 SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT); 8123 } 8124 8125 ReuseLoadInfo RLI; 8126 SDValue Bits; 8127 8128 MachineFunction &MF = DAG.getMachineFunction(); 8129 if (canReuseLoadAddress(SINT, MVT::i64, RLI, DAG)) { 8130 Bits = DAG.getLoad(MVT::f64, dl, RLI.Chain, RLI.Ptr, RLI.MPI, 8131 RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges); 8132 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG); 8133 } else if (Subtarget.hasLFIWAX() && 8134 canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::SEXTLOAD)) { 8135 MachineMemOperand *MMO = 8136 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 8137 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 8138 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 8139 Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWAX, dl, 8140 DAG.getVTList(MVT::f64, MVT::Other), 8141 Ops, MVT::i32, MMO); 8142 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG); 8143 } else if (Subtarget.hasFPCVT() && 8144 canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::ZEXTLOAD)) { 8145 MachineMemOperand *MMO = 8146 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 8147 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 8148 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 8149 Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWZX, dl, 8150 DAG.getVTList(MVT::f64, MVT::Other), 8151 Ops, MVT::i32, MMO); 8152 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG); 8153 } else if (((Subtarget.hasLFIWAX() && 8154 SINT.getOpcode() == ISD::SIGN_EXTEND) || 8155 (Subtarget.hasFPCVT() && 8156 SINT.getOpcode() == ISD::ZERO_EXTEND)) && 8157 SINT.getOperand(0).getValueType() == MVT::i32) { 8158 MachineFrameInfo &MFI = MF.getFrameInfo(); 8159 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 8160 8161 int FrameIdx = MFI.CreateStackObject(4, 4, false); 8162 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 8163 8164 SDValue Store = 8165 DAG.getStore(DAG.getEntryNode(), dl, SINT.getOperand(0), FIdx, 8166 MachinePointerInfo::getFixedStack( 8167 DAG.getMachineFunction(), FrameIdx)); 8168 8169 assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 && 8170 "Expected an i32 store"); 8171 8172 RLI.Ptr = FIdx; 8173 RLI.Chain = Store; 8174 RLI.MPI = 8175 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 8176 RLI.Alignment = 4; 8177 8178 MachineMemOperand *MMO = 8179 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 8180 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 8181 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 8182 Bits = DAG.getMemIntrinsicNode(SINT.getOpcode() == ISD::ZERO_EXTEND ? 8183 PPCISD::LFIWZX : PPCISD::LFIWAX, 8184 dl, DAG.getVTList(MVT::f64, MVT::Other), 8185 Ops, MVT::i32, MMO); 8186 } else 8187 Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT); 8188 8189 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Bits); 8190 8191 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) 8192 FP = DAG.getNode(ISD::FP_ROUND, dl, 8193 MVT::f32, FP, DAG.getIntPtrConstant(0, dl)); 8194 return FP; 8195 } 8196 8197 assert(Op.getOperand(0).getValueType() == MVT::i32 && 8198 "Unhandled INT_TO_FP type in custom expander!"); 8199 // Since we only generate this in 64-bit mode, we can take advantage of 8200 // 64-bit registers. In particular, sign extend the input value into the 8201 // 64-bit register with extsw, store the WHOLE 64-bit value into the stack 8202 // then lfd it and fcfid it. 8203 MachineFunction &MF = DAG.getMachineFunction(); 8204 MachineFrameInfo &MFI = MF.getFrameInfo(); 8205 EVT PtrVT = getPointerTy(MF.getDataLayout()); 8206 8207 SDValue Ld; 8208 if (Subtarget.hasLFIWAX() || Subtarget.hasFPCVT()) { 8209 ReuseLoadInfo RLI; 8210 bool ReusingLoad; 8211 if (!(ReusingLoad = canReuseLoadAddress(Op.getOperand(0), MVT::i32, RLI, 8212 DAG))) { 8213 int FrameIdx = MFI.CreateStackObject(4, 4, false); 8214 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 8215 8216 SDValue Store = 8217 DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx, 8218 MachinePointerInfo::getFixedStack( 8219 DAG.getMachineFunction(), FrameIdx)); 8220 8221 assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 && 8222 "Expected an i32 store"); 8223 8224 RLI.Ptr = FIdx; 8225 RLI.Chain = Store; 8226 RLI.MPI = 8227 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 8228 RLI.Alignment = 4; 8229 } 8230 8231 MachineMemOperand *MMO = 8232 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 8233 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 8234 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 8235 Ld = DAG.getMemIntrinsicNode(Op.getOpcode() == ISD::UINT_TO_FP ? 8236 PPCISD::LFIWZX : PPCISD::LFIWAX, 8237 dl, DAG.getVTList(MVT::f64, MVT::Other), 8238 Ops, MVT::i32, MMO); 8239 if (ReusingLoad) 8240 spliceIntoChain(RLI.ResChain, Ld.getValue(1), DAG); 8241 } else { 8242 assert(Subtarget.isPPC64() && 8243 "i32->FP without LFIWAX supported only on PPC64"); 8244 8245 int FrameIdx = MFI.CreateStackObject(8, 8, false); 8246 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 8247 8248 SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64, 8249 Op.getOperand(0)); 8250 8251 // STD the extended value into the stack slot. 8252 SDValue Store = DAG.getStore( 8253 DAG.getEntryNode(), dl, Ext64, FIdx, 8254 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx)); 8255 8256 // Load the value as a double. 8257 Ld = DAG.getLoad( 8258 MVT::f64, dl, Store, FIdx, 8259 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx)); 8260 } 8261 8262 // FCFID it and return it. 8263 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Ld); 8264 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) 8265 FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP, 8266 DAG.getIntPtrConstant(0, dl)); 8267 return FP; 8268 } 8269 8270 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op, 8271 SelectionDAG &DAG) const { 8272 SDLoc dl(Op); 8273 /* 8274 The rounding mode is in bits 30:31 of FPSR, and has the following 8275 settings: 8276 00 Round to nearest 8277 01 Round to 0 8278 10 Round to +inf 8279 11 Round to -inf 8280 8281 FLT_ROUNDS, on the other hand, expects the following: 8282 -1 Undefined 8283 0 Round to 0 8284 1 Round to nearest 8285 2 Round to +inf 8286 3 Round to -inf 8287 8288 To perform the conversion, we do: 8289 ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1)) 8290 */ 8291 8292 MachineFunction &MF = DAG.getMachineFunction(); 8293 EVT VT = Op.getValueType(); 8294 EVT PtrVT = getPointerTy(MF.getDataLayout()); 8295 8296 // Save FP Control Word to register 8297 SDValue Chain = Op.getOperand(0); 8298 SDValue MFFS = DAG.getNode(PPCISD::MFFS, dl, {MVT::f64, MVT::Other}, Chain); 8299 Chain = MFFS.getValue(1); 8300 8301 // Save FP register to stack slot 8302 int SSFI = MF.getFrameInfo().CreateStackObject(8, 8, false); 8303 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT); 8304 Chain = DAG.getStore(Chain, dl, MFFS, StackSlot, MachinePointerInfo()); 8305 8306 // Load FP Control Word from low 32 bits of stack slot. 8307 SDValue Four = DAG.getConstant(4, dl, PtrVT); 8308 SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four); 8309 SDValue CWD = DAG.getLoad(MVT::i32, dl, Chain, Addr, MachinePointerInfo()); 8310 Chain = CWD.getValue(1); 8311 8312 // Transform as necessary 8313 SDValue CWD1 = 8314 DAG.getNode(ISD::AND, dl, MVT::i32, 8315 CWD, DAG.getConstant(3, dl, MVT::i32)); 8316 SDValue CWD2 = 8317 DAG.getNode(ISD::SRL, dl, MVT::i32, 8318 DAG.getNode(ISD::AND, dl, MVT::i32, 8319 DAG.getNode(ISD::XOR, dl, MVT::i32, 8320 CWD, DAG.getConstant(3, dl, MVT::i32)), 8321 DAG.getConstant(3, dl, MVT::i32)), 8322 DAG.getConstant(1, dl, MVT::i32)); 8323 8324 SDValue RetVal = 8325 DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2); 8326 8327 RetVal = 8328 DAG.getNode((VT.getSizeInBits() < 16 ? ISD::TRUNCATE : ISD::ZERO_EXTEND), 8329 dl, VT, RetVal); 8330 8331 return DAG.getMergeValues({RetVal, Chain}, dl); 8332 } 8333 8334 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const { 8335 EVT VT = Op.getValueType(); 8336 unsigned BitWidth = VT.getSizeInBits(); 8337 SDLoc dl(Op); 8338 assert(Op.getNumOperands() == 3 && 8339 VT == Op.getOperand(1).getValueType() && 8340 "Unexpected SHL!"); 8341 8342 // Expand into a bunch of logical ops. Note that these ops 8343 // depend on the PPC behavior for oversized shift amounts. 8344 SDValue Lo = Op.getOperand(0); 8345 SDValue Hi = Op.getOperand(1); 8346 SDValue Amt = Op.getOperand(2); 8347 EVT AmtVT = Amt.getValueType(); 8348 8349 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, 8350 DAG.getConstant(BitWidth, dl, AmtVT), Amt); 8351 SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt); 8352 SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1); 8353 SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3); 8354 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, 8355 DAG.getConstant(-BitWidth, dl, AmtVT)); 8356 SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5); 8357 SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6); 8358 SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt); 8359 SDValue OutOps[] = { OutLo, OutHi }; 8360 return DAG.getMergeValues(OutOps, dl); 8361 } 8362 8363 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const { 8364 EVT VT = Op.getValueType(); 8365 SDLoc dl(Op); 8366 unsigned BitWidth = VT.getSizeInBits(); 8367 assert(Op.getNumOperands() == 3 && 8368 VT == Op.getOperand(1).getValueType() && 8369 "Unexpected SRL!"); 8370 8371 // Expand into a bunch of logical ops. Note that these ops 8372 // depend on the PPC behavior for oversized shift amounts. 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::SRL, dl, VT, Hi, Tmp5); 8386 SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6); 8387 SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt); 8388 SDValue OutOps[] = { OutLo, OutHi }; 8389 return DAG.getMergeValues(OutOps, dl); 8390 } 8391 8392 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const { 8393 SDLoc dl(Op); 8394 EVT VT = Op.getValueType(); 8395 unsigned BitWidth = VT.getSizeInBits(); 8396 assert(Op.getNumOperands() == 3 && 8397 VT == Op.getOperand(1).getValueType() && 8398 "Unexpected SRA!"); 8399 8400 // Expand into a bunch of logical ops, followed by a select_cc. 8401 SDValue Lo = Op.getOperand(0); 8402 SDValue Hi = Op.getOperand(1); 8403 SDValue Amt = Op.getOperand(2); 8404 EVT AmtVT = Amt.getValueType(); 8405 8406 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, 8407 DAG.getConstant(BitWidth, dl, AmtVT), Amt); 8408 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt); 8409 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1); 8410 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3); 8411 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, 8412 DAG.getConstant(-BitWidth, dl, AmtVT)); 8413 SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5); 8414 SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt); 8415 SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, dl, AmtVT), 8416 Tmp4, Tmp6, ISD::SETLE); 8417 SDValue OutOps[] = { OutLo, OutHi }; 8418 return DAG.getMergeValues(OutOps, dl); 8419 } 8420 8421 //===----------------------------------------------------------------------===// 8422 // Vector related lowering. 8423 // 8424 8425 /// BuildSplatI - Build a canonical splati of Val with an element size of 8426 /// SplatSize. Cast the result to VT. 8427 static SDValue BuildSplatI(int Val, unsigned SplatSize, EVT VT, 8428 SelectionDAG &DAG, const SDLoc &dl) { 8429 static const MVT VTys[] = { // canonical VT to use for each size. 8430 MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32 8431 }; 8432 8433 EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1]; 8434 8435 // Force vspltis[hw] -1 to vspltisb -1 to canonicalize. 8436 if (Val == -1) 8437 SplatSize = 1; 8438 8439 EVT CanonicalVT = VTys[SplatSize-1]; 8440 8441 // Build a canonical splat for this value. 8442 return DAG.getBitcast(ReqVT, DAG.getConstant(Val, dl, CanonicalVT)); 8443 } 8444 8445 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the 8446 /// specified intrinsic ID. 8447 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op, SelectionDAG &DAG, 8448 const SDLoc &dl, EVT DestVT = MVT::Other) { 8449 if (DestVT == MVT::Other) DestVT = Op.getValueType(); 8450 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 8451 DAG.getConstant(IID, dl, MVT::i32), Op); 8452 } 8453 8454 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the 8455 /// specified intrinsic ID. 8456 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS, 8457 SelectionDAG &DAG, const SDLoc &dl, 8458 EVT DestVT = MVT::Other) { 8459 if (DestVT == MVT::Other) DestVT = LHS.getValueType(); 8460 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 8461 DAG.getConstant(IID, dl, MVT::i32), LHS, RHS); 8462 } 8463 8464 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the 8465 /// specified intrinsic ID. 8466 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1, 8467 SDValue Op2, SelectionDAG &DAG, const SDLoc &dl, 8468 EVT DestVT = MVT::Other) { 8469 if (DestVT == MVT::Other) DestVT = Op0.getValueType(); 8470 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 8471 DAG.getConstant(IID, dl, MVT::i32), Op0, Op1, Op2); 8472 } 8473 8474 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified 8475 /// amount. The result has the specified value type. 8476 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt, EVT VT, 8477 SelectionDAG &DAG, const SDLoc &dl) { 8478 // Force LHS/RHS to be the right type. 8479 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS); 8480 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS); 8481 8482 int Ops[16]; 8483 for (unsigned i = 0; i != 16; ++i) 8484 Ops[i] = i + Amt; 8485 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops); 8486 return DAG.getNode(ISD::BITCAST, dl, VT, T); 8487 } 8488 8489 /// Do we have an efficient pattern in a .td file for this node? 8490 /// 8491 /// \param V - pointer to the BuildVectorSDNode being matched 8492 /// \param HasDirectMove - does this subtarget have VSR <-> GPR direct moves? 8493 /// 8494 /// There are some patterns where it is beneficial to keep a BUILD_VECTOR 8495 /// node as a BUILD_VECTOR node rather than expanding it. The patterns where 8496 /// the opposite is true (expansion is beneficial) are: 8497 /// - The node builds a vector out of integers that are not 32 or 64-bits 8498 /// - The node builds a vector out of constants 8499 /// - The node is a "load-and-splat" 8500 /// In all other cases, we will choose to keep the BUILD_VECTOR. 8501 static bool haveEfficientBuildVectorPattern(BuildVectorSDNode *V, 8502 bool HasDirectMove, 8503 bool HasP8Vector) { 8504 EVT VecVT = V->getValueType(0); 8505 bool RightType = VecVT == MVT::v2f64 || 8506 (HasP8Vector && VecVT == MVT::v4f32) || 8507 (HasDirectMove && (VecVT == MVT::v2i64 || VecVT == MVT::v4i32)); 8508 if (!RightType) 8509 return false; 8510 8511 bool IsSplat = true; 8512 bool IsLoad = false; 8513 SDValue Op0 = V->getOperand(0); 8514 8515 // This function is called in a block that confirms the node is not a constant 8516 // splat. So a constant BUILD_VECTOR here means the vector is built out of 8517 // different constants. 8518 if (V->isConstant()) 8519 return false; 8520 for (int i = 0, e = V->getNumOperands(); i < e; ++i) { 8521 if (V->getOperand(i).isUndef()) 8522 return false; 8523 // We want to expand nodes that represent load-and-splat even if the 8524 // loaded value is a floating point truncation or conversion to int. 8525 if (V->getOperand(i).getOpcode() == ISD::LOAD || 8526 (V->getOperand(i).getOpcode() == ISD::FP_ROUND && 8527 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) || 8528 (V->getOperand(i).getOpcode() == ISD::FP_TO_SINT && 8529 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) || 8530 (V->getOperand(i).getOpcode() == ISD::FP_TO_UINT && 8531 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD)) 8532 IsLoad = true; 8533 // If the operands are different or the input is not a load and has more 8534 // uses than just this BV node, then it isn't a splat. 8535 if (V->getOperand(i) != Op0 || 8536 (!IsLoad && !V->isOnlyUserOf(V->getOperand(i).getNode()))) 8537 IsSplat = false; 8538 } 8539 return !(IsSplat && IsLoad); 8540 } 8541 8542 // Lower BITCAST(f128, (build_pair i64, i64)) to BUILD_FP128. 8543 SDValue PPCTargetLowering::LowerBITCAST(SDValue Op, SelectionDAG &DAG) const { 8544 8545 SDLoc dl(Op); 8546 SDValue Op0 = Op->getOperand(0); 8547 8548 if (!EnableQuadPrecision || 8549 (Op.getValueType() != MVT::f128 ) || 8550 (Op0.getOpcode() != ISD::BUILD_PAIR) || 8551 (Op0.getOperand(0).getValueType() != MVT::i64) || 8552 (Op0.getOperand(1).getValueType() != MVT::i64)) 8553 return SDValue(); 8554 8555 return DAG.getNode(PPCISD::BUILD_FP128, dl, MVT::f128, Op0.getOperand(0), 8556 Op0.getOperand(1)); 8557 } 8558 8559 static const SDValue *getNormalLoadInput(const SDValue &Op) { 8560 const SDValue *InputLoad = &Op; 8561 if (InputLoad->getOpcode() == ISD::BITCAST) 8562 InputLoad = &InputLoad->getOperand(0); 8563 if (InputLoad->getOpcode() == ISD::SCALAR_TO_VECTOR) 8564 InputLoad = &InputLoad->getOperand(0); 8565 if (InputLoad->getOpcode() != ISD::LOAD) 8566 return nullptr; 8567 LoadSDNode *LD = cast<LoadSDNode>(*InputLoad); 8568 return ISD::isNormalLoad(LD) ? InputLoad : nullptr; 8569 } 8570 8571 // If this is a case we can't handle, return null and let the default 8572 // expansion code take care of it. If we CAN select this case, and if it 8573 // selects to a single instruction, return Op. Otherwise, if we can codegen 8574 // this case more efficiently than a constant pool load, lower it to the 8575 // sequence of ops that should be used. 8576 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op, 8577 SelectionDAG &DAG) const { 8578 SDLoc dl(Op); 8579 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode()); 8580 assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR"); 8581 8582 if (Subtarget.hasQPX() && Op.getValueType() == MVT::v4i1) { 8583 // We first build an i32 vector, load it into a QPX register, 8584 // then convert it to a floating-point vector and compare it 8585 // to a zero vector to get the boolean result. 8586 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 8587 int FrameIdx = MFI.CreateStackObject(16, 16, false); 8588 MachinePointerInfo PtrInfo = 8589 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 8590 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 8591 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 8592 8593 assert(BVN->getNumOperands() == 4 && 8594 "BUILD_VECTOR for v4i1 does not have 4 operands"); 8595 8596 bool IsConst = true; 8597 for (unsigned i = 0; i < 4; ++i) { 8598 if (BVN->getOperand(i).isUndef()) continue; 8599 if (!isa<ConstantSDNode>(BVN->getOperand(i))) { 8600 IsConst = false; 8601 break; 8602 } 8603 } 8604 8605 if (IsConst) { 8606 Constant *One = 8607 ConstantFP::get(Type::getFloatTy(*DAG.getContext()), 1.0); 8608 Constant *NegOne = 8609 ConstantFP::get(Type::getFloatTy(*DAG.getContext()), -1.0); 8610 8611 Constant *CV[4]; 8612 for (unsigned i = 0; i < 4; ++i) { 8613 if (BVN->getOperand(i).isUndef()) 8614 CV[i] = UndefValue::get(Type::getFloatTy(*DAG.getContext())); 8615 else if (isNullConstant(BVN->getOperand(i))) 8616 CV[i] = NegOne; 8617 else 8618 CV[i] = One; 8619 } 8620 8621 Constant *CP = ConstantVector::get(CV); 8622 SDValue CPIdx = DAG.getConstantPool(CP, getPointerTy(DAG.getDataLayout()), 8623 16 /* alignment */); 8624 8625 SDValue Ops[] = {DAG.getEntryNode(), CPIdx}; 8626 SDVTList VTs = DAG.getVTList({MVT::v4i1, /*chain*/ MVT::Other}); 8627 return DAG.getMemIntrinsicNode( 8628 PPCISD::QVLFSb, dl, VTs, Ops, MVT::v4f32, 8629 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 8630 } 8631 8632 SmallVector<SDValue, 4> Stores; 8633 for (unsigned i = 0; i < 4; ++i) { 8634 if (BVN->getOperand(i).isUndef()) continue; 8635 8636 unsigned Offset = 4*i; 8637 SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType()); 8638 Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx); 8639 8640 unsigned StoreSize = BVN->getOperand(i).getValueType().getStoreSize(); 8641 if (StoreSize > 4) { 8642 Stores.push_back( 8643 DAG.getTruncStore(DAG.getEntryNode(), dl, BVN->getOperand(i), Idx, 8644 PtrInfo.getWithOffset(Offset), MVT::i32)); 8645 } else { 8646 SDValue StoreValue = BVN->getOperand(i); 8647 if (StoreSize < 4) 8648 StoreValue = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, StoreValue); 8649 8650 Stores.push_back(DAG.getStore(DAG.getEntryNode(), dl, StoreValue, Idx, 8651 PtrInfo.getWithOffset(Offset))); 8652 } 8653 } 8654 8655 SDValue StoreChain; 8656 if (!Stores.empty()) 8657 StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores); 8658 else 8659 StoreChain = DAG.getEntryNode(); 8660 8661 // Now load from v4i32 into the QPX register; this will extend it to 8662 // v4i64 but not yet convert it to a floating point. Nevertheless, this 8663 // is typed as v4f64 because the QPX register integer states are not 8664 // explicitly represented. 8665 8666 SDValue Ops[] = {StoreChain, 8667 DAG.getConstant(Intrinsic::ppc_qpx_qvlfiwz, dl, MVT::i32), 8668 FIdx}; 8669 SDVTList VTs = DAG.getVTList({MVT::v4f64, /*chain*/ MVT::Other}); 8670 8671 SDValue LoadedVect = DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, 8672 dl, VTs, Ops, MVT::v4i32, PtrInfo); 8673 LoadedVect = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64, 8674 DAG.getConstant(Intrinsic::ppc_qpx_qvfcfidu, dl, MVT::i32), 8675 LoadedVect); 8676 8677 SDValue FPZeros = DAG.getConstantFP(0.0, dl, MVT::v4f64); 8678 8679 return DAG.getSetCC(dl, MVT::v4i1, LoadedVect, FPZeros, ISD::SETEQ); 8680 } 8681 8682 // All other QPX vectors are handled by generic code. 8683 if (Subtarget.hasQPX()) 8684 return SDValue(); 8685 8686 // Check if this is a splat of a constant value. 8687 APInt APSplatBits, APSplatUndef; 8688 unsigned SplatBitSize; 8689 bool HasAnyUndefs; 8690 if (! BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize, 8691 HasAnyUndefs, 0, !Subtarget.isLittleEndian()) || 8692 SplatBitSize > 32) { 8693 8694 const SDValue *InputLoad = getNormalLoadInput(Op.getOperand(0)); 8695 // Handle load-and-splat patterns as we have instructions that will do this 8696 // in one go. 8697 if (InputLoad && DAG.isSplatValue(Op, true)) { 8698 LoadSDNode *LD = cast<LoadSDNode>(*InputLoad); 8699 8700 // We have handling for 4 and 8 byte elements. 8701 unsigned ElementSize = LD->getMemoryVT().getScalarSizeInBits(); 8702 8703 // Checking for a single use of this load, we have to check for vector 8704 // width (128 bits) / ElementSize uses (since each operand of the 8705 // BUILD_VECTOR is a separate use of the value. 8706 if (InputLoad->getNode()->hasNUsesOfValue(128 / ElementSize, 0) && 8707 ((Subtarget.hasVSX() && ElementSize == 64) || 8708 (Subtarget.hasP9Vector() && ElementSize == 32))) { 8709 SDValue Ops[] = { 8710 LD->getChain(), // Chain 8711 LD->getBasePtr(), // Ptr 8712 DAG.getValueType(Op.getValueType()) // VT 8713 }; 8714 return 8715 DAG.getMemIntrinsicNode(PPCISD::LD_SPLAT, dl, 8716 DAG.getVTList(Op.getValueType(), MVT::Other), 8717 Ops, LD->getMemoryVT(), LD->getMemOperand()); 8718 } 8719 } 8720 8721 // BUILD_VECTOR nodes that are not constant splats of up to 32-bits can be 8722 // lowered to VSX instructions under certain conditions. 8723 // Without VSX, there is no pattern more efficient than expanding the node. 8724 if (Subtarget.hasVSX() && 8725 haveEfficientBuildVectorPattern(BVN, Subtarget.hasDirectMove(), 8726 Subtarget.hasP8Vector())) 8727 return Op; 8728 return SDValue(); 8729 } 8730 8731 unsigned SplatBits = APSplatBits.getZExtValue(); 8732 unsigned SplatUndef = APSplatUndef.getZExtValue(); 8733 unsigned SplatSize = SplatBitSize / 8; 8734 8735 // First, handle single instruction cases. 8736 8737 // All zeros? 8738 if (SplatBits == 0) { 8739 // Canonicalize all zero vectors to be v4i32. 8740 if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) { 8741 SDValue Z = DAG.getConstant(0, dl, MVT::v4i32); 8742 Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z); 8743 } 8744 return Op; 8745 } 8746 8747 // We have XXSPLTIB for constant splats one byte wide 8748 // FIXME: SplatBits is an unsigned int being cast to an int while passing it 8749 // as an argument to BuildSplatiI. Given SplatSize == 1 it is okay here. 8750 if (Subtarget.hasP9Vector() && SplatSize == 1) 8751 return BuildSplatI(SplatBits, SplatSize, Op.getValueType(), DAG, dl); 8752 8753 // If the sign extended value is in the range [-16,15], use VSPLTI[bhw]. 8754 int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >> 8755 (32-SplatBitSize)); 8756 if (SextVal >= -16 && SextVal <= 15) 8757 return BuildSplatI(SextVal, SplatSize, Op.getValueType(), DAG, dl); 8758 8759 // Two instruction sequences. 8760 8761 // If this value is in the range [-32,30] and is even, use: 8762 // VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2) 8763 // If this value is in the range [17,31] and is odd, use: 8764 // VSPLTI[bhw](val-16) - VSPLTI[bhw](-16) 8765 // If this value is in the range [-31,-17] and is odd, use: 8766 // VSPLTI[bhw](val+16) + VSPLTI[bhw](-16) 8767 // Note the last two are three-instruction sequences. 8768 if (SextVal >= -32 && SextVal <= 31) { 8769 // To avoid having these optimizations undone by constant folding, 8770 // we convert to a pseudo that will be expanded later into one of 8771 // the above forms. 8772 SDValue Elt = DAG.getConstant(SextVal, dl, MVT::i32); 8773 EVT VT = (SplatSize == 1 ? MVT::v16i8 : 8774 (SplatSize == 2 ? MVT::v8i16 : MVT::v4i32)); 8775 SDValue EltSize = DAG.getConstant(SplatSize, dl, MVT::i32); 8776 SDValue RetVal = DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize); 8777 if (VT == Op.getValueType()) 8778 return RetVal; 8779 else 8780 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), RetVal); 8781 } 8782 8783 // If this is 0x8000_0000 x 4, turn into vspltisw + vslw. If it is 8784 // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000). This is important 8785 // for fneg/fabs. 8786 if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) { 8787 // Make -1 and vspltisw -1: 8788 SDValue OnesV = BuildSplatI(-1, 4, MVT::v4i32, DAG, dl); 8789 8790 // Make the VSLW intrinsic, computing 0x8000_0000. 8791 SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV, 8792 OnesV, DAG, dl); 8793 8794 // xor by OnesV to invert it. 8795 Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV); 8796 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 8797 } 8798 8799 // Check to see if this is a wide variety of vsplti*, binop self cases. 8800 static const signed char SplatCsts[] = { 8801 -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7, 8802 -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16 8803 }; 8804 8805 for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) { 8806 // Indirect through the SplatCsts array so that we favor 'vsplti -1' for 8807 // cases which are ambiguous (e.g. formation of 0x8000_0000). 'vsplti -1' 8808 int i = SplatCsts[idx]; 8809 8810 // Figure out what shift amount will be used by altivec if shifted by i in 8811 // this splat size. 8812 unsigned TypeShiftAmt = i & (SplatBitSize-1); 8813 8814 // vsplti + shl self. 8815 if (SextVal == (int)((unsigned)i << TypeShiftAmt)) { 8816 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl); 8817 static const unsigned IIDs[] = { // Intrinsic to use for each size. 8818 Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0, 8819 Intrinsic::ppc_altivec_vslw 8820 }; 8821 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 8822 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 8823 } 8824 8825 // vsplti + srl self. 8826 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) { 8827 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl); 8828 static const unsigned IIDs[] = { // Intrinsic to use for each size. 8829 Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0, 8830 Intrinsic::ppc_altivec_vsrw 8831 }; 8832 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 8833 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 8834 } 8835 8836 // vsplti + sra self. 8837 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) { 8838 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl); 8839 static const unsigned IIDs[] = { // Intrinsic to use for each size. 8840 Intrinsic::ppc_altivec_vsrab, Intrinsic::ppc_altivec_vsrah, 0, 8841 Intrinsic::ppc_altivec_vsraw 8842 }; 8843 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 8844 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 8845 } 8846 8847 // vsplti + rol self. 8848 if (SextVal == (int)(((unsigned)i << TypeShiftAmt) | 8849 ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) { 8850 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl); 8851 static const unsigned IIDs[] = { // Intrinsic to use for each size. 8852 Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0, 8853 Intrinsic::ppc_altivec_vrlw 8854 }; 8855 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 8856 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 8857 } 8858 8859 // t = vsplti c, result = vsldoi t, t, 1 8860 if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) { 8861 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl); 8862 unsigned Amt = Subtarget.isLittleEndian() ? 15 : 1; 8863 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl); 8864 } 8865 // t = vsplti c, result = vsldoi t, t, 2 8866 if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) { 8867 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl); 8868 unsigned Amt = Subtarget.isLittleEndian() ? 14 : 2; 8869 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl); 8870 } 8871 // t = vsplti c, result = vsldoi t, t, 3 8872 if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) { 8873 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl); 8874 unsigned Amt = Subtarget.isLittleEndian() ? 13 : 3; 8875 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl); 8876 } 8877 } 8878 8879 return SDValue(); 8880 } 8881 8882 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit 8883 /// the specified operations to build the shuffle. 8884 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS, 8885 SDValue RHS, SelectionDAG &DAG, 8886 const SDLoc &dl) { 8887 unsigned OpNum = (PFEntry >> 26) & 0x0F; 8888 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1); 8889 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1); 8890 8891 enum { 8892 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3> 8893 OP_VMRGHW, 8894 OP_VMRGLW, 8895 OP_VSPLTISW0, 8896 OP_VSPLTISW1, 8897 OP_VSPLTISW2, 8898 OP_VSPLTISW3, 8899 OP_VSLDOI4, 8900 OP_VSLDOI8, 8901 OP_VSLDOI12 8902 }; 8903 8904 if (OpNum == OP_COPY) { 8905 if (LHSID == (1*9+2)*9+3) return LHS; 8906 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!"); 8907 return RHS; 8908 } 8909 8910 SDValue OpLHS, OpRHS; 8911 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl); 8912 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl); 8913 8914 int ShufIdxs[16]; 8915 switch (OpNum) { 8916 default: llvm_unreachable("Unknown i32 permute!"); 8917 case OP_VMRGHW: 8918 ShufIdxs[ 0] = 0; ShufIdxs[ 1] = 1; ShufIdxs[ 2] = 2; ShufIdxs[ 3] = 3; 8919 ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19; 8920 ShufIdxs[ 8] = 4; ShufIdxs[ 9] = 5; ShufIdxs[10] = 6; ShufIdxs[11] = 7; 8921 ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23; 8922 break; 8923 case OP_VMRGLW: 8924 ShufIdxs[ 0] = 8; ShufIdxs[ 1] = 9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11; 8925 ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27; 8926 ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15; 8927 ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31; 8928 break; 8929 case OP_VSPLTISW0: 8930 for (unsigned i = 0; i != 16; ++i) 8931 ShufIdxs[i] = (i&3)+0; 8932 break; 8933 case OP_VSPLTISW1: 8934 for (unsigned i = 0; i != 16; ++i) 8935 ShufIdxs[i] = (i&3)+4; 8936 break; 8937 case OP_VSPLTISW2: 8938 for (unsigned i = 0; i != 16; ++i) 8939 ShufIdxs[i] = (i&3)+8; 8940 break; 8941 case OP_VSPLTISW3: 8942 for (unsigned i = 0; i != 16; ++i) 8943 ShufIdxs[i] = (i&3)+12; 8944 break; 8945 case OP_VSLDOI4: 8946 return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl); 8947 case OP_VSLDOI8: 8948 return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl); 8949 case OP_VSLDOI12: 8950 return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl); 8951 } 8952 EVT VT = OpLHS.getValueType(); 8953 OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS); 8954 OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS); 8955 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs); 8956 return DAG.getNode(ISD::BITCAST, dl, VT, T); 8957 } 8958 8959 /// lowerToVINSERTB - Return the SDValue if this VECTOR_SHUFFLE can be handled 8960 /// by the VINSERTB instruction introduced in ISA 3.0, else just return default 8961 /// SDValue. 8962 SDValue PPCTargetLowering::lowerToVINSERTB(ShuffleVectorSDNode *N, 8963 SelectionDAG &DAG) const { 8964 const unsigned BytesInVector = 16; 8965 bool IsLE = Subtarget.isLittleEndian(); 8966 SDLoc dl(N); 8967 SDValue V1 = N->getOperand(0); 8968 SDValue V2 = N->getOperand(1); 8969 unsigned ShiftElts = 0, InsertAtByte = 0; 8970 bool Swap = false; 8971 8972 // Shifts required to get the byte we want at element 7. 8973 unsigned LittleEndianShifts[] = {8, 7, 6, 5, 4, 3, 2, 1, 8974 0, 15, 14, 13, 12, 11, 10, 9}; 8975 unsigned BigEndianShifts[] = {9, 10, 11, 12, 13, 14, 15, 0, 8976 1, 2, 3, 4, 5, 6, 7, 8}; 8977 8978 ArrayRef<int> Mask = N->getMask(); 8979 int OriginalOrder[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}; 8980 8981 // For each mask element, find out if we're just inserting something 8982 // from V2 into V1 or vice versa. 8983 // Possible permutations inserting an element from V2 into V1: 8984 // X, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 8985 // 0, X, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 8986 // ... 8987 // 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, X 8988 // Inserting from V1 into V2 will be similar, except mask range will be 8989 // [16,31]. 8990 8991 bool FoundCandidate = false; 8992 // If both vector operands for the shuffle are the same vector, the mask 8993 // will contain only elements from the first one and the second one will be 8994 // undef. 8995 unsigned VINSERTBSrcElem = IsLE ? 8 : 7; 8996 // Go through the mask of half-words to find an element that's being moved 8997 // from one vector to the other. 8998 for (unsigned i = 0; i < BytesInVector; ++i) { 8999 unsigned CurrentElement = Mask[i]; 9000 // If 2nd operand is undefined, we should only look for element 7 in the 9001 // Mask. 9002 if (V2.isUndef() && CurrentElement != VINSERTBSrcElem) 9003 continue; 9004 9005 bool OtherElementsInOrder = true; 9006 // Examine the other elements in the Mask to see if they're in original 9007 // order. 9008 for (unsigned j = 0; j < BytesInVector; ++j) { 9009 if (j == i) 9010 continue; 9011 // If CurrentElement is from V1 [0,15], then we the rest of the Mask to be 9012 // from V2 [16,31] and vice versa. Unless the 2nd operand is undefined, 9013 // in which we always assume we're always picking from the 1st operand. 9014 int MaskOffset = 9015 (!V2.isUndef() && CurrentElement < BytesInVector) ? BytesInVector : 0; 9016 if (Mask[j] != OriginalOrder[j] + MaskOffset) { 9017 OtherElementsInOrder = false; 9018 break; 9019 } 9020 } 9021 // If other elements are in original order, we record the number of shifts 9022 // we need to get the element we want into element 7. Also record which byte 9023 // in the vector we should insert into. 9024 if (OtherElementsInOrder) { 9025 // If 2nd operand is undefined, we assume no shifts and no swapping. 9026 if (V2.isUndef()) { 9027 ShiftElts = 0; 9028 Swap = false; 9029 } else { 9030 // Only need the last 4-bits for shifts because operands will be swapped if CurrentElement is >= 2^4. 9031 ShiftElts = IsLE ? LittleEndianShifts[CurrentElement & 0xF] 9032 : BigEndianShifts[CurrentElement & 0xF]; 9033 Swap = CurrentElement < BytesInVector; 9034 } 9035 InsertAtByte = IsLE ? BytesInVector - (i + 1) : i; 9036 FoundCandidate = true; 9037 break; 9038 } 9039 } 9040 9041 if (!FoundCandidate) 9042 return SDValue(); 9043 9044 // Candidate found, construct the proper SDAG sequence with VINSERTB, 9045 // optionally with VECSHL if shift is required. 9046 if (Swap) 9047 std::swap(V1, V2); 9048 if (V2.isUndef()) 9049 V2 = V1; 9050 if (ShiftElts) { 9051 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2, 9052 DAG.getConstant(ShiftElts, dl, MVT::i32)); 9053 return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, Shl, 9054 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9055 } 9056 return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, V2, 9057 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9058 } 9059 9060 /// lowerToVINSERTH - Return the SDValue if this VECTOR_SHUFFLE can be handled 9061 /// by the VINSERTH instruction introduced in ISA 3.0, else just return default 9062 /// SDValue. 9063 SDValue PPCTargetLowering::lowerToVINSERTH(ShuffleVectorSDNode *N, 9064 SelectionDAG &DAG) const { 9065 const unsigned NumHalfWords = 8; 9066 const unsigned BytesInVector = NumHalfWords * 2; 9067 // Check that the shuffle is on half-words. 9068 if (!isNByteElemShuffleMask(N, 2, 1)) 9069 return SDValue(); 9070 9071 bool IsLE = Subtarget.isLittleEndian(); 9072 SDLoc dl(N); 9073 SDValue V1 = N->getOperand(0); 9074 SDValue V2 = N->getOperand(1); 9075 unsigned ShiftElts = 0, InsertAtByte = 0; 9076 bool Swap = false; 9077 9078 // Shifts required to get the half-word we want at element 3. 9079 unsigned LittleEndianShifts[] = {4, 3, 2, 1, 0, 7, 6, 5}; 9080 unsigned BigEndianShifts[] = {5, 6, 7, 0, 1, 2, 3, 4}; 9081 9082 uint32_t Mask = 0; 9083 uint32_t OriginalOrderLow = 0x1234567; 9084 uint32_t OriginalOrderHigh = 0x89ABCDEF; 9085 // Now we look at mask elements 0,2,4,6,8,10,12,14. Pack the mask into a 9086 // 32-bit space, only need 4-bit nibbles per element. 9087 for (unsigned i = 0; i < NumHalfWords; ++i) { 9088 unsigned MaskShift = (NumHalfWords - 1 - i) * 4; 9089 Mask |= ((uint32_t)(N->getMaskElt(i * 2) / 2) << MaskShift); 9090 } 9091 9092 // For each mask element, find out if we're just inserting something 9093 // from V2 into V1 or vice versa. Possible permutations inserting an element 9094 // from V2 into V1: 9095 // X, 1, 2, 3, 4, 5, 6, 7 9096 // 0, X, 2, 3, 4, 5, 6, 7 9097 // 0, 1, X, 3, 4, 5, 6, 7 9098 // 0, 1, 2, X, 4, 5, 6, 7 9099 // 0, 1, 2, 3, X, 5, 6, 7 9100 // 0, 1, 2, 3, 4, X, 6, 7 9101 // 0, 1, 2, 3, 4, 5, X, 7 9102 // 0, 1, 2, 3, 4, 5, 6, X 9103 // Inserting from V1 into V2 will be similar, except mask range will be [8,15]. 9104 9105 bool FoundCandidate = false; 9106 // Go through the mask of half-words to find an element that's being moved 9107 // from one vector to the other. 9108 for (unsigned i = 0; i < NumHalfWords; ++i) { 9109 unsigned MaskShift = (NumHalfWords - 1 - i) * 4; 9110 uint32_t MaskOneElt = (Mask >> MaskShift) & 0xF; 9111 uint32_t MaskOtherElts = ~(0xF << MaskShift); 9112 uint32_t TargetOrder = 0x0; 9113 9114 // If both vector operands for the shuffle are the same vector, the mask 9115 // will contain only elements from the first one and the second one will be 9116 // undef. 9117 if (V2.isUndef()) { 9118 ShiftElts = 0; 9119 unsigned VINSERTHSrcElem = IsLE ? 4 : 3; 9120 TargetOrder = OriginalOrderLow; 9121 Swap = false; 9122 // Skip if not the correct element or mask of other elements don't equal 9123 // to our expected order. 9124 if (MaskOneElt == VINSERTHSrcElem && 9125 (Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) { 9126 InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2; 9127 FoundCandidate = true; 9128 break; 9129 } 9130 } else { // If both operands are defined. 9131 // Target order is [8,15] if the current mask is between [0,7]. 9132 TargetOrder = 9133 (MaskOneElt < NumHalfWords) ? OriginalOrderHigh : OriginalOrderLow; 9134 // Skip if mask of other elements don't equal our expected order. 9135 if ((Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) { 9136 // We only need the last 3 bits for the number of shifts. 9137 ShiftElts = IsLE ? LittleEndianShifts[MaskOneElt & 0x7] 9138 : BigEndianShifts[MaskOneElt & 0x7]; 9139 InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2; 9140 Swap = MaskOneElt < NumHalfWords; 9141 FoundCandidate = true; 9142 break; 9143 } 9144 } 9145 } 9146 9147 if (!FoundCandidate) 9148 return SDValue(); 9149 9150 // Candidate found, construct the proper SDAG sequence with VINSERTH, 9151 // optionally with VECSHL if shift is required. 9152 if (Swap) 9153 std::swap(V1, V2); 9154 if (V2.isUndef()) 9155 V2 = V1; 9156 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1); 9157 if (ShiftElts) { 9158 // Double ShiftElts because we're left shifting on v16i8 type. 9159 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2, 9160 DAG.getConstant(2 * ShiftElts, dl, MVT::i32)); 9161 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, Shl); 9162 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2, 9163 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9164 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 9165 } 9166 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2); 9167 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2, 9168 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9169 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 9170 } 9171 9172 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE. If this 9173 /// is a shuffle we can handle in a single instruction, return it. Otherwise, 9174 /// return the code it can be lowered into. Worst case, it can always be 9175 /// lowered into a vperm. 9176 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, 9177 SelectionDAG &DAG) const { 9178 SDLoc dl(Op); 9179 SDValue V1 = Op.getOperand(0); 9180 SDValue V2 = Op.getOperand(1); 9181 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op); 9182 EVT VT = Op.getValueType(); 9183 bool isLittleEndian = Subtarget.isLittleEndian(); 9184 9185 unsigned ShiftElts, InsertAtByte; 9186 bool Swap = false; 9187 9188 // If this is a load-and-splat, we can do that with a single instruction 9189 // in some cases. However if the load has multiple uses, we don't want to 9190 // combine it because that will just produce multiple loads. 9191 const SDValue *InputLoad = getNormalLoadInput(V1); 9192 if (InputLoad && Subtarget.hasVSX() && V2.isUndef() && 9193 (PPC::isSplatShuffleMask(SVOp, 4) || PPC::isSplatShuffleMask(SVOp, 8)) && 9194 InputLoad->hasOneUse()) { 9195 bool IsFourByte = PPC::isSplatShuffleMask(SVOp, 4); 9196 int SplatIdx = 9197 PPC::getSplatIdxForPPCMnemonics(SVOp, IsFourByte ? 4 : 8, DAG); 9198 9199 LoadSDNode *LD = cast<LoadSDNode>(*InputLoad); 9200 // For 4-byte load-and-splat, we need Power9. 9201 if ((IsFourByte && Subtarget.hasP9Vector()) || !IsFourByte) { 9202 uint64_t Offset = 0; 9203 if (IsFourByte) 9204 Offset = isLittleEndian ? (3 - SplatIdx) * 4 : SplatIdx * 4; 9205 else 9206 Offset = isLittleEndian ? (1 - SplatIdx) * 8 : SplatIdx * 8; 9207 SDValue BasePtr = LD->getBasePtr(); 9208 if (Offset != 0) 9209 BasePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()), 9210 BasePtr, DAG.getIntPtrConstant(Offset, dl)); 9211 SDValue Ops[] = { 9212 LD->getChain(), // Chain 9213 BasePtr, // BasePtr 9214 DAG.getValueType(Op.getValueType()) // VT 9215 }; 9216 SDVTList VTL = 9217 DAG.getVTList(IsFourByte ? MVT::v4i32 : MVT::v2i64, MVT::Other); 9218 SDValue LdSplt = 9219 DAG.getMemIntrinsicNode(PPCISD::LD_SPLAT, dl, VTL, 9220 Ops, LD->getMemoryVT(), LD->getMemOperand()); 9221 if (LdSplt.getValueType() != SVOp->getValueType(0)) 9222 LdSplt = DAG.getBitcast(SVOp->getValueType(0), LdSplt); 9223 return LdSplt; 9224 } 9225 } 9226 if (Subtarget.hasP9Vector() && 9227 PPC::isXXINSERTWMask(SVOp, ShiftElts, InsertAtByte, Swap, 9228 isLittleEndian)) { 9229 if (Swap) 9230 std::swap(V1, V2); 9231 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 9232 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2); 9233 if (ShiftElts) { 9234 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv2, Conv2, 9235 DAG.getConstant(ShiftElts, dl, MVT::i32)); 9236 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Shl, 9237 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9238 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 9239 } 9240 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Conv2, 9241 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9242 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 9243 } 9244 9245 if (Subtarget.hasP9Altivec()) { 9246 SDValue NewISDNode; 9247 if ((NewISDNode = lowerToVINSERTH(SVOp, DAG))) 9248 return NewISDNode; 9249 9250 if ((NewISDNode = lowerToVINSERTB(SVOp, DAG))) 9251 return NewISDNode; 9252 } 9253 9254 if (Subtarget.hasVSX() && 9255 PPC::isXXSLDWIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) { 9256 if (Swap) 9257 std::swap(V1, V2); 9258 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 9259 SDValue Conv2 = 9260 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2.isUndef() ? V1 : V2); 9261 9262 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv1, Conv2, 9263 DAG.getConstant(ShiftElts, dl, MVT::i32)); 9264 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Shl); 9265 } 9266 9267 if (Subtarget.hasVSX() && 9268 PPC::isXXPERMDIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) { 9269 if (Swap) 9270 std::swap(V1, V2); 9271 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1); 9272 SDValue Conv2 = 9273 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2.isUndef() ? V1 : V2); 9274 9275 SDValue PermDI = DAG.getNode(PPCISD::XXPERMDI, dl, MVT::v2i64, Conv1, Conv2, 9276 DAG.getConstant(ShiftElts, dl, MVT::i32)); 9277 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, PermDI); 9278 } 9279 9280 if (Subtarget.hasP9Vector()) { 9281 if (PPC::isXXBRHShuffleMask(SVOp)) { 9282 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1); 9283 SDValue ReveHWord = DAG.getNode(ISD::BSWAP, dl, MVT::v8i16, Conv); 9284 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveHWord); 9285 } else if (PPC::isXXBRWShuffleMask(SVOp)) { 9286 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 9287 SDValue ReveWord = DAG.getNode(ISD::BSWAP, dl, MVT::v4i32, Conv); 9288 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveWord); 9289 } else if (PPC::isXXBRDShuffleMask(SVOp)) { 9290 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1); 9291 SDValue ReveDWord = DAG.getNode(ISD::BSWAP, dl, MVT::v2i64, Conv); 9292 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveDWord); 9293 } else if (PPC::isXXBRQShuffleMask(SVOp)) { 9294 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, V1); 9295 SDValue ReveQWord = DAG.getNode(ISD::BSWAP, dl, MVT::v1i128, Conv); 9296 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveQWord); 9297 } 9298 } 9299 9300 if (Subtarget.hasVSX()) { 9301 if (V2.isUndef() && PPC::isSplatShuffleMask(SVOp, 4)) { 9302 int SplatIdx = PPC::getSplatIdxForPPCMnemonics(SVOp, 4, DAG); 9303 9304 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 9305 SDValue Splat = DAG.getNode(PPCISD::XXSPLT, dl, MVT::v4i32, Conv, 9306 DAG.getConstant(SplatIdx, dl, MVT::i32)); 9307 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Splat); 9308 } 9309 9310 // Left shifts of 8 bytes are actually swaps. Convert accordingly. 9311 if (V2.isUndef() && PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) == 8) { 9312 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1); 9313 SDValue Swap = DAG.getNode(PPCISD::SWAP_NO_CHAIN, dl, MVT::v2f64, Conv); 9314 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Swap); 9315 } 9316 } 9317 9318 if (Subtarget.hasQPX()) { 9319 if (VT.getVectorNumElements() != 4) 9320 return SDValue(); 9321 9322 if (V2.isUndef()) V2 = V1; 9323 9324 int AlignIdx = PPC::isQVALIGNIShuffleMask(SVOp); 9325 if (AlignIdx != -1) { 9326 return DAG.getNode(PPCISD::QVALIGNI, dl, VT, V1, V2, 9327 DAG.getConstant(AlignIdx, dl, MVT::i32)); 9328 } else if (SVOp->isSplat()) { 9329 int SplatIdx = SVOp->getSplatIndex(); 9330 if (SplatIdx >= 4) { 9331 std::swap(V1, V2); 9332 SplatIdx -= 4; 9333 } 9334 9335 return DAG.getNode(PPCISD::QVESPLATI, dl, VT, V1, 9336 DAG.getConstant(SplatIdx, dl, MVT::i32)); 9337 } 9338 9339 // Lower this into a qvgpci/qvfperm pair. 9340 9341 // Compute the qvgpci literal 9342 unsigned idx = 0; 9343 for (unsigned i = 0; i < 4; ++i) { 9344 int m = SVOp->getMaskElt(i); 9345 unsigned mm = m >= 0 ? (unsigned) m : i; 9346 idx |= mm << (3-i)*3; 9347 } 9348 9349 SDValue V3 = DAG.getNode(PPCISD::QVGPCI, dl, MVT::v4f64, 9350 DAG.getConstant(idx, dl, MVT::i32)); 9351 return DAG.getNode(PPCISD::QVFPERM, dl, VT, V1, V2, V3); 9352 } 9353 9354 // Cases that are handled by instructions that take permute immediates 9355 // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be 9356 // selected by the instruction selector. 9357 if (V2.isUndef()) { 9358 if (PPC::isSplatShuffleMask(SVOp, 1) || 9359 PPC::isSplatShuffleMask(SVOp, 2) || 9360 PPC::isSplatShuffleMask(SVOp, 4) || 9361 PPC::isVPKUWUMShuffleMask(SVOp, 1, DAG) || 9362 PPC::isVPKUHUMShuffleMask(SVOp, 1, DAG) || 9363 PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) != -1 || 9364 PPC::isVMRGLShuffleMask(SVOp, 1, 1, DAG) || 9365 PPC::isVMRGLShuffleMask(SVOp, 2, 1, DAG) || 9366 PPC::isVMRGLShuffleMask(SVOp, 4, 1, DAG) || 9367 PPC::isVMRGHShuffleMask(SVOp, 1, 1, DAG) || 9368 PPC::isVMRGHShuffleMask(SVOp, 2, 1, DAG) || 9369 PPC::isVMRGHShuffleMask(SVOp, 4, 1, DAG) || 9370 (Subtarget.hasP8Altivec() && ( 9371 PPC::isVPKUDUMShuffleMask(SVOp, 1, DAG) || 9372 PPC::isVMRGEOShuffleMask(SVOp, true, 1, DAG) || 9373 PPC::isVMRGEOShuffleMask(SVOp, false, 1, DAG)))) { 9374 return Op; 9375 } 9376 } 9377 9378 // Altivec has a variety of "shuffle immediates" that take two vector inputs 9379 // and produce a fixed permutation. If any of these match, do not lower to 9380 // VPERM. 9381 unsigned int ShuffleKind = isLittleEndian ? 2 : 0; 9382 if (PPC::isVPKUWUMShuffleMask(SVOp, ShuffleKind, DAG) || 9383 PPC::isVPKUHUMShuffleMask(SVOp, ShuffleKind, DAG) || 9384 PPC::isVSLDOIShuffleMask(SVOp, ShuffleKind, DAG) != -1 || 9385 PPC::isVMRGLShuffleMask(SVOp, 1, ShuffleKind, DAG) || 9386 PPC::isVMRGLShuffleMask(SVOp, 2, ShuffleKind, DAG) || 9387 PPC::isVMRGLShuffleMask(SVOp, 4, ShuffleKind, DAG) || 9388 PPC::isVMRGHShuffleMask(SVOp, 1, ShuffleKind, DAG) || 9389 PPC::isVMRGHShuffleMask(SVOp, 2, ShuffleKind, DAG) || 9390 PPC::isVMRGHShuffleMask(SVOp, 4, ShuffleKind, DAG) || 9391 (Subtarget.hasP8Altivec() && ( 9392 PPC::isVPKUDUMShuffleMask(SVOp, ShuffleKind, DAG) || 9393 PPC::isVMRGEOShuffleMask(SVOp, true, ShuffleKind, DAG) || 9394 PPC::isVMRGEOShuffleMask(SVOp, false, ShuffleKind, DAG)))) 9395 return Op; 9396 9397 // Check to see if this is a shuffle of 4-byte values. If so, we can use our 9398 // perfect shuffle table to emit an optimal matching sequence. 9399 ArrayRef<int> PermMask = SVOp->getMask(); 9400 9401 unsigned PFIndexes[4]; 9402 bool isFourElementShuffle = true; 9403 for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number 9404 unsigned EltNo = 8; // Start out undef. 9405 for (unsigned j = 0; j != 4; ++j) { // Intra-element byte. 9406 if (PermMask[i*4+j] < 0) 9407 continue; // Undef, ignore it. 9408 9409 unsigned ByteSource = PermMask[i*4+j]; 9410 if ((ByteSource & 3) != j) { 9411 isFourElementShuffle = false; 9412 break; 9413 } 9414 9415 if (EltNo == 8) { 9416 EltNo = ByteSource/4; 9417 } else if (EltNo != ByteSource/4) { 9418 isFourElementShuffle = false; 9419 break; 9420 } 9421 } 9422 PFIndexes[i] = EltNo; 9423 } 9424 9425 // If this shuffle can be expressed as a shuffle of 4-byte elements, use the 9426 // perfect shuffle vector to determine if it is cost effective to do this as 9427 // discrete instructions, or whether we should use a vperm. 9428 // For now, we skip this for little endian until such time as we have a 9429 // little-endian perfect shuffle table. 9430 if (isFourElementShuffle && !isLittleEndian) { 9431 // Compute the index in the perfect shuffle table. 9432 unsigned PFTableIndex = 9433 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3]; 9434 9435 unsigned PFEntry = PerfectShuffleTable[PFTableIndex]; 9436 unsigned Cost = (PFEntry >> 30); 9437 9438 // Determining when to avoid vperm is tricky. Many things affect the cost 9439 // of vperm, particularly how many times the perm mask needs to be computed. 9440 // For example, if the perm mask can be hoisted out of a loop or is already 9441 // used (perhaps because there are multiple permutes with the same shuffle 9442 // mask?) the vperm has a cost of 1. OTOH, hoisting the permute mask out of 9443 // the loop requires an extra register. 9444 // 9445 // As a compromise, we only emit discrete instructions if the shuffle can be 9446 // generated in 3 or fewer operations. When we have loop information 9447 // available, if this block is within a loop, we should avoid using vperm 9448 // for 3-operation perms and use a constant pool load instead. 9449 if (Cost < 3) 9450 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl); 9451 } 9452 9453 // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant 9454 // vector that will get spilled to the constant pool. 9455 if (V2.isUndef()) V2 = V1; 9456 9457 // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except 9458 // that it is in input element units, not in bytes. Convert now. 9459 9460 // For little endian, the order of the input vectors is reversed, and 9461 // the permutation mask is complemented with respect to 31. This is 9462 // necessary to produce proper semantics with the big-endian-biased vperm 9463 // instruction. 9464 EVT EltVT = V1.getValueType().getVectorElementType(); 9465 unsigned BytesPerElement = EltVT.getSizeInBits()/8; 9466 9467 SmallVector<SDValue, 16> ResultMask; 9468 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) { 9469 unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i]; 9470 9471 for (unsigned j = 0; j != BytesPerElement; ++j) 9472 if (isLittleEndian) 9473 ResultMask.push_back(DAG.getConstant(31 - (SrcElt*BytesPerElement + j), 9474 dl, MVT::i32)); 9475 else 9476 ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement + j, dl, 9477 MVT::i32)); 9478 } 9479 9480 SDValue VPermMask = DAG.getBuildVector(MVT::v16i8, dl, ResultMask); 9481 if (isLittleEndian) 9482 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(), 9483 V2, V1, VPermMask); 9484 else 9485 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(), 9486 V1, V2, VPermMask); 9487 } 9488 9489 /// getVectorCompareInfo - Given an intrinsic, return false if it is not a 9490 /// vector comparison. If it is, return true and fill in Opc/isDot with 9491 /// information about the intrinsic. 9492 static bool getVectorCompareInfo(SDValue Intrin, int &CompareOpc, 9493 bool &isDot, const PPCSubtarget &Subtarget) { 9494 unsigned IntrinsicID = 9495 cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue(); 9496 CompareOpc = -1; 9497 isDot = false; 9498 switch (IntrinsicID) { 9499 default: 9500 return false; 9501 // Comparison predicates. 9502 case Intrinsic::ppc_altivec_vcmpbfp_p: 9503 CompareOpc = 966; 9504 isDot = true; 9505 break; 9506 case Intrinsic::ppc_altivec_vcmpeqfp_p: 9507 CompareOpc = 198; 9508 isDot = true; 9509 break; 9510 case Intrinsic::ppc_altivec_vcmpequb_p: 9511 CompareOpc = 6; 9512 isDot = true; 9513 break; 9514 case Intrinsic::ppc_altivec_vcmpequh_p: 9515 CompareOpc = 70; 9516 isDot = true; 9517 break; 9518 case Intrinsic::ppc_altivec_vcmpequw_p: 9519 CompareOpc = 134; 9520 isDot = true; 9521 break; 9522 case Intrinsic::ppc_altivec_vcmpequd_p: 9523 if (Subtarget.hasP8Altivec()) { 9524 CompareOpc = 199; 9525 isDot = true; 9526 } else 9527 return false; 9528 break; 9529 case Intrinsic::ppc_altivec_vcmpneb_p: 9530 case Intrinsic::ppc_altivec_vcmpneh_p: 9531 case Intrinsic::ppc_altivec_vcmpnew_p: 9532 case Intrinsic::ppc_altivec_vcmpnezb_p: 9533 case Intrinsic::ppc_altivec_vcmpnezh_p: 9534 case Intrinsic::ppc_altivec_vcmpnezw_p: 9535 if (Subtarget.hasP9Altivec()) { 9536 switch (IntrinsicID) { 9537 default: 9538 llvm_unreachable("Unknown comparison intrinsic."); 9539 case Intrinsic::ppc_altivec_vcmpneb_p: 9540 CompareOpc = 7; 9541 break; 9542 case Intrinsic::ppc_altivec_vcmpneh_p: 9543 CompareOpc = 71; 9544 break; 9545 case Intrinsic::ppc_altivec_vcmpnew_p: 9546 CompareOpc = 135; 9547 break; 9548 case Intrinsic::ppc_altivec_vcmpnezb_p: 9549 CompareOpc = 263; 9550 break; 9551 case Intrinsic::ppc_altivec_vcmpnezh_p: 9552 CompareOpc = 327; 9553 break; 9554 case Intrinsic::ppc_altivec_vcmpnezw_p: 9555 CompareOpc = 391; 9556 break; 9557 } 9558 isDot = true; 9559 } else 9560 return false; 9561 break; 9562 case Intrinsic::ppc_altivec_vcmpgefp_p: 9563 CompareOpc = 454; 9564 isDot = true; 9565 break; 9566 case Intrinsic::ppc_altivec_vcmpgtfp_p: 9567 CompareOpc = 710; 9568 isDot = true; 9569 break; 9570 case Intrinsic::ppc_altivec_vcmpgtsb_p: 9571 CompareOpc = 774; 9572 isDot = true; 9573 break; 9574 case Intrinsic::ppc_altivec_vcmpgtsh_p: 9575 CompareOpc = 838; 9576 isDot = true; 9577 break; 9578 case Intrinsic::ppc_altivec_vcmpgtsw_p: 9579 CompareOpc = 902; 9580 isDot = true; 9581 break; 9582 case Intrinsic::ppc_altivec_vcmpgtsd_p: 9583 if (Subtarget.hasP8Altivec()) { 9584 CompareOpc = 967; 9585 isDot = true; 9586 } else 9587 return false; 9588 break; 9589 case Intrinsic::ppc_altivec_vcmpgtub_p: 9590 CompareOpc = 518; 9591 isDot = true; 9592 break; 9593 case Intrinsic::ppc_altivec_vcmpgtuh_p: 9594 CompareOpc = 582; 9595 isDot = true; 9596 break; 9597 case Intrinsic::ppc_altivec_vcmpgtuw_p: 9598 CompareOpc = 646; 9599 isDot = true; 9600 break; 9601 case Intrinsic::ppc_altivec_vcmpgtud_p: 9602 if (Subtarget.hasP8Altivec()) { 9603 CompareOpc = 711; 9604 isDot = true; 9605 } else 9606 return false; 9607 break; 9608 9609 // VSX predicate comparisons use the same infrastructure 9610 case Intrinsic::ppc_vsx_xvcmpeqdp_p: 9611 case Intrinsic::ppc_vsx_xvcmpgedp_p: 9612 case Intrinsic::ppc_vsx_xvcmpgtdp_p: 9613 case Intrinsic::ppc_vsx_xvcmpeqsp_p: 9614 case Intrinsic::ppc_vsx_xvcmpgesp_p: 9615 case Intrinsic::ppc_vsx_xvcmpgtsp_p: 9616 if (Subtarget.hasVSX()) { 9617 switch (IntrinsicID) { 9618 case Intrinsic::ppc_vsx_xvcmpeqdp_p: 9619 CompareOpc = 99; 9620 break; 9621 case Intrinsic::ppc_vsx_xvcmpgedp_p: 9622 CompareOpc = 115; 9623 break; 9624 case Intrinsic::ppc_vsx_xvcmpgtdp_p: 9625 CompareOpc = 107; 9626 break; 9627 case Intrinsic::ppc_vsx_xvcmpeqsp_p: 9628 CompareOpc = 67; 9629 break; 9630 case Intrinsic::ppc_vsx_xvcmpgesp_p: 9631 CompareOpc = 83; 9632 break; 9633 case Intrinsic::ppc_vsx_xvcmpgtsp_p: 9634 CompareOpc = 75; 9635 break; 9636 } 9637 isDot = true; 9638 } else 9639 return false; 9640 break; 9641 9642 // Normal Comparisons. 9643 case Intrinsic::ppc_altivec_vcmpbfp: 9644 CompareOpc = 966; 9645 break; 9646 case Intrinsic::ppc_altivec_vcmpeqfp: 9647 CompareOpc = 198; 9648 break; 9649 case Intrinsic::ppc_altivec_vcmpequb: 9650 CompareOpc = 6; 9651 break; 9652 case Intrinsic::ppc_altivec_vcmpequh: 9653 CompareOpc = 70; 9654 break; 9655 case Intrinsic::ppc_altivec_vcmpequw: 9656 CompareOpc = 134; 9657 break; 9658 case Intrinsic::ppc_altivec_vcmpequd: 9659 if (Subtarget.hasP8Altivec()) 9660 CompareOpc = 199; 9661 else 9662 return false; 9663 break; 9664 case Intrinsic::ppc_altivec_vcmpneb: 9665 case Intrinsic::ppc_altivec_vcmpneh: 9666 case Intrinsic::ppc_altivec_vcmpnew: 9667 case Intrinsic::ppc_altivec_vcmpnezb: 9668 case Intrinsic::ppc_altivec_vcmpnezh: 9669 case Intrinsic::ppc_altivec_vcmpnezw: 9670 if (Subtarget.hasP9Altivec()) 9671 switch (IntrinsicID) { 9672 default: 9673 llvm_unreachable("Unknown comparison intrinsic."); 9674 case Intrinsic::ppc_altivec_vcmpneb: 9675 CompareOpc = 7; 9676 break; 9677 case Intrinsic::ppc_altivec_vcmpneh: 9678 CompareOpc = 71; 9679 break; 9680 case Intrinsic::ppc_altivec_vcmpnew: 9681 CompareOpc = 135; 9682 break; 9683 case Intrinsic::ppc_altivec_vcmpnezb: 9684 CompareOpc = 263; 9685 break; 9686 case Intrinsic::ppc_altivec_vcmpnezh: 9687 CompareOpc = 327; 9688 break; 9689 case Intrinsic::ppc_altivec_vcmpnezw: 9690 CompareOpc = 391; 9691 break; 9692 } 9693 else 9694 return false; 9695 break; 9696 case Intrinsic::ppc_altivec_vcmpgefp: 9697 CompareOpc = 454; 9698 break; 9699 case Intrinsic::ppc_altivec_vcmpgtfp: 9700 CompareOpc = 710; 9701 break; 9702 case Intrinsic::ppc_altivec_vcmpgtsb: 9703 CompareOpc = 774; 9704 break; 9705 case Intrinsic::ppc_altivec_vcmpgtsh: 9706 CompareOpc = 838; 9707 break; 9708 case Intrinsic::ppc_altivec_vcmpgtsw: 9709 CompareOpc = 902; 9710 break; 9711 case Intrinsic::ppc_altivec_vcmpgtsd: 9712 if (Subtarget.hasP8Altivec()) 9713 CompareOpc = 967; 9714 else 9715 return false; 9716 break; 9717 case Intrinsic::ppc_altivec_vcmpgtub: 9718 CompareOpc = 518; 9719 break; 9720 case Intrinsic::ppc_altivec_vcmpgtuh: 9721 CompareOpc = 582; 9722 break; 9723 case Intrinsic::ppc_altivec_vcmpgtuw: 9724 CompareOpc = 646; 9725 break; 9726 case Intrinsic::ppc_altivec_vcmpgtud: 9727 if (Subtarget.hasP8Altivec()) 9728 CompareOpc = 711; 9729 else 9730 return false; 9731 break; 9732 } 9733 return true; 9734 } 9735 9736 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom 9737 /// lower, do it, otherwise return null. 9738 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 9739 SelectionDAG &DAG) const { 9740 unsigned IntrinsicID = 9741 cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 9742 9743 SDLoc dl(Op); 9744 9745 if (IntrinsicID == Intrinsic::thread_pointer) { 9746 // Reads the thread pointer register, used for __builtin_thread_pointer. 9747 if (Subtarget.isPPC64()) 9748 return DAG.getRegister(PPC::X13, MVT::i64); 9749 return DAG.getRegister(PPC::R2, MVT::i32); 9750 } 9751 9752 // If this is a lowered altivec predicate compare, CompareOpc is set to the 9753 // opcode number of the comparison. 9754 int CompareOpc; 9755 bool isDot; 9756 if (!getVectorCompareInfo(Op, CompareOpc, isDot, Subtarget)) 9757 return SDValue(); // Don't custom lower most intrinsics. 9758 9759 // If this is a non-dot comparison, make the VCMP node and we are done. 9760 if (!isDot) { 9761 SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(), 9762 Op.getOperand(1), Op.getOperand(2), 9763 DAG.getConstant(CompareOpc, dl, MVT::i32)); 9764 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp); 9765 } 9766 9767 // Create the PPCISD altivec 'dot' comparison node. 9768 SDValue Ops[] = { 9769 Op.getOperand(2), // LHS 9770 Op.getOperand(3), // RHS 9771 DAG.getConstant(CompareOpc, dl, MVT::i32) 9772 }; 9773 EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue }; 9774 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops); 9775 9776 // Now that we have the comparison, emit a copy from the CR to a GPR. 9777 // This is flagged to the above dot comparison. 9778 SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32, 9779 DAG.getRegister(PPC::CR6, MVT::i32), 9780 CompNode.getValue(1)); 9781 9782 // Unpack the result based on how the target uses it. 9783 unsigned BitNo; // Bit # of CR6. 9784 bool InvertBit; // Invert result? 9785 switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) { 9786 default: // Can't happen, don't crash on invalid number though. 9787 case 0: // Return the value of the EQ bit of CR6. 9788 BitNo = 0; InvertBit = false; 9789 break; 9790 case 1: // Return the inverted value of the EQ bit of CR6. 9791 BitNo = 0; InvertBit = true; 9792 break; 9793 case 2: // Return the value of the LT bit of CR6. 9794 BitNo = 2; InvertBit = false; 9795 break; 9796 case 3: // Return the inverted value of the LT bit of CR6. 9797 BitNo = 2; InvertBit = true; 9798 break; 9799 } 9800 9801 // Shift the bit into the low position. 9802 Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags, 9803 DAG.getConstant(8 - (3 - BitNo), dl, MVT::i32)); 9804 // Isolate the bit. 9805 Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags, 9806 DAG.getConstant(1, dl, MVT::i32)); 9807 9808 // If we are supposed to, toggle the bit. 9809 if (InvertBit) 9810 Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags, 9811 DAG.getConstant(1, dl, MVT::i32)); 9812 return Flags; 9813 } 9814 9815 SDValue PPCTargetLowering::LowerINTRINSIC_VOID(SDValue Op, 9816 SelectionDAG &DAG) const { 9817 // SelectionDAGBuilder::visitTargetIntrinsic may insert one extra chain to 9818 // the beginning of the argument list. 9819 int ArgStart = isa<ConstantSDNode>(Op.getOperand(0)) ? 0 : 1; 9820 SDLoc DL(Op); 9821 switch (cast<ConstantSDNode>(Op.getOperand(ArgStart))->getZExtValue()) { 9822 case Intrinsic::ppc_cfence: { 9823 assert(ArgStart == 1 && "llvm.ppc.cfence must carry a chain argument."); 9824 assert(Subtarget.isPPC64() && "Only 64-bit is supported for now."); 9825 return SDValue(DAG.getMachineNode(PPC::CFENCE8, DL, MVT::Other, 9826 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, 9827 Op.getOperand(ArgStart + 1)), 9828 Op.getOperand(0)), 9829 0); 9830 } 9831 default: 9832 break; 9833 } 9834 return SDValue(); 9835 } 9836 9837 SDValue PPCTargetLowering::LowerREM(SDValue Op, SelectionDAG &DAG) const { 9838 // Check for a DIV with the same operands as this REM. 9839 for (auto UI : Op.getOperand(1)->uses()) { 9840 if ((Op.getOpcode() == ISD::SREM && UI->getOpcode() == ISD::SDIV) || 9841 (Op.getOpcode() == ISD::UREM && UI->getOpcode() == ISD::UDIV)) 9842 if (UI->getOperand(0) == Op.getOperand(0) && 9843 UI->getOperand(1) == Op.getOperand(1)) 9844 return SDValue(); 9845 } 9846 return Op; 9847 } 9848 9849 // Lower scalar BSWAP64 to xxbrd. 9850 SDValue PPCTargetLowering::LowerBSWAP(SDValue Op, SelectionDAG &DAG) const { 9851 SDLoc dl(Op); 9852 // MTVSRDD 9853 Op = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i64, Op.getOperand(0), 9854 Op.getOperand(0)); 9855 // XXBRD 9856 Op = DAG.getNode(ISD::BSWAP, dl, MVT::v2i64, Op); 9857 // MFVSRD 9858 int VectorIndex = 0; 9859 if (Subtarget.isLittleEndian()) 9860 VectorIndex = 1; 9861 Op = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Op, 9862 DAG.getTargetConstant(VectorIndex, dl, MVT::i32)); 9863 return Op; 9864 } 9865 9866 // ATOMIC_CMP_SWAP for i8/i16 needs to zero-extend its input since it will be 9867 // compared to a value that is atomically loaded (atomic loads zero-extend). 9868 SDValue PPCTargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, 9869 SelectionDAG &DAG) const { 9870 assert(Op.getOpcode() == ISD::ATOMIC_CMP_SWAP && 9871 "Expecting an atomic compare-and-swap here."); 9872 SDLoc dl(Op); 9873 auto *AtomicNode = cast<AtomicSDNode>(Op.getNode()); 9874 EVT MemVT = AtomicNode->getMemoryVT(); 9875 if (MemVT.getSizeInBits() >= 32) 9876 return Op; 9877 9878 SDValue CmpOp = Op.getOperand(2); 9879 // If this is already correctly zero-extended, leave it alone. 9880 auto HighBits = APInt::getHighBitsSet(32, 32 - MemVT.getSizeInBits()); 9881 if (DAG.MaskedValueIsZero(CmpOp, HighBits)) 9882 return Op; 9883 9884 // Clear the high bits of the compare operand. 9885 unsigned MaskVal = (1 << MemVT.getSizeInBits()) - 1; 9886 SDValue NewCmpOp = 9887 DAG.getNode(ISD::AND, dl, MVT::i32, CmpOp, 9888 DAG.getConstant(MaskVal, dl, MVT::i32)); 9889 9890 // Replace the existing compare operand with the properly zero-extended one. 9891 SmallVector<SDValue, 4> Ops; 9892 for (int i = 0, e = AtomicNode->getNumOperands(); i < e; i++) 9893 Ops.push_back(AtomicNode->getOperand(i)); 9894 Ops[2] = NewCmpOp; 9895 MachineMemOperand *MMO = AtomicNode->getMemOperand(); 9896 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::Other); 9897 auto NodeTy = 9898 (MemVT == MVT::i8) ? PPCISD::ATOMIC_CMP_SWAP_8 : PPCISD::ATOMIC_CMP_SWAP_16; 9899 return DAG.getMemIntrinsicNode(NodeTy, dl, Tys, Ops, MemVT, MMO); 9900 } 9901 9902 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, 9903 SelectionDAG &DAG) const { 9904 SDLoc dl(Op); 9905 // Create a stack slot that is 16-byte aligned. 9906 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 9907 int FrameIdx = MFI.CreateStackObject(16, 16, false); 9908 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 9909 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 9910 9911 // Store the input value into Value#0 of the stack slot. 9912 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx, 9913 MachinePointerInfo()); 9914 // Load it out. 9915 return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo()); 9916 } 9917 9918 SDValue PPCTargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, 9919 SelectionDAG &DAG) const { 9920 assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && 9921 "Should only be called for ISD::INSERT_VECTOR_ELT"); 9922 9923 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(2)); 9924 // We have legal lowering for constant indices but not for variable ones. 9925 if (!C) 9926 return SDValue(); 9927 9928 EVT VT = Op.getValueType(); 9929 SDLoc dl(Op); 9930 SDValue V1 = Op.getOperand(0); 9931 SDValue V2 = Op.getOperand(1); 9932 // We can use MTVSRZ + VECINSERT for v8i16 and v16i8 types. 9933 if (VT == MVT::v8i16 || VT == MVT::v16i8) { 9934 SDValue Mtvsrz = DAG.getNode(PPCISD::MTVSRZ, dl, VT, V2); 9935 unsigned BytesInEachElement = VT.getVectorElementType().getSizeInBits() / 8; 9936 unsigned InsertAtElement = C->getZExtValue(); 9937 unsigned InsertAtByte = InsertAtElement * BytesInEachElement; 9938 if (Subtarget.isLittleEndian()) { 9939 InsertAtByte = (16 - BytesInEachElement) - InsertAtByte; 9940 } 9941 return DAG.getNode(PPCISD::VECINSERT, dl, VT, V1, Mtvsrz, 9942 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9943 } 9944 return Op; 9945 } 9946 9947 SDValue PPCTargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op, 9948 SelectionDAG &DAG) const { 9949 SDLoc dl(Op); 9950 SDNode *N = Op.getNode(); 9951 9952 assert(N->getOperand(0).getValueType() == MVT::v4i1 && 9953 "Unknown extract_vector_elt type"); 9954 9955 SDValue Value = N->getOperand(0); 9956 9957 // The first part of this is like the store lowering except that we don't 9958 // need to track the chain. 9959 9960 // The values are now known to be -1 (false) or 1 (true). To convert this 9961 // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5). 9962 // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5 9963 Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value); 9964 9965 // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to 9966 // understand how to form the extending load. 9967 SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64); 9968 9969 Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs); 9970 9971 // Now convert to an integer and store. 9972 Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64, 9973 DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32), 9974 Value); 9975 9976 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 9977 int FrameIdx = MFI.CreateStackObject(16, 16, false); 9978 MachinePointerInfo PtrInfo = 9979 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 9980 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 9981 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 9982 9983 SDValue StoreChain = DAG.getEntryNode(); 9984 SDValue Ops[] = {StoreChain, 9985 DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32), 9986 Value, FIdx}; 9987 SDVTList VTs = DAG.getVTList(/*chain*/ MVT::Other); 9988 9989 StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, 9990 dl, VTs, Ops, MVT::v4i32, PtrInfo); 9991 9992 // Extract the value requested. 9993 unsigned Offset = 4*cast<ConstantSDNode>(N->getOperand(1))->getZExtValue(); 9994 SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType()); 9995 Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx); 9996 9997 SDValue IntVal = 9998 DAG.getLoad(MVT::i32, dl, StoreChain, Idx, PtrInfo.getWithOffset(Offset)); 9999 10000 if (!Subtarget.useCRBits()) 10001 return IntVal; 10002 10003 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, IntVal); 10004 } 10005 10006 /// Lowering for QPX v4i1 loads 10007 SDValue PPCTargetLowering::LowerVectorLoad(SDValue Op, 10008 SelectionDAG &DAG) const { 10009 SDLoc dl(Op); 10010 LoadSDNode *LN = cast<LoadSDNode>(Op.getNode()); 10011 SDValue LoadChain = LN->getChain(); 10012 SDValue BasePtr = LN->getBasePtr(); 10013 10014 if (Op.getValueType() == MVT::v4f64 || 10015 Op.getValueType() == MVT::v4f32) { 10016 EVT MemVT = LN->getMemoryVT(); 10017 unsigned Alignment = LN->getAlignment(); 10018 10019 // If this load is properly aligned, then it is legal. 10020 if (Alignment >= MemVT.getStoreSize()) 10021 return Op; 10022 10023 EVT ScalarVT = Op.getValueType().getScalarType(), 10024 ScalarMemVT = MemVT.getScalarType(); 10025 unsigned Stride = ScalarMemVT.getStoreSize(); 10026 10027 SDValue Vals[4], LoadChains[4]; 10028 for (unsigned Idx = 0; Idx < 4; ++Idx) { 10029 SDValue Load; 10030 if (ScalarVT != ScalarMemVT) 10031 Load = DAG.getExtLoad(LN->getExtensionType(), dl, ScalarVT, LoadChain, 10032 BasePtr, 10033 LN->getPointerInfo().getWithOffset(Idx * Stride), 10034 ScalarMemVT, MinAlign(Alignment, Idx * Stride), 10035 LN->getMemOperand()->getFlags(), LN->getAAInfo()); 10036 else 10037 Load = DAG.getLoad(ScalarVT, dl, LoadChain, BasePtr, 10038 LN->getPointerInfo().getWithOffset(Idx * Stride), 10039 MinAlign(Alignment, Idx * Stride), 10040 LN->getMemOperand()->getFlags(), LN->getAAInfo()); 10041 10042 if (Idx == 0 && LN->isIndexed()) { 10043 assert(LN->getAddressingMode() == ISD::PRE_INC && 10044 "Unknown addressing mode on vector load"); 10045 Load = DAG.getIndexedLoad(Load, dl, BasePtr, LN->getOffset(), 10046 LN->getAddressingMode()); 10047 } 10048 10049 Vals[Idx] = Load; 10050 LoadChains[Idx] = Load.getValue(1); 10051 10052 BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, 10053 DAG.getConstant(Stride, dl, 10054 BasePtr.getValueType())); 10055 } 10056 10057 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains); 10058 SDValue Value = DAG.getBuildVector(Op.getValueType(), dl, Vals); 10059 10060 if (LN->isIndexed()) { 10061 SDValue RetOps[] = { Value, Vals[0].getValue(1), TF }; 10062 return DAG.getMergeValues(RetOps, dl); 10063 } 10064 10065 SDValue RetOps[] = { Value, TF }; 10066 return DAG.getMergeValues(RetOps, dl); 10067 } 10068 10069 assert(Op.getValueType() == MVT::v4i1 && "Unknown load to lower"); 10070 assert(LN->isUnindexed() && "Indexed v4i1 loads are not supported"); 10071 10072 // To lower v4i1 from a byte array, we load the byte elements of the 10073 // vector and then reuse the BUILD_VECTOR logic. 10074 10075 SDValue VectElmts[4], VectElmtChains[4]; 10076 for (unsigned i = 0; i < 4; ++i) { 10077 SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType()); 10078 Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx); 10079 10080 VectElmts[i] = DAG.getExtLoad( 10081 ISD::EXTLOAD, dl, MVT::i32, LoadChain, Idx, 10082 LN->getPointerInfo().getWithOffset(i), MVT::i8, 10083 /* Alignment = */ 1, LN->getMemOperand()->getFlags(), LN->getAAInfo()); 10084 VectElmtChains[i] = VectElmts[i].getValue(1); 10085 } 10086 10087 LoadChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, VectElmtChains); 10088 SDValue Value = DAG.getBuildVector(MVT::v4i1, dl, VectElmts); 10089 10090 SDValue RVals[] = { Value, LoadChain }; 10091 return DAG.getMergeValues(RVals, dl); 10092 } 10093 10094 /// Lowering for QPX v4i1 stores 10095 SDValue PPCTargetLowering::LowerVectorStore(SDValue Op, 10096 SelectionDAG &DAG) const { 10097 SDLoc dl(Op); 10098 StoreSDNode *SN = cast<StoreSDNode>(Op.getNode()); 10099 SDValue StoreChain = SN->getChain(); 10100 SDValue BasePtr = SN->getBasePtr(); 10101 SDValue Value = SN->getValue(); 10102 10103 if (Value.getValueType() == MVT::v4f64 || 10104 Value.getValueType() == MVT::v4f32) { 10105 EVT MemVT = SN->getMemoryVT(); 10106 unsigned Alignment = SN->getAlignment(); 10107 10108 // If this store is properly aligned, then it is legal. 10109 if (Alignment >= MemVT.getStoreSize()) 10110 return Op; 10111 10112 EVT ScalarVT = Value.getValueType().getScalarType(), 10113 ScalarMemVT = MemVT.getScalarType(); 10114 unsigned Stride = ScalarMemVT.getStoreSize(); 10115 10116 SDValue Stores[4]; 10117 for (unsigned Idx = 0; Idx < 4; ++Idx) { 10118 SDValue Ex = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, Value, 10119 DAG.getVectorIdxConstant(Idx, dl)); 10120 SDValue Store; 10121 if (ScalarVT != ScalarMemVT) 10122 Store = 10123 DAG.getTruncStore(StoreChain, dl, Ex, BasePtr, 10124 SN->getPointerInfo().getWithOffset(Idx * Stride), 10125 ScalarMemVT, MinAlign(Alignment, Idx * Stride), 10126 SN->getMemOperand()->getFlags(), SN->getAAInfo()); 10127 else 10128 Store = DAG.getStore(StoreChain, dl, Ex, BasePtr, 10129 SN->getPointerInfo().getWithOffset(Idx * Stride), 10130 MinAlign(Alignment, Idx * Stride), 10131 SN->getMemOperand()->getFlags(), SN->getAAInfo()); 10132 10133 if (Idx == 0 && SN->isIndexed()) { 10134 assert(SN->getAddressingMode() == ISD::PRE_INC && 10135 "Unknown addressing mode on vector store"); 10136 Store = DAG.getIndexedStore(Store, dl, BasePtr, SN->getOffset(), 10137 SN->getAddressingMode()); 10138 } 10139 10140 BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, 10141 DAG.getConstant(Stride, dl, 10142 BasePtr.getValueType())); 10143 Stores[Idx] = Store; 10144 } 10145 10146 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores); 10147 10148 if (SN->isIndexed()) { 10149 SDValue RetOps[] = { TF, Stores[0].getValue(1) }; 10150 return DAG.getMergeValues(RetOps, dl); 10151 } 10152 10153 return TF; 10154 } 10155 10156 assert(SN->isUnindexed() && "Indexed v4i1 stores are not supported"); 10157 assert(Value.getValueType() == MVT::v4i1 && "Unknown store to lower"); 10158 10159 // The values are now known to be -1 (false) or 1 (true). To convert this 10160 // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5). 10161 // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5 10162 Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value); 10163 10164 // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to 10165 // understand how to form the extending load. 10166 SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64); 10167 10168 Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs); 10169 10170 // Now convert to an integer and store. 10171 Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64, 10172 DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32), 10173 Value); 10174 10175 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 10176 int FrameIdx = MFI.CreateStackObject(16, 16, false); 10177 MachinePointerInfo PtrInfo = 10178 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 10179 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 10180 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 10181 10182 SDValue Ops[] = {StoreChain, 10183 DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32), 10184 Value, FIdx}; 10185 SDVTList VTs = DAG.getVTList(/*chain*/ MVT::Other); 10186 10187 StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, 10188 dl, VTs, Ops, MVT::v4i32, PtrInfo); 10189 10190 // Move data into the byte array. 10191 SDValue Loads[4], LoadChains[4]; 10192 for (unsigned i = 0; i < 4; ++i) { 10193 unsigned Offset = 4*i; 10194 SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType()); 10195 Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx); 10196 10197 Loads[i] = DAG.getLoad(MVT::i32, dl, StoreChain, Idx, 10198 PtrInfo.getWithOffset(Offset)); 10199 LoadChains[i] = Loads[i].getValue(1); 10200 } 10201 10202 StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains); 10203 10204 SDValue Stores[4]; 10205 for (unsigned i = 0; i < 4; ++i) { 10206 SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType()); 10207 Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx); 10208 10209 Stores[i] = DAG.getTruncStore( 10210 StoreChain, dl, Loads[i], Idx, SN->getPointerInfo().getWithOffset(i), 10211 MVT::i8, /* Alignment = */ 1, SN->getMemOperand()->getFlags(), 10212 SN->getAAInfo()); 10213 } 10214 10215 StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores); 10216 10217 return StoreChain; 10218 } 10219 10220 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const { 10221 SDLoc dl(Op); 10222 if (Op.getValueType() == MVT::v4i32) { 10223 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 10224 10225 SDValue Zero = BuildSplatI( 0, 1, MVT::v4i32, DAG, dl); 10226 SDValue Neg16 = BuildSplatI(-16, 4, MVT::v4i32, DAG, dl);//+16 as shift amt. 10227 10228 SDValue RHSSwap = // = vrlw RHS, 16 10229 BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl); 10230 10231 // Shrinkify inputs to v8i16. 10232 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS); 10233 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS); 10234 RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap); 10235 10236 // Low parts multiplied together, generating 32-bit results (we ignore the 10237 // top parts). 10238 SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh, 10239 LHS, RHS, DAG, dl, MVT::v4i32); 10240 10241 SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm, 10242 LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32); 10243 // Shift the high parts up 16 bits. 10244 HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd, 10245 Neg16, DAG, dl); 10246 return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd); 10247 } else if (Op.getValueType() == MVT::v8i16) { 10248 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 10249 10250 SDValue Zero = BuildSplatI(0, 1, MVT::v8i16, DAG, dl); 10251 10252 return BuildIntrinsicOp(Intrinsic::ppc_altivec_vmladduhm, 10253 LHS, RHS, Zero, DAG, dl); 10254 } else if (Op.getValueType() == MVT::v16i8) { 10255 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 10256 bool isLittleEndian = Subtarget.isLittleEndian(); 10257 10258 // Multiply the even 8-bit parts, producing 16-bit sums. 10259 SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub, 10260 LHS, RHS, DAG, dl, MVT::v8i16); 10261 EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts); 10262 10263 // Multiply the odd 8-bit parts, producing 16-bit sums. 10264 SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub, 10265 LHS, RHS, DAG, dl, MVT::v8i16); 10266 OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts); 10267 10268 // Merge the results together. Because vmuleub and vmuloub are 10269 // instructions with a big-endian bias, we must reverse the 10270 // element numbering and reverse the meaning of "odd" and "even" 10271 // when generating little endian code. 10272 int Ops[16]; 10273 for (unsigned i = 0; i != 8; ++i) { 10274 if (isLittleEndian) { 10275 Ops[i*2 ] = 2*i; 10276 Ops[i*2+1] = 2*i+16; 10277 } else { 10278 Ops[i*2 ] = 2*i+1; 10279 Ops[i*2+1] = 2*i+1+16; 10280 } 10281 } 10282 if (isLittleEndian) 10283 return DAG.getVectorShuffle(MVT::v16i8, dl, OddParts, EvenParts, Ops); 10284 else 10285 return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops); 10286 } else { 10287 llvm_unreachable("Unknown mul to lower!"); 10288 } 10289 } 10290 10291 SDValue PPCTargetLowering::LowerABS(SDValue Op, SelectionDAG &DAG) const { 10292 10293 assert(Op.getOpcode() == ISD::ABS && "Should only be called for ISD::ABS"); 10294 10295 EVT VT = Op.getValueType(); 10296 assert(VT.isVector() && 10297 "Only set vector abs as custom, scalar abs shouldn't reach here!"); 10298 assert((VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 || 10299 VT == MVT::v16i8) && 10300 "Unexpected vector element type!"); 10301 assert((VT != MVT::v2i64 || Subtarget.hasP8Altivec()) && 10302 "Current subtarget doesn't support smax v2i64!"); 10303 10304 // For vector abs, it can be lowered to: 10305 // abs x 10306 // ==> 10307 // y = -x 10308 // smax(x, y) 10309 10310 SDLoc dl(Op); 10311 SDValue X = Op.getOperand(0); 10312 SDValue Zero = DAG.getConstant(0, dl, VT); 10313 SDValue Y = DAG.getNode(ISD::SUB, dl, VT, Zero, X); 10314 10315 // SMAX patch https://reviews.llvm.org/D47332 10316 // hasn't landed yet, so use intrinsic first here. 10317 // TODO: Should use SMAX directly once SMAX patch landed 10318 Intrinsic::ID BifID = Intrinsic::ppc_altivec_vmaxsw; 10319 if (VT == MVT::v2i64) 10320 BifID = Intrinsic::ppc_altivec_vmaxsd; 10321 else if (VT == MVT::v8i16) 10322 BifID = Intrinsic::ppc_altivec_vmaxsh; 10323 else if (VT == MVT::v16i8) 10324 BifID = Intrinsic::ppc_altivec_vmaxsb; 10325 10326 return BuildIntrinsicOp(BifID, X, Y, DAG, dl, VT); 10327 } 10328 10329 // Custom lowering for fpext vf32 to v2f64 10330 SDValue PPCTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const { 10331 10332 assert(Op.getOpcode() == ISD::FP_EXTEND && 10333 "Should only be called for ISD::FP_EXTEND"); 10334 10335 // We only want to custom lower an extend from v2f32 to v2f64. 10336 if (Op.getValueType() != MVT::v2f64 || 10337 Op.getOperand(0).getValueType() != MVT::v2f32) 10338 return SDValue(); 10339 10340 SDLoc dl(Op); 10341 SDValue Op0 = Op.getOperand(0); 10342 10343 switch (Op0.getOpcode()) { 10344 default: 10345 return SDValue(); 10346 case ISD::EXTRACT_SUBVECTOR: { 10347 assert(Op0.getNumOperands() == 2 && 10348 isa<ConstantSDNode>(Op0->getOperand(1)) && 10349 "Node should have 2 operands with second one being a constant!"); 10350 10351 if (Op0.getOperand(0).getValueType() != MVT::v4f32) 10352 return SDValue(); 10353 10354 // Custom lower is only done for high or low doubleword. 10355 int Idx = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue(); 10356 if (Idx % 2 != 0) 10357 return SDValue(); 10358 10359 // Since input is v4f32, at this point Idx is either 0 or 2. 10360 // Shift to get the doubleword position we want. 10361 int DWord = Idx >> 1; 10362 10363 // High and low word positions are different on little endian. 10364 if (Subtarget.isLittleEndian()) 10365 DWord ^= 0x1; 10366 10367 return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, 10368 Op0.getOperand(0), DAG.getConstant(DWord, dl, MVT::i32)); 10369 } 10370 case ISD::FADD: 10371 case ISD::FMUL: 10372 case ISD::FSUB: { 10373 SDValue NewLoad[2]; 10374 for (unsigned i = 0, ie = Op0.getNumOperands(); i != ie; ++i) { 10375 // Ensure both input are loads. 10376 SDValue LdOp = Op0.getOperand(i); 10377 if (LdOp.getOpcode() != ISD::LOAD) 10378 return SDValue(); 10379 // Generate new load node. 10380 LoadSDNode *LD = cast<LoadSDNode>(LdOp); 10381 SDValue LoadOps[] = {LD->getChain(), LD->getBasePtr()}; 10382 NewLoad[i] = DAG.getMemIntrinsicNode( 10383 PPCISD::LD_VSX_LH, dl, DAG.getVTList(MVT::v4f32, MVT::Other), LoadOps, 10384 LD->getMemoryVT(), LD->getMemOperand()); 10385 } 10386 SDValue NewOp = 10387 DAG.getNode(Op0.getOpcode(), SDLoc(Op0), MVT::v4f32, NewLoad[0], 10388 NewLoad[1], Op0.getNode()->getFlags()); 10389 return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, NewOp, 10390 DAG.getConstant(0, dl, MVT::i32)); 10391 } 10392 case ISD::LOAD: { 10393 LoadSDNode *LD = cast<LoadSDNode>(Op0); 10394 SDValue LoadOps[] = {LD->getChain(), LD->getBasePtr()}; 10395 SDValue NewLd = DAG.getMemIntrinsicNode( 10396 PPCISD::LD_VSX_LH, dl, DAG.getVTList(MVT::v4f32, MVT::Other), LoadOps, 10397 LD->getMemoryVT(), LD->getMemOperand()); 10398 return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, NewLd, 10399 DAG.getConstant(0, dl, MVT::i32)); 10400 } 10401 } 10402 llvm_unreachable("ERROR:Should return for all cases within swtich."); 10403 } 10404 10405 /// LowerOperation - Provide custom lowering hooks for some operations. 10406 /// 10407 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 10408 switch (Op.getOpcode()) { 10409 default: llvm_unreachable("Wasn't expecting to be able to lower this!"); 10410 case ISD::ConstantPool: return LowerConstantPool(Op, DAG); 10411 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG); 10412 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG); 10413 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG); 10414 case ISD::JumpTable: return LowerJumpTable(Op, DAG); 10415 case ISD::SETCC: return LowerSETCC(Op, DAG); 10416 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG); 10417 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG); 10418 10419 // Variable argument lowering. 10420 case ISD::VASTART: return LowerVASTART(Op, DAG); 10421 case ISD::VAARG: return LowerVAARG(Op, DAG); 10422 case ISD::VACOPY: return LowerVACOPY(Op, DAG); 10423 10424 case ISD::STACKRESTORE: return LowerSTACKRESTORE(Op, DAG); 10425 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG); 10426 case ISD::GET_DYNAMIC_AREA_OFFSET: 10427 return LowerGET_DYNAMIC_AREA_OFFSET(Op, DAG); 10428 10429 // Exception handling lowering. 10430 case ISD::EH_DWARF_CFA: return LowerEH_DWARF_CFA(Op, DAG); 10431 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG); 10432 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG); 10433 10434 case ISD::LOAD: return LowerLOAD(Op, DAG); 10435 case ISD::STORE: return LowerSTORE(Op, DAG); 10436 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG); 10437 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG); 10438 case ISD::FP_TO_UINT: 10439 case ISD::FP_TO_SINT: return LowerFP_TO_INT(Op, DAG, SDLoc(Op)); 10440 case ISD::UINT_TO_FP: 10441 case ISD::SINT_TO_FP: return LowerINT_TO_FP(Op, DAG); 10442 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG); 10443 10444 // Lower 64-bit shifts. 10445 case ISD::SHL_PARTS: return LowerSHL_PARTS(Op, DAG); 10446 case ISD::SRL_PARTS: return LowerSRL_PARTS(Op, DAG); 10447 case ISD::SRA_PARTS: return LowerSRA_PARTS(Op, DAG); 10448 10449 // Vector-related lowering. 10450 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG); 10451 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG); 10452 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG); 10453 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG); 10454 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG); 10455 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG); 10456 case ISD::MUL: return LowerMUL(Op, DAG); 10457 case ISD::ABS: return LowerABS(Op, DAG); 10458 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG); 10459 10460 // For counter-based loop handling. 10461 case ISD::INTRINSIC_W_CHAIN: return SDValue(); 10462 10463 case ISD::BITCAST: return LowerBITCAST(Op, DAG); 10464 10465 // Frame & Return address. 10466 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG); 10467 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG); 10468 10469 case ISD::INTRINSIC_VOID: 10470 return LowerINTRINSIC_VOID(Op, DAG); 10471 case ISD::SREM: 10472 case ISD::UREM: 10473 return LowerREM(Op, DAG); 10474 case ISD::BSWAP: 10475 return LowerBSWAP(Op, DAG); 10476 case ISD::ATOMIC_CMP_SWAP: 10477 return LowerATOMIC_CMP_SWAP(Op, DAG); 10478 } 10479 } 10480 10481 void PPCTargetLowering::ReplaceNodeResults(SDNode *N, 10482 SmallVectorImpl<SDValue>&Results, 10483 SelectionDAG &DAG) const { 10484 SDLoc dl(N); 10485 switch (N->getOpcode()) { 10486 default: 10487 llvm_unreachable("Do not know how to custom type legalize this operation!"); 10488 case ISD::READCYCLECOUNTER: { 10489 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other); 10490 SDValue RTB = DAG.getNode(PPCISD::READ_TIME_BASE, dl, VTs, N->getOperand(0)); 10491 10492 Results.push_back( 10493 DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, RTB, RTB.getValue(1))); 10494 Results.push_back(RTB.getValue(2)); 10495 break; 10496 } 10497 case ISD::INTRINSIC_W_CHAIN: { 10498 if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 10499 Intrinsic::loop_decrement) 10500 break; 10501 10502 assert(N->getValueType(0) == MVT::i1 && 10503 "Unexpected result type for CTR decrement intrinsic"); 10504 EVT SVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 10505 N->getValueType(0)); 10506 SDVTList VTs = DAG.getVTList(SVT, MVT::Other); 10507 SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0), 10508 N->getOperand(1)); 10509 10510 Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewInt)); 10511 Results.push_back(NewInt.getValue(1)); 10512 break; 10513 } 10514 case ISD::VAARG: { 10515 if (!Subtarget.isSVR4ABI() || Subtarget.isPPC64()) 10516 return; 10517 10518 EVT VT = N->getValueType(0); 10519 10520 if (VT == MVT::i64) { 10521 SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG); 10522 10523 Results.push_back(NewNode); 10524 Results.push_back(NewNode.getValue(1)); 10525 } 10526 return; 10527 } 10528 case ISD::FP_TO_SINT: 10529 case ISD::FP_TO_UINT: 10530 // LowerFP_TO_INT() can only handle f32 and f64. 10531 if (N->getOperand(0).getValueType() == MVT::ppcf128) 10532 return; 10533 Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl)); 10534 return; 10535 case ISD::TRUNCATE: { 10536 EVT TrgVT = N->getValueType(0); 10537 EVT OpVT = N->getOperand(0).getValueType(); 10538 if (TrgVT.isVector() && 10539 isOperationCustom(N->getOpcode(), TrgVT) && 10540 OpVT.getSizeInBits() <= 128 && 10541 isPowerOf2_32(OpVT.getVectorElementType().getSizeInBits())) 10542 Results.push_back(LowerTRUNCATEVector(SDValue(N, 0), DAG)); 10543 return; 10544 } 10545 case ISD::BITCAST: 10546 // Don't handle bitcast here. 10547 return; 10548 } 10549 } 10550 10551 //===----------------------------------------------------------------------===// 10552 // Other Lowering Code 10553 //===----------------------------------------------------------------------===// 10554 10555 static Instruction* callIntrinsic(IRBuilder<> &Builder, Intrinsic::ID Id) { 10556 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 10557 Function *Func = Intrinsic::getDeclaration(M, Id); 10558 return Builder.CreateCall(Func, {}); 10559 } 10560 10561 // The mappings for emitLeading/TrailingFence is taken from 10562 // http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html 10563 Instruction *PPCTargetLowering::emitLeadingFence(IRBuilder<> &Builder, 10564 Instruction *Inst, 10565 AtomicOrdering Ord) const { 10566 if (Ord == AtomicOrdering::SequentiallyConsistent) 10567 return callIntrinsic(Builder, Intrinsic::ppc_sync); 10568 if (isReleaseOrStronger(Ord)) 10569 return callIntrinsic(Builder, Intrinsic::ppc_lwsync); 10570 return nullptr; 10571 } 10572 10573 Instruction *PPCTargetLowering::emitTrailingFence(IRBuilder<> &Builder, 10574 Instruction *Inst, 10575 AtomicOrdering Ord) const { 10576 if (Inst->hasAtomicLoad() && isAcquireOrStronger(Ord)) { 10577 // See http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html and 10578 // http://www.rdrop.com/users/paulmck/scalability/paper/N2745r.2011.03.04a.html 10579 // and http://www.cl.cam.ac.uk/~pes20/cppppc/ for justification. 10580 if (isa<LoadInst>(Inst) && Subtarget.isPPC64()) 10581 return Builder.CreateCall( 10582 Intrinsic::getDeclaration( 10583 Builder.GetInsertBlock()->getParent()->getParent(), 10584 Intrinsic::ppc_cfence, {Inst->getType()}), 10585 {Inst}); 10586 // FIXME: Can use isync for rmw operation. 10587 return callIntrinsic(Builder, Intrinsic::ppc_lwsync); 10588 } 10589 return nullptr; 10590 } 10591 10592 MachineBasicBlock * 10593 PPCTargetLowering::EmitAtomicBinary(MachineInstr &MI, MachineBasicBlock *BB, 10594 unsigned AtomicSize, 10595 unsigned BinOpcode, 10596 unsigned CmpOpcode, 10597 unsigned CmpPred) const { 10598 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0. 10599 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 10600 10601 auto LoadMnemonic = PPC::LDARX; 10602 auto StoreMnemonic = PPC::STDCX; 10603 switch (AtomicSize) { 10604 default: 10605 llvm_unreachable("Unexpected size of atomic entity"); 10606 case 1: 10607 LoadMnemonic = PPC::LBARX; 10608 StoreMnemonic = PPC::STBCX; 10609 assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4"); 10610 break; 10611 case 2: 10612 LoadMnemonic = PPC::LHARX; 10613 StoreMnemonic = PPC::STHCX; 10614 assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4"); 10615 break; 10616 case 4: 10617 LoadMnemonic = PPC::LWARX; 10618 StoreMnemonic = PPC::STWCX; 10619 break; 10620 case 8: 10621 LoadMnemonic = PPC::LDARX; 10622 StoreMnemonic = PPC::STDCX; 10623 break; 10624 } 10625 10626 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 10627 MachineFunction *F = BB->getParent(); 10628 MachineFunction::iterator It = ++BB->getIterator(); 10629 10630 Register dest = MI.getOperand(0).getReg(); 10631 Register ptrA = MI.getOperand(1).getReg(); 10632 Register ptrB = MI.getOperand(2).getReg(); 10633 Register incr = MI.getOperand(3).getReg(); 10634 DebugLoc dl = MI.getDebugLoc(); 10635 10636 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB); 10637 MachineBasicBlock *loop2MBB = 10638 CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr; 10639 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 10640 F->insert(It, loopMBB); 10641 if (CmpOpcode) 10642 F->insert(It, loop2MBB); 10643 F->insert(It, exitMBB); 10644 exitMBB->splice(exitMBB->begin(), BB, 10645 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 10646 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 10647 10648 MachineRegisterInfo &RegInfo = F->getRegInfo(); 10649 Register TmpReg = (!BinOpcode) ? incr : 10650 RegInfo.createVirtualRegister( AtomicSize == 8 ? &PPC::G8RCRegClass 10651 : &PPC::GPRCRegClass); 10652 10653 // thisMBB: 10654 // ... 10655 // fallthrough --> loopMBB 10656 BB->addSuccessor(loopMBB); 10657 10658 // loopMBB: 10659 // l[wd]arx dest, ptr 10660 // add r0, dest, incr 10661 // st[wd]cx. r0, ptr 10662 // bne- loopMBB 10663 // fallthrough --> exitMBB 10664 10665 // For max/min... 10666 // loopMBB: 10667 // l[wd]arx dest, ptr 10668 // cmpl?[wd] incr, dest 10669 // bgt exitMBB 10670 // loop2MBB: 10671 // st[wd]cx. dest, ptr 10672 // bne- loopMBB 10673 // fallthrough --> exitMBB 10674 10675 BB = loopMBB; 10676 BuildMI(BB, dl, TII->get(LoadMnemonic), dest) 10677 .addReg(ptrA).addReg(ptrB); 10678 if (BinOpcode) 10679 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest); 10680 if (CmpOpcode) { 10681 // Signed comparisons of byte or halfword values must be sign-extended. 10682 if (CmpOpcode == PPC::CMPW && AtomicSize < 4) { 10683 Register ExtReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass); 10684 BuildMI(BB, dl, TII->get(AtomicSize == 1 ? PPC::EXTSB : PPC::EXTSH), 10685 ExtReg).addReg(dest); 10686 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0) 10687 .addReg(incr).addReg(ExtReg); 10688 } else 10689 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0) 10690 .addReg(incr).addReg(dest); 10691 10692 BuildMI(BB, dl, TII->get(PPC::BCC)) 10693 .addImm(CmpPred).addReg(PPC::CR0).addMBB(exitMBB); 10694 BB->addSuccessor(loop2MBB); 10695 BB->addSuccessor(exitMBB); 10696 BB = loop2MBB; 10697 } 10698 BuildMI(BB, dl, TII->get(StoreMnemonic)) 10699 .addReg(TmpReg).addReg(ptrA).addReg(ptrB); 10700 BuildMI(BB, dl, TII->get(PPC::BCC)) 10701 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB); 10702 BB->addSuccessor(loopMBB); 10703 BB->addSuccessor(exitMBB); 10704 10705 // exitMBB: 10706 // ... 10707 BB = exitMBB; 10708 return BB; 10709 } 10710 10711 MachineBasicBlock *PPCTargetLowering::EmitPartwordAtomicBinary( 10712 MachineInstr &MI, MachineBasicBlock *BB, 10713 bool is8bit, // operation 10714 unsigned BinOpcode, unsigned CmpOpcode, unsigned CmpPred) const { 10715 // If we support part-word atomic mnemonics, just use them 10716 if (Subtarget.hasPartwordAtomics()) 10717 return EmitAtomicBinary(MI, BB, is8bit ? 1 : 2, BinOpcode, CmpOpcode, 10718 CmpPred); 10719 10720 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0. 10721 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 10722 // In 64 bit mode we have to use 64 bits for addresses, even though the 10723 // lwarx/stwcx are 32 bits. With the 32-bit atomics we can use address 10724 // registers without caring whether they're 32 or 64, but here we're 10725 // doing actual arithmetic on the addresses. 10726 bool is64bit = Subtarget.isPPC64(); 10727 bool isLittleEndian = Subtarget.isLittleEndian(); 10728 unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO; 10729 10730 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 10731 MachineFunction *F = BB->getParent(); 10732 MachineFunction::iterator It = ++BB->getIterator(); 10733 10734 Register dest = MI.getOperand(0).getReg(); 10735 Register ptrA = MI.getOperand(1).getReg(); 10736 Register ptrB = MI.getOperand(2).getReg(); 10737 Register incr = MI.getOperand(3).getReg(); 10738 DebugLoc dl = MI.getDebugLoc(); 10739 10740 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB); 10741 MachineBasicBlock *loop2MBB = 10742 CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr; 10743 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 10744 F->insert(It, loopMBB); 10745 if (CmpOpcode) 10746 F->insert(It, loop2MBB); 10747 F->insert(It, exitMBB); 10748 exitMBB->splice(exitMBB->begin(), BB, 10749 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 10750 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 10751 10752 MachineRegisterInfo &RegInfo = F->getRegInfo(); 10753 const TargetRegisterClass *RC = 10754 is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 10755 const TargetRegisterClass *GPRC = &PPC::GPRCRegClass; 10756 10757 Register PtrReg = RegInfo.createVirtualRegister(RC); 10758 Register Shift1Reg = RegInfo.createVirtualRegister(GPRC); 10759 Register ShiftReg = 10760 isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC); 10761 Register Incr2Reg = RegInfo.createVirtualRegister(GPRC); 10762 Register MaskReg = RegInfo.createVirtualRegister(GPRC); 10763 Register Mask2Reg = RegInfo.createVirtualRegister(GPRC); 10764 Register Mask3Reg = RegInfo.createVirtualRegister(GPRC); 10765 Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC); 10766 Register Tmp3Reg = RegInfo.createVirtualRegister(GPRC); 10767 Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC); 10768 Register TmpDestReg = RegInfo.createVirtualRegister(GPRC); 10769 Register Ptr1Reg; 10770 Register TmpReg = 10771 (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(GPRC); 10772 10773 // thisMBB: 10774 // ... 10775 // fallthrough --> loopMBB 10776 BB->addSuccessor(loopMBB); 10777 10778 // The 4-byte load must be aligned, while a char or short may be 10779 // anywhere in the word. Hence all this nasty bookkeeping code. 10780 // add ptr1, ptrA, ptrB [copy if ptrA==0] 10781 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27] 10782 // xori shift, shift1, 24 [16] 10783 // rlwinm ptr, ptr1, 0, 0, 29 10784 // slw incr2, incr, shift 10785 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535] 10786 // slw mask, mask2, shift 10787 // loopMBB: 10788 // lwarx tmpDest, ptr 10789 // add tmp, tmpDest, incr2 10790 // andc tmp2, tmpDest, mask 10791 // and tmp3, tmp, mask 10792 // or tmp4, tmp3, tmp2 10793 // stwcx. tmp4, ptr 10794 // bne- loopMBB 10795 // fallthrough --> exitMBB 10796 // srw dest, tmpDest, shift 10797 if (ptrA != ZeroReg) { 10798 Ptr1Reg = RegInfo.createVirtualRegister(RC); 10799 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg) 10800 .addReg(ptrA) 10801 .addReg(ptrB); 10802 } else { 10803 Ptr1Reg = ptrB; 10804 } 10805 // We need use 32-bit subregister to avoid mismatch register class in 64-bit 10806 // mode. 10807 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg) 10808 .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0) 10809 .addImm(3) 10810 .addImm(27) 10811 .addImm(is8bit ? 28 : 27); 10812 if (!isLittleEndian) 10813 BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg) 10814 .addReg(Shift1Reg) 10815 .addImm(is8bit ? 24 : 16); 10816 if (is64bit) 10817 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg) 10818 .addReg(Ptr1Reg) 10819 .addImm(0) 10820 .addImm(61); 10821 else 10822 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg) 10823 .addReg(Ptr1Reg) 10824 .addImm(0) 10825 .addImm(0) 10826 .addImm(29); 10827 BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg).addReg(incr).addReg(ShiftReg); 10828 if (is8bit) 10829 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255); 10830 else { 10831 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0); 10832 BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg) 10833 .addReg(Mask3Reg) 10834 .addImm(65535); 10835 } 10836 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg) 10837 .addReg(Mask2Reg) 10838 .addReg(ShiftReg); 10839 10840 BB = loopMBB; 10841 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg) 10842 .addReg(ZeroReg) 10843 .addReg(PtrReg); 10844 if (BinOpcode) 10845 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg) 10846 .addReg(Incr2Reg) 10847 .addReg(TmpDestReg); 10848 BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg) 10849 .addReg(TmpDestReg) 10850 .addReg(MaskReg); 10851 BuildMI(BB, dl, TII->get(PPC::AND), Tmp3Reg).addReg(TmpReg).addReg(MaskReg); 10852 if (CmpOpcode) { 10853 // For unsigned comparisons, we can directly compare the shifted values. 10854 // For signed comparisons we shift and sign extend. 10855 Register SReg = RegInfo.createVirtualRegister(GPRC); 10856 BuildMI(BB, dl, TII->get(PPC::AND), SReg) 10857 .addReg(TmpDestReg) 10858 .addReg(MaskReg); 10859 unsigned ValueReg = SReg; 10860 unsigned CmpReg = Incr2Reg; 10861 if (CmpOpcode == PPC::CMPW) { 10862 ValueReg = RegInfo.createVirtualRegister(GPRC); 10863 BuildMI(BB, dl, TII->get(PPC::SRW), ValueReg) 10864 .addReg(SReg) 10865 .addReg(ShiftReg); 10866 Register ValueSReg = RegInfo.createVirtualRegister(GPRC); 10867 BuildMI(BB, dl, TII->get(is8bit ? PPC::EXTSB : PPC::EXTSH), ValueSReg) 10868 .addReg(ValueReg); 10869 ValueReg = ValueSReg; 10870 CmpReg = incr; 10871 } 10872 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0) 10873 .addReg(CmpReg) 10874 .addReg(ValueReg); 10875 BuildMI(BB, dl, TII->get(PPC::BCC)) 10876 .addImm(CmpPred) 10877 .addReg(PPC::CR0) 10878 .addMBB(exitMBB); 10879 BB->addSuccessor(loop2MBB); 10880 BB->addSuccessor(exitMBB); 10881 BB = loop2MBB; 10882 } 10883 BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg).addReg(Tmp3Reg).addReg(Tmp2Reg); 10884 BuildMI(BB, dl, TII->get(PPC::STWCX)) 10885 .addReg(Tmp4Reg) 10886 .addReg(ZeroReg) 10887 .addReg(PtrReg); 10888 BuildMI(BB, dl, TII->get(PPC::BCC)) 10889 .addImm(PPC::PRED_NE) 10890 .addReg(PPC::CR0) 10891 .addMBB(loopMBB); 10892 BB->addSuccessor(loopMBB); 10893 BB->addSuccessor(exitMBB); 10894 10895 // exitMBB: 10896 // ... 10897 BB = exitMBB; 10898 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest) 10899 .addReg(TmpDestReg) 10900 .addReg(ShiftReg); 10901 return BB; 10902 } 10903 10904 llvm::MachineBasicBlock * 10905 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr &MI, 10906 MachineBasicBlock *MBB) const { 10907 DebugLoc DL = MI.getDebugLoc(); 10908 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 10909 const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo(); 10910 10911 MachineFunction *MF = MBB->getParent(); 10912 MachineRegisterInfo &MRI = MF->getRegInfo(); 10913 10914 const BasicBlock *BB = MBB->getBasicBlock(); 10915 MachineFunction::iterator I = ++MBB->getIterator(); 10916 10917 Register DstReg = MI.getOperand(0).getReg(); 10918 const TargetRegisterClass *RC = MRI.getRegClass(DstReg); 10919 assert(TRI->isTypeLegalForClass(*RC, MVT::i32) && "Invalid destination!"); 10920 Register mainDstReg = MRI.createVirtualRegister(RC); 10921 Register restoreDstReg = MRI.createVirtualRegister(RC); 10922 10923 MVT PVT = getPointerTy(MF->getDataLayout()); 10924 assert((PVT == MVT::i64 || PVT == MVT::i32) && 10925 "Invalid Pointer Size!"); 10926 // For v = setjmp(buf), we generate 10927 // 10928 // thisMBB: 10929 // SjLjSetup mainMBB 10930 // bl mainMBB 10931 // v_restore = 1 10932 // b sinkMBB 10933 // 10934 // mainMBB: 10935 // buf[LabelOffset] = LR 10936 // v_main = 0 10937 // 10938 // sinkMBB: 10939 // v = phi(main, restore) 10940 // 10941 10942 MachineBasicBlock *thisMBB = MBB; 10943 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB); 10944 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB); 10945 MF->insert(I, mainMBB); 10946 MF->insert(I, sinkMBB); 10947 10948 MachineInstrBuilder MIB; 10949 10950 // Transfer the remainder of BB and its successor edges to sinkMBB. 10951 sinkMBB->splice(sinkMBB->begin(), MBB, 10952 std::next(MachineBasicBlock::iterator(MI)), MBB->end()); 10953 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB); 10954 10955 // Note that the structure of the jmp_buf used here is not compatible 10956 // with that used by libc, and is not designed to be. Specifically, it 10957 // stores only those 'reserved' registers that LLVM does not otherwise 10958 // understand how to spill. Also, by convention, by the time this 10959 // intrinsic is called, Clang has already stored the frame address in the 10960 // first slot of the buffer and stack address in the third. Following the 10961 // X86 target code, we'll store the jump address in the second slot. We also 10962 // need to save the TOC pointer (R2) to handle jumps between shared 10963 // libraries, and that will be stored in the fourth slot. The thread 10964 // identifier (R13) is not affected. 10965 10966 // thisMBB: 10967 const int64_t LabelOffset = 1 * PVT.getStoreSize(); 10968 const int64_t TOCOffset = 3 * PVT.getStoreSize(); 10969 const int64_t BPOffset = 4 * PVT.getStoreSize(); 10970 10971 // Prepare IP either in reg. 10972 const TargetRegisterClass *PtrRC = getRegClassFor(PVT); 10973 Register LabelReg = MRI.createVirtualRegister(PtrRC); 10974 Register BufReg = MI.getOperand(1).getReg(); 10975 10976 if (Subtarget.is64BitELFABI()) { 10977 setUsesTOCBasePtr(*MBB->getParent()); 10978 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD)) 10979 .addReg(PPC::X2) 10980 .addImm(TOCOffset) 10981 .addReg(BufReg) 10982 .cloneMemRefs(MI); 10983 } 10984 10985 // Naked functions never have a base pointer, and so we use r1. For all 10986 // other functions, this decision must be delayed until during PEI. 10987 unsigned BaseReg; 10988 if (MF->getFunction().hasFnAttribute(Attribute::Naked)) 10989 BaseReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1; 10990 else 10991 BaseReg = Subtarget.isPPC64() ? PPC::BP8 : PPC::BP; 10992 10993 MIB = BuildMI(*thisMBB, MI, DL, 10994 TII->get(Subtarget.isPPC64() ? PPC::STD : PPC::STW)) 10995 .addReg(BaseReg) 10996 .addImm(BPOffset) 10997 .addReg(BufReg) 10998 .cloneMemRefs(MI); 10999 11000 // Setup 11001 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB); 11002 MIB.addRegMask(TRI->getNoPreservedMask()); 11003 11004 BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1); 11005 11006 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup)) 11007 .addMBB(mainMBB); 11008 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB); 11009 11010 thisMBB->addSuccessor(mainMBB, BranchProbability::getZero()); 11011 thisMBB->addSuccessor(sinkMBB, BranchProbability::getOne()); 11012 11013 // mainMBB: 11014 // mainDstReg = 0 11015 MIB = 11016 BuildMI(mainMBB, DL, 11017 TII->get(Subtarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg); 11018 11019 // Store IP 11020 if (Subtarget.isPPC64()) { 11021 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD)) 11022 .addReg(LabelReg) 11023 .addImm(LabelOffset) 11024 .addReg(BufReg); 11025 } else { 11026 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW)) 11027 .addReg(LabelReg) 11028 .addImm(LabelOffset) 11029 .addReg(BufReg); 11030 } 11031 MIB.cloneMemRefs(MI); 11032 11033 BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0); 11034 mainMBB->addSuccessor(sinkMBB); 11035 11036 // sinkMBB: 11037 BuildMI(*sinkMBB, sinkMBB->begin(), DL, 11038 TII->get(PPC::PHI), DstReg) 11039 .addReg(mainDstReg).addMBB(mainMBB) 11040 .addReg(restoreDstReg).addMBB(thisMBB); 11041 11042 MI.eraseFromParent(); 11043 return sinkMBB; 11044 } 11045 11046 MachineBasicBlock * 11047 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr &MI, 11048 MachineBasicBlock *MBB) const { 11049 DebugLoc DL = MI.getDebugLoc(); 11050 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 11051 11052 MachineFunction *MF = MBB->getParent(); 11053 MachineRegisterInfo &MRI = MF->getRegInfo(); 11054 11055 MVT PVT = getPointerTy(MF->getDataLayout()); 11056 assert((PVT == MVT::i64 || PVT == MVT::i32) && 11057 "Invalid Pointer Size!"); 11058 11059 const TargetRegisterClass *RC = 11060 (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 11061 Register Tmp = MRI.createVirtualRegister(RC); 11062 // Since FP is only updated here but NOT referenced, it's treated as GPR. 11063 unsigned FP = (PVT == MVT::i64) ? PPC::X31 : PPC::R31; 11064 unsigned SP = (PVT == MVT::i64) ? PPC::X1 : PPC::R1; 11065 unsigned BP = 11066 (PVT == MVT::i64) 11067 ? PPC::X30 11068 : (Subtarget.isSVR4ABI() && isPositionIndependent() ? PPC::R29 11069 : PPC::R30); 11070 11071 MachineInstrBuilder MIB; 11072 11073 const int64_t LabelOffset = 1 * PVT.getStoreSize(); 11074 const int64_t SPOffset = 2 * PVT.getStoreSize(); 11075 const int64_t TOCOffset = 3 * PVT.getStoreSize(); 11076 const int64_t BPOffset = 4 * PVT.getStoreSize(); 11077 11078 Register BufReg = MI.getOperand(0).getReg(); 11079 11080 // Reload FP (the jumped-to function may not have had a 11081 // frame pointer, and if so, then its r31 will be restored 11082 // as necessary). 11083 if (PVT == MVT::i64) { 11084 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP) 11085 .addImm(0) 11086 .addReg(BufReg); 11087 } else { 11088 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP) 11089 .addImm(0) 11090 .addReg(BufReg); 11091 } 11092 MIB.cloneMemRefs(MI); 11093 11094 // Reload IP 11095 if (PVT == MVT::i64) { 11096 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp) 11097 .addImm(LabelOffset) 11098 .addReg(BufReg); 11099 } else { 11100 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp) 11101 .addImm(LabelOffset) 11102 .addReg(BufReg); 11103 } 11104 MIB.cloneMemRefs(MI); 11105 11106 // Reload SP 11107 if (PVT == MVT::i64) { 11108 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP) 11109 .addImm(SPOffset) 11110 .addReg(BufReg); 11111 } else { 11112 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP) 11113 .addImm(SPOffset) 11114 .addReg(BufReg); 11115 } 11116 MIB.cloneMemRefs(MI); 11117 11118 // Reload BP 11119 if (PVT == MVT::i64) { 11120 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP) 11121 .addImm(BPOffset) 11122 .addReg(BufReg); 11123 } else { 11124 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP) 11125 .addImm(BPOffset) 11126 .addReg(BufReg); 11127 } 11128 MIB.cloneMemRefs(MI); 11129 11130 // Reload TOC 11131 if (PVT == MVT::i64 && Subtarget.isSVR4ABI()) { 11132 setUsesTOCBasePtr(*MBB->getParent()); 11133 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2) 11134 .addImm(TOCOffset) 11135 .addReg(BufReg) 11136 .cloneMemRefs(MI); 11137 } 11138 11139 // Jump 11140 BuildMI(*MBB, MI, DL, 11141 TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp); 11142 BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR)); 11143 11144 MI.eraseFromParent(); 11145 return MBB; 11146 } 11147 11148 MachineBasicBlock * 11149 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI, 11150 MachineBasicBlock *BB) const { 11151 if (MI.getOpcode() == TargetOpcode::STACKMAP || 11152 MI.getOpcode() == TargetOpcode::PATCHPOINT) { 11153 if (Subtarget.is64BitELFABI() && 11154 MI.getOpcode() == TargetOpcode::PATCHPOINT) { 11155 // Call lowering should have added an r2 operand to indicate a dependence 11156 // on the TOC base pointer value. It can't however, because there is no 11157 // way to mark the dependence as implicit there, and so the stackmap code 11158 // will confuse it with a regular operand. Instead, add the dependence 11159 // here. 11160 MI.addOperand(MachineOperand::CreateReg(PPC::X2, false, true)); 11161 } 11162 11163 return emitPatchPoint(MI, BB); 11164 } 11165 11166 if (MI.getOpcode() == PPC::EH_SjLj_SetJmp32 || 11167 MI.getOpcode() == PPC::EH_SjLj_SetJmp64) { 11168 return emitEHSjLjSetJmp(MI, BB); 11169 } else if (MI.getOpcode() == PPC::EH_SjLj_LongJmp32 || 11170 MI.getOpcode() == PPC::EH_SjLj_LongJmp64) { 11171 return emitEHSjLjLongJmp(MI, BB); 11172 } 11173 11174 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 11175 11176 // To "insert" these instructions we actually have to insert their 11177 // control-flow patterns. 11178 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 11179 MachineFunction::iterator It = ++BB->getIterator(); 11180 11181 MachineFunction *F = BB->getParent(); 11182 11183 if (MI.getOpcode() == PPC::SELECT_CC_I4 || 11184 MI.getOpcode() == PPC::SELECT_CC_I8 || MI.getOpcode() == PPC::SELECT_I4 || 11185 MI.getOpcode() == PPC::SELECT_I8) { 11186 SmallVector<MachineOperand, 2> Cond; 11187 if (MI.getOpcode() == PPC::SELECT_CC_I4 || 11188 MI.getOpcode() == PPC::SELECT_CC_I8) 11189 Cond.push_back(MI.getOperand(4)); 11190 else 11191 Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET)); 11192 Cond.push_back(MI.getOperand(1)); 11193 11194 DebugLoc dl = MI.getDebugLoc(); 11195 TII->insertSelect(*BB, MI, dl, MI.getOperand(0).getReg(), Cond, 11196 MI.getOperand(2).getReg(), MI.getOperand(3).getReg()); 11197 } else if (MI.getOpcode() == PPC::SELECT_CC_F4 || 11198 MI.getOpcode() == PPC::SELECT_CC_F8 || 11199 MI.getOpcode() == PPC::SELECT_CC_F16 || 11200 MI.getOpcode() == PPC::SELECT_CC_QFRC || 11201 MI.getOpcode() == PPC::SELECT_CC_QSRC || 11202 MI.getOpcode() == PPC::SELECT_CC_QBRC || 11203 MI.getOpcode() == PPC::SELECT_CC_VRRC || 11204 MI.getOpcode() == PPC::SELECT_CC_VSFRC || 11205 MI.getOpcode() == PPC::SELECT_CC_VSSRC || 11206 MI.getOpcode() == PPC::SELECT_CC_VSRC || 11207 MI.getOpcode() == PPC::SELECT_CC_SPE4 || 11208 MI.getOpcode() == PPC::SELECT_CC_SPE || 11209 MI.getOpcode() == PPC::SELECT_F4 || 11210 MI.getOpcode() == PPC::SELECT_F8 || 11211 MI.getOpcode() == PPC::SELECT_F16 || 11212 MI.getOpcode() == PPC::SELECT_QFRC || 11213 MI.getOpcode() == PPC::SELECT_QSRC || 11214 MI.getOpcode() == PPC::SELECT_QBRC || 11215 MI.getOpcode() == PPC::SELECT_SPE || 11216 MI.getOpcode() == PPC::SELECT_SPE4 || 11217 MI.getOpcode() == PPC::SELECT_VRRC || 11218 MI.getOpcode() == PPC::SELECT_VSFRC || 11219 MI.getOpcode() == PPC::SELECT_VSSRC || 11220 MI.getOpcode() == PPC::SELECT_VSRC) { 11221 // The incoming instruction knows the destination vreg to set, the 11222 // condition code register to branch on, the true/false values to 11223 // select between, and a branch opcode to use. 11224 11225 // thisMBB: 11226 // ... 11227 // TrueVal = ... 11228 // cmpTY ccX, r1, r2 11229 // bCC copy1MBB 11230 // fallthrough --> copy0MBB 11231 MachineBasicBlock *thisMBB = BB; 11232 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB); 11233 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 11234 DebugLoc dl = MI.getDebugLoc(); 11235 F->insert(It, copy0MBB); 11236 F->insert(It, sinkMBB); 11237 11238 // Transfer the remainder of BB and its successor edges to sinkMBB. 11239 sinkMBB->splice(sinkMBB->begin(), BB, 11240 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 11241 sinkMBB->transferSuccessorsAndUpdatePHIs(BB); 11242 11243 // Next, add the true and fallthrough blocks as its successors. 11244 BB->addSuccessor(copy0MBB); 11245 BB->addSuccessor(sinkMBB); 11246 11247 if (MI.getOpcode() == PPC::SELECT_I4 || MI.getOpcode() == PPC::SELECT_I8 || 11248 MI.getOpcode() == PPC::SELECT_F4 || MI.getOpcode() == PPC::SELECT_F8 || 11249 MI.getOpcode() == PPC::SELECT_F16 || 11250 MI.getOpcode() == PPC::SELECT_SPE4 || 11251 MI.getOpcode() == PPC::SELECT_SPE || 11252 MI.getOpcode() == PPC::SELECT_QFRC || 11253 MI.getOpcode() == PPC::SELECT_QSRC || 11254 MI.getOpcode() == PPC::SELECT_QBRC || 11255 MI.getOpcode() == PPC::SELECT_VRRC || 11256 MI.getOpcode() == PPC::SELECT_VSFRC || 11257 MI.getOpcode() == PPC::SELECT_VSSRC || 11258 MI.getOpcode() == PPC::SELECT_VSRC) { 11259 BuildMI(BB, dl, TII->get(PPC::BC)) 11260 .addReg(MI.getOperand(1).getReg()) 11261 .addMBB(sinkMBB); 11262 } else { 11263 unsigned SelectPred = MI.getOperand(4).getImm(); 11264 BuildMI(BB, dl, TII->get(PPC::BCC)) 11265 .addImm(SelectPred) 11266 .addReg(MI.getOperand(1).getReg()) 11267 .addMBB(sinkMBB); 11268 } 11269 11270 // copy0MBB: 11271 // %FalseValue = ... 11272 // # fallthrough to sinkMBB 11273 BB = copy0MBB; 11274 11275 // Update machine-CFG edges 11276 BB->addSuccessor(sinkMBB); 11277 11278 // sinkMBB: 11279 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ] 11280 // ... 11281 BB = sinkMBB; 11282 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::PHI), MI.getOperand(0).getReg()) 11283 .addReg(MI.getOperand(3).getReg()) 11284 .addMBB(copy0MBB) 11285 .addReg(MI.getOperand(2).getReg()) 11286 .addMBB(thisMBB); 11287 } else if (MI.getOpcode() == PPC::ReadTB) { 11288 // To read the 64-bit time-base register on a 32-bit target, we read the 11289 // two halves. Should the counter have wrapped while it was being read, we 11290 // need to try again. 11291 // ... 11292 // readLoop: 11293 // mfspr Rx,TBU # load from TBU 11294 // mfspr Ry,TB # load from TB 11295 // mfspr Rz,TBU # load from TBU 11296 // cmpw crX,Rx,Rz # check if 'old'='new' 11297 // bne readLoop # branch if they're not equal 11298 // ... 11299 11300 MachineBasicBlock *readMBB = F->CreateMachineBasicBlock(LLVM_BB); 11301 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 11302 DebugLoc dl = MI.getDebugLoc(); 11303 F->insert(It, readMBB); 11304 F->insert(It, sinkMBB); 11305 11306 // Transfer the remainder of BB and its successor edges to sinkMBB. 11307 sinkMBB->splice(sinkMBB->begin(), BB, 11308 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 11309 sinkMBB->transferSuccessorsAndUpdatePHIs(BB); 11310 11311 BB->addSuccessor(readMBB); 11312 BB = readMBB; 11313 11314 MachineRegisterInfo &RegInfo = F->getRegInfo(); 11315 Register ReadAgainReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass); 11316 Register LoReg = MI.getOperand(0).getReg(); 11317 Register HiReg = MI.getOperand(1).getReg(); 11318 11319 BuildMI(BB, dl, TII->get(PPC::MFSPR), HiReg).addImm(269); 11320 BuildMI(BB, dl, TII->get(PPC::MFSPR), LoReg).addImm(268); 11321 BuildMI(BB, dl, TII->get(PPC::MFSPR), ReadAgainReg).addImm(269); 11322 11323 Register CmpReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass); 11324 11325 BuildMI(BB, dl, TII->get(PPC::CMPW), CmpReg) 11326 .addReg(HiReg) 11327 .addReg(ReadAgainReg); 11328 BuildMI(BB, dl, TII->get(PPC::BCC)) 11329 .addImm(PPC::PRED_NE) 11330 .addReg(CmpReg) 11331 .addMBB(readMBB); 11332 11333 BB->addSuccessor(readMBB); 11334 BB->addSuccessor(sinkMBB); 11335 } else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I8) 11336 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4); 11337 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I16) 11338 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4); 11339 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I32) 11340 BB = EmitAtomicBinary(MI, BB, 4, PPC::ADD4); 11341 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I64) 11342 BB = EmitAtomicBinary(MI, BB, 8, PPC::ADD8); 11343 11344 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I8) 11345 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND); 11346 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I16) 11347 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND); 11348 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I32) 11349 BB = EmitAtomicBinary(MI, BB, 4, PPC::AND); 11350 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I64) 11351 BB = EmitAtomicBinary(MI, BB, 8, PPC::AND8); 11352 11353 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I8) 11354 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR); 11355 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I16) 11356 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR); 11357 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I32) 11358 BB = EmitAtomicBinary(MI, BB, 4, PPC::OR); 11359 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I64) 11360 BB = EmitAtomicBinary(MI, BB, 8, PPC::OR8); 11361 11362 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I8) 11363 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR); 11364 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I16) 11365 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR); 11366 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I32) 11367 BB = EmitAtomicBinary(MI, BB, 4, PPC::XOR); 11368 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I64) 11369 BB = EmitAtomicBinary(MI, BB, 8, PPC::XOR8); 11370 11371 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I8) 11372 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::NAND); 11373 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I16) 11374 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::NAND); 11375 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I32) 11376 BB = EmitAtomicBinary(MI, BB, 4, PPC::NAND); 11377 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I64) 11378 BB = EmitAtomicBinary(MI, BB, 8, PPC::NAND8); 11379 11380 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I8) 11381 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF); 11382 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I16) 11383 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF); 11384 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I32) 11385 BB = EmitAtomicBinary(MI, BB, 4, PPC::SUBF); 11386 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I64) 11387 BB = EmitAtomicBinary(MI, BB, 8, PPC::SUBF8); 11388 11389 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I8) 11390 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_GE); 11391 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I16) 11392 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_GE); 11393 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I32) 11394 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_GE); 11395 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I64) 11396 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_GE); 11397 11398 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I8) 11399 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_LE); 11400 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I16) 11401 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_LE); 11402 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I32) 11403 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_LE); 11404 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I64) 11405 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_LE); 11406 11407 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I8) 11408 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_GE); 11409 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I16) 11410 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_GE); 11411 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I32) 11412 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_GE); 11413 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I64) 11414 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_GE); 11415 11416 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I8) 11417 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_LE); 11418 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I16) 11419 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_LE); 11420 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I32) 11421 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_LE); 11422 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I64) 11423 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_LE); 11424 11425 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I8) 11426 BB = EmitPartwordAtomicBinary(MI, BB, true, 0); 11427 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I16) 11428 BB = EmitPartwordAtomicBinary(MI, BB, false, 0); 11429 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I32) 11430 BB = EmitAtomicBinary(MI, BB, 4, 0); 11431 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I64) 11432 BB = EmitAtomicBinary(MI, BB, 8, 0); 11433 else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 || 11434 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64 || 11435 (Subtarget.hasPartwordAtomics() && 11436 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8) || 11437 (Subtarget.hasPartwordAtomics() && 11438 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16)) { 11439 bool is64bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64; 11440 11441 auto LoadMnemonic = PPC::LDARX; 11442 auto StoreMnemonic = PPC::STDCX; 11443 switch (MI.getOpcode()) { 11444 default: 11445 llvm_unreachable("Compare and swap of unknown size"); 11446 case PPC::ATOMIC_CMP_SWAP_I8: 11447 LoadMnemonic = PPC::LBARX; 11448 StoreMnemonic = PPC::STBCX; 11449 assert(Subtarget.hasPartwordAtomics() && "No support partword atomics."); 11450 break; 11451 case PPC::ATOMIC_CMP_SWAP_I16: 11452 LoadMnemonic = PPC::LHARX; 11453 StoreMnemonic = PPC::STHCX; 11454 assert(Subtarget.hasPartwordAtomics() && "No support partword atomics."); 11455 break; 11456 case PPC::ATOMIC_CMP_SWAP_I32: 11457 LoadMnemonic = PPC::LWARX; 11458 StoreMnemonic = PPC::STWCX; 11459 break; 11460 case PPC::ATOMIC_CMP_SWAP_I64: 11461 LoadMnemonic = PPC::LDARX; 11462 StoreMnemonic = PPC::STDCX; 11463 break; 11464 } 11465 Register dest = MI.getOperand(0).getReg(); 11466 Register ptrA = MI.getOperand(1).getReg(); 11467 Register ptrB = MI.getOperand(2).getReg(); 11468 Register oldval = MI.getOperand(3).getReg(); 11469 Register newval = MI.getOperand(4).getReg(); 11470 DebugLoc dl = MI.getDebugLoc(); 11471 11472 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB); 11473 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB); 11474 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB); 11475 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 11476 F->insert(It, loop1MBB); 11477 F->insert(It, loop2MBB); 11478 F->insert(It, midMBB); 11479 F->insert(It, exitMBB); 11480 exitMBB->splice(exitMBB->begin(), BB, 11481 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 11482 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 11483 11484 // thisMBB: 11485 // ... 11486 // fallthrough --> loopMBB 11487 BB->addSuccessor(loop1MBB); 11488 11489 // loop1MBB: 11490 // l[bhwd]arx dest, ptr 11491 // cmp[wd] dest, oldval 11492 // bne- midMBB 11493 // loop2MBB: 11494 // st[bhwd]cx. newval, ptr 11495 // bne- loopMBB 11496 // b exitBB 11497 // midMBB: 11498 // st[bhwd]cx. dest, ptr 11499 // exitBB: 11500 BB = loop1MBB; 11501 BuildMI(BB, dl, TII->get(LoadMnemonic), dest).addReg(ptrA).addReg(ptrB); 11502 BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0) 11503 .addReg(oldval) 11504 .addReg(dest); 11505 BuildMI(BB, dl, TII->get(PPC::BCC)) 11506 .addImm(PPC::PRED_NE) 11507 .addReg(PPC::CR0) 11508 .addMBB(midMBB); 11509 BB->addSuccessor(loop2MBB); 11510 BB->addSuccessor(midMBB); 11511 11512 BB = loop2MBB; 11513 BuildMI(BB, dl, TII->get(StoreMnemonic)) 11514 .addReg(newval) 11515 .addReg(ptrA) 11516 .addReg(ptrB); 11517 BuildMI(BB, dl, TII->get(PPC::BCC)) 11518 .addImm(PPC::PRED_NE) 11519 .addReg(PPC::CR0) 11520 .addMBB(loop1MBB); 11521 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB); 11522 BB->addSuccessor(loop1MBB); 11523 BB->addSuccessor(exitMBB); 11524 11525 BB = midMBB; 11526 BuildMI(BB, dl, TII->get(StoreMnemonic)) 11527 .addReg(dest) 11528 .addReg(ptrA) 11529 .addReg(ptrB); 11530 BB->addSuccessor(exitMBB); 11531 11532 // exitMBB: 11533 // ... 11534 BB = exitMBB; 11535 } else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 || 11536 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) { 11537 // We must use 64-bit registers for addresses when targeting 64-bit, 11538 // since we're actually doing arithmetic on them. Other registers 11539 // can be 32-bit. 11540 bool is64bit = Subtarget.isPPC64(); 11541 bool isLittleEndian = Subtarget.isLittleEndian(); 11542 bool is8bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8; 11543 11544 Register dest = MI.getOperand(0).getReg(); 11545 Register ptrA = MI.getOperand(1).getReg(); 11546 Register ptrB = MI.getOperand(2).getReg(); 11547 Register oldval = MI.getOperand(3).getReg(); 11548 Register newval = MI.getOperand(4).getReg(); 11549 DebugLoc dl = MI.getDebugLoc(); 11550 11551 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB); 11552 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB); 11553 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB); 11554 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 11555 F->insert(It, loop1MBB); 11556 F->insert(It, loop2MBB); 11557 F->insert(It, midMBB); 11558 F->insert(It, exitMBB); 11559 exitMBB->splice(exitMBB->begin(), BB, 11560 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 11561 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 11562 11563 MachineRegisterInfo &RegInfo = F->getRegInfo(); 11564 const TargetRegisterClass *RC = 11565 is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 11566 const TargetRegisterClass *GPRC = &PPC::GPRCRegClass; 11567 11568 Register PtrReg = RegInfo.createVirtualRegister(RC); 11569 Register Shift1Reg = RegInfo.createVirtualRegister(GPRC); 11570 Register ShiftReg = 11571 isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC); 11572 Register NewVal2Reg = RegInfo.createVirtualRegister(GPRC); 11573 Register NewVal3Reg = RegInfo.createVirtualRegister(GPRC); 11574 Register OldVal2Reg = RegInfo.createVirtualRegister(GPRC); 11575 Register OldVal3Reg = RegInfo.createVirtualRegister(GPRC); 11576 Register MaskReg = RegInfo.createVirtualRegister(GPRC); 11577 Register Mask2Reg = RegInfo.createVirtualRegister(GPRC); 11578 Register Mask3Reg = RegInfo.createVirtualRegister(GPRC); 11579 Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC); 11580 Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC); 11581 Register TmpDestReg = RegInfo.createVirtualRegister(GPRC); 11582 Register Ptr1Reg; 11583 Register TmpReg = RegInfo.createVirtualRegister(GPRC); 11584 Register ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO; 11585 // thisMBB: 11586 // ... 11587 // fallthrough --> loopMBB 11588 BB->addSuccessor(loop1MBB); 11589 11590 // The 4-byte load must be aligned, while a char or short may be 11591 // anywhere in the word. Hence all this nasty bookkeeping code. 11592 // add ptr1, ptrA, ptrB [copy if ptrA==0] 11593 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27] 11594 // xori shift, shift1, 24 [16] 11595 // rlwinm ptr, ptr1, 0, 0, 29 11596 // slw newval2, newval, shift 11597 // slw oldval2, oldval,shift 11598 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535] 11599 // slw mask, mask2, shift 11600 // and newval3, newval2, mask 11601 // and oldval3, oldval2, mask 11602 // loop1MBB: 11603 // lwarx tmpDest, ptr 11604 // and tmp, tmpDest, mask 11605 // cmpw tmp, oldval3 11606 // bne- midMBB 11607 // loop2MBB: 11608 // andc tmp2, tmpDest, mask 11609 // or tmp4, tmp2, newval3 11610 // stwcx. tmp4, ptr 11611 // bne- loop1MBB 11612 // b exitBB 11613 // midMBB: 11614 // stwcx. tmpDest, ptr 11615 // exitBB: 11616 // srw dest, tmpDest, shift 11617 if (ptrA != ZeroReg) { 11618 Ptr1Reg = RegInfo.createVirtualRegister(RC); 11619 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg) 11620 .addReg(ptrA) 11621 .addReg(ptrB); 11622 } else { 11623 Ptr1Reg = ptrB; 11624 } 11625 11626 // We need use 32-bit subregister to avoid mismatch register class in 64-bit 11627 // mode. 11628 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg) 11629 .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0) 11630 .addImm(3) 11631 .addImm(27) 11632 .addImm(is8bit ? 28 : 27); 11633 if (!isLittleEndian) 11634 BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg) 11635 .addReg(Shift1Reg) 11636 .addImm(is8bit ? 24 : 16); 11637 if (is64bit) 11638 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg) 11639 .addReg(Ptr1Reg) 11640 .addImm(0) 11641 .addImm(61); 11642 else 11643 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg) 11644 .addReg(Ptr1Reg) 11645 .addImm(0) 11646 .addImm(0) 11647 .addImm(29); 11648 BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg) 11649 .addReg(newval) 11650 .addReg(ShiftReg); 11651 BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg) 11652 .addReg(oldval) 11653 .addReg(ShiftReg); 11654 if (is8bit) 11655 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255); 11656 else { 11657 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0); 11658 BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg) 11659 .addReg(Mask3Reg) 11660 .addImm(65535); 11661 } 11662 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg) 11663 .addReg(Mask2Reg) 11664 .addReg(ShiftReg); 11665 BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg) 11666 .addReg(NewVal2Reg) 11667 .addReg(MaskReg); 11668 BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg) 11669 .addReg(OldVal2Reg) 11670 .addReg(MaskReg); 11671 11672 BB = loop1MBB; 11673 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg) 11674 .addReg(ZeroReg) 11675 .addReg(PtrReg); 11676 BuildMI(BB, dl, TII->get(PPC::AND), TmpReg) 11677 .addReg(TmpDestReg) 11678 .addReg(MaskReg); 11679 BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0) 11680 .addReg(TmpReg) 11681 .addReg(OldVal3Reg); 11682 BuildMI(BB, dl, TII->get(PPC::BCC)) 11683 .addImm(PPC::PRED_NE) 11684 .addReg(PPC::CR0) 11685 .addMBB(midMBB); 11686 BB->addSuccessor(loop2MBB); 11687 BB->addSuccessor(midMBB); 11688 11689 BB = loop2MBB; 11690 BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg) 11691 .addReg(TmpDestReg) 11692 .addReg(MaskReg); 11693 BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg) 11694 .addReg(Tmp2Reg) 11695 .addReg(NewVal3Reg); 11696 BuildMI(BB, dl, TII->get(PPC::STWCX)) 11697 .addReg(Tmp4Reg) 11698 .addReg(ZeroReg) 11699 .addReg(PtrReg); 11700 BuildMI(BB, dl, TII->get(PPC::BCC)) 11701 .addImm(PPC::PRED_NE) 11702 .addReg(PPC::CR0) 11703 .addMBB(loop1MBB); 11704 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB); 11705 BB->addSuccessor(loop1MBB); 11706 BB->addSuccessor(exitMBB); 11707 11708 BB = midMBB; 11709 BuildMI(BB, dl, TII->get(PPC::STWCX)) 11710 .addReg(TmpDestReg) 11711 .addReg(ZeroReg) 11712 .addReg(PtrReg); 11713 BB->addSuccessor(exitMBB); 11714 11715 // exitMBB: 11716 // ... 11717 BB = exitMBB; 11718 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest) 11719 .addReg(TmpReg) 11720 .addReg(ShiftReg); 11721 } else if (MI.getOpcode() == PPC::FADDrtz) { 11722 // This pseudo performs an FADD with rounding mode temporarily forced 11723 // to round-to-zero. We emit this via custom inserter since the FPSCR 11724 // is not modeled at the SelectionDAG level. 11725 Register Dest = MI.getOperand(0).getReg(); 11726 Register Src1 = MI.getOperand(1).getReg(); 11727 Register Src2 = MI.getOperand(2).getReg(); 11728 DebugLoc dl = MI.getDebugLoc(); 11729 11730 MachineRegisterInfo &RegInfo = F->getRegInfo(); 11731 Register MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass); 11732 11733 // Save FPSCR value. 11734 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg); 11735 11736 // Set rounding mode to round-to-zero. 11737 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1)).addImm(31); 11738 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0)).addImm(30); 11739 11740 // Perform addition. 11741 BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest).addReg(Src1).addReg(Src2); 11742 11743 // Restore FPSCR value. 11744 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSFb)).addImm(1).addReg(MFFSReg); 11745 } else if (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT || 11746 MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT || 11747 MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8 || 11748 MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT8) { 11749 unsigned Opcode = (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8 || 11750 MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT8) 11751 ? PPC::ANDI8_rec 11752 : PPC::ANDI_rec; 11753 bool IsEQ = (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT || 11754 MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8); 11755 11756 MachineRegisterInfo &RegInfo = F->getRegInfo(); 11757 Register Dest = RegInfo.createVirtualRegister( 11758 Opcode == PPC::ANDI_rec ? &PPC::GPRCRegClass : &PPC::G8RCRegClass); 11759 11760 DebugLoc Dl = MI.getDebugLoc(); 11761 BuildMI(*BB, MI, Dl, TII->get(Opcode), Dest) 11762 .addReg(MI.getOperand(1).getReg()) 11763 .addImm(1); 11764 BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY), 11765 MI.getOperand(0).getReg()) 11766 .addReg(IsEQ ? PPC::CR0EQ : PPC::CR0GT); 11767 } else if (MI.getOpcode() == PPC::TCHECK_RET) { 11768 DebugLoc Dl = MI.getDebugLoc(); 11769 MachineRegisterInfo &RegInfo = F->getRegInfo(); 11770 Register CRReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass); 11771 BuildMI(*BB, MI, Dl, TII->get(PPC::TCHECK), CRReg); 11772 BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY), 11773 MI.getOperand(0).getReg()) 11774 .addReg(CRReg); 11775 } else if (MI.getOpcode() == PPC::TBEGIN_RET) { 11776 DebugLoc Dl = MI.getDebugLoc(); 11777 unsigned Imm = MI.getOperand(1).getImm(); 11778 BuildMI(*BB, MI, Dl, TII->get(PPC::TBEGIN)).addImm(Imm); 11779 BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY), 11780 MI.getOperand(0).getReg()) 11781 .addReg(PPC::CR0EQ); 11782 } else if (MI.getOpcode() == PPC::SETRNDi) { 11783 DebugLoc dl = MI.getDebugLoc(); 11784 Register OldFPSCRReg = MI.getOperand(0).getReg(); 11785 11786 // Save FPSCR value. 11787 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg); 11788 11789 // The floating point rounding mode is in the bits 62:63 of FPCSR, and has 11790 // the following settings: 11791 // 00 Round to nearest 11792 // 01 Round to 0 11793 // 10 Round to +inf 11794 // 11 Round to -inf 11795 11796 // When the operand is immediate, using the two least significant bits of 11797 // the immediate to set the bits 62:63 of FPSCR. 11798 unsigned Mode = MI.getOperand(1).getImm(); 11799 BuildMI(*BB, MI, dl, TII->get((Mode & 1) ? PPC::MTFSB1 : PPC::MTFSB0)) 11800 .addImm(31); 11801 11802 BuildMI(*BB, MI, dl, TII->get((Mode & 2) ? PPC::MTFSB1 : PPC::MTFSB0)) 11803 .addImm(30); 11804 } else if (MI.getOpcode() == PPC::SETRND) { 11805 DebugLoc dl = MI.getDebugLoc(); 11806 11807 // Copy register from F8RCRegClass::SrcReg to G8RCRegClass::DestReg 11808 // or copy register from G8RCRegClass::SrcReg to F8RCRegClass::DestReg. 11809 // If the target doesn't have DirectMove, we should use stack to do the 11810 // conversion, because the target doesn't have the instructions like mtvsrd 11811 // or mfvsrd to do this conversion directly. 11812 auto copyRegFromG8RCOrF8RC = [&] (unsigned DestReg, unsigned SrcReg) { 11813 if (Subtarget.hasDirectMove()) { 11814 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), DestReg) 11815 .addReg(SrcReg); 11816 } else { 11817 // Use stack to do the register copy. 11818 unsigned StoreOp = PPC::STD, LoadOp = PPC::LFD; 11819 MachineRegisterInfo &RegInfo = F->getRegInfo(); 11820 const TargetRegisterClass *RC = RegInfo.getRegClass(SrcReg); 11821 if (RC == &PPC::F8RCRegClass) { 11822 // Copy register from F8RCRegClass to G8RCRegclass. 11823 assert((RegInfo.getRegClass(DestReg) == &PPC::G8RCRegClass) && 11824 "Unsupported RegClass."); 11825 11826 StoreOp = PPC::STFD; 11827 LoadOp = PPC::LD; 11828 } else { 11829 // Copy register from G8RCRegClass to F8RCRegclass. 11830 assert((RegInfo.getRegClass(SrcReg) == &PPC::G8RCRegClass) && 11831 (RegInfo.getRegClass(DestReg) == &PPC::F8RCRegClass) && 11832 "Unsupported RegClass."); 11833 } 11834 11835 MachineFrameInfo &MFI = F->getFrameInfo(); 11836 int FrameIdx = MFI.CreateStackObject(8, 8, false); 11837 11838 MachineMemOperand *MMOStore = F->getMachineMemOperand( 11839 MachinePointerInfo::getFixedStack(*F, FrameIdx, 0), 11840 MachineMemOperand::MOStore, MFI.getObjectSize(FrameIdx), 11841 MFI.getObjectAlignment(FrameIdx)); 11842 11843 // Store the SrcReg into the stack. 11844 BuildMI(*BB, MI, dl, TII->get(StoreOp)) 11845 .addReg(SrcReg) 11846 .addImm(0) 11847 .addFrameIndex(FrameIdx) 11848 .addMemOperand(MMOStore); 11849 11850 MachineMemOperand *MMOLoad = F->getMachineMemOperand( 11851 MachinePointerInfo::getFixedStack(*F, FrameIdx, 0), 11852 MachineMemOperand::MOLoad, MFI.getObjectSize(FrameIdx), 11853 MFI.getObjectAlignment(FrameIdx)); 11854 11855 // Load from the stack where SrcReg is stored, and save to DestReg, 11856 // so we have done the RegClass conversion from RegClass::SrcReg to 11857 // RegClass::DestReg. 11858 BuildMI(*BB, MI, dl, TII->get(LoadOp), DestReg) 11859 .addImm(0) 11860 .addFrameIndex(FrameIdx) 11861 .addMemOperand(MMOLoad); 11862 } 11863 }; 11864 11865 Register OldFPSCRReg = MI.getOperand(0).getReg(); 11866 11867 // Save FPSCR value. 11868 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg); 11869 11870 // When the operand is gprc register, use two least significant bits of the 11871 // register and mtfsf instruction to set the bits 62:63 of FPSCR. 11872 // 11873 // copy OldFPSCRTmpReg, OldFPSCRReg 11874 // (INSERT_SUBREG ExtSrcReg, (IMPLICIT_DEF ImDefReg), SrcOp, 1) 11875 // rldimi NewFPSCRTmpReg, ExtSrcReg, OldFPSCRReg, 0, 62 11876 // copy NewFPSCRReg, NewFPSCRTmpReg 11877 // mtfsf 255, NewFPSCRReg 11878 MachineOperand SrcOp = MI.getOperand(1); 11879 MachineRegisterInfo &RegInfo = F->getRegInfo(); 11880 Register OldFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 11881 11882 copyRegFromG8RCOrF8RC(OldFPSCRTmpReg, OldFPSCRReg); 11883 11884 Register ImDefReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 11885 Register ExtSrcReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 11886 11887 // The first operand of INSERT_SUBREG should be a register which has 11888 // subregisters, we only care about its RegClass, so we should use an 11889 // IMPLICIT_DEF register. 11890 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::IMPLICIT_DEF), ImDefReg); 11891 BuildMI(*BB, MI, dl, TII->get(PPC::INSERT_SUBREG), ExtSrcReg) 11892 .addReg(ImDefReg) 11893 .add(SrcOp) 11894 .addImm(1); 11895 11896 Register NewFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 11897 BuildMI(*BB, MI, dl, TII->get(PPC::RLDIMI), NewFPSCRTmpReg) 11898 .addReg(OldFPSCRTmpReg) 11899 .addReg(ExtSrcReg) 11900 .addImm(0) 11901 .addImm(62); 11902 11903 Register NewFPSCRReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass); 11904 copyRegFromG8RCOrF8RC(NewFPSCRReg, NewFPSCRTmpReg); 11905 11906 // The mask 255 means that put the 32:63 bits of NewFPSCRReg to the 32:63 11907 // bits of FPSCR. 11908 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSF)) 11909 .addImm(255) 11910 .addReg(NewFPSCRReg) 11911 .addImm(0) 11912 .addImm(0); 11913 } else { 11914 llvm_unreachable("Unexpected instr type to insert"); 11915 } 11916 11917 MI.eraseFromParent(); // The pseudo instruction is gone now. 11918 return BB; 11919 } 11920 11921 //===----------------------------------------------------------------------===// 11922 // Target Optimization Hooks 11923 //===----------------------------------------------------------------------===// 11924 11925 static int getEstimateRefinementSteps(EVT VT, const PPCSubtarget &Subtarget) { 11926 // For the estimates, convergence is quadratic, so we essentially double the 11927 // number of digits correct after every iteration. For both FRE and FRSQRTE, 11928 // the minimum architected relative accuracy is 2^-5. When hasRecipPrec(), 11929 // this is 2^-14. IEEE float has 23 digits and double has 52 digits. 11930 int RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3; 11931 if (VT.getScalarType() == MVT::f64) 11932 RefinementSteps++; 11933 return RefinementSteps; 11934 } 11935 11936 SDValue PPCTargetLowering::getSqrtEstimate(SDValue Operand, SelectionDAG &DAG, 11937 int Enabled, int &RefinementSteps, 11938 bool &UseOneConstNR, 11939 bool Reciprocal) const { 11940 EVT VT = Operand.getValueType(); 11941 if ((VT == MVT::f32 && Subtarget.hasFRSQRTES()) || 11942 (VT == MVT::f64 && Subtarget.hasFRSQRTE()) || 11943 (VT == MVT::v4f32 && Subtarget.hasAltivec()) || 11944 (VT == MVT::v2f64 && Subtarget.hasVSX()) || 11945 (VT == MVT::v4f32 && Subtarget.hasQPX()) || 11946 (VT == MVT::v4f64 && Subtarget.hasQPX())) { 11947 if (RefinementSteps == ReciprocalEstimate::Unspecified) 11948 RefinementSteps = getEstimateRefinementSteps(VT, Subtarget); 11949 11950 // The Newton-Raphson computation with a single constant does not provide 11951 // enough accuracy on some CPUs. 11952 UseOneConstNR = !Subtarget.needsTwoConstNR(); 11953 return DAG.getNode(PPCISD::FRSQRTE, SDLoc(Operand), VT, Operand); 11954 } 11955 return SDValue(); 11956 } 11957 11958 SDValue PPCTargetLowering::getRecipEstimate(SDValue Operand, SelectionDAG &DAG, 11959 int Enabled, 11960 int &RefinementSteps) const { 11961 EVT VT = Operand.getValueType(); 11962 if ((VT == MVT::f32 && Subtarget.hasFRES()) || 11963 (VT == MVT::f64 && Subtarget.hasFRE()) || 11964 (VT == MVT::v4f32 && Subtarget.hasAltivec()) || 11965 (VT == MVT::v2f64 && Subtarget.hasVSX()) || 11966 (VT == MVT::v4f32 && Subtarget.hasQPX()) || 11967 (VT == MVT::v4f64 && Subtarget.hasQPX())) { 11968 if (RefinementSteps == ReciprocalEstimate::Unspecified) 11969 RefinementSteps = getEstimateRefinementSteps(VT, Subtarget); 11970 return DAG.getNode(PPCISD::FRE, SDLoc(Operand), VT, Operand); 11971 } 11972 return SDValue(); 11973 } 11974 11975 unsigned PPCTargetLowering::combineRepeatedFPDivisors() const { 11976 // Note: This functionality is used only when unsafe-fp-math is enabled, and 11977 // on cores with reciprocal estimates (which are used when unsafe-fp-math is 11978 // enabled for division), this functionality is redundant with the default 11979 // combiner logic (once the division -> reciprocal/multiply transformation 11980 // has taken place). As a result, this matters more for older cores than for 11981 // newer ones. 11982 11983 // Combine multiple FDIVs with the same divisor into multiple FMULs by the 11984 // reciprocal if there are two or more FDIVs (for embedded cores with only 11985 // one FP pipeline) for three or more FDIVs (for generic OOO cores). 11986 switch (Subtarget.getCPUDirective()) { 11987 default: 11988 return 3; 11989 case PPC::DIR_440: 11990 case PPC::DIR_A2: 11991 case PPC::DIR_E500: 11992 case PPC::DIR_E500mc: 11993 case PPC::DIR_E5500: 11994 return 2; 11995 } 11996 } 11997 11998 // isConsecutiveLSLoc needs to work even if all adds have not yet been 11999 // collapsed, and so we need to look through chains of them. 12000 static void getBaseWithConstantOffset(SDValue Loc, SDValue &Base, 12001 int64_t& Offset, SelectionDAG &DAG) { 12002 if (DAG.isBaseWithConstantOffset(Loc)) { 12003 Base = Loc.getOperand(0); 12004 Offset += cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue(); 12005 12006 // The base might itself be a base plus an offset, and if so, accumulate 12007 // that as well. 12008 getBaseWithConstantOffset(Loc.getOperand(0), Base, Offset, DAG); 12009 } 12010 } 12011 12012 static bool isConsecutiveLSLoc(SDValue Loc, EVT VT, LSBaseSDNode *Base, 12013 unsigned Bytes, int Dist, 12014 SelectionDAG &DAG) { 12015 if (VT.getSizeInBits() / 8 != Bytes) 12016 return false; 12017 12018 SDValue BaseLoc = Base->getBasePtr(); 12019 if (Loc.getOpcode() == ISD::FrameIndex) { 12020 if (BaseLoc.getOpcode() != ISD::FrameIndex) 12021 return false; 12022 const MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 12023 int FI = cast<FrameIndexSDNode>(Loc)->getIndex(); 12024 int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex(); 12025 int FS = MFI.getObjectSize(FI); 12026 int BFS = MFI.getObjectSize(BFI); 12027 if (FS != BFS || FS != (int)Bytes) return false; 12028 return MFI.getObjectOffset(FI) == (MFI.getObjectOffset(BFI) + Dist*Bytes); 12029 } 12030 12031 SDValue Base1 = Loc, Base2 = BaseLoc; 12032 int64_t Offset1 = 0, Offset2 = 0; 12033 getBaseWithConstantOffset(Loc, Base1, Offset1, DAG); 12034 getBaseWithConstantOffset(BaseLoc, Base2, Offset2, DAG); 12035 if (Base1 == Base2 && Offset1 == (Offset2 + Dist * Bytes)) 12036 return true; 12037 12038 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 12039 const GlobalValue *GV1 = nullptr; 12040 const GlobalValue *GV2 = nullptr; 12041 Offset1 = 0; 12042 Offset2 = 0; 12043 bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1); 12044 bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2); 12045 if (isGA1 && isGA2 && GV1 == GV2) 12046 return Offset1 == (Offset2 + Dist*Bytes); 12047 return false; 12048 } 12049 12050 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does 12051 // not enforce equality of the chain operands. 12052 static bool isConsecutiveLS(SDNode *N, LSBaseSDNode *Base, 12053 unsigned Bytes, int Dist, 12054 SelectionDAG &DAG) { 12055 if (LSBaseSDNode *LS = dyn_cast<LSBaseSDNode>(N)) { 12056 EVT VT = LS->getMemoryVT(); 12057 SDValue Loc = LS->getBasePtr(); 12058 return isConsecutiveLSLoc(Loc, VT, Base, Bytes, Dist, DAG); 12059 } 12060 12061 if (N->getOpcode() == ISD::INTRINSIC_W_CHAIN) { 12062 EVT VT; 12063 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 12064 default: return false; 12065 case Intrinsic::ppc_qpx_qvlfd: 12066 case Intrinsic::ppc_qpx_qvlfda: 12067 VT = MVT::v4f64; 12068 break; 12069 case Intrinsic::ppc_qpx_qvlfs: 12070 case Intrinsic::ppc_qpx_qvlfsa: 12071 VT = MVT::v4f32; 12072 break; 12073 case Intrinsic::ppc_qpx_qvlfcd: 12074 case Intrinsic::ppc_qpx_qvlfcda: 12075 VT = MVT::v2f64; 12076 break; 12077 case Intrinsic::ppc_qpx_qvlfcs: 12078 case Intrinsic::ppc_qpx_qvlfcsa: 12079 VT = MVT::v2f32; 12080 break; 12081 case Intrinsic::ppc_qpx_qvlfiwa: 12082 case Intrinsic::ppc_qpx_qvlfiwz: 12083 case Intrinsic::ppc_altivec_lvx: 12084 case Intrinsic::ppc_altivec_lvxl: 12085 case Intrinsic::ppc_vsx_lxvw4x: 12086 case Intrinsic::ppc_vsx_lxvw4x_be: 12087 VT = MVT::v4i32; 12088 break; 12089 case Intrinsic::ppc_vsx_lxvd2x: 12090 case Intrinsic::ppc_vsx_lxvd2x_be: 12091 VT = MVT::v2f64; 12092 break; 12093 case Intrinsic::ppc_altivec_lvebx: 12094 VT = MVT::i8; 12095 break; 12096 case Intrinsic::ppc_altivec_lvehx: 12097 VT = MVT::i16; 12098 break; 12099 case Intrinsic::ppc_altivec_lvewx: 12100 VT = MVT::i32; 12101 break; 12102 } 12103 12104 return isConsecutiveLSLoc(N->getOperand(2), VT, Base, Bytes, Dist, DAG); 12105 } 12106 12107 if (N->getOpcode() == ISD::INTRINSIC_VOID) { 12108 EVT VT; 12109 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 12110 default: return false; 12111 case Intrinsic::ppc_qpx_qvstfd: 12112 case Intrinsic::ppc_qpx_qvstfda: 12113 VT = MVT::v4f64; 12114 break; 12115 case Intrinsic::ppc_qpx_qvstfs: 12116 case Intrinsic::ppc_qpx_qvstfsa: 12117 VT = MVT::v4f32; 12118 break; 12119 case Intrinsic::ppc_qpx_qvstfcd: 12120 case Intrinsic::ppc_qpx_qvstfcda: 12121 VT = MVT::v2f64; 12122 break; 12123 case Intrinsic::ppc_qpx_qvstfcs: 12124 case Intrinsic::ppc_qpx_qvstfcsa: 12125 VT = MVT::v2f32; 12126 break; 12127 case Intrinsic::ppc_qpx_qvstfiw: 12128 case Intrinsic::ppc_qpx_qvstfiwa: 12129 case Intrinsic::ppc_altivec_stvx: 12130 case Intrinsic::ppc_altivec_stvxl: 12131 case Intrinsic::ppc_vsx_stxvw4x: 12132 VT = MVT::v4i32; 12133 break; 12134 case Intrinsic::ppc_vsx_stxvd2x: 12135 VT = MVT::v2f64; 12136 break; 12137 case Intrinsic::ppc_vsx_stxvw4x_be: 12138 VT = MVT::v4i32; 12139 break; 12140 case Intrinsic::ppc_vsx_stxvd2x_be: 12141 VT = MVT::v2f64; 12142 break; 12143 case Intrinsic::ppc_altivec_stvebx: 12144 VT = MVT::i8; 12145 break; 12146 case Intrinsic::ppc_altivec_stvehx: 12147 VT = MVT::i16; 12148 break; 12149 case Intrinsic::ppc_altivec_stvewx: 12150 VT = MVT::i32; 12151 break; 12152 } 12153 12154 return isConsecutiveLSLoc(N->getOperand(3), VT, Base, Bytes, Dist, DAG); 12155 } 12156 12157 return false; 12158 } 12159 12160 // Return true is there is a nearyby consecutive load to the one provided 12161 // (regardless of alignment). We search up and down the chain, looking though 12162 // token factors and other loads (but nothing else). As a result, a true result 12163 // indicates that it is safe to create a new consecutive load adjacent to the 12164 // load provided. 12165 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) { 12166 SDValue Chain = LD->getChain(); 12167 EVT VT = LD->getMemoryVT(); 12168 12169 SmallSet<SDNode *, 16> LoadRoots; 12170 SmallVector<SDNode *, 8> Queue(1, Chain.getNode()); 12171 SmallSet<SDNode *, 16> Visited; 12172 12173 // First, search up the chain, branching to follow all token-factor operands. 12174 // If we find a consecutive load, then we're done, otherwise, record all 12175 // nodes just above the top-level loads and token factors. 12176 while (!Queue.empty()) { 12177 SDNode *ChainNext = Queue.pop_back_val(); 12178 if (!Visited.insert(ChainNext).second) 12179 continue; 12180 12181 if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(ChainNext)) { 12182 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG)) 12183 return true; 12184 12185 if (!Visited.count(ChainLD->getChain().getNode())) 12186 Queue.push_back(ChainLD->getChain().getNode()); 12187 } else if (ChainNext->getOpcode() == ISD::TokenFactor) { 12188 for (const SDUse &O : ChainNext->ops()) 12189 if (!Visited.count(O.getNode())) 12190 Queue.push_back(O.getNode()); 12191 } else 12192 LoadRoots.insert(ChainNext); 12193 } 12194 12195 // Second, search down the chain, starting from the top-level nodes recorded 12196 // in the first phase. These top-level nodes are the nodes just above all 12197 // loads and token factors. Starting with their uses, recursively look though 12198 // all loads (just the chain uses) and token factors to find a consecutive 12199 // load. 12200 Visited.clear(); 12201 Queue.clear(); 12202 12203 for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(), 12204 IE = LoadRoots.end(); I != IE; ++I) { 12205 Queue.push_back(*I); 12206 12207 while (!Queue.empty()) { 12208 SDNode *LoadRoot = Queue.pop_back_val(); 12209 if (!Visited.insert(LoadRoot).second) 12210 continue; 12211 12212 if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(LoadRoot)) 12213 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG)) 12214 return true; 12215 12216 for (SDNode::use_iterator UI = LoadRoot->use_begin(), 12217 UE = LoadRoot->use_end(); UI != UE; ++UI) 12218 if (((isa<MemSDNode>(*UI) && 12219 cast<MemSDNode>(*UI)->getChain().getNode() == LoadRoot) || 12220 UI->getOpcode() == ISD::TokenFactor) && !Visited.count(*UI)) 12221 Queue.push_back(*UI); 12222 } 12223 } 12224 12225 return false; 12226 } 12227 12228 /// This function is called when we have proved that a SETCC node can be replaced 12229 /// by subtraction (and other supporting instructions) so that the result of 12230 /// comparison is kept in a GPR instead of CR. This function is purely for 12231 /// codegen purposes and has some flags to guide the codegen process. 12232 static SDValue generateEquivalentSub(SDNode *N, int Size, bool Complement, 12233 bool Swap, SDLoc &DL, SelectionDAG &DAG) { 12234 assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected."); 12235 12236 // Zero extend the operands to the largest legal integer. Originally, they 12237 // must be of a strictly smaller size. 12238 auto Op0 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(0), 12239 DAG.getConstant(Size, DL, MVT::i32)); 12240 auto Op1 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1), 12241 DAG.getConstant(Size, DL, MVT::i32)); 12242 12243 // Swap if needed. Depends on the condition code. 12244 if (Swap) 12245 std::swap(Op0, Op1); 12246 12247 // Subtract extended integers. 12248 auto SubNode = DAG.getNode(ISD::SUB, DL, MVT::i64, Op0, Op1); 12249 12250 // Move the sign bit to the least significant position and zero out the rest. 12251 // Now the least significant bit carries the result of original comparison. 12252 auto Shifted = DAG.getNode(ISD::SRL, DL, MVT::i64, SubNode, 12253 DAG.getConstant(Size - 1, DL, MVT::i32)); 12254 auto Final = Shifted; 12255 12256 // Complement the result if needed. Based on the condition code. 12257 if (Complement) 12258 Final = DAG.getNode(ISD::XOR, DL, MVT::i64, Shifted, 12259 DAG.getConstant(1, DL, MVT::i64)); 12260 12261 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Final); 12262 } 12263 12264 SDValue PPCTargetLowering::ConvertSETCCToSubtract(SDNode *N, 12265 DAGCombinerInfo &DCI) const { 12266 assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected."); 12267 12268 SelectionDAG &DAG = DCI.DAG; 12269 SDLoc DL(N); 12270 12271 // Size of integers being compared has a critical role in the following 12272 // analysis, so we prefer to do this when all types are legal. 12273 if (!DCI.isAfterLegalizeDAG()) 12274 return SDValue(); 12275 12276 // If all users of SETCC extend its value to a legal integer type 12277 // then we replace SETCC with a subtraction 12278 for (SDNode::use_iterator UI = N->use_begin(), 12279 UE = N->use_end(); UI != UE; ++UI) { 12280 if (UI->getOpcode() != ISD::ZERO_EXTEND) 12281 return SDValue(); 12282 } 12283 12284 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 12285 auto OpSize = N->getOperand(0).getValueSizeInBits(); 12286 12287 unsigned Size = DAG.getDataLayout().getLargestLegalIntTypeSizeInBits(); 12288 12289 if (OpSize < Size) { 12290 switch (CC) { 12291 default: break; 12292 case ISD::SETULT: 12293 return generateEquivalentSub(N, Size, false, false, DL, DAG); 12294 case ISD::SETULE: 12295 return generateEquivalentSub(N, Size, true, true, DL, DAG); 12296 case ISD::SETUGT: 12297 return generateEquivalentSub(N, Size, false, true, DL, DAG); 12298 case ISD::SETUGE: 12299 return generateEquivalentSub(N, Size, true, false, DL, DAG); 12300 } 12301 } 12302 12303 return SDValue(); 12304 } 12305 12306 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N, 12307 DAGCombinerInfo &DCI) const { 12308 SelectionDAG &DAG = DCI.DAG; 12309 SDLoc dl(N); 12310 12311 assert(Subtarget.useCRBits() && "Expecting to be tracking CR bits"); 12312 // If we're tracking CR bits, we need to be careful that we don't have: 12313 // trunc(binary-ops(zext(x), zext(y))) 12314 // or 12315 // trunc(binary-ops(binary-ops(zext(x), zext(y)), ...) 12316 // such that we're unnecessarily moving things into GPRs when it would be 12317 // better to keep them in CR bits. 12318 12319 // Note that trunc here can be an actual i1 trunc, or can be the effective 12320 // truncation that comes from a setcc or select_cc. 12321 if (N->getOpcode() == ISD::TRUNCATE && 12322 N->getValueType(0) != MVT::i1) 12323 return SDValue(); 12324 12325 if (N->getOperand(0).getValueType() != MVT::i32 && 12326 N->getOperand(0).getValueType() != MVT::i64) 12327 return SDValue(); 12328 12329 if (N->getOpcode() == ISD::SETCC || 12330 N->getOpcode() == ISD::SELECT_CC) { 12331 // If we're looking at a comparison, then we need to make sure that the 12332 // high bits (all except for the first) don't matter the result. 12333 ISD::CondCode CC = 12334 cast<CondCodeSDNode>(N->getOperand( 12335 N->getOpcode() == ISD::SETCC ? 2 : 4))->get(); 12336 unsigned OpBits = N->getOperand(0).getValueSizeInBits(); 12337 12338 if (ISD::isSignedIntSetCC(CC)) { 12339 if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits || 12340 DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits) 12341 return SDValue(); 12342 } else if (ISD::isUnsignedIntSetCC(CC)) { 12343 if (!DAG.MaskedValueIsZero(N->getOperand(0), 12344 APInt::getHighBitsSet(OpBits, OpBits-1)) || 12345 !DAG.MaskedValueIsZero(N->getOperand(1), 12346 APInt::getHighBitsSet(OpBits, OpBits-1))) 12347 return (N->getOpcode() == ISD::SETCC ? ConvertSETCCToSubtract(N, DCI) 12348 : SDValue()); 12349 } else { 12350 // This is neither a signed nor an unsigned comparison, just make sure 12351 // that the high bits are equal. 12352 KnownBits Op1Known = DAG.computeKnownBits(N->getOperand(0)); 12353 KnownBits Op2Known = DAG.computeKnownBits(N->getOperand(1)); 12354 12355 // We don't really care about what is known about the first bit (if 12356 // anything), so clear it in all masks prior to comparing them. 12357 Op1Known.Zero.clearBit(0); Op1Known.One.clearBit(0); 12358 Op2Known.Zero.clearBit(0); Op2Known.One.clearBit(0); 12359 12360 if (Op1Known.Zero != Op2Known.Zero || Op1Known.One != Op2Known.One) 12361 return SDValue(); 12362 } 12363 } 12364 12365 // We now know that the higher-order bits are irrelevant, we just need to 12366 // make sure that all of the intermediate operations are bit operations, and 12367 // all inputs are extensions. 12368 if (N->getOperand(0).getOpcode() != ISD::AND && 12369 N->getOperand(0).getOpcode() != ISD::OR && 12370 N->getOperand(0).getOpcode() != ISD::XOR && 12371 N->getOperand(0).getOpcode() != ISD::SELECT && 12372 N->getOperand(0).getOpcode() != ISD::SELECT_CC && 12373 N->getOperand(0).getOpcode() != ISD::TRUNCATE && 12374 N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND && 12375 N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND && 12376 N->getOperand(0).getOpcode() != ISD::ANY_EXTEND) 12377 return SDValue(); 12378 12379 if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) && 12380 N->getOperand(1).getOpcode() != ISD::AND && 12381 N->getOperand(1).getOpcode() != ISD::OR && 12382 N->getOperand(1).getOpcode() != ISD::XOR && 12383 N->getOperand(1).getOpcode() != ISD::SELECT && 12384 N->getOperand(1).getOpcode() != ISD::SELECT_CC && 12385 N->getOperand(1).getOpcode() != ISD::TRUNCATE && 12386 N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND && 12387 N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND && 12388 N->getOperand(1).getOpcode() != ISD::ANY_EXTEND) 12389 return SDValue(); 12390 12391 SmallVector<SDValue, 4> Inputs; 12392 SmallVector<SDValue, 8> BinOps, PromOps; 12393 SmallPtrSet<SDNode *, 16> Visited; 12394 12395 for (unsigned i = 0; i < 2; ++i) { 12396 if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND || 12397 N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND || 12398 N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) && 12399 N->getOperand(i).getOperand(0).getValueType() == MVT::i1) || 12400 isa<ConstantSDNode>(N->getOperand(i))) 12401 Inputs.push_back(N->getOperand(i)); 12402 else 12403 BinOps.push_back(N->getOperand(i)); 12404 12405 if (N->getOpcode() == ISD::TRUNCATE) 12406 break; 12407 } 12408 12409 // Visit all inputs, collect all binary operations (and, or, xor and 12410 // select) that are all fed by extensions. 12411 while (!BinOps.empty()) { 12412 SDValue BinOp = BinOps.back(); 12413 BinOps.pop_back(); 12414 12415 if (!Visited.insert(BinOp.getNode()).second) 12416 continue; 12417 12418 PromOps.push_back(BinOp); 12419 12420 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) { 12421 // The condition of the select is not promoted. 12422 if (BinOp.getOpcode() == ISD::SELECT && i == 0) 12423 continue; 12424 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3) 12425 continue; 12426 12427 if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND || 12428 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND || 12429 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) && 12430 BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) || 12431 isa<ConstantSDNode>(BinOp.getOperand(i))) { 12432 Inputs.push_back(BinOp.getOperand(i)); 12433 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND || 12434 BinOp.getOperand(i).getOpcode() == ISD::OR || 12435 BinOp.getOperand(i).getOpcode() == ISD::XOR || 12436 BinOp.getOperand(i).getOpcode() == ISD::SELECT || 12437 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC || 12438 BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE || 12439 BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND || 12440 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND || 12441 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) { 12442 BinOps.push_back(BinOp.getOperand(i)); 12443 } else { 12444 // We have an input that is not an extension or another binary 12445 // operation; we'll abort this transformation. 12446 return SDValue(); 12447 } 12448 } 12449 } 12450 12451 // Make sure that this is a self-contained cluster of operations (which 12452 // is not quite the same thing as saying that everything has only one 12453 // use). 12454 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 12455 if (isa<ConstantSDNode>(Inputs[i])) 12456 continue; 12457 12458 for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(), 12459 UE = Inputs[i].getNode()->use_end(); 12460 UI != UE; ++UI) { 12461 SDNode *User = *UI; 12462 if (User != N && !Visited.count(User)) 12463 return SDValue(); 12464 12465 // Make sure that we're not going to promote the non-output-value 12466 // operand(s) or SELECT or SELECT_CC. 12467 // FIXME: Although we could sometimes handle this, and it does occur in 12468 // practice that one of the condition inputs to the select is also one of 12469 // the outputs, we currently can't deal with this. 12470 if (User->getOpcode() == ISD::SELECT) { 12471 if (User->getOperand(0) == Inputs[i]) 12472 return SDValue(); 12473 } else if (User->getOpcode() == ISD::SELECT_CC) { 12474 if (User->getOperand(0) == Inputs[i] || 12475 User->getOperand(1) == Inputs[i]) 12476 return SDValue(); 12477 } 12478 } 12479 } 12480 12481 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) { 12482 for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(), 12483 UE = PromOps[i].getNode()->use_end(); 12484 UI != UE; ++UI) { 12485 SDNode *User = *UI; 12486 if (User != N && !Visited.count(User)) 12487 return SDValue(); 12488 12489 // Make sure that we're not going to promote the non-output-value 12490 // operand(s) or SELECT or SELECT_CC. 12491 // FIXME: Although we could sometimes handle this, and it does occur in 12492 // practice that one of the condition inputs to the select is also one of 12493 // the outputs, we currently can't deal with this. 12494 if (User->getOpcode() == ISD::SELECT) { 12495 if (User->getOperand(0) == PromOps[i]) 12496 return SDValue(); 12497 } else if (User->getOpcode() == ISD::SELECT_CC) { 12498 if (User->getOperand(0) == PromOps[i] || 12499 User->getOperand(1) == PromOps[i]) 12500 return SDValue(); 12501 } 12502 } 12503 } 12504 12505 // Replace all inputs with the extension operand. 12506 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 12507 // Constants may have users outside the cluster of to-be-promoted nodes, 12508 // and so we need to replace those as we do the promotions. 12509 if (isa<ConstantSDNode>(Inputs[i])) 12510 continue; 12511 else 12512 DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0)); 12513 } 12514 12515 std::list<HandleSDNode> PromOpHandles; 12516 for (auto &PromOp : PromOps) 12517 PromOpHandles.emplace_back(PromOp); 12518 12519 // Replace all operations (these are all the same, but have a different 12520 // (i1) return type). DAG.getNode will validate that the types of 12521 // a binary operator match, so go through the list in reverse so that 12522 // we've likely promoted both operands first. Any intermediate truncations or 12523 // extensions disappear. 12524 while (!PromOpHandles.empty()) { 12525 SDValue PromOp = PromOpHandles.back().getValue(); 12526 PromOpHandles.pop_back(); 12527 12528 if (PromOp.getOpcode() == ISD::TRUNCATE || 12529 PromOp.getOpcode() == ISD::SIGN_EXTEND || 12530 PromOp.getOpcode() == ISD::ZERO_EXTEND || 12531 PromOp.getOpcode() == ISD::ANY_EXTEND) { 12532 if (!isa<ConstantSDNode>(PromOp.getOperand(0)) && 12533 PromOp.getOperand(0).getValueType() != MVT::i1) { 12534 // The operand is not yet ready (see comment below). 12535 PromOpHandles.emplace_front(PromOp); 12536 continue; 12537 } 12538 12539 SDValue RepValue = PromOp.getOperand(0); 12540 if (isa<ConstantSDNode>(RepValue)) 12541 RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue); 12542 12543 DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue); 12544 continue; 12545 } 12546 12547 unsigned C; 12548 switch (PromOp.getOpcode()) { 12549 default: C = 0; break; 12550 case ISD::SELECT: C = 1; break; 12551 case ISD::SELECT_CC: C = 2; break; 12552 } 12553 12554 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) && 12555 PromOp.getOperand(C).getValueType() != MVT::i1) || 12556 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) && 12557 PromOp.getOperand(C+1).getValueType() != MVT::i1)) { 12558 // The to-be-promoted operands of this node have not yet been 12559 // promoted (this should be rare because we're going through the 12560 // list backward, but if one of the operands has several users in 12561 // this cluster of to-be-promoted nodes, it is possible). 12562 PromOpHandles.emplace_front(PromOp); 12563 continue; 12564 } 12565 12566 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(), 12567 PromOp.getNode()->op_end()); 12568 12569 // If there are any constant inputs, make sure they're replaced now. 12570 for (unsigned i = 0; i < 2; ++i) 12571 if (isa<ConstantSDNode>(Ops[C+i])) 12572 Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]); 12573 12574 DAG.ReplaceAllUsesOfValueWith(PromOp, 12575 DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops)); 12576 } 12577 12578 // Now we're left with the initial truncation itself. 12579 if (N->getOpcode() == ISD::TRUNCATE) 12580 return N->getOperand(0); 12581 12582 // Otherwise, this is a comparison. The operands to be compared have just 12583 // changed type (to i1), but everything else is the same. 12584 return SDValue(N, 0); 12585 } 12586 12587 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N, 12588 DAGCombinerInfo &DCI) const { 12589 SelectionDAG &DAG = DCI.DAG; 12590 SDLoc dl(N); 12591 12592 // If we're tracking CR bits, we need to be careful that we don't have: 12593 // zext(binary-ops(trunc(x), trunc(y))) 12594 // or 12595 // zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...) 12596 // such that we're unnecessarily moving things into CR bits that can more 12597 // efficiently stay in GPRs. Note that if we're not certain that the high 12598 // bits are set as required by the final extension, we still may need to do 12599 // some masking to get the proper behavior. 12600 12601 // This same functionality is important on PPC64 when dealing with 12602 // 32-to-64-bit extensions; these occur often when 32-bit values are used as 12603 // the return values of functions. Because it is so similar, it is handled 12604 // here as well. 12605 12606 if (N->getValueType(0) != MVT::i32 && 12607 N->getValueType(0) != MVT::i64) 12608 return SDValue(); 12609 12610 if (!((N->getOperand(0).getValueType() == MVT::i1 && Subtarget.useCRBits()) || 12611 (N->getOperand(0).getValueType() == MVT::i32 && Subtarget.isPPC64()))) 12612 return SDValue(); 12613 12614 if (N->getOperand(0).getOpcode() != ISD::AND && 12615 N->getOperand(0).getOpcode() != ISD::OR && 12616 N->getOperand(0).getOpcode() != ISD::XOR && 12617 N->getOperand(0).getOpcode() != ISD::SELECT && 12618 N->getOperand(0).getOpcode() != ISD::SELECT_CC) 12619 return SDValue(); 12620 12621 SmallVector<SDValue, 4> Inputs; 12622 SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps; 12623 SmallPtrSet<SDNode *, 16> Visited; 12624 12625 // Visit all inputs, collect all binary operations (and, or, xor and 12626 // select) that are all fed by truncations. 12627 while (!BinOps.empty()) { 12628 SDValue BinOp = BinOps.back(); 12629 BinOps.pop_back(); 12630 12631 if (!Visited.insert(BinOp.getNode()).second) 12632 continue; 12633 12634 PromOps.push_back(BinOp); 12635 12636 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) { 12637 // The condition of the select is not promoted. 12638 if (BinOp.getOpcode() == ISD::SELECT && i == 0) 12639 continue; 12640 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3) 12641 continue; 12642 12643 if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE || 12644 isa<ConstantSDNode>(BinOp.getOperand(i))) { 12645 Inputs.push_back(BinOp.getOperand(i)); 12646 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND || 12647 BinOp.getOperand(i).getOpcode() == ISD::OR || 12648 BinOp.getOperand(i).getOpcode() == ISD::XOR || 12649 BinOp.getOperand(i).getOpcode() == ISD::SELECT || 12650 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) { 12651 BinOps.push_back(BinOp.getOperand(i)); 12652 } else { 12653 // We have an input that is not a truncation or another binary 12654 // operation; we'll abort this transformation. 12655 return SDValue(); 12656 } 12657 } 12658 } 12659 12660 // The operands of a select that must be truncated when the select is 12661 // promoted because the operand is actually part of the to-be-promoted set. 12662 DenseMap<SDNode *, EVT> SelectTruncOp[2]; 12663 12664 // Make sure that this is a self-contained cluster of operations (which 12665 // is not quite the same thing as saying that everything has only one 12666 // use). 12667 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 12668 if (isa<ConstantSDNode>(Inputs[i])) 12669 continue; 12670 12671 for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(), 12672 UE = Inputs[i].getNode()->use_end(); 12673 UI != UE; ++UI) { 12674 SDNode *User = *UI; 12675 if (User != N && !Visited.count(User)) 12676 return SDValue(); 12677 12678 // If we're going to promote the non-output-value operand(s) or SELECT or 12679 // SELECT_CC, record them for truncation. 12680 if (User->getOpcode() == ISD::SELECT) { 12681 if (User->getOperand(0) == Inputs[i]) 12682 SelectTruncOp[0].insert(std::make_pair(User, 12683 User->getOperand(0).getValueType())); 12684 } else if (User->getOpcode() == ISD::SELECT_CC) { 12685 if (User->getOperand(0) == Inputs[i]) 12686 SelectTruncOp[0].insert(std::make_pair(User, 12687 User->getOperand(0).getValueType())); 12688 if (User->getOperand(1) == Inputs[i]) 12689 SelectTruncOp[1].insert(std::make_pair(User, 12690 User->getOperand(1).getValueType())); 12691 } 12692 } 12693 } 12694 12695 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) { 12696 for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(), 12697 UE = PromOps[i].getNode()->use_end(); 12698 UI != UE; ++UI) { 12699 SDNode *User = *UI; 12700 if (User != N && !Visited.count(User)) 12701 return SDValue(); 12702 12703 // If we're going to promote the non-output-value operand(s) or SELECT or 12704 // SELECT_CC, record them for truncation. 12705 if (User->getOpcode() == ISD::SELECT) { 12706 if (User->getOperand(0) == PromOps[i]) 12707 SelectTruncOp[0].insert(std::make_pair(User, 12708 User->getOperand(0).getValueType())); 12709 } else if (User->getOpcode() == ISD::SELECT_CC) { 12710 if (User->getOperand(0) == PromOps[i]) 12711 SelectTruncOp[0].insert(std::make_pair(User, 12712 User->getOperand(0).getValueType())); 12713 if (User->getOperand(1) == PromOps[i]) 12714 SelectTruncOp[1].insert(std::make_pair(User, 12715 User->getOperand(1).getValueType())); 12716 } 12717 } 12718 } 12719 12720 unsigned PromBits = N->getOperand(0).getValueSizeInBits(); 12721 bool ReallyNeedsExt = false; 12722 if (N->getOpcode() != ISD::ANY_EXTEND) { 12723 // If all of the inputs are not already sign/zero extended, then 12724 // we'll still need to do that at the end. 12725 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 12726 if (isa<ConstantSDNode>(Inputs[i])) 12727 continue; 12728 12729 unsigned OpBits = 12730 Inputs[i].getOperand(0).getValueSizeInBits(); 12731 assert(PromBits < OpBits && "Truncation not to a smaller bit count?"); 12732 12733 if ((N->getOpcode() == ISD::ZERO_EXTEND && 12734 !DAG.MaskedValueIsZero(Inputs[i].getOperand(0), 12735 APInt::getHighBitsSet(OpBits, 12736 OpBits-PromBits))) || 12737 (N->getOpcode() == ISD::SIGN_EXTEND && 12738 DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) < 12739 (OpBits-(PromBits-1)))) { 12740 ReallyNeedsExt = true; 12741 break; 12742 } 12743 } 12744 } 12745 12746 // Replace all inputs, either with the truncation operand, or a 12747 // truncation or extension to the final output type. 12748 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 12749 // Constant inputs need to be replaced with the to-be-promoted nodes that 12750 // use them because they might have users outside of the cluster of 12751 // promoted nodes. 12752 if (isa<ConstantSDNode>(Inputs[i])) 12753 continue; 12754 12755 SDValue InSrc = Inputs[i].getOperand(0); 12756 if (Inputs[i].getValueType() == N->getValueType(0)) 12757 DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc); 12758 else if (N->getOpcode() == ISD::SIGN_EXTEND) 12759 DAG.ReplaceAllUsesOfValueWith(Inputs[i], 12760 DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0))); 12761 else if (N->getOpcode() == ISD::ZERO_EXTEND) 12762 DAG.ReplaceAllUsesOfValueWith(Inputs[i], 12763 DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0))); 12764 else 12765 DAG.ReplaceAllUsesOfValueWith(Inputs[i], 12766 DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0))); 12767 } 12768 12769 std::list<HandleSDNode> PromOpHandles; 12770 for (auto &PromOp : PromOps) 12771 PromOpHandles.emplace_back(PromOp); 12772 12773 // Replace all operations (these are all the same, but have a different 12774 // (promoted) return type). DAG.getNode will validate that the types of 12775 // a binary operator match, so go through the list in reverse so that 12776 // we've likely promoted both operands first. 12777 while (!PromOpHandles.empty()) { 12778 SDValue PromOp = PromOpHandles.back().getValue(); 12779 PromOpHandles.pop_back(); 12780 12781 unsigned C; 12782 switch (PromOp.getOpcode()) { 12783 default: C = 0; break; 12784 case ISD::SELECT: C = 1; break; 12785 case ISD::SELECT_CC: C = 2; break; 12786 } 12787 12788 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) && 12789 PromOp.getOperand(C).getValueType() != N->getValueType(0)) || 12790 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) && 12791 PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) { 12792 // The to-be-promoted operands of this node have not yet been 12793 // promoted (this should be rare because we're going through the 12794 // list backward, but if one of the operands has several users in 12795 // this cluster of to-be-promoted nodes, it is possible). 12796 PromOpHandles.emplace_front(PromOp); 12797 continue; 12798 } 12799 12800 // For SELECT and SELECT_CC nodes, we do a similar check for any 12801 // to-be-promoted comparison inputs. 12802 if (PromOp.getOpcode() == ISD::SELECT || 12803 PromOp.getOpcode() == ISD::SELECT_CC) { 12804 if ((SelectTruncOp[0].count(PromOp.getNode()) && 12805 PromOp.getOperand(0).getValueType() != N->getValueType(0)) || 12806 (SelectTruncOp[1].count(PromOp.getNode()) && 12807 PromOp.getOperand(1).getValueType() != N->getValueType(0))) { 12808 PromOpHandles.emplace_front(PromOp); 12809 continue; 12810 } 12811 } 12812 12813 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(), 12814 PromOp.getNode()->op_end()); 12815 12816 // If this node has constant inputs, then they'll need to be promoted here. 12817 for (unsigned i = 0; i < 2; ++i) { 12818 if (!isa<ConstantSDNode>(Ops[C+i])) 12819 continue; 12820 if (Ops[C+i].getValueType() == N->getValueType(0)) 12821 continue; 12822 12823 if (N->getOpcode() == ISD::SIGN_EXTEND) 12824 Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); 12825 else if (N->getOpcode() == ISD::ZERO_EXTEND) 12826 Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); 12827 else 12828 Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); 12829 } 12830 12831 // If we've promoted the comparison inputs of a SELECT or SELECT_CC, 12832 // truncate them again to the original value type. 12833 if (PromOp.getOpcode() == ISD::SELECT || 12834 PromOp.getOpcode() == ISD::SELECT_CC) { 12835 auto SI0 = SelectTruncOp[0].find(PromOp.getNode()); 12836 if (SI0 != SelectTruncOp[0].end()) 12837 Ops[0] = DAG.getNode(ISD::TRUNCATE, dl, SI0->second, Ops[0]); 12838 auto SI1 = SelectTruncOp[1].find(PromOp.getNode()); 12839 if (SI1 != SelectTruncOp[1].end()) 12840 Ops[1] = DAG.getNode(ISD::TRUNCATE, dl, SI1->second, Ops[1]); 12841 } 12842 12843 DAG.ReplaceAllUsesOfValueWith(PromOp, 12844 DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops)); 12845 } 12846 12847 // Now we're left with the initial extension itself. 12848 if (!ReallyNeedsExt) 12849 return N->getOperand(0); 12850 12851 // To zero extend, just mask off everything except for the first bit (in the 12852 // i1 case). 12853 if (N->getOpcode() == ISD::ZERO_EXTEND) 12854 return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0), 12855 DAG.getConstant(APInt::getLowBitsSet( 12856 N->getValueSizeInBits(0), PromBits), 12857 dl, N->getValueType(0))); 12858 12859 assert(N->getOpcode() == ISD::SIGN_EXTEND && 12860 "Invalid extension type"); 12861 EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0), DAG.getDataLayout()); 12862 SDValue ShiftCst = 12863 DAG.getConstant(N->getValueSizeInBits(0) - PromBits, dl, ShiftAmountTy); 12864 return DAG.getNode( 12865 ISD::SRA, dl, N->getValueType(0), 12866 DAG.getNode(ISD::SHL, dl, N->getValueType(0), N->getOperand(0), ShiftCst), 12867 ShiftCst); 12868 } 12869 12870 SDValue PPCTargetLowering::combineSetCC(SDNode *N, 12871 DAGCombinerInfo &DCI) const { 12872 assert(N->getOpcode() == ISD::SETCC && 12873 "Should be called with a SETCC node"); 12874 12875 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 12876 if (CC == ISD::SETNE || CC == ISD::SETEQ) { 12877 SDValue LHS = N->getOperand(0); 12878 SDValue RHS = N->getOperand(1); 12879 12880 // If there is a '0 - y' pattern, canonicalize the pattern to the RHS. 12881 if (LHS.getOpcode() == ISD::SUB && isNullConstant(LHS.getOperand(0)) && 12882 LHS.hasOneUse()) 12883 std::swap(LHS, RHS); 12884 12885 // x == 0-y --> x+y == 0 12886 // x != 0-y --> x+y != 0 12887 if (RHS.getOpcode() == ISD::SUB && isNullConstant(RHS.getOperand(0)) && 12888 RHS.hasOneUse()) { 12889 SDLoc DL(N); 12890 SelectionDAG &DAG = DCI.DAG; 12891 EVT VT = N->getValueType(0); 12892 EVT OpVT = LHS.getValueType(); 12893 SDValue Add = DAG.getNode(ISD::ADD, DL, OpVT, LHS, RHS.getOperand(1)); 12894 return DAG.getSetCC(DL, VT, Add, DAG.getConstant(0, DL, OpVT), CC); 12895 } 12896 } 12897 12898 return DAGCombineTruncBoolExt(N, DCI); 12899 } 12900 12901 // Is this an extending load from an f32 to an f64? 12902 static bool isFPExtLoad(SDValue Op) { 12903 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op.getNode())) 12904 return LD->getExtensionType() == ISD::EXTLOAD && 12905 Op.getValueType() == MVT::f64; 12906 return false; 12907 } 12908 12909 /// Reduces the number of fp-to-int conversion when building a vector. 12910 /// 12911 /// If this vector is built out of floating to integer conversions, 12912 /// transform it to a vector built out of floating point values followed by a 12913 /// single floating to integer conversion of the vector. 12914 /// Namely (build_vector (fptosi $A), (fptosi $B), ...) 12915 /// becomes (fptosi (build_vector ($A, $B, ...))) 12916 SDValue PPCTargetLowering:: 12917 combineElementTruncationToVectorTruncation(SDNode *N, 12918 DAGCombinerInfo &DCI) const { 12919 assert(N->getOpcode() == ISD::BUILD_VECTOR && 12920 "Should be called with a BUILD_VECTOR node"); 12921 12922 SelectionDAG &DAG = DCI.DAG; 12923 SDLoc dl(N); 12924 12925 SDValue FirstInput = N->getOperand(0); 12926 assert(FirstInput.getOpcode() == PPCISD::MFVSR && 12927 "The input operand must be an fp-to-int conversion."); 12928 12929 // This combine happens after legalization so the fp_to_[su]i nodes are 12930 // already converted to PPCSISD nodes. 12931 unsigned FirstConversion = FirstInput.getOperand(0).getOpcode(); 12932 if (FirstConversion == PPCISD::FCTIDZ || 12933 FirstConversion == PPCISD::FCTIDUZ || 12934 FirstConversion == PPCISD::FCTIWZ || 12935 FirstConversion == PPCISD::FCTIWUZ) { 12936 bool IsSplat = true; 12937 bool Is32Bit = FirstConversion == PPCISD::FCTIWZ || 12938 FirstConversion == PPCISD::FCTIWUZ; 12939 EVT SrcVT = FirstInput.getOperand(0).getValueType(); 12940 SmallVector<SDValue, 4> Ops; 12941 EVT TargetVT = N->getValueType(0); 12942 for (int i = 0, e = N->getNumOperands(); i < e; ++i) { 12943 SDValue NextOp = N->getOperand(i); 12944 if (NextOp.getOpcode() != PPCISD::MFVSR) 12945 return SDValue(); 12946 unsigned NextConversion = NextOp.getOperand(0).getOpcode(); 12947 if (NextConversion != FirstConversion) 12948 return SDValue(); 12949 // If we are converting to 32-bit integers, we need to add an FP_ROUND. 12950 // This is not valid if the input was originally double precision. It is 12951 // also not profitable to do unless this is an extending load in which 12952 // case doing this combine will allow us to combine consecutive loads. 12953 if (Is32Bit && !isFPExtLoad(NextOp.getOperand(0).getOperand(0))) 12954 return SDValue(); 12955 if (N->getOperand(i) != FirstInput) 12956 IsSplat = false; 12957 } 12958 12959 // If this is a splat, we leave it as-is since there will be only a single 12960 // fp-to-int conversion followed by a splat of the integer. This is better 12961 // for 32-bit and smaller ints and neutral for 64-bit ints. 12962 if (IsSplat) 12963 return SDValue(); 12964 12965 // Now that we know we have the right type of node, get its operands 12966 for (int i = 0, e = N->getNumOperands(); i < e; ++i) { 12967 SDValue In = N->getOperand(i).getOperand(0); 12968 if (Is32Bit) { 12969 // For 32-bit values, we need to add an FP_ROUND node (if we made it 12970 // here, we know that all inputs are extending loads so this is safe). 12971 if (In.isUndef()) 12972 Ops.push_back(DAG.getUNDEF(SrcVT)); 12973 else { 12974 SDValue Trunc = DAG.getNode(ISD::FP_ROUND, dl, 12975 MVT::f32, In.getOperand(0), 12976 DAG.getIntPtrConstant(1, dl)); 12977 Ops.push_back(Trunc); 12978 } 12979 } else 12980 Ops.push_back(In.isUndef() ? DAG.getUNDEF(SrcVT) : In.getOperand(0)); 12981 } 12982 12983 unsigned Opcode; 12984 if (FirstConversion == PPCISD::FCTIDZ || 12985 FirstConversion == PPCISD::FCTIWZ) 12986 Opcode = ISD::FP_TO_SINT; 12987 else 12988 Opcode = ISD::FP_TO_UINT; 12989 12990 EVT NewVT = TargetVT == MVT::v2i64 ? MVT::v2f64 : MVT::v4f32; 12991 SDValue BV = DAG.getBuildVector(NewVT, dl, Ops); 12992 return DAG.getNode(Opcode, dl, TargetVT, BV); 12993 } 12994 return SDValue(); 12995 } 12996 12997 /// Reduce the number of loads when building a vector. 12998 /// 12999 /// Building a vector out of multiple loads can be converted to a load 13000 /// of the vector type if the loads are consecutive. If the loads are 13001 /// consecutive but in descending order, a shuffle is added at the end 13002 /// to reorder the vector. 13003 static SDValue combineBVOfConsecutiveLoads(SDNode *N, SelectionDAG &DAG) { 13004 assert(N->getOpcode() == ISD::BUILD_VECTOR && 13005 "Should be called with a BUILD_VECTOR node"); 13006 13007 SDLoc dl(N); 13008 13009 // Return early for non byte-sized type, as they can't be consecutive. 13010 if (!N->getValueType(0).getVectorElementType().isByteSized()) 13011 return SDValue(); 13012 13013 bool InputsAreConsecutiveLoads = true; 13014 bool InputsAreReverseConsecutive = true; 13015 unsigned ElemSize = N->getValueType(0).getScalarType().getStoreSize(); 13016 SDValue FirstInput = N->getOperand(0); 13017 bool IsRoundOfExtLoad = false; 13018 13019 if (FirstInput.getOpcode() == ISD::FP_ROUND && 13020 FirstInput.getOperand(0).getOpcode() == ISD::LOAD) { 13021 LoadSDNode *LD = dyn_cast<LoadSDNode>(FirstInput.getOperand(0)); 13022 IsRoundOfExtLoad = LD->getExtensionType() == ISD::EXTLOAD; 13023 } 13024 // Not a build vector of (possibly fp_rounded) loads. 13025 if ((!IsRoundOfExtLoad && FirstInput.getOpcode() != ISD::LOAD) || 13026 N->getNumOperands() == 1) 13027 return SDValue(); 13028 13029 for (int i = 1, e = N->getNumOperands(); i < e; ++i) { 13030 // If any inputs are fp_round(extload), they all must be. 13031 if (IsRoundOfExtLoad && N->getOperand(i).getOpcode() != ISD::FP_ROUND) 13032 return SDValue(); 13033 13034 SDValue NextInput = IsRoundOfExtLoad ? N->getOperand(i).getOperand(0) : 13035 N->getOperand(i); 13036 if (NextInput.getOpcode() != ISD::LOAD) 13037 return SDValue(); 13038 13039 SDValue PreviousInput = 13040 IsRoundOfExtLoad ? N->getOperand(i-1).getOperand(0) : N->getOperand(i-1); 13041 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(PreviousInput); 13042 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(NextInput); 13043 13044 // If any inputs are fp_round(extload), they all must be. 13045 if (IsRoundOfExtLoad && LD2->getExtensionType() != ISD::EXTLOAD) 13046 return SDValue(); 13047 13048 if (!isConsecutiveLS(LD2, LD1, ElemSize, 1, DAG)) 13049 InputsAreConsecutiveLoads = false; 13050 if (!isConsecutiveLS(LD1, LD2, ElemSize, 1, DAG)) 13051 InputsAreReverseConsecutive = false; 13052 13053 // Exit early if the loads are neither consecutive nor reverse consecutive. 13054 if (!InputsAreConsecutiveLoads && !InputsAreReverseConsecutive) 13055 return SDValue(); 13056 } 13057 13058 assert(!(InputsAreConsecutiveLoads && InputsAreReverseConsecutive) && 13059 "The loads cannot be both consecutive and reverse consecutive."); 13060 13061 SDValue FirstLoadOp = 13062 IsRoundOfExtLoad ? FirstInput.getOperand(0) : FirstInput; 13063 SDValue LastLoadOp = 13064 IsRoundOfExtLoad ? N->getOperand(N->getNumOperands()-1).getOperand(0) : 13065 N->getOperand(N->getNumOperands()-1); 13066 13067 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(FirstLoadOp); 13068 LoadSDNode *LDL = dyn_cast<LoadSDNode>(LastLoadOp); 13069 if (InputsAreConsecutiveLoads) { 13070 assert(LD1 && "Input needs to be a LoadSDNode."); 13071 return DAG.getLoad(N->getValueType(0), dl, LD1->getChain(), 13072 LD1->getBasePtr(), LD1->getPointerInfo(), 13073 LD1->getAlignment()); 13074 } 13075 if (InputsAreReverseConsecutive) { 13076 assert(LDL && "Input needs to be a LoadSDNode."); 13077 SDValue Load = DAG.getLoad(N->getValueType(0), dl, LDL->getChain(), 13078 LDL->getBasePtr(), LDL->getPointerInfo(), 13079 LDL->getAlignment()); 13080 SmallVector<int, 16> Ops; 13081 for (int i = N->getNumOperands() - 1; i >= 0; i--) 13082 Ops.push_back(i); 13083 13084 return DAG.getVectorShuffle(N->getValueType(0), dl, Load, 13085 DAG.getUNDEF(N->getValueType(0)), Ops); 13086 } 13087 return SDValue(); 13088 } 13089 13090 // This function adds the required vector_shuffle needed to get 13091 // the elements of the vector extract in the correct position 13092 // as specified by the CorrectElems encoding. 13093 static SDValue addShuffleForVecExtend(SDNode *N, SelectionDAG &DAG, 13094 SDValue Input, uint64_t Elems, 13095 uint64_t CorrectElems) { 13096 SDLoc dl(N); 13097 13098 unsigned NumElems = Input.getValueType().getVectorNumElements(); 13099 SmallVector<int, 16> ShuffleMask(NumElems, -1); 13100 13101 // Knowing the element indices being extracted from the original 13102 // vector and the order in which they're being inserted, just put 13103 // them at element indices required for the instruction. 13104 for (unsigned i = 0; i < N->getNumOperands(); i++) { 13105 if (DAG.getDataLayout().isLittleEndian()) 13106 ShuffleMask[CorrectElems & 0xF] = Elems & 0xF; 13107 else 13108 ShuffleMask[(CorrectElems & 0xF0) >> 4] = (Elems & 0xF0) >> 4; 13109 CorrectElems = CorrectElems >> 8; 13110 Elems = Elems >> 8; 13111 } 13112 13113 SDValue Shuffle = 13114 DAG.getVectorShuffle(Input.getValueType(), dl, Input, 13115 DAG.getUNDEF(Input.getValueType()), ShuffleMask); 13116 13117 EVT Ty = N->getValueType(0); 13118 SDValue BV = DAG.getNode(PPCISD::SExtVElems, dl, Ty, Shuffle); 13119 return BV; 13120 } 13121 13122 // Look for build vector patterns where input operands come from sign 13123 // extended vector_extract elements of specific indices. If the correct indices 13124 // aren't used, add a vector shuffle to fix up the indices and create a new 13125 // PPCISD:SExtVElems node which selects the vector sign extend instructions 13126 // during instruction selection. 13127 static SDValue combineBVOfVecSExt(SDNode *N, SelectionDAG &DAG) { 13128 // This array encodes the indices that the vector sign extend instructions 13129 // extract from when extending from one type to another for both BE and LE. 13130 // The right nibble of each byte corresponds to the LE incides. 13131 // and the left nibble of each byte corresponds to the BE incides. 13132 // For example: 0x3074B8FC byte->word 13133 // For LE: the allowed indices are: 0x0,0x4,0x8,0xC 13134 // For BE: the allowed indices are: 0x3,0x7,0xB,0xF 13135 // For example: 0x000070F8 byte->double word 13136 // For LE: the allowed indices are: 0x0,0x8 13137 // For BE: the allowed indices are: 0x7,0xF 13138 uint64_t TargetElems[] = { 13139 0x3074B8FC, // b->w 13140 0x000070F8, // b->d 13141 0x10325476, // h->w 13142 0x00003074, // h->d 13143 0x00001032, // w->d 13144 }; 13145 13146 uint64_t Elems = 0; 13147 int Index; 13148 SDValue Input; 13149 13150 auto isSExtOfVecExtract = [&](SDValue Op) -> bool { 13151 if (!Op) 13152 return false; 13153 if (Op.getOpcode() != ISD::SIGN_EXTEND && 13154 Op.getOpcode() != ISD::SIGN_EXTEND_INREG) 13155 return false; 13156 13157 // A SIGN_EXTEND_INREG might be fed by an ANY_EXTEND to produce a value 13158 // of the right width. 13159 SDValue Extract = Op.getOperand(0); 13160 if (Extract.getOpcode() == ISD::ANY_EXTEND) 13161 Extract = Extract.getOperand(0); 13162 if (Extract.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 13163 return false; 13164 13165 ConstantSDNode *ExtOp = dyn_cast<ConstantSDNode>(Extract.getOperand(1)); 13166 if (!ExtOp) 13167 return false; 13168 13169 Index = ExtOp->getZExtValue(); 13170 if (Input && Input != Extract.getOperand(0)) 13171 return false; 13172 13173 if (!Input) 13174 Input = Extract.getOperand(0); 13175 13176 Elems = Elems << 8; 13177 Index = DAG.getDataLayout().isLittleEndian() ? Index : Index << 4; 13178 Elems |= Index; 13179 13180 return true; 13181 }; 13182 13183 // If the build vector operands aren't sign extended vector extracts, 13184 // of the same input vector, then return. 13185 for (unsigned i = 0; i < N->getNumOperands(); i++) { 13186 if (!isSExtOfVecExtract(N->getOperand(i))) { 13187 return SDValue(); 13188 } 13189 } 13190 13191 // If the vector extract indicies are not correct, add the appropriate 13192 // vector_shuffle. 13193 int TgtElemArrayIdx; 13194 int InputSize = Input.getValueType().getScalarSizeInBits(); 13195 int OutputSize = N->getValueType(0).getScalarSizeInBits(); 13196 if (InputSize + OutputSize == 40) 13197 TgtElemArrayIdx = 0; 13198 else if (InputSize + OutputSize == 72) 13199 TgtElemArrayIdx = 1; 13200 else if (InputSize + OutputSize == 48) 13201 TgtElemArrayIdx = 2; 13202 else if (InputSize + OutputSize == 80) 13203 TgtElemArrayIdx = 3; 13204 else if (InputSize + OutputSize == 96) 13205 TgtElemArrayIdx = 4; 13206 else 13207 return SDValue(); 13208 13209 uint64_t CorrectElems = TargetElems[TgtElemArrayIdx]; 13210 CorrectElems = DAG.getDataLayout().isLittleEndian() 13211 ? CorrectElems & 0x0F0F0F0F0F0F0F0F 13212 : CorrectElems & 0xF0F0F0F0F0F0F0F0; 13213 if (Elems != CorrectElems) { 13214 return addShuffleForVecExtend(N, DAG, Input, Elems, CorrectElems); 13215 } 13216 13217 // Regular lowering will catch cases where a shuffle is not needed. 13218 return SDValue(); 13219 } 13220 13221 SDValue PPCTargetLowering::DAGCombineBuildVector(SDNode *N, 13222 DAGCombinerInfo &DCI) const { 13223 assert(N->getOpcode() == ISD::BUILD_VECTOR && 13224 "Should be called with a BUILD_VECTOR node"); 13225 13226 SelectionDAG &DAG = DCI.DAG; 13227 SDLoc dl(N); 13228 13229 if (!Subtarget.hasVSX()) 13230 return SDValue(); 13231 13232 // The target independent DAG combiner will leave a build_vector of 13233 // float-to-int conversions intact. We can generate MUCH better code for 13234 // a float-to-int conversion of a vector of floats. 13235 SDValue FirstInput = N->getOperand(0); 13236 if (FirstInput.getOpcode() == PPCISD::MFVSR) { 13237 SDValue Reduced = combineElementTruncationToVectorTruncation(N, DCI); 13238 if (Reduced) 13239 return Reduced; 13240 } 13241 13242 // If we're building a vector out of consecutive loads, just load that 13243 // vector type. 13244 SDValue Reduced = combineBVOfConsecutiveLoads(N, DAG); 13245 if (Reduced) 13246 return Reduced; 13247 13248 // If we're building a vector out of extended elements from another vector 13249 // we have P9 vector integer extend instructions. The code assumes legal 13250 // input types (i.e. it can't handle things like v4i16) so do not run before 13251 // legalization. 13252 if (Subtarget.hasP9Altivec() && !DCI.isBeforeLegalize()) { 13253 Reduced = combineBVOfVecSExt(N, DAG); 13254 if (Reduced) 13255 return Reduced; 13256 } 13257 13258 13259 if (N->getValueType(0) != MVT::v2f64) 13260 return SDValue(); 13261 13262 // Looking for: 13263 // (build_vector ([su]int_to_fp (extractelt 0)), [su]int_to_fp (extractelt 1)) 13264 if (FirstInput.getOpcode() != ISD::SINT_TO_FP && 13265 FirstInput.getOpcode() != ISD::UINT_TO_FP) 13266 return SDValue(); 13267 if (N->getOperand(1).getOpcode() != ISD::SINT_TO_FP && 13268 N->getOperand(1).getOpcode() != ISD::UINT_TO_FP) 13269 return SDValue(); 13270 if (FirstInput.getOpcode() != N->getOperand(1).getOpcode()) 13271 return SDValue(); 13272 13273 SDValue Ext1 = FirstInput.getOperand(0); 13274 SDValue Ext2 = N->getOperand(1).getOperand(0); 13275 if(Ext1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 13276 Ext2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 13277 return SDValue(); 13278 13279 ConstantSDNode *Ext1Op = dyn_cast<ConstantSDNode>(Ext1.getOperand(1)); 13280 ConstantSDNode *Ext2Op = dyn_cast<ConstantSDNode>(Ext2.getOperand(1)); 13281 if (!Ext1Op || !Ext2Op) 13282 return SDValue(); 13283 if (Ext1.getOperand(0).getValueType() != MVT::v4i32 || 13284 Ext1.getOperand(0) != Ext2.getOperand(0)) 13285 return SDValue(); 13286 13287 int FirstElem = Ext1Op->getZExtValue(); 13288 int SecondElem = Ext2Op->getZExtValue(); 13289 int SubvecIdx; 13290 if (FirstElem == 0 && SecondElem == 1) 13291 SubvecIdx = Subtarget.isLittleEndian() ? 1 : 0; 13292 else if (FirstElem == 2 && SecondElem == 3) 13293 SubvecIdx = Subtarget.isLittleEndian() ? 0 : 1; 13294 else 13295 return SDValue(); 13296 13297 SDValue SrcVec = Ext1.getOperand(0); 13298 auto NodeType = (N->getOperand(1).getOpcode() == ISD::SINT_TO_FP) ? 13299 PPCISD::SINT_VEC_TO_FP : PPCISD::UINT_VEC_TO_FP; 13300 return DAG.getNode(NodeType, dl, MVT::v2f64, 13301 SrcVec, DAG.getIntPtrConstant(SubvecIdx, dl)); 13302 } 13303 13304 SDValue PPCTargetLowering::combineFPToIntToFP(SDNode *N, 13305 DAGCombinerInfo &DCI) const { 13306 assert((N->getOpcode() == ISD::SINT_TO_FP || 13307 N->getOpcode() == ISD::UINT_TO_FP) && 13308 "Need an int -> FP conversion node here"); 13309 13310 if (useSoftFloat() || !Subtarget.has64BitSupport()) 13311 return SDValue(); 13312 13313 SelectionDAG &DAG = DCI.DAG; 13314 SDLoc dl(N); 13315 SDValue Op(N, 0); 13316 13317 // Don't handle ppc_fp128 here or conversions that are out-of-range capable 13318 // from the hardware. 13319 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64) 13320 return SDValue(); 13321 if (Op.getOperand(0).getValueType().getSimpleVT() <= MVT(MVT::i1) || 13322 Op.getOperand(0).getValueType().getSimpleVT() > MVT(MVT::i64)) 13323 return SDValue(); 13324 13325 SDValue FirstOperand(Op.getOperand(0)); 13326 bool SubWordLoad = FirstOperand.getOpcode() == ISD::LOAD && 13327 (FirstOperand.getValueType() == MVT::i8 || 13328 FirstOperand.getValueType() == MVT::i16); 13329 if (Subtarget.hasP9Vector() && Subtarget.hasP9Altivec() && SubWordLoad) { 13330 bool Signed = N->getOpcode() == ISD::SINT_TO_FP; 13331 bool DstDouble = Op.getValueType() == MVT::f64; 13332 unsigned ConvOp = Signed ? 13333 (DstDouble ? PPCISD::FCFID : PPCISD::FCFIDS) : 13334 (DstDouble ? PPCISD::FCFIDU : PPCISD::FCFIDUS); 13335 SDValue WidthConst = 13336 DAG.getIntPtrConstant(FirstOperand.getValueType() == MVT::i8 ? 1 : 2, 13337 dl, false); 13338 LoadSDNode *LDN = cast<LoadSDNode>(FirstOperand.getNode()); 13339 SDValue Ops[] = { LDN->getChain(), LDN->getBasePtr(), WidthConst }; 13340 SDValue Ld = DAG.getMemIntrinsicNode(PPCISD::LXSIZX, dl, 13341 DAG.getVTList(MVT::f64, MVT::Other), 13342 Ops, MVT::i8, LDN->getMemOperand()); 13343 13344 // For signed conversion, we need to sign-extend the value in the VSR 13345 if (Signed) { 13346 SDValue ExtOps[] = { Ld, WidthConst }; 13347 SDValue Ext = DAG.getNode(PPCISD::VEXTS, dl, MVT::f64, ExtOps); 13348 return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ext); 13349 } else 13350 return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ld); 13351 } 13352 13353 13354 // For i32 intermediate values, unfortunately, the conversion functions 13355 // leave the upper 32 bits of the value are undefined. Within the set of 13356 // scalar instructions, we have no method for zero- or sign-extending the 13357 // value. Thus, we cannot handle i32 intermediate values here. 13358 if (Op.getOperand(0).getValueType() == MVT::i32) 13359 return SDValue(); 13360 13361 assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) && 13362 "UINT_TO_FP is supported only with FPCVT"); 13363 13364 // If we have FCFIDS, then use it when converting to single-precision. 13365 // Otherwise, convert to double-precision and then round. 13366 unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 13367 ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS 13368 : PPCISD::FCFIDS) 13369 : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU 13370 : PPCISD::FCFID); 13371 MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 13372 ? MVT::f32 13373 : MVT::f64; 13374 13375 // If we're converting from a float, to an int, and back to a float again, 13376 // then we don't need the store/load pair at all. 13377 if ((Op.getOperand(0).getOpcode() == ISD::FP_TO_UINT && 13378 Subtarget.hasFPCVT()) || 13379 (Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT)) { 13380 SDValue Src = Op.getOperand(0).getOperand(0); 13381 if (Src.getValueType() == MVT::f32) { 13382 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src); 13383 DCI.AddToWorklist(Src.getNode()); 13384 } else if (Src.getValueType() != MVT::f64) { 13385 // Make sure that we don't pick up a ppc_fp128 source value. 13386 return SDValue(); 13387 } 13388 13389 unsigned FCTOp = 13390 Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT ? PPCISD::FCTIDZ : 13391 PPCISD::FCTIDUZ; 13392 13393 SDValue Tmp = DAG.getNode(FCTOp, dl, MVT::f64, Src); 13394 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Tmp); 13395 13396 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) { 13397 FP = DAG.getNode(ISD::FP_ROUND, dl, 13398 MVT::f32, FP, DAG.getIntPtrConstant(0, dl)); 13399 DCI.AddToWorklist(FP.getNode()); 13400 } 13401 13402 return FP; 13403 } 13404 13405 return SDValue(); 13406 } 13407 13408 // expandVSXLoadForLE - Convert VSX loads (which may be intrinsics for 13409 // builtins) into loads with swaps. 13410 SDValue PPCTargetLowering::expandVSXLoadForLE(SDNode *N, 13411 DAGCombinerInfo &DCI) const { 13412 SelectionDAG &DAG = DCI.DAG; 13413 SDLoc dl(N); 13414 SDValue Chain; 13415 SDValue Base; 13416 MachineMemOperand *MMO; 13417 13418 switch (N->getOpcode()) { 13419 default: 13420 llvm_unreachable("Unexpected opcode for little endian VSX load"); 13421 case ISD::LOAD: { 13422 LoadSDNode *LD = cast<LoadSDNode>(N); 13423 Chain = LD->getChain(); 13424 Base = LD->getBasePtr(); 13425 MMO = LD->getMemOperand(); 13426 // If the MMO suggests this isn't a load of a full vector, leave 13427 // things alone. For a built-in, we have to make the change for 13428 // correctness, so if there is a size problem that will be a bug. 13429 if (MMO->getSize() < 16) 13430 return SDValue(); 13431 break; 13432 } 13433 case ISD::INTRINSIC_W_CHAIN: { 13434 MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N); 13435 Chain = Intrin->getChain(); 13436 // Similarly to the store case below, Intrin->getBasePtr() doesn't get 13437 // us what we want. Get operand 2 instead. 13438 Base = Intrin->getOperand(2); 13439 MMO = Intrin->getMemOperand(); 13440 break; 13441 } 13442 } 13443 13444 MVT VecTy = N->getValueType(0).getSimpleVT(); 13445 13446 // Do not expand to PPCISD::LXVD2X + PPCISD::XXSWAPD when the load is 13447 // aligned and the type is a vector with elements up to 4 bytes 13448 if (Subtarget.needsSwapsForVSXMemOps() && !(MMO->getAlignment()%16) 13449 && VecTy.getScalarSizeInBits() <= 32 ) { 13450 return SDValue(); 13451 } 13452 13453 SDValue LoadOps[] = { Chain, Base }; 13454 SDValue Load = DAG.getMemIntrinsicNode(PPCISD::LXVD2X, dl, 13455 DAG.getVTList(MVT::v2f64, MVT::Other), 13456 LoadOps, MVT::v2f64, MMO); 13457 13458 DCI.AddToWorklist(Load.getNode()); 13459 Chain = Load.getValue(1); 13460 SDValue Swap = DAG.getNode( 13461 PPCISD::XXSWAPD, dl, DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Load); 13462 DCI.AddToWorklist(Swap.getNode()); 13463 13464 // Add a bitcast if the resulting load type doesn't match v2f64. 13465 if (VecTy != MVT::v2f64) { 13466 SDValue N = DAG.getNode(ISD::BITCAST, dl, VecTy, Swap); 13467 DCI.AddToWorklist(N.getNode()); 13468 // Package {bitcast value, swap's chain} to match Load's shape. 13469 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VecTy, MVT::Other), 13470 N, Swap.getValue(1)); 13471 } 13472 13473 return Swap; 13474 } 13475 13476 // expandVSXStoreForLE - Convert VSX stores (which may be intrinsics for 13477 // builtins) into stores with swaps. 13478 SDValue PPCTargetLowering::expandVSXStoreForLE(SDNode *N, 13479 DAGCombinerInfo &DCI) const { 13480 SelectionDAG &DAG = DCI.DAG; 13481 SDLoc dl(N); 13482 SDValue Chain; 13483 SDValue Base; 13484 unsigned SrcOpnd; 13485 MachineMemOperand *MMO; 13486 13487 switch (N->getOpcode()) { 13488 default: 13489 llvm_unreachable("Unexpected opcode for little endian VSX store"); 13490 case ISD::STORE: { 13491 StoreSDNode *ST = cast<StoreSDNode>(N); 13492 Chain = ST->getChain(); 13493 Base = ST->getBasePtr(); 13494 MMO = ST->getMemOperand(); 13495 SrcOpnd = 1; 13496 // If the MMO suggests this isn't a store of a full vector, leave 13497 // things alone. For a built-in, we have to make the change for 13498 // correctness, so if there is a size problem that will be a bug. 13499 if (MMO->getSize() < 16) 13500 return SDValue(); 13501 break; 13502 } 13503 case ISD::INTRINSIC_VOID: { 13504 MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N); 13505 Chain = Intrin->getChain(); 13506 // Intrin->getBasePtr() oddly does not get what we want. 13507 Base = Intrin->getOperand(3); 13508 MMO = Intrin->getMemOperand(); 13509 SrcOpnd = 2; 13510 break; 13511 } 13512 } 13513 13514 SDValue Src = N->getOperand(SrcOpnd); 13515 MVT VecTy = Src.getValueType().getSimpleVT(); 13516 13517 // Do not expand to PPCISD::XXSWAPD and PPCISD::STXVD2X when the load is 13518 // aligned and the type is a vector with elements up to 4 bytes 13519 if (Subtarget.needsSwapsForVSXMemOps() && !(MMO->getAlignment()%16) 13520 && VecTy.getScalarSizeInBits() <= 32 ) { 13521 return SDValue(); 13522 } 13523 13524 // All stores are done as v2f64 and possible bit cast. 13525 if (VecTy != MVT::v2f64) { 13526 Src = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Src); 13527 DCI.AddToWorklist(Src.getNode()); 13528 } 13529 13530 SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl, 13531 DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Src); 13532 DCI.AddToWorklist(Swap.getNode()); 13533 Chain = Swap.getValue(1); 13534 SDValue StoreOps[] = { Chain, Swap, Base }; 13535 SDValue Store = DAG.getMemIntrinsicNode(PPCISD::STXVD2X, dl, 13536 DAG.getVTList(MVT::Other), 13537 StoreOps, VecTy, MMO); 13538 DCI.AddToWorklist(Store.getNode()); 13539 return Store; 13540 } 13541 13542 // Handle DAG combine for STORE (FP_TO_INT F). 13543 SDValue PPCTargetLowering::combineStoreFPToInt(SDNode *N, 13544 DAGCombinerInfo &DCI) const { 13545 13546 SelectionDAG &DAG = DCI.DAG; 13547 SDLoc dl(N); 13548 unsigned Opcode = N->getOperand(1).getOpcode(); 13549 13550 assert((Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT) 13551 && "Not a FP_TO_INT Instruction!"); 13552 13553 SDValue Val = N->getOperand(1).getOperand(0); 13554 EVT Op1VT = N->getOperand(1).getValueType(); 13555 EVT ResVT = Val.getValueType(); 13556 13557 // Floating point types smaller than 32 bits are not legal on Power. 13558 if (ResVT.getScalarSizeInBits() < 32) 13559 return SDValue(); 13560 13561 // Only perform combine for conversion to i64/i32 or power9 i16/i8. 13562 bool ValidTypeForStoreFltAsInt = 13563 (Op1VT == MVT::i32 || Op1VT == MVT::i64 || 13564 (Subtarget.hasP9Vector() && (Op1VT == MVT::i16 || Op1VT == MVT::i8))); 13565 13566 if (ResVT == MVT::ppcf128 || !Subtarget.hasP8Altivec() || 13567 cast<StoreSDNode>(N)->isTruncatingStore() || !ValidTypeForStoreFltAsInt) 13568 return SDValue(); 13569 13570 // Extend f32 values to f64 13571 if (ResVT.getScalarSizeInBits() == 32) { 13572 Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val); 13573 DCI.AddToWorklist(Val.getNode()); 13574 } 13575 13576 // Set signed or unsigned conversion opcode. 13577 unsigned ConvOpcode = (Opcode == ISD::FP_TO_SINT) ? 13578 PPCISD::FP_TO_SINT_IN_VSR : 13579 PPCISD::FP_TO_UINT_IN_VSR; 13580 13581 Val = DAG.getNode(ConvOpcode, 13582 dl, ResVT == MVT::f128 ? MVT::f128 : MVT::f64, Val); 13583 DCI.AddToWorklist(Val.getNode()); 13584 13585 // Set number of bytes being converted. 13586 unsigned ByteSize = Op1VT.getScalarSizeInBits() / 8; 13587 SDValue Ops[] = { N->getOperand(0), Val, N->getOperand(2), 13588 DAG.getIntPtrConstant(ByteSize, dl, false), 13589 DAG.getValueType(Op1VT) }; 13590 13591 Val = DAG.getMemIntrinsicNode(PPCISD::ST_VSR_SCAL_INT, dl, 13592 DAG.getVTList(MVT::Other), Ops, 13593 cast<StoreSDNode>(N)->getMemoryVT(), 13594 cast<StoreSDNode>(N)->getMemOperand()); 13595 13596 DCI.AddToWorklist(Val.getNode()); 13597 return Val; 13598 } 13599 13600 SDValue PPCTargetLowering::combineVReverseMemOP(ShuffleVectorSDNode *SVN, 13601 LSBaseSDNode *LSBase, 13602 DAGCombinerInfo &DCI) const { 13603 assert((ISD::isNormalLoad(LSBase) || ISD::isNormalStore(LSBase)) && 13604 "Not a reverse memop pattern!"); 13605 13606 auto IsElementReverse = [](const ShuffleVectorSDNode *SVN) -> bool { 13607 auto Mask = SVN->getMask(); 13608 int i = 0; 13609 auto I = Mask.rbegin(); 13610 auto E = Mask.rend(); 13611 13612 for (; I != E; ++I) { 13613 if (*I != i) 13614 return false; 13615 i++; 13616 } 13617 return true; 13618 }; 13619 13620 SelectionDAG &DAG = DCI.DAG; 13621 EVT VT = SVN->getValueType(0); 13622 13623 if (!isTypeLegal(VT) || !Subtarget.isLittleEndian() || !Subtarget.hasVSX()) 13624 return SDValue(); 13625 13626 // Before P9, we have PPCVSXSwapRemoval pass to hack the element order. 13627 // See comment in PPCVSXSwapRemoval.cpp. 13628 // It is conflict with PPCVSXSwapRemoval opt. So we don't do it. 13629 if (!Subtarget.hasP9Vector()) 13630 return SDValue(); 13631 13632 if(!IsElementReverse(SVN)) 13633 return SDValue(); 13634 13635 if (LSBase->getOpcode() == ISD::LOAD) { 13636 SDLoc dl(SVN); 13637 SDValue LoadOps[] = {LSBase->getChain(), LSBase->getBasePtr()}; 13638 return DAG.getMemIntrinsicNode( 13639 PPCISD::LOAD_VEC_BE, dl, DAG.getVTList(VT, MVT::Other), LoadOps, 13640 LSBase->getMemoryVT(), LSBase->getMemOperand()); 13641 } 13642 13643 if (LSBase->getOpcode() == ISD::STORE) { 13644 SDLoc dl(LSBase); 13645 SDValue StoreOps[] = {LSBase->getChain(), SVN->getOperand(0), 13646 LSBase->getBasePtr()}; 13647 return DAG.getMemIntrinsicNode( 13648 PPCISD::STORE_VEC_BE, dl, DAG.getVTList(MVT::Other), StoreOps, 13649 LSBase->getMemoryVT(), LSBase->getMemOperand()); 13650 } 13651 13652 llvm_unreachable("Expected a load or store node here"); 13653 } 13654 13655 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N, 13656 DAGCombinerInfo &DCI) const { 13657 SelectionDAG &DAG = DCI.DAG; 13658 SDLoc dl(N); 13659 switch (N->getOpcode()) { 13660 default: break; 13661 case ISD::ADD: 13662 return combineADD(N, DCI); 13663 case ISD::SHL: 13664 return combineSHL(N, DCI); 13665 case ISD::SRA: 13666 return combineSRA(N, DCI); 13667 case ISD::SRL: 13668 return combineSRL(N, DCI); 13669 case ISD::MUL: 13670 return combineMUL(N, DCI); 13671 case PPCISD::SHL: 13672 if (isNullConstant(N->getOperand(0))) // 0 << V -> 0. 13673 return N->getOperand(0); 13674 break; 13675 case PPCISD::SRL: 13676 if (isNullConstant(N->getOperand(0))) // 0 >>u V -> 0. 13677 return N->getOperand(0); 13678 break; 13679 case PPCISD::SRA: 13680 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) { 13681 if (C->isNullValue() || // 0 >>s V -> 0. 13682 C->isAllOnesValue()) // -1 >>s V -> -1. 13683 return N->getOperand(0); 13684 } 13685 break; 13686 case ISD::SIGN_EXTEND: 13687 case ISD::ZERO_EXTEND: 13688 case ISD::ANY_EXTEND: 13689 return DAGCombineExtBoolTrunc(N, DCI); 13690 case ISD::TRUNCATE: 13691 return combineTRUNCATE(N, DCI); 13692 case ISD::SETCC: 13693 if (SDValue CSCC = combineSetCC(N, DCI)) 13694 return CSCC; 13695 LLVM_FALLTHROUGH; 13696 case ISD::SELECT_CC: 13697 return DAGCombineTruncBoolExt(N, DCI); 13698 case ISD::SINT_TO_FP: 13699 case ISD::UINT_TO_FP: 13700 return combineFPToIntToFP(N, DCI); 13701 case ISD::VECTOR_SHUFFLE: 13702 if (ISD::isNormalLoad(N->getOperand(0).getNode())) { 13703 LSBaseSDNode* LSBase = cast<LSBaseSDNode>(N->getOperand(0)); 13704 return combineVReverseMemOP(cast<ShuffleVectorSDNode>(N), LSBase, DCI); 13705 } 13706 break; 13707 case ISD::STORE: { 13708 13709 EVT Op1VT = N->getOperand(1).getValueType(); 13710 unsigned Opcode = N->getOperand(1).getOpcode(); 13711 13712 if (Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT) { 13713 SDValue Val= combineStoreFPToInt(N, DCI); 13714 if (Val) 13715 return Val; 13716 } 13717 13718 if (Opcode == ISD::VECTOR_SHUFFLE && ISD::isNormalStore(N)) { 13719 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N->getOperand(1)); 13720 SDValue Val= combineVReverseMemOP(SVN, cast<LSBaseSDNode>(N), DCI); 13721 if (Val) 13722 return Val; 13723 } 13724 13725 // Turn STORE (BSWAP) -> sthbrx/stwbrx. 13726 if (cast<StoreSDNode>(N)->isUnindexed() && Opcode == ISD::BSWAP && 13727 N->getOperand(1).getNode()->hasOneUse() && 13728 (Op1VT == MVT::i32 || Op1VT == MVT::i16 || 13729 (Subtarget.hasLDBRX() && Subtarget.isPPC64() && Op1VT == MVT::i64))) { 13730 13731 // STBRX can only handle simple types and it makes no sense to store less 13732 // two bytes in byte-reversed order. 13733 EVT mVT = cast<StoreSDNode>(N)->getMemoryVT(); 13734 if (mVT.isExtended() || mVT.getSizeInBits() < 16) 13735 break; 13736 13737 SDValue BSwapOp = N->getOperand(1).getOperand(0); 13738 // Do an any-extend to 32-bits if this is a half-word input. 13739 if (BSwapOp.getValueType() == MVT::i16) 13740 BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp); 13741 13742 // If the type of BSWAP operand is wider than stored memory width 13743 // it need to be shifted to the right side before STBRX. 13744 if (Op1VT.bitsGT(mVT)) { 13745 int Shift = Op1VT.getSizeInBits() - mVT.getSizeInBits(); 13746 BSwapOp = DAG.getNode(ISD::SRL, dl, Op1VT, BSwapOp, 13747 DAG.getConstant(Shift, dl, MVT::i32)); 13748 // Need to truncate if this is a bswap of i64 stored as i32/i16. 13749 if (Op1VT == MVT::i64) 13750 BSwapOp = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BSwapOp); 13751 } 13752 13753 SDValue Ops[] = { 13754 N->getOperand(0), BSwapOp, N->getOperand(2), DAG.getValueType(mVT) 13755 }; 13756 return 13757 DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other), 13758 Ops, cast<StoreSDNode>(N)->getMemoryVT(), 13759 cast<StoreSDNode>(N)->getMemOperand()); 13760 } 13761 13762 // STORE Constant:i32<0> -> STORE<trunc to i32> Constant:i64<0> 13763 // So it can increase the chance of CSE constant construction. 13764 if (Subtarget.isPPC64() && !DCI.isBeforeLegalize() && 13765 isa<ConstantSDNode>(N->getOperand(1)) && Op1VT == MVT::i32) { 13766 // Need to sign-extended to 64-bits to handle negative values. 13767 EVT MemVT = cast<StoreSDNode>(N)->getMemoryVT(); 13768 uint64_t Val64 = SignExtend64(N->getConstantOperandVal(1), 13769 MemVT.getSizeInBits()); 13770 SDValue Const64 = DAG.getConstant(Val64, dl, MVT::i64); 13771 13772 // DAG.getTruncStore() can't be used here because it doesn't accept 13773 // the general (base + offset) addressing mode. 13774 // So we use UpdateNodeOperands and setTruncatingStore instead. 13775 DAG.UpdateNodeOperands(N, N->getOperand(0), Const64, N->getOperand(2), 13776 N->getOperand(3)); 13777 cast<StoreSDNode>(N)->setTruncatingStore(true); 13778 return SDValue(N, 0); 13779 } 13780 13781 // For little endian, VSX stores require generating xxswapd/lxvd2x. 13782 // Not needed on ISA 3.0 based CPUs since we have a non-permuting store. 13783 if (Op1VT.isSimple()) { 13784 MVT StoreVT = Op1VT.getSimpleVT(); 13785 if (Subtarget.needsSwapsForVSXMemOps() && 13786 (StoreVT == MVT::v2f64 || StoreVT == MVT::v2i64 || 13787 StoreVT == MVT::v4f32 || StoreVT == MVT::v4i32)) 13788 return expandVSXStoreForLE(N, DCI); 13789 } 13790 break; 13791 } 13792 case ISD::LOAD: { 13793 LoadSDNode *LD = cast<LoadSDNode>(N); 13794 EVT VT = LD->getValueType(0); 13795 13796 // For little endian, VSX loads require generating lxvd2x/xxswapd. 13797 // Not needed on ISA 3.0 based CPUs since we have a non-permuting load. 13798 if (VT.isSimple()) { 13799 MVT LoadVT = VT.getSimpleVT(); 13800 if (Subtarget.needsSwapsForVSXMemOps() && 13801 (LoadVT == MVT::v2f64 || LoadVT == MVT::v2i64 || 13802 LoadVT == MVT::v4f32 || LoadVT == MVT::v4i32)) 13803 return expandVSXLoadForLE(N, DCI); 13804 } 13805 13806 // We sometimes end up with a 64-bit integer load, from which we extract 13807 // two single-precision floating-point numbers. This happens with 13808 // std::complex<float>, and other similar structures, because of the way we 13809 // canonicalize structure copies. However, if we lack direct moves, 13810 // then the final bitcasts from the extracted integer values to the 13811 // floating-point numbers turn into store/load pairs. Even with direct moves, 13812 // just loading the two floating-point numbers is likely better. 13813 auto ReplaceTwoFloatLoad = [&]() { 13814 if (VT != MVT::i64) 13815 return false; 13816 13817 if (LD->getExtensionType() != ISD::NON_EXTLOAD || 13818 LD->isVolatile()) 13819 return false; 13820 13821 // We're looking for a sequence like this: 13822 // t13: i64,ch = load<LD8[%ref.tmp]> t0, t6, undef:i64 13823 // t16: i64 = srl t13, Constant:i32<32> 13824 // t17: i32 = truncate t16 13825 // t18: f32 = bitcast t17 13826 // t19: i32 = truncate t13 13827 // t20: f32 = bitcast t19 13828 13829 if (!LD->hasNUsesOfValue(2, 0)) 13830 return false; 13831 13832 auto UI = LD->use_begin(); 13833 while (UI.getUse().getResNo() != 0) ++UI; 13834 SDNode *Trunc = *UI++; 13835 while (UI.getUse().getResNo() != 0) ++UI; 13836 SDNode *RightShift = *UI; 13837 if (Trunc->getOpcode() != ISD::TRUNCATE) 13838 std::swap(Trunc, RightShift); 13839 13840 if (Trunc->getOpcode() != ISD::TRUNCATE || 13841 Trunc->getValueType(0) != MVT::i32 || 13842 !Trunc->hasOneUse()) 13843 return false; 13844 if (RightShift->getOpcode() != ISD::SRL || 13845 !isa<ConstantSDNode>(RightShift->getOperand(1)) || 13846 RightShift->getConstantOperandVal(1) != 32 || 13847 !RightShift->hasOneUse()) 13848 return false; 13849 13850 SDNode *Trunc2 = *RightShift->use_begin(); 13851 if (Trunc2->getOpcode() != ISD::TRUNCATE || 13852 Trunc2->getValueType(0) != MVT::i32 || 13853 !Trunc2->hasOneUse()) 13854 return false; 13855 13856 SDNode *Bitcast = *Trunc->use_begin(); 13857 SDNode *Bitcast2 = *Trunc2->use_begin(); 13858 13859 if (Bitcast->getOpcode() != ISD::BITCAST || 13860 Bitcast->getValueType(0) != MVT::f32) 13861 return false; 13862 if (Bitcast2->getOpcode() != ISD::BITCAST || 13863 Bitcast2->getValueType(0) != MVT::f32) 13864 return false; 13865 13866 if (Subtarget.isLittleEndian()) 13867 std::swap(Bitcast, Bitcast2); 13868 13869 // Bitcast has the second float (in memory-layout order) and Bitcast2 13870 // has the first one. 13871 13872 SDValue BasePtr = LD->getBasePtr(); 13873 if (LD->isIndexed()) { 13874 assert(LD->getAddressingMode() == ISD::PRE_INC && 13875 "Non-pre-inc AM on PPC?"); 13876 BasePtr = 13877 DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, 13878 LD->getOffset()); 13879 } 13880 13881 auto MMOFlags = 13882 LD->getMemOperand()->getFlags() & ~MachineMemOperand::MOVolatile; 13883 SDValue FloatLoad = DAG.getLoad(MVT::f32, dl, LD->getChain(), BasePtr, 13884 LD->getPointerInfo(), LD->getAlignment(), 13885 MMOFlags, LD->getAAInfo()); 13886 SDValue AddPtr = 13887 DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), 13888 BasePtr, DAG.getIntPtrConstant(4, dl)); 13889 SDValue FloatLoad2 = DAG.getLoad( 13890 MVT::f32, dl, SDValue(FloatLoad.getNode(), 1), AddPtr, 13891 LD->getPointerInfo().getWithOffset(4), 13892 MinAlign(LD->getAlignment(), 4), MMOFlags, LD->getAAInfo()); 13893 13894 if (LD->isIndexed()) { 13895 // Note that DAGCombine should re-form any pre-increment load(s) from 13896 // what is produced here if that makes sense. 13897 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), BasePtr); 13898 } 13899 13900 DCI.CombineTo(Bitcast2, FloatLoad); 13901 DCI.CombineTo(Bitcast, FloatLoad2); 13902 13903 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, LD->isIndexed() ? 2 : 1), 13904 SDValue(FloatLoad2.getNode(), 1)); 13905 return true; 13906 }; 13907 13908 if (ReplaceTwoFloatLoad()) 13909 return SDValue(N, 0); 13910 13911 EVT MemVT = LD->getMemoryVT(); 13912 Type *Ty = MemVT.getTypeForEVT(*DAG.getContext()); 13913 unsigned ABIAlignment = DAG.getDataLayout().getABITypeAlignment(Ty); 13914 Type *STy = MemVT.getScalarType().getTypeForEVT(*DAG.getContext()); 13915 unsigned ScalarABIAlignment = DAG.getDataLayout().getABITypeAlignment(STy); 13916 if (LD->isUnindexed() && VT.isVector() && 13917 ((Subtarget.hasAltivec() && ISD::isNON_EXTLoad(N) && 13918 // P8 and later hardware should just use LOAD. 13919 !Subtarget.hasP8Vector() && (VT == MVT::v16i8 || VT == MVT::v8i16 || 13920 VT == MVT::v4i32 || VT == MVT::v4f32)) || 13921 (Subtarget.hasQPX() && (VT == MVT::v4f64 || VT == MVT::v4f32) && 13922 LD->getAlignment() >= ScalarABIAlignment)) && 13923 LD->getAlignment() < ABIAlignment) { 13924 // This is a type-legal unaligned Altivec or QPX load. 13925 SDValue Chain = LD->getChain(); 13926 SDValue Ptr = LD->getBasePtr(); 13927 bool isLittleEndian = Subtarget.isLittleEndian(); 13928 13929 // This implements the loading of unaligned vectors as described in 13930 // the venerable Apple Velocity Engine overview. Specifically: 13931 // https://developer.apple.com/hardwaredrivers/ve/alignment.html 13932 // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html 13933 // 13934 // The general idea is to expand a sequence of one or more unaligned 13935 // loads into an alignment-based permutation-control instruction (lvsl 13936 // or lvsr), a series of regular vector loads (which always truncate 13937 // their input address to an aligned address), and a series of 13938 // permutations. The results of these permutations are the requested 13939 // loaded values. The trick is that the last "extra" load is not taken 13940 // from the address you might suspect (sizeof(vector) bytes after the 13941 // last requested load), but rather sizeof(vector) - 1 bytes after the 13942 // last requested vector. The point of this is to avoid a page fault if 13943 // the base address happened to be aligned. This works because if the 13944 // base address is aligned, then adding less than a full vector length 13945 // will cause the last vector in the sequence to be (re)loaded. 13946 // Otherwise, the next vector will be fetched as you might suspect was 13947 // necessary. 13948 13949 // We might be able to reuse the permutation generation from 13950 // a different base address offset from this one by an aligned amount. 13951 // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this 13952 // optimization later. 13953 Intrinsic::ID Intr, IntrLD, IntrPerm; 13954 MVT PermCntlTy, PermTy, LDTy; 13955 if (Subtarget.hasAltivec()) { 13956 Intr = isLittleEndian ? Intrinsic::ppc_altivec_lvsr : 13957 Intrinsic::ppc_altivec_lvsl; 13958 IntrLD = Intrinsic::ppc_altivec_lvx; 13959 IntrPerm = Intrinsic::ppc_altivec_vperm; 13960 PermCntlTy = MVT::v16i8; 13961 PermTy = MVT::v4i32; 13962 LDTy = MVT::v4i32; 13963 } else { 13964 Intr = MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlpcld : 13965 Intrinsic::ppc_qpx_qvlpcls; 13966 IntrLD = MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlfd : 13967 Intrinsic::ppc_qpx_qvlfs; 13968 IntrPerm = Intrinsic::ppc_qpx_qvfperm; 13969 PermCntlTy = MVT::v4f64; 13970 PermTy = MVT::v4f64; 13971 LDTy = MemVT.getSimpleVT(); 13972 } 13973 13974 SDValue PermCntl = BuildIntrinsicOp(Intr, Ptr, DAG, dl, PermCntlTy); 13975 13976 // Create the new MMO for the new base load. It is like the original MMO, 13977 // but represents an area in memory almost twice the vector size centered 13978 // on the original address. If the address is unaligned, we might start 13979 // reading up to (sizeof(vector)-1) bytes below the address of the 13980 // original unaligned load. 13981 MachineFunction &MF = DAG.getMachineFunction(); 13982 MachineMemOperand *BaseMMO = 13983 MF.getMachineMemOperand(LD->getMemOperand(), 13984 -(long)MemVT.getStoreSize()+1, 13985 2*MemVT.getStoreSize()-1); 13986 13987 // Create the new base load. 13988 SDValue LDXIntID = 13989 DAG.getTargetConstant(IntrLD, dl, getPointerTy(MF.getDataLayout())); 13990 SDValue BaseLoadOps[] = { Chain, LDXIntID, Ptr }; 13991 SDValue BaseLoad = 13992 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl, 13993 DAG.getVTList(PermTy, MVT::Other), 13994 BaseLoadOps, LDTy, BaseMMO); 13995 13996 // Note that the value of IncOffset (which is provided to the next 13997 // load's pointer info offset value, and thus used to calculate the 13998 // alignment), and the value of IncValue (which is actually used to 13999 // increment the pointer value) are different! This is because we 14000 // require the next load to appear to be aligned, even though it 14001 // is actually offset from the base pointer by a lesser amount. 14002 int IncOffset = VT.getSizeInBits() / 8; 14003 int IncValue = IncOffset; 14004 14005 // Walk (both up and down) the chain looking for another load at the real 14006 // (aligned) offset (the alignment of the other load does not matter in 14007 // this case). If found, then do not use the offset reduction trick, as 14008 // that will prevent the loads from being later combined (as they would 14009 // otherwise be duplicates). 14010 if (!findConsecutiveLoad(LD, DAG)) 14011 --IncValue; 14012 14013 SDValue Increment = 14014 DAG.getConstant(IncValue, dl, getPointerTy(MF.getDataLayout())); 14015 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment); 14016 14017 MachineMemOperand *ExtraMMO = 14018 MF.getMachineMemOperand(LD->getMemOperand(), 14019 1, 2*MemVT.getStoreSize()-1); 14020 SDValue ExtraLoadOps[] = { Chain, LDXIntID, Ptr }; 14021 SDValue ExtraLoad = 14022 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl, 14023 DAG.getVTList(PermTy, MVT::Other), 14024 ExtraLoadOps, LDTy, ExtraMMO); 14025 14026 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 14027 BaseLoad.getValue(1), ExtraLoad.getValue(1)); 14028 14029 // Because vperm has a big-endian bias, we must reverse the order 14030 // of the input vectors and complement the permute control vector 14031 // when generating little endian code. We have already handled the 14032 // latter by using lvsr instead of lvsl, so just reverse BaseLoad 14033 // and ExtraLoad here. 14034 SDValue Perm; 14035 if (isLittleEndian) 14036 Perm = BuildIntrinsicOp(IntrPerm, 14037 ExtraLoad, BaseLoad, PermCntl, DAG, dl); 14038 else 14039 Perm = BuildIntrinsicOp(IntrPerm, 14040 BaseLoad, ExtraLoad, PermCntl, DAG, dl); 14041 14042 if (VT != PermTy) 14043 Perm = Subtarget.hasAltivec() ? 14044 DAG.getNode(ISD::BITCAST, dl, VT, Perm) : 14045 DAG.getNode(ISD::FP_ROUND, dl, VT, Perm, // QPX 14046 DAG.getTargetConstant(1, dl, MVT::i64)); 14047 // second argument is 1 because this rounding 14048 // is always exact. 14049 14050 // The output of the permutation is our loaded result, the TokenFactor is 14051 // our new chain. 14052 DCI.CombineTo(N, Perm, TF); 14053 return SDValue(N, 0); 14054 } 14055 } 14056 break; 14057 case ISD::INTRINSIC_WO_CHAIN: { 14058 bool isLittleEndian = Subtarget.isLittleEndian(); 14059 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 14060 Intrinsic::ID Intr = (isLittleEndian ? Intrinsic::ppc_altivec_lvsr 14061 : Intrinsic::ppc_altivec_lvsl); 14062 if ((IID == Intr || 14063 IID == Intrinsic::ppc_qpx_qvlpcld || 14064 IID == Intrinsic::ppc_qpx_qvlpcls) && 14065 N->getOperand(1)->getOpcode() == ISD::ADD) { 14066 SDValue Add = N->getOperand(1); 14067 14068 int Bits = IID == Intrinsic::ppc_qpx_qvlpcld ? 14069 5 /* 32 byte alignment */ : 4 /* 16 byte alignment */; 14070 14071 if (DAG.MaskedValueIsZero(Add->getOperand(1), 14072 APInt::getAllOnesValue(Bits /* alignment */) 14073 .zext(Add.getScalarValueSizeInBits()))) { 14074 SDNode *BasePtr = Add->getOperand(0).getNode(); 14075 for (SDNode::use_iterator UI = BasePtr->use_begin(), 14076 UE = BasePtr->use_end(); 14077 UI != UE; ++UI) { 14078 if (UI->getOpcode() == ISD::INTRINSIC_WO_CHAIN && 14079 cast<ConstantSDNode>(UI->getOperand(0))->getZExtValue() == IID) { 14080 // We've found another LVSL/LVSR, and this address is an aligned 14081 // multiple of that one. The results will be the same, so use the 14082 // one we've just found instead. 14083 14084 return SDValue(*UI, 0); 14085 } 14086 } 14087 } 14088 14089 if (isa<ConstantSDNode>(Add->getOperand(1))) { 14090 SDNode *BasePtr = Add->getOperand(0).getNode(); 14091 for (SDNode::use_iterator UI = BasePtr->use_begin(), 14092 UE = BasePtr->use_end(); UI != UE; ++UI) { 14093 if (UI->getOpcode() == ISD::ADD && 14094 isa<ConstantSDNode>(UI->getOperand(1)) && 14095 (cast<ConstantSDNode>(Add->getOperand(1))->getZExtValue() - 14096 cast<ConstantSDNode>(UI->getOperand(1))->getZExtValue()) % 14097 (1ULL << Bits) == 0) { 14098 SDNode *OtherAdd = *UI; 14099 for (SDNode::use_iterator VI = OtherAdd->use_begin(), 14100 VE = OtherAdd->use_end(); VI != VE; ++VI) { 14101 if (VI->getOpcode() == ISD::INTRINSIC_WO_CHAIN && 14102 cast<ConstantSDNode>(VI->getOperand(0))->getZExtValue() == IID) { 14103 return SDValue(*VI, 0); 14104 } 14105 } 14106 } 14107 } 14108 } 14109 } 14110 14111 // Combine vmaxsw/h/b(a, a's negation) to abs(a) 14112 // Expose the vabsduw/h/b opportunity for down stream 14113 if (!DCI.isAfterLegalizeDAG() && Subtarget.hasP9Altivec() && 14114 (IID == Intrinsic::ppc_altivec_vmaxsw || 14115 IID == Intrinsic::ppc_altivec_vmaxsh || 14116 IID == Intrinsic::ppc_altivec_vmaxsb)) { 14117 SDValue V1 = N->getOperand(1); 14118 SDValue V2 = N->getOperand(2); 14119 if ((V1.getSimpleValueType() == MVT::v4i32 || 14120 V1.getSimpleValueType() == MVT::v8i16 || 14121 V1.getSimpleValueType() == MVT::v16i8) && 14122 V1.getSimpleValueType() == V2.getSimpleValueType()) { 14123 // (0-a, a) 14124 if (V1.getOpcode() == ISD::SUB && 14125 ISD::isBuildVectorAllZeros(V1.getOperand(0).getNode()) && 14126 V1.getOperand(1) == V2) { 14127 return DAG.getNode(ISD::ABS, dl, V2.getValueType(), V2); 14128 } 14129 // (a, 0-a) 14130 if (V2.getOpcode() == ISD::SUB && 14131 ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()) && 14132 V2.getOperand(1) == V1) { 14133 return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1); 14134 } 14135 // (x-y, y-x) 14136 if (V1.getOpcode() == ISD::SUB && V2.getOpcode() == ISD::SUB && 14137 V1.getOperand(0) == V2.getOperand(1) && 14138 V1.getOperand(1) == V2.getOperand(0)) { 14139 return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1); 14140 } 14141 } 14142 } 14143 } 14144 14145 break; 14146 case ISD::INTRINSIC_W_CHAIN: 14147 // For little endian, VSX loads require generating lxvd2x/xxswapd. 14148 // Not needed on ISA 3.0 based CPUs since we have a non-permuting load. 14149 if (Subtarget.needsSwapsForVSXMemOps()) { 14150 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 14151 default: 14152 break; 14153 case Intrinsic::ppc_vsx_lxvw4x: 14154 case Intrinsic::ppc_vsx_lxvd2x: 14155 return expandVSXLoadForLE(N, DCI); 14156 } 14157 } 14158 break; 14159 case ISD::INTRINSIC_VOID: 14160 // For little endian, VSX stores require generating xxswapd/stxvd2x. 14161 // Not needed on ISA 3.0 based CPUs since we have a non-permuting store. 14162 if (Subtarget.needsSwapsForVSXMemOps()) { 14163 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 14164 default: 14165 break; 14166 case Intrinsic::ppc_vsx_stxvw4x: 14167 case Intrinsic::ppc_vsx_stxvd2x: 14168 return expandVSXStoreForLE(N, DCI); 14169 } 14170 } 14171 break; 14172 case ISD::BSWAP: 14173 // Turn BSWAP (LOAD) -> lhbrx/lwbrx. 14174 if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) && 14175 N->getOperand(0).hasOneUse() && 14176 (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 || 14177 (Subtarget.hasLDBRX() && Subtarget.isPPC64() && 14178 N->getValueType(0) == MVT::i64))) { 14179 SDValue Load = N->getOperand(0); 14180 LoadSDNode *LD = cast<LoadSDNode>(Load); 14181 // Create the byte-swapping load. 14182 SDValue Ops[] = { 14183 LD->getChain(), // Chain 14184 LD->getBasePtr(), // Ptr 14185 DAG.getValueType(N->getValueType(0)) // VT 14186 }; 14187 SDValue BSLoad = 14188 DAG.getMemIntrinsicNode(PPCISD::LBRX, dl, 14189 DAG.getVTList(N->getValueType(0) == MVT::i64 ? 14190 MVT::i64 : MVT::i32, MVT::Other), 14191 Ops, LD->getMemoryVT(), LD->getMemOperand()); 14192 14193 // If this is an i16 load, insert the truncate. 14194 SDValue ResVal = BSLoad; 14195 if (N->getValueType(0) == MVT::i16) 14196 ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad); 14197 14198 // First, combine the bswap away. This makes the value produced by the 14199 // load dead. 14200 DCI.CombineTo(N, ResVal); 14201 14202 // Next, combine the load away, we give it a bogus result value but a real 14203 // chain result. The result value is dead because the bswap is dead. 14204 DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1)); 14205 14206 // Return N so it doesn't get rechecked! 14207 return SDValue(N, 0); 14208 } 14209 break; 14210 case PPCISD::VCMP: 14211 // If a VCMPo node already exists with exactly the same operands as this 14212 // node, use its result instead of this node (VCMPo computes both a CR6 and 14213 // a normal output). 14214 // 14215 if (!N->getOperand(0).hasOneUse() && 14216 !N->getOperand(1).hasOneUse() && 14217 !N->getOperand(2).hasOneUse()) { 14218 14219 // Scan all of the users of the LHS, looking for VCMPo's that match. 14220 SDNode *VCMPoNode = nullptr; 14221 14222 SDNode *LHSN = N->getOperand(0).getNode(); 14223 for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end(); 14224 UI != E; ++UI) 14225 if (UI->getOpcode() == PPCISD::VCMPo && 14226 UI->getOperand(1) == N->getOperand(1) && 14227 UI->getOperand(2) == N->getOperand(2) && 14228 UI->getOperand(0) == N->getOperand(0)) { 14229 VCMPoNode = *UI; 14230 break; 14231 } 14232 14233 // If there is no VCMPo node, or if the flag value has a single use, don't 14234 // transform this. 14235 if (!VCMPoNode || VCMPoNode->hasNUsesOfValue(0, 1)) 14236 break; 14237 14238 // Look at the (necessarily single) use of the flag value. If it has a 14239 // chain, this transformation is more complex. Note that multiple things 14240 // could use the value result, which we should ignore. 14241 SDNode *FlagUser = nullptr; 14242 for (SDNode::use_iterator UI = VCMPoNode->use_begin(); 14243 FlagUser == nullptr; ++UI) { 14244 assert(UI != VCMPoNode->use_end() && "Didn't find user!"); 14245 SDNode *User = *UI; 14246 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) { 14247 if (User->getOperand(i) == SDValue(VCMPoNode, 1)) { 14248 FlagUser = User; 14249 break; 14250 } 14251 } 14252 } 14253 14254 // If the user is a MFOCRF instruction, we know this is safe. 14255 // Otherwise we give up for right now. 14256 if (FlagUser->getOpcode() == PPCISD::MFOCRF) 14257 return SDValue(VCMPoNode, 0); 14258 } 14259 break; 14260 case ISD::BRCOND: { 14261 SDValue Cond = N->getOperand(1); 14262 SDValue Target = N->getOperand(2); 14263 14264 if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN && 14265 cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() == 14266 Intrinsic::loop_decrement) { 14267 14268 // We now need to make the intrinsic dead (it cannot be instruction 14269 // selected). 14270 DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0)); 14271 assert(Cond.getNode()->hasOneUse() && 14272 "Counter decrement has more than one use"); 14273 14274 return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other, 14275 N->getOperand(0), Target); 14276 } 14277 } 14278 break; 14279 case ISD::BR_CC: { 14280 // If this is a branch on an altivec predicate comparison, lower this so 14281 // that we don't have to do a MFOCRF: instead, branch directly on CR6. This 14282 // lowering is done pre-legalize, because the legalizer lowers the predicate 14283 // compare down to code that is difficult to reassemble. 14284 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get(); 14285 SDValue LHS = N->getOperand(2), RHS = N->getOperand(3); 14286 14287 // Sometimes the promoted value of the intrinsic is ANDed by some non-zero 14288 // value. If so, pass-through the AND to get to the intrinsic. 14289 if (LHS.getOpcode() == ISD::AND && 14290 LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN && 14291 cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() == 14292 Intrinsic::loop_decrement && 14293 isa<ConstantSDNode>(LHS.getOperand(1)) && 14294 !isNullConstant(LHS.getOperand(1))) 14295 LHS = LHS.getOperand(0); 14296 14297 if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN && 14298 cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() == 14299 Intrinsic::loop_decrement && 14300 isa<ConstantSDNode>(RHS)) { 14301 assert((CC == ISD::SETEQ || CC == ISD::SETNE) && 14302 "Counter decrement comparison is not EQ or NE"); 14303 14304 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue(); 14305 bool isBDNZ = (CC == ISD::SETEQ && Val) || 14306 (CC == ISD::SETNE && !Val); 14307 14308 // We now need to make the intrinsic dead (it cannot be instruction 14309 // selected). 14310 DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0)); 14311 assert(LHS.getNode()->hasOneUse() && 14312 "Counter decrement has more than one use"); 14313 14314 return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other, 14315 N->getOperand(0), N->getOperand(4)); 14316 } 14317 14318 int CompareOpc; 14319 bool isDot; 14320 14321 if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN && 14322 isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) && 14323 getVectorCompareInfo(LHS, CompareOpc, isDot, Subtarget)) { 14324 assert(isDot && "Can't compare against a vector result!"); 14325 14326 // If this is a comparison against something other than 0/1, then we know 14327 // that the condition is never/always true. 14328 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue(); 14329 if (Val != 0 && Val != 1) { 14330 if (CC == ISD::SETEQ) // Cond never true, remove branch. 14331 return N->getOperand(0); 14332 // Always !=, turn it into an unconditional branch. 14333 return DAG.getNode(ISD::BR, dl, MVT::Other, 14334 N->getOperand(0), N->getOperand(4)); 14335 } 14336 14337 bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0); 14338 14339 // Create the PPCISD altivec 'dot' comparison node. 14340 SDValue Ops[] = { 14341 LHS.getOperand(2), // LHS of compare 14342 LHS.getOperand(3), // RHS of compare 14343 DAG.getConstant(CompareOpc, dl, MVT::i32) 14344 }; 14345 EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue }; 14346 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops); 14347 14348 // Unpack the result based on how the target uses it. 14349 PPC::Predicate CompOpc; 14350 switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) { 14351 default: // Can't happen, don't crash on invalid number though. 14352 case 0: // Branch on the value of the EQ bit of CR6. 14353 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE; 14354 break; 14355 case 1: // Branch on the inverted value of the EQ bit of CR6. 14356 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ; 14357 break; 14358 case 2: // Branch on the value of the LT bit of CR6. 14359 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE; 14360 break; 14361 case 3: // Branch on the inverted value of the LT bit of CR6. 14362 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT; 14363 break; 14364 } 14365 14366 return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0), 14367 DAG.getConstant(CompOpc, dl, MVT::i32), 14368 DAG.getRegister(PPC::CR6, MVT::i32), 14369 N->getOperand(4), CompNode.getValue(1)); 14370 } 14371 break; 14372 } 14373 case ISD::BUILD_VECTOR: 14374 return DAGCombineBuildVector(N, DCI); 14375 case ISD::ABS: 14376 return combineABS(N, DCI); 14377 case ISD::VSELECT: 14378 return combineVSelect(N, DCI); 14379 } 14380 14381 return SDValue(); 14382 } 14383 14384 SDValue 14385 PPCTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor, 14386 SelectionDAG &DAG, 14387 SmallVectorImpl<SDNode *> &Created) const { 14388 // fold (sdiv X, pow2) 14389 EVT VT = N->getValueType(0); 14390 if (VT == MVT::i64 && !Subtarget.isPPC64()) 14391 return SDValue(); 14392 if ((VT != MVT::i32 && VT != MVT::i64) || 14393 !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2())) 14394 return SDValue(); 14395 14396 SDLoc DL(N); 14397 SDValue N0 = N->getOperand(0); 14398 14399 bool IsNegPow2 = (-Divisor).isPowerOf2(); 14400 unsigned Lg2 = (IsNegPow2 ? -Divisor : Divisor).countTrailingZeros(); 14401 SDValue ShiftAmt = DAG.getConstant(Lg2, DL, VT); 14402 14403 SDValue Op = DAG.getNode(PPCISD::SRA_ADDZE, DL, VT, N0, ShiftAmt); 14404 Created.push_back(Op.getNode()); 14405 14406 if (IsNegPow2) { 14407 Op = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Op); 14408 Created.push_back(Op.getNode()); 14409 } 14410 14411 return Op; 14412 } 14413 14414 //===----------------------------------------------------------------------===// 14415 // Inline Assembly Support 14416 //===----------------------------------------------------------------------===// 14417 14418 void PPCTargetLowering::computeKnownBitsForTargetNode(const SDValue Op, 14419 KnownBits &Known, 14420 const APInt &DemandedElts, 14421 const SelectionDAG &DAG, 14422 unsigned Depth) const { 14423 Known.resetAll(); 14424 switch (Op.getOpcode()) { 14425 default: break; 14426 case PPCISD::LBRX: { 14427 // lhbrx is known to have the top bits cleared out. 14428 if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16) 14429 Known.Zero = 0xFFFF0000; 14430 break; 14431 } 14432 case ISD::INTRINSIC_WO_CHAIN: { 14433 switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) { 14434 default: break; 14435 case Intrinsic::ppc_altivec_vcmpbfp_p: 14436 case Intrinsic::ppc_altivec_vcmpeqfp_p: 14437 case Intrinsic::ppc_altivec_vcmpequb_p: 14438 case Intrinsic::ppc_altivec_vcmpequh_p: 14439 case Intrinsic::ppc_altivec_vcmpequw_p: 14440 case Intrinsic::ppc_altivec_vcmpequd_p: 14441 case Intrinsic::ppc_altivec_vcmpgefp_p: 14442 case Intrinsic::ppc_altivec_vcmpgtfp_p: 14443 case Intrinsic::ppc_altivec_vcmpgtsb_p: 14444 case Intrinsic::ppc_altivec_vcmpgtsh_p: 14445 case Intrinsic::ppc_altivec_vcmpgtsw_p: 14446 case Intrinsic::ppc_altivec_vcmpgtsd_p: 14447 case Intrinsic::ppc_altivec_vcmpgtub_p: 14448 case Intrinsic::ppc_altivec_vcmpgtuh_p: 14449 case Intrinsic::ppc_altivec_vcmpgtuw_p: 14450 case Intrinsic::ppc_altivec_vcmpgtud_p: 14451 Known.Zero = ~1U; // All bits but the low one are known to be zero. 14452 break; 14453 } 14454 } 14455 } 14456 } 14457 14458 Align PPCTargetLowering::getPrefLoopAlignment(MachineLoop *ML) const { 14459 switch (Subtarget.getCPUDirective()) { 14460 default: break; 14461 case PPC::DIR_970: 14462 case PPC::DIR_PWR4: 14463 case PPC::DIR_PWR5: 14464 case PPC::DIR_PWR5X: 14465 case PPC::DIR_PWR6: 14466 case PPC::DIR_PWR6X: 14467 case PPC::DIR_PWR7: 14468 case PPC::DIR_PWR8: 14469 case PPC::DIR_PWR9: 14470 case PPC::DIR_PWR_FUTURE: { 14471 if (!ML) 14472 break; 14473 14474 if (!DisableInnermostLoopAlign32) { 14475 // If the nested loop is an innermost loop, prefer to a 32-byte alignment, 14476 // so that we can decrease cache misses and branch-prediction misses. 14477 // Actual alignment of the loop will depend on the hotness check and other 14478 // logic in alignBlocks. 14479 if (ML->getLoopDepth() > 1 && ML->getSubLoops().empty()) 14480 return Align(32); 14481 } 14482 14483 const PPCInstrInfo *TII = Subtarget.getInstrInfo(); 14484 14485 // For small loops (between 5 and 8 instructions), align to a 32-byte 14486 // boundary so that the entire loop fits in one instruction-cache line. 14487 uint64_t LoopSize = 0; 14488 for (auto I = ML->block_begin(), IE = ML->block_end(); I != IE; ++I) 14489 for (auto J = (*I)->begin(), JE = (*I)->end(); J != JE; ++J) { 14490 LoopSize += TII->getInstSizeInBytes(*J); 14491 if (LoopSize > 32) 14492 break; 14493 } 14494 14495 if (LoopSize > 16 && LoopSize <= 32) 14496 return Align(32); 14497 14498 break; 14499 } 14500 } 14501 14502 return TargetLowering::getPrefLoopAlignment(ML); 14503 } 14504 14505 /// getConstraintType - Given a constraint, return the type of 14506 /// constraint it is for this target. 14507 PPCTargetLowering::ConstraintType 14508 PPCTargetLowering::getConstraintType(StringRef Constraint) const { 14509 if (Constraint.size() == 1) { 14510 switch (Constraint[0]) { 14511 default: break; 14512 case 'b': 14513 case 'r': 14514 case 'f': 14515 case 'd': 14516 case 'v': 14517 case 'y': 14518 return C_RegisterClass; 14519 case 'Z': 14520 // FIXME: While Z does indicate a memory constraint, it specifically 14521 // indicates an r+r address (used in conjunction with the 'y' modifier 14522 // in the replacement string). Currently, we're forcing the base 14523 // register to be r0 in the asm printer (which is interpreted as zero) 14524 // and forming the complete address in the second register. This is 14525 // suboptimal. 14526 return C_Memory; 14527 } 14528 } else if (Constraint == "wc") { // individual CR bits. 14529 return C_RegisterClass; 14530 } else if (Constraint == "wa" || Constraint == "wd" || 14531 Constraint == "wf" || Constraint == "ws" || 14532 Constraint == "wi" || Constraint == "ww") { 14533 return C_RegisterClass; // VSX registers. 14534 } 14535 return TargetLowering::getConstraintType(Constraint); 14536 } 14537 14538 /// Examine constraint type and operand type and determine a weight value. 14539 /// This object must already have been set up with the operand type 14540 /// and the current alternative constraint selected. 14541 TargetLowering::ConstraintWeight 14542 PPCTargetLowering::getSingleConstraintMatchWeight( 14543 AsmOperandInfo &info, const char *constraint) const { 14544 ConstraintWeight weight = CW_Invalid; 14545 Value *CallOperandVal = info.CallOperandVal; 14546 // If we don't have a value, we can't do a match, 14547 // but allow it at the lowest weight. 14548 if (!CallOperandVal) 14549 return CW_Default; 14550 Type *type = CallOperandVal->getType(); 14551 14552 // Look at the constraint type. 14553 if (StringRef(constraint) == "wc" && type->isIntegerTy(1)) 14554 return CW_Register; // an individual CR bit. 14555 else if ((StringRef(constraint) == "wa" || 14556 StringRef(constraint) == "wd" || 14557 StringRef(constraint) == "wf") && 14558 type->isVectorTy()) 14559 return CW_Register; 14560 else if (StringRef(constraint) == "wi" && type->isIntegerTy(64)) 14561 return CW_Register; // just hold 64-bit integers data. 14562 else if (StringRef(constraint) == "ws" && type->isDoubleTy()) 14563 return CW_Register; 14564 else if (StringRef(constraint) == "ww" && type->isFloatTy()) 14565 return CW_Register; 14566 14567 switch (*constraint) { 14568 default: 14569 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint); 14570 break; 14571 case 'b': 14572 if (type->isIntegerTy()) 14573 weight = CW_Register; 14574 break; 14575 case 'f': 14576 if (type->isFloatTy()) 14577 weight = CW_Register; 14578 break; 14579 case 'd': 14580 if (type->isDoubleTy()) 14581 weight = CW_Register; 14582 break; 14583 case 'v': 14584 if (type->isVectorTy()) 14585 weight = CW_Register; 14586 break; 14587 case 'y': 14588 weight = CW_Register; 14589 break; 14590 case 'Z': 14591 weight = CW_Memory; 14592 break; 14593 } 14594 return weight; 14595 } 14596 14597 std::pair<unsigned, const TargetRegisterClass *> 14598 PPCTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, 14599 StringRef Constraint, 14600 MVT VT) const { 14601 if (Constraint.size() == 1) { 14602 // GCC RS6000 Constraint Letters 14603 switch (Constraint[0]) { 14604 case 'b': // R1-R31 14605 if (VT == MVT::i64 && Subtarget.isPPC64()) 14606 return std::make_pair(0U, &PPC::G8RC_NOX0RegClass); 14607 return std::make_pair(0U, &PPC::GPRC_NOR0RegClass); 14608 case 'r': // R0-R31 14609 if (VT == MVT::i64 && Subtarget.isPPC64()) 14610 return std::make_pair(0U, &PPC::G8RCRegClass); 14611 return std::make_pair(0U, &PPC::GPRCRegClass); 14612 // 'd' and 'f' constraints are both defined to be "the floating point 14613 // registers", where one is for 32-bit and the other for 64-bit. We don't 14614 // really care overly much here so just give them all the same reg classes. 14615 case 'd': 14616 case 'f': 14617 if (Subtarget.hasSPE()) { 14618 if (VT == MVT::f32 || VT == MVT::i32) 14619 return std::make_pair(0U, &PPC::GPRCRegClass); 14620 if (VT == MVT::f64 || VT == MVT::i64) 14621 return std::make_pair(0U, &PPC::SPERCRegClass); 14622 } else { 14623 if (VT == MVT::f32 || VT == MVT::i32) 14624 return std::make_pair(0U, &PPC::F4RCRegClass); 14625 if (VT == MVT::f64 || VT == MVT::i64) 14626 return std::make_pair(0U, &PPC::F8RCRegClass); 14627 if (VT == MVT::v4f64 && Subtarget.hasQPX()) 14628 return std::make_pair(0U, &PPC::QFRCRegClass); 14629 if (VT == MVT::v4f32 && Subtarget.hasQPX()) 14630 return std::make_pair(0U, &PPC::QSRCRegClass); 14631 } 14632 break; 14633 case 'v': 14634 if (VT == MVT::v4f64 && Subtarget.hasQPX()) 14635 return std::make_pair(0U, &PPC::QFRCRegClass); 14636 if (VT == MVT::v4f32 && Subtarget.hasQPX()) 14637 return std::make_pair(0U, &PPC::QSRCRegClass); 14638 if (Subtarget.hasAltivec()) 14639 return std::make_pair(0U, &PPC::VRRCRegClass); 14640 break; 14641 case 'y': // crrc 14642 return std::make_pair(0U, &PPC::CRRCRegClass); 14643 } 14644 } else if (Constraint == "wc" && Subtarget.useCRBits()) { 14645 // An individual CR bit. 14646 return std::make_pair(0U, &PPC::CRBITRCRegClass); 14647 } else if ((Constraint == "wa" || Constraint == "wd" || 14648 Constraint == "wf" || Constraint == "wi") && 14649 Subtarget.hasVSX()) { 14650 return std::make_pair(0U, &PPC::VSRCRegClass); 14651 } else if ((Constraint == "ws" || Constraint == "ww") && Subtarget.hasVSX()) { 14652 if (VT == MVT::f32 && Subtarget.hasP8Vector()) 14653 return std::make_pair(0U, &PPC::VSSRCRegClass); 14654 else 14655 return std::make_pair(0U, &PPC::VSFRCRegClass); 14656 } 14657 14658 // If we name a VSX register, we can't defer to the base class because it 14659 // will not recognize the correct register (their names will be VSL{0-31} 14660 // and V{0-31} so they won't match). So we match them here. 14661 if (Constraint.size() > 3 && Constraint[1] == 'v' && Constraint[2] == 's') { 14662 int VSNum = atoi(Constraint.data() + 3); 14663 assert(VSNum >= 0 && VSNum <= 63 && 14664 "Attempted to access a vsr out of range"); 14665 if (VSNum < 32) 14666 return std::make_pair(PPC::VSL0 + VSNum, &PPC::VSRCRegClass); 14667 return std::make_pair(PPC::V0 + VSNum - 32, &PPC::VSRCRegClass); 14668 } 14669 std::pair<unsigned, const TargetRegisterClass *> R = 14670 TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 14671 14672 // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers 14673 // (which we call X[0-9]+). If a 64-bit value has been requested, and a 14674 // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent 14675 // register. 14676 // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use 14677 // the AsmName field from *RegisterInfo.td, then this would not be necessary. 14678 if (R.first && VT == MVT::i64 && Subtarget.isPPC64() && 14679 PPC::GPRCRegClass.contains(R.first)) 14680 return std::make_pair(TRI->getMatchingSuperReg(R.first, 14681 PPC::sub_32, &PPC::G8RCRegClass), 14682 &PPC::G8RCRegClass); 14683 14684 // GCC accepts 'cc' as an alias for 'cr0', and we need to do the same. 14685 if (!R.second && StringRef("{cc}").equals_lower(Constraint)) { 14686 R.first = PPC::CR0; 14687 R.second = &PPC::CRRCRegClass; 14688 } 14689 14690 return R; 14691 } 14692 14693 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops 14694 /// vector. If it is invalid, don't add anything to Ops. 14695 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op, 14696 std::string &Constraint, 14697 std::vector<SDValue>&Ops, 14698 SelectionDAG &DAG) const { 14699 SDValue Result; 14700 14701 // Only support length 1 constraints. 14702 if (Constraint.length() > 1) return; 14703 14704 char Letter = Constraint[0]; 14705 switch (Letter) { 14706 default: break; 14707 case 'I': 14708 case 'J': 14709 case 'K': 14710 case 'L': 14711 case 'M': 14712 case 'N': 14713 case 'O': 14714 case 'P': { 14715 ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op); 14716 if (!CST) return; // Must be an immediate to match. 14717 SDLoc dl(Op); 14718 int64_t Value = CST->getSExtValue(); 14719 EVT TCVT = MVT::i64; // All constants taken to be 64 bits so that negative 14720 // numbers are printed as such. 14721 switch (Letter) { 14722 default: llvm_unreachable("Unknown constraint letter!"); 14723 case 'I': // "I" is a signed 16-bit constant. 14724 if (isInt<16>(Value)) 14725 Result = DAG.getTargetConstant(Value, dl, TCVT); 14726 break; 14727 case 'J': // "J" is a constant with only the high-order 16 bits nonzero. 14728 if (isShiftedUInt<16, 16>(Value)) 14729 Result = DAG.getTargetConstant(Value, dl, TCVT); 14730 break; 14731 case 'L': // "L" is a signed 16-bit constant shifted left 16 bits. 14732 if (isShiftedInt<16, 16>(Value)) 14733 Result = DAG.getTargetConstant(Value, dl, TCVT); 14734 break; 14735 case 'K': // "K" is a constant with only the low-order 16 bits nonzero. 14736 if (isUInt<16>(Value)) 14737 Result = DAG.getTargetConstant(Value, dl, TCVT); 14738 break; 14739 case 'M': // "M" is a constant that is greater than 31. 14740 if (Value > 31) 14741 Result = DAG.getTargetConstant(Value, dl, TCVT); 14742 break; 14743 case 'N': // "N" is a positive constant that is an exact power of two. 14744 if (Value > 0 && isPowerOf2_64(Value)) 14745 Result = DAG.getTargetConstant(Value, dl, TCVT); 14746 break; 14747 case 'O': // "O" is the constant zero. 14748 if (Value == 0) 14749 Result = DAG.getTargetConstant(Value, dl, TCVT); 14750 break; 14751 case 'P': // "P" is a constant whose negation is a signed 16-bit constant. 14752 if (isInt<16>(-Value)) 14753 Result = DAG.getTargetConstant(Value, dl, TCVT); 14754 break; 14755 } 14756 break; 14757 } 14758 } 14759 14760 if (Result.getNode()) { 14761 Ops.push_back(Result); 14762 return; 14763 } 14764 14765 // Handle standard constraint letters. 14766 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 14767 } 14768 14769 // isLegalAddressingMode - Return true if the addressing mode represented 14770 // by AM is legal for this target, for a load/store of the specified type. 14771 bool PPCTargetLowering::isLegalAddressingMode(const DataLayout &DL, 14772 const AddrMode &AM, Type *Ty, 14773 unsigned AS, Instruction *I) const { 14774 // PPC does not allow r+i addressing modes for vectors! 14775 if (Ty->isVectorTy() && AM.BaseOffs != 0) 14776 return false; 14777 14778 // PPC allows a sign-extended 16-bit immediate field. 14779 if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1) 14780 return false; 14781 14782 // No global is ever allowed as a base. 14783 if (AM.BaseGV) 14784 return false; 14785 14786 // PPC only support r+r, 14787 switch (AM.Scale) { 14788 case 0: // "r+i" or just "i", depending on HasBaseReg. 14789 break; 14790 case 1: 14791 if (AM.HasBaseReg && AM.BaseOffs) // "r+r+i" is not allowed. 14792 return false; 14793 // Otherwise we have r+r or r+i. 14794 break; 14795 case 2: 14796 if (AM.HasBaseReg || AM.BaseOffs) // 2*r+r or 2*r+i is not allowed. 14797 return false; 14798 // Allow 2*r as r+r. 14799 break; 14800 default: 14801 // No other scales are supported. 14802 return false; 14803 } 14804 14805 return true; 14806 } 14807 14808 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op, 14809 SelectionDAG &DAG) const { 14810 MachineFunction &MF = DAG.getMachineFunction(); 14811 MachineFrameInfo &MFI = MF.getFrameInfo(); 14812 MFI.setReturnAddressIsTaken(true); 14813 14814 if (verifyReturnAddressArgumentIsConstant(Op, DAG)) 14815 return SDValue(); 14816 14817 SDLoc dl(Op); 14818 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 14819 14820 // Make sure the function does not optimize away the store of the RA to 14821 // the stack. 14822 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 14823 FuncInfo->setLRStoreRequired(); 14824 bool isPPC64 = Subtarget.isPPC64(); 14825 auto PtrVT = getPointerTy(MF.getDataLayout()); 14826 14827 if (Depth > 0) { 14828 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG); 14829 SDValue Offset = 14830 DAG.getConstant(Subtarget.getFrameLowering()->getReturnSaveOffset(), dl, 14831 isPPC64 ? MVT::i64 : MVT::i32); 14832 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), 14833 DAG.getNode(ISD::ADD, dl, PtrVT, FrameAddr, Offset), 14834 MachinePointerInfo()); 14835 } 14836 14837 // Just load the return address off the stack. 14838 SDValue RetAddrFI = getReturnAddrFrameIndex(DAG); 14839 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), RetAddrFI, 14840 MachinePointerInfo()); 14841 } 14842 14843 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op, 14844 SelectionDAG &DAG) const { 14845 SDLoc dl(Op); 14846 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 14847 14848 MachineFunction &MF = DAG.getMachineFunction(); 14849 MachineFrameInfo &MFI = MF.getFrameInfo(); 14850 MFI.setFrameAddressIsTaken(true); 14851 14852 EVT PtrVT = getPointerTy(MF.getDataLayout()); 14853 bool isPPC64 = PtrVT == MVT::i64; 14854 14855 // Naked functions never have a frame pointer, and so we use r1. For all 14856 // other functions, this decision must be delayed until during PEI. 14857 unsigned FrameReg; 14858 if (MF.getFunction().hasFnAttribute(Attribute::Naked)) 14859 FrameReg = isPPC64 ? PPC::X1 : PPC::R1; 14860 else 14861 FrameReg = isPPC64 ? PPC::FP8 : PPC::FP; 14862 14863 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, 14864 PtrVT); 14865 while (Depth--) 14866 FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(), 14867 FrameAddr, MachinePointerInfo()); 14868 return FrameAddr; 14869 } 14870 14871 // FIXME? Maybe this could be a TableGen attribute on some registers and 14872 // this table could be generated automatically from RegInfo. 14873 Register PPCTargetLowering::getRegisterByName(const char* RegName, LLT VT, 14874 const MachineFunction &MF) const { 14875 bool isPPC64 = Subtarget.isPPC64(); 14876 14877 bool is64Bit = isPPC64 && VT == LLT::scalar(64); 14878 if (!is64Bit && VT != LLT::scalar(32)) 14879 report_fatal_error("Invalid register global variable type"); 14880 14881 Register Reg = StringSwitch<Register>(RegName) 14882 .Case("r1", is64Bit ? PPC::X1 : PPC::R1) 14883 .Case("r2", isPPC64 ? Register() : PPC::R2) 14884 .Case("r13", (is64Bit ? PPC::X13 : PPC::R13)) 14885 .Default(Register()); 14886 14887 if (Reg) 14888 return Reg; 14889 report_fatal_error("Invalid register name global variable"); 14890 } 14891 14892 bool PPCTargetLowering::isAccessedAsGotIndirect(SDValue GA) const { 14893 // 32-bit SVR4 ABI access everything as got-indirect. 14894 if (Subtarget.is32BitELFABI()) 14895 return true; 14896 14897 // AIX accesses everything indirectly through the TOC, which is similar to 14898 // the GOT. 14899 if (Subtarget.isAIXABI()) 14900 return true; 14901 14902 CodeModel::Model CModel = getTargetMachine().getCodeModel(); 14903 // If it is small or large code model, module locals are accessed 14904 // indirectly by loading their address from .toc/.got. 14905 if (CModel == CodeModel::Small || CModel == CodeModel::Large) 14906 return true; 14907 14908 // JumpTable and BlockAddress are accessed as got-indirect. 14909 if (isa<JumpTableSDNode>(GA) || isa<BlockAddressSDNode>(GA)) 14910 return true; 14911 14912 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(GA)) 14913 return Subtarget.isGVIndirectSymbol(G->getGlobal()); 14914 14915 return false; 14916 } 14917 14918 bool 14919 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 14920 // The PowerPC target isn't yet aware of offsets. 14921 return false; 14922 } 14923 14924 bool PPCTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 14925 const CallInst &I, 14926 MachineFunction &MF, 14927 unsigned Intrinsic) const { 14928 switch (Intrinsic) { 14929 case Intrinsic::ppc_qpx_qvlfd: 14930 case Intrinsic::ppc_qpx_qvlfs: 14931 case Intrinsic::ppc_qpx_qvlfcd: 14932 case Intrinsic::ppc_qpx_qvlfcs: 14933 case Intrinsic::ppc_qpx_qvlfiwa: 14934 case Intrinsic::ppc_qpx_qvlfiwz: 14935 case Intrinsic::ppc_altivec_lvx: 14936 case Intrinsic::ppc_altivec_lvxl: 14937 case Intrinsic::ppc_altivec_lvebx: 14938 case Intrinsic::ppc_altivec_lvehx: 14939 case Intrinsic::ppc_altivec_lvewx: 14940 case Intrinsic::ppc_vsx_lxvd2x: 14941 case Intrinsic::ppc_vsx_lxvw4x: { 14942 EVT VT; 14943 switch (Intrinsic) { 14944 case Intrinsic::ppc_altivec_lvebx: 14945 VT = MVT::i8; 14946 break; 14947 case Intrinsic::ppc_altivec_lvehx: 14948 VT = MVT::i16; 14949 break; 14950 case Intrinsic::ppc_altivec_lvewx: 14951 VT = MVT::i32; 14952 break; 14953 case Intrinsic::ppc_vsx_lxvd2x: 14954 VT = MVT::v2f64; 14955 break; 14956 case Intrinsic::ppc_qpx_qvlfd: 14957 VT = MVT::v4f64; 14958 break; 14959 case Intrinsic::ppc_qpx_qvlfs: 14960 VT = MVT::v4f32; 14961 break; 14962 case Intrinsic::ppc_qpx_qvlfcd: 14963 VT = MVT::v2f64; 14964 break; 14965 case Intrinsic::ppc_qpx_qvlfcs: 14966 VT = MVT::v2f32; 14967 break; 14968 default: 14969 VT = MVT::v4i32; 14970 break; 14971 } 14972 14973 Info.opc = ISD::INTRINSIC_W_CHAIN; 14974 Info.memVT = VT; 14975 Info.ptrVal = I.getArgOperand(0); 14976 Info.offset = -VT.getStoreSize()+1; 14977 Info.size = 2*VT.getStoreSize()-1; 14978 Info.align = Align(1); 14979 Info.flags = MachineMemOperand::MOLoad; 14980 return true; 14981 } 14982 case Intrinsic::ppc_qpx_qvlfda: 14983 case Intrinsic::ppc_qpx_qvlfsa: 14984 case Intrinsic::ppc_qpx_qvlfcda: 14985 case Intrinsic::ppc_qpx_qvlfcsa: 14986 case Intrinsic::ppc_qpx_qvlfiwaa: 14987 case Intrinsic::ppc_qpx_qvlfiwza: { 14988 EVT VT; 14989 switch (Intrinsic) { 14990 case Intrinsic::ppc_qpx_qvlfda: 14991 VT = MVT::v4f64; 14992 break; 14993 case Intrinsic::ppc_qpx_qvlfsa: 14994 VT = MVT::v4f32; 14995 break; 14996 case Intrinsic::ppc_qpx_qvlfcda: 14997 VT = MVT::v2f64; 14998 break; 14999 case Intrinsic::ppc_qpx_qvlfcsa: 15000 VT = MVT::v2f32; 15001 break; 15002 default: 15003 VT = MVT::v4i32; 15004 break; 15005 } 15006 15007 Info.opc = ISD::INTRINSIC_W_CHAIN; 15008 Info.memVT = VT; 15009 Info.ptrVal = I.getArgOperand(0); 15010 Info.offset = 0; 15011 Info.size = VT.getStoreSize(); 15012 Info.align = Align(1); 15013 Info.flags = MachineMemOperand::MOLoad; 15014 return true; 15015 } 15016 case Intrinsic::ppc_qpx_qvstfd: 15017 case Intrinsic::ppc_qpx_qvstfs: 15018 case Intrinsic::ppc_qpx_qvstfcd: 15019 case Intrinsic::ppc_qpx_qvstfcs: 15020 case Intrinsic::ppc_qpx_qvstfiw: 15021 case Intrinsic::ppc_altivec_stvx: 15022 case Intrinsic::ppc_altivec_stvxl: 15023 case Intrinsic::ppc_altivec_stvebx: 15024 case Intrinsic::ppc_altivec_stvehx: 15025 case Intrinsic::ppc_altivec_stvewx: 15026 case Intrinsic::ppc_vsx_stxvd2x: 15027 case Intrinsic::ppc_vsx_stxvw4x: { 15028 EVT VT; 15029 switch (Intrinsic) { 15030 case Intrinsic::ppc_altivec_stvebx: 15031 VT = MVT::i8; 15032 break; 15033 case Intrinsic::ppc_altivec_stvehx: 15034 VT = MVT::i16; 15035 break; 15036 case Intrinsic::ppc_altivec_stvewx: 15037 VT = MVT::i32; 15038 break; 15039 case Intrinsic::ppc_vsx_stxvd2x: 15040 VT = MVT::v2f64; 15041 break; 15042 case Intrinsic::ppc_qpx_qvstfd: 15043 VT = MVT::v4f64; 15044 break; 15045 case Intrinsic::ppc_qpx_qvstfs: 15046 VT = MVT::v4f32; 15047 break; 15048 case Intrinsic::ppc_qpx_qvstfcd: 15049 VT = MVT::v2f64; 15050 break; 15051 case Intrinsic::ppc_qpx_qvstfcs: 15052 VT = MVT::v2f32; 15053 break; 15054 default: 15055 VT = MVT::v4i32; 15056 break; 15057 } 15058 15059 Info.opc = ISD::INTRINSIC_VOID; 15060 Info.memVT = VT; 15061 Info.ptrVal = I.getArgOperand(1); 15062 Info.offset = -VT.getStoreSize()+1; 15063 Info.size = 2*VT.getStoreSize()-1; 15064 Info.align = Align(1); 15065 Info.flags = MachineMemOperand::MOStore; 15066 return true; 15067 } 15068 case Intrinsic::ppc_qpx_qvstfda: 15069 case Intrinsic::ppc_qpx_qvstfsa: 15070 case Intrinsic::ppc_qpx_qvstfcda: 15071 case Intrinsic::ppc_qpx_qvstfcsa: 15072 case Intrinsic::ppc_qpx_qvstfiwa: { 15073 EVT VT; 15074 switch (Intrinsic) { 15075 case Intrinsic::ppc_qpx_qvstfda: 15076 VT = MVT::v4f64; 15077 break; 15078 case Intrinsic::ppc_qpx_qvstfsa: 15079 VT = MVT::v4f32; 15080 break; 15081 case Intrinsic::ppc_qpx_qvstfcda: 15082 VT = MVT::v2f64; 15083 break; 15084 case Intrinsic::ppc_qpx_qvstfcsa: 15085 VT = MVT::v2f32; 15086 break; 15087 default: 15088 VT = MVT::v4i32; 15089 break; 15090 } 15091 15092 Info.opc = ISD::INTRINSIC_VOID; 15093 Info.memVT = VT; 15094 Info.ptrVal = I.getArgOperand(1); 15095 Info.offset = 0; 15096 Info.size = VT.getStoreSize(); 15097 Info.align = Align(1); 15098 Info.flags = MachineMemOperand::MOStore; 15099 return true; 15100 } 15101 default: 15102 break; 15103 } 15104 15105 return false; 15106 } 15107 15108 /// It returns EVT::Other if the type should be determined using generic 15109 /// target-independent logic. 15110 EVT PPCTargetLowering::getOptimalMemOpType( 15111 const MemOp &Op, const AttributeList &FuncAttributes) const { 15112 if (getTargetMachine().getOptLevel() != CodeGenOpt::None) { 15113 // When expanding a memset, require at least two QPX instructions to cover 15114 // the cost of loading the value to be stored from the constant pool. 15115 if (Subtarget.hasQPX() && Op.size() >= 32 && 15116 (Op.isMemcpy() || Op.size() >= 64) && Op.isAligned(Align(32)) && 15117 !FuncAttributes.hasFnAttribute(Attribute::NoImplicitFloat)) { 15118 return MVT::v4f64; 15119 } 15120 15121 // We should use Altivec/VSX loads and stores when available. For unaligned 15122 // addresses, unaligned VSX loads are only fast starting with the P8. 15123 if (Subtarget.hasAltivec() && Op.size() >= 16 && 15124 (Op.isAligned(Align(16)) || 15125 ((Op.isMemset() && Subtarget.hasVSX()) || Subtarget.hasP8Vector()))) 15126 return MVT::v4i32; 15127 } 15128 15129 if (Subtarget.isPPC64()) { 15130 return MVT::i64; 15131 } 15132 15133 return MVT::i32; 15134 } 15135 15136 /// Returns true if it is beneficial to convert a load of a constant 15137 /// to just the constant itself. 15138 bool PPCTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 15139 Type *Ty) const { 15140 assert(Ty->isIntegerTy()); 15141 15142 unsigned BitSize = Ty->getPrimitiveSizeInBits(); 15143 return !(BitSize == 0 || BitSize > 64); 15144 } 15145 15146 bool PPCTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const { 15147 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy()) 15148 return false; 15149 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits(); 15150 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits(); 15151 return NumBits1 == 64 && NumBits2 == 32; 15152 } 15153 15154 bool PPCTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const { 15155 if (!VT1.isInteger() || !VT2.isInteger()) 15156 return false; 15157 unsigned NumBits1 = VT1.getSizeInBits(); 15158 unsigned NumBits2 = VT2.getSizeInBits(); 15159 return NumBits1 == 64 && NumBits2 == 32; 15160 } 15161 15162 bool PPCTargetLowering::isZExtFree(SDValue Val, EVT VT2) const { 15163 // Generally speaking, zexts are not free, but they are free when they can be 15164 // folded with other operations. 15165 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Val)) { 15166 EVT MemVT = LD->getMemoryVT(); 15167 if ((MemVT == MVT::i1 || MemVT == MVT::i8 || MemVT == MVT::i16 || 15168 (Subtarget.isPPC64() && MemVT == MVT::i32)) && 15169 (LD->getExtensionType() == ISD::NON_EXTLOAD || 15170 LD->getExtensionType() == ISD::ZEXTLOAD)) 15171 return true; 15172 } 15173 15174 // FIXME: Add other cases... 15175 // - 32-bit shifts with a zext to i64 15176 // - zext after ctlz, bswap, etc. 15177 // - zext after and by a constant mask 15178 15179 return TargetLowering::isZExtFree(Val, VT2); 15180 } 15181 15182 bool PPCTargetLowering::isFPExtFree(EVT DestVT, EVT SrcVT) const { 15183 assert(DestVT.isFloatingPoint() && SrcVT.isFloatingPoint() && 15184 "invalid fpext types"); 15185 // Extending to float128 is not free. 15186 if (DestVT == MVT::f128) 15187 return false; 15188 return true; 15189 } 15190 15191 bool PPCTargetLowering::isLegalICmpImmediate(int64_t Imm) const { 15192 return isInt<16>(Imm) || isUInt<16>(Imm); 15193 } 15194 15195 bool PPCTargetLowering::isLegalAddImmediate(int64_t Imm) const { 15196 return isInt<16>(Imm) || isUInt<16>(Imm); 15197 } 15198 15199 bool PPCTargetLowering::allowsMisalignedMemoryAccesses(EVT VT, 15200 unsigned, 15201 unsigned, 15202 MachineMemOperand::Flags, 15203 bool *Fast) const { 15204 if (DisablePPCUnaligned) 15205 return false; 15206 15207 // PowerPC supports unaligned memory access for simple non-vector types. 15208 // Although accessing unaligned addresses is not as efficient as accessing 15209 // aligned addresses, it is generally more efficient than manual expansion, 15210 // and generally only traps for software emulation when crossing page 15211 // boundaries. 15212 15213 if (!VT.isSimple()) 15214 return false; 15215 15216 if (VT.isFloatingPoint() && !Subtarget.allowsUnalignedFPAccess()) 15217 return false; 15218 15219 if (VT.getSimpleVT().isVector()) { 15220 if (Subtarget.hasVSX()) { 15221 if (VT != MVT::v2f64 && VT != MVT::v2i64 && 15222 VT != MVT::v4f32 && VT != MVT::v4i32) 15223 return false; 15224 } else { 15225 return false; 15226 } 15227 } 15228 15229 if (VT == MVT::ppcf128) 15230 return false; 15231 15232 if (Fast) 15233 *Fast = true; 15234 15235 return true; 15236 } 15237 15238 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, 15239 EVT VT) const { 15240 VT = VT.getScalarType(); 15241 15242 if (!VT.isSimple()) 15243 return false; 15244 15245 switch (VT.getSimpleVT().SimpleTy) { 15246 case MVT::f32: 15247 case MVT::f64: 15248 return true; 15249 case MVT::f128: 15250 return (EnableQuadPrecision && Subtarget.hasP9Vector()); 15251 default: 15252 break; 15253 } 15254 15255 return false; 15256 } 15257 15258 const MCPhysReg * 15259 PPCTargetLowering::getScratchRegisters(CallingConv::ID) const { 15260 // LR is a callee-save register, but we must treat it as clobbered by any call 15261 // site. Hence we include LR in the scratch registers, which are in turn added 15262 // as implicit-defs for stackmaps and patchpoints. The same reasoning applies 15263 // to CTR, which is used by any indirect call. 15264 static const MCPhysReg ScratchRegs[] = { 15265 PPC::X12, PPC::LR8, PPC::CTR8, 0 15266 }; 15267 15268 return ScratchRegs; 15269 } 15270 15271 unsigned PPCTargetLowering::getExceptionPointerRegister( 15272 const Constant *PersonalityFn) const { 15273 return Subtarget.isPPC64() ? PPC::X3 : PPC::R3; 15274 } 15275 15276 unsigned PPCTargetLowering::getExceptionSelectorRegister( 15277 const Constant *PersonalityFn) const { 15278 return Subtarget.isPPC64() ? PPC::X4 : PPC::R4; 15279 } 15280 15281 bool 15282 PPCTargetLowering::shouldExpandBuildVectorWithShuffles( 15283 EVT VT , unsigned DefinedValues) const { 15284 if (VT == MVT::v2i64) 15285 return Subtarget.hasDirectMove(); // Don't need stack ops with direct moves 15286 15287 if (Subtarget.hasVSX() || Subtarget.hasQPX()) 15288 return true; 15289 15290 return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues); 15291 } 15292 15293 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const { 15294 if (DisableILPPref || Subtarget.enableMachineScheduler()) 15295 return TargetLowering::getSchedulingPreference(N); 15296 15297 return Sched::ILP; 15298 } 15299 15300 // Create a fast isel object. 15301 FastISel * 15302 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo, 15303 const TargetLibraryInfo *LibInfo) const { 15304 return PPC::createFastISel(FuncInfo, LibInfo); 15305 } 15306 15307 void PPCTargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const { 15308 if (!Subtarget.isPPC64()) return; 15309 15310 // Update IsSplitCSR in PPCFunctionInfo 15311 PPCFunctionInfo *PFI = Entry->getParent()->getInfo<PPCFunctionInfo>(); 15312 PFI->setIsSplitCSR(true); 15313 } 15314 15315 void PPCTargetLowering::insertCopiesSplitCSR( 15316 MachineBasicBlock *Entry, 15317 const SmallVectorImpl<MachineBasicBlock *> &Exits) const { 15318 const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo(); 15319 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent()); 15320 if (!IStart) 15321 return; 15322 15323 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 15324 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo(); 15325 MachineBasicBlock::iterator MBBI = Entry->begin(); 15326 for (const MCPhysReg *I = IStart; *I; ++I) { 15327 const TargetRegisterClass *RC = nullptr; 15328 if (PPC::G8RCRegClass.contains(*I)) 15329 RC = &PPC::G8RCRegClass; 15330 else if (PPC::F8RCRegClass.contains(*I)) 15331 RC = &PPC::F8RCRegClass; 15332 else if (PPC::CRRCRegClass.contains(*I)) 15333 RC = &PPC::CRRCRegClass; 15334 else if (PPC::VRRCRegClass.contains(*I)) 15335 RC = &PPC::VRRCRegClass; 15336 else 15337 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 15338 15339 Register NewVR = MRI->createVirtualRegister(RC); 15340 // Create copy from CSR to a virtual register. 15341 // FIXME: this currently does not emit CFI pseudo-instructions, it works 15342 // fine for CXX_FAST_TLS since the C++-style TLS access functions should be 15343 // nounwind. If we want to generalize this later, we may need to emit 15344 // CFI pseudo-instructions. 15345 assert(Entry->getParent()->getFunction().hasFnAttribute( 15346 Attribute::NoUnwind) && 15347 "Function should be nounwind in insertCopiesSplitCSR!"); 15348 Entry->addLiveIn(*I); 15349 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR) 15350 .addReg(*I); 15351 15352 // Insert the copy-back instructions right before the terminator. 15353 for (auto *Exit : Exits) 15354 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(), 15355 TII->get(TargetOpcode::COPY), *I) 15356 .addReg(NewVR); 15357 } 15358 } 15359 15360 // Override to enable LOAD_STACK_GUARD lowering on Linux. 15361 bool PPCTargetLowering::useLoadStackGuardNode() const { 15362 if (!Subtarget.isTargetLinux()) 15363 return TargetLowering::useLoadStackGuardNode(); 15364 return true; 15365 } 15366 15367 // Override to disable global variable loading on Linux. 15368 void PPCTargetLowering::insertSSPDeclarations(Module &M) const { 15369 if (!Subtarget.isTargetLinux()) 15370 return TargetLowering::insertSSPDeclarations(M); 15371 } 15372 15373 bool PPCTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT, 15374 bool ForCodeSize) const { 15375 if (!VT.isSimple() || !Subtarget.hasVSX()) 15376 return false; 15377 15378 switch(VT.getSimpleVT().SimpleTy) { 15379 default: 15380 // For FP types that are currently not supported by PPC backend, return 15381 // false. Examples: f16, f80. 15382 return false; 15383 case MVT::f32: 15384 case MVT::f64: 15385 case MVT::ppcf128: 15386 return Imm.isPosZero(); 15387 } 15388 } 15389 15390 // For vector shift operation op, fold 15391 // (op x, (and y, ((1 << numbits(x)) - 1))) -> (target op x, y) 15392 static SDValue stripModuloOnShift(const TargetLowering &TLI, SDNode *N, 15393 SelectionDAG &DAG) { 15394 SDValue N0 = N->getOperand(0); 15395 SDValue N1 = N->getOperand(1); 15396 EVT VT = N0.getValueType(); 15397 unsigned OpSizeInBits = VT.getScalarSizeInBits(); 15398 unsigned Opcode = N->getOpcode(); 15399 unsigned TargetOpcode; 15400 15401 switch (Opcode) { 15402 default: 15403 llvm_unreachable("Unexpected shift operation"); 15404 case ISD::SHL: 15405 TargetOpcode = PPCISD::SHL; 15406 break; 15407 case ISD::SRL: 15408 TargetOpcode = PPCISD::SRL; 15409 break; 15410 case ISD::SRA: 15411 TargetOpcode = PPCISD::SRA; 15412 break; 15413 } 15414 15415 if (VT.isVector() && TLI.isOperationLegal(Opcode, VT) && 15416 N1->getOpcode() == ISD::AND) 15417 if (ConstantSDNode *Mask = isConstOrConstSplat(N1->getOperand(1))) 15418 if (Mask->getZExtValue() == OpSizeInBits - 1) 15419 return DAG.getNode(TargetOpcode, SDLoc(N), VT, N0, N1->getOperand(0)); 15420 15421 return SDValue(); 15422 } 15423 15424 SDValue PPCTargetLowering::combineSHL(SDNode *N, DAGCombinerInfo &DCI) const { 15425 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG)) 15426 return Value; 15427 15428 SDValue N0 = N->getOperand(0); 15429 ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N->getOperand(1)); 15430 if (!Subtarget.isISA3_0() || 15431 N0.getOpcode() != ISD::SIGN_EXTEND || 15432 N0.getOperand(0).getValueType() != MVT::i32 || 15433 CN1 == nullptr || N->getValueType(0) != MVT::i64) 15434 return SDValue(); 15435 15436 // We can't save an operation here if the value is already extended, and 15437 // the existing shift is easier to combine. 15438 SDValue ExtsSrc = N0.getOperand(0); 15439 if (ExtsSrc.getOpcode() == ISD::TRUNCATE && 15440 ExtsSrc.getOperand(0).getOpcode() == ISD::AssertSext) 15441 return SDValue(); 15442 15443 SDLoc DL(N0); 15444 SDValue ShiftBy = SDValue(CN1, 0); 15445 // We want the shift amount to be i32 on the extswli, but the shift could 15446 // have an i64. 15447 if (ShiftBy.getValueType() == MVT::i64) 15448 ShiftBy = DCI.DAG.getConstant(CN1->getZExtValue(), DL, MVT::i32); 15449 15450 return DCI.DAG.getNode(PPCISD::EXTSWSLI, DL, MVT::i64, N0->getOperand(0), 15451 ShiftBy); 15452 } 15453 15454 SDValue PPCTargetLowering::combineSRA(SDNode *N, DAGCombinerInfo &DCI) const { 15455 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG)) 15456 return Value; 15457 15458 return SDValue(); 15459 } 15460 15461 SDValue PPCTargetLowering::combineSRL(SDNode *N, DAGCombinerInfo &DCI) const { 15462 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG)) 15463 return Value; 15464 15465 return SDValue(); 15466 } 15467 15468 // Transform (add X, (zext(setne Z, C))) -> (addze X, (addic (addi Z, -C), -1)) 15469 // Transform (add X, (zext(sete Z, C))) -> (addze X, (subfic (addi Z, -C), 0)) 15470 // When C is zero, the equation (addi Z, -C) can be simplified to Z 15471 // Requirement: -C in [-32768, 32767], X and Z are MVT::i64 types 15472 static SDValue combineADDToADDZE(SDNode *N, SelectionDAG &DAG, 15473 const PPCSubtarget &Subtarget) { 15474 if (!Subtarget.isPPC64()) 15475 return SDValue(); 15476 15477 SDValue LHS = N->getOperand(0); 15478 SDValue RHS = N->getOperand(1); 15479 15480 auto isZextOfCompareWithConstant = [](SDValue Op) { 15481 if (Op.getOpcode() != ISD::ZERO_EXTEND || !Op.hasOneUse() || 15482 Op.getValueType() != MVT::i64) 15483 return false; 15484 15485 SDValue Cmp = Op.getOperand(0); 15486 if (Cmp.getOpcode() != ISD::SETCC || !Cmp.hasOneUse() || 15487 Cmp.getOperand(0).getValueType() != MVT::i64) 15488 return false; 15489 15490 if (auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1))) { 15491 int64_t NegConstant = 0 - Constant->getSExtValue(); 15492 // Due to the limitations of the addi instruction, 15493 // -C is required to be [-32768, 32767]. 15494 return isInt<16>(NegConstant); 15495 } 15496 15497 return false; 15498 }; 15499 15500 bool LHSHasPattern = isZextOfCompareWithConstant(LHS); 15501 bool RHSHasPattern = isZextOfCompareWithConstant(RHS); 15502 15503 // If there is a pattern, canonicalize a zext operand to the RHS. 15504 if (LHSHasPattern && !RHSHasPattern) 15505 std::swap(LHS, RHS); 15506 else if (!LHSHasPattern && !RHSHasPattern) 15507 return SDValue(); 15508 15509 SDLoc DL(N); 15510 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Glue); 15511 SDValue Cmp = RHS.getOperand(0); 15512 SDValue Z = Cmp.getOperand(0); 15513 auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1)); 15514 15515 assert(Constant && "Constant Should not be a null pointer."); 15516 int64_t NegConstant = 0 - Constant->getSExtValue(); 15517 15518 switch(cast<CondCodeSDNode>(Cmp.getOperand(2))->get()) { 15519 default: break; 15520 case ISD::SETNE: { 15521 // when C == 0 15522 // --> addze X, (addic Z, -1).carry 15523 // / 15524 // add X, (zext(setne Z, C))-- 15525 // \ when -32768 <= -C <= 32767 && C != 0 15526 // --> addze X, (addic (addi Z, -C), -1).carry 15527 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z, 15528 DAG.getConstant(NegConstant, DL, MVT::i64)); 15529 SDValue AddOrZ = NegConstant != 0 ? Add : Z; 15530 SDValue Addc = DAG.getNode(ISD::ADDC, DL, DAG.getVTList(MVT::i64, MVT::Glue), 15531 AddOrZ, DAG.getConstant(-1ULL, DL, MVT::i64)); 15532 return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64), 15533 SDValue(Addc.getNode(), 1)); 15534 } 15535 case ISD::SETEQ: { 15536 // when C == 0 15537 // --> addze X, (subfic Z, 0).carry 15538 // / 15539 // add X, (zext(sete Z, C))-- 15540 // \ when -32768 <= -C <= 32767 && C != 0 15541 // --> addze X, (subfic (addi Z, -C), 0).carry 15542 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z, 15543 DAG.getConstant(NegConstant, DL, MVT::i64)); 15544 SDValue AddOrZ = NegConstant != 0 ? Add : Z; 15545 SDValue Subc = DAG.getNode(ISD::SUBC, DL, DAG.getVTList(MVT::i64, MVT::Glue), 15546 DAG.getConstant(0, DL, MVT::i64), AddOrZ); 15547 return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64), 15548 SDValue(Subc.getNode(), 1)); 15549 } 15550 } 15551 15552 return SDValue(); 15553 } 15554 15555 SDValue PPCTargetLowering::combineADD(SDNode *N, DAGCombinerInfo &DCI) const { 15556 if (auto Value = combineADDToADDZE(N, DCI.DAG, Subtarget)) 15557 return Value; 15558 15559 return SDValue(); 15560 } 15561 15562 // Detect TRUNCATE operations on bitcasts of float128 values. 15563 // What we are looking for here is the situtation where we extract a subset 15564 // of bits from a 128 bit float. 15565 // This can be of two forms: 15566 // 1) BITCAST of f128 feeding TRUNCATE 15567 // 2) BITCAST of f128 feeding SRL (a shift) feeding TRUNCATE 15568 // The reason this is required is because we do not have a legal i128 type 15569 // and so we want to prevent having to store the f128 and then reload part 15570 // of it. 15571 SDValue PPCTargetLowering::combineTRUNCATE(SDNode *N, 15572 DAGCombinerInfo &DCI) const { 15573 // If we are using CRBits then try that first. 15574 if (Subtarget.useCRBits()) { 15575 // Check if CRBits did anything and return that if it did. 15576 if (SDValue CRTruncValue = DAGCombineTruncBoolExt(N, DCI)) 15577 return CRTruncValue; 15578 } 15579 15580 SDLoc dl(N); 15581 SDValue Op0 = N->getOperand(0); 15582 15583 // Looking for a truncate of i128 to i64. 15584 if (Op0.getValueType() != MVT::i128 || N->getValueType(0) != MVT::i64) 15585 return SDValue(); 15586 15587 int EltToExtract = DCI.DAG.getDataLayout().isBigEndian() ? 1 : 0; 15588 15589 // SRL feeding TRUNCATE. 15590 if (Op0.getOpcode() == ISD::SRL) { 15591 ConstantSDNode *ConstNode = dyn_cast<ConstantSDNode>(Op0.getOperand(1)); 15592 // The right shift has to be by 64 bits. 15593 if (!ConstNode || ConstNode->getZExtValue() != 64) 15594 return SDValue(); 15595 15596 // Switch the element number to extract. 15597 EltToExtract = EltToExtract ? 0 : 1; 15598 // Update Op0 past the SRL. 15599 Op0 = Op0.getOperand(0); 15600 } 15601 15602 // BITCAST feeding a TRUNCATE possibly via SRL. 15603 if (Op0.getOpcode() == ISD::BITCAST && 15604 Op0.getValueType() == MVT::i128 && 15605 Op0.getOperand(0).getValueType() == MVT::f128) { 15606 SDValue Bitcast = DCI.DAG.getBitcast(MVT::v2i64, Op0.getOperand(0)); 15607 return DCI.DAG.getNode( 15608 ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Bitcast, 15609 DCI.DAG.getTargetConstant(EltToExtract, dl, MVT::i32)); 15610 } 15611 return SDValue(); 15612 } 15613 15614 SDValue PPCTargetLowering::combineMUL(SDNode *N, DAGCombinerInfo &DCI) const { 15615 SelectionDAG &DAG = DCI.DAG; 15616 15617 ConstantSDNode *ConstOpOrElement = isConstOrConstSplat(N->getOperand(1)); 15618 if (!ConstOpOrElement) 15619 return SDValue(); 15620 15621 // An imul is usually smaller than the alternative sequence for legal type. 15622 if (DAG.getMachineFunction().getFunction().hasMinSize() && 15623 isOperationLegal(ISD::MUL, N->getValueType(0))) 15624 return SDValue(); 15625 15626 auto IsProfitable = [this](bool IsNeg, bool IsAddOne, EVT VT) -> bool { 15627 switch (this->Subtarget.getCPUDirective()) { 15628 default: 15629 // TODO: enhance the condition for subtarget before pwr8 15630 return false; 15631 case PPC::DIR_PWR8: 15632 // type mul add shl 15633 // scalar 4 1 1 15634 // vector 7 2 2 15635 return true; 15636 case PPC::DIR_PWR9: 15637 case PPC::DIR_PWR_FUTURE: 15638 // type mul add shl 15639 // scalar 5 2 2 15640 // vector 7 2 2 15641 15642 // The cycle RATIO of related operations are showed as a table above. 15643 // Because mul is 5(scalar)/7(vector), add/sub/shl are all 2 for both 15644 // scalar and vector type. For 2 instrs patterns, add/sub + shl 15645 // are 4, it is always profitable; but for 3 instrs patterns 15646 // (mul x, -(2^N + 1)) => -(add (shl x, N), x), sub + add + shl are 6. 15647 // So we should only do it for vector type. 15648 return IsAddOne && IsNeg ? VT.isVector() : true; 15649 } 15650 }; 15651 15652 EVT VT = N->getValueType(0); 15653 SDLoc DL(N); 15654 15655 const APInt &MulAmt = ConstOpOrElement->getAPIntValue(); 15656 bool IsNeg = MulAmt.isNegative(); 15657 APInt MulAmtAbs = MulAmt.abs(); 15658 15659 if ((MulAmtAbs - 1).isPowerOf2()) { 15660 // (mul x, 2^N + 1) => (add (shl x, N), x) 15661 // (mul x, -(2^N + 1)) => -(add (shl x, N), x) 15662 15663 if (!IsProfitable(IsNeg, true, 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 SDValue Res = DAG.getNode(ISD::ADD, DL, VT, Op0, Op1); 15671 15672 if (!IsNeg) 15673 return Res; 15674 15675 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Res); 15676 } else if ((MulAmtAbs + 1).isPowerOf2()) { 15677 // (mul x, 2^N - 1) => (sub (shl x, N), x) 15678 // (mul x, -(2^N - 1)) => (sub x, (shl x, N)) 15679 15680 if (!IsProfitable(IsNeg, false, VT)) 15681 return SDValue(); 15682 15683 SDValue Op0 = N->getOperand(0); 15684 SDValue Op1 = 15685 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0), 15686 DAG.getConstant((MulAmtAbs + 1).logBase2(), DL, VT)); 15687 15688 if (!IsNeg) 15689 return DAG.getNode(ISD::SUB, DL, VT, Op1, Op0); 15690 else 15691 return DAG.getNode(ISD::SUB, DL, VT, Op0, Op1); 15692 15693 } else { 15694 return SDValue(); 15695 } 15696 } 15697 15698 bool PPCTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 15699 // Only duplicate to increase tail-calls for the 64bit SysV ABIs. 15700 if (!Subtarget.is64BitELFABI()) 15701 return false; 15702 15703 // If not a tail call then no need to proceed. 15704 if (!CI->isTailCall()) 15705 return false; 15706 15707 // If sibling calls have been disabled and tail-calls aren't guaranteed 15708 // there is no reason to duplicate. 15709 auto &TM = getTargetMachine(); 15710 if (!TM.Options.GuaranteedTailCallOpt && DisableSCO) 15711 return false; 15712 15713 // Can't tail call a function called indirectly, or if it has variadic args. 15714 const Function *Callee = CI->getCalledFunction(); 15715 if (!Callee || Callee->isVarArg()) 15716 return false; 15717 15718 // Make sure the callee and caller calling conventions are eligible for tco. 15719 const Function *Caller = CI->getParent()->getParent(); 15720 if (!areCallingConvEligibleForTCO_64SVR4(Caller->getCallingConv(), 15721 CI->getCallingConv())) 15722 return false; 15723 15724 // If the function is local then we have a good chance at tail-calling it 15725 return getTargetMachine().shouldAssumeDSOLocal(*Caller->getParent(), Callee); 15726 } 15727 15728 bool PPCTargetLowering::hasBitPreservingFPLogic(EVT VT) const { 15729 if (!Subtarget.hasVSX()) 15730 return false; 15731 if (Subtarget.hasP9Vector() && VT == MVT::f128) 15732 return true; 15733 return VT == MVT::f32 || VT == MVT::f64 || 15734 VT == MVT::v4f32 || VT == MVT::v2f64; 15735 } 15736 15737 bool PPCTargetLowering:: 15738 isMaskAndCmp0FoldingBeneficial(const Instruction &AndI) const { 15739 const Value *Mask = AndI.getOperand(1); 15740 // If the mask is suitable for andi. or andis. we should sink the and. 15741 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Mask)) { 15742 // Can't handle constants wider than 64-bits. 15743 if (CI->getBitWidth() > 64) 15744 return false; 15745 int64_t ConstVal = CI->getZExtValue(); 15746 return isUInt<16>(ConstVal) || 15747 (isUInt<16>(ConstVal >> 16) && !(ConstVal & 0xFFFF)); 15748 } 15749 15750 // For non-constant masks, we can always use the record-form and. 15751 return true; 15752 } 15753 15754 // Transform (abs (sub (zext a), (zext b))) to (vabsd a b 0) 15755 // Transform (abs (sub (zext a), (zext_invec b))) to (vabsd a b 0) 15756 // Transform (abs (sub (zext_invec a), (zext_invec b))) to (vabsd a b 0) 15757 // Transform (abs (sub (zext_invec a), (zext b))) to (vabsd a b 0) 15758 // Transform (abs (sub a, b) to (vabsd a b 1)) if a & b of type v4i32 15759 SDValue PPCTargetLowering::combineABS(SDNode *N, DAGCombinerInfo &DCI) const { 15760 assert((N->getOpcode() == ISD::ABS) && "Need ABS node here"); 15761 assert(Subtarget.hasP9Altivec() && 15762 "Only combine this when P9 altivec supported!"); 15763 EVT VT = N->getValueType(0); 15764 if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8) 15765 return SDValue(); 15766 15767 SelectionDAG &DAG = DCI.DAG; 15768 SDLoc dl(N); 15769 if (N->getOperand(0).getOpcode() == ISD::SUB) { 15770 // Even for signed integers, if it's known to be positive (as signed 15771 // integer) due to zero-extended inputs. 15772 unsigned SubOpcd0 = N->getOperand(0)->getOperand(0).getOpcode(); 15773 unsigned SubOpcd1 = N->getOperand(0)->getOperand(1).getOpcode(); 15774 if ((SubOpcd0 == ISD::ZERO_EXTEND || 15775 SubOpcd0 == ISD::ZERO_EXTEND_VECTOR_INREG) && 15776 (SubOpcd1 == ISD::ZERO_EXTEND || 15777 SubOpcd1 == ISD::ZERO_EXTEND_VECTOR_INREG)) { 15778 return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(), 15779 N->getOperand(0)->getOperand(0), 15780 N->getOperand(0)->getOperand(1), 15781 DAG.getTargetConstant(0, dl, MVT::i32)); 15782 } 15783 15784 // For type v4i32, it can be optimized with xvnegsp + vabsduw 15785 if (N->getOperand(0).getValueType() == MVT::v4i32 && 15786 N->getOperand(0).hasOneUse()) { 15787 return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(), 15788 N->getOperand(0)->getOperand(0), 15789 N->getOperand(0)->getOperand(1), 15790 DAG.getTargetConstant(1, dl, MVT::i32)); 15791 } 15792 } 15793 15794 return SDValue(); 15795 } 15796 15797 // For type v4i32/v8ii16/v16i8, transform 15798 // from (vselect (setcc a, b, setugt), (sub a, b), (sub b, a)) to (vabsd a, b) 15799 // from (vselect (setcc a, b, setuge), (sub a, b), (sub b, a)) to (vabsd a, b) 15800 // from (vselect (setcc a, b, setult), (sub b, a), (sub a, b)) to (vabsd a, b) 15801 // from (vselect (setcc a, b, setule), (sub b, a), (sub a, b)) to (vabsd a, b) 15802 SDValue PPCTargetLowering::combineVSelect(SDNode *N, 15803 DAGCombinerInfo &DCI) const { 15804 assert((N->getOpcode() == ISD::VSELECT) && "Need VSELECT node here"); 15805 assert(Subtarget.hasP9Altivec() && 15806 "Only combine this when P9 altivec supported!"); 15807 15808 SelectionDAG &DAG = DCI.DAG; 15809 SDLoc dl(N); 15810 SDValue Cond = N->getOperand(0); 15811 SDValue TrueOpnd = N->getOperand(1); 15812 SDValue FalseOpnd = N->getOperand(2); 15813 EVT VT = N->getOperand(1).getValueType(); 15814 15815 if (Cond.getOpcode() != ISD::SETCC || TrueOpnd.getOpcode() != ISD::SUB || 15816 FalseOpnd.getOpcode() != ISD::SUB) 15817 return SDValue(); 15818 15819 // ABSD only available for type v4i32/v8i16/v16i8 15820 if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8) 15821 return SDValue(); 15822 15823 // At least to save one more dependent computation 15824 if (!(Cond.hasOneUse() || TrueOpnd.hasOneUse() || FalseOpnd.hasOneUse())) 15825 return SDValue(); 15826 15827 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get(); 15828 15829 // Can only handle unsigned comparison here 15830 switch (CC) { 15831 default: 15832 return SDValue(); 15833 case ISD::SETUGT: 15834 case ISD::SETUGE: 15835 break; 15836 case ISD::SETULT: 15837 case ISD::SETULE: 15838 std::swap(TrueOpnd, FalseOpnd); 15839 break; 15840 } 15841 15842 SDValue CmpOpnd1 = Cond.getOperand(0); 15843 SDValue CmpOpnd2 = Cond.getOperand(1); 15844 15845 // SETCC CmpOpnd1 CmpOpnd2 cond 15846 // TrueOpnd = CmpOpnd1 - CmpOpnd2 15847 // FalseOpnd = CmpOpnd2 - CmpOpnd1 15848 if (TrueOpnd.getOperand(0) == CmpOpnd1 && 15849 TrueOpnd.getOperand(1) == CmpOpnd2 && 15850 FalseOpnd.getOperand(0) == CmpOpnd2 && 15851 FalseOpnd.getOperand(1) == CmpOpnd1) { 15852 return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(1).getValueType(), 15853 CmpOpnd1, CmpOpnd2, 15854 DAG.getTargetConstant(0, dl, MVT::i32)); 15855 } 15856 15857 return SDValue(); 15858 } 15859