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 // Use _setjmp/_longjmp instead of setjmp/longjmp. 141 setUseUnderscoreSetJmp(true); 142 setUseUnderscoreLongJmp(true); 143 144 // On PPC32/64, arguments smaller than 4/8 bytes are extended, so all 145 // arguments are at least 4/8 bytes aligned. 146 bool isPPC64 = Subtarget.isPPC64(); 147 setMinStackArgumentAlignment(isPPC64 ? Align(8) : Align(4)); 148 149 // Set up the register classes. 150 addRegisterClass(MVT::i32, &PPC::GPRCRegClass); 151 if (!useSoftFloat()) { 152 if (hasSPE()) { 153 addRegisterClass(MVT::f32, &PPC::GPRCRegClass); 154 addRegisterClass(MVT::f64, &PPC::SPERCRegClass); 155 } else { 156 addRegisterClass(MVT::f32, &PPC::F4RCRegClass); 157 addRegisterClass(MVT::f64, &PPC::F8RCRegClass); 158 } 159 } 160 161 // Match BITREVERSE to customized fast code sequence in the td file. 162 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal); 163 setOperationAction(ISD::BITREVERSE, MVT::i64, Legal); 164 165 // Sub-word ATOMIC_CMP_SWAP need to ensure that the input is zero-extended. 166 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom); 167 168 // PowerPC has an i16 but no i8 (or i1) SEXTLOAD. 169 for (MVT VT : MVT::integer_valuetypes()) { 170 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote); 171 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i8, Expand); 172 } 173 174 setTruncStoreAction(MVT::f64, MVT::f32, Expand); 175 176 // PowerPC has pre-inc load and store's. 177 setIndexedLoadAction(ISD::PRE_INC, MVT::i1, Legal); 178 setIndexedLoadAction(ISD::PRE_INC, MVT::i8, Legal); 179 setIndexedLoadAction(ISD::PRE_INC, MVT::i16, Legal); 180 setIndexedLoadAction(ISD::PRE_INC, MVT::i32, Legal); 181 setIndexedLoadAction(ISD::PRE_INC, MVT::i64, Legal); 182 setIndexedStoreAction(ISD::PRE_INC, MVT::i1, Legal); 183 setIndexedStoreAction(ISD::PRE_INC, MVT::i8, Legal); 184 setIndexedStoreAction(ISD::PRE_INC, MVT::i16, Legal); 185 setIndexedStoreAction(ISD::PRE_INC, MVT::i32, Legal); 186 setIndexedStoreAction(ISD::PRE_INC, MVT::i64, Legal); 187 if (!Subtarget.hasSPE()) { 188 setIndexedLoadAction(ISD::PRE_INC, MVT::f32, Legal); 189 setIndexedLoadAction(ISD::PRE_INC, MVT::f64, Legal); 190 setIndexedStoreAction(ISD::PRE_INC, MVT::f32, Legal); 191 setIndexedStoreAction(ISD::PRE_INC, MVT::f64, Legal); 192 } 193 194 // PowerPC uses ADDC/ADDE/SUBC/SUBE to propagate carry. 195 const MVT ScalarIntVTs[] = { MVT::i32, MVT::i64 }; 196 for (MVT VT : ScalarIntVTs) { 197 setOperationAction(ISD::ADDC, VT, Legal); 198 setOperationAction(ISD::ADDE, VT, Legal); 199 setOperationAction(ISD::SUBC, VT, Legal); 200 setOperationAction(ISD::SUBE, VT, Legal); 201 } 202 203 if (Subtarget.useCRBits()) { 204 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); 205 206 if (isPPC64 || Subtarget.hasFPCVT()) { 207 setOperationAction(ISD::SINT_TO_FP, MVT::i1, Promote); 208 AddPromotedToType (ISD::SINT_TO_FP, MVT::i1, 209 isPPC64 ? MVT::i64 : MVT::i32); 210 setOperationAction(ISD::UINT_TO_FP, MVT::i1, Promote); 211 AddPromotedToType(ISD::UINT_TO_FP, MVT::i1, 212 isPPC64 ? MVT::i64 : MVT::i32); 213 } else { 214 setOperationAction(ISD::SINT_TO_FP, MVT::i1, Custom); 215 setOperationAction(ISD::UINT_TO_FP, MVT::i1, Custom); 216 } 217 218 // PowerPC does not support direct load/store of condition registers. 219 setOperationAction(ISD::LOAD, MVT::i1, Custom); 220 setOperationAction(ISD::STORE, MVT::i1, Custom); 221 222 // FIXME: Remove this once the ANDI glue bug is fixed: 223 if (ANDIGlueBug) 224 setOperationAction(ISD::TRUNCATE, MVT::i1, Custom); 225 226 for (MVT VT : MVT::integer_valuetypes()) { 227 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote); 228 setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote); 229 setTruncStoreAction(VT, MVT::i1, Expand); 230 } 231 232 addRegisterClass(MVT::i1, &PPC::CRBITRCRegClass); 233 } 234 235 // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on 236 // PPC (the libcall is not available). 237 setOperationAction(ISD::FP_TO_SINT, MVT::ppcf128, Custom); 238 setOperationAction(ISD::FP_TO_UINT, MVT::ppcf128, Custom); 239 240 // We do not currently implement these libm ops for PowerPC. 241 setOperationAction(ISD::FFLOOR, MVT::ppcf128, Expand); 242 setOperationAction(ISD::FCEIL, MVT::ppcf128, Expand); 243 setOperationAction(ISD::FTRUNC, MVT::ppcf128, Expand); 244 setOperationAction(ISD::FRINT, MVT::ppcf128, Expand); 245 setOperationAction(ISD::FNEARBYINT, MVT::ppcf128, Expand); 246 setOperationAction(ISD::FREM, MVT::ppcf128, Expand); 247 248 // PowerPC has no SREM/UREM instructions unless we are on P9 249 // On P9 we may use a hardware instruction to compute the remainder. 250 // The instructions are not legalized directly because in the cases where the 251 // result of both the remainder and the division is required it is more 252 // efficient to compute the remainder from the result of the division rather 253 // than use the remainder instruction. 254 if (Subtarget.isISA3_0()) { 255 setOperationAction(ISD::SREM, MVT::i32, Custom); 256 setOperationAction(ISD::UREM, MVT::i32, Custom); 257 setOperationAction(ISD::SREM, MVT::i64, Custom); 258 setOperationAction(ISD::UREM, MVT::i64, Custom); 259 } else { 260 setOperationAction(ISD::SREM, MVT::i32, Expand); 261 setOperationAction(ISD::UREM, MVT::i32, Expand); 262 setOperationAction(ISD::SREM, MVT::i64, Expand); 263 setOperationAction(ISD::UREM, MVT::i64, Expand); 264 } 265 266 // Don't use SMUL_LOHI/UMUL_LOHI or SDIVREM/UDIVREM to lower SREM/UREM. 267 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand); 268 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand); 269 setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand); 270 setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand); 271 setOperationAction(ISD::UDIVREM, MVT::i32, Expand); 272 setOperationAction(ISD::SDIVREM, MVT::i32, Expand); 273 setOperationAction(ISD::UDIVREM, MVT::i64, Expand); 274 setOperationAction(ISD::SDIVREM, MVT::i64, Expand); 275 276 // We don't support sin/cos/sqrt/fmod/pow 277 setOperationAction(ISD::FSIN , MVT::f64, Expand); 278 setOperationAction(ISD::FCOS , MVT::f64, Expand); 279 setOperationAction(ISD::FSINCOS, MVT::f64, Expand); 280 setOperationAction(ISD::FREM , MVT::f64, Expand); 281 setOperationAction(ISD::FPOW , MVT::f64, Expand); 282 setOperationAction(ISD::FSIN , MVT::f32, Expand); 283 setOperationAction(ISD::FCOS , MVT::f32, Expand); 284 setOperationAction(ISD::FSINCOS, MVT::f32, Expand); 285 setOperationAction(ISD::FREM , MVT::f32, Expand); 286 setOperationAction(ISD::FPOW , MVT::f32, Expand); 287 if (Subtarget.hasSPE()) { 288 setOperationAction(ISD::FMA , MVT::f64, Expand); 289 setOperationAction(ISD::FMA , MVT::f32, Expand); 290 } else { 291 setOperationAction(ISD::FMA , MVT::f64, Legal); 292 setOperationAction(ISD::FMA , MVT::f32, Legal); 293 } 294 295 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom); 296 297 // If we're enabling GP optimizations, use hardware square root 298 if (!Subtarget.hasFSQRT() && 299 !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTE() && 300 Subtarget.hasFRE())) 301 setOperationAction(ISD::FSQRT, MVT::f64, Expand); 302 303 if (!Subtarget.hasFSQRT() && 304 !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTES() && 305 Subtarget.hasFRES())) 306 setOperationAction(ISD::FSQRT, MVT::f32, Expand); 307 308 if (Subtarget.hasFCPSGN()) { 309 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Legal); 310 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Legal); 311 } else { 312 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand); 313 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand); 314 } 315 316 if (Subtarget.hasFPRND()) { 317 setOperationAction(ISD::FFLOOR, MVT::f64, Legal); 318 setOperationAction(ISD::FCEIL, MVT::f64, Legal); 319 setOperationAction(ISD::FTRUNC, MVT::f64, Legal); 320 setOperationAction(ISD::FROUND, MVT::f64, Legal); 321 322 setOperationAction(ISD::FFLOOR, MVT::f32, Legal); 323 setOperationAction(ISD::FCEIL, MVT::f32, Legal); 324 setOperationAction(ISD::FTRUNC, MVT::f32, Legal); 325 setOperationAction(ISD::FROUND, MVT::f32, Legal); 326 } 327 328 // PowerPC does not have BSWAP, but we can use vector BSWAP instruction xxbrd 329 // to speed up scalar BSWAP64. 330 // CTPOP or CTTZ were introduced in P8/P9 respectively 331 setOperationAction(ISD::BSWAP, MVT::i32 , Expand); 332 if (Subtarget.hasP9Vector()) 333 setOperationAction(ISD::BSWAP, MVT::i64 , Custom); 334 else 335 setOperationAction(ISD::BSWAP, MVT::i64 , Expand); 336 if (Subtarget.isISA3_0()) { 337 setOperationAction(ISD::CTTZ , MVT::i32 , Legal); 338 setOperationAction(ISD::CTTZ , MVT::i64 , Legal); 339 } else { 340 setOperationAction(ISD::CTTZ , MVT::i32 , Expand); 341 setOperationAction(ISD::CTTZ , MVT::i64 , Expand); 342 } 343 344 if (Subtarget.hasPOPCNTD() == PPCSubtarget::POPCNTD_Fast) { 345 setOperationAction(ISD::CTPOP, MVT::i32 , Legal); 346 setOperationAction(ISD::CTPOP, MVT::i64 , Legal); 347 } else { 348 setOperationAction(ISD::CTPOP, MVT::i32 , Expand); 349 setOperationAction(ISD::CTPOP, MVT::i64 , Expand); 350 } 351 352 // PowerPC does not have ROTR 353 setOperationAction(ISD::ROTR, MVT::i32 , Expand); 354 setOperationAction(ISD::ROTR, MVT::i64 , Expand); 355 356 if (!Subtarget.useCRBits()) { 357 // PowerPC does not have Select 358 setOperationAction(ISD::SELECT, MVT::i32, Expand); 359 setOperationAction(ISD::SELECT, MVT::i64, Expand); 360 setOperationAction(ISD::SELECT, MVT::f32, Expand); 361 setOperationAction(ISD::SELECT, MVT::f64, Expand); 362 } 363 364 // PowerPC wants to turn select_cc of FP into fsel when possible. 365 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom); 366 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom); 367 368 // PowerPC wants to optimize integer setcc a bit 369 if (!Subtarget.useCRBits()) 370 setOperationAction(ISD::SETCC, MVT::i32, Custom); 371 372 // PowerPC does not have BRCOND which requires SetCC 373 if (!Subtarget.useCRBits()) 374 setOperationAction(ISD::BRCOND, MVT::Other, Expand); 375 376 setOperationAction(ISD::BR_JT, MVT::Other, Expand); 377 378 if (Subtarget.hasSPE()) { 379 // SPE has built-in conversions 380 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Legal); 381 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Legal); 382 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Legal); 383 } else { 384 // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores. 385 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 386 387 // PowerPC does not have [U|S]INT_TO_FP 388 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Expand); 389 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand); 390 } 391 392 if (Subtarget.hasDirectMove() && isPPC64) { 393 setOperationAction(ISD::BITCAST, MVT::f32, Legal); 394 setOperationAction(ISD::BITCAST, MVT::i32, Legal); 395 setOperationAction(ISD::BITCAST, MVT::i64, Legal); 396 setOperationAction(ISD::BITCAST, MVT::f64, Legal); 397 } else { 398 setOperationAction(ISD::BITCAST, MVT::f32, Expand); 399 setOperationAction(ISD::BITCAST, MVT::i32, Expand); 400 setOperationAction(ISD::BITCAST, MVT::i64, Expand); 401 setOperationAction(ISD::BITCAST, MVT::f64, Expand); 402 } 403 404 // We cannot sextinreg(i1). Expand to shifts. 405 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); 406 407 // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support 408 // SjLj exception handling but a light-weight setjmp/longjmp replacement to 409 // support continuation, user-level threading, and etc.. As a result, no 410 // other SjLj exception interfaces are implemented and please don't build 411 // your own exception handling based on them. 412 // LLVM/Clang supports zero-cost DWARF exception handling. 413 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom); 414 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom); 415 416 // We want to legalize GlobalAddress and ConstantPool nodes into the 417 // appropriate instructions to materialize the address. 418 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom); 419 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom); 420 setOperationAction(ISD::BlockAddress, MVT::i32, Custom); 421 setOperationAction(ISD::ConstantPool, MVT::i32, Custom); 422 setOperationAction(ISD::JumpTable, MVT::i32, Custom); 423 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom); 424 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom); 425 setOperationAction(ISD::BlockAddress, MVT::i64, Custom); 426 setOperationAction(ISD::ConstantPool, MVT::i64, Custom); 427 setOperationAction(ISD::JumpTable, MVT::i64, Custom); 428 429 // TRAP is legal. 430 setOperationAction(ISD::TRAP, MVT::Other, Legal); 431 432 // TRAMPOLINE is custom lowered. 433 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom); 434 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom); 435 436 // VASTART needs to be custom lowered to use the VarArgsFrameIndex 437 setOperationAction(ISD::VASTART , MVT::Other, Custom); 438 439 if (Subtarget.is64BitELFABI()) { 440 // VAARG always uses double-word chunks, so promote anything smaller. 441 setOperationAction(ISD::VAARG, MVT::i1, Promote); 442 AddPromotedToType(ISD::VAARG, MVT::i1, MVT::i64); 443 setOperationAction(ISD::VAARG, MVT::i8, Promote); 444 AddPromotedToType(ISD::VAARG, MVT::i8, MVT::i64); 445 setOperationAction(ISD::VAARG, MVT::i16, Promote); 446 AddPromotedToType(ISD::VAARG, MVT::i16, MVT::i64); 447 setOperationAction(ISD::VAARG, MVT::i32, Promote); 448 AddPromotedToType(ISD::VAARG, MVT::i32, MVT::i64); 449 setOperationAction(ISD::VAARG, MVT::Other, Expand); 450 } else if (Subtarget.is32BitELFABI()) { 451 // VAARG is custom lowered with the 32-bit SVR4 ABI. 452 setOperationAction(ISD::VAARG, MVT::Other, Custom); 453 setOperationAction(ISD::VAARG, MVT::i64, Custom); 454 } else 455 setOperationAction(ISD::VAARG, MVT::Other, Expand); 456 457 // VACOPY is custom lowered with the 32-bit SVR4 ABI. 458 if (Subtarget.is32BitELFABI()) 459 setOperationAction(ISD::VACOPY , MVT::Other, Custom); 460 else 461 setOperationAction(ISD::VACOPY , MVT::Other, Expand); 462 463 // Use the default implementation. 464 setOperationAction(ISD::VAEND , MVT::Other, Expand); 465 setOperationAction(ISD::STACKSAVE , MVT::Other, Expand); 466 setOperationAction(ISD::STACKRESTORE , MVT::Other, Custom); 467 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32 , Custom); 468 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64 , Custom); 469 setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i32, Custom); 470 setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i64, Custom); 471 setOperationAction(ISD::EH_DWARF_CFA, MVT::i32, Custom); 472 setOperationAction(ISD::EH_DWARF_CFA, MVT::i64, Custom); 473 474 // We want to custom lower some of our intrinsics. 475 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 476 477 // To handle counter-based loop conditions. 478 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i1, Custom); 479 480 setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom); 481 setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom); 482 setOperationAction(ISD::INTRINSIC_VOID, MVT::i32, Custom); 483 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom); 484 485 // Comparisons that require checking two conditions. 486 if (Subtarget.hasSPE()) { 487 setCondCodeAction(ISD::SETO, MVT::f32, Expand); 488 setCondCodeAction(ISD::SETO, MVT::f64, Expand); 489 setCondCodeAction(ISD::SETUO, MVT::f32, Expand); 490 setCondCodeAction(ISD::SETUO, MVT::f64, Expand); 491 } 492 setCondCodeAction(ISD::SETULT, MVT::f32, Expand); 493 setCondCodeAction(ISD::SETULT, MVT::f64, Expand); 494 setCondCodeAction(ISD::SETUGT, MVT::f32, Expand); 495 setCondCodeAction(ISD::SETUGT, MVT::f64, Expand); 496 setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand); 497 setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand); 498 setCondCodeAction(ISD::SETOGE, MVT::f32, Expand); 499 setCondCodeAction(ISD::SETOGE, MVT::f64, Expand); 500 setCondCodeAction(ISD::SETOLE, MVT::f32, Expand); 501 setCondCodeAction(ISD::SETOLE, MVT::f64, Expand); 502 setCondCodeAction(ISD::SETONE, MVT::f32, Expand); 503 setCondCodeAction(ISD::SETONE, MVT::f64, Expand); 504 505 if (Subtarget.has64BitSupport()) { 506 // They also have instructions for converting between i64 and fp. 507 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom); 508 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand); 509 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom); 510 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand); 511 // This is just the low 32 bits of a (signed) fp->i64 conversion. 512 // We cannot do this with Promote because i64 is not a legal type. 513 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 514 515 if (Subtarget.hasLFIWAX() || Subtarget.isPPC64()) 516 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom); 517 } else { 518 // PowerPC does not have FP_TO_UINT on 32-bit implementations. 519 if (Subtarget.hasSPE()) 520 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Legal); 521 else 522 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand); 523 } 524 525 // With the instructions enabled under FPCVT, we can do everything. 526 if (Subtarget.hasFPCVT()) { 527 if (Subtarget.has64BitSupport()) { 528 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom); 529 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom); 530 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom); 531 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom); 532 } 533 534 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 535 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 536 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom); 537 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom); 538 } 539 540 if (Subtarget.use64BitRegs()) { 541 // 64-bit PowerPC implementations can support i64 types directly 542 addRegisterClass(MVT::i64, &PPC::G8RCRegClass); 543 // BUILD_PAIR can't be handled natively, and should be expanded to shl/or 544 setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand); 545 // 64-bit PowerPC wants to expand i128 shifts itself. 546 setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom); 547 setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom); 548 setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom); 549 } else { 550 // 32-bit PowerPC wants to expand i64 shifts itself. 551 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom); 552 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom); 553 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom); 554 } 555 556 if (Subtarget.hasVSX()) { 557 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f64, Legal); 558 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f32, Legal); 559 setOperationAction(ISD::FMINNUM_IEEE, MVT::f64, Legal); 560 setOperationAction(ISD::FMINNUM_IEEE, MVT::f32, Legal); 561 } 562 563 if (Subtarget.hasAltivec()) { 564 // First set operation action for all vector types to expand. Then we 565 // will selectively turn on ones that can be effectively codegen'd. 566 for (MVT VT : MVT::fixedlen_vector_valuetypes()) { 567 // add/sub are legal for all supported vector VT's. 568 setOperationAction(ISD::ADD, VT, Legal); 569 setOperationAction(ISD::SUB, VT, Legal); 570 571 // For v2i64, these are only valid with P8Vector. This is corrected after 572 // the loop. 573 if (VT.getSizeInBits() <= 128 && VT.getScalarSizeInBits() <= 64) { 574 setOperationAction(ISD::SMAX, VT, Legal); 575 setOperationAction(ISD::SMIN, VT, Legal); 576 setOperationAction(ISD::UMAX, VT, Legal); 577 setOperationAction(ISD::UMIN, VT, Legal); 578 } 579 else { 580 setOperationAction(ISD::SMAX, VT, Expand); 581 setOperationAction(ISD::SMIN, VT, Expand); 582 setOperationAction(ISD::UMAX, VT, Expand); 583 setOperationAction(ISD::UMIN, VT, Expand); 584 } 585 586 if (Subtarget.hasVSX()) { 587 setOperationAction(ISD::FMAXNUM, VT, Legal); 588 setOperationAction(ISD::FMINNUM, VT, Legal); 589 } 590 591 // Vector instructions introduced in P8 592 if (Subtarget.hasP8Altivec() && (VT.SimpleTy != MVT::v1i128)) { 593 setOperationAction(ISD::CTPOP, VT, Legal); 594 setOperationAction(ISD::CTLZ, VT, Legal); 595 } 596 else { 597 setOperationAction(ISD::CTPOP, VT, Expand); 598 setOperationAction(ISD::CTLZ, VT, Expand); 599 } 600 601 // Vector instructions introduced in P9 602 if (Subtarget.hasP9Altivec() && (VT.SimpleTy != MVT::v1i128)) 603 setOperationAction(ISD::CTTZ, VT, Legal); 604 else 605 setOperationAction(ISD::CTTZ, VT, Expand); 606 607 // We promote all shuffles to v16i8. 608 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Promote); 609 AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8); 610 611 // We promote all non-typed operations to v4i32. 612 setOperationAction(ISD::AND , VT, Promote); 613 AddPromotedToType (ISD::AND , VT, MVT::v4i32); 614 setOperationAction(ISD::OR , VT, Promote); 615 AddPromotedToType (ISD::OR , VT, MVT::v4i32); 616 setOperationAction(ISD::XOR , VT, Promote); 617 AddPromotedToType (ISD::XOR , VT, MVT::v4i32); 618 setOperationAction(ISD::LOAD , VT, Promote); 619 AddPromotedToType (ISD::LOAD , VT, MVT::v4i32); 620 setOperationAction(ISD::SELECT, VT, Promote); 621 AddPromotedToType (ISD::SELECT, VT, MVT::v4i32); 622 setOperationAction(ISD::VSELECT, VT, Legal); 623 setOperationAction(ISD::SELECT_CC, VT, Promote); 624 AddPromotedToType (ISD::SELECT_CC, VT, MVT::v4i32); 625 setOperationAction(ISD::STORE, VT, Promote); 626 AddPromotedToType (ISD::STORE, VT, MVT::v4i32); 627 628 // No other operations are legal. 629 setOperationAction(ISD::MUL , VT, Expand); 630 setOperationAction(ISD::SDIV, VT, Expand); 631 setOperationAction(ISD::SREM, VT, Expand); 632 setOperationAction(ISD::UDIV, VT, Expand); 633 setOperationAction(ISD::UREM, VT, Expand); 634 setOperationAction(ISD::FDIV, VT, Expand); 635 setOperationAction(ISD::FREM, VT, Expand); 636 setOperationAction(ISD::FNEG, VT, Expand); 637 setOperationAction(ISD::FSQRT, VT, Expand); 638 setOperationAction(ISD::FLOG, VT, Expand); 639 setOperationAction(ISD::FLOG10, VT, Expand); 640 setOperationAction(ISD::FLOG2, VT, Expand); 641 setOperationAction(ISD::FEXP, VT, Expand); 642 setOperationAction(ISD::FEXP2, VT, Expand); 643 setOperationAction(ISD::FSIN, VT, Expand); 644 setOperationAction(ISD::FCOS, VT, Expand); 645 setOperationAction(ISD::FABS, VT, Expand); 646 setOperationAction(ISD::FFLOOR, VT, Expand); 647 setOperationAction(ISD::FCEIL, VT, Expand); 648 setOperationAction(ISD::FTRUNC, VT, Expand); 649 setOperationAction(ISD::FRINT, VT, Expand); 650 setOperationAction(ISD::FNEARBYINT, VT, Expand); 651 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand); 652 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand); 653 setOperationAction(ISD::BUILD_VECTOR, VT, Expand); 654 setOperationAction(ISD::MULHU, VT, Expand); 655 setOperationAction(ISD::MULHS, VT, Expand); 656 setOperationAction(ISD::UMUL_LOHI, VT, Expand); 657 setOperationAction(ISD::SMUL_LOHI, VT, Expand); 658 setOperationAction(ISD::UDIVREM, VT, Expand); 659 setOperationAction(ISD::SDIVREM, VT, Expand); 660 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand); 661 setOperationAction(ISD::FPOW, VT, Expand); 662 setOperationAction(ISD::BSWAP, VT, Expand); 663 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand); 664 setOperationAction(ISD::ROTL, VT, Expand); 665 setOperationAction(ISD::ROTR, VT, Expand); 666 667 for (MVT InnerVT : MVT::fixedlen_vector_valuetypes()) { 668 setTruncStoreAction(VT, InnerVT, Expand); 669 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand); 670 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand); 671 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand); 672 } 673 } 674 if (!Subtarget.hasP8Vector()) { 675 setOperationAction(ISD::SMAX, MVT::v2i64, Expand); 676 setOperationAction(ISD::SMIN, MVT::v2i64, Expand); 677 setOperationAction(ISD::UMAX, MVT::v2i64, Expand); 678 setOperationAction(ISD::UMIN, MVT::v2i64, Expand); 679 } 680 681 for (auto VT : {MVT::v2i64, MVT::v4i32, MVT::v8i16, MVT::v16i8}) 682 setOperationAction(ISD::ABS, VT, Custom); 683 684 // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle 685 // with merges, splats, etc. 686 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom); 687 688 // Vector truncates to sub-word integer that fit in an Altivec/VSX register 689 // are cheap, so handle them before they get expanded to scalar. 690 setOperationAction(ISD::TRUNCATE, MVT::v8i8, Custom); 691 setOperationAction(ISD::TRUNCATE, MVT::v4i8, Custom); 692 setOperationAction(ISD::TRUNCATE, MVT::v2i8, Custom); 693 setOperationAction(ISD::TRUNCATE, MVT::v4i16, Custom); 694 setOperationAction(ISD::TRUNCATE, MVT::v2i16, Custom); 695 696 setOperationAction(ISD::AND , MVT::v4i32, Legal); 697 setOperationAction(ISD::OR , MVT::v4i32, Legal); 698 setOperationAction(ISD::XOR , MVT::v4i32, Legal); 699 setOperationAction(ISD::LOAD , MVT::v4i32, Legal); 700 setOperationAction(ISD::SELECT, MVT::v4i32, 701 Subtarget.useCRBits() ? Legal : Expand); 702 setOperationAction(ISD::STORE , MVT::v4i32, Legal); 703 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal); 704 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal); 705 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal); 706 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal); 707 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal); 708 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal); 709 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal); 710 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal); 711 712 // Without hasP8Altivec set, v2i64 SMAX isn't available. 713 // But ABS custom lowering requires SMAX support. 714 if (!Subtarget.hasP8Altivec()) 715 setOperationAction(ISD::ABS, MVT::v2i64, Expand); 716 717 addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass); 718 addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass); 719 addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass); 720 addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass); 721 722 setOperationAction(ISD::MUL, MVT::v4f32, Legal); 723 setOperationAction(ISD::FMA, MVT::v4f32, Legal); 724 725 if (TM.Options.UnsafeFPMath || Subtarget.hasVSX()) { 726 setOperationAction(ISD::FDIV, MVT::v4f32, Legal); 727 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal); 728 } 729 730 if (Subtarget.hasP8Altivec()) 731 setOperationAction(ISD::MUL, MVT::v4i32, Legal); 732 else 733 setOperationAction(ISD::MUL, MVT::v4i32, Custom); 734 735 setOperationAction(ISD::MUL, MVT::v8i16, Custom); 736 setOperationAction(ISD::MUL, MVT::v16i8, Custom); 737 738 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom); 739 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom); 740 741 setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom); 742 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom); 743 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom); 744 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom); 745 746 // Altivec does not contain unordered floating-point compare instructions 747 setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand); 748 setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand); 749 setCondCodeAction(ISD::SETO, MVT::v4f32, Expand); 750 setCondCodeAction(ISD::SETONE, MVT::v4f32, Expand); 751 752 if (Subtarget.hasVSX()) { 753 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal); 754 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal); 755 if (Subtarget.hasP8Vector()) { 756 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal); 757 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Legal); 758 } 759 if (Subtarget.hasDirectMove() && isPPC64) { 760 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Legal); 761 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Legal); 762 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Legal); 763 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i64, Legal); 764 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Legal); 765 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Legal); 766 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Legal); 767 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal); 768 } 769 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal); 770 771 setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal); 772 setOperationAction(ISD::FCEIL, MVT::v2f64, Legal); 773 setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal); 774 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal); 775 setOperationAction(ISD::FROUND, MVT::v2f64, Legal); 776 777 setOperationAction(ISD::FROUND, MVT::v4f32, Legal); 778 779 setOperationAction(ISD::MUL, MVT::v2f64, Legal); 780 setOperationAction(ISD::FMA, MVT::v2f64, Legal); 781 782 setOperationAction(ISD::FDIV, MVT::v2f64, Legal); 783 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal); 784 785 // Share the Altivec comparison restrictions. 786 setCondCodeAction(ISD::SETUO, MVT::v2f64, Expand); 787 setCondCodeAction(ISD::SETUEQ, MVT::v2f64, Expand); 788 setCondCodeAction(ISD::SETO, MVT::v2f64, Expand); 789 setCondCodeAction(ISD::SETONE, MVT::v2f64, Expand); 790 791 setOperationAction(ISD::LOAD, MVT::v2f64, Legal); 792 setOperationAction(ISD::STORE, MVT::v2f64, Legal); 793 794 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Legal); 795 796 if (Subtarget.hasP8Vector()) 797 addRegisterClass(MVT::f32, &PPC::VSSRCRegClass); 798 799 addRegisterClass(MVT::f64, &PPC::VSFRCRegClass); 800 801 addRegisterClass(MVT::v4i32, &PPC::VSRCRegClass); 802 addRegisterClass(MVT::v4f32, &PPC::VSRCRegClass); 803 addRegisterClass(MVT::v2f64, &PPC::VSRCRegClass); 804 805 if (Subtarget.hasP8Altivec()) { 806 setOperationAction(ISD::SHL, MVT::v2i64, Legal); 807 setOperationAction(ISD::SRA, MVT::v2i64, Legal); 808 setOperationAction(ISD::SRL, MVT::v2i64, Legal); 809 810 // 128 bit shifts can be accomplished via 3 instructions for SHL and 811 // SRL, but not for SRA because of the instructions available: 812 // VS{RL} and VS{RL}O. However due to direct move costs, it's not worth 813 // doing 814 setOperationAction(ISD::SHL, MVT::v1i128, Expand); 815 setOperationAction(ISD::SRL, MVT::v1i128, Expand); 816 setOperationAction(ISD::SRA, MVT::v1i128, Expand); 817 818 setOperationAction(ISD::SETCC, MVT::v2i64, Legal); 819 } 820 else { 821 setOperationAction(ISD::SHL, MVT::v2i64, Expand); 822 setOperationAction(ISD::SRA, MVT::v2i64, Expand); 823 setOperationAction(ISD::SRL, MVT::v2i64, Expand); 824 825 setOperationAction(ISD::SETCC, MVT::v2i64, Custom); 826 827 // VSX v2i64 only supports non-arithmetic operations. 828 setOperationAction(ISD::ADD, MVT::v2i64, Expand); 829 setOperationAction(ISD::SUB, MVT::v2i64, Expand); 830 } 831 832 setOperationAction(ISD::LOAD, MVT::v2i64, Promote); 833 AddPromotedToType (ISD::LOAD, MVT::v2i64, MVT::v2f64); 834 setOperationAction(ISD::STORE, MVT::v2i64, Promote); 835 AddPromotedToType (ISD::STORE, MVT::v2i64, MVT::v2f64); 836 837 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Legal); 838 839 setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal); 840 setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal); 841 setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal); 842 setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal); 843 844 // Custom handling for partial vectors of integers converted to 845 // floating point. We already have optimal handling for v2i32 through 846 // the DAG combine, so those aren't necessary. 847 setOperationAction(ISD::UINT_TO_FP, MVT::v2i8, Custom); 848 setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Custom); 849 setOperationAction(ISD::UINT_TO_FP, MVT::v2i16, Custom); 850 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom); 851 setOperationAction(ISD::SINT_TO_FP, MVT::v2i8, Custom); 852 setOperationAction(ISD::SINT_TO_FP, MVT::v4i8, Custom); 853 setOperationAction(ISD::SINT_TO_FP, MVT::v2i16, Custom); 854 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom); 855 856 setOperationAction(ISD::FNEG, MVT::v4f32, Legal); 857 setOperationAction(ISD::FNEG, MVT::v2f64, Legal); 858 setOperationAction(ISD::FABS, MVT::v4f32, Legal); 859 setOperationAction(ISD::FABS, MVT::v2f64, Legal); 860 setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Legal); 861 setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Legal); 862 863 if (Subtarget.hasDirectMove()) 864 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom); 865 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom); 866 867 addRegisterClass(MVT::v2i64, &PPC::VSRCRegClass); 868 } 869 870 if (Subtarget.hasP8Altivec()) { 871 addRegisterClass(MVT::v2i64, &PPC::VRRCRegClass); 872 addRegisterClass(MVT::v1i128, &PPC::VRRCRegClass); 873 } 874 875 if (Subtarget.hasP9Vector()) { 876 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom); 877 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom); 878 879 // 128 bit shifts can be accomplished via 3 instructions for SHL and 880 // SRL, but not for SRA because of the instructions available: 881 // VS{RL} and VS{RL}O. 882 setOperationAction(ISD::SHL, MVT::v1i128, Legal); 883 setOperationAction(ISD::SRL, MVT::v1i128, Legal); 884 setOperationAction(ISD::SRA, MVT::v1i128, Expand); 885 886 if (EnableQuadPrecision) { 887 addRegisterClass(MVT::f128, &PPC::VRRCRegClass); 888 setOperationAction(ISD::FADD, MVT::f128, Legal); 889 setOperationAction(ISD::FSUB, MVT::f128, Legal); 890 setOperationAction(ISD::FDIV, MVT::f128, Legal); 891 setOperationAction(ISD::FMUL, MVT::f128, Legal); 892 setOperationAction(ISD::FP_EXTEND, MVT::f128, Legal); 893 // No extending loads to f128 on PPC. 894 for (MVT FPT : MVT::fp_valuetypes()) 895 setLoadExtAction(ISD::EXTLOAD, MVT::f128, FPT, Expand); 896 setOperationAction(ISD::FMA, MVT::f128, Legal); 897 setCondCodeAction(ISD::SETULT, MVT::f128, Expand); 898 setCondCodeAction(ISD::SETUGT, MVT::f128, Expand); 899 setCondCodeAction(ISD::SETUEQ, MVT::f128, Expand); 900 setCondCodeAction(ISD::SETOGE, MVT::f128, Expand); 901 setCondCodeAction(ISD::SETOLE, MVT::f128, Expand); 902 setCondCodeAction(ISD::SETONE, MVT::f128, Expand); 903 904 setOperationAction(ISD::FTRUNC, MVT::f128, Legal); 905 setOperationAction(ISD::FRINT, MVT::f128, Legal); 906 setOperationAction(ISD::FFLOOR, MVT::f128, Legal); 907 setOperationAction(ISD::FCEIL, MVT::f128, Legal); 908 setOperationAction(ISD::FNEARBYINT, MVT::f128, Legal); 909 setOperationAction(ISD::FROUND, MVT::f128, Legal); 910 911 setOperationAction(ISD::SELECT, MVT::f128, Expand); 912 setOperationAction(ISD::FP_ROUND, MVT::f64, Legal); 913 setOperationAction(ISD::FP_ROUND, MVT::f32, Legal); 914 setTruncStoreAction(MVT::f128, MVT::f64, Expand); 915 setTruncStoreAction(MVT::f128, MVT::f32, Expand); 916 setOperationAction(ISD::BITCAST, MVT::i128, Custom); 917 // No implementation for these ops for PowerPC. 918 setOperationAction(ISD::FSIN , MVT::f128, Expand); 919 setOperationAction(ISD::FCOS , MVT::f128, Expand); 920 setOperationAction(ISD::FPOW, MVT::f128, Expand); 921 setOperationAction(ISD::FPOWI, MVT::f128, Expand); 922 setOperationAction(ISD::FREM, MVT::f128, Expand); 923 } 924 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom); 925 setOperationAction(ISD::BSWAP, MVT::v8i16, Legal); 926 setOperationAction(ISD::BSWAP, MVT::v4i32, Legal); 927 setOperationAction(ISD::BSWAP, MVT::v2i64, Legal); 928 setOperationAction(ISD::BSWAP, MVT::v1i128, Legal); 929 } 930 931 if (Subtarget.hasP9Altivec()) { 932 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom); 933 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom); 934 935 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Legal); 936 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Legal); 937 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i32, Legal); 938 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Legal); 939 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Legal); 940 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i32, Legal); 941 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i64, Legal); 942 } 943 } 944 945 if (Subtarget.hasQPX()) { 946 setOperationAction(ISD::FADD, MVT::v4f64, Legal); 947 setOperationAction(ISD::FSUB, MVT::v4f64, Legal); 948 setOperationAction(ISD::FMUL, MVT::v4f64, Legal); 949 setOperationAction(ISD::FREM, MVT::v4f64, Expand); 950 951 setOperationAction(ISD::FCOPYSIGN, MVT::v4f64, Legal); 952 setOperationAction(ISD::FGETSIGN, MVT::v4f64, Expand); 953 954 setOperationAction(ISD::LOAD , MVT::v4f64, Custom); 955 setOperationAction(ISD::STORE , MVT::v4f64, Custom); 956 957 setTruncStoreAction(MVT::v4f64, MVT::v4f32, Custom); 958 setLoadExtAction(ISD::EXTLOAD, MVT::v4f64, MVT::v4f32, Custom); 959 960 if (!Subtarget.useCRBits()) 961 setOperationAction(ISD::SELECT, MVT::v4f64, Expand); 962 setOperationAction(ISD::VSELECT, MVT::v4f64, Legal); 963 964 setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f64, Legal); 965 setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f64, Expand); 966 setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f64, Expand); 967 setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f64, Expand); 968 setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f64, Custom); 969 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f64, Legal); 970 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f64, Custom); 971 972 setOperationAction(ISD::FP_TO_SINT , MVT::v4f64, Legal); 973 setOperationAction(ISD::FP_TO_UINT , MVT::v4f64, Expand); 974 975 setOperationAction(ISD::FP_ROUND , MVT::v4f32, Legal); 976 setOperationAction(ISD::FP_EXTEND, MVT::v4f64, Legal); 977 978 setOperationAction(ISD::FNEG , MVT::v4f64, Legal); 979 setOperationAction(ISD::FABS , MVT::v4f64, Legal); 980 setOperationAction(ISD::FSIN , MVT::v4f64, Expand); 981 setOperationAction(ISD::FCOS , MVT::v4f64, Expand); 982 setOperationAction(ISD::FPOW , MVT::v4f64, Expand); 983 setOperationAction(ISD::FLOG , MVT::v4f64, Expand); 984 setOperationAction(ISD::FLOG2 , MVT::v4f64, Expand); 985 setOperationAction(ISD::FLOG10 , MVT::v4f64, Expand); 986 setOperationAction(ISD::FEXP , MVT::v4f64, Expand); 987 setOperationAction(ISD::FEXP2 , MVT::v4f64, Expand); 988 989 setOperationAction(ISD::FMINNUM, MVT::v4f64, Legal); 990 setOperationAction(ISD::FMAXNUM, MVT::v4f64, Legal); 991 992 setIndexedLoadAction(ISD::PRE_INC, MVT::v4f64, Legal); 993 setIndexedStoreAction(ISD::PRE_INC, MVT::v4f64, Legal); 994 995 addRegisterClass(MVT::v4f64, &PPC::QFRCRegClass); 996 997 setOperationAction(ISD::FADD, MVT::v4f32, Legal); 998 setOperationAction(ISD::FSUB, MVT::v4f32, Legal); 999 setOperationAction(ISD::FMUL, MVT::v4f32, Legal); 1000 setOperationAction(ISD::FREM, MVT::v4f32, Expand); 1001 1002 setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Legal); 1003 setOperationAction(ISD::FGETSIGN, MVT::v4f32, Expand); 1004 1005 setOperationAction(ISD::LOAD , MVT::v4f32, Custom); 1006 setOperationAction(ISD::STORE , MVT::v4f32, Custom); 1007 1008 if (!Subtarget.useCRBits()) 1009 setOperationAction(ISD::SELECT, MVT::v4f32, Expand); 1010 setOperationAction(ISD::VSELECT, MVT::v4f32, Legal); 1011 1012 setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f32, Legal); 1013 setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f32, Expand); 1014 setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f32, Expand); 1015 setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f32, Expand); 1016 setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f32, Custom); 1017 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal); 1018 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom); 1019 1020 setOperationAction(ISD::FP_TO_SINT , MVT::v4f32, Legal); 1021 setOperationAction(ISD::FP_TO_UINT , MVT::v4f32, Expand); 1022 1023 setOperationAction(ISD::FNEG , MVT::v4f32, Legal); 1024 setOperationAction(ISD::FABS , MVT::v4f32, Legal); 1025 setOperationAction(ISD::FSIN , MVT::v4f32, Expand); 1026 setOperationAction(ISD::FCOS , MVT::v4f32, Expand); 1027 setOperationAction(ISD::FPOW , MVT::v4f32, Expand); 1028 setOperationAction(ISD::FLOG , MVT::v4f32, Expand); 1029 setOperationAction(ISD::FLOG2 , MVT::v4f32, Expand); 1030 setOperationAction(ISD::FLOG10 , MVT::v4f32, Expand); 1031 setOperationAction(ISD::FEXP , MVT::v4f32, Expand); 1032 setOperationAction(ISD::FEXP2 , MVT::v4f32, Expand); 1033 1034 setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal); 1035 setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal); 1036 1037 setIndexedLoadAction(ISD::PRE_INC, MVT::v4f32, Legal); 1038 setIndexedStoreAction(ISD::PRE_INC, MVT::v4f32, Legal); 1039 1040 addRegisterClass(MVT::v4f32, &PPC::QSRCRegClass); 1041 1042 setOperationAction(ISD::AND , MVT::v4i1, Legal); 1043 setOperationAction(ISD::OR , MVT::v4i1, Legal); 1044 setOperationAction(ISD::XOR , MVT::v4i1, Legal); 1045 1046 if (!Subtarget.useCRBits()) 1047 setOperationAction(ISD::SELECT, MVT::v4i1, Expand); 1048 setOperationAction(ISD::VSELECT, MVT::v4i1, Legal); 1049 1050 setOperationAction(ISD::LOAD , MVT::v4i1, Custom); 1051 setOperationAction(ISD::STORE , MVT::v4i1, Custom); 1052 1053 setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4i1, Custom); 1054 setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4i1, Expand); 1055 setOperationAction(ISD::CONCAT_VECTORS , MVT::v4i1, Expand); 1056 setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4i1, Expand); 1057 setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4i1, Custom); 1058 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i1, Expand); 1059 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i1, Custom); 1060 1061 setOperationAction(ISD::SINT_TO_FP, MVT::v4i1, Custom); 1062 setOperationAction(ISD::UINT_TO_FP, MVT::v4i1, Custom); 1063 1064 addRegisterClass(MVT::v4i1, &PPC::QBRCRegClass); 1065 1066 setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal); 1067 setOperationAction(ISD::FCEIL, MVT::v4f64, Legal); 1068 setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal); 1069 setOperationAction(ISD::FROUND, MVT::v4f64, Legal); 1070 1071 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal); 1072 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal); 1073 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal); 1074 setOperationAction(ISD::FROUND, MVT::v4f32, Legal); 1075 1076 setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Expand); 1077 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand); 1078 1079 // These need to set FE_INEXACT, and so cannot be vectorized here. 1080 setOperationAction(ISD::FRINT, MVT::v4f64, Expand); 1081 setOperationAction(ISD::FRINT, MVT::v4f32, Expand); 1082 1083 if (TM.Options.UnsafeFPMath) { 1084 setOperationAction(ISD::FDIV, MVT::v4f64, Legal); 1085 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal); 1086 1087 setOperationAction(ISD::FDIV, MVT::v4f32, Legal); 1088 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal); 1089 } else { 1090 setOperationAction(ISD::FDIV, MVT::v4f64, Expand); 1091 setOperationAction(ISD::FSQRT, MVT::v4f64, Expand); 1092 1093 setOperationAction(ISD::FDIV, MVT::v4f32, Expand); 1094 setOperationAction(ISD::FSQRT, MVT::v4f32, Expand); 1095 } 1096 } 1097 1098 if (Subtarget.has64BitSupport()) 1099 setOperationAction(ISD::PREFETCH, MVT::Other, Legal); 1100 1101 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, isPPC64 ? Legal : Custom); 1102 1103 if (!isPPC64) { 1104 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Expand); 1105 setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand); 1106 } 1107 1108 setBooleanContents(ZeroOrOneBooleanContent); 1109 1110 if (Subtarget.hasAltivec()) { 1111 // Altivec instructions set fields to all zeros or all ones. 1112 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent); 1113 } 1114 1115 if (!isPPC64) { 1116 // These libcalls are not available in 32-bit. 1117 setLibcallName(RTLIB::SHL_I128, nullptr); 1118 setLibcallName(RTLIB::SRL_I128, nullptr); 1119 setLibcallName(RTLIB::SRA_I128, nullptr); 1120 } 1121 1122 setStackPointerRegisterToSaveRestore(isPPC64 ? PPC::X1 : PPC::R1); 1123 1124 // We have target-specific dag combine patterns for the following nodes: 1125 setTargetDAGCombine(ISD::ADD); 1126 setTargetDAGCombine(ISD::SHL); 1127 setTargetDAGCombine(ISD::SRA); 1128 setTargetDAGCombine(ISD::SRL); 1129 setTargetDAGCombine(ISD::MUL); 1130 setTargetDAGCombine(ISD::SINT_TO_FP); 1131 setTargetDAGCombine(ISD::BUILD_VECTOR); 1132 if (Subtarget.hasFPCVT()) 1133 setTargetDAGCombine(ISD::UINT_TO_FP); 1134 setTargetDAGCombine(ISD::LOAD); 1135 setTargetDAGCombine(ISD::STORE); 1136 setTargetDAGCombine(ISD::BR_CC); 1137 if (Subtarget.useCRBits()) 1138 setTargetDAGCombine(ISD::BRCOND); 1139 setTargetDAGCombine(ISD::BSWAP); 1140 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN); 1141 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN); 1142 setTargetDAGCombine(ISD::INTRINSIC_VOID); 1143 1144 setTargetDAGCombine(ISD::SIGN_EXTEND); 1145 setTargetDAGCombine(ISD::ZERO_EXTEND); 1146 setTargetDAGCombine(ISD::ANY_EXTEND); 1147 1148 setTargetDAGCombine(ISD::TRUNCATE); 1149 setTargetDAGCombine(ISD::VECTOR_SHUFFLE); 1150 1151 1152 if (Subtarget.useCRBits()) { 1153 setTargetDAGCombine(ISD::TRUNCATE); 1154 setTargetDAGCombine(ISD::SETCC); 1155 setTargetDAGCombine(ISD::SELECT_CC); 1156 } 1157 1158 // Use reciprocal estimates. 1159 if (TM.Options.UnsafeFPMath) { 1160 setTargetDAGCombine(ISD::FDIV); 1161 setTargetDAGCombine(ISD::FSQRT); 1162 } 1163 1164 if (Subtarget.hasP9Altivec()) { 1165 setTargetDAGCombine(ISD::ABS); 1166 setTargetDAGCombine(ISD::VSELECT); 1167 } 1168 1169 // Darwin long double math library functions have $LDBL128 appended. 1170 if (Subtarget.isDarwin()) { 1171 setLibcallName(RTLIB::COS_PPCF128, "cosl$LDBL128"); 1172 setLibcallName(RTLIB::POW_PPCF128, "powl$LDBL128"); 1173 setLibcallName(RTLIB::REM_PPCF128, "fmodl$LDBL128"); 1174 setLibcallName(RTLIB::SIN_PPCF128, "sinl$LDBL128"); 1175 setLibcallName(RTLIB::SQRT_PPCF128, "sqrtl$LDBL128"); 1176 setLibcallName(RTLIB::LOG_PPCF128, "logl$LDBL128"); 1177 setLibcallName(RTLIB::LOG2_PPCF128, "log2l$LDBL128"); 1178 setLibcallName(RTLIB::LOG10_PPCF128, "log10l$LDBL128"); 1179 setLibcallName(RTLIB::EXP_PPCF128, "expl$LDBL128"); 1180 setLibcallName(RTLIB::EXP2_PPCF128, "exp2l$LDBL128"); 1181 } 1182 1183 if (EnableQuadPrecision) { 1184 setLibcallName(RTLIB::LOG_F128, "logf128"); 1185 setLibcallName(RTLIB::LOG2_F128, "log2f128"); 1186 setLibcallName(RTLIB::LOG10_F128, "log10f128"); 1187 setLibcallName(RTLIB::EXP_F128, "expf128"); 1188 setLibcallName(RTLIB::EXP2_F128, "exp2f128"); 1189 setLibcallName(RTLIB::SIN_F128, "sinf128"); 1190 setLibcallName(RTLIB::COS_F128, "cosf128"); 1191 setLibcallName(RTLIB::POW_F128, "powf128"); 1192 setLibcallName(RTLIB::FMIN_F128, "fminf128"); 1193 setLibcallName(RTLIB::FMAX_F128, "fmaxf128"); 1194 setLibcallName(RTLIB::POWI_F128, "__powikf2"); 1195 setLibcallName(RTLIB::REM_F128, "fmodf128"); 1196 } 1197 1198 // With 32 condition bits, we don't need to sink (and duplicate) compares 1199 // aggressively in CodeGenPrep. 1200 if (Subtarget.useCRBits()) { 1201 setHasMultipleConditionRegisters(); 1202 setJumpIsExpensive(); 1203 } 1204 1205 setMinFunctionAlignment(Align(4)); 1206 if (Subtarget.isDarwin()) 1207 setPrefFunctionAlignment(Align(16)); 1208 1209 switch (Subtarget.getCPUDirective()) { 1210 default: break; 1211 case PPC::DIR_970: 1212 case PPC::DIR_A2: 1213 case PPC::DIR_E500: 1214 case PPC::DIR_E500mc: 1215 case PPC::DIR_E5500: 1216 case PPC::DIR_PWR4: 1217 case PPC::DIR_PWR5: 1218 case PPC::DIR_PWR5X: 1219 case PPC::DIR_PWR6: 1220 case PPC::DIR_PWR6X: 1221 case PPC::DIR_PWR7: 1222 case PPC::DIR_PWR8: 1223 case PPC::DIR_PWR9: 1224 case PPC::DIR_PWR_FUTURE: 1225 setPrefLoopAlignment(Align(16)); 1226 setPrefFunctionAlignment(Align(16)); 1227 break; 1228 } 1229 1230 if (Subtarget.enableMachineScheduler()) 1231 setSchedulingPreference(Sched::Source); 1232 else 1233 setSchedulingPreference(Sched::Hybrid); 1234 1235 computeRegisterProperties(STI.getRegisterInfo()); 1236 1237 // The Freescale cores do better with aggressive inlining of memcpy and 1238 // friends. GCC uses same threshold of 128 bytes (= 32 word stores). 1239 if (Subtarget.getCPUDirective() == PPC::DIR_E500mc || 1240 Subtarget.getCPUDirective() == PPC::DIR_E5500) { 1241 MaxStoresPerMemset = 32; 1242 MaxStoresPerMemsetOptSize = 16; 1243 MaxStoresPerMemcpy = 32; 1244 MaxStoresPerMemcpyOptSize = 8; 1245 MaxStoresPerMemmove = 32; 1246 MaxStoresPerMemmoveOptSize = 8; 1247 } else if (Subtarget.getCPUDirective() == PPC::DIR_A2) { 1248 // The A2 also benefits from (very) aggressive inlining of memcpy and 1249 // friends. The overhead of a the function call, even when warm, can be 1250 // over one hundred cycles. 1251 MaxStoresPerMemset = 128; 1252 MaxStoresPerMemcpy = 128; 1253 MaxStoresPerMemmove = 128; 1254 MaxLoadsPerMemcmp = 128; 1255 } else { 1256 MaxLoadsPerMemcmp = 8; 1257 MaxLoadsPerMemcmpOptSize = 4; 1258 } 1259 } 1260 1261 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine 1262 /// the desired ByVal argument alignment. 1263 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign, 1264 unsigned MaxMaxAlign) { 1265 if (MaxAlign == MaxMaxAlign) 1266 return; 1267 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) { 1268 if (MaxMaxAlign >= 32 && VTy->getBitWidth() >= 256) 1269 MaxAlign = 32; 1270 else if (VTy->getBitWidth() >= 128 && MaxAlign < 16) 1271 MaxAlign = 16; 1272 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) { 1273 unsigned EltAlign = 0; 1274 getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign); 1275 if (EltAlign > MaxAlign) 1276 MaxAlign = EltAlign; 1277 } else if (StructType *STy = dyn_cast<StructType>(Ty)) { 1278 for (auto *EltTy : STy->elements()) { 1279 unsigned EltAlign = 0; 1280 getMaxByValAlign(EltTy, EltAlign, MaxMaxAlign); 1281 if (EltAlign > MaxAlign) 1282 MaxAlign = EltAlign; 1283 if (MaxAlign == MaxMaxAlign) 1284 break; 1285 } 1286 } 1287 } 1288 1289 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate 1290 /// function arguments in the caller parameter area. 1291 unsigned PPCTargetLowering::getByValTypeAlignment(Type *Ty, 1292 const DataLayout &DL) const { 1293 // Darwin passes everything on 4 byte boundary. 1294 if (Subtarget.isDarwin()) 1295 return 4; 1296 1297 // 16byte and wider vectors are passed on 16byte boundary. 1298 // The rest is 8 on PPC64 and 4 on PPC32 boundary. 1299 unsigned Align = Subtarget.isPPC64() ? 8 : 4; 1300 if (Subtarget.hasAltivec() || Subtarget.hasQPX()) 1301 getMaxByValAlign(Ty, Align, Subtarget.hasQPX() ? 32 : 16); 1302 return Align; 1303 } 1304 1305 bool PPCTargetLowering::useSoftFloat() const { 1306 return Subtarget.useSoftFloat(); 1307 } 1308 1309 bool PPCTargetLowering::hasSPE() const { 1310 return Subtarget.hasSPE(); 1311 } 1312 1313 bool PPCTargetLowering::preferIncOfAddToSubOfNot(EVT VT) const { 1314 return VT.isScalarInteger(); 1315 } 1316 1317 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const { 1318 switch ((PPCISD::NodeType)Opcode) { 1319 case PPCISD::FIRST_NUMBER: break; 1320 case PPCISD::FSEL: return "PPCISD::FSEL"; 1321 case PPCISD::XSMAXCDP: return "PPCISD::XSMAXCDP"; 1322 case PPCISD::XSMINCDP: return "PPCISD::XSMINCDP"; 1323 case PPCISD::FCFID: return "PPCISD::FCFID"; 1324 case PPCISD::FCFIDU: return "PPCISD::FCFIDU"; 1325 case PPCISD::FCFIDS: return "PPCISD::FCFIDS"; 1326 case PPCISD::FCFIDUS: return "PPCISD::FCFIDUS"; 1327 case PPCISD::FCTIDZ: return "PPCISD::FCTIDZ"; 1328 case PPCISD::FCTIWZ: return "PPCISD::FCTIWZ"; 1329 case PPCISD::FCTIDUZ: return "PPCISD::FCTIDUZ"; 1330 case PPCISD::FCTIWUZ: return "PPCISD::FCTIWUZ"; 1331 case PPCISD::FP_TO_UINT_IN_VSR: 1332 return "PPCISD::FP_TO_UINT_IN_VSR,"; 1333 case PPCISD::FP_TO_SINT_IN_VSR: 1334 return "PPCISD::FP_TO_SINT_IN_VSR"; 1335 case PPCISD::FRE: return "PPCISD::FRE"; 1336 case PPCISD::FRSQRTE: return "PPCISD::FRSQRTE"; 1337 case PPCISD::STFIWX: return "PPCISD::STFIWX"; 1338 case PPCISD::VMADDFP: return "PPCISD::VMADDFP"; 1339 case PPCISD::VNMSUBFP: return "PPCISD::VNMSUBFP"; 1340 case PPCISD::VPERM: return "PPCISD::VPERM"; 1341 case PPCISD::XXSPLT: return "PPCISD::XXSPLT"; 1342 case PPCISD::VECINSERT: return "PPCISD::VECINSERT"; 1343 case PPCISD::XXREVERSE: return "PPCISD::XXREVERSE"; 1344 case PPCISD::XXPERMDI: return "PPCISD::XXPERMDI"; 1345 case PPCISD::VECSHL: return "PPCISD::VECSHL"; 1346 case PPCISD::CMPB: return "PPCISD::CMPB"; 1347 case PPCISD::Hi: return "PPCISD::Hi"; 1348 case PPCISD::Lo: return "PPCISD::Lo"; 1349 case PPCISD::TOC_ENTRY: return "PPCISD::TOC_ENTRY"; 1350 case PPCISD::ATOMIC_CMP_SWAP_8: return "PPCISD::ATOMIC_CMP_SWAP_8"; 1351 case PPCISD::ATOMIC_CMP_SWAP_16: return "PPCISD::ATOMIC_CMP_SWAP_16"; 1352 case PPCISD::DYNALLOC: return "PPCISD::DYNALLOC"; 1353 case PPCISD::DYNAREAOFFSET: return "PPCISD::DYNAREAOFFSET"; 1354 case PPCISD::GlobalBaseReg: return "PPCISD::GlobalBaseReg"; 1355 case PPCISD::SRL: return "PPCISD::SRL"; 1356 case PPCISD::SRA: return "PPCISD::SRA"; 1357 case PPCISD::SHL: return "PPCISD::SHL"; 1358 case PPCISD::SRA_ADDZE: return "PPCISD::SRA_ADDZE"; 1359 case PPCISD::CALL: return "PPCISD::CALL"; 1360 case PPCISD::CALL_NOP: return "PPCISD::CALL_NOP"; 1361 case PPCISD::MTCTR: return "PPCISD::MTCTR"; 1362 case PPCISD::BCTRL: return "PPCISD::BCTRL"; 1363 case PPCISD::BCTRL_LOAD_TOC: return "PPCISD::BCTRL_LOAD_TOC"; 1364 case PPCISD::RET_FLAG: return "PPCISD::RET_FLAG"; 1365 case PPCISD::READ_TIME_BASE: return "PPCISD::READ_TIME_BASE"; 1366 case PPCISD::EH_SJLJ_SETJMP: return "PPCISD::EH_SJLJ_SETJMP"; 1367 case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP"; 1368 case PPCISD::MFOCRF: return "PPCISD::MFOCRF"; 1369 case PPCISD::MFVSR: return "PPCISD::MFVSR"; 1370 case PPCISD::MTVSRA: return "PPCISD::MTVSRA"; 1371 case PPCISD::MTVSRZ: return "PPCISD::MTVSRZ"; 1372 case PPCISD::SINT_VEC_TO_FP: return "PPCISD::SINT_VEC_TO_FP"; 1373 case PPCISD::UINT_VEC_TO_FP: return "PPCISD::UINT_VEC_TO_FP"; 1374 case PPCISD::ANDIo_1_EQ_BIT: return "PPCISD::ANDIo_1_EQ_BIT"; 1375 case PPCISD::ANDIo_1_GT_BIT: return "PPCISD::ANDIo_1_GT_BIT"; 1376 case PPCISD::VCMP: return "PPCISD::VCMP"; 1377 case PPCISD::VCMPo: return "PPCISD::VCMPo"; 1378 case PPCISD::LBRX: return "PPCISD::LBRX"; 1379 case PPCISD::STBRX: return "PPCISD::STBRX"; 1380 case PPCISD::LFIWAX: return "PPCISD::LFIWAX"; 1381 case PPCISD::LFIWZX: return "PPCISD::LFIWZX"; 1382 case PPCISD::LXSIZX: return "PPCISD::LXSIZX"; 1383 case PPCISD::STXSIX: return "PPCISD::STXSIX"; 1384 case PPCISD::VEXTS: return "PPCISD::VEXTS"; 1385 case PPCISD::SExtVElems: return "PPCISD::SExtVElems"; 1386 case PPCISD::LXVD2X: return "PPCISD::LXVD2X"; 1387 case PPCISD::STXVD2X: return "PPCISD::STXVD2X"; 1388 case PPCISD::LOAD_VEC_BE: return "PPCISD::LOAD_VEC_BE"; 1389 case PPCISD::STORE_VEC_BE: return "PPCISD::STORE_VEC_BE"; 1390 case PPCISD::ST_VSR_SCAL_INT: 1391 return "PPCISD::ST_VSR_SCAL_INT"; 1392 case PPCISD::COND_BRANCH: return "PPCISD::COND_BRANCH"; 1393 case PPCISD::BDNZ: return "PPCISD::BDNZ"; 1394 case PPCISD::BDZ: return "PPCISD::BDZ"; 1395 case PPCISD::MFFS: return "PPCISD::MFFS"; 1396 case PPCISD::FADDRTZ: return "PPCISD::FADDRTZ"; 1397 case PPCISD::TC_RETURN: return "PPCISD::TC_RETURN"; 1398 case PPCISD::CR6SET: return "PPCISD::CR6SET"; 1399 case PPCISD::CR6UNSET: return "PPCISD::CR6UNSET"; 1400 case PPCISD::PPC32_GOT: return "PPCISD::PPC32_GOT"; 1401 case PPCISD::PPC32_PICGOT: return "PPCISD::PPC32_PICGOT"; 1402 case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA"; 1403 case PPCISD::LD_GOT_TPREL_L: return "PPCISD::LD_GOT_TPREL_L"; 1404 case PPCISD::ADD_TLS: return "PPCISD::ADD_TLS"; 1405 case PPCISD::ADDIS_TLSGD_HA: return "PPCISD::ADDIS_TLSGD_HA"; 1406 case PPCISD::ADDI_TLSGD_L: return "PPCISD::ADDI_TLSGD_L"; 1407 case PPCISD::GET_TLS_ADDR: return "PPCISD::GET_TLS_ADDR"; 1408 case PPCISD::ADDI_TLSGD_L_ADDR: return "PPCISD::ADDI_TLSGD_L_ADDR"; 1409 case PPCISD::ADDIS_TLSLD_HA: return "PPCISD::ADDIS_TLSLD_HA"; 1410 case PPCISD::ADDI_TLSLD_L: return "PPCISD::ADDI_TLSLD_L"; 1411 case PPCISD::GET_TLSLD_ADDR: return "PPCISD::GET_TLSLD_ADDR"; 1412 case PPCISD::ADDI_TLSLD_L_ADDR: return "PPCISD::ADDI_TLSLD_L_ADDR"; 1413 case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA"; 1414 case PPCISD::ADDI_DTPREL_L: return "PPCISD::ADDI_DTPREL_L"; 1415 case PPCISD::VADD_SPLAT: return "PPCISD::VADD_SPLAT"; 1416 case PPCISD::SC: return "PPCISD::SC"; 1417 case PPCISD::CLRBHRB: return "PPCISD::CLRBHRB"; 1418 case PPCISD::MFBHRBE: return "PPCISD::MFBHRBE"; 1419 case PPCISD::RFEBB: return "PPCISD::RFEBB"; 1420 case PPCISD::XXSWAPD: return "PPCISD::XXSWAPD"; 1421 case PPCISD::SWAP_NO_CHAIN: return "PPCISD::SWAP_NO_CHAIN"; 1422 case PPCISD::VABSD: return "PPCISD::VABSD"; 1423 case PPCISD::QVFPERM: return "PPCISD::QVFPERM"; 1424 case PPCISD::QVGPCI: return "PPCISD::QVGPCI"; 1425 case PPCISD::QVALIGNI: return "PPCISD::QVALIGNI"; 1426 case PPCISD::QVESPLATI: return "PPCISD::QVESPLATI"; 1427 case PPCISD::QBFLT: return "PPCISD::QBFLT"; 1428 case PPCISD::QVLFSb: return "PPCISD::QVLFSb"; 1429 case PPCISD::BUILD_FP128: return "PPCISD::BUILD_FP128"; 1430 case PPCISD::BUILD_SPE64: return "PPCISD::BUILD_SPE64"; 1431 case PPCISD::EXTRACT_SPE: return "PPCISD::EXTRACT_SPE"; 1432 case PPCISD::EXTSWSLI: return "PPCISD::EXTSWSLI"; 1433 case PPCISD::LD_VSX_LH: return "PPCISD::LD_VSX_LH"; 1434 case PPCISD::FP_EXTEND_HALF: return "PPCISD::FP_EXTEND_HALF"; 1435 case PPCISD::LD_SPLAT: return "PPCISD::LD_SPLAT"; 1436 } 1437 return nullptr; 1438 } 1439 1440 EVT PPCTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &C, 1441 EVT VT) const { 1442 if (!VT.isVector()) 1443 return Subtarget.useCRBits() ? MVT::i1 : MVT::i32; 1444 1445 if (Subtarget.hasQPX()) 1446 return EVT::getVectorVT(C, MVT::i1, VT.getVectorNumElements()); 1447 1448 return VT.changeVectorElementTypeToInteger(); 1449 } 1450 1451 bool PPCTargetLowering::enableAggressiveFMAFusion(EVT VT) const { 1452 assert(VT.isFloatingPoint() && "Non-floating-point FMA?"); 1453 return true; 1454 } 1455 1456 //===----------------------------------------------------------------------===// 1457 // Node matching predicates, for use by the tblgen matching code. 1458 //===----------------------------------------------------------------------===// 1459 1460 /// isFloatingPointZero - Return true if this is 0.0 or -0.0. 1461 static bool isFloatingPointZero(SDValue Op) { 1462 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) 1463 return CFP->getValueAPF().isZero(); 1464 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) { 1465 // Maybe this has already been legalized into the constant pool? 1466 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1))) 1467 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal())) 1468 return CFP->getValueAPF().isZero(); 1469 } 1470 return false; 1471 } 1472 1473 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode. Return 1474 /// true if Op is undef or if it matches the specified value. 1475 static bool isConstantOrUndef(int Op, int Val) { 1476 return Op < 0 || Op == Val; 1477 } 1478 1479 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a 1480 /// VPKUHUM instruction. 1481 /// The ShuffleKind distinguishes between big-endian operations with 1482 /// two different inputs (0), either-endian operations with two identical 1483 /// inputs (1), and little-endian operations with two different inputs (2). 1484 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td). 1485 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind, 1486 SelectionDAG &DAG) { 1487 bool IsLE = DAG.getDataLayout().isLittleEndian(); 1488 if (ShuffleKind == 0) { 1489 if (IsLE) 1490 return false; 1491 for (unsigned i = 0; i != 16; ++i) 1492 if (!isConstantOrUndef(N->getMaskElt(i), i*2+1)) 1493 return false; 1494 } else if (ShuffleKind == 2) { 1495 if (!IsLE) 1496 return false; 1497 for (unsigned i = 0; i != 16; ++i) 1498 if (!isConstantOrUndef(N->getMaskElt(i), i*2)) 1499 return false; 1500 } else if (ShuffleKind == 1) { 1501 unsigned j = IsLE ? 0 : 1; 1502 for (unsigned i = 0; i != 8; ++i) 1503 if (!isConstantOrUndef(N->getMaskElt(i), i*2+j) || 1504 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j)) 1505 return false; 1506 } 1507 return true; 1508 } 1509 1510 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a 1511 /// VPKUWUM instruction. 1512 /// The ShuffleKind distinguishes between big-endian operations with 1513 /// two different inputs (0), either-endian operations with two identical 1514 /// inputs (1), and little-endian operations with two different inputs (2). 1515 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td). 1516 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind, 1517 SelectionDAG &DAG) { 1518 bool IsLE = DAG.getDataLayout().isLittleEndian(); 1519 if (ShuffleKind == 0) { 1520 if (IsLE) 1521 return false; 1522 for (unsigned i = 0; i != 16; i += 2) 1523 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+2) || 1524 !isConstantOrUndef(N->getMaskElt(i+1), i*2+3)) 1525 return false; 1526 } else if (ShuffleKind == 2) { 1527 if (!IsLE) 1528 return false; 1529 for (unsigned i = 0; i != 16; i += 2) 1530 if (!isConstantOrUndef(N->getMaskElt(i ), i*2) || 1531 !isConstantOrUndef(N->getMaskElt(i+1), i*2+1)) 1532 return false; 1533 } else if (ShuffleKind == 1) { 1534 unsigned j = IsLE ? 0 : 2; 1535 for (unsigned i = 0; i != 8; i += 2) 1536 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+j) || 1537 !isConstantOrUndef(N->getMaskElt(i+1), i*2+j+1) || 1538 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j) || 1539 !isConstantOrUndef(N->getMaskElt(i+9), i*2+j+1)) 1540 return false; 1541 } 1542 return true; 1543 } 1544 1545 /// isVPKUDUMShuffleMask - Return true if this is the shuffle mask for a 1546 /// VPKUDUM instruction, AND the VPKUDUM instruction exists for the 1547 /// current subtarget. 1548 /// 1549 /// The ShuffleKind distinguishes between big-endian operations with 1550 /// two different inputs (0), either-endian operations with two identical 1551 /// inputs (1), and little-endian operations with two different inputs (2). 1552 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td). 1553 bool PPC::isVPKUDUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind, 1554 SelectionDAG &DAG) { 1555 const PPCSubtarget& Subtarget = 1556 static_cast<const PPCSubtarget&>(DAG.getSubtarget()); 1557 if (!Subtarget.hasP8Vector()) 1558 return false; 1559 1560 bool IsLE = DAG.getDataLayout().isLittleEndian(); 1561 if (ShuffleKind == 0) { 1562 if (IsLE) 1563 return false; 1564 for (unsigned i = 0; i != 16; i += 4) 1565 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+4) || 1566 !isConstantOrUndef(N->getMaskElt(i+1), i*2+5) || 1567 !isConstantOrUndef(N->getMaskElt(i+2), i*2+6) || 1568 !isConstantOrUndef(N->getMaskElt(i+3), i*2+7)) 1569 return false; 1570 } else if (ShuffleKind == 2) { 1571 if (!IsLE) 1572 return false; 1573 for (unsigned i = 0; i != 16; i += 4) 1574 if (!isConstantOrUndef(N->getMaskElt(i ), i*2) || 1575 !isConstantOrUndef(N->getMaskElt(i+1), i*2+1) || 1576 !isConstantOrUndef(N->getMaskElt(i+2), i*2+2) || 1577 !isConstantOrUndef(N->getMaskElt(i+3), i*2+3)) 1578 return false; 1579 } else if (ShuffleKind == 1) { 1580 unsigned j = IsLE ? 0 : 4; 1581 for (unsigned i = 0; i != 8; i += 4) 1582 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+j) || 1583 !isConstantOrUndef(N->getMaskElt(i+1), i*2+j+1) || 1584 !isConstantOrUndef(N->getMaskElt(i+2), i*2+j+2) || 1585 !isConstantOrUndef(N->getMaskElt(i+3), i*2+j+3) || 1586 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j) || 1587 !isConstantOrUndef(N->getMaskElt(i+9), i*2+j+1) || 1588 !isConstantOrUndef(N->getMaskElt(i+10), i*2+j+2) || 1589 !isConstantOrUndef(N->getMaskElt(i+11), i*2+j+3)) 1590 return false; 1591 } 1592 return true; 1593 } 1594 1595 /// isVMerge - Common function, used to match vmrg* shuffles. 1596 /// 1597 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize, 1598 unsigned LHSStart, unsigned RHSStart) { 1599 if (N->getValueType(0) != MVT::v16i8) 1600 return false; 1601 assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) && 1602 "Unsupported merge size!"); 1603 1604 for (unsigned i = 0; i != 8/UnitSize; ++i) // Step over units 1605 for (unsigned j = 0; j != UnitSize; ++j) { // Step over bytes within unit 1606 if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j), 1607 LHSStart+j+i*UnitSize) || 1608 !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j), 1609 RHSStart+j+i*UnitSize)) 1610 return false; 1611 } 1612 return true; 1613 } 1614 1615 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for 1616 /// a VMRGL* instruction with the specified unit size (1,2 or 4 bytes). 1617 /// The ShuffleKind distinguishes between big-endian merges with two 1618 /// different inputs (0), either-endian merges with two identical inputs (1), 1619 /// and little-endian merges with two different inputs (2). For the latter, 1620 /// the input operands are swapped (see PPCInstrAltivec.td). 1621 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize, 1622 unsigned ShuffleKind, SelectionDAG &DAG) { 1623 if (DAG.getDataLayout().isLittleEndian()) { 1624 if (ShuffleKind == 1) // unary 1625 return isVMerge(N, UnitSize, 0, 0); 1626 else if (ShuffleKind == 2) // swapped 1627 return isVMerge(N, UnitSize, 0, 16); 1628 else 1629 return false; 1630 } else { 1631 if (ShuffleKind == 1) // unary 1632 return isVMerge(N, UnitSize, 8, 8); 1633 else if (ShuffleKind == 0) // normal 1634 return isVMerge(N, UnitSize, 8, 24); 1635 else 1636 return false; 1637 } 1638 } 1639 1640 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for 1641 /// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes). 1642 /// The ShuffleKind distinguishes between big-endian merges with two 1643 /// different inputs (0), either-endian merges with two identical inputs (1), 1644 /// and little-endian merges with two different inputs (2). For the latter, 1645 /// the input operands are swapped (see PPCInstrAltivec.td). 1646 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize, 1647 unsigned ShuffleKind, SelectionDAG &DAG) { 1648 if (DAG.getDataLayout().isLittleEndian()) { 1649 if (ShuffleKind == 1) // unary 1650 return isVMerge(N, UnitSize, 8, 8); 1651 else if (ShuffleKind == 2) // swapped 1652 return isVMerge(N, UnitSize, 8, 24); 1653 else 1654 return false; 1655 } else { 1656 if (ShuffleKind == 1) // unary 1657 return isVMerge(N, UnitSize, 0, 0); 1658 else if (ShuffleKind == 0) // normal 1659 return isVMerge(N, UnitSize, 0, 16); 1660 else 1661 return false; 1662 } 1663 } 1664 1665 /** 1666 * Common function used to match vmrgew and vmrgow shuffles 1667 * 1668 * The indexOffset determines whether to look for even or odd words in 1669 * the shuffle mask. This is based on the of the endianness of the target 1670 * machine. 1671 * - Little Endian: 1672 * - Use offset of 0 to check for odd elements 1673 * - Use offset of 4 to check for even elements 1674 * - Big Endian: 1675 * - Use offset of 0 to check for even elements 1676 * - Use offset of 4 to check for odd elements 1677 * A detailed description of the vector element ordering for little endian and 1678 * big endian can be found at 1679 * http://www.ibm.com/developerworks/library/l-ibm-xl-c-cpp-compiler/index.html 1680 * Targeting your applications - what little endian and big endian IBM XL C/C++ 1681 * compiler differences mean to you 1682 * 1683 * The mask to the shuffle vector instruction specifies the indices of the 1684 * elements from the two input vectors to place in the result. The elements are 1685 * numbered in array-access order, starting with the first vector. These vectors 1686 * are always of type v16i8, thus each vector will contain 16 elements of size 1687 * 8. More info on the shuffle vector can be found in the 1688 * http://llvm.org/docs/LangRef.html#shufflevector-instruction 1689 * Language Reference. 1690 * 1691 * The RHSStartValue indicates whether the same input vectors are used (unary) 1692 * or two different input vectors are used, based on the following: 1693 * - If the instruction uses the same vector for both inputs, the range of the 1694 * indices will be 0 to 15. In this case, the RHSStart value passed should 1695 * be 0. 1696 * - If the instruction has two different vectors then the range of the 1697 * indices will be 0 to 31. In this case, the RHSStart value passed should 1698 * be 16 (indices 0-15 specify elements in the first vector while indices 16 1699 * to 31 specify elements in the second vector). 1700 * 1701 * \param[in] N The shuffle vector SD Node to analyze 1702 * \param[in] IndexOffset Specifies whether to look for even or odd elements 1703 * \param[in] RHSStartValue Specifies the starting index for the righthand input 1704 * vector to the shuffle_vector instruction 1705 * \return true iff this shuffle vector represents an even or odd word merge 1706 */ 1707 static bool isVMerge(ShuffleVectorSDNode *N, unsigned IndexOffset, 1708 unsigned RHSStartValue) { 1709 if (N->getValueType(0) != MVT::v16i8) 1710 return false; 1711 1712 for (unsigned i = 0; i < 2; ++i) 1713 for (unsigned j = 0; j < 4; ++j) 1714 if (!isConstantOrUndef(N->getMaskElt(i*4+j), 1715 i*RHSStartValue+j+IndexOffset) || 1716 !isConstantOrUndef(N->getMaskElt(i*4+j+8), 1717 i*RHSStartValue+j+IndexOffset+8)) 1718 return false; 1719 return true; 1720 } 1721 1722 /** 1723 * Determine if the specified shuffle mask is suitable for the vmrgew or 1724 * vmrgow instructions. 1725 * 1726 * \param[in] N The shuffle vector SD Node to analyze 1727 * \param[in] CheckEven Check for an even merge (true) or an odd merge (false) 1728 * \param[in] ShuffleKind Identify the type of merge: 1729 * - 0 = big-endian merge with two different inputs; 1730 * - 1 = either-endian merge with two identical inputs; 1731 * - 2 = little-endian merge with two different inputs (inputs are swapped for 1732 * little-endian merges). 1733 * \param[in] DAG The current SelectionDAG 1734 * \return true iff this shuffle mask 1735 */ 1736 bool PPC::isVMRGEOShuffleMask(ShuffleVectorSDNode *N, bool CheckEven, 1737 unsigned ShuffleKind, SelectionDAG &DAG) { 1738 if (DAG.getDataLayout().isLittleEndian()) { 1739 unsigned indexOffset = CheckEven ? 4 : 0; 1740 if (ShuffleKind == 1) // Unary 1741 return isVMerge(N, indexOffset, 0); 1742 else if (ShuffleKind == 2) // swapped 1743 return isVMerge(N, indexOffset, 16); 1744 else 1745 return false; 1746 } 1747 else { 1748 unsigned indexOffset = CheckEven ? 0 : 4; 1749 if (ShuffleKind == 1) // Unary 1750 return isVMerge(N, indexOffset, 0); 1751 else if (ShuffleKind == 0) // Normal 1752 return isVMerge(N, indexOffset, 16); 1753 else 1754 return false; 1755 } 1756 return false; 1757 } 1758 1759 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift 1760 /// amount, otherwise return -1. 1761 /// The ShuffleKind distinguishes between big-endian operations with two 1762 /// different inputs (0), either-endian operations with two identical inputs 1763 /// (1), and little-endian operations with two different inputs (2). For the 1764 /// latter, the input operands are swapped (see PPCInstrAltivec.td). 1765 int PPC::isVSLDOIShuffleMask(SDNode *N, unsigned ShuffleKind, 1766 SelectionDAG &DAG) { 1767 if (N->getValueType(0) != MVT::v16i8) 1768 return -1; 1769 1770 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 1771 1772 // Find the first non-undef value in the shuffle mask. 1773 unsigned i; 1774 for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i) 1775 /*search*/; 1776 1777 if (i == 16) return -1; // all undef. 1778 1779 // Otherwise, check to see if the rest of the elements are consecutively 1780 // numbered from this value. 1781 unsigned ShiftAmt = SVOp->getMaskElt(i); 1782 if (ShiftAmt < i) return -1; 1783 1784 ShiftAmt -= i; 1785 bool isLE = DAG.getDataLayout().isLittleEndian(); 1786 1787 if ((ShuffleKind == 0 && !isLE) || (ShuffleKind == 2 && isLE)) { 1788 // Check the rest of the elements to see if they are consecutive. 1789 for (++i; i != 16; ++i) 1790 if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i)) 1791 return -1; 1792 } else if (ShuffleKind == 1) { 1793 // Check the rest of the elements to see if they are consecutive. 1794 for (++i; i != 16; ++i) 1795 if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15)) 1796 return -1; 1797 } else 1798 return -1; 1799 1800 if (isLE) 1801 ShiftAmt = 16 - ShiftAmt; 1802 1803 return ShiftAmt; 1804 } 1805 1806 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand 1807 /// specifies a splat of a single element that is suitable for input to 1808 /// one of the splat operations (VSPLTB/VSPLTH/VSPLTW/XXSPLTW/LXVDSX/etc.). 1809 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) { 1810 assert(N->getValueType(0) == MVT::v16i8 && isPowerOf2_32(EltSize) && 1811 EltSize <= 8 && "Can only handle 1,2,4,8 byte element sizes"); 1812 1813 // The consecutive indices need to specify an element, not part of two 1814 // different elements. So abandon ship early if this isn't the case. 1815 if (N->getMaskElt(0) % EltSize != 0) 1816 return false; 1817 1818 // This is a splat operation if each element of the permute is the same, and 1819 // if the value doesn't reference the second vector. 1820 unsigned ElementBase = N->getMaskElt(0); 1821 1822 // FIXME: Handle UNDEF elements too! 1823 if (ElementBase >= 16) 1824 return false; 1825 1826 // Check that the indices are consecutive, in the case of a multi-byte element 1827 // splatted with a v16i8 mask. 1828 for (unsigned i = 1; i != EltSize; ++i) 1829 if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase)) 1830 return false; 1831 1832 for (unsigned i = EltSize, e = 16; i != e; i += EltSize) { 1833 if (N->getMaskElt(i) < 0) continue; 1834 for (unsigned j = 0; j != EltSize; ++j) 1835 if (N->getMaskElt(i+j) != N->getMaskElt(j)) 1836 return false; 1837 } 1838 return true; 1839 } 1840 1841 /// Check that the mask is shuffling N byte elements. Within each N byte 1842 /// element of the mask, the indices could be either in increasing or 1843 /// decreasing order as long as they are consecutive. 1844 /// \param[in] N the shuffle vector SD Node to analyze 1845 /// \param[in] Width the element width in bytes, could be 2/4/8/16 (HalfWord/ 1846 /// Word/DoubleWord/QuadWord). 1847 /// \param[in] StepLen the delta indices number among the N byte element, if 1848 /// the mask is in increasing/decreasing order then it is 1/-1. 1849 /// \return true iff the mask is shuffling N byte elements. 1850 static bool isNByteElemShuffleMask(ShuffleVectorSDNode *N, unsigned Width, 1851 int StepLen) { 1852 assert((Width == 2 || Width == 4 || Width == 8 || Width == 16) && 1853 "Unexpected element width."); 1854 assert((StepLen == 1 || StepLen == -1) && "Unexpected element width."); 1855 1856 unsigned NumOfElem = 16 / Width; 1857 unsigned MaskVal[16]; // Width is never greater than 16 1858 for (unsigned i = 0; i < NumOfElem; ++i) { 1859 MaskVal[0] = N->getMaskElt(i * Width); 1860 if ((StepLen == 1) && (MaskVal[0] % Width)) { 1861 return false; 1862 } else if ((StepLen == -1) && ((MaskVal[0] + 1) % Width)) { 1863 return false; 1864 } 1865 1866 for (unsigned int j = 1; j < Width; ++j) { 1867 MaskVal[j] = N->getMaskElt(i * Width + j); 1868 if (MaskVal[j] != MaskVal[j-1] + StepLen) { 1869 return false; 1870 } 1871 } 1872 } 1873 1874 return true; 1875 } 1876 1877 bool PPC::isXXINSERTWMask(ShuffleVectorSDNode *N, unsigned &ShiftElts, 1878 unsigned &InsertAtByte, bool &Swap, bool IsLE) { 1879 if (!isNByteElemShuffleMask(N, 4, 1)) 1880 return false; 1881 1882 // Now we look at mask elements 0,4,8,12 1883 unsigned M0 = N->getMaskElt(0) / 4; 1884 unsigned M1 = N->getMaskElt(4) / 4; 1885 unsigned M2 = N->getMaskElt(8) / 4; 1886 unsigned M3 = N->getMaskElt(12) / 4; 1887 unsigned LittleEndianShifts[] = { 2, 1, 0, 3 }; 1888 unsigned BigEndianShifts[] = { 3, 0, 1, 2 }; 1889 1890 // Below, let H and L be arbitrary elements of the shuffle mask 1891 // where H is in the range [4,7] and L is in the range [0,3]. 1892 // H, 1, 2, 3 or L, 5, 6, 7 1893 if ((M0 > 3 && M1 == 1 && M2 == 2 && M3 == 3) || 1894 (M0 < 4 && M1 == 5 && M2 == 6 && M3 == 7)) { 1895 ShiftElts = IsLE ? LittleEndianShifts[M0 & 0x3] : BigEndianShifts[M0 & 0x3]; 1896 InsertAtByte = IsLE ? 12 : 0; 1897 Swap = M0 < 4; 1898 return true; 1899 } 1900 // 0, H, 2, 3 or 4, L, 6, 7 1901 if ((M1 > 3 && M0 == 0 && M2 == 2 && M3 == 3) || 1902 (M1 < 4 && M0 == 4 && M2 == 6 && M3 == 7)) { 1903 ShiftElts = IsLE ? LittleEndianShifts[M1 & 0x3] : BigEndianShifts[M1 & 0x3]; 1904 InsertAtByte = IsLE ? 8 : 4; 1905 Swap = M1 < 4; 1906 return true; 1907 } 1908 // 0, 1, H, 3 or 4, 5, L, 7 1909 if ((M2 > 3 && M0 == 0 && M1 == 1 && M3 == 3) || 1910 (M2 < 4 && M0 == 4 && M1 == 5 && M3 == 7)) { 1911 ShiftElts = IsLE ? LittleEndianShifts[M2 & 0x3] : BigEndianShifts[M2 & 0x3]; 1912 InsertAtByte = IsLE ? 4 : 8; 1913 Swap = M2 < 4; 1914 return true; 1915 } 1916 // 0, 1, 2, H or 4, 5, 6, L 1917 if ((M3 > 3 && M0 == 0 && M1 == 1 && M2 == 2) || 1918 (M3 < 4 && M0 == 4 && M1 == 5 && M2 == 6)) { 1919 ShiftElts = IsLE ? LittleEndianShifts[M3 & 0x3] : BigEndianShifts[M3 & 0x3]; 1920 InsertAtByte = IsLE ? 0 : 12; 1921 Swap = M3 < 4; 1922 return true; 1923 } 1924 1925 // If both vector operands for the shuffle are the same vector, the mask will 1926 // contain only elements from the first one and the second one will be undef. 1927 if (N->getOperand(1).isUndef()) { 1928 ShiftElts = 0; 1929 Swap = true; 1930 unsigned XXINSERTWSrcElem = IsLE ? 2 : 1; 1931 if (M0 == XXINSERTWSrcElem && M1 == 1 && M2 == 2 && M3 == 3) { 1932 InsertAtByte = IsLE ? 12 : 0; 1933 return true; 1934 } 1935 if (M0 == 0 && M1 == XXINSERTWSrcElem && M2 == 2 && M3 == 3) { 1936 InsertAtByte = IsLE ? 8 : 4; 1937 return true; 1938 } 1939 if (M0 == 0 && M1 == 1 && M2 == XXINSERTWSrcElem && M3 == 3) { 1940 InsertAtByte = IsLE ? 4 : 8; 1941 return true; 1942 } 1943 if (M0 == 0 && M1 == 1 && M2 == 2 && M3 == XXINSERTWSrcElem) { 1944 InsertAtByte = IsLE ? 0 : 12; 1945 return true; 1946 } 1947 } 1948 1949 return false; 1950 } 1951 1952 bool PPC::isXXSLDWIShuffleMask(ShuffleVectorSDNode *N, unsigned &ShiftElts, 1953 bool &Swap, bool IsLE) { 1954 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8"); 1955 // Ensure each byte index of the word is consecutive. 1956 if (!isNByteElemShuffleMask(N, 4, 1)) 1957 return false; 1958 1959 // Now we look at mask elements 0,4,8,12, which are the beginning of words. 1960 unsigned M0 = N->getMaskElt(0) / 4; 1961 unsigned M1 = N->getMaskElt(4) / 4; 1962 unsigned M2 = N->getMaskElt(8) / 4; 1963 unsigned M3 = N->getMaskElt(12) / 4; 1964 1965 // If both vector operands for the shuffle are the same vector, the mask will 1966 // contain only elements from the first one and the second one will be undef. 1967 if (N->getOperand(1).isUndef()) { 1968 assert(M0 < 4 && "Indexing into an undef vector?"); 1969 if (M1 != (M0 + 1) % 4 || M2 != (M1 + 1) % 4 || M3 != (M2 + 1) % 4) 1970 return false; 1971 1972 ShiftElts = IsLE ? (4 - M0) % 4 : M0; 1973 Swap = false; 1974 return true; 1975 } 1976 1977 // Ensure each word index of the ShuffleVector Mask is consecutive. 1978 if (M1 != (M0 + 1) % 8 || M2 != (M1 + 1) % 8 || M3 != (M2 + 1) % 8) 1979 return false; 1980 1981 if (IsLE) { 1982 if (M0 == 0 || M0 == 7 || M0 == 6 || M0 == 5) { 1983 // Input vectors don't need to be swapped if the leading element 1984 // of the result is one of the 3 left elements of the second vector 1985 // (or if there is no shift to be done at all). 1986 Swap = false; 1987 ShiftElts = (8 - M0) % 8; 1988 } else if (M0 == 4 || M0 == 3 || M0 == 2 || M0 == 1) { 1989 // Input vectors need to be swapped if the leading element 1990 // of the result is one of the 3 left elements of the first vector 1991 // (or if we're shifting by 4 - thereby simply swapping the vectors). 1992 Swap = true; 1993 ShiftElts = (4 - M0) % 4; 1994 } 1995 1996 return true; 1997 } else { // BE 1998 if (M0 == 0 || M0 == 1 || M0 == 2 || M0 == 3) { 1999 // Input vectors don't need to be swapped if the leading element 2000 // of the result is one of the 4 elements of the first vector. 2001 Swap = false; 2002 ShiftElts = M0; 2003 } else if (M0 == 4 || M0 == 5 || M0 == 6 || M0 == 7) { 2004 // Input vectors need to be swapped if the leading element 2005 // of the result is one of the 4 elements of the right vector. 2006 Swap = true; 2007 ShiftElts = M0 - 4; 2008 } 2009 2010 return true; 2011 } 2012 } 2013 2014 bool static isXXBRShuffleMaskHelper(ShuffleVectorSDNode *N, int Width) { 2015 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8"); 2016 2017 if (!isNByteElemShuffleMask(N, Width, -1)) 2018 return false; 2019 2020 for (int i = 0; i < 16; i += Width) 2021 if (N->getMaskElt(i) != i + Width - 1) 2022 return false; 2023 2024 return true; 2025 } 2026 2027 bool PPC::isXXBRHShuffleMask(ShuffleVectorSDNode *N) { 2028 return isXXBRShuffleMaskHelper(N, 2); 2029 } 2030 2031 bool PPC::isXXBRWShuffleMask(ShuffleVectorSDNode *N) { 2032 return isXXBRShuffleMaskHelper(N, 4); 2033 } 2034 2035 bool PPC::isXXBRDShuffleMask(ShuffleVectorSDNode *N) { 2036 return isXXBRShuffleMaskHelper(N, 8); 2037 } 2038 2039 bool PPC::isXXBRQShuffleMask(ShuffleVectorSDNode *N) { 2040 return isXXBRShuffleMaskHelper(N, 16); 2041 } 2042 2043 /// Can node \p N be lowered to an XXPERMDI instruction? If so, set \p Swap 2044 /// if the inputs to the instruction should be swapped and set \p DM to the 2045 /// value for the immediate. 2046 /// Specifically, set \p Swap to true only if \p N can be lowered to XXPERMDI 2047 /// AND element 0 of the result comes from the first input (LE) or second input 2048 /// (BE). Set \p DM to the calculated result (0-3) only if \p N can be lowered. 2049 /// \return true iff the given mask of shuffle node \p N is a XXPERMDI shuffle 2050 /// mask. 2051 bool PPC::isXXPERMDIShuffleMask(ShuffleVectorSDNode *N, unsigned &DM, 2052 bool &Swap, bool IsLE) { 2053 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8"); 2054 2055 // Ensure each byte index of the double word is consecutive. 2056 if (!isNByteElemShuffleMask(N, 8, 1)) 2057 return false; 2058 2059 unsigned M0 = N->getMaskElt(0) / 8; 2060 unsigned M1 = N->getMaskElt(8) / 8; 2061 assert(((M0 | M1) < 4) && "A mask element out of bounds?"); 2062 2063 // If both vector operands for the shuffle are the same vector, the mask will 2064 // contain only elements from the first one and the second one will be undef. 2065 if (N->getOperand(1).isUndef()) { 2066 if ((M0 | M1) < 2) { 2067 DM = IsLE ? (((~M1) & 1) << 1) + ((~M0) & 1) : (M0 << 1) + (M1 & 1); 2068 Swap = false; 2069 return true; 2070 } else 2071 return false; 2072 } 2073 2074 if (IsLE) { 2075 if (M0 > 1 && M1 < 2) { 2076 Swap = false; 2077 } else if (M0 < 2 && M1 > 1) { 2078 M0 = (M0 + 2) % 4; 2079 M1 = (M1 + 2) % 4; 2080 Swap = true; 2081 } else 2082 return false; 2083 2084 // Note: if control flow comes here that means Swap is already set above 2085 DM = (((~M1) & 1) << 1) + ((~M0) & 1); 2086 return true; 2087 } else { // BE 2088 if (M0 < 2 && M1 > 1) { 2089 Swap = false; 2090 } else if (M0 > 1 && M1 < 2) { 2091 M0 = (M0 + 2) % 4; 2092 M1 = (M1 + 2) % 4; 2093 Swap = true; 2094 } else 2095 return false; 2096 2097 // Note: if control flow comes here that means Swap is already set above 2098 DM = (M0 << 1) + (M1 & 1); 2099 return true; 2100 } 2101 } 2102 2103 2104 /// getSplatIdxForPPCMnemonics - Return the splat index as a value that is 2105 /// appropriate for PPC mnemonics (which have a big endian bias - namely 2106 /// elements are counted from the left of the vector register). 2107 unsigned PPC::getSplatIdxForPPCMnemonics(SDNode *N, unsigned EltSize, 2108 SelectionDAG &DAG) { 2109 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 2110 assert(isSplatShuffleMask(SVOp, EltSize)); 2111 if (DAG.getDataLayout().isLittleEndian()) 2112 return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize); 2113 else 2114 return SVOp->getMaskElt(0) / EltSize; 2115 } 2116 2117 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed 2118 /// by using a vspltis[bhw] instruction of the specified element size, return 2119 /// the constant being splatted. The ByteSize field indicates the number of 2120 /// bytes of each element [124] -> [bhw]. 2121 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) { 2122 SDValue OpVal(nullptr, 0); 2123 2124 // If ByteSize of the splat is bigger than the element size of the 2125 // build_vector, then we have a case where we are checking for a splat where 2126 // multiple elements of the buildvector are folded together into a single 2127 // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8). 2128 unsigned EltSize = 16/N->getNumOperands(); 2129 if (EltSize < ByteSize) { 2130 unsigned Multiple = ByteSize/EltSize; // Number of BV entries per spltval. 2131 SDValue UniquedVals[4]; 2132 assert(Multiple > 1 && Multiple <= 4 && "How can this happen?"); 2133 2134 // See if all of the elements in the buildvector agree across. 2135 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 2136 if (N->getOperand(i).isUndef()) continue; 2137 // If the element isn't a constant, bail fully out. 2138 if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue(); 2139 2140 if (!UniquedVals[i&(Multiple-1)].getNode()) 2141 UniquedVals[i&(Multiple-1)] = N->getOperand(i); 2142 else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i)) 2143 return SDValue(); // no match. 2144 } 2145 2146 // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains 2147 // either constant or undef values that are identical for each chunk. See 2148 // if these chunks can form into a larger vspltis*. 2149 2150 // Check to see if all of the leading entries are either 0 or -1. If 2151 // neither, then this won't fit into the immediate field. 2152 bool LeadingZero = true; 2153 bool LeadingOnes = true; 2154 for (unsigned i = 0; i != Multiple-1; ++i) { 2155 if (!UniquedVals[i].getNode()) continue; // Must have been undefs. 2156 2157 LeadingZero &= isNullConstant(UniquedVals[i]); 2158 LeadingOnes &= isAllOnesConstant(UniquedVals[i]); 2159 } 2160 // Finally, check the least significant entry. 2161 if (LeadingZero) { 2162 if (!UniquedVals[Multiple-1].getNode()) 2163 return DAG.getTargetConstant(0, SDLoc(N), MVT::i32); // 0,0,0,undef 2164 int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue(); 2165 if (Val < 16) // 0,0,0,4 -> vspltisw(4) 2166 return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32); 2167 } 2168 if (LeadingOnes) { 2169 if (!UniquedVals[Multiple-1].getNode()) 2170 return DAG.getTargetConstant(~0U, SDLoc(N), MVT::i32); // -1,-1,-1,undef 2171 int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue(); 2172 if (Val >= -16) // -1,-1,-1,-2 -> vspltisw(-2) 2173 return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32); 2174 } 2175 2176 return SDValue(); 2177 } 2178 2179 // Check to see if this buildvec has a single non-undef value in its elements. 2180 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 2181 if (N->getOperand(i).isUndef()) continue; 2182 if (!OpVal.getNode()) 2183 OpVal = N->getOperand(i); 2184 else if (OpVal != N->getOperand(i)) 2185 return SDValue(); 2186 } 2187 2188 if (!OpVal.getNode()) return SDValue(); // All UNDEF: use implicit def. 2189 2190 unsigned ValSizeInBytes = EltSize; 2191 uint64_t Value = 0; 2192 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) { 2193 Value = CN->getZExtValue(); 2194 } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) { 2195 assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!"); 2196 Value = FloatToBits(CN->getValueAPF().convertToFloat()); 2197 } 2198 2199 // If the splat value is larger than the element value, then we can never do 2200 // this splat. The only case that we could fit the replicated bits into our 2201 // immediate field for would be zero, and we prefer to use vxor for it. 2202 if (ValSizeInBytes < ByteSize) return SDValue(); 2203 2204 // If the element value is larger than the splat value, check if it consists 2205 // of a repeated bit pattern of size ByteSize. 2206 if (!APInt(ValSizeInBytes * 8, Value).isSplat(ByteSize * 8)) 2207 return SDValue(); 2208 2209 // Properly sign extend the value. 2210 int MaskVal = SignExtend32(Value, ByteSize * 8); 2211 2212 // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros. 2213 if (MaskVal == 0) return SDValue(); 2214 2215 // Finally, if this value fits in a 5 bit sext field, return it 2216 if (SignExtend32<5>(MaskVal) == MaskVal) 2217 return DAG.getTargetConstant(MaskVal, SDLoc(N), MVT::i32); 2218 return SDValue(); 2219 } 2220 2221 /// isQVALIGNIShuffleMask - If this is a qvaligni shuffle mask, return the shift 2222 /// amount, otherwise return -1. 2223 int PPC::isQVALIGNIShuffleMask(SDNode *N) { 2224 EVT VT = N->getValueType(0); 2225 if (VT != MVT::v4f64 && VT != MVT::v4f32 && VT != MVT::v4i1) 2226 return -1; 2227 2228 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 2229 2230 // Find the first non-undef value in the shuffle mask. 2231 unsigned i; 2232 for (i = 0; i != 4 && SVOp->getMaskElt(i) < 0; ++i) 2233 /*search*/; 2234 2235 if (i == 4) return -1; // all undef. 2236 2237 // Otherwise, check to see if the rest of the elements are consecutively 2238 // numbered from this value. 2239 unsigned ShiftAmt = SVOp->getMaskElt(i); 2240 if (ShiftAmt < i) return -1; 2241 ShiftAmt -= i; 2242 2243 // Check the rest of the elements to see if they are consecutive. 2244 for (++i; i != 4; ++i) 2245 if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i)) 2246 return -1; 2247 2248 return ShiftAmt; 2249 } 2250 2251 //===----------------------------------------------------------------------===// 2252 // Addressing Mode Selection 2253 //===----------------------------------------------------------------------===// 2254 2255 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit 2256 /// or 64-bit immediate, and if the value can be accurately represented as a 2257 /// sign extension from a 16-bit value. If so, this returns true and the 2258 /// immediate. 2259 bool llvm::isIntS16Immediate(SDNode *N, int16_t &Imm) { 2260 if (!isa<ConstantSDNode>(N)) 2261 return false; 2262 2263 Imm = (int16_t)cast<ConstantSDNode>(N)->getZExtValue(); 2264 if (N->getValueType(0) == MVT::i32) 2265 return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue(); 2266 else 2267 return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue(); 2268 } 2269 bool llvm::isIntS16Immediate(SDValue Op, int16_t &Imm) { 2270 return isIntS16Immediate(Op.getNode(), Imm); 2271 } 2272 2273 2274 /// SelectAddressEVXRegReg - Given the specified address, check to see if it can 2275 /// be represented as an indexed [r+r] operation. 2276 bool PPCTargetLowering::SelectAddressEVXRegReg(SDValue N, SDValue &Base, 2277 SDValue &Index, 2278 SelectionDAG &DAG) const { 2279 for (SDNode::use_iterator UI = N->use_begin(), E = N->use_end(); 2280 UI != E; ++UI) { 2281 if (MemSDNode *Memop = dyn_cast<MemSDNode>(*UI)) { 2282 if (Memop->getMemoryVT() == MVT::f64) { 2283 Base = N.getOperand(0); 2284 Index = N.getOperand(1); 2285 return true; 2286 } 2287 } 2288 } 2289 return false; 2290 } 2291 2292 /// SelectAddressRegReg - Given the specified addressed, check to see if it 2293 /// can be represented as an indexed [r+r] operation. Returns false if it 2294 /// can be more efficiently represented as [r+imm]. If \p EncodingAlignment is 2295 /// non-zero and N can be represented by a base register plus a signed 16-bit 2296 /// displacement, make a more precise judgement by checking (displacement % \p 2297 /// EncodingAlignment). 2298 bool PPCTargetLowering::SelectAddressRegReg(SDValue N, SDValue &Base, 2299 SDValue &Index, SelectionDAG &DAG, 2300 unsigned EncodingAlignment) const { 2301 int16_t imm = 0; 2302 if (N.getOpcode() == ISD::ADD) { 2303 // Is there any SPE load/store (f64), which can't handle 16bit offset? 2304 // SPE load/store can only handle 8-bit offsets. 2305 if (hasSPE() && SelectAddressEVXRegReg(N, Base, Index, DAG)) 2306 return true; 2307 if (isIntS16Immediate(N.getOperand(1), imm) && 2308 (!EncodingAlignment || !(imm % EncodingAlignment))) 2309 return false; // r+i 2310 if (N.getOperand(1).getOpcode() == PPCISD::Lo) 2311 return false; // r+i 2312 2313 Base = N.getOperand(0); 2314 Index = N.getOperand(1); 2315 return true; 2316 } else if (N.getOpcode() == ISD::OR) { 2317 if (isIntS16Immediate(N.getOperand(1), imm) && 2318 (!EncodingAlignment || !(imm % EncodingAlignment))) 2319 return false; // r+i can fold it if we can. 2320 2321 // If this is an or of disjoint bitfields, we can codegen this as an add 2322 // (for better address arithmetic) if the LHS and RHS of the OR are provably 2323 // disjoint. 2324 KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0)); 2325 2326 if (LHSKnown.Zero.getBoolValue()) { 2327 KnownBits RHSKnown = DAG.computeKnownBits(N.getOperand(1)); 2328 // If all of the bits are known zero on the LHS or RHS, the add won't 2329 // carry. 2330 if (~(LHSKnown.Zero | RHSKnown.Zero) == 0) { 2331 Base = N.getOperand(0); 2332 Index = N.getOperand(1); 2333 return true; 2334 } 2335 } 2336 } 2337 2338 return false; 2339 } 2340 2341 // If we happen to be doing an i64 load or store into a stack slot that has 2342 // less than a 4-byte alignment, then the frame-index elimination may need to 2343 // use an indexed load or store instruction (because the offset may not be a 2344 // multiple of 4). The extra register needed to hold the offset comes from the 2345 // register scavenger, and it is possible that the scavenger will need to use 2346 // an emergency spill slot. As a result, we need to make sure that a spill slot 2347 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned 2348 // stack slot. 2349 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) { 2350 // FIXME: This does not handle the LWA case. 2351 if (VT != MVT::i64) 2352 return; 2353 2354 // NOTE: We'll exclude negative FIs here, which come from argument 2355 // lowering, because there are no known test cases triggering this problem 2356 // using packed structures (or similar). We can remove this exclusion if 2357 // we find such a test case. The reason why this is so test-case driven is 2358 // because this entire 'fixup' is only to prevent crashes (from the 2359 // register scavenger) on not-really-valid inputs. For example, if we have: 2360 // %a = alloca i1 2361 // %b = bitcast i1* %a to i64* 2362 // store i64* a, i64 b 2363 // then the store should really be marked as 'align 1', but is not. If it 2364 // were marked as 'align 1' then the indexed form would have been 2365 // instruction-selected initially, and the problem this 'fixup' is preventing 2366 // won't happen regardless. 2367 if (FrameIdx < 0) 2368 return; 2369 2370 MachineFunction &MF = DAG.getMachineFunction(); 2371 MachineFrameInfo &MFI = MF.getFrameInfo(); 2372 2373 unsigned Align = MFI.getObjectAlignment(FrameIdx); 2374 if (Align >= 4) 2375 return; 2376 2377 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 2378 FuncInfo->setHasNonRISpills(); 2379 } 2380 2381 /// Returns true if the address N can be represented by a base register plus 2382 /// a signed 16-bit displacement [r+imm], and if it is not better 2383 /// represented as reg+reg. If \p EncodingAlignment is non-zero, only accept 2384 /// displacements that are multiples of that value. 2385 bool PPCTargetLowering::SelectAddressRegImm(SDValue N, SDValue &Disp, 2386 SDValue &Base, 2387 SelectionDAG &DAG, 2388 unsigned EncodingAlignment) const { 2389 // FIXME dl should come from parent load or store, not from address 2390 SDLoc dl(N); 2391 // If this can be more profitably realized as r+r, fail. 2392 if (SelectAddressRegReg(N, Disp, Base, DAG, EncodingAlignment)) 2393 return false; 2394 2395 if (N.getOpcode() == ISD::ADD) { 2396 int16_t imm = 0; 2397 if (isIntS16Immediate(N.getOperand(1), imm) && 2398 (!EncodingAlignment || (imm % EncodingAlignment) == 0)) { 2399 Disp = DAG.getTargetConstant(imm, dl, N.getValueType()); 2400 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) { 2401 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2402 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 2403 } else { 2404 Base = N.getOperand(0); 2405 } 2406 return true; // [r+i] 2407 } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) { 2408 // Match LOAD (ADD (X, Lo(G))). 2409 assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue() 2410 && "Cannot handle constant offsets yet!"); 2411 Disp = N.getOperand(1).getOperand(0); // The global address. 2412 assert(Disp.getOpcode() == ISD::TargetGlobalAddress || 2413 Disp.getOpcode() == ISD::TargetGlobalTLSAddress || 2414 Disp.getOpcode() == ISD::TargetConstantPool || 2415 Disp.getOpcode() == ISD::TargetJumpTable); 2416 Base = N.getOperand(0); 2417 return true; // [&g+r] 2418 } 2419 } else if (N.getOpcode() == ISD::OR) { 2420 int16_t imm = 0; 2421 if (isIntS16Immediate(N.getOperand(1), imm) && 2422 (!EncodingAlignment || (imm % EncodingAlignment) == 0)) { 2423 // If this is an or of disjoint bitfields, we can codegen this as an add 2424 // (for better address arithmetic) if the LHS and RHS of the OR are 2425 // provably disjoint. 2426 KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0)); 2427 2428 if ((LHSKnown.Zero.getZExtValue()|~(uint64_t)imm) == ~0ULL) { 2429 // If all of the bits are known zero on the LHS or RHS, the add won't 2430 // carry. 2431 if (FrameIndexSDNode *FI = 2432 dyn_cast<FrameIndexSDNode>(N.getOperand(0))) { 2433 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2434 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 2435 } else { 2436 Base = N.getOperand(0); 2437 } 2438 Disp = DAG.getTargetConstant(imm, dl, N.getValueType()); 2439 return true; 2440 } 2441 } 2442 } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) { 2443 // Loading from a constant address. 2444 2445 // If this address fits entirely in a 16-bit sext immediate field, codegen 2446 // this as "d, 0" 2447 int16_t Imm; 2448 if (isIntS16Immediate(CN, Imm) && 2449 (!EncodingAlignment || (Imm % EncodingAlignment) == 0)) { 2450 Disp = DAG.getTargetConstant(Imm, dl, CN->getValueType(0)); 2451 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO, 2452 CN->getValueType(0)); 2453 return true; 2454 } 2455 2456 // Handle 32-bit sext immediates with LIS + addr mode. 2457 if ((CN->getValueType(0) == MVT::i32 || 2458 (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) && 2459 (!EncodingAlignment || (CN->getZExtValue() % EncodingAlignment) == 0)) { 2460 int Addr = (int)CN->getZExtValue(); 2461 2462 // Otherwise, break this down into an LIS + disp. 2463 Disp = DAG.getTargetConstant((short)Addr, dl, MVT::i32); 2464 2465 Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, dl, 2466 MVT::i32); 2467 unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8; 2468 Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0); 2469 return true; 2470 } 2471 } 2472 2473 Disp = DAG.getTargetConstant(0, dl, getPointerTy(DAG.getDataLayout())); 2474 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) { 2475 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2476 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 2477 } else 2478 Base = N; 2479 return true; // [r+0] 2480 } 2481 2482 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be 2483 /// represented as an indexed [r+r] operation. 2484 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base, 2485 SDValue &Index, 2486 SelectionDAG &DAG) const { 2487 // Check to see if we can easily represent this as an [r+r] address. This 2488 // will fail if it thinks that the address is more profitably represented as 2489 // reg+imm, e.g. where imm = 0. 2490 if (SelectAddressRegReg(N, Base, Index, DAG)) 2491 return true; 2492 2493 // If the address is the result of an add, we will utilize the fact that the 2494 // address calculation includes an implicit add. However, we can reduce 2495 // register pressure if we do not materialize a constant just for use as the 2496 // index register. We only get rid of the add if it is not an add of a 2497 // value and a 16-bit signed constant and both have a single use. 2498 int16_t imm = 0; 2499 if (N.getOpcode() == ISD::ADD && 2500 (!isIntS16Immediate(N.getOperand(1), imm) || 2501 !N.getOperand(1).hasOneUse() || !N.getOperand(0).hasOneUse())) { 2502 Base = N.getOperand(0); 2503 Index = N.getOperand(1); 2504 return true; 2505 } 2506 2507 // Otherwise, do it the hard way, using R0 as the base register. 2508 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO, 2509 N.getValueType()); 2510 Index = N; 2511 return true; 2512 } 2513 2514 /// Returns true if we should use a direct load into vector instruction 2515 /// (such as lxsd or lfd), instead of a load into gpr + direct move sequence. 2516 static bool usePartialVectorLoads(SDNode *N, const PPCSubtarget& ST) { 2517 2518 // If there are any other uses other than scalar to vector, then we should 2519 // keep it as a scalar load -> direct move pattern to prevent multiple 2520 // loads. 2521 LoadSDNode *LD = dyn_cast<LoadSDNode>(N); 2522 if (!LD) 2523 return false; 2524 2525 EVT MemVT = LD->getMemoryVT(); 2526 if (!MemVT.isSimple()) 2527 return false; 2528 switch(MemVT.getSimpleVT().SimpleTy) { 2529 case MVT::i64: 2530 break; 2531 case MVT::i32: 2532 if (!ST.hasP8Vector()) 2533 return false; 2534 break; 2535 case MVT::i16: 2536 case MVT::i8: 2537 if (!ST.hasP9Vector()) 2538 return false; 2539 break; 2540 default: 2541 return false; 2542 } 2543 2544 SDValue LoadedVal(N, 0); 2545 if (!LoadedVal.hasOneUse()) 2546 return false; 2547 2548 for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end(); 2549 UI != UE; ++UI) 2550 if (UI.getUse().get().getResNo() == 0 && 2551 UI->getOpcode() != ISD::SCALAR_TO_VECTOR) 2552 return false; 2553 2554 return true; 2555 } 2556 2557 /// getPreIndexedAddressParts - returns true by value, base pointer and 2558 /// offset pointer and addressing mode by reference if the node's address 2559 /// can be legally represented as pre-indexed load / store address. 2560 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base, 2561 SDValue &Offset, 2562 ISD::MemIndexedMode &AM, 2563 SelectionDAG &DAG) const { 2564 if (DisablePPCPreinc) return false; 2565 2566 bool isLoad = true; 2567 SDValue Ptr; 2568 EVT VT; 2569 unsigned Alignment; 2570 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 2571 Ptr = LD->getBasePtr(); 2572 VT = LD->getMemoryVT(); 2573 Alignment = LD->getAlignment(); 2574 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 2575 Ptr = ST->getBasePtr(); 2576 VT = ST->getMemoryVT(); 2577 Alignment = ST->getAlignment(); 2578 isLoad = false; 2579 } else 2580 return false; 2581 2582 // Do not generate pre-inc forms for specific loads that feed scalar_to_vector 2583 // instructions because we can fold these into a more efficient instruction 2584 // instead, (such as LXSD). 2585 if (isLoad && usePartialVectorLoads(N, Subtarget)) { 2586 return false; 2587 } 2588 2589 // PowerPC doesn't have preinc load/store instructions for vectors (except 2590 // for QPX, which does have preinc r+r forms). 2591 if (VT.isVector()) { 2592 if (!Subtarget.hasQPX() || (VT != MVT::v4f64 && VT != MVT::v4f32)) { 2593 return false; 2594 } else if (SelectAddressRegRegOnly(Ptr, Offset, Base, DAG)) { 2595 AM = ISD::PRE_INC; 2596 return true; 2597 } 2598 } 2599 2600 if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) { 2601 // Common code will reject creating a pre-inc form if the base pointer 2602 // is a frame index, or if N is a store and the base pointer is either 2603 // the same as or a predecessor of the value being stored. Check for 2604 // those situations here, and try with swapped Base/Offset instead. 2605 bool Swap = false; 2606 2607 if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base)) 2608 Swap = true; 2609 else if (!isLoad) { 2610 SDValue Val = cast<StoreSDNode>(N)->getValue(); 2611 if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode())) 2612 Swap = true; 2613 } 2614 2615 if (Swap) 2616 std::swap(Base, Offset); 2617 2618 AM = ISD::PRE_INC; 2619 return true; 2620 } 2621 2622 // LDU/STU can only handle immediates that are a multiple of 4. 2623 if (VT != MVT::i64) { 2624 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, 0)) 2625 return false; 2626 } else { 2627 // LDU/STU need an address with at least 4-byte alignment. 2628 if (Alignment < 4) 2629 return false; 2630 2631 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, 4)) 2632 return false; 2633 } 2634 2635 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 2636 // PPC64 doesn't have lwau, but it does have lwaux. Reject preinc load of 2637 // sext i32 to i64 when addr mode is r+i. 2638 if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 && 2639 LD->getExtensionType() == ISD::SEXTLOAD && 2640 isa<ConstantSDNode>(Offset)) 2641 return false; 2642 } 2643 2644 AM = ISD::PRE_INC; 2645 return true; 2646 } 2647 2648 //===----------------------------------------------------------------------===// 2649 // LowerOperation implementation 2650 //===----------------------------------------------------------------------===// 2651 2652 /// Return true if we should reference labels using a PICBase, set the HiOpFlags 2653 /// and LoOpFlags to the target MO flags. 2654 static void getLabelAccessInfo(bool IsPIC, const PPCSubtarget &Subtarget, 2655 unsigned &HiOpFlags, unsigned &LoOpFlags, 2656 const GlobalValue *GV = nullptr) { 2657 HiOpFlags = PPCII::MO_HA; 2658 LoOpFlags = PPCII::MO_LO; 2659 2660 // Don't use the pic base if not in PIC relocation model. 2661 if (IsPIC) { 2662 HiOpFlags |= PPCII::MO_PIC_FLAG; 2663 LoOpFlags |= PPCII::MO_PIC_FLAG; 2664 } 2665 2666 // If this is a reference to a global value that requires a non-lazy-ptr, make 2667 // sure that instruction lowering adds it. 2668 if (GV && Subtarget.hasLazyResolverStub(GV)) { 2669 HiOpFlags |= PPCII::MO_NLP_FLAG; 2670 LoOpFlags |= PPCII::MO_NLP_FLAG; 2671 2672 if (GV->hasHiddenVisibility()) { 2673 HiOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG; 2674 LoOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG; 2675 } 2676 } 2677 } 2678 2679 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC, 2680 SelectionDAG &DAG) { 2681 SDLoc DL(HiPart); 2682 EVT PtrVT = HiPart.getValueType(); 2683 SDValue Zero = DAG.getConstant(0, DL, PtrVT); 2684 2685 SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero); 2686 SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero); 2687 2688 // With PIC, the first instruction is actually "GR+hi(&G)". 2689 if (isPIC) 2690 Hi = DAG.getNode(ISD::ADD, DL, PtrVT, 2691 DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi); 2692 2693 // Generate non-pic code that has direct accesses to the constant pool. 2694 // The address of the global is just (hi(&g)+lo(&g)). 2695 return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo); 2696 } 2697 2698 static void setUsesTOCBasePtr(MachineFunction &MF) { 2699 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 2700 FuncInfo->setUsesTOCBasePtr(); 2701 } 2702 2703 static void setUsesTOCBasePtr(SelectionDAG &DAG) { 2704 setUsesTOCBasePtr(DAG.getMachineFunction()); 2705 } 2706 2707 SDValue PPCTargetLowering::getTOCEntry(SelectionDAG &DAG, const SDLoc &dl, 2708 SDValue GA) const { 2709 const bool Is64Bit = Subtarget.isPPC64(); 2710 EVT VT = Is64Bit ? MVT::i64 : MVT::i32; 2711 SDValue Reg = Is64Bit ? DAG.getRegister(PPC::X2, VT) 2712 : Subtarget.isAIXABI() 2713 ? DAG.getRegister(PPC::R2, VT) 2714 : DAG.getNode(PPCISD::GlobalBaseReg, dl, VT); 2715 SDValue Ops[] = { GA, Reg }; 2716 return DAG.getMemIntrinsicNode( 2717 PPCISD::TOC_ENTRY, dl, DAG.getVTList(VT, MVT::Other), Ops, VT, 2718 MachinePointerInfo::getGOT(DAG.getMachineFunction()), 0, 2719 MachineMemOperand::MOLoad); 2720 } 2721 2722 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op, 2723 SelectionDAG &DAG) const { 2724 EVT PtrVT = Op.getValueType(); 2725 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op); 2726 const Constant *C = CP->getConstVal(); 2727 2728 // 64-bit SVR4 ABI and AIX ABI code are always position-independent. 2729 // The actual address of the GlobalValue is stored in the TOC. 2730 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) { 2731 setUsesTOCBasePtr(DAG); 2732 SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0); 2733 return getTOCEntry(DAG, SDLoc(CP), GA); 2734 } 2735 2736 unsigned MOHiFlag, MOLoFlag; 2737 bool IsPIC = isPositionIndependent(); 2738 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag); 2739 2740 if (IsPIC && Subtarget.isSVR4ABI()) { 2741 SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 2742 PPCII::MO_PIC_FLAG); 2743 return getTOCEntry(DAG, SDLoc(CP), GA); 2744 } 2745 2746 SDValue CPIHi = 2747 DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOHiFlag); 2748 SDValue CPILo = 2749 DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOLoFlag); 2750 return LowerLabelRef(CPIHi, CPILo, IsPIC, DAG); 2751 } 2752 2753 // For 64-bit PowerPC, prefer the more compact relative encodings. 2754 // This trades 32 bits per jump table entry for one or two instructions 2755 // on the jump site. 2756 unsigned PPCTargetLowering::getJumpTableEncoding() const { 2757 if (isJumpTableRelative()) 2758 return MachineJumpTableInfo::EK_LabelDifference32; 2759 2760 return TargetLowering::getJumpTableEncoding(); 2761 } 2762 2763 bool PPCTargetLowering::isJumpTableRelative() const { 2764 if (UseAbsoluteJumpTables) 2765 return false; 2766 if (Subtarget.isPPC64() || Subtarget.isAIXABI()) 2767 return true; 2768 return TargetLowering::isJumpTableRelative(); 2769 } 2770 2771 SDValue PPCTargetLowering::getPICJumpTableRelocBase(SDValue Table, 2772 SelectionDAG &DAG) const { 2773 if (!Subtarget.isPPC64() || Subtarget.isAIXABI()) 2774 return TargetLowering::getPICJumpTableRelocBase(Table, DAG); 2775 2776 switch (getTargetMachine().getCodeModel()) { 2777 case CodeModel::Small: 2778 case CodeModel::Medium: 2779 return TargetLowering::getPICJumpTableRelocBase(Table, DAG); 2780 default: 2781 return DAG.getNode(PPCISD::GlobalBaseReg, SDLoc(), 2782 getPointerTy(DAG.getDataLayout())); 2783 } 2784 } 2785 2786 const MCExpr * 2787 PPCTargetLowering::getPICJumpTableRelocBaseExpr(const MachineFunction *MF, 2788 unsigned JTI, 2789 MCContext &Ctx) const { 2790 if (!Subtarget.isPPC64() || Subtarget.isAIXABI()) 2791 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx); 2792 2793 switch (getTargetMachine().getCodeModel()) { 2794 case CodeModel::Small: 2795 case CodeModel::Medium: 2796 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx); 2797 default: 2798 return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx); 2799 } 2800 } 2801 2802 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const { 2803 EVT PtrVT = Op.getValueType(); 2804 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op); 2805 2806 // 64-bit SVR4 ABI and AIX ABI code are always position-independent. 2807 // The actual address of the GlobalValue is stored in the TOC. 2808 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) { 2809 setUsesTOCBasePtr(DAG); 2810 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT); 2811 return getTOCEntry(DAG, SDLoc(JT), GA); 2812 } 2813 2814 unsigned MOHiFlag, MOLoFlag; 2815 bool IsPIC = isPositionIndependent(); 2816 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag); 2817 2818 if (IsPIC && Subtarget.isSVR4ABI()) { 2819 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, 2820 PPCII::MO_PIC_FLAG); 2821 return getTOCEntry(DAG, SDLoc(GA), GA); 2822 } 2823 2824 SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag); 2825 SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag); 2826 return LowerLabelRef(JTIHi, JTILo, IsPIC, DAG); 2827 } 2828 2829 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op, 2830 SelectionDAG &DAG) const { 2831 EVT PtrVT = Op.getValueType(); 2832 BlockAddressSDNode *BASDN = cast<BlockAddressSDNode>(Op); 2833 const BlockAddress *BA = BASDN->getBlockAddress(); 2834 2835 // 64-bit SVR4 ABI and AIX ABI code are always position-independent. 2836 // The actual BlockAddress is stored in the TOC. 2837 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) { 2838 setUsesTOCBasePtr(DAG); 2839 SDValue GA = DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset()); 2840 return getTOCEntry(DAG, SDLoc(BASDN), GA); 2841 } 2842 2843 // 32-bit position-independent ELF stores the BlockAddress in the .got. 2844 if (Subtarget.is32BitELFABI() && isPositionIndependent()) 2845 return getTOCEntry( 2846 DAG, SDLoc(BASDN), 2847 DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset())); 2848 2849 unsigned MOHiFlag, MOLoFlag; 2850 bool IsPIC = isPositionIndependent(); 2851 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag); 2852 SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag); 2853 SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag); 2854 return LowerLabelRef(TgtBAHi, TgtBALo, IsPIC, DAG); 2855 } 2856 2857 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op, 2858 SelectionDAG &DAG) const { 2859 // FIXME: TLS addresses currently use medium model code sequences, 2860 // which is the most useful form. Eventually support for small and 2861 // large models could be added if users need it, at the cost of 2862 // additional complexity. 2863 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op); 2864 if (DAG.getTarget().useEmulatedTLS()) 2865 return LowerToTLSEmulatedModel(GA, DAG); 2866 2867 SDLoc dl(GA); 2868 const GlobalValue *GV = GA->getGlobal(); 2869 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2870 bool is64bit = Subtarget.isPPC64(); 2871 const Module *M = DAG.getMachineFunction().getFunction().getParent(); 2872 PICLevel::Level picLevel = M->getPICLevel(); 2873 2874 const TargetMachine &TM = getTargetMachine(); 2875 TLSModel::Model Model = TM.getTLSModel(GV); 2876 2877 if (Model == TLSModel::LocalExec) { 2878 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 2879 PPCII::MO_TPREL_HA); 2880 SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 2881 PPCII::MO_TPREL_LO); 2882 SDValue TLSReg = is64bit ? DAG.getRegister(PPC::X13, MVT::i64) 2883 : DAG.getRegister(PPC::R2, MVT::i32); 2884 2885 SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg); 2886 return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi); 2887 } 2888 2889 if (Model == TLSModel::InitialExec) { 2890 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0); 2891 SDValue TGATLS = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 2892 PPCII::MO_TLS); 2893 SDValue GOTPtr; 2894 if (is64bit) { 2895 setUsesTOCBasePtr(DAG); 2896 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64); 2897 GOTPtr = DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl, 2898 PtrVT, GOTReg, TGA); 2899 } else { 2900 if (!TM.isPositionIndependent()) 2901 GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT); 2902 else if (picLevel == PICLevel::SmallPIC) 2903 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT); 2904 else 2905 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT); 2906 } 2907 SDValue TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl, 2908 PtrVT, TGA, GOTPtr); 2909 return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS); 2910 } 2911 2912 if (Model == TLSModel::GeneralDynamic) { 2913 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0); 2914 SDValue GOTPtr; 2915 if (is64bit) { 2916 setUsesTOCBasePtr(DAG); 2917 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64); 2918 GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT, 2919 GOTReg, TGA); 2920 } else { 2921 if (picLevel == PICLevel::SmallPIC) 2922 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT); 2923 else 2924 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT); 2925 } 2926 return DAG.getNode(PPCISD::ADDI_TLSGD_L_ADDR, dl, PtrVT, 2927 GOTPtr, TGA, TGA); 2928 } 2929 2930 if (Model == TLSModel::LocalDynamic) { 2931 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0); 2932 SDValue GOTPtr; 2933 if (is64bit) { 2934 setUsesTOCBasePtr(DAG); 2935 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64); 2936 GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT, 2937 GOTReg, TGA); 2938 } else { 2939 if (picLevel == PICLevel::SmallPIC) 2940 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT); 2941 else 2942 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT); 2943 } 2944 SDValue TLSAddr = DAG.getNode(PPCISD::ADDI_TLSLD_L_ADDR, dl, 2945 PtrVT, GOTPtr, TGA, TGA); 2946 SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl, 2947 PtrVT, TLSAddr, TGA); 2948 return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA); 2949 } 2950 2951 llvm_unreachable("Unknown TLS model!"); 2952 } 2953 2954 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op, 2955 SelectionDAG &DAG) const { 2956 EVT PtrVT = Op.getValueType(); 2957 GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op); 2958 SDLoc DL(GSDN); 2959 const GlobalValue *GV = GSDN->getGlobal(); 2960 2961 // 64-bit SVR4 ABI & AIX ABI code is always position-independent. 2962 // The actual address of the GlobalValue is stored in the TOC. 2963 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) { 2964 setUsesTOCBasePtr(DAG); 2965 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset()); 2966 return getTOCEntry(DAG, DL, GA); 2967 } 2968 2969 unsigned MOHiFlag, MOLoFlag; 2970 bool IsPIC = isPositionIndependent(); 2971 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag, GV); 2972 2973 if (IsPIC && Subtarget.isSVR4ABI()) { 2974 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 2975 GSDN->getOffset(), 2976 PPCII::MO_PIC_FLAG); 2977 return getTOCEntry(DAG, DL, GA); 2978 } 2979 2980 SDValue GAHi = 2981 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag); 2982 SDValue GALo = 2983 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag); 2984 2985 SDValue Ptr = LowerLabelRef(GAHi, GALo, IsPIC, DAG); 2986 2987 // If the global reference is actually to a non-lazy-pointer, we have to do an 2988 // extra load to get the address of the global. 2989 if (MOHiFlag & PPCII::MO_NLP_FLAG) 2990 Ptr = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo()); 2991 return Ptr; 2992 } 2993 2994 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const { 2995 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get(); 2996 SDLoc dl(Op); 2997 2998 if (Op.getValueType() == MVT::v2i64) { 2999 // When the operands themselves are v2i64 values, we need to do something 3000 // special because VSX has no underlying comparison operations for these. 3001 if (Op.getOperand(0).getValueType() == MVT::v2i64) { 3002 // Equality can be handled by casting to the legal type for Altivec 3003 // comparisons, everything else needs to be expanded. 3004 if (CC == ISD::SETEQ || CC == ISD::SETNE) { 3005 return DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, 3006 DAG.getSetCC(dl, MVT::v4i32, 3007 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0)), 3008 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(1)), 3009 CC)); 3010 } 3011 3012 return SDValue(); 3013 } 3014 3015 // We handle most of these in the usual way. 3016 return Op; 3017 } 3018 3019 // If we're comparing for equality to zero, expose the fact that this is 3020 // implemented as a ctlz/srl pair on ppc, so that the dag combiner can 3021 // fold the new nodes. 3022 if (SDValue V = lowerCmpEqZeroToCtlzSrl(Op, DAG)) 3023 return V; 3024 3025 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 3026 // Leave comparisons against 0 and -1 alone for now, since they're usually 3027 // optimized. FIXME: revisit this when we can custom lower all setcc 3028 // optimizations. 3029 if (C->isAllOnesValue() || C->isNullValue()) 3030 return SDValue(); 3031 } 3032 3033 // If we have an integer seteq/setne, turn it into a compare against zero 3034 // by xor'ing the rhs with the lhs, which is faster than setting a 3035 // condition register, reading it back out, and masking the correct bit. The 3036 // normal approach here uses sub to do this instead of xor. Using xor exposes 3037 // the result to other bit-twiddling opportunities. 3038 EVT LHSVT = Op.getOperand(0).getValueType(); 3039 if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) { 3040 EVT VT = Op.getValueType(); 3041 SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0), 3042 Op.getOperand(1)); 3043 return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, dl, LHSVT), CC); 3044 } 3045 return SDValue(); 3046 } 3047 3048 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const { 3049 SDNode *Node = Op.getNode(); 3050 EVT VT = Node->getValueType(0); 3051 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3052 SDValue InChain = Node->getOperand(0); 3053 SDValue VAListPtr = Node->getOperand(1); 3054 const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue(); 3055 SDLoc dl(Node); 3056 3057 assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only"); 3058 3059 // gpr_index 3060 SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain, 3061 VAListPtr, MachinePointerInfo(SV), MVT::i8); 3062 InChain = GprIndex.getValue(1); 3063 3064 if (VT == MVT::i64) { 3065 // Check if GprIndex is even 3066 SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex, 3067 DAG.getConstant(1, dl, MVT::i32)); 3068 SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd, 3069 DAG.getConstant(0, dl, MVT::i32), ISD::SETNE); 3070 SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex, 3071 DAG.getConstant(1, dl, MVT::i32)); 3072 // Align GprIndex to be even if it isn't 3073 GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne, 3074 GprIndex); 3075 } 3076 3077 // fpr index is 1 byte after gpr 3078 SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, 3079 DAG.getConstant(1, dl, MVT::i32)); 3080 3081 // fpr 3082 SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain, 3083 FprPtr, MachinePointerInfo(SV), MVT::i8); 3084 InChain = FprIndex.getValue(1); 3085 3086 SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, 3087 DAG.getConstant(8, dl, MVT::i32)); 3088 3089 SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, 3090 DAG.getConstant(4, dl, MVT::i32)); 3091 3092 // areas 3093 SDValue OverflowArea = 3094 DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr, MachinePointerInfo()); 3095 InChain = OverflowArea.getValue(1); 3096 3097 SDValue RegSaveArea = 3098 DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr, MachinePointerInfo()); 3099 InChain = RegSaveArea.getValue(1); 3100 3101 // select overflow_area if index > 8 3102 SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex, 3103 DAG.getConstant(8, dl, MVT::i32), ISD::SETLT); 3104 3105 // adjustment constant gpr_index * 4/8 3106 SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32, 3107 VT.isInteger() ? GprIndex : FprIndex, 3108 DAG.getConstant(VT.isInteger() ? 4 : 8, dl, 3109 MVT::i32)); 3110 3111 // OurReg = RegSaveArea + RegConstant 3112 SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea, 3113 RegConstant); 3114 3115 // Floating types are 32 bytes into RegSaveArea 3116 if (VT.isFloatingPoint()) 3117 OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg, 3118 DAG.getConstant(32, dl, MVT::i32)); 3119 3120 // increase {f,g}pr_index by 1 (or 2 if VT is i64) 3121 SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32, 3122 VT.isInteger() ? GprIndex : FprIndex, 3123 DAG.getConstant(VT == MVT::i64 ? 2 : 1, dl, 3124 MVT::i32)); 3125 3126 InChain = DAG.getTruncStore(InChain, dl, IndexPlus1, 3127 VT.isInteger() ? VAListPtr : FprPtr, 3128 MachinePointerInfo(SV), MVT::i8); 3129 3130 // determine if we should load from reg_save_area or overflow_area 3131 SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea); 3132 3133 // increase overflow_area by 4/8 if gpr/fpr > 8 3134 SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea, 3135 DAG.getConstant(VT.isInteger() ? 4 : 8, 3136 dl, MVT::i32)); 3137 3138 OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea, 3139 OverflowAreaPlusN); 3140 3141 InChain = DAG.getTruncStore(InChain, dl, OverflowArea, OverflowAreaPtr, 3142 MachinePointerInfo(), MVT::i32); 3143 3144 return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo()); 3145 } 3146 3147 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const { 3148 assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only"); 3149 3150 // We have to copy the entire va_list struct: 3151 // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte 3152 return DAG.getMemcpy(Op.getOperand(0), Op, 3153 Op.getOperand(1), Op.getOperand(2), 3154 DAG.getConstant(12, SDLoc(Op), MVT::i32), 8, false, true, 3155 false, MachinePointerInfo(), MachinePointerInfo()); 3156 } 3157 3158 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op, 3159 SelectionDAG &DAG) const { 3160 if (Subtarget.isAIXABI()) 3161 report_fatal_error("ADJUST_TRAMPOLINE operation is not supported on AIX."); 3162 3163 return Op.getOperand(0); 3164 } 3165 3166 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op, 3167 SelectionDAG &DAG) const { 3168 if (Subtarget.isAIXABI()) 3169 report_fatal_error("INIT_TRAMPOLINE operation is not supported on AIX."); 3170 3171 SDValue Chain = Op.getOperand(0); 3172 SDValue Trmp = Op.getOperand(1); // trampoline 3173 SDValue FPtr = Op.getOperand(2); // nested function 3174 SDValue Nest = Op.getOperand(3); // 'nest' parameter value 3175 SDLoc dl(Op); 3176 3177 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3178 bool isPPC64 = (PtrVT == MVT::i64); 3179 Type *IntPtrTy = DAG.getDataLayout().getIntPtrType(*DAG.getContext()); 3180 3181 TargetLowering::ArgListTy Args; 3182 TargetLowering::ArgListEntry Entry; 3183 3184 Entry.Ty = IntPtrTy; 3185 Entry.Node = Trmp; Args.push_back(Entry); 3186 3187 // TrampSize == (isPPC64 ? 48 : 40); 3188 Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40, dl, 3189 isPPC64 ? MVT::i64 : MVT::i32); 3190 Args.push_back(Entry); 3191 3192 Entry.Node = FPtr; Args.push_back(Entry); 3193 Entry.Node = Nest; Args.push_back(Entry); 3194 3195 // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg) 3196 TargetLowering::CallLoweringInfo CLI(DAG); 3197 CLI.setDebugLoc(dl).setChain(Chain).setLibCallee( 3198 CallingConv::C, Type::getVoidTy(*DAG.getContext()), 3199 DAG.getExternalSymbol("__trampoline_setup", PtrVT), std::move(Args)); 3200 3201 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 3202 return CallResult.second; 3203 } 3204 3205 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const { 3206 MachineFunction &MF = DAG.getMachineFunction(); 3207 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 3208 EVT PtrVT = getPointerTy(MF.getDataLayout()); 3209 3210 SDLoc dl(Op); 3211 3212 if (Subtarget.isDarwinABI() || Subtarget.isPPC64()) { 3213 // vastart just stores the address of the VarArgsFrameIndex slot into the 3214 // memory location argument. 3215 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 3216 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 3217 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1), 3218 MachinePointerInfo(SV)); 3219 } 3220 3221 // For the 32-bit SVR4 ABI we follow the layout of the va_list struct. 3222 // We suppose the given va_list is already allocated. 3223 // 3224 // typedef struct { 3225 // char gpr; /* index into the array of 8 GPRs 3226 // * stored in the register save area 3227 // * gpr=0 corresponds to r3, 3228 // * gpr=1 to r4, etc. 3229 // */ 3230 // char fpr; /* index into the array of 8 FPRs 3231 // * stored in the register save area 3232 // * fpr=0 corresponds to f1, 3233 // * fpr=1 to f2, etc. 3234 // */ 3235 // char *overflow_arg_area; 3236 // /* location on stack that holds 3237 // * the next overflow argument 3238 // */ 3239 // char *reg_save_area; 3240 // /* where r3:r10 and f1:f8 (if saved) 3241 // * are stored 3242 // */ 3243 // } va_list[1]; 3244 3245 SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), dl, MVT::i32); 3246 SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), dl, MVT::i32); 3247 SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(), 3248 PtrVT); 3249 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), 3250 PtrVT); 3251 3252 uint64_t FrameOffset = PtrVT.getSizeInBits()/8; 3253 SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, dl, PtrVT); 3254 3255 uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1; 3256 SDValue ConstStackOffset = DAG.getConstant(StackOffset, dl, PtrVT); 3257 3258 uint64_t FPROffset = 1; 3259 SDValue ConstFPROffset = DAG.getConstant(FPROffset, dl, PtrVT); 3260 3261 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 3262 3263 // Store first byte : number of int regs 3264 SDValue firstStore = 3265 DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR, Op.getOperand(1), 3266 MachinePointerInfo(SV), MVT::i8); 3267 uint64_t nextOffset = FPROffset; 3268 SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1), 3269 ConstFPROffset); 3270 3271 // Store second byte : number of float regs 3272 SDValue secondStore = 3273 DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr, 3274 MachinePointerInfo(SV, nextOffset), MVT::i8); 3275 nextOffset += StackOffset; 3276 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset); 3277 3278 // Store second word : arguments given on stack 3279 SDValue thirdStore = DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr, 3280 MachinePointerInfo(SV, nextOffset)); 3281 nextOffset += FrameOffset; 3282 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset); 3283 3284 // Store third word : arguments given in registers 3285 return DAG.getStore(thirdStore, dl, FR, nextPtr, 3286 MachinePointerInfo(SV, nextOffset)); 3287 } 3288 3289 /// FPR - The set of FP registers that should be allocated for arguments 3290 /// on Darwin and AIX. 3291 static const MCPhysReg FPR[] = {PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, 3292 PPC::F6, PPC::F7, PPC::F8, PPC::F9, PPC::F10, 3293 PPC::F11, PPC::F12, PPC::F13}; 3294 3295 /// QFPR - The set of QPX registers that should be allocated for arguments. 3296 static const MCPhysReg QFPR[] = { 3297 PPC::QF1, PPC::QF2, PPC::QF3, PPC::QF4, PPC::QF5, PPC::QF6, PPC::QF7, 3298 PPC::QF8, PPC::QF9, PPC::QF10, PPC::QF11, PPC::QF12, PPC::QF13}; 3299 3300 /// CalculateStackSlotSize - Calculates the size reserved for this argument on 3301 /// the stack. 3302 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags, 3303 unsigned PtrByteSize) { 3304 unsigned ArgSize = ArgVT.getStoreSize(); 3305 if (Flags.isByVal()) 3306 ArgSize = Flags.getByValSize(); 3307 3308 // Round up to multiples of the pointer size, except for array members, 3309 // which are always packed. 3310 if (!Flags.isInConsecutiveRegs()) 3311 ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3312 3313 return ArgSize; 3314 } 3315 3316 /// CalculateStackSlotAlignment - Calculates the alignment of this argument 3317 /// on the stack. 3318 static unsigned CalculateStackSlotAlignment(EVT ArgVT, EVT OrigVT, 3319 ISD::ArgFlagsTy Flags, 3320 unsigned PtrByteSize) { 3321 unsigned Align = PtrByteSize; 3322 3323 // Altivec parameters are padded to a 16 byte boundary. 3324 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 || 3325 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 || 3326 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 || 3327 ArgVT == MVT::v1i128 || ArgVT == MVT::f128) 3328 Align = 16; 3329 // QPX vector types stored in double-precision are padded to a 32 byte 3330 // boundary. 3331 else if (ArgVT == MVT::v4f64 || ArgVT == MVT::v4i1) 3332 Align = 32; 3333 3334 // ByVal parameters are aligned as requested. 3335 if (Flags.isByVal()) { 3336 unsigned BVAlign = Flags.getByValAlign(); 3337 if (BVAlign > PtrByteSize) { 3338 if (BVAlign % PtrByteSize != 0) 3339 llvm_unreachable( 3340 "ByVal alignment is not a multiple of the pointer size"); 3341 3342 Align = BVAlign; 3343 } 3344 } 3345 3346 // Array members are always packed to their original alignment. 3347 if (Flags.isInConsecutiveRegs()) { 3348 // If the array member was split into multiple registers, the first 3349 // needs to be aligned to the size of the full type. (Except for 3350 // ppcf128, which is only aligned as its f64 components.) 3351 if (Flags.isSplit() && OrigVT != MVT::ppcf128) 3352 Align = OrigVT.getStoreSize(); 3353 else 3354 Align = ArgVT.getStoreSize(); 3355 } 3356 3357 return Align; 3358 } 3359 3360 /// CalculateStackSlotUsed - Return whether this argument will use its 3361 /// stack slot (instead of being passed in registers). ArgOffset, 3362 /// AvailableFPRs, and AvailableVRs must hold the current argument 3363 /// position, and will be updated to account for this argument. 3364 static bool CalculateStackSlotUsed(EVT ArgVT, EVT OrigVT, 3365 ISD::ArgFlagsTy Flags, 3366 unsigned PtrByteSize, 3367 unsigned LinkageSize, 3368 unsigned ParamAreaSize, 3369 unsigned &ArgOffset, 3370 unsigned &AvailableFPRs, 3371 unsigned &AvailableVRs, bool HasQPX) { 3372 bool UseMemory = false; 3373 3374 // Respect alignment of argument on the stack. 3375 unsigned Align = 3376 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize); 3377 ArgOffset = ((ArgOffset + Align - 1) / Align) * Align; 3378 // If there's no space left in the argument save area, we must 3379 // use memory (this check also catches zero-sized arguments). 3380 if (ArgOffset >= LinkageSize + ParamAreaSize) 3381 UseMemory = true; 3382 3383 // Allocate argument on the stack. 3384 ArgOffset += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize); 3385 if (Flags.isInConsecutiveRegsLast()) 3386 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3387 // If we overran the argument save area, we must use memory 3388 // (this check catches arguments passed partially in memory) 3389 if (ArgOffset > LinkageSize + ParamAreaSize) 3390 UseMemory = true; 3391 3392 // However, if the argument is actually passed in an FPR or a VR, 3393 // we don't use memory after all. 3394 if (!Flags.isByVal()) { 3395 if (ArgVT == MVT::f32 || ArgVT == MVT::f64 || 3396 // QPX registers overlap with the scalar FP registers. 3397 (HasQPX && (ArgVT == MVT::v4f32 || 3398 ArgVT == MVT::v4f64 || 3399 ArgVT == MVT::v4i1))) 3400 if (AvailableFPRs > 0) { 3401 --AvailableFPRs; 3402 return false; 3403 } 3404 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 || 3405 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 || 3406 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 || 3407 ArgVT == MVT::v1i128 || ArgVT == MVT::f128) 3408 if (AvailableVRs > 0) { 3409 --AvailableVRs; 3410 return false; 3411 } 3412 } 3413 3414 return UseMemory; 3415 } 3416 3417 /// EnsureStackAlignment - Round stack frame size up from NumBytes to 3418 /// ensure minimum alignment required for target. 3419 static unsigned EnsureStackAlignment(const PPCFrameLowering *Lowering, 3420 unsigned NumBytes) { 3421 unsigned TargetAlign = Lowering->getStackAlignment(); 3422 unsigned AlignMask = TargetAlign - 1; 3423 NumBytes = (NumBytes + AlignMask) & ~AlignMask; 3424 return NumBytes; 3425 } 3426 3427 SDValue PPCTargetLowering::LowerFormalArguments( 3428 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3429 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3430 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3431 if (Subtarget.isAIXABI()) 3432 return LowerFormalArguments_AIX(Chain, CallConv, isVarArg, Ins, dl, DAG, 3433 InVals); 3434 if (Subtarget.is64BitELFABI()) 3435 return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins, dl, DAG, 3436 InVals); 3437 if (Subtarget.is32BitELFABI()) 3438 return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins, dl, DAG, 3439 InVals); 3440 3441 return LowerFormalArguments_Darwin(Chain, CallConv, isVarArg, Ins, dl, DAG, 3442 InVals); 3443 } 3444 3445 SDValue PPCTargetLowering::LowerFormalArguments_32SVR4( 3446 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3447 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3448 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3449 3450 // 32-bit SVR4 ABI Stack Frame Layout: 3451 // +-----------------------------------+ 3452 // +--> | Back chain | 3453 // | +-----------------------------------+ 3454 // | | Floating-point register save area | 3455 // | +-----------------------------------+ 3456 // | | General register save area | 3457 // | +-----------------------------------+ 3458 // | | CR save word | 3459 // | +-----------------------------------+ 3460 // | | VRSAVE save word | 3461 // | +-----------------------------------+ 3462 // | | Alignment padding | 3463 // | +-----------------------------------+ 3464 // | | Vector register save area | 3465 // | +-----------------------------------+ 3466 // | | Local variable space | 3467 // | +-----------------------------------+ 3468 // | | Parameter list area | 3469 // | +-----------------------------------+ 3470 // | | LR save word | 3471 // | +-----------------------------------+ 3472 // SP--> +--- | Back chain | 3473 // +-----------------------------------+ 3474 // 3475 // Specifications: 3476 // System V Application Binary Interface PowerPC Processor Supplement 3477 // AltiVec Technology Programming Interface Manual 3478 3479 MachineFunction &MF = DAG.getMachineFunction(); 3480 MachineFrameInfo &MFI = MF.getFrameInfo(); 3481 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 3482 3483 EVT PtrVT = getPointerTy(MF.getDataLayout()); 3484 // Potential tail calls could cause overwriting of argument stack slots. 3485 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt && 3486 (CallConv == CallingConv::Fast)); 3487 unsigned PtrByteSize = 4; 3488 3489 // Assign locations to all of the incoming arguments. 3490 SmallVector<CCValAssign, 16> ArgLocs; 3491 PPCCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 3492 *DAG.getContext()); 3493 3494 // Reserve space for the linkage area on the stack. 3495 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 3496 CCInfo.AllocateStack(LinkageSize, PtrByteSize); 3497 if (useSoftFloat()) 3498 CCInfo.PreAnalyzeFormalArguments(Ins); 3499 3500 CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4); 3501 CCInfo.clearWasPPCF128(); 3502 3503 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 3504 CCValAssign &VA = ArgLocs[i]; 3505 3506 // Arguments stored in registers. 3507 if (VA.isRegLoc()) { 3508 const TargetRegisterClass *RC; 3509 EVT ValVT = VA.getValVT(); 3510 3511 switch (ValVT.getSimpleVT().SimpleTy) { 3512 default: 3513 llvm_unreachable("ValVT not supported by formal arguments Lowering"); 3514 case MVT::i1: 3515 case MVT::i32: 3516 RC = &PPC::GPRCRegClass; 3517 break; 3518 case MVT::f32: 3519 if (Subtarget.hasP8Vector()) 3520 RC = &PPC::VSSRCRegClass; 3521 else if (Subtarget.hasSPE()) 3522 RC = &PPC::GPRCRegClass; 3523 else 3524 RC = &PPC::F4RCRegClass; 3525 break; 3526 case MVT::f64: 3527 if (Subtarget.hasVSX()) 3528 RC = &PPC::VSFRCRegClass; 3529 else if (Subtarget.hasSPE()) 3530 // SPE passes doubles in GPR pairs. 3531 RC = &PPC::GPRCRegClass; 3532 else 3533 RC = &PPC::F8RCRegClass; 3534 break; 3535 case MVT::v16i8: 3536 case MVT::v8i16: 3537 case MVT::v4i32: 3538 RC = &PPC::VRRCRegClass; 3539 break; 3540 case MVT::v4f32: 3541 RC = Subtarget.hasQPX() ? &PPC::QSRCRegClass : &PPC::VRRCRegClass; 3542 break; 3543 case MVT::v2f64: 3544 case MVT::v2i64: 3545 RC = &PPC::VRRCRegClass; 3546 break; 3547 case MVT::v4f64: 3548 RC = &PPC::QFRCRegClass; 3549 break; 3550 case MVT::v4i1: 3551 RC = &PPC::QBRCRegClass; 3552 break; 3553 } 3554 3555 SDValue ArgValue; 3556 // Transform the arguments stored in physical registers into 3557 // virtual ones. 3558 if (VA.getLocVT() == MVT::f64 && Subtarget.hasSPE()) { 3559 assert(i + 1 < e && "No second half of double precision argument"); 3560 unsigned RegLo = MF.addLiveIn(VA.getLocReg(), RC); 3561 unsigned RegHi = MF.addLiveIn(ArgLocs[++i].getLocReg(), RC); 3562 SDValue ArgValueLo = DAG.getCopyFromReg(Chain, dl, RegLo, MVT::i32); 3563 SDValue ArgValueHi = DAG.getCopyFromReg(Chain, dl, RegHi, MVT::i32); 3564 if (!Subtarget.isLittleEndian()) 3565 std::swap (ArgValueLo, ArgValueHi); 3566 ArgValue = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, ArgValueLo, 3567 ArgValueHi); 3568 } else { 3569 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC); 3570 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, 3571 ValVT == MVT::i1 ? MVT::i32 : ValVT); 3572 if (ValVT == MVT::i1) 3573 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue); 3574 } 3575 3576 InVals.push_back(ArgValue); 3577 } else { 3578 // Argument stored in memory. 3579 assert(VA.isMemLoc()); 3580 3581 // Get the extended size of the argument type in stack 3582 unsigned ArgSize = VA.getLocVT().getStoreSize(); 3583 // Get the actual size of the argument type 3584 unsigned ObjSize = VA.getValVT().getStoreSize(); 3585 unsigned ArgOffset = VA.getLocMemOffset(); 3586 // Stack objects in PPC32 are right justified. 3587 ArgOffset += ArgSize - ObjSize; 3588 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, isImmutable); 3589 3590 // Create load nodes to retrieve arguments from the stack. 3591 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3592 InVals.push_back( 3593 DAG.getLoad(VA.getValVT(), dl, Chain, FIN, MachinePointerInfo())); 3594 } 3595 } 3596 3597 // Assign locations to all of the incoming aggregate by value arguments. 3598 // Aggregates passed by value are stored in the local variable space of the 3599 // caller's stack frame, right above the parameter list area. 3600 SmallVector<CCValAssign, 16> ByValArgLocs; 3601 CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(), 3602 ByValArgLocs, *DAG.getContext()); 3603 3604 // Reserve stack space for the allocations in CCInfo. 3605 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize); 3606 3607 CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal); 3608 3609 // Area that is at least reserved in the caller of this function. 3610 unsigned MinReservedArea = CCByValInfo.getNextStackOffset(); 3611 MinReservedArea = std::max(MinReservedArea, LinkageSize); 3612 3613 // Set the size that is at least reserved in caller of this function. Tail 3614 // call optimized function's reserved stack space needs to be aligned so that 3615 // taking the difference between two stack areas will result in an aligned 3616 // stack. 3617 MinReservedArea = 3618 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea); 3619 FuncInfo->setMinReservedArea(MinReservedArea); 3620 3621 SmallVector<SDValue, 8> MemOps; 3622 3623 // If the function takes variable number of arguments, make a frame index for 3624 // the start of the first vararg value... for expansion of llvm.va_start. 3625 if (isVarArg) { 3626 static const MCPhysReg GPArgRegs[] = { 3627 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 3628 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 3629 }; 3630 const unsigned NumGPArgRegs = array_lengthof(GPArgRegs); 3631 3632 static const MCPhysReg FPArgRegs[] = { 3633 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7, 3634 PPC::F8 3635 }; 3636 unsigned NumFPArgRegs = array_lengthof(FPArgRegs); 3637 3638 if (useSoftFloat() || hasSPE()) 3639 NumFPArgRegs = 0; 3640 3641 FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs)); 3642 FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs)); 3643 3644 // Make room for NumGPArgRegs and NumFPArgRegs. 3645 int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 + 3646 NumFPArgRegs * MVT(MVT::f64).getSizeInBits()/8; 3647 3648 FuncInfo->setVarArgsStackOffset( 3649 MFI.CreateFixedObject(PtrVT.getSizeInBits()/8, 3650 CCInfo.getNextStackOffset(), true)); 3651 3652 FuncInfo->setVarArgsFrameIndex(MFI.CreateStackObject(Depth, 8, false)); 3653 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 3654 3655 // The fixed integer arguments of a variadic function are stored to the 3656 // VarArgsFrameIndex on the stack so that they may be loaded by 3657 // dereferencing the result of va_next. 3658 for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) { 3659 // Get an existing live-in vreg, or add a new one. 3660 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]); 3661 if (!VReg) 3662 VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass); 3663 3664 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 3665 SDValue Store = 3666 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 3667 MemOps.push_back(Store); 3668 // Increment the address by four for the next argument to store 3669 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT); 3670 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 3671 } 3672 3673 // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6 3674 // is set. 3675 // The double arguments are stored to the VarArgsFrameIndex 3676 // on the stack. 3677 for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) { 3678 // Get an existing live-in vreg, or add a new one. 3679 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]); 3680 if (!VReg) 3681 VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass); 3682 3683 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64); 3684 SDValue Store = 3685 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 3686 MemOps.push_back(Store); 3687 // Increment the address by eight for the next argument to store 3688 SDValue PtrOff = DAG.getConstant(MVT(MVT::f64).getSizeInBits()/8, dl, 3689 PtrVT); 3690 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 3691 } 3692 } 3693 3694 if (!MemOps.empty()) 3695 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 3696 3697 return Chain; 3698 } 3699 3700 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote 3701 // value to MVT::i64 and then truncate to the correct register size. 3702 SDValue PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags, 3703 EVT ObjectVT, SelectionDAG &DAG, 3704 SDValue ArgVal, 3705 const SDLoc &dl) const { 3706 if (Flags.isSExt()) 3707 ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal, 3708 DAG.getValueType(ObjectVT)); 3709 else if (Flags.isZExt()) 3710 ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal, 3711 DAG.getValueType(ObjectVT)); 3712 3713 return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal); 3714 } 3715 3716 SDValue PPCTargetLowering::LowerFormalArguments_64SVR4( 3717 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3718 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3719 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3720 // TODO: add description of PPC stack frame format, or at least some docs. 3721 // 3722 bool isELFv2ABI = Subtarget.isELFv2ABI(); 3723 bool isLittleEndian = Subtarget.isLittleEndian(); 3724 MachineFunction &MF = DAG.getMachineFunction(); 3725 MachineFrameInfo &MFI = MF.getFrameInfo(); 3726 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 3727 3728 assert(!(CallConv == CallingConv::Fast && isVarArg) && 3729 "fastcc not supported on varargs functions"); 3730 3731 EVT PtrVT = getPointerTy(MF.getDataLayout()); 3732 // Potential tail calls could cause overwriting of argument stack slots. 3733 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt && 3734 (CallConv == CallingConv::Fast)); 3735 unsigned PtrByteSize = 8; 3736 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 3737 3738 static const MCPhysReg GPR[] = { 3739 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 3740 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 3741 }; 3742 static const MCPhysReg VR[] = { 3743 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 3744 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 3745 }; 3746 3747 const unsigned Num_GPR_Regs = array_lengthof(GPR); 3748 const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13; 3749 const unsigned Num_VR_Regs = array_lengthof(VR); 3750 const unsigned Num_QFPR_Regs = Num_FPR_Regs; 3751 3752 // Do a first pass over the arguments to determine whether the ABI 3753 // guarantees that our caller has allocated the parameter save area 3754 // on its stack frame. In the ELFv1 ABI, this is always the case; 3755 // in the ELFv2 ABI, it is true if this is a vararg function or if 3756 // any parameter is located in a stack slot. 3757 3758 bool HasParameterArea = !isELFv2ABI || isVarArg; 3759 unsigned ParamAreaSize = Num_GPR_Regs * PtrByteSize; 3760 unsigned NumBytes = LinkageSize; 3761 unsigned AvailableFPRs = Num_FPR_Regs; 3762 unsigned AvailableVRs = Num_VR_Regs; 3763 for (unsigned i = 0, e = Ins.size(); i != e; ++i) { 3764 if (Ins[i].Flags.isNest()) 3765 continue; 3766 3767 if (CalculateStackSlotUsed(Ins[i].VT, Ins[i].ArgVT, Ins[i].Flags, 3768 PtrByteSize, LinkageSize, ParamAreaSize, 3769 NumBytes, AvailableFPRs, AvailableVRs, 3770 Subtarget.hasQPX())) 3771 HasParameterArea = true; 3772 } 3773 3774 // Add DAG nodes to load the arguments or copy them out of registers. On 3775 // entry to a function on PPC, the arguments start after the linkage area, 3776 // although the first ones are often in registers. 3777 3778 unsigned ArgOffset = LinkageSize; 3779 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 3780 unsigned &QFPR_idx = FPR_idx; 3781 SmallVector<SDValue, 8> MemOps; 3782 Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin(); 3783 unsigned CurArgIdx = 0; 3784 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) { 3785 SDValue ArgVal; 3786 bool needsLoad = false; 3787 EVT ObjectVT = Ins[ArgNo].VT; 3788 EVT OrigVT = Ins[ArgNo].ArgVT; 3789 unsigned ObjSize = ObjectVT.getStoreSize(); 3790 unsigned ArgSize = ObjSize; 3791 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags; 3792 if (Ins[ArgNo].isOrigArg()) { 3793 std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx); 3794 CurArgIdx = Ins[ArgNo].getOrigArgIndex(); 3795 } 3796 // We re-align the argument offset for each argument, except when using the 3797 // fast calling convention, when we need to make sure we do that only when 3798 // we'll actually use a stack slot. 3799 unsigned CurArgOffset, Align; 3800 auto ComputeArgOffset = [&]() { 3801 /* Respect alignment of argument on the stack. */ 3802 Align = CalculateStackSlotAlignment(ObjectVT, OrigVT, Flags, PtrByteSize); 3803 ArgOffset = ((ArgOffset + Align - 1) / Align) * Align; 3804 CurArgOffset = ArgOffset; 3805 }; 3806 3807 if (CallConv != CallingConv::Fast) { 3808 ComputeArgOffset(); 3809 3810 /* Compute GPR index associated with argument offset. */ 3811 GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize; 3812 GPR_idx = std::min(GPR_idx, Num_GPR_Regs); 3813 } 3814 3815 // FIXME the codegen can be much improved in some cases. 3816 // We do not have to keep everything in memory. 3817 if (Flags.isByVal()) { 3818 assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit"); 3819 3820 if (CallConv == CallingConv::Fast) 3821 ComputeArgOffset(); 3822 3823 // ObjSize is the true size, ArgSize rounded up to multiple of registers. 3824 ObjSize = Flags.getByValSize(); 3825 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3826 // Empty aggregate parameters do not take up registers. Examples: 3827 // struct { } a; 3828 // union { } b; 3829 // int c[0]; 3830 // etc. However, we have to provide a place-holder in InVals, so 3831 // pretend we have an 8-byte item at the current address for that 3832 // purpose. 3833 if (!ObjSize) { 3834 int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true); 3835 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3836 InVals.push_back(FIN); 3837 continue; 3838 } 3839 3840 // Create a stack object covering all stack doublewords occupied 3841 // by the argument. If the argument is (fully or partially) on 3842 // the stack, or if the argument is fully in registers but the 3843 // caller has allocated the parameter save anyway, we can refer 3844 // directly to the caller's stack frame. Otherwise, create a 3845 // local copy in our own frame. 3846 int FI; 3847 if (HasParameterArea || 3848 ArgSize + ArgOffset > LinkageSize + Num_GPR_Regs * PtrByteSize) 3849 FI = MFI.CreateFixedObject(ArgSize, ArgOffset, false, true); 3850 else 3851 FI = MFI.CreateStackObject(ArgSize, Align, false); 3852 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3853 3854 // Handle aggregates smaller than 8 bytes. 3855 if (ObjSize < PtrByteSize) { 3856 // The value of the object is its address, which differs from the 3857 // address of the enclosing doubleword on big-endian systems. 3858 SDValue Arg = FIN; 3859 if (!isLittleEndian) { 3860 SDValue ArgOff = DAG.getConstant(PtrByteSize - ObjSize, dl, PtrVT); 3861 Arg = DAG.getNode(ISD::ADD, dl, ArgOff.getValueType(), Arg, ArgOff); 3862 } 3863 InVals.push_back(Arg); 3864 3865 if (GPR_idx != Num_GPR_Regs) { 3866 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass); 3867 FuncInfo->addLiveInAttr(VReg, Flags); 3868 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 3869 SDValue Store; 3870 3871 if (ObjSize==1 || ObjSize==2 || ObjSize==4) { 3872 EVT ObjType = (ObjSize == 1 ? MVT::i8 : 3873 (ObjSize == 2 ? MVT::i16 : MVT::i32)); 3874 Store = DAG.getTruncStore(Val.getValue(1), dl, Val, Arg, 3875 MachinePointerInfo(&*FuncArg), ObjType); 3876 } else { 3877 // For sizes that don't fit a truncating store (3, 5, 6, 7), 3878 // store the whole register as-is to the parameter save area 3879 // slot. 3880 Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, 3881 MachinePointerInfo(&*FuncArg)); 3882 } 3883 3884 MemOps.push_back(Store); 3885 } 3886 // Whether we copied from a register or not, advance the offset 3887 // into the parameter save area by a full doubleword. 3888 ArgOffset += PtrByteSize; 3889 continue; 3890 } 3891 3892 // The value of the object is its address, which is the address of 3893 // its first stack doubleword. 3894 InVals.push_back(FIN); 3895 3896 // Store whatever pieces of the object are in registers to memory. 3897 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) { 3898 if (GPR_idx == Num_GPR_Regs) 3899 break; 3900 3901 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 3902 FuncInfo->addLiveInAttr(VReg, Flags); 3903 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 3904 SDValue Addr = FIN; 3905 if (j) { 3906 SDValue Off = DAG.getConstant(j, dl, PtrVT); 3907 Addr = DAG.getNode(ISD::ADD, dl, Off.getValueType(), Addr, Off); 3908 } 3909 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, Addr, 3910 MachinePointerInfo(&*FuncArg, j)); 3911 MemOps.push_back(Store); 3912 ++GPR_idx; 3913 } 3914 ArgOffset += ArgSize; 3915 continue; 3916 } 3917 3918 switch (ObjectVT.getSimpleVT().SimpleTy) { 3919 default: llvm_unreachable("Unhandled argument type!"); 3920 case MVT::i1: 3921 case MVT::i32: 3922 case MVT::i64: 3923 if (Flags.isNest()) { 3924 // The 'nest' parameter, if any, is passed in R11. 3925 unsigned VReg = MF.addLiveIn(PPC::X11, &PPC::G8RCRegClass); 3926 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 3927 3928 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1) 3929 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl); 3930 3931 break; 3932 } 3933 3934 // These can be scalar arguments or elements of an integer array type 3935 // passed directly. Clang may use those instead of "byval" aggregate 3936 // types to avoid forcing arguments to memory unnecessarily. 3937 if (GPR_idx != Num_GPR_Regs) { 3938 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass); 3939 FuncInfo->addLiveInAttr(VReg, Flags); 3940 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 3941 3942 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1) 3943 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote 3944 // value to MVT::i64 and then truncate to the correct register size. 3945 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl); 3946 } else { 3947 if (CallConv == CallingConv::Fast) 3948 ComputeArgOffset(); 3949 3950 needsLoad = true; 3951 ArgSize = PtrByteSize; 3952 } 3953 if (CallConv != CallingConv::Fast || needsLoad) 3954 ArgOffset += 8; 3955 break; 3956 3957 case MVT::f32: 3958 case MVT::f64: 3959 // These can be scalar arguments or elements of a float array type 3960 // passed directly. The latter are used to implement ELFv2 homogenous 3961 // float aggregates. 3962 if (FPR_idx != Num_FPR_Regs) { 3963 unsigned VReg; 3964 3965 if (ObjectVT == MVT::f32) 3966 VReg = MF.addLiveIn(FPR[FPR_idx], 3967 Subtarget.hasP8Vector() 3968 ? &PPC::VSSRCRegClass 3969 : &PPC::F4RCRegClass); 3970 else 3971 VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX() 3972 ? &PPC::VSFRCRegClass 3973 : &PPC::F8RCRegClass); 3974 3975 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 3976 ++FPR_idx; 3977 } else if (GPR_idx != Num_GPR_Regs && CallConv != CallingConv::Fast) { 3978 // FIXME: We may want to re-enable this for CallingConv::Fast on the P8 3979 // once we support fp <-> gpr moves. 3980 3981 // This can only ever happen in the presence of f32 array types, 3982 // since otherwise we never run out of FPRs before running out 3983 // of GPRs. 3984 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass); 3985 FuncInfo->addLiveInAttr(VReg, Flags); 3986 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 3987 3988 if (ObjectVT == MVT::f32) { 3989 if ((ArgOffset % PtrByteSize) == (isLittleEndian ? 4 : 0)) 3990 ArgVal = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgVal, 3991 DAG.getConstant(32, dl, MVT::i32)); 3992 ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal); 3993 } 3994 3995 ArgVal = DAG.getNode(ISD::BITCAST, dl, ObjectVT, ArgVal); 3996 } else { 3997 if (CallConv == CallingConv::Fast) 3998 ComputeArgOffset(); 3999 4000 needsLoad = true; 4001 } 4002 4003 // When passing an array of floats, the array occupies consecutive 4004 // space in the argument area; only round up to the next doubleword 4005 // at the end of the array. Otherwise, each float takes 8 bytes. 4006 if (CallConv != CallingConv::Fast || needsLoad) { 4007 ArgSize = Flags.isInConsecutiveRegs() ? ObjSize : PtrByteSize; 4008 ArgOffset += ArgSize; 4009 if (Flags.isInConsecutiveRegsLast()) 4010 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 4011 } 4012 break; 4013 case MVT::v4f32: 4014 case MVT::v4i32: 4015 case MVT::v8i16: 4016 case MVT::v16i8: 4017 case MVT::v2f64: 4018 case MVT::v2i64: 4019 case MVT::v1i128: 4020 case MVT::f128: 4021 if (!Subtarget.hasQPX()) { 4022 // These can be scalar arguments or elements of a vector array type 4023 // passed directly. The latter are used to implement ELFv2 homogenous 4024 // vector aggregates. 4025 if (VR_idx != Num_VR_Regs) { 4026 unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass); 4027 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 4028 ++VR_idx; 4029 } else { 4030 if (CallConv == CallingConv::Fast) 4031 ComputeArgOffset(); 4032 needsLoad = true; 4033 } 4034 if (CallConv != CallingConv::Fast || needsLoad) 4035 ArgOffset += 16; 4036 break; 4037 } // not QPX 4038 4039 assert(ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 && 4040 "Invalid QPX parameter type"); 4041 LLVM_FALLTHROUGH; 4042 4043 case MVT::v4f64: 4044 case MVT::v4i1: 4045 // QPX vectors are treated like their scalar floating-point subregisters 4046 // (except that they're larger). 4047 unsigned Sz = ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 ? 16 : 32; 4048 if (QFPR_idx != Num_QFPR_Regs) { 4049 const TargetRegisterClass *RC; 4050 switch (ObjectVT.getSimpleVT().SimpleTy) { 4051 case MVT::v4f64: RC = &PPC::QFRCRegClass; break; 4052 case MVT::v4f32: RC = &PPC::QSRCRegClass; break; 4053 default: RC = &PPC::QBRCRegClass; break; 4054 } 4055 4056 unsigned VReg = MF.addLiveIn(QFPR[QFPR_idx], RC); 4057 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 4058 ++QFPR_idx; 4059 } else { 4060 if (CallConv == CallingConv::Fast) 4061 ComputeArgOffset(); 4062 needsLoad = true; 4063 } 4064 if (CallConv != CallingConv::Fast || needsLoad) 4065 ArgOffset += Sz; 4066 break; 4067 } 4068 4069 // We need to load the argument to a virtual register if we determined 4070 // above that we ran out of physical registers of the appropriate type. 4071 if (needsLoad) { 4072 if (ObjSize < ArgSize && !isLittleEndian) 4073 CurArgOffset += ArgSize - ObjSize; 4074 int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, isImmutable); 4075 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4076 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo()); 4077 } 4078 4079 InVals.push_back(ArgVal); 4080 } 4081 4082 // Area that is at least reserved in the caller of this function. 4083 unsigned MinReservedArea; 4084 if (HasParameterArea) 4085 MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize); 4086 else 4087 MinReservedArea = LinkageSize; 4088 4089 // Set the size that is at least reserved in caller of this function. Tail 4090 // call optimized functions' reserved stack space needs to be aligned so that 4091 // taking the difference between two stack areas will result in an aligned 4092 // stack. 4093 MinReservedArea = 4094 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea); 4095 FuncInfo->setMinReservedArea(MinReservedArea); 4096 4097 // If the function takes variable number of arguments, make a frame index for 4098 // the start of the first vararg value... for expansion of llvm.va_start. 4099 if (isVarArg) { 4100 int Depth = ArgOffset; 4101 4102 FuncInfo->setVarArgsFrameIndex( 4103 MFI.CreateFixedObject(PtrByteSize, Depth, true)); 4104 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 4105 4106 // If this function is vararg, store any remaining integer argument regs 4107 // to their spots on the stack so that they may be loaded by dereferencing 4108 // the result of va_next. 4109 for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize; 4110 GPR_idx < Num_GPR_Regs; ++GPR_idx) { 4111 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4112 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4113 SDValue Store = 4114 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 4115 MemOps.push_back(Store); 4116 // Increment the address by four for the next argument to store 4117 SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT); 4118 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 4119 } 4120 } 4121 4122 if (!MemOps.empty()) 4123 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 4124 4125 return Chain; 4126 } 4127 4128 SDValue PPCTargetLowering::LowerFormalArguments_Darwin( 4129 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 4130 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 4131 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 4132 // TODO: add description of PPC stack frame format, or at least some docs. 4133 // 4134 MachineFunction &MF = DAG.getMachineFunction(); 4135 MachineFrameInfo &MFI = MF.getFrameInfo(); 4136 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 4137 4138 EVT PtrVT = getPointerTy(MF.getDataLayout()); 4139 bool isPPC64 = PtrVT == MVT::i64; 4140 // Potential tail calls could cause overwriting of argument stack slots. 4141 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt && 4142 (CallConv == CallingConv::Fast)); 4143 unsigned PtrByteSize = isPPC64 ? 8 : 4; 4144 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 4145 unsigned ArgOffset = LinkageSize; 4146 // Area that is at least reserved in caller of this function. 4147 unsigned MinReservedArea = ArgOffset; 4148 4149 static const MCPhysReg GPR_32[] = { // 32-bit registers. 4150 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 4151 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 4152 }; 4153 static const MCPhysReg GPR_64[] = { // 64-bit registers. 4154 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 4155 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 4156 }; 4157 static const MCPhysReg VR[] = { 4158 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 4159 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 4160 }; 4161 4162 const unsigned Num_GPR_Regs = array_lengthof(GPR_32); 4163 const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13; 4164 const unsigned Num_VR_Regs = array_lengthof( VR); 4165 4166 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 4167 4168 const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32; 4169 4170 // In 32-bit non-varargs functions, the stack space for vectors is after the 4171 // stack space for non-vectors. We do not use this space unless we have 4172 // too many vectors to fit in registers, something that only occurs in 4173 // constructed examples:), but we have to walk the arglist to figure 4174 // that out...for the pathological case, compute VecArgOffset as the 4175 // start of the vector parameter area. Computing VecArgOffset is the 4176 // entire point of the following loop. 4177 unsigned VecArgOffset = ArgOffset; 4178 if (!isVarArg && !isPPC64) { 4179 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; 4180 ++ArgNo) { 4181 EVT ObjectVT = Ins[ArgNo].VT; 4182 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags; 4183 4184 if (Flags.isByVal()) { 4185 // ObjSize is the true size, ArgSize rounded up to multiple of regs. 4186 unsigned ObjSize = Flags.getByValSize(); 4187 unsigned ArgSize = 4188 ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 4189 VecArgOffset += ArgSize; 4190 continue; 4191 } 4192 4193 switch(ObjectVT.getSimpleVT().SimpleTy) { 4194 default: llvm_unreachable("Unhandled argument type!"); 4195 case MVT::i1: 4196 case MVT::i32: 4197 case MVT::f32: 4198 VecArgOffset += 4; 4199 break; 4200 case MVT::i64: // PPC64 4201 case MVT::f64: 4202 // FIXME: We are guaranteed to be !isPPC64 at this point. 4203 // Does MVT::i64 apply? 4204 VecArgOffset += 8; 4205 break; 4206 case MVT::v4f32: 4207 case MVT::v4i32: 4208 case MVT::v8i16: 4209 case MVT::v16i8: 4210 // Nothing to do, we're only looking at Nonvector args here. 4211 break; 4212 } 4213 } 4214 } 4215 // We've found where the vector parameter area in memory is. Skip the 4216 // first 12 parameters; these don't use that memory. 4217 VecArgOffset = ((VecArgOffset+15)/16)*16; 4218 VecArgOffset += 12*16; 4219 4220 // Add DAG nodes to load the arguments or copy them out of registers. On 4221 // entry to a function on PPC, the arguments start after the linkage area, 4222 // although the first ones are often in registers. 4223 4224 SmallVector<SDValue, 8> MemOps; 4225 unsigned nAltivecParamsAtEnd = 0; 4226 Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin(); 4227 unsigned CurArgIdx = 0; 4228 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) { 4229 SDValue ArgVal; 4230 bool needsLoad = false; 4231 EVT ObjectVT = Ins[ArgNo].VT; 4232 unsigned ObjSize = ObjectVT.getSizeInBits()/8; 4233 unsigned ArgSize = ObjSize; 4234 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags; 4235 if (Ins[ArgNo].isOrigArg()) { 4236 std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx); 4237 CurArgIdx = Ins[ArgNo].getOrigArgIndex(); 4238 } 4239 unsigned CurArgOffset = ArgOffset; 4240 4241 // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary. 4242 if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 || 4243 ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) { 4244 if (isVarArg || isPPC64) { 4245 MinReservedArea = ((MinReservedArea+15)/16)*16; 4246 MinReservedArea += CalculateStackSlotSize(ObjectVT, 4247 Flags, 4248 PtrByteSize); 4249 } else nAltivecParamsAtEnd++; 4250 } else 4251 // Calculate min reserved area. 4252 MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT, 4253 Flags, 4254 PtrByteSize); 4255 4256 // FIXME the codegen can be much improved in some cases. 4257 // We do not have to keep everything in memory. 4258 if (Flags.isByVal()) { 4259 assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit"); 4260 4261 // ObjSize is the true size, ArgSize rounded up to multiple of registers. 4262 ObjSize = Flags.getByValSize(); 4263 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 4264 // Objects of size 1 and 2 are right justified, everything else is 4265 // left justified. This means the memory address is adjusted forwards. 4266 if (ObjSize==1 || ObjSize==2) { 4267 CurArgOffset = CurArgOffset + (4 - ObjSize); 4268 } 4269 // The value of the object is its address. 4270 int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, false, true); 4271 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4272 InVals.push_back(FIN); 4273 if (ObjSize==1 || ObjSize==2) { 4274 if (GPR_idx != Num_GPR_Regs) { 4275 unsigned VReg; 4276 if (isPPC64) 4277 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4278 else 4279 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 4280 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4281 EVT ObjType = ObjSize == 1 ? MVT::i8 : MVT::i16; 4282 SDValue Store = 4283 DAG.getTruncStore(Val.getValue(1), dl, Val, FIN, 4284 MachinePointerInfo(&*FuncArg), ObjType); 4285 MemOps.push_back(Store); 4286 ++GPR_idx; 4287 } 4288 4289 ArgOffset += PtrByteSize; 4290 4291 continue; 4292 } 4293 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) { 4294 // Store whatever pieces of the object are in registers 4295 // to memory. ArgOffset will be the address of the beginning 4296 // of the object. 4297 if (GPR_idx != Num_GPR_Regs) { 4298 unsigned VReg; 4299 if (isPPC64) 4300 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4301 else 4302 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 4303 int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true); 4304 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4305 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4306 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, 4307 MachinePointerInfo(&*FuncArg, j)); 4308 MemOps.push_back(Store); 4309 ++GPR_idx; 4310 ArgOffset += PtrByteSize; 4311 } else { 4312 ArgOffset += ArgSize - (ArgOffset-CurArgOffset); 4313 break; 4314 } 4315 } 4316 continue; 4317 } 4318 4319 switch (ObjectVT.getSimpleVT().SimpleTy) { 4320 default: llvm_unreachable("Unhandled argument type!"); 4321 case MVT::i1: 4322 case MVT::i32: 4323 if (!isPPC64) { 4324 if (GPR_idx != Num_GPR_Regs) { 4325 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 4326 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32); 4327 4328 if (ObjectVT == MVT::i1) 4329 ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgVal); 4330 4331 ++GPR_idx; 4332 } else { 4333 needsLoad = true; 4334 ArgSize = PtrByteSize; 4335 } 4336 // All int arguments reserve stack space in the Darwin ABI. 4337 ArgOffset += PtrByteSize; 4338 break; 4339 } 4340 LLVM_FALLTHROUGH; 4341 case MVT::i64: // PPC64 4342 if (GPR_idx != Num_GPR_Regs) { 4343 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4344 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 4345 4346 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1) 4347 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote 4348 // value to MVT::i64 and then truncate to the correct register size. 4349 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl); 4350 4351 ++GPR_idx; 4352 } else { 4353 needsLoad = true; 4354 ArgSize = PtrByteSize; 4355 } 4356 // All int arguments reserve stack space in the Darwin ABI. 4357 ArgOffset += 8; 4358 break; 4359 4360 case MVT::f32: 4361 case MVT::f64: 4362 // Every 4 bytes of argument space consumes one of the GPRs available for 4363 // argument passing. 4364 if (GPR_idx != Num_GPR_Regs) { 4365 ++GPR_idx; 4366 if (ObjSize == 8 && GPR_idx != Num_GPR_Regs && !isPPC64) 4367 ++GPR_idx; 4368 } 4369 if (FPR_idx != Num_FPR_Regs) { 4370 unsigned VReg; 4371 4372 if (ObjectVT == MVT::f32) 4373 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass); 4374 else 4375 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass); 4376 4377 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 4378 ++FPR_idx; 4379 } else { 4380 needsLoad = true; 4381 } 4382 4383 // All FP arguments reserve stack space in the Darwin ABI. 4384 ArgOffset += isPPC64 ? 8 : ObjSize; 4385 break; 4386 case MVT::v4f32: 4387 case MVT::v4i32: 4388 case MVT::v8i16: 4389 case MVT::v16i8: 4390 // Note that vector arguments in registers don't reserve stack space, 4391 // except in varargs functions. 4392 if (VR_idx != Num_VR_Regs) { 4393 unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass); 4394 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 4395 if (isVarArg) { 4396 while ((ArgOffset % 16) != 0) { 4397 ArgOffset += PtrByteSize; 4398 if (GPR_idx != Num_GPR_Regs) 4399 GPR_idx++; 4400 } 4401 ArgOffset += 16; 4402 GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64? 4403 } 4404 ++VR_idx; 4405 } else { 4406 if (!isVarArg && !isPPC64) { 4407 // Vectors go after all the nonvectors. 4408 CurArgOffset = VecArgOffset; 4409 VecArgOffset += 16; 4410 } else { 4411 // Vectors are aligned. 4412 ArgOffset = ((ArgOffset+15)/16)*16; 4413 CurArgOffset = ArgOffset; 4414 ArgOffset += 16; 4415 } 4416 needsLoad = true; 4417 } 4418 break; 4419 } 4420 4421 // We need to load the argument to a virtual register if we determined above 4422 // that we ran out of physical registers of the appropriate type. 4423 if (needsLoad) { 4424 int FI = MFI.CreateFixedObject(ObjSize, 4425 CurArgOffset + (ArgSize - ObjSize), 4426 isImmutable); 4427 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4428 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo()); 4429 } 4430 4431 InVals.push_back(ArgVal); 4432 } 4433 4434 // Allow for Altivec parameters at the end, if needed. 4435 if (nAltivecParamsAtEnd) { 4436 MinReservedArea = ((MinReservedArea+15)/16)*16; 4437 MinReservedArea += 16*nAltivecParamsAtEnd; 4438 } 4439 4440 // Area that is at least reserved in the caller of this function. 4441 MinReservedArea = std::max(MinReservedArea, LinkageSize + 8 * PtrByteSize); 4442 4443 // Set the size that is at least reserved in caller of this function. Tail 4444 // call optimized functions' reserved stack space needs to be aligned so that 4445 // taking the difference between two stack areas will result in an aligned 4446 // stack. 4447 MinReservedArea = 4448 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea); 4449 FuncInfo->setMinReservedArea(MinReservedArea); 4450 4451 // If the function takes variable number of arguments, make a frame index for 4452 // the start of the first vararg value... for expansion of llvm.va_start. 4453 if (isVarArg) { 4454 int Depth = ArgOffset; 4455 4456 FuncInfo->setVarArgsFrameIndex( 4457 MFI.CreateFixedObject(PtrVT.getSizeInBits()/8, 4458 Depth, true)); 4459 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 4460 4461 // If this function is vararg, store any remaining integer argument regs 4462 // to their spots on the stack so that they may be loaded by dereferencing 4463 // the result of va_next. 4464 for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) { 4465 unsigned VReg; 4466 4467 if (isPPC64) 4468 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4469 else 4470 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 4471 4472 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4473 SDValue Store = 4474 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 4475 MemOps.push_back(Store); 4476 // Increment the address by four for the next argument to store 4477 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT); 4478 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 4479 } 4480 } 4481 4482 if (!MemOps.empty()) 4483 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 4484 4485 return Chain; 4486 } 4487 4488 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be 4489 /// adjusted to accommodate the arguments for the tailcall. 4490 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall, 4491 unsigned ParamSize) { 4492 4493 if (!isTailCall) return 0; 4494 4495 PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>(); 4496 unsigned CallerMinReservedArea = FI->getMinReservedArea(); 4497 int SPDiff = (int)CallerMinReservedArea - (int)ParamSize; 4498 // Remember only if the new adjustment is bigger. 4499 if (SPDiff < FI->getTailCallSPDelta()) 4500 FI->setTailCallSPDelta(SPDiff); 4501 4502 return SPDiff; 4503 } 4504 4505 static bool isFunctionGlobalAddress(SDValue Callee); 4506 4507 static bool 4508 callsShareTOCBase(const Function *Caller, SDValue Callee, 4509 const TargetMachine &TM) { 4510 // Callee is either a GlobalAddress or an ExternalSymbol. ExternalSymbols 4511 // don't have enough information to determine if the caller and calle share 4512 // the same TOC base, so we have to pessimistically assume they don't for 4513 // correctness. 4514 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee); 4515 if (!G) 4516 return false; 4517 4518 const GlobalValue *GV = G->getGlobal(); 4519 // The medium and large code models are expected to provide a sufficiently 4520 // large TOC to provide all data addressing needs of a module with a 4521 // single TOC. Since each module will be addressed with a single TOC then we 4522 // only need to check that caller and callee don't cross dso boundaries. 4523 if (CodeModel::Medium == TM.getCodeModel() || 4524 CodeModel::Large == TM.getCodeModel()) 4525 return TM.shouldAssumeDSOLocal(*Caller->getParent(), GV); 4526 4527 // Otherwise we need to ensure callee and caller are in the same section, 4528 // since the linker may allocate multiple TOCs, and we don't know which 4529 // sections will belong to the same TOC base. 4530 4531 if (!GV->isStrongDefinitionForLinker()) 4532 return false; 4533 4534 // Any explicitly-specified sections and section prefixes must also match. 4535 // Also, if we're using -ffunction-sections, then each function is always in 4536 // a different section (the same is true for COMDAT functions). 4537 if (TM.getFunctionSections() || GV->hasComdat() || Caller->hasComdat() || 4538 GV->getSection() != Caller->getSection()) 4539 return false; 4540 if (const auto *F = dyn_cast<Function>(GV)) { 4541 if (F->getSectionPrefix() != Caller->getSectionPrefix()) 4542 return false; 4543 } 4544 4545 // If the callee might be interposed, then we can't assume the ultimate call 4546 // target will be in the same section. Even in cases where we can assume that 4547 // interposition won't happen, in any case where the linker might insert a 4548 // stub to allow for interposition, we must generate code as though 4549 // interposition might occur. To understand why this matters, consider a 4550 // situation where: a -> b -> c where the arrows indicate calls. b and c are 4551 // in the same section, but a is in a different module (i.e. has a different 4552 // TOC base pointer). If the linker allows for interposition between b and c, 4553 // then it will generate a stub for the call edge between b and c which will 4554 // save the TOC pointer into the designated stack slot allocated by b. If we 4555 // return true here, and therefore allow a tail call between b and c, that 4556 // stack slot won't exist and the b -> c stub will end up saving b'c TOC base 4557 // pointer into the stack slot allocated by a (where the a -> b stub saved 4558 // a's TOC base pointer). If we're not considering a tail call, but rather, 4559 // whether a nop is needed after the call instruction in b, because the linker 4560 // will insert a stub, it might complain about a missing nop if we omit it 4561 // (although many don't complain in this case). 4562 if (!TM.shouldAssumeDSOLocal(*Caller->getParent(), GV)) 4563 return false; 4564 4565 return true; 4566 } 4567 4568 static bool 4569 needStackSlotPassParameters(const PPCSubtarget &Subtarget, 4570 const SmallVectorImpl<ISD::OutputArg> &Outs) { 4571 assert(Subtarget.is64BitELFABI()); 4572 4573 const unsigned PtrByteSize = 8; 4574 const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 4575 4576 static const MCPhysReg GPR[] = { 4577 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 4578 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 4579 }; 4580 static const MCPhysReg VR[] = { 4581 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 4582 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 4583 }; 4584 4585 const unsigned NumGPRs = array_lengthof(GPR); 4586 const unsigned NumFPRs = 13; 4587 const unsigned NumVRs = array_lengthof(VR); 4588 const unsigned ParamAreaSize = NumGPRs * PtrByteSize; 4589 4590 unsigned NumBytes = LinkageSize; 4591 unsigned AvailableFPRs = NumFPRs; 4592 unsigned AvailableVRs = NumVRs; 4593 4594 for (const ISD::OutputArg& Param : Outs) { 4595 if (Param.Flags.isNest()) continue; 4596 4597 if (CalculateStackSlotUsed(Param.VT, Param.ArgVT, Param.Flags, 4598 PtrByteSize, LinkageSize, ParamAreaSize, 4599 NumBytes, AvailableFPRs, AvailableVRs, 4600 Subtarget.hasQPX())) 4601 return true; 4602 } 4603 return false; 4604 } 4605 4606 static bool 4607 hasSameArgumentList(const Function *CallerFn, ImmutableCallSite CS) { 4608 if (CS.arg_size() != CallerFn->arg_size()) 4609 return false; 4610 4611 ImmutableCallSite::arg_iterator CalleeArgIter = CS.arg_begin(); 4612 ImmutableCallSite::arg_iterator CalleeArgEnd = CS.arg_end(); 4613 Function::const_arg_iterator CallerArgIter = CallerFn->arg_begin(); 4614 4615 for (; CalleeArgIter != CalleeArgEnd; ++CalleeArgIter, ++CallerArgIter) { 4616 const Value* CalleeArg = *CalleeArgIter; 4617 const Value* CallerArg = &(*CallerArgIter); 4618 if (CalleeArg == CallerArg) 4619 continue; 4620 4621 // e.g. @caller([4 x i64] %a, [4 x i64] %b) { 4622 // tail call @callee([4 x i64] undef, [4 x i64] %b) 4623 // } 4624 // 1st argument of callee is undef and has the same type as caller. 4625 if (CalleeArg->getType() == CallerArg->getType() && 4626 isa<UndefValue>(CalleeArg)) 4627 continue; 4628 4629 return false; 4630 } 4631 4632 return true; 4633 } 4634 4635 // Returns true if TCO is possible between the callers and callees 4636 // calling conventions. 4637 static bool 4638 areCallingConvEligibleForTCO_64SVR4(CallingConv::ID CallerCC, 4639 CallingConv::ID CalleeCC) { 4640 // Tail calls are possible with fastcc and ccc. 4641 auto isTailCallableCC = [] (CallingConv::ID CC){ 4642 return CC == CallingConv::C || CC == CallingConv::Fast; 4643 }; 4644 if (!isTailCallableCC(CallerCC) || !isTailCallableCC(CalleeCC)) 4645 return false; 4646 4647 // We can safely tail call both fastcc and ccc callees from a c calling 4648 // convention caller. If the caller is fastcc, we may have less stack space 4649 // than a non-fastcc caller with the same signature so disable tail-calls in 4650 // that case. 4651 return CallerCC == CallingConv::C || CallerCC == CalleeCC; 4652 } 4653 4654 bool 4655 PPCTargetLowering::IsEligibleForTailCallOptimization_64SVR4( 4656 SDValue Callee, 4657 CallingConv::ID CalleeCC, 4658 ImmutableCallSite CS, 4659 bool isVarArg, 4660 const SmallVectorImpl<ISD::OutputArg> &Outs, 4661 const SmallVectorImpl<ISD::InputArg> &Ins, 4662 SelectionDAG& DAG) const { 4663 bool TailCallOpt = getTargetMachine().Options.GuaranteedTailCallOpt; 4664 4665 if (DisableSCO && !TailCallOpt) return false; 4666 4667 // Variadic argument functions are not supported. 4668 if (isVarArg) return false; 4669 4670 auto &Caller = DAG.getMachineFunction().getFunction(); 4671 // Check that the calling conventions are compatible for tco. 4672 if (!areCallingConvEligibleForTCO_64SVR4(Caller.getCallingConv(), CalleeCC)) 4673 return false; 4674 4675 // Caller contains any byval parameter is not supported. 4676 if (any_of(Ins, [](const ISD::InputArg &IA) { return IA.Flags.isByVal(); })) 4677 return false; 4678 4679 // Callee contains any byval parameter is not supported, too. 4680 // Note: This is a quick work around, because in some cases, e.g. 4681 // caller's stack size > callee's stack size, we are still able to apply 4682 // sibling call optimization. For example, gcc is able to do SCO for caller1 4683 // in the following example, but not for caller2. 4684 // struct test { 4685 // long int a; 4686 // char ary[56]; 4687 // } gTest; 4688 // __attribute__((noinline)) int callee(struct test v, struct test *b) { 4689 // b->a = v.a; 4690 // return 0; 4691 // } 4692 // void caller1(struct test a, struct test c, struct test *b) { 4693 // callee(gTest, b); } 4694 // void caller2(struct test *b) { callee(gTest, b); } 4695 if (any_of(Outs, [](const ISD::OutputArg& OA) { return OA.Flags.isByVal(); })) 4696 return false; 4697 4698 // If callee and caller use different calling conventions, we cannot pass 4699 // parameters on stack since offsets for the parameter area may be different. 4700 if (Caller.getCallingConv() != CalleeCC && 4701 needStackSlotPassParameters(Subtarget, Outs)) 4702 return false; 4703 4704 // No TCO/SCO on indirect call because Caller have to restore its TOC 4705 if (!isFunctionGlobalAddress(Callee) && 4706 !isa<ExternalSymbolSDNode>(Callee)) 4707 return false; 4708 4709 // If the caller and callee potentially have different TOC bases then we 4710 // cannot tail call since we need to restore the TOC pointer after the call. 4711 // ref: https://bugzilla.mozilla.org/show_bug.cgi?id=973977 4712 if (!callsShareTOCBase(&Caller, Callee, getTargetMachine())) 4713 return false; 4714 4715 // TCO allows altering callee ABI, so we don't have to check further. 4716 if (CalleeCC == CallingConv::Fast && TailCallOpt) 4717 return true; 4718 4719 if (DisableSCO) return false; 4720 4721 // If callee use the same argument list that caller is using, then we can 4722 // apply SCO on this case. If it is not, then we need to check if callee needs 4723 // stack for passing arguments. 4724 if (!hasSameArgumentList(&Caller, CS) && 4725 needStackSlotPassParameters(Subtarget, Outs)) { 4726 return false; 4727 } 4728 4729 return true; 4730 } 4731 4732 /// IsEligibleForTailCallOptimization - Check whether the call is eligible 4733 /// for tail call optimization. Targets which want to do tail call 4734 /// optimization should implement this function. 4735 bool 4736 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee, 4737 CallingConv::ID CalleeCC, 4738 bool isVarArg, 4739 const SmallVectorImpl<ISD::InputArg> &Ins, 4740 SelectionDAG& DAG) const { 4741 if (!getTargetMachine().Options.GuaranteedTailCallOpt) 4742 return false; 4743 4744 // Variable argument functions are not supported. 4745 if (isVarArg) 4746 return false; 4747 4748 MachineFunction &MF = DAG.getMachineFunction(); 4749 CallingConv::ID CallerCC = MF.getFunction().getCallingConv(); 4750 if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) { 4751 // Functions containing by val parameters are not supported. 4752 for (unsigned i = 0; i != Ins.size(); i++) { 4753 ISD::ArgFlagsTy Flags = Ins[i].Flags; 4754 if (Flags.isByVal()) return false; 4755 } 4756 4757 // Non-PIC/GOT tail calls are supported. 4758 if (getTargetMachine().getRelocationModel() != Reloc::PIC_) 4759 return true; 4760 4761 // At the moment we can only do local tail calls (in same module, hidden 4762 // or protected) if we are generating PIC. 4763 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) 4764 return G->getGlobal()->hasHiddenVisibility() 4765 || G->getGlobal()->hasProtectedVisibility(); 4766 } 4767 4768 return false; 4769 } 4770 4771 /// isCallCompatibleAddress - Return the immediate to use if the specified 4772 /// 32-bit value is representable in the immediate field of a BxA instruction. 4773 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) { 4774 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op); 4775 if (!C) return nullptr; 4776 4777 int Addr = C->getZExtValue(); 4778 if ((Addr & 3) != 0 || // Low 2 bits are implicitly zero. 4779 SignExtend32<26>(Addr) != Addr) 4780 return nullptr; // Top 6 bits have to be sext of immediate. 4781 4782 return DAG 4783 .getConstant( 4784 (int)C->getZExtValue() >> 2, SDLoc(Op), 4785 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout())) 4786 .getNode(); 4787 } 4788 4789 namespace { 4790 4791 struct TailCallArgumentInfo { 4792 SDValue Arg; 4793 SDValue FrameIdxOp; 4794 int FrameIdx = 0; 4795 4796 TailCallArgumentInfo() = default; 4797 }; 4798 4799 } // end anonymous namespace 4800 4801 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot. 4802 static void StoreTailCallArgumentsToStackSlot( 4803 SelectionDAG &DAG, SDValue Chain, 4804 const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs, 4805 SmallVectorImpl<SDValue> &MemOpChains, const SDLoc &dl) { 4806 for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) { 4807 SDValue Arg = TailCallArgs[i].Arg; 4808 SDValue FIN = TailCallArgs[i].FrameIdxOp; 4809 int FI = TailCallArgs[i].FrameIdx; 4810 // Store relative to framepointer. 4811 MemOpChains.push_back(DAG.getStore( 4812 Chain, dl, Arg, FIN, 4813 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI))); 4814 } 4815 } 4816 4817 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to 4818 /// the appropriate stack slot for the tail call optimized function call. 4819 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG, SDValue Chain, 4820 SDValue OldRetAddr, SDValue OldFP, 4821 int SPDiff, const SDLoc &dl) { 4822 if (SPDiff) { 4823 // Calculate the new stack slot for the return address. 4824 MachineFunction &MF = DAG.getMachineFunction(); 4825 const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>(); 4826 const PPCFrameLowering *FL = Subtarget.getFrameLowering(); 4827 bool isPPC64 = Subtarget.isPPC64(); 4828 int SlotSize = isPPC64 ? 8 : 4; 4829 int NewRetAddrLoc = SPDiff + FL->getReturnSaveOffset(); 4830 int NewRetAddr = MF.getFrameInfo().CreateFixedObject(SlotSize, 4831 NewRetAddrLoc, true); 4832 EVT VT = isPPC64 ? MVT::i64 : MVT::i32; 4833 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT); 4834 Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx, 4835 MachinePointerInfo::getFixedStack(MF, NewRetAddr)); 4836 4837 // When using the 32/64-bit SVR4 ABI there is no need to move the FP stack 4838 // slot as the FP is never overwritten. 4839 if (Subtarget.isDarwinABI()) { 4840 int NewFPLoc = SPDiff + FL->getFramePointerSaveOffset(); 4841 int NewFPIdx = MF.getFrameInfo().CreateFixedObject(SlotSize, NewFPLoc, 4842 true); 4843 SDValue NewFramePtrIdx = DAG.getFrameIndex(NewFPIdx, VT); 4844 Chain = DAG.getStore(Chain, dl, OldFP, NewFramePtrIdx, 4845 MachinePointerInfo::getFixedStack( 4846 DAG.getMachineFunction(), NewFPIdx)); 4847 } 4848 } 4849 return Chain; 4850 } 4851 4852 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate 4853 /// the position of the argument. 4854 static void 4855 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64, 4856 SDValue Arg, int SPDiff, unsigned ArgOffset, 4857 SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) { 4858 int Offset = ArgOffset + SPDiff; 4859 uint32_t OpSize = (Arg.getValueSizeInBits() + 7) / 8; 4860 int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true); 4861 EVT VT = isPPC64 ? MVT::i64 : MVT::i32; 4862 SDValue FIN = DAG.getFrameIndex(FI, VT); 4863 TailCallArgumentInfo Info; 4864 Info.Arg = Arg; 4865 Info.FrameIdxOp = FIN; 4866 Info.FrameIdx = FI; 4867 TailCallArguments.push_back(Info); 4868 } 4869 4870 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address 4871 /// stack slot. Returns the chain as result and the loaded frame pointers in 4872 /// LROpOut/FPOpout. Used when tail calling. 4873 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr( 4874 SelectionDAG &DAG, int SPDiff, SDValue Chain, SDValue &LROpOut, 4875 SDValue &FPOpOut, const SDLoc &dl) const { 4876 if (SPDiff) { 4877 // Load the LR and FP stack slot for later adjusting. 4878 EVT VT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32; 4879 LROpOut = getReturnAddrFrameIndex(DAG); 4880 LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo()); 4881 Chain = SDValue(LROpOut.getNode(), 1); 4882 4883 // When using the 32/64-bit SVR4 ABI there is no need to load the FP stack 4884 // slot as the FP is never overwritten. 4885 if (Subtarget.isDarwinABI()) { 4886 FPOpOut = getFramePointerFrameIndex(DAG); 4887 FPOpOut = DAG.getLoad(VT, dl, Chain, FPOpOut, MachinePointerInfo()); 4888 Chain = SDValue(FPOpOut.getNode(), 1); 4889 } 4890 } 4891 return Chain; 4892 } 4893 4894 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified 4895 /// by "Src" to address "Dst" of size "Size". Alignment information is 4896 /// specified by the specific parameter attribute. The copy will be passed as 4897 /// a byval function parameter. 4898 /// Sometimes what we are copying is the end of a larger object, the part that 4899 /// does not fit in registers. 4900 static SDValue CreateCopyOfByValArgument(SDValue Src, SDValue Dst, 4901 SDValue Chain, ISD::ArgFlagsTy Flags, 4902 SelectionDAG &DAG, const SDLoc &dl) { 4903 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32); 4904 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(), 4905 false, false, false, MachinePointerInfo(), 4906 MachinePointerInfo()); 4907 } 4908 4909 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of 4910 /// tail calls. 4911 static void LowerMemOpCallTo( 4912 SelectionDAG &DAG, MachineFunction &MF, SDValue Chain, SDValue Arg, 4913 SDValue PtrOff, int SPDiff, unsigned ArgOffset, bool isPPC64, 4914 bool isTailCall, bool isVector, SmallVectorImpl<SDValue> &MemOpChains, 4915 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments, const SDLoc &dl) { 4916 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 4917 if (!isTailCall) { 4918 if (isVector) { 4919 SDValue StackPtr; 4920 if (isPPC64) 4921 StackPtr = DAG.getRegister(PPC::X1, MVT::i64); 4922 else 4923 StackPtr = DAG.getRegister(PPC::R1, MVT::i32); 4924 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, 4925 DAG.getConstant(ArgOffset, dl, PtrVT)); 4926 } 4927 MemOpChains.push_back( 4928 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo())); 4929 // Calculate and remember argument location. 4930 } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset, 4931 TailCallArguments); 4932 } 4933 4934 static void 4935 PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain, 4936 const SDLoc &dl, int SPDiff, unsigned NumBytes, SDValue LROp, 4937 SDValue FPOp, 4938 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) { 4939 // Emit a sequence of copyto/copyfrom virtual registers for arguments that 4940 // might overwrite each other in case of tail call optimization. 4941 SmallVector<SDValue, 8> MemOpChains2; 4942 // Do not flag preceding copytoreg stuff together with the following stuff. 4943 InFlag = SDValue(); 4944 StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments, 4945 MemOpChains2, dl); 4946 if (!MemOpChains2.empty()) 4947 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2); 4948 4949 // Store the return address to the appropriate stack slot. 4950 Chain = EmitTailCallStoreFPAndRetAddr(DAG, Chain, LROp, FPOp, SPDiff, dl); 4951 4952 // Emit callseq_end just before tailcall node. 4953 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true), 4954 DAG.getIntPtrConstant(0, dl, true), InFlag, dl); 4955 InFlag = Chain.getValue(1); 4956 } 4957 4958 // Is this global address that of a function that can be called by name? (as 4959 // opposed to something that must hold a descriptor for an indirect call). 4960 static bool isFunctionGlobalAddress(SDValue Callee) { 4961 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 4962 if (Callee.getOpcode() == ISD::GlobalTLSAddress || 4963 Callee.getOpcode() == ISD::TargetGlobalTLSAddress) 4964 return false; 4965 4966 return G->getGlobal()->getValueType()->isFunctionTy(); 4967 } 4968 4969 return false; 4970 } 4971 4972 SDValue PPCTargetLowering::LowerCallResult( 4973 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg, 4974 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 4975 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 4976 SmallVector<CCValAssign, 16> RVLocs; 4977 CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 4978 *DAG.getContext()); 4979 4980 CCRetInfo.AnalyzeCallResult( 4981 Ins, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold) 4982 ? RetCC_PPC_Cold 4983 : RetCC_PPC); 4984 4985 // Copy all of the result registers out of their specified physreg. 4986 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) { 4987 CCValAssign &VA = RVLocs[i]; 4988 assert(VA.isRegLoc() && "Can only return in registers!"); 4989 4990 SDValue Val; 4991 4992 if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) { 4993 SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, 4994 InFlag); 4995 Chain = Lo.getValue(1); 4996 InFlag = Lo.getValue(2); 4997 VA = RVLocs[++i]; // skip ahead to next loc 4998 SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, 4999 InFlag); 5000 Chain = Hi.getValue(1); 5001 InFlag = Hi.getValue(2); 5002 if (!Subtarget.isLittleEndian()) 5003 std::swap (Lo, Hi); 5004 Val = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, Lo, Hi); 5005 } else { 5006 Val = DAG.getCopyFromReg(Chain, dl, 5007 VA.getLocReg(), VA.getLocVT(), InFlag); 5008 Chain = Val.getValue(1); 5009 InFlag = Val.getValue(2); 5010 } 5011 5012 switch (VA.getLocInfo()) { 5013 default: llvm_unreachable("Unknown loc info!"); 5014 case CCValAssign::Full: break; 5015 case CCValAssign::AExt: 5016 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val); 5017 break; 5018 case CCValAssign::ZExt: 5019 Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val, 5020 DAG.getValueType(VA.getValVT())); 5021 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val); 5022 break; 5023 case CCValAssign::SExt: 5024 Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val, 5025 DAG.getValueType(VA.getValVT())); 5026 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val); 5027 break; 5028 } 5029 5030 InVals.push_back(Val); 5031 } 5032 5033 return Chain; 5034 } 5035 5036 static bool isIndirectCall(const SDValue &Callee, SelectionDAG &DAG, 5037 const PPCSubtarget &Subtarget, bool isPatchPoint) { 5038 // PatchPoint calls are not indirect. 5039 if (isPatchPoint) 5040 return false; 5041 5042 if (isFunctionGlobalAddress(Callee) || dyn_cast<ExternalSymbolSDNode>(Callee)) 5043 return false; 5044 5045 // Darwin, and 32-bit ELF can use a BLA. The descriptor based ABIs can not 5046 // becuase the immediate function pointer points to a descriptor instead of 5047 // a function entry point. The ELFv2 ABI cannot use a BLA because the function 5048 // pointer immediate points to the global entry point, while the BLA would 5049 // need to jump to the local entry point (see rL211174). 5050 if (!Subtarget.usesFunctionDescriptors() && !Subtarget.isELFv2ABI() && 5051 isBLACompatibleAddress(Callee, DAG)) 5052 return false; 5053 5054 return true; 5055 } 5056 5057 static unsigned getCallOpcode(bool isIndirectCall, bool isPatchPoint, 5058 bool isTailCall, const Function &Caller, 5059 const SDValue &Callee, 5060 const PPCSubtarget &Subtarget, 5061 const TargetMachine &TM) { 5062 if (isTailCall) 5063 return PPCISD::TC_RETURN; 5064 5065 // This is a call through a function pointer. 5066 if (isIndirectCall) { 5067 // AIX and the 64-bit ELF ABIs need to maintain the TOC pointer accross 5068 // indirect calls. The save of the caller's TOC pointer to the stack will be 5069 // inserted into the DAG as part of call lowering. The restore of the TOC 5070 // pointer is modeled by using a pseudo instruction for the call opcode that 5071 // represents the 2 instruction sequence of an indirect branch and link, 5072 // immediately followed by a load of the TOC pointer from the the stack save 5073 // slot into gpr2. 5074 if (Subtarget.isAIXABI() || Subtarget.is64BitELFABI()) 5075 return PPCISD::BCTRL_LOAD_TOC; 5076 5077 // An indirect call that does not need a TOC restore. 5078 return PPCISD::BCTRL; 5079 } 5080 5081 // The ABIs that maintain a TOC pointer accross calls need to have a nop 5082 // immediately following the call instruction if the caller and callee may 5083 // have different TOC bases. At link time if the linker determines the calls 5084 // may not share a TOC base, the call is redirected to a trampoline inserted 5085 // by the linker. The trampoline will (among other things) save the callers 5086 // TOC pointer at an ABI designated offset in the linkage area and the linker 5087 // will rewrite the nop to be a load of the TOC pointer from the linkage area 5088 // into gpr2. 5089 if (Subtarget.isAIXABI() || Subtarget.is64BitELFABI()) 5090 return callsShareTOCBase(&Caller, Callee, TM) ? PPCISD::CALL 5091 : PPCISD::CALL_NOP; 5092 5093 return PPCISD::CALL; 5094 } 5095 static SDValue transformCallee(const SDValue &Callee, SelectionDAG &DAG, 5096 const SDLoc &dl, const PPCSubtarget &Subtarget) { 5097 if (!Subtarget.usesFunctionDescriptors() && !Subtarget.isELFv2ABI()) 5098 if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG)) 5099 return SDValue(Dest, 0); 5100 5101 // Returns true if the callee is local, and false otherwise. 5102 auto isLocalCallee = [&]() { 5103 const GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee); 5104 const Module *Mod = DAG.getMachineFunction().getFunction().getParent(); 5105 5106 return DAG.getTarget().shouldAssumeDSOLocal(*Mod, 5107 G ? G->getGlobal() : nullptr); 5108 }; 5109 5110 // The PLT is only used in 32-bit ELF PIC mode. Attempting to use the PLT in 5111 // a static relocation model causes some versions of GNU LD (2.17.50, at 5112 // least) to force BSS-PLT, instead of secure-PLT, even if all objects are 5113 // built with secure-PLT. 5114 bool UsePlt = 5115 Subtarget.is32BitELFABI() && !isLocalCallee() && 5116 Subtarget.getTargetMachine().getRelocationModel() == Reloc::PIC_; 5117 5118 if (isFunctionGlobalAddress(Callee)) { 5119 const GlobalAddressSDNode *G = cast<GlobalAddressSDNode>(Callee); 5120 if (!Subtarget.isAIXABI()) 5121 return DAG.getTargetGlobalAddress(G->getGlobal(), dl, 5122 Callee.getValueType(), 0, 5123 UsePlt ? PPCII::MO_PLT : 0); 5124 5125 // On AIX, direct function calls reference the symbol for the function's 5126 // entry point, which is named by prepending a "." before the function's 5127 // C-linkage name. 5128 auto &Context = DAG.getMachineFunction().getMMI().getContext(); 5129 5130 const GlobalObject *GO = cast<GlobalObject>(G->getGlobal()); 5131 MCSymbolXCOFF *S = cast<MCSymbolXCOFF>( 5132 Context.getOrCreateSymbol(Twine(".") + Twine(GO->getName()))); 5133 5134 if (GO && GO->isDeclaration() && !S->hasContainingCsect()) { 5135 // On AIX, an undefined symbol needs to be associated with a 5136 // MCSectionXCOFF to get the correct storage mapping class. 5137 // In this case, XCOFF::XMC_PR. 5138 const XCOFF::StorageClass SC = 5139 TargetLoweringObjectFileXCOFF::getStorageClassForGlobal(GO); 5140 MCSectionXCOFF *Sec = 5141 Context.getXCOFFSection(S->getName(), XCOFF::XMC_PR, XCOFF::XTY_ER, 5142 SC, SectionKind::getMetadata()); 5143 S->setContainingCsect(Sec); 5144 } 5145 5146 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 5147 return DAG.getMCSymbol(S, PtrVT); 5148 } 5149 5150 if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) 5151 return DAG.getTargetExternalSymbol(S->getSymbol(), Callee.getValueType(), 5152 UsePlt ? PPCII::MO_PLT : 0); 5153 5154 // No transformation needed. 5155 assert(Callee.getNode() && "What no callee?"); 5156 return Callee; 5157 } 5158 5159 static SDValue getOutputChainFromCallSeq(SDValue CallSeqStart) { 5160 assert(CallSeqStart.getOpcode() == ISD::CALLSEQ_START && 5161 "Expected a CALLSEQ_STARTSDNode."); 5162 5163 // The last operand is the chain, except when the node has glue. If the node 5164 // has glue, then the last operand is the glue, and the chain is the second 5165 // last operand. 5166 SDValue LastValue = CallSeqStart.getValue(CallSeqStart->getNumValues() - 1); 5167 if (LastValue.getValueType() != MVT::Glue) 5168 return LastValue; 5169 5170 return CallSeqStart.getValue(CallSeqStart->getNumValues() - 2); 5171 } 5172 5173 // Creates the node that moves a functions address into the count register 5174 // to prepare for an indirect call instruction. 5175 static void prepareIndirectCall(SelectionDAG &DAG, SDValue &Callee, 5176 SDValue &Glue, SDValue &Chain, 5177 const SDLoc &dl) { 5178 SDValue MTCTROps[] = {Chain, Callee, Glue}; 5179 EVT ReturnTypes[] = {MVT::Other, MVT::Glue}; 5180 Chain = DAG.getNode(PPCISD::MTCTR, dl, makeArrayRef(ReturnTypes, 2), 5181 makeArrayRef(MTCTROps, Glue.getNode() ? 3 : 2)); 5182 // The glue is the second value produced. 5183 Glue = Chain.getValue(1); 5184 } 5185 5186 static void prepareDescriptorIndirectCall(SelectionDAG &DAG, SDValue &Callee, 5187 SDValue &Glue, SDValue &Chain, 5188 SDValue CallSeqStart, 5189 ImmutableCallSite CS, const SDLoc &dl, 5190 bool hasNest, 5191 const PPCSubtarget &Subtarget) { 5192 // Function pointers in the 64-bit SVR4 ABI do not point to the function 5193 // entry point, but to the function descriptor (the function entry point 5194 // address is part of the function descriptor though). 5195 // The function descriptor is a three doubleword structure with the 5196 // following fields: function entry point, TOC base address and 5197 // environment pointer. 5198 // Thus for a call through a function pointer, the following actions need 5199 // to be performed: 5200 // 1. Save the TOC of the caller in the TOC save area of its stack 5201 // frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()). 5202 // 2. Load the address of the function entry point from the function 5203 // descriptor. 5204 // 3. Load the TOC of the callee from the function descriptor into r2. 5205 // 4. Load the environment pointer from the function descriptor into 5206 // r11. 5207 // 5. Branch to the function entry point address. 5208 // 6. On return of the callee, the TOC of the caller needs to be 5209 // restored (this is done in FinishCall()). 5210 // 5211 // The loads are scheduled at the beginning of the call sequence, and the 5212 // register copies are flagged together to ensure that no other 5213 // operations can be scheduled in between. E.g. without flagging the 5214 // copies together, a TOC access in the caller could be scheduled between 5215 // the assignment of the callee TOC and the branch to the callee, which leads 5216 // to incorrect code. 5217 5218 // Start by loading the function address from the descriptor. 5219 SDValue LDChain = getOutputChainFromCallSeq(CallSeqStart); 5220 auto MMOFlags = Subtarget.hasInvariantFunctionDescriptors() 5221 ? (MachineMemOperand::MODereferenceable | 5222 MachineMemOperand::MOInvariant) 5223 : MachineMemOperand::MONone; 5224 5225 MachinePointerInfo MPI(CS ? CS.getCalledValue() : nullptr); 5226 5227 // Registers used in building the DAG. 5228 const MCRegister EnvPtrReg = Subtarget.getEnvironmentPointerRegister(); 5229 const MCRegister TOCReg = Subtarget.getTOCPointerRegister(); 5230 5231 // Offsets of descriptor members. 5232 const unsigned TOCAnchorOffset = Subtarget.descriptorTOCAnchorOffset(); 5233 const unsigned EnvPtrOffset = Subtarget.descriptorEnvironmentPointerOffset(); 5234 5235 const MVT RegVT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32; 5236 const unsigned Alignment = Subtarget.isPPC64() ? 8 : 4; 5237 5238 // One load for the functions entry point address. 5239 SDValue LoadFuncPtr = DAG.getLoad(RegVT, dl, LDChain, Callee, MPI, 5240 Alignment, MMOFlags); 5241 5242 // One for loading the TOC anchor for the module that contains the called 5243 // function. 5244 SDValue TOCOff = DAG.getIntPtrConstant(TOCAnchorOffset, dl); 5245 SDValue AddTOC = DAG.getNode(ISD::ADD, dl, RegVT, Callee, TOCOff); 5246 SDValue TOCPtr = 5247 DAG.getLoad(RegVT, dl, LDChain, AddTOC, 5248 MPI.getWithOffset(TOCAnchorOffset), Alignment, MMOFlags); 5249 5250 // One for loading the environment pointer. 5251 SDValue PtrOff = DAG.getIntPtrConstant(EnvPtrOffset, dl); 5252 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, RegVT, Callee, PtrOff); 5253 SDValue LoadEnvPtr = 5254 DAG.getLoad(RegVT, dl, LDChain, AddPtr, 5255 MPI.getWithOffset(EnvPtrOffset), Alignment, MMOFlags); 5256 5257 5258 // Then copy the newly loaded TOC anchor to the TOC pointer. 5259 SDValue TOCVal = DAG.getCopyToReg(Chain, dl, TOCReg, TOCPtr, Glue); 5260 Chain = TOCVal.getValue(0); 5261 Glue = TOCVal.getValue(1); 5262 5263 // If the function call has an explicit 'nest' parameter, it takes the 5264 // place of the environment pointer. 5265 assert((!hasNest || !Subtarget.isAIXABI()) && 5266 "Nest parameter is not supported on AIX."); 5267 if (!hasNest) { 5268 SDValue EnvVal = DAG.getCopyToReg(Chain, dl, EnvPtrReg, LoadEnvPtr, Glue); 5269 Chain = EnvVal.getValue(0); 5270 Glue = EnvVal.getValue(1); 5271 } 5272 5273 // The rest of the indirect call sequence is the same as the non-descriptor 5274 // DAG. 5275 prepareIndirectCall(DAG, LoadFuncPtr, Glue, Chain, dl); 5276 } 5277 5278 static void 5279 buildCallOperands(SmallVectorImpl<SDValue> &Ops, CallingConv::ID CallConv, 5280 const SDLoc &dl, bool isTailCall, bool isVarArg, 5281 bool isPatchPoint, bool hasNest, SelectionDAG &DAG, 5282 SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, 5283 SDValue Glue, SDValue Chain, SDValue &Callee, int SPDiff, 5284 const PPCSubtarget &Subtarget, bool isIndirect) { 5285 const bool IsPPC64 = Subtarget.isPPC64(); 5286 // MVT for a general purpose register. 5287 const MVT RegVT = IsPPC64 ? MVT::i64 : MVT::i32; 5288 5289 // First operand is always the chain. 5290 Ops.push_back(Chain); 5291 5292 // If it's a direct call pass the callee as the second operand. 5293 if (!isIndirect) 5294 Ops.push_back(Callee); 5295 else { 5296 assert(!isPatchPoint && "Patch point call are not indirect."); 5297 5298 // For the TOC based ABIs, we have saved the TOC pointer to the linkage area 5299 // on the stack (this would have been done in `LowerCall_64SVR4` or 5300 // `LowerCall_AIX`). The call instruction is a pseudo instruction that 5301 // represents both the indirect branch and a load that restores the TOC 5302 // pointer from the linkage area. The operand for the TOC restore is an add 5303 // of the TOC save offset to the stack pointer. This must be the second 5304 // operand: after the chain input but before any other variadic arguments. 5305 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) { 5306 const MCRegister StackPtrReg = Subtarget.getStackPointerRegister(); 5307 5308 SDValue StackPtr = DAG.getRegister(StackPtrReg, RegVT); 5309 unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset(); 5310 SDValue TOCOff = DAG.getIntPtrConstant(TOCSaveOffset, dl); 5311 SDValue AddTOC = DAG.getNode(ISD::ADD, dl, RegVT, StackPtr, TOCOff); 5312 Ops.push_back(AddTOC); 5313 } 5314 5315 // Add the register used for the environment pointer. 5316 if (Subtarget.usesFunctionDescriptors() && !hasNest) 5317 Ops.push_back(DAG.getRegister(Subtarget.getEnvironmentPointerRegister(), 5318 RegVT)); 5319 5320 5321 // Add CTR register as callee so a bctr can be emitted later. 5322 if (isTailCall) 5323 Ops.push_back(DAG.getRegister(IsPPC64 ? PPC::CTR8 : PPC::CTR, RegVT)); 5324 } 5325 5326 // If this is a tail call add stack pointer delta. 5327 if (isTailCall) 5328 Ops.push_back(DAG.getConstant(SPDiff, dl, MVT::i32)); 5329 5330 // Add argument registers to the end of the list so that they are known live 5331 // into the call. 5332 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) 5333 Ops.push_back(DAG.getRegister(RegsToPass[i].first, 5334 RegsToPass[i].second.getValueType())); 5335 5336 // We cannot add R2/X2 as an operand here for PATCHPOINT, because there is 5337 // no way to mark dependencies as implicit here. 5338 // We will add the R2/X2 dependency in EmitInstrWithCustomInserter. 5339 if ((Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) && !isPatchPoint) 5340 Ops.push_back(DAG.getRegister(Subtarget.getTOCPointerRegister(), RegVT)); 5341 5342 // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls 5343 if (isVarArg && Subtarget.is32BitELFABI()) 5344 Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32)); 5345 5346 // Add a register mask operand representing the call-preserved registers. 5347 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo(); 5348 const uint32_t *Mask = 5349 TRI->getCallPreservedMask(DAG.getMachineFunction(), CallConv); 5350 assert(Mask && "Missing call preserved mask for calling convention"); 5351 Ops.push_back(DAG.getRegisterMask(Mask)); 5352 5353 // If the glue is valid, it is the last operand. 5354 if (Glue.getNode()) 5355 Ops.push_back(Glue); 5356 } 5357 5358 SDValue PPCTargetLowering::FinishCall( 5359 CallingConv::ID CallConv, const SDLoc &dl, bool isTailCall, bool isVarArg, 5360 bool isPatchPoint, bool hasNest, SelectionDAG &DAG, 5361 SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, SDValue Glue, 5362 SDValue Chain, SDValue CallSeqStart, SDValue &Callee, int SPDiff, 5363 unsigned NumBytes, const SmallVectorImpl<ISD::InputArg> &Ins, 5364 SmallVectorImpl<SDValue> &InVals, ImmutableCallSite CS) const { 5365 5366 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) 5367 setUsesTOCBasePtr(DAG); 5368 5369 const bool isIndirect = isIndirectCall(Callee, DAG, Subtarget, isPatchPoint); 5370 unsigned CallOpc = getCallOpcode(isIndirect, isPatchPoint, isTailCall, 5371 DAG.getMachineFunction().getFunction(), 5372 Callee, Subtarget, DAG.getTarget()); 5373 5374 if (!isIndirect) 5375 Callee = transformCallee(Callee, DAG, dl, Subtarget); 5376 else if (Subtarget.usesFunctionDescriptors()) 5377 prepareDescriptorIndirectCall(DAG, Callee, Glue, Chain, CallSeqStart, CS, 5378 dl, hasNest, Subtarget); 5379 else 5380 prepareIndirectCall(DAG, Callee, Glue, Chain, dl); 5381 5382 // Build the operand list for the call instruction. 5383 SmallVector<SDValue, 8> Ops; 5384 buildCallOperands(Ops, CallConv, dl, isTailCall, isVarArg, isPatchPoint, 5385 hasNest, DAG, RegsToPass, Glue, Chain, Callee, SPDiff, 5386 Subtarget, isIndirect); 5387 5388 // Emit tail call. 5389 if (isTailCall) { 5390 assert(((Callee.getOpcode() == ISD::Register && 5391 cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) || 5392 Callee.getOpcode() == ISD::TargetExternalSymbol || 5393 Callee.getOpcode() == ISD::TargetGlobalAddress || 5394 isa<ConstantSDNode>(Callee)) && 5395 "Expecting a global address, external symbol, absolute value or " 5396 "register"); 5397 assert(CallOpc == PPCISD::TC_RETURN && 5398 "Unexpected call opcode for a tail call."); 5399 DAG.getMachineFunction().getFrameInfo().setHasTailCall(); 5400 return DAG.getNode(CallOpc, dl, MVT::Other, Ops); 5401 } 5402 5403 std::array<EVT, 2> ReturnTypes = {{MVT::Other, MVT::Glue}}; 5404 Chain = DAG.getNode(CallOpc, dl, ReturnTypes, Ops); 5405 Glue = Chain.getValue(1); 5406 5407 // When performing tail call optimization the callee pops its arguments off 5408 // the stack. Account for this here so these bytes can be pushed back on in 5409 // PPCFrameLowering::eliminateCallFramePseudoInstr. 5410 int BytesCalleePops = (CallConv == CallingConv::Fast && 5411 getTargetMachine().Options.GuaranteedTailCallOpt) 5412 ? NumBytes 5413 : 0; 5414 5415 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true), 5416 DAG.getIntPtrConstant(BytesCalleePops, dl, true), 5417 Glue, dl); 5418 Glue = Chain.getValue(1); 5419 5420 return LowerCallResult(Chain, Glue, CallConv, isVarArg, Ins, dl, DAG, InVals); 5421 } 5422 5423 SDValue 5424 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI, 5425 SmallVectorImpl<SDValue> &InVals) const { 5426 SelectionDAG &DAG = CLI.DAG; 5427 SDLoc &dl = CLI.DL; 5428 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs; 5429 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals; 5430 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins; 5431 SDValue Chain = CLI.Chain; 5432 SDValue Callee = CLI.Callee; 5433 bool &isTailCall = CLI.IsTailCall; 5434 CallingConv::ID CallConv = CLI.CallConv; 5435 bool isVarArg = CLI.IsVarArg; 5436 bool isPatchPoint = CLI.IsPatchPoint; 5437 ImmutableCallSite CS = CLI.CS; 5438 5439 if (isTailCall) { 5440 if (Subtarget.useLongCalls() && !(CS && CS.isMustTailCall())) 5441 isTailCall = false; 5442 else if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) 5443 isTailCall = 5444 IsEligibleForTailCallOptimization_64SVR4(Callee, CallConv, CS, 5445 isVarArg, Outs, Ins, DAG); 5446 else 5447 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg, 5448 Ins, DAG); 5449 if (isTailCall) { 5450 ++NumTailCalls; 5451 if (!getTargetMachine().Options.GuaranteedTailCallOpt) 5452 ++NumSiblingCalls; 5453 5454 assert(isa<GlobalAddressSDNode>(Callee) && 5455 "Callee should be an llvm::Function object."); 5456 LLVM_DEBUG( 5457 const GlobalValue *GV = 5458 cast<GlobalAddressSDNode>(Callee)->getGlobal(); 5459 const unsigned Width = 5460 80 - strlen("TCO caller: ") - strlen(", callee linkage: 0, 0"); 5461 dbgs() << "TCO caller: " 5462 << left_justify(DAG.getMachineFunction().getName(), Width) 5463 << ", callee linkage: " << GV->getVisibility() << ", " 5464 << GV->getLinkage() << "\n"); 5465 } 5466 } 5467 5468 if (!isTailCall && CS && CS.isMustTailCall()) 5469 report_fatal_error("failed to perform tail call elimination on a call " 5470 "site marked musttail"); 5471 5472 // When long calls (i.e. indirect calls) are always used, calls are always 5473 // made via function pointer. If we have a function name, first translate it 5474 // into a pointer. 5475 if (Subtarget.useLongCalls() && isa<GlobalAddressSDNode>(Callee) && 5476 !isTailCall) 5477 Callee = LowerGlobalAddress(Callee, DAG); 5478 5479 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) 5480 return LowerCall_64SVR4(Chain, Callee, CallConv, isVarArg, 5481 isTailCall, isPatchPoint, Outs, OutVals, Ins, 5482 dl, DAG, InVals, CS); 5483 5484 if (Subtarget.isSVR4ABI()) 5485 return LowerCall_32SVR4(Chain, Callee, CallConv, isVarArg, 5486 isTailCall, isPatchPoint, Outs, OutVals, Ins, 5487 dl, DAG, InVals, CS); 5488 5489 if (Subtarget.isAIXABI()) 5490 return LowerCall_AIX(Chain, Callee, CallConv, isVarArg, 5491 isTailCall, isPatchPoint, Outs, OutVals, Ins, 5492 dl, DAG, InVals, CS); 5493 5494 return LowerCall_Darwin(Chain, Callee, CallConv, isVarArg, 5495 isTailCall, isPatchPoint, Outs, OutVals, Ins, 5496 dl, DAG, InVals, CS); 5497 } 5498 5499 SDValue PPCTargetLowering::LowerCall_32SVR4( 5500 SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg, 5501 bool isTailCall, bool isPatchPoint, 5502 const SmallVectorImpl<ISD::OutputArg> &Outs, 5503 const SmallVectorImpl<SDValue> &OutVals, 5504 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 5505 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 5506 ImmutableCallSite CS) const { 5507 // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description 5508 // of the 32-bit SVR4 ABI stack frame layout. 5509 5510 assert((CallConv == CallingConv::C || 5511 CallConv == CallingConv::Cold || 5512 CallConv == CallingConv::Fast) && "Unknown calling convention!"); 5513 5514 unsigned PtrByteSize = 4; 5515 5516 MachineFunction &MF = DAG.getMachineFunction(); 5517 5518 // Mark this function as potentially containing a function that contains a 5519 // tail call. As a consequence the frame pointer will be used for dynamicalloc 5520 // and restoring the callers stack pointer in this functions epilog. This is 5521 // done because by tail calling the called function might overwrite the value 5522 // in this function's (MF) stack pointer stack slot 0(SP). 5523 if (getTargetMachine().Options.GuaranteedTailCallOpt && 5524 CallConv == CallingConv::Fast) 5525 MF.getInfo<PPCFunctionInfo>()->setHasFastCall(); 5526 5527 // Count how many bytes are to be pushed on the stack, including the linkage 5528 // area, parameter list area and the part of the local variable space which 5529 // contains copies of aggregates which are passed by value. 5530 5531 // Assign locations to all of the outgoing arguments. 5532 SmallVector<CCValAssign, 16> ArgLocs; 5533 PPCCCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext()); 5534 5535 // Reserve space for the linkage area on the stack. 5536 CCInfo.AllocateStack(Subtarget.getFrameLowering()->getLinkageSize(), 5537 PtrByteSize); 5538 if (useSoftFloat()) 5539 CCInfo.PreAnalyzeCallOperands(Outs); 5540 5541 if (isVarArg) { 5542 // Handle fixed and variable vector arguments differently. 5543 // Fixed vector arguments go into registers as long as registers are 5544 // available. Variable vector arguments always go into memory. 5545 unsigned NumArgs = Outs.size(); 5546 5547 for (unsigned i = 0; i != NumArgs; ++i) { 5548 MVT ArgVT = Outs[i].VT; 5549 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 5550 bool Result; 5551 5552 if (Outs[i].IsFixed) { 5553 Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, 5554 CCInfo); 5555 } else { 5556 Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full, 5557 ArgFlags, CCInfo); 5558 } 5559 5560 if (Result) { 5561 #ifndef NDEBUG 5562 errs() << "Call operand #" << i << " has unhandled type " 5563 << EVT(ArgVT).getEVTString() << "\n"; 5564 #endif 5565 llvm_unreachable(nullptr); 5566 } 5567 } 5568 } else { 5569 // All arguments are treated the same. 5570 CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4); 5571 } 5572 CCInfo.clearWasPPCF128(); 5573 5574 // Assign locations to all of the outgoing aggregate by value arguments. 5575 SmallVector<CCValAssign, 16> ByValArgLocs; 5576 CCState CCByValInfo(CallConv, isVarArg, MF, ByValArgLocs, *DAG.getContext()); 5577 5578 // Reserve stack space for the allocations in CCInfo. 5579 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize); 5580 5581 CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal); 5582 5583 // Size of the linkage area, parameter list area and the part of the local 5584 // space variable where copies of aggregates which are passed by value are 5585 // stored. 5586 unsigned NumBytes = CCByValInfo.getNextStackOffset(); 5587 5588 // Calculate by how many bytes the stack has to be adjusted in case of tail 5589 // call optimization. 5590 int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes); 5591 5592 // Adjust the stack pointer for the new arguments... 5593 // These operations are automatically eliminated by the prolog/epilog pass 5594 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 5595 SDValue CallSeqStart = Chain; 5596 5597 // Load the return address and frame pointer so it can be moved somewhere else 5598 // later. 5599 SDValue LROp, FPOp; 5600 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl); 5601 5602 // Set up a copy of the stack pointer for use loading and storing any 5603 // arguments that may not fit in the registers available for argument 5604 // passing. 5605 SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32); 5606 5607 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 5608 SmallVector<TailCallArgumentInfo, 8> TailCallArguments; 5609 SmallVector<SDValue, 8> MemOpChains; 5610 5611 bool seenFloatArg = false; 5612 // Walk the register/memloc assignments, inserting copies/loads. 5613 // i - Tracks the index into the list of registers allocated for the call 5614 // RealArgIdx - Tracks the index into the list of actual function arguments 5615 // j - Tracks the index into the list of byval arguments 5616 for (unsigned i = 0, RealArgIdx = 0, j = 0, e = ArgLocs.size(); 5617 i != e; 5618 ++i, ++RealArgIdx) { 5619 CCValAssign &VA = ArgLocs[i]; 5620 SDValue Arg = OutVals[RealArgIdx]; 5621 ISD::ArgFlagsTy Flags = Outs[RealArgIdx].Flags; 5622 5623 if (Flags.isByVal()) { 5624 // Argument is an aggregate which is passed by value, thus we need to 5625 // create a copy of it in the local variable space of the current stack 5626 // frame (which is the stack frame of the caller) and pass the address of 5627 // this copy to the callee. 5628 assert((j < ByValArgLocs.size()) && "Index out of bounds!"); 5629 CCValAssign &ByValVA = ByValArgLocs[j++]; 5630 assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!"); 5631 5632 // Memory reserved in the local variable space of the callers stack frame. 5633 unsigned LocMemOffset = ByValVA.getLocMemOffset(); 5634 5635 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 5636 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()), 5637 StackPtr, PtrOff); 5638 5639 // Create a copy of the argument in the local area of the current 5640 // stack frame. 5641 SDValue MemcpyCall = 5642 CreateCopyOfByValArgument(Arg, PtrOff, 5643 CallSeqStart.getNode()->getOperand(0), 5644 Flags, DAG, dl); 5645 5646 // This must go outside the CALLSEQ_START..END. 5647 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, NumBytes, 0, 5648 SDLoc(MemcpyCall)); 5649 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(), 5650 NewCallSeqStart.getNode()); 5651 Chain = CallSeqStart = NewCallSeqStart; 5652 5653 // Pass the address of the aggregate copy on the stack either in a 5654 // physical register or in the parameter list area of the current stack 5655 // frame to the callee. 5656 Arg = PtrOff; 5657 } 5658 5659 // When useCRBits() is true, there can be i1 arguments. 5660 // It is because getRegisterType(MVT::i1) => MVT::i1, 5661 // and for other integer types getRegisterType() => MVT::i32. 5662 // Extend i1 and ensure callee will get i32. 5663 if (Arg.getValueType() == MVT::i1) 5664 Arg = DAG.getNode(Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, 5665 dl, MVT::i32, Arg); 5666 5667 if (VA.isRegLoc()) { 5668 seenFloatArg |= VA.getLocVT().isFloatingPoint(); 5669 // Put argument in a physical register. 5670 if (Subtarget.hasSPE() && Arg.getValueType() == MVT::f64) { 5671 bool IsLE = Subtarget.isLittleEndian(); 5672 SDValue SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg, 5673 DAG.getIntPtrConstant(IsLE ? 0 : 1, dl)); 5674 RegsToPass.push_back(std::make_pair(VA.getLocReg(), SVal.getValue(0))); 5675 SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg, 5676 DAG.getIntPtrConstant(IsLE ? 1 : 0, dl)); 5677 RegsToPass.push_back(std::make_pair(ArgLocs[++i].getLocReg(), 5678 SVal.getValue(0))); 5679 } else 5680 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 5681 } else { 5682 // Put argument in the parameter list area of the current stack frame. 5683 assert(VA.isMemLoc()); 5684 unsigned LocMemOffset = VA.getLocMemOffset(); 5685 5686 if (!isTailCall) { 5687 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 5688 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()), 5689 StackPtr, PtrOff); 5690 5691 MemOpChains.push_back( 5692 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo())); 5693 } else { 5694 // Calculate and remember argument location. 5695 CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset, 5696 TailCallArguments); 5697 } 5698 } 5699 } 5700 5701 if (!MemOpChains.empty()) 5702 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 5703 5704 // Build a sequence of copy-to-reg nodes chained together with token chain 5705 // and flag operands which copy the outgoing args into the appropriate regs. 5706 SDValue InFlag; 5707 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 5708 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 5709 RegsToPass[i].second, InFlag); 5710 InFlag = Chain.getValue(1); 5711 } 5712 5713 // Set CR bit 6 to true if this is a vararg call with floating args passed in 5714 // registers. 5715 if (isVarArg) { 5716 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue); 5717 SDValue Ops[] = { Chain, InFlag }; 5718 5719 Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET, 5720 dl, VTs, makeArrayRef(Ops, InFlag.getNode() ? 2 : 1)); 5721 5722 InFlag = Chain.getValue(1); 5723 } 5724 5725 if (isTailCall) 5726 PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp, 5727 TailCallArguments); 5728 5729 return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint, 5730 /* unused except on PPC64 ELFv1 */ false, DAG, 5731 RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff, 5732 NumBytes, Ins, InVals, CS); 5733 } 5734 5735 // Copy an argument into memory, being careful to do this outside the 5736 // call sequence for the call to which the argument belongs. 5737 SDValue PPCTargetLowering::createMemcpyOutsideCallSeq( 5738 SDValue Arg, SDValue PtrOff, SDValue CallSeqStart, ISD::ArgFlagsTy Flags, 5739 SelectionDAG &DAG, const SDLoc &dl) const { 5740 SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff, 5741 CallSeqStart.getNode()->getOperand(0), 5742 Flags, DAG, dl); 5743 // The MEMCPY must go outside the CALLSEQ_START..END. 5744 int64_t FrameSize = CallSeqStart.getConstantOperandVal(1); 5745 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, FrameSize, 0, 5746 SDLoc(MemcpyCall)); 5747 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(), 5748 NewCallSeqStart.getNode()); 5749 return NewCallSeqStart; 5750 } 5751 5752 SDValue PPCTargetLowering::LowerCall_64SVR4( 5753 SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg, 5754 bool isTailCall, bool isPatchPoint, 5755 const SmallVectorImpl<ISD::OutputArg> &Outs, 5756 const SmallVectorImpl<SDValue> &OutVals, 5757 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 5758 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 5759 ImmutableCallSite CS) const { 5760 bool isELFv2ABI = Subtarget.isELFv2ABI(); 5761 bool isLittleEndian = Subtarget.isLittleEndian(); 5762 unsigned NumOps = Outs.size(); 5763 bool hasNest = false; 5764 bool IsSibCall = false; 5765 5766 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 5767 unsigned PtrByteSize = 8; 5768 5769 MachineFunction &MF = DAG.getMachineFunction(); 5770 5771 if (isTailCall && !getTargetMachine().Options.GuaranteedTailCallOpt) 5772 IsSibCall = true; 5773 5774 // Mark this function as potentially containing a function that contains a 5775 // tail call. As a consequence the frame pointer will be used for dynamicalloc 5776 // and restoring the callers stack pointer in this functions epilog. This is 5777 // done because by tail calling the called function might overwrite the value 5778 // in this function's (MF) stack pointer stack slot 0(SP). 5779 if (getTargetMachine().Options.GuaranteedTailCallOpt && 5780 CallConv == CallingConv::Fast) 5781 MF.getInfo<PPCFunctionInfo>()->setHasFastCall(); 5782 5783 assert(!(CallConv == CallingConv::Fast && isVarArg) && 5784 "fastcc not supported on varargs functions"); 5785 5786 // Count how many bytes are to be pushed on the stack, including the linkage 5787 // area, and parameter passing area. On ELFv1, the linkage area is 48 bytes 5788 // reserved space for [SP][CR][LR][2 x unused][TOC]; on ELFv2, the linkage 5789 // area is 32 bytes reserved space for [SP][CR][LR][TOC]. 5790 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 5791 unsigned NumBytes = LinkageSize; 5792 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 5793 unsigned &QFPR_idx = FPR_idx; 5794 5795 static const MCPhysReg GPR[] = { 5796 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 5797 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 5798 }; 5799 static const MCPhysReg VR[] = { 5800 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 5801 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 5802 }; 5803 5804 const unsigned NumGPRs = array_lengthof(GPR); 5805 const unsigned NumFPRs = useSoftFloat() ? 0 : 13; 5806 const unsigned NumVRs = array_lengthof(VR); 5807 const unsigned NumQFPRs = NumFPRs; 5808 5809 // On ELFv2, we can avoid allocating the parameter area if all the arguments 5810 // can be passed to the callee in registers. 5811 // For the fast calling convention, there is another check below. 5812 // Note: We should keep consistent with LowerFormalArguments_64SVR4() 5813 bool HasParameterArea = !isELFv2ABI || isVarArg || CallConv == CallingConv::Fast; 5814 if (!HasParameterArea) { 5815 unsigned ParamAreaSize = NumGPRs * PtrByteSize; 5816 unsigned AvailableFPRs = NumFPRs; 5817 unsigned AvailableVRs = NumVRs; 5818 unsigned NumBytesTmp = NumBytes; 5819 for (unsigned i = 0; i != NumOps; ++i) { 5820 if (Outs[i].Flags.isNest()) continue; 5821 if (CalculateStackSlotUsed(Outs[i].VT, Outs[i].ArgVT, Outs[i].Flags, 5822 PtrByteSize, LinkageSize, ParamAreaSize, 5823 NumBytesTmp, AvailableFPRs, AvailableVRs, 5824 Subtarget.hasQPX())) 5825 HasParameterArea = true; 5826 } 5827 } 5828 5829 // When using the fast calling convention, we don't provide backing for 5830 // arguments that will be in registers. 5831 unsigned NumGPRsUsed = 0, NumFPRsUsed = 0, NumVRsUsed = 0; 5832 5833 // Avoid allocating parameter area for fastcc functions if all the arguments 5834 // can be passed in the registers. 5835 if (CallConv == CallingConv::Fast) 5836 HasParameterArea = false; 5837 5838 // Add up all the space actually used. 5839 for (unsigned i = 0; i != NumOps; ++i) { 5840 ISD::ArgFlagsTy Flags = Outs[i].Flags; 5841 EVT ArgVT = Outs[i].VT; 5842 EVT OrigVT = Outs[i].ArgVT; 5843 5844 if (Flags.isNest()) 5845 continue; 5846 5847 if (CallConv == CallingConv::Fast) { 5848 if (Flags.isByVal()) { 5849 NumGPRsUsed += (Flags.getByValSize()+7)/8; 5850 if (NumGPRsUsed > NumGPRs) 5851 HasParameterArea = true; 5852 } else { 5853 switch (ArgVT.getSimpleVT().SimpleTy) { 5854 default: llvm_unreachable("Unexpected ValueType for argument!"); 5855 case MVT::i1: 5856 case MVT::i32: 5857 case MVT::i64: 5858 if (++NumGPRsUsed <= NumGPRs) 5859 continue; 5860 break; 5861 case MVT::v4i32: 5862 case MVT::v8i16: 5863 case MVT::v16i8: 5864 case MVT::v2f64: 5865 case MVT::v2i64: 5866 case MVT::v1i128: 5867 case MVT::f128: 5868 if (++NumVRsUsed <= NumVRs) 5869 continue; 5870 break; 5871 case MVT::v4f32: 5872 // When using QPX, this is handled like a FP register, otherwise, it 5873 // is an Altivec register. 5874 if (Subtarget.hasQPX()) { 5875 if (++NumFPRsUsed <= NumFPRs) 5876 continue; 5877 } else { 5878 if (++NumVRsUsed <= NumVRs) 5879 continue; 5880 } 5881 break; 5882 case MVT::f32: 5883 case MVT::f64: 5884 case MVT::v4f64: // QPX 5885 case MVT::v4i1: // QPX 5886 if (++NumFPRsUsed <= NumFPRs) 5887 continue; 5888 break; 5889 } 5890 HasParameterArea = true; 5891 } 5892 } 5893 5894 /* Respect alignment of argument on the stack. */ 5895 unsigned Align = 5896 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize); 5897 NumBytes = ((NumBytes + Align - 1) / Align) * Align; 5898 5899 NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize); 5900 if (Flags.isInConsecutiveRegsLast()) 5901 NumBytes = ((NumBytes + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 5902 } 5903 5904 unsigned NumBytesActuallyUsed = NumBytes; 5905 5906 // In the old ELFv1 ABI, 5907 // the prolog code of the callee may store up to 8 GPR argument registers to 5908 // the stack, allowing va_start to index over them in memory if its varargs. 5909 // Because we cannot tell if this is needed on the caller side, we have to 5910 // conservatively assume that it is needed. As such, make sure we have at 5911 // least enough stack space for the caller to store the 8 GPRs. 5912 // In the ELFv2 ABI, we allocate the parameter area iff a callee 5913 // really requires memory operands, e.g. a vararg function. 5914 if (HasParameterArea) 5915 NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize); 5916 else 5917 NumBytes = LinkageSize; 5918 5919 // Tail call needs the stack to be aligned. 5920 if (getTargetMachine().Options.GuaranteedTailCallOpt && 5921 CallConv == CallingConv::Fast) 5922 NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes); 5923 5924 int SPDiff = 0; 5925 5926 // Calculate by how many bytes the stack has to be adjusted in case of tail 5927 // call optimization. 5928 if (!IsSibCall) 5929 SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes); 5930 5931 // To protect arguments on the stack from being clobbered in a tail call, 5932 // force all the loads to happen before doing any other lowering. 5933 if (isTailCall) 5934 Chain = DAG.getStackArgumentTokenFactor(Chain); 5935 5936 // Adjust the stack pointer for the new arguments... 5937 // These operations are automatically eliminated by the prolog/epilog pass 5938 if (!IsSibCall) 5939 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 5940 SDValue CallSeqStart = Chain; 5941 5942 // Load the return address and frame pointer so it can be move somewhere else 5943 // later. 5944 SDValue LROp, FPOp; 5945 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl); 5946 5947 // Set up a copy of the stack pointer for use loading and storing any 5948 // arguments that may not fit in the registers available for argument 5949 // passing. 5950 SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64); 5951 5952 // Figure out which arguments are going to go in registers, and which in 5953 // memory. Also, if this is a vararg function, floating point operations 5954 // must be stored to our stack, and loaded into integer regs as well, if 5955 // any integer regs are available for argument passing. 5956 unsigned ArgOffset = LinkageSize; 5957 5958 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 5959 SmallVector<TailCallArgumentInfo, 8> TailCallArguments; 5960 5961 SmallVector<SDValue, 8> MemOpChains; 5962 for (unsigned i = 0; i != NumOps; ++i) { 5963 SDValue Arg = OutVals[i]; 5964 ISD::ArgFlagsTy Flags = Outs[i].Flags; 5965 EVT ArgVT = Outs[i].VT; 5966 EVT OrigVT = Outs[i].ArgVT; 5967 5968 // PtrOff will be used to store the current argument to the stack if a 5969 // register cannot be found for it. 5970 SDValue PtrOff; 5971 5972 // We re-align the argument offset for each argument, except when using the 5973 // fast calling convention, when we need to make sure we do that only when 5974 // we'll actually use a stack slot. 5975 auto ComputePtrOff = [&]() { 5976 /* Respect alignment of argument on the stack. */ 5977 unsigned Align = 5978 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize); 5979 ArgOffset = ((ArgOffset + Align - 1) / Align) * Align; 5980 5981 PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType()); 5982 5983 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 5984 }; 5985 5986 if (CallConv != CallingConv::Fast) { 5987 ComputePtrOff(); 5988 5989 /* Compute GPR index associated with argument offset. */ 5990 GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize; 5991 GPR_idx = std::min(GPR_idx, NumGPRs); 5992 } 5993 5994 // Promote integers to 64-bit values. 5995 if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) { 5996 // FIXME: Should this use ANY_EXTEND if neither sext nor zext? 5997 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 5998 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg); 5999 } 6000 6001 // FIXME memcpy is used way more than necessary. Correctness first. 6002 // Note: "by value" is code for passing a structure by value, not 6003 // basic types. 6004 if (Flags.isByVal()) { 6005 // Note: Size includes alignment padding, so 6006 // struct x { short a; char b; } 6007 // will have Size = 4. With #pragma pack(1), it will have Size = 3. 6008 // These are the proper values we need for right-justifying the 6009 // aggregate in a parameter register. 6010 unsigned Size = Flags.getByValSize(); 6011 6012 // An empty aggregate parameter takes up no storage and no 6013 // registers. 6014 if (Size == 0) 6015 continue; 6016 6017 if (CallConv == CallingConv::Fast) 6018 ComputePtrOff(); 6019 6020 // All aggregates smaller than 8 bytes must be passed right-justified. 6021 if (Size==1 || Size==2 || Size==4) { 6022 EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32); 6023 if (GPR_idx != NumGPRs) { 6024 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg, 6025 MachinePointerInfo(), VT); 6026 MemOpChains.push_back(Load.getValue(1)); 6027 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6028 6029 ArgOffset += PtrByteSize; 6030 continue; 6031 } 6032 } 6033 6034 if (GPR_idx == NumGPRs && Size < 8) { 6035 SDValue AddPtr = PtrOff; 6036 if (!isLittleEndian) { 6037 SDValue Const = DAG.getConstant(PtrByteSize - Size, dl, 6038 PtrOff.getValueType()); 6039 AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const); 6040 } 6041 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr, 6042 CallSeqStart, 6043 Flags, DAG, dl); 6044 ArgOffset += PtrByteSize; 6045 continue; 6046 } 6047 // Copy entire object into memory. There are cases where gcc-generated 6048 // code assumes it is there, even if it could be put entirely into 6049 // registers. (This is not what the doc says.) 6050 6051 // FIXME: The above statement is likely due to a misunderstanding of the 6052 // documents. All arguments must be copied into the parameter area BY 6053 // THE CALLEE in the event that the callee takes the address of any 6054 // formal argument. That has not yet been implemented. However, it is 6055 // reasonable to use the stack area as a staging area for the register 6056 // load. 6057 6058 // Skip this for small aggregates, as we will use the same slot for a 6059 // right-justified copy, below. 6060 if (Size >= 8) 6061 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff, 6062 CallSeqStart, 6063 Flags, DAG, dl); 6064 6065 // When a register is available, pass a small aggregate right-justified. 6066 if (Size < 8 && GPR_idx != NumGPRs) { 6067 // The easiest way to get this right-justified in a register 6068 // is to copy the structure into the rightmost portion of a 6069 // local variable slot, then load the whole slot into the 6070 // register. 6071 // FIXME: The memcpy seems to produce pretty awful code for 6072 // small aggregates, particularly for packed ones. 6073 // FIXME: It would be preferable to use the slot in the 6074 // parameter save area instead of a new local variable. 6075 SDValue AddPtr = PtrOff; 6076 if (!isLittleEndian) { 6077 SDValue Const = DAG.getConstant(8 - Size, dl, PtrOff.getValueType()); 6078 AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const); 6079 } 6080 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr, 6081 CallSeqStart, 6082 Flags, DAG, dl); 6083 6084 // Load the slot into the register. 6085 SDValue Load = 6086 DAG.getLoad(PtrVT, dl, Chain, PtrOff, MachinePointerInfo()); 6087 MemOpChains.push_back(Load.getValue(1)); 6088 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6089 6090 // Done with this argument. 6091 ArgOffset += PtrByteSize; 6092 continue; 6093 } 6094 6095 // For aggregates larger than PtrByteSize, copy the pieces of the 6096 // object that fit into registers from the parameter save area. 6097 for (unsigned j=0; j<Size; j+=PtrByteSize) { 6098 SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType()); 6099 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const); 6100 if (GPR_idx != NumGPRs) { 6101 SDValue Load = 6102 DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo()); 6103 MemOpChains.push_back(Load.getValue(1)); 6104 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6105 ArgOffset += PtrByteSize; 6106 } else { 6107 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize; 6108 break; 6109 } 6110 } 6111 continue; 6112 } 6113 6114 switch (Arg.getSimpleValueType().SimpleTy) { 6115 default: llvm_unreachable("Unexpected ValueType for argument!"); 6116 case MVT::i1: 6117 case MVT::i32: 6118 case MVT::i64: 6119 if (Flags.isNest()) { 6120 // The 'nest' parameter, if any, is passed in R11. 6121 RegsToPass.push_back(std::make_pair(PPC::X11, Arg)); 6122 hasNest = true; 6123 break; 6124 } 6125 6126 // These can be scalar arguments or elements of an integer array type 6127 // passed directly. Clang may use those instead of "byval" aggregate 6128 // types to avoid forcing arguments to memory unnecessarily. 6129 if (GPR_idx != NumGPRs) { 6130 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg)); 6131 } else { 6132 if (CallConv == CallingConv::Fast) 6133 ComputePtrOff(); 6134 6135 assert(HasParameterArea && 6136 "Parameter area must exist to pass an argument in memory."); 6137 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6138 true, isTailCall, false, MemOpChains, 6139 TailCallArguments, dl); 6140 if (CallConv == CallingConv::Fast) 6141 ArgOffset += PtrByteSize; 6142 } 6143 if (CallConv != CallingConv::Fast) 6144 ArgOffset += PtrByteSize; 6145 break; 6146 case MVT::f32: 6147 case MVT::f64: { 6148 // These can be scalar arguments or elements of a float array type 6149 // passed directly. The latter are used to implement ELFv2 homogenous 6150 // float aggregates. 6151 6152 // Named arguments go into FPRs first, and once they overflow, the 6153 // remaining arguments go into GPRs and then the parameter save area. 6154 // Unnamed arguments for vararg functions always go to GPRs and 6155 // then the parameter save area. For now, put all arguments to vararg 6156 // routines always in both locations (FPR *and* GPR or stack slot). 6157 bool NeedGPROrStack = isVarArg || FPR_idx == NumFPRs; 6158 bool NeededLoad = false; 6159 6160 // First load the argument into the next available FPR. 6161 if (FPR_idx != NumFPRs) 6162 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg)); 6163 6164 // Next, load the argument into GPR or stack slot if needed. 6165 if (!NeedGPROrStack) 6166 ; 6167 else if (GPR_idx != NumGPRs && CallConv != CallingConv::Fast) { 6168 // FIXME: We may want to re-enable this for CallingConv::Fast on the P8 6169 // once we support fp <-> gpr moves. 6170 6171 // In the non-vararg case, this can only ever happen in the 6172 // presence of f32 array types, since otherwise we never run 6173 // out of FPRs before running out of GPRs. 6174 SDValue ArgVal; 6175 6176 // Double values are always passed in a single GPR. 6177 if (Arg.getValueType() != MVT::f32) { 6178 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg); 6179 6180 // Non-array float values are extended and passed in a GPR. 6181 } else if (!Flags.isInConsecutiveRegs()) { 6182 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg); 6183 ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal); 6184 6185 // If we have an array of floats, we collect every odd element 6186 // together with its predecessor into one GPR. 6187 } else if (ArgOffset % PtrByteSize != 0) { 6188 SDValue Lo, Hi; 6189 Lo = DAG.getNode(ISD::BITCAST, dl, MVT::i32, OutVals[i - 1]); 6190 Hi = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg); 6191 if (!isLittleEndian) 6192 std::swap(Lo, Hi); 6193 ArgVal = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi); 6194 6195 // The final element, if even, goes into the first half of a GPR. 6196 } else if (Flags.isInConsecutiveRegsLast()) { 6197 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg); 6198 ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal); 6199 if (!isLittleEndian) 6200 ArgVal = DAG.getNode(ISD::SHL, dl, MVT::i64, ArgVal, 6201 DAG.getConstant(32, dl, MVT::i32)); 6202 6203 // Non-final even elements are skipped; they will be handled 6204 // together the with subsequent argument on the next go-around. 6205 } else 6206 ArgVal = SDValue(); 6207 6208 if (ArgVal.getNode()) 6209 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], ArgVal)); 6210 } else { 6211 if (CallConv == CallingConv::Fast) 6212 ComputePtrOff(); 6213 6214 // Single-precision floating-point values are mapped to the 6215 // second (rightmost) word of the stack doubleword. 6216 if (Arg.getValueType() == MVT::f32 && 6217 !isLittleEndian && !Flags.isInConsecutiveRegs()) { 6218 SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType()); 6219 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour); 6220 } 6221 6222 assert(HasParameterArea && 6223 "Parameter area must exist to pass an argument in memory."); 6224 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6225 true, isTailCall, false, MemOpChains, 6226 TailCallArguments, dl); 6227 6228 NeededLoad = true; 6229 } 6230 // When passing an array of floats, the array occupies consecutive 6231 // space in the argument area; only round up to the next doubleword 6232 // at the end of the array. Otherwise, each float takes 8 bytes. 6233 if (CallConv != CallingConv::Fast || NeededLoad) { 6234 ArgOffset += (Arg.getValueType() == MVT::f32 && 6235 Flags.isInConsecutiveRegs()) ? 4 : 8; 6236 if (Flags.isInConsecutiveRegsLast()) 6237 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 6238 } 6239 break; 6240 } 6241 case MVT::v4f32: 6242 case MVT::v4i32: 6243 case MVT::v8i16: 6244 case MVT::v16i8: 6245 case MVT::v2f64: 6246 case MVT::v2i64: 6247 case MVT::v1i128: 6248 case MVT::f128: 6249 if (!Subtarget.hasQPX()) { 6250 // These can be scalar arguments or elements of a vector array type 6251 // passed directly. The latter are used to implement ELFv2 homogenous 6252 // vector aggregates. 6253 6254 // For a varargs call, named arguments go into VRs or on the stack as 6255 // usual; unnamed arguments always go to the stack or the corresponding 6256 // GPRs when within range. For now, we always put the value in both 6257 // locations (or even all three). 6258 if (isVarArg) { 6259 assert(HasParameterArea && 6260 "Parameter area must exist if we have a varargs call."); 6261 // We could elide this store in the case where the object fits 6262 // entirely in R registers. Maybe later. 6263 SDValue Store = 6264 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 6265 MemOpChains.push_back(Store); 6266 if (VR_idx != NumVRs) { 6267 SDValue Load = 6268 DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo()); 6269 MemOpChains.push_back(Load.getValue(1)); 6270 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load)); 6271 } 6272 ArgOffset += 16; 6273 for (unsigned i=0; i<16; i+=PtrByteSize) { 6274 if (GPR_idx == NumGPRs) 6275 break; 6276 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, 6277 DAG.getConstant(i, dl, PtrVT)); 6278 SDValue Load = 6279 DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo()); 6280 MemOpChains.push_back(Load.getValue(1)); 6281 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6282 } 6283 break; 6284 } 6285 6286 // Non-varargs Altivec params go into VRs or on the stack. 6287 if (VR_idx != NumVRs) { 6288 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg)); 6289 } else { 6290 if (CallConv == CallingConv::Fast) 6291 ComputePtrOff(); 6292 6293 assert(HasParameterArea && 6294 "Parameter area must exist to pass an argument in memory."); 6295 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6296 true, isTailCall, true, MemOpChains, 6297 TailCallArguments, dl); 6298 if (CallConv == CallingConv::Fast) 6299 ArgOffset += 16; 6300 } 6301 6302 if (CallConv != CallingConv::Fast) 6303 ArgOffset += 16; 6304 break; 6305 } // not QPX 6306 6307 assert(Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32 && 6308 "Invalid QPX parameter type"); 6309 6310 LLVM_FALLTHROUGH; 6311 case MVT::v4f64: 6312 case MVT::v4i1: { 6313 bool IsF32 = Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32; 6314 if (isVarArg) { 6315 assert(HasParameterArea && 6316 "Parameter area must exist if we have a varargs call."); 6317 // We could elide this store in the case where the object fits 6318 // entirely in R registers. Maybe later. 6319 SDValue Store = 6320 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 6321 MemOpChains.push_back(Store); 6322 if (QFPR_idx != NumQFPRs) { 6323 SDValue Load = DAG.getLoad(IsF32 ? MVT::v4f32 : MVT::v4f64, dl, Store, 6324 PtrOff, MachinePointerInfo()); 6325 MemOpChains.push_back(Load.getValue(1)); 6326 RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Load)); 6327 } 6328 ArgOffset += (IsF32 ? 16 : 32); 6329 for (unsigned i = 0; i < (IsF32 ? 16U : 32U); i += PtrByteSize) { 6330 if (GPR_idx == NumGPRs) 6331 break; 6332 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, 6333 DAG.getConstant(i, dl, PtrVT)); 6334 SDValue Load = 6335 DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo()); 6336 MemOpChains.push_back(Load.getValue(1)); 6337 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6338 } 6339 break; 6340 } 6341 6342 // Non-varargs QPX params go into registers or on the stack. 6343 if (QFPR_idx != NumQFPRs) { 6344 RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Arg)); 6345 } else { 6346 if (CallConv == CallingConv::Fast) 6347 ComputePtrOff(); 6348 6349 assert(HasParameterArea && 6350 "Parameter area must exist to pass an argument in memory."); 6351 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6352 true, isTailCall, true, MemOpChains, 6353 TailCallArguments, dl); 6354 if (CallConv == CallingConv::Fast) 6355 ArgOffset += (IsF32 ? 16 : 32); 6356 } 6357 6358 if (CallConv != CallingConv::Fast) 6359 ArgOffset += (IsF32 ? 16 : 32); 6360 break; 6361 } 6362 } 6363 } 6364 6365 assert((!HasParameterArea || NumBytesActuallyUsed == ArgOffset) && 6366 "mismatch in size of parameter area"); 6367 (void)NumBytesActuallyUsed; 6368 6369 if (!MemOpChains.empty()) 6370 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 6371 6372 // Check if this is an indirect call (MTCTR/BCTRL). 6373 // See prepareDescriptorIndirectCall and buildCallOperands for more 6374 // information about calls through function pointers in the 64-bit SVR4 ABI. 6375 if (!isTailCall && !isPatchPoint && 6376 !isFunctionGlobalAddress(Callee) && 6377 !isa<ExternalSymbolSDNode>(Callee)) { 6378 // Load r2 into a virtual register and store it to the TOC save area. 6379 setUsesTOCBasePtr(DAG); 6380 SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64); 6381 // TOC save area offset. 6382 unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset(); 6383 SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl); 6384 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 6385 Chain = DAG.getStore( 6386 Val.getValue(1), dl, Val, AddPtr, 6387 MachinePointerInfo::getStack(DAG.getMachineFunction(), TOCSaveOffset)); 6388 // In the ELFv2 ABI, R12 must contain the address of an indirect callee. 6389 // This does not mean the MTCTR instruction must use R12; it's easier 6390 // to model this as an extra parameter, so do that. 6391 if (isELFv2ABI && !isPatchPoint) 6392 RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee)); 6393 } 6394 6395 // Build a sequence of copy-to-reg nodes chained together with token chain 6396 // and flag operands which copy the outgoing args into the appropriate regs. 6397 SDValue InFlag; 6398 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 6399 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 6400 RegsToPass[i].second, InFlag); 6401 InFlag = Chain.getValue(1); 6402 } 6403 6404 if (isTailCall && !IsSibCall) 6405 PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp, 6406 TailCallArguments); 6407 6408 return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint, hasNest, 6409 DAG, RegsToPass, InFlag, Chain, CallSeqStart, Callee, 6410 SPDiff, NumBytes, Ins, InVals, CS); 6411 } 6412 6413 SDValue PPCTargetLowering::LowerCall_Darwin( 6414 SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg, 6415 bool isTailCall, bool isPatchPoint, 6416 const SmallVectorImpl<ISD::OutputArg> &Outs, 6417 const SmallVectorImpl<SDValue> &OutVals, 6418 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 6419 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 6420 ImmutableCallSite CS) const { 6421 unsigned NumOps = Outs.size(); 6422 6423 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 6424 bool isPPC64 = PtrVT == MVT::i64; 6425 unsigned PtrByteSize = isPPC64 ? 8 : 4; 6426 6427 MachineFunction &MF = DAG.getMachineFunction(); 6428 6429 // Mark this function as potentially containing a function that contains a 6430 // tail call. As a consequence the frame pointer will be used for dynamicalloc 6431 // and restoring the callers stack pointer in this functions epilog. This is 6432 // done because by tail calling the called function might overwrite the value 6433 // in this function's (MF) stack pointer stack slot 0(SP). 6434 if (getTargetMachine().Options.GuaranteedTailCallOpt && 6435 CallConv == CallingConv::Fast) 6436 MF.getInfo<PPCFunctionInfo>()->setHasFastCall(); 6437 6438 // Count how many bytes are to be pushed on the stack, including the linkage 6439 // area, and parameter passing area. We start with 24/48 bytes, which is 6440 // prereserved space for [SP][CR][LR][3 x unused]. 6441 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 6442 unsigned NumBytes = LinkageSize; 6443 6444 // Add up all the space actually used. 6445 // In 32-bit non-varargs calls, Altivec parameters all go at the end; usually 6446 // they all go in registers, but we must reserve stack space for them for 6447 // possible use by the caller. In varargs or 64-bit calls, parameters are 6448 // assigned stack space in order, with padding so Altivec parameters are 6449 // 16-byte aligned. 6450 unsigned nAltivecParamsAtEnd = 0; 6451 for (unsigned i = 0; i != NumOps; ++i) { 6452 ISD::ArgFlagsTy Flags = Outs[i].Flags; 6453 EVT ArgVT = Outs[i].VT; 6454 // Varargs Altivec parameters are padded to a 16 byte boundary. 6455 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 || 6456 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 || 6457 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64) { 6458 if (!isVarArg && !isPPC64) { 6459 // Non-varargs Altivec parameters go after all the non-Altivec 6460 // parameters; handle those later so we know how much padding we need. 6461 nAltivecParamsAtEnd++; 6462 continue; 6463 } 6464 // Varargs and 64-bit Altivec parameters are padded to 16 byte boundary. 6465 NumBytes = ((NumBytes+15)/16)*16; 6466 } 6467 NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize); 6468 } 6469 6470 // Allow for Altivec parameters at the end, if needed. 6471 if (nAltivecParamsAtEnd) { 6472 NumBytes = ((NumBytes+15)/16)*16; 6473 NumBytes += 16*nAltivecParamsAtEnd; 6474 } 6475 6476 // The prolog code of the callee may store up to 8 GPR argument registers to 6477 // the stack, allowing va_start to index over them in memory if its varargs. 6478 // Because we cannot tell if this is needed on the caller side, we have to 6479 // conservatively assume that it is needed. As such, make sure we have at 6480 // least enough stack space for the caller to store the 8 GPRs. 6481 NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize); 6482 6483 // Tail call needs the stack to be aligned. 6484 if (getTargetMachine().Options.GuaranteedTailCallOpt && 6485 CallConv == CallingConv::Fast) 6486 NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes); 6487 6488 // Calculate by how many bytes the stack has to be adjusted in case of tail 6489 // call optimization. 6490 int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes); 6491 6492 // To protect arguments on the stack from being clobbered in a tail call, 6493 // force all the loads to happen before doing any other lowering. 6494 if (isTailCall) 6495 Chain = DAG.getStackArgumentTokenFactor(Chain); 6496 6497 // Adjust the stack pointer for the new arguments... 6498 // These operations are automatically eliminated by the prolog/epilog pass 6499 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 6500 SDValue CallSeqStart = Chain; 6501 6502 // Load the return address and frame pointer so it can be move somewhere else 6503 // later. 6504 SDValue LROp, FPOp; 6505 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl); 6506 6507 // Set up a copy of the stack pointer for use loading and storing any 6508 // arguments that may not fit in the registers available for argument 6509 // passing. 6510 SDValue StackPtr; 6511 if (isPPC64) 6512 StackPtr = DAG.getRegister(PPC::X1, MVT::i64); 6513 else 6514 StackPtr = DAG.getRegister(PPC::R1, MVT::i32); 6515 6516 // Figure out which arguments are going to go in registers, and which in 6517 // memory. Also, if this is a vararg function, floating point operations 6518 // must be stored to our stack, and loaded into integer regs as well, if 6519 // any integer regs are available for argument passing. 6520 unsigned ArgOffset = LinkageSize; 6521 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 6522 6523 static const MCPhysReg GPR_32[] = { // 32-bit registers. 6524 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 6525 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 6526 }; 6527 static const MCPhysReg GPR_64[] = { // 64-bit registers. 6528 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 6529 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 6530 }; 6531 static const MCPhysReg VR[] = { 6532 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 6533 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 6534 }; 6535 const unsigned NumGPRs = array_lengthof(GPR_32); 6536 const unsigned NumFPRs = 13; 6537 const unsigned NumVRs = array_lengthof(VR); 6538 6539 const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32; 6540 6541 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 6542 SmallVector<TailCallArgumentInfo, 8> TailCallArguments; 6543 6544 SmallVector<SDValue, 8> MemOpChains; 6545 for (unsigned i = 0; i != NumOps; ++i) { 6546 SDValue Arg = OutVals[i]; 6547 ISD::ArgFlagsTy Flags = Outs[i].Flags; 6548 6549 // PtrOff will be used to store the current argument to the stack if a 6550 // register cannot be found for it. 6551 SDValue PtrOff; 6552 6553 PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType()); 6554 6555 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 6556 6557 // On PPC64, promote integers to 64-bit values. 6558 if (isPPC64 && Arg.getValueType() == MVT::i32) { 6559 // FIXME: Should this use ANY_EXTEND if neither sext nor zext? 6560 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 6561 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg); 6562 } 6563 6564 // FIXME memcpy is used way more than necessary. Correctness first. 6565 // Note: "by value" is code for passing a structure by value, not 6566 // basic types. 6567 if (Flags.isByVal()) { 6568 unsigned Size = Flags.getByValSize(); 6569 // Very small objects are passed right-justified. Everything else is 6570 // passed left-justified. 6571 if (Size==1 || Size==2) { 6572 EVT VT = (Size==1) ? MVT::i8 : MVT::i16; 6573 if (GPR_idx != NumGPRs) { 6574 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg, 6575 MachinePointerInfo(), VT); 6576 MemOpChains.push_back(Load.getValue(1)); 6577 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6578 6579 ArgOffset += PtrByteSize; 6580 } else { 6581 SDValue Const = DAG.getConstant(PtrByteSize - Size, dl, 6582 PtrOff.getValueType()); 6583 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const); 6584 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr, 6585 CallSeqStart, 6586 Flags, DAG, dl); 6587 ArgOffset += PtrByteSize; 6588 } 6589 continue; 6590 } 6591 // Copy entire object into memory. There are cases where gcc-generated 6592 // code assumes it is there, even if it could be put entirely into 6593 // registers. (This is not what the doc says.) 6594 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff, 6595 CallSeqStart, 6596 Flags, DAG, dl); 6597 6598 // For small aggregates (Darwin only) and aggregates >= PtrByteSize, 6599 // copy the pieces of the object that fit into registers from the 6600 // parameter save area. 6601 for (unsigned j=0; j<Size; j+=PtrByteSize) { 6602 SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType()); 6603 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const); 6604 if (GPR_idx != NumGPRs) { 6605 SDValue Load = 6606 DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo()); 6607 MemOpChains.push_back(Load.getValue(1)); 6608 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6609 ArgOffset += PtrByteSize; 6610 } else { 6611 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize; 6612 break; 6613 } 6614 } 6615 continue; 6616 } 6617 6618 switch (Arg.getSimpleValueType().SimpleTy) { 6619 default: llvm_unreachable("Unexpected ValueType for argument!"); 6620 case MVT::i1: 6621 case MVT::i32: 6622 case MVT::i64: 6623 if (GPR_idx != NumGPRs) { 6624 if (Arg.getValueType() == MVT::i1) 6625 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, PtrVT, Arg); 6626 6627 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg)); 6628 } else { 6629 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6630 isPPC64, isTailCall, false, MemOpChains, 6631 TailCallArguments, dl); 6632 } 6633 ArgOffset += PtrByteSize; 6634 break; 6635 case MVT::f32: 6636 case MVT::f64: 6637 if (FPR_idx != NumFPRs) { 6638 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg)); 6639 6640 if (isVarArg) { 6641 SDValue Store = 6642 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 6643 MemOpChains.push_back(Store); 6644 6645 // Float varargs are always shadowed in available integer registers 6646 if (GPR_idx != NumGPRs) { 6647 SDValue Load = 6648 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo()); 6649 MemOpChains.push_back(Load.getValue(1)); 6650 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6651 } 6652 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && !isPPC64){ 6653 SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType()); 6654 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour); 6655 SDValue Load = 6656 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo()); 6657 MemOpChains.push_back(Load.getValue(1)); 6658 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6659 } 6660 } else { 6661 // If we have any FPRs remaining, we may also have GPRs remaining. 6662 // Args passed in FPRs consume either 1 (f32) or 2 (f64) available 6663 // GPRs. 6664 if (GPR_idx != NumGPRs) 6665 ++GPR_idx; 6666 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && 6667 !isPPC64) // PPC64 has 64-bit GPR's obviously :) 6668 ++GPR_idx; 6669 } 6670 } else 6671 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6672 isPPC64, isTailCall, false, MemOpChains, 6673 TailCallArguments, dl); 6674 if (isPPC64) 6675 ArgOffset += 8; 6676 else 6677 ArgOffset += Arg.getValueType() == MVT::f32 ? 4 : 8; 6678 break; 6679 case MVT::v4f32: 6680 case MVT::v4i32: 6681 case MVT::v8i16: 6682 case MVT::v16i8: 6683 if (isVarArg) { 6684 // These go aligned on the stack, or in the corresponding R registers 6685 // when within range. The Darwin PPC ABI doc claims they also go in 6686 // V registers; in fact gcc does this only for arguments that are 6687 // prototyped, not for those that match the ... We do it for all 6688 // arguments, seems to work. 6689 while (ArgOffset % 16 !=0) { 6690 ArgOffset += PtrByteSize; 6691 if (GPR_idx != NumGPRs) 6692 GPR_idx++; 6693 } 6694 // We could elide this store in the case where the object fits 6695 // entirely in R registers. Maybe later. 6696 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, 6697 DAG.getConstant(ArgOffset, dl, PtrVT)); 6698 SDValue Store = 6699 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 6700 MemOpChains.push_back(Store); 6701 if (VR_idx != NumVRs) { 6702 SDValue Load = 6703 DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo()); 6704 MemOpChains.push_back(Load.getValue(1)); 6705 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load)); 6706 } 6707 ArgOffset += 16; 6708 for (unsigned i=0; i<16; i+=PtrByteSize) { 6709 if (GPR_idx == NumGPRs) 6710 break; 6711 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, 6712 DAG.getConstant(i, dl, PtrVT)); 6713 SDValue Load = 6714 DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo()); 6715 MemOpChains.push_back(Load.getValue(1)); 6716 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6717 } 6718 break; 6719 } 6720 6721 // Non-varargs Altivec params generally go in registers, but have 6722 // stack space allocated at the end. 6723 if (VR_idx != NumVRs) { 6724 // Doesn't have GPR space allocated. 6725 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg)); 6726 } else if (nAltivecParamsAtEnd==0) { 6727 // We are emitting Altivec params in order. 6728 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6729 isPPC64, isTailCall, true, MemOpChains, 6730 TailCallArguments, dl); 6731 ArgOffset += 16; 6732 } 6733 break; 6734 } 6735 } 6736 // If all Altivec parameters fit in registers, as they usually do, 6737 // they get stack space following the non-Altivec parameters. We 6738 // don't track this here because nobody below needs it. 6739 // If there are more Altivec parameters than fit in registers emit 6740 // the stores here. 6741 if (!isVarArg && nAltivecParamsAtEnd > NumVRs) { 6742 unsigned j = 0; 6743 // Offset is aligned; skip 1st 12 params which go in V registers. 6744 ArgOffset = ((ArgOffset+15)/16)*16; 6745 ArgOffset += 12*16; 6746 for (unsigned i = 0; i != NumOps; ++i) { 6747 SDValue Arg = OutVals[i]; 6748 EVT ArgType = Outs[i].VT; 6749 if (ArgType==MVT::v4f32 || ArgType==MVT::v4i32 || 6750 ArgType==MVT::v8i16 || ArgType==MVT::v16i8) { 6751 if (++j > NumVRs) { 6752 SDValue PtrOff; 6753 // We are emitting Altivec params in order. 6754 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6755 isPPC64, isTailCall, true, MemOpChains, 6756 TailCallArguments, dl); 6757 ArgOffset += 16; 6758 } 6759 } 6760 } 6761 } 6762 6763 if (!MemOpChains.empty()) 6764 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 6765 6766 // On Darwin, R12 must contain the address of an indirect callee. This does 6767 // not mean the MTCTR instruction must use R12; it's easier to model this as 6768 // an extra parameter, so do that. 6769 if (!isTailCall && 6770 !isFunctionGlobalAddress(Callee) && 6771 !isa<ExternalSymbolSDNode>(Callee) && 6772 !isBLACompatibleAddress(Callee, DAG)) 6773 RegsToPass.push_back(std::make_pair((unsigned)(isPPC64 ? PPC::X12 : 6774 PPC::R12), Callee)); 6775 6776 // Build a sequence of copy-to-reg nodes chained together with token chain 6777 // and flag operands which copy the outgoing args into the appropriate regs. 6778 SDValue InFlag; 6779 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 6780 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 6781 RegsToPass[i].second, InFlag); 6782 InFlag = Chain.getValue(1); 6783 } 6784 6785 if (isTailCall) 6786 PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp, 6787 TailCallArguments); 6788 6789 return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint, 6790 /* unused except on PPC64 ELFv1 */ false, DAG, 6791 RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff, 6792 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.isSRet()) 6806 report_fatal_error("Struct return arguments are unimplemented."); 6807 6808 if (ArgFlags.isNest()) 6809 report_fatal_error("Nest arguments are unimplemented."); 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 State.AllocateStack(PtrByteSize, PtrByteSize); 6834 if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32)) { 6835 MVT RegVT = IsPPC64 ? MVT::i64 : MVT::i32; 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 report_fatal_error("Handling of placing parameters on the stack is " 6844 "unimplemented!"); 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 State.AllocateStack(IsPPC64 ? 8 : StoreSize, 4); 6854 if (unsigned Reg = State.AllocateReg(FPR)) 6855 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, MVT::f64, LocInfo)); 6856 else 6857 report_fatal_error("Handling of placing parameters on the stack is " 6858 "unimplemented!"); 6859 6860 // f32 reserves 1 GPR in both PPC32 and PPC64. 6861 // f64 reserves 2 GPRs in PPC32 and 1 GPR in PPC64. 6862 for (unsigned i = 0; i < StoreSize; i += PtrByteSize) 6863 State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32); 6864 return false; 6865 } 6866 } 6867 } 6868 6869 static const TargetRegisterClass *getRegClassForSVT(MVT::SimpleValueType SVT, 6870 bool IsPPC64) { 6871 assert((IsPPC64 || SVT != MVT::i64) && 6872 "i64 should have been split for 32-bit codegen."); 6873 6874 switch (SVT) { 6875 default: 6876 report_fatal_error("Unexpected value type for formal argument"); 6877 case MVT::i1: 6878 case MVT::i32: 6879 case MVT::i64: 6880 return IsPPC64 ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 6881 case MVT::f32: 6882 return &PPC::F4RCRegClass; 6883 case MVT::f64: 6884 return &PPC::F8RCRegClass; 6885 } 6886 } 6887 6888 static SDValue truncateScalarIntegerArg(ISD::ArgFlagsTy Flags, EVT ValVT, 6889 SelectionDAG &DAG, SDValue ArgValue, 6890 MVT LocVT, const SDLoc &dl) { 6891 assert(ValVT.isScalarInteger() && LocVT.isScalarInteger()); 6892 assert(ValVT.getSizeInBits() < LocVT.getSizeInBits()); 6893 6894 if (Flags.isSExt()) 6895 ArgValue = DAG.getNode(ISD::AssertSext, dl, LocVT, ArgValue, 6896 DAG.getValueType(ValVT)); 6897 else if (Flags.isZExt()) 6898 ArgValue = DAG.getNode(ISD::AssertZext, dl, LocVT, ArgValue, 6899 DAG.getValueType(ValVT)); 6900 6901 return DAG.getNode(ISD::TRUNCATE, dl, ValVT, ArgValue); 6902 } 6903 6904 SDValue PPCTargetLowering::LowerFormalArguments_AIX( 6905 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 6906 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 6907 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 6908 6909 assert((CallConv == CallingConv::C || CallConv == CallingConv::Cold || 6910 CallConv == CallingConv::Fast) && 6911 "Unexpected calling convention!"); 6912 6913 if (isVarArg) 6914 report_fatal_error("This call type is unimplemented on AIX."); 6915 6916 if (getTargetMachine().Options.GuaranteedTailCallOpt) 6917 report_fatal_error("Tail call support is unimplemented on AIX."); 6918 6919 if (useSoftFloat()) 6920 report_fatal_error("Soft float support is unimplemented on AIX."); 6921 6922 const PPCSubtarget &Subtarget = 6923 static_cast<const PPCSubtarget &>(DAG.getSubtarget()); 6924 if (Subtarget.hasQPX()) 6925 report_fatal_error("QPX support is not supported on AIX."); 6926 6927 const bool IsPPC64 = Subtarget.isPPC64(); 6928 const unsigned PtrByteSize = IsPPC64 ? 8 : 4; 6929 6930 // Assign locations to all of the incoming arguments. 6931 SmallVector<CCValAssign, 16> ArgLocs; 6932 MachineFunction &MF = DAG.getMachineFunction(); 6933 CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext()); 6934 6935 // Reserve space for the linkage area on the stack. 6936 const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 6937 // On AIX a minimum of 8 words is saved to the parameter save area. 6938 const unsigned MinParameterSaveArea = 8 * PtrByteSize; 6939 CCInfo.AllocateStack(LinkageSize + MinParameterSaveArea, PtrByteSize); 6940 CCInfo.AnalyzeFormalArguments(Ins, CC_AIX); 6941 6942 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 6943 CCValAssign &VA = ArgLocs[i]; 6944 SDValue ArgValue; 6945 ISD::ArgFlagsTy Flags = Ins[i].Flags; 6946 if (VA.isRegLoc()) { 6947 EVT ValVT = VA.getValVT(); 6948 MVT LocVT = VA.getLocVT(); 6949 MVT::SimpleValueType SVT = ValVT.getSimpleVT().SimpleTy; 6950 unsigned VReg = 6951 MF.addLiveIn(VA.getLocReg(), getRegClassForSVT(SVT, IsPPC64)); 6952 ArgValue = DAG.getCopyFromReg(Chain, dl, VReg, LocVT); 6953 if (ValVT.isScalarInteger() && 6954 (ValVT.getSizeInBits() < LocVT.getSizeInBits())) { 6955 ArgValue = 6956 truncateScalarIntegerArg(Flags, ValVT, DAG, ArgValue, LocVT, dl); 6957 } 6958 InVals.push_back(ArgValue); 6959 } else { 6960 report_fatal_error("Handling of formal arguments on the stack is " 6961 "unimplemented!"); 6962 } 6963 } 6964 6965 // Area that is at least reserved in the caller of this function. 6966 unsigned MinReservedArea = CCInfo.getNextStackOffset(); 6967 6968 // Set the size that is at least reserved in caller of this function. Tail 6969 // call optimized function's reserved stack space needs to be aligned so 6970 // that taking the difference between two stack areas will result in an 6971 // aligned stack. 6972 MinReservedArea = 6973 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea); 6974 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 6975 FuncInfo->setMinReservedArea(MinReservedArea); 6976 6977 return Chain; 6978 } 6979 6980 SDValue PPCTargetLowering::LowerCall_AIX( 6981 SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg, 6982 bool isTailCall, bool isPatchPoint, 6983 const SmallVectorImpl<ISD::OutputArg> &Outs, 6984 const SmallVectorImpl<SDValue> &OutVals, 6985 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 6986 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 6987 ImmutableCallSite CS) const { 6988 6989 assert((CallConv == CallingConv::C || 6990 CallConv == CallingConv::Cold || 6991 CallConv == CallingConv::Fast) && "Unexpected calling convention!"); 6992 6993 if (isVarArg || isPatchPoint) 6994 report_fatal_error("This call type is unimplemented on AIX."); 6995 6996 const PPCSubtarget& Subtarget = 6997 static_cast<const PPCSubtarget&>(DAG.getSubtarget()); 6998 if (Subtarget.hasQPX()) 6999 report_fatal_error("QPX is not supported on AIX."); 7000 if (Subtarget.hasAltivec()) 7001 report_fatal_error("Altivec support is unimplemented on AIX."); 7002 7003 MachineFunction &MF = DAG.getMachineFunction(); 7004 SmallVector<CCValAssign, 16> ArgLocs; 7005 CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext()); 7006 7007 // Reserve space for the linkage save area (LSA) on the stack. 7008 // In both PPC32 and PPC64 there are 6 reserved slots in the LSA: 7009 // [SP][CR][LR][2 x reserved][TOC]. 7010 // The LSA is 24 bytes (6x4) in PPC32 and 48 bytes (6x8) in PPC64. 7011 const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 7012 const unsigned PtrByteSize = Subtarget.isPPC64() ? 8 : 4; 7013 CCInfo.AllocateStack(LinkageSize, PtrByteSize); 7014 CCInfo.AnalyzeCallOperands(Outs, CC_AIX); 7015 7016 // The prolog code of the callee may store up to 8 GPR argument registers to 7017 // the stack, allowing va_start to index over them in memory if the callee 7018 // is variadic. 7019 // Because we cannot tell if this is needed on the caller side, we have to 7020 // conservatively assume that it is needed. As such, make sure we have at 7021 // least enough stack space for the caller to store the 8 GPRs. 7022 const unsigned MinParameterSaveAreaSize = 8 * PtrByteSize; 7023 const unsigned NumBytes = LinkageSize + MinParameterSaveAreaSize; 7024 7025 // Adjust the stack pointer for the new arguments... 7026 // These operations are automatically eliminated by the prolog/epilog pass. 7027 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 7028 SDValue CallSeqStart = Chain; 7029 7030 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 7031 7032 for (CCValAssign &VA : ArgLocs) { 7033 SDValue Arg = OutVals[VA.getValNo()]; 7034 7035 switch (VA.getLocInfo()) { 7036 default: report_fatal_error("Unexpected argument extension type."); 7037 case CCValAssign::Full: break; 7038 case CCValAssign::ZExt: 7039 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg); 7040 break; 7041 case CCValAssign::SExt: 7042 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg); 7043 break; 7044 } 7045 7046 if (VA.isRegLoc()) 7047 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 7048 7049 if (VA.isMemLoc()) 7050 report_fatal_error("Handling of placing parameters on the stack is " 7051 "unimplemented!"); 7052 } 7053 7054 // For indirect calls, we need to save the TOC base to the stack for 7055 // restoration after the call. 7056 if (!isTailCall && !isPatchPoint && 7057 !isFunctionGlobalAddress(Callee) && !isa<ExternalSymbolSDNode>(Callee)) { 7058 const MCRegister TOCBaseReg = Subtarget.getTOCPointerRegister(); 7059 const MCRegister StackPtrReg = Subtarget.getStackPointerRegister(); 7060 const MVT PtrVT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32; 7061 const unsigned TOCSaveOffset = 7062 Subtarget.getFrameLowering()->getTOCSaveOffset(); 7063 7064 setUsesTOCBasePtr(DAG); 7065 SDValue Val = DAG.getCopyFromReg(Chain, dl, TOCBaseReg, PtrVT); 7066 SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl); 7067 SDValue StackPtr = DAG.getRegister(StackPtrReg, PtrVT); 7068 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 7069 Chain = DAG.getStore( 7070 Val.getValue(1), dl, Val, AddPtr, 7071 MachinePointerInfo::getStack(DAG.getMachineFunction(), TOCSaveOffset)); 7072 } 7073 7074 // Build a sequence of copy-to-reg nodes chained together with token chain 7075 // and flag operands which copy the outgoing args into the appropriate regs. 7076 SDValue InFlag; 7077 for (auto Reg : RegsToPass) { 7078 Chain = DAG.getCopyToReg(Chain, dl, Reg.first, Reg.second, InFlag); 7079 InFlag = Chain.getValue(1); 7080 } 7081 7082 const int SPDiff = 0; 7083 return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint, 7084 /* unused except on PPC64 ELFv1 */ false, DAG, RegsToPass, 7085 InFlag, Chain, CallSeqStart, Callee, SPDiff, NumBytes, Ins, 7086 InVals, CS); 7087 } 7088 7089 bool 7090 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv, 7091 MachineFunction &MF, bool isVarArg, 7092 const SmallVectorImpl<ISD::OutputArg> &Outs, 7093 LLVMContext &Context) const { 7094 SmallVector<CCValAssign, 16> RVLocs; 7095 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context); 7096 return CCInfo.CheckReturn( 7097 Outs, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold) 7098 ? RetCC_PPC_Cold 7099 : RetCC_PPC); 7100 } 7101 7102 SDValue 7103 PPCTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 7104 bool isVarArg, 7105 const SmallVectorImpl<ISD::OutputArg> &Outs, 7106 const SmallVectorImpl<SDValue> &OutVals, 7107 const SDLoc &dl, SelectionDAG &DAG) const { 7108 SmallVector<CCValAssign, 16> RVLocs; 7109 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 7110 *DAG.getContext()); 7111 CCInfo.AnalyzeReturn(Outs, 7112 (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold) 7113 ? RetCC_PPC_Cold 7114 : RetCC_PPC); 7115 7116 SDValue Flag; 7117 SmallVector<SDValue, 4> RetOps(1, Chain); 7118 7119 // Copy the result values into the output registers. 7120 for (unsigned i = 0, RealResIdx = 0; i != RVLocs.size(); ++i, ++RealResIdx) { 7121 CCValAssign &VA = RVLocs[i]; 7122 assert(VA.isRegLoc() && "Can only return in registers!"); 7123 7124 SDValue Arg = OutVals[RealResIdx]; 7125 7126 switch (VA.getLocInfo()) { 7127 default: llvm_unreachable("Unknown loc info!"); 7128 case CCValAssign::Full: break; 7129 case CCValAssign::AExt: 7130 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg); 7131 break; 7132 case CCValAssign::ZExt: 7133 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg); 7134 break; 7135 case CCValAssign::SExt: 7136 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg); 7137 break; 7138 } 7139 if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) { 7140 bool isLittleEndian = Subtarget.isLittleEndian(); 7141 // Legalize ret f64 -> ret 2 x i32. 7142 SDValue SVal = 7143 DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg, 7144 DAG.getIntPtrConstant(isLittleEndian ? 0 : 1, dl)); 7145 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Flag); 7146 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 7147 SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg, 7148 DAG.getIntPtrConstant(isLittleEndian ? 1 : 0, dl)); 7149 Flag = Chain.getValue(1); 7150 VA = RVLocs[++i]; // skip ahead to next loc 7151 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Flag); 7152 } else 7153 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag); 7154 Flag = Chain.getValue(1); 7155 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 7156 } 7157 7158 const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo(); 7159 const MCPhysReg *I = 7160 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction()); 7161 if (I) { 7162 for (; *I; ++I) { 7163 7164 if (PPC::G8RCRegClass.contains(*I)) 7165 RetOps.push_back(DAG.getRegister(*I, MVT::i64)); 7166 else if (PPC::F8RCRegClass.contains(*I)) 7167 RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64))); 7168 else if (PPC::CRRCRegClass.contains(*I)) 7169 RetOps.push_back(DAG.getRegister(*I, MVT::i1)); 7170 else if (PPC::VRRCRegClass.contains(*I)) 7171 RetOps.push_back(DAG.getRegister(*I, MVT::Other)); 7172 else 7173 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 7174 } 7175 } 7176 7177 RetOps[0] = Chain; // Update chain. 7178 7179 // Add the flag if we have it. 7180 if (Flag.getNode()) 7181 RetOps.push_back(Flag); 7182 7183 return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, RetOps); 7184 } 7185 7186 SDValue 7187 PPCTargetLowering::LowerGET_DYNAMIC_AREA_OFFSET(SDValue Op, 7188 SelectionDAG &DAG) const { 7189 SDLoc dl(Op); 7190 7191 // Get the correct type for integers. 7192 EVT IntVT = Op.getValueType(); 7193 7194 // Get the inputs. 7195 SDValue Chain = Op.getOperand(0); 7196 SDValue FPSIdx = getFramePointerFrameIndex(DAG); 7197 // Build a DYNAREAOFFSET node. 7198 SDValue Ops[2] = {Chain, FPSIdx}; 7199 SDVTList VTs = DAG.getVTList(IntVT); 7200 return DAG.getNode(PPCISD::DYNAREAOFFSET, dl, VTs, Ops); 7201 } 7202 7203 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op, 7204 SelectionDAG &DAG) const { 7205 // When we pop the dynamic allocation we need to restore the SP link. 7206 SDLoc dl(Op); 7207 7208 // Get the correct type for pointers. 7209 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7210 7211 // Construct the stack pointer operand. 7212 bool isPPC64 = Subtarget.isPPC64(); 7213 unsigned SP = isPPC64 ? PPC::X1 : PPC::R1; 7214 SDValue StackPtr = DAG.getRegister(SP, PtrVT); 7215 7216 // Get the operands for the STACKRESTORE. 7217 SDValue Chain = Op.getOperand(0); 7218 SDValue SaveSP = Op.getOperand(1); 7219 7220 // Load the old link SP. 7221 SDValue LoadLinkSP = 7222 DAG.getLoad(PtrVT, dl, Chain, StackPtr, MachinePointerInfo()); 7223 7224 // Restore the stack pointer. 7225 Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP); 7226 7227 // Store the old link SP. 7228 return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo()); 7229 } 7230 7231 SDValue PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG &DAG) const { 7232 MachineFunction &MF = DAG.getMachineFunction(); 7233 bool isPPC64 = Subtarget.isPPC64(); 7234 EVT PtrVT = getPointerTy(MF.getDataLayout()); 7235 7236 // Get current frame pointer save index. The users of this index will be 7237 // primarily DYNALLOC instructions. 7238 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>(); 7239 int RASI = FI->getReturnAddrSaveIndex(); 7240 7241 // If the frame pointer save index hasn't been defined yet. 7242 if (!RASI) { 7243 // Find out what the fix offset of the frame pointer save area. 7244 int LROffset = Subtarget.getFrameLowering()->getReturnSaveOffset(); 7245 // Allocate the frame index for frame pointer save area. 7246 RASI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, LROffset, false); 7247 // Save the result. 7248 FI->setReturnAddrSaveIndex(RASI); 7249 } 7250 return DAG.getFrameIndex(RASI, PtrVT); 7251 } 7252 7253 SDValue 7254 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const { 7255 MachineFunction &MF = DAG.getMachineFunction(); 7256 bool isPPC64 = Subtarget.isPPC64(); 7257 EVT PtrVT = getPointerTy(MF.getDataLayout()); 7258 7259 // Get current frame pointer save index. The users of this index will be 7260 // primarily DYNALLOC instructions. 7261 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>(); 7262 int FPSI = FI->getFramePointerSaveIndex(); 7263 7264 // If the frame pointer save index hasn't been defined yet. 7265 if (!FPSI) { 7266 // Find out what the fix offset of the frame pointer save area. 7267 int FPOffset = Subtarget.getFrameLowering()->getFramePointerSaveOffset(); 7268 // Allocate the frame index for frame pointer save area. 7269 FPSI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, FPOffset, true); 7270 // Save the result. 7271 FI->setFramePointerSaveIndex(FPSI); 7272 } 7273 return DAG.getFrameIndex(FPSI, PtrVT); 7274 } 7275 7276 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, 7277 SelectionDAG &DAG) const { 7278 // Get the inputs. 7279 SDValue Chain = Op.getOperand(0); 7280 SDValue Size = Op.getOperand(1); 7281 SDLoc dl(Op); 7282 7283 // Get the correct type for pointers. 7284 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7285 // Negate the size. 7286 SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT, 7287 DAG.getConstant(0, dl, PtrVT), Size); 7288 // Construct a node for the frame pointer save index. 7289 SDValue FPSIdx = getFramePointerFrameIndex(DAG); 7290 // Build a DYNALLOC node. 7291 SDValue Ops[3] = { Chain, NegSize, FPSIdx }; 7292 SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other); 7293 return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops); 7294 } 7295 7296 SDValue PPCTargetLowering::LowerEH_DWARF_CFA(SDValue Op, 7297 SelectionDAG &DAG) const { 7298 MachineFunction &MF = DAG.getMachineFunction(); 7299 7300 bool isPPC64 = Subtarget.isPPC64(); 7301 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7302 7303 int FI = MF.getFrameInfo().CreateFixedObject(isPPC64 ? 8 : 4, 0, false); 7304 return DAG.getFrameIndex(FI, PtrVT); 7305 } 7306 7307 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op, 7308 SelectionDAG &DAG) const { 7309 SDLoc DL(Op); 7310 return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL, 7311 DAG.getVTList(MVT::i32, MVT::Other), 7312 Op.getOperand(0), Op.getOperand(1)); 7313 } 7314 7315 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op, 7316 SelectionDAG &DAG) const { 7317 SDLoc DL(Op); 7318 return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other, 7319 Op.getOperand(0), Op.getOperand(1)); 7320 } 7321 7322 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const { 7323 if (Op.getValueType().isVector()) 7324 return LowerVectorLoad(Op, DAG); 7325 7326 assert(Op.getValueType() == MVT::i1 && 7327 "Custom lowering only for i1 loads"); 7328 7329 // First, load 8 bits into 32 bits, then truncate to 1 bit. 7330 7331 SDLoc dl(Op); 7332 LoadSDNode *LD = cast<LoadSDNode>(Op); 7333 7334 SDValue Chain = LD->getChain(); 7335 SDValue BasePtr = LD->getBasePtr(); 7336 MachineMemOperand *MMO = LD->getMemOperand(); 7337 7338 SDValue NewLD = 7339 DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(DAG.getDataLayout()), Chain, 7340 BasePtr, MVT::i8, MMO); 7341 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD); 7342 7343 SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) }; 7344 return DAG.getMergeValues(Ops, dl); 7345 } 7346 7347 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const { 7348 if (Op.getOperand(1).getValueType().isVector()) 7349 return LowerVectorStore(Op, DAG); 7350 7351 assert(Op.getOperand(1).getValueType() == MVT::i1 && 7352 "Custom lowering only for i1 stores"); 7353 7354 // First, zero extend to 32 bits, then use a truncating store to 8 bits. 7355 7356 SDLoc dl(Op); 7357 StoreSDNode *ST = cast<StoreSDNode>(Op); 7358 7359 SDValue Chain = ST->getChain(); 7360 SDValue BasePtr = ST->getBasePtr(); 7361 SDValue Value = ST->getValue(); 7362 MachineMemOperand *MMO = ST->getMemOperand(); 7363 7364 Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(DAG.getDataLayout()), 7365 Value); 7366 return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO); 7367 } 7368 7369 // FIXME: Remove this once the ANDI glue bug is fixed: 7370 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const { 7371 assert(Op.getValueType() == MVT::i1 && 7372 "Custom lowering only for i1 results"); 7373 7374 SDLoc DL(Op); 7375 return DAG.getNode(PPCISD::ANDIo_1_GT_BIT, DL, MVT::i1, 7376 Op.getOperand(0)); 7377 } 7378 7379 SDValue PPCTargetLowering::LowerTRUNCATEVector(SDValue Op, 7380 SelectionDAG &DAG) const { 7381 7382 // Implements a vector truncate that fits in a vector register as a shuffle. 7383 // We want to legalize vector truncates down to where the source fits in 7384 // a vector register (and target is therefore smaller than vector register 7385 // size). At that point legalization will try to custom lower the sub-legal 7386 // result and get here - where we can contain the truncate as a single target 7387 // operation. 7388 7389 // For example a trunc <2 x i16> to <2 x i8> could be visualized as follows: 7390 // <MSB1|LSB1, MSB2|LSB2> to <LSB1, LSB2> 7391 // 7392 // We will implement it for big-endian ordering as this (where x denotes 7393 // undefined): 7394 // < MSB1|LSB1, MSB2|LSB2, uu, uu, uu, uu, uu, uu> to 7395 // < LSB1, LSB2, u, u, u, u, u, u, u, u, u, u, u, u, u, u> 7396 // 7397 // The same operation in little-endian ordering will be: 7398 // <uu, uu, uu, uu, uu, uu, LSB2|MSB2, LSB1|MSB1> to 7399 // <u, u, u, u, u, u, u, u, u, u, u, u, u, u, LSB2, LSB1> 7400 7401 assert(Op.getValueType().isVector() && "Vector type expected."); 7402 7403 SDLoc DL(Op); 7404 SDValue N1 = Op.getOperand(0); 7405 unsigned SrcSize = N1.getValueType().getSizeInBits(); 7406 assert(SrcSize <= 128 && "Source must fit in an Altivec/VSX vector"); 7407 SDValue WideSrc = SrcSize == 128 ? N1 : widenVec(DAG, N1, DL); 7408 7409 EVT TrgVT = Op.getValueType(); 7410 unsigned TrgNumElts = TrgVT.getVectorNumElements(); 7411 EVT EltVT = TrgVT.getVectorElementType(); 7412 unsigned WideNumElts = 128 / EltVT.getSizeInBits(); 7413 EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts); 7414 7415 // First list the elements we want to keep. 7416 unsigned SizeMult = SrcSize / TrgVT.getSizeInBits(); 7417 SmallVector<int, 16> ShuffV; 7418 if (Subtarget.isLittleEndian()) 7419 for (unsigned i = 0; i < TrgNumElts; ++i) 7420 ShuffV.push_back(i * SizeMult); 7421 else 7422 for (unsigned i = 1; i <= TrgNumElts; ++i) 7423 ShuffV.push_back(i * SizeMult - 1); 7424 7425 // Populate the remaining elements with undefs. 7426 for (unsigned i = TrgNumElts; i < WideNumElts; ++i) 7427 // ShuffV.push_back(i + WideNumElts); 7428 ShuffV.push_back(WideNumElts + 1); 7429 7430 SDValue Conv = DAG.getNode(ISD::BITCAST, DL, WideVT, WideSrc); 7431 return DAG.getVectorShuffle(WideVT, DL, Conv, DAG.getUNDEF(WideVT), ShuffV); 7432 } 7433 7434 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when 7435 /// possible. 7436 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const { 7437 // Not FP? Not a fsel. 7438 if (!Op.getOperand(0).getValueType().isFloatingPoint() || 7439 !Op.getOperand(2).getValueType().isFloatingPoint()) 7440 return Op; 7441 7442 bool HasNoInfs = DAG.getTarget().Options.NoInfsFPMath; 7443 bool HasNoNaNs = DAG.getTarget().Options.NoNaNsFPMath; 7444 // We might be able to do better than this under some circumstances, but in 7445 // general, fsel-based lowering of select is a finite-math-only optimization. 7446 // For more information, see section F.3 of the 2.06 ISA specification. 7447 // With ISA 3.0, we have xsmaxcdp/xsmincdp which are OK to emit even in the 7448 // presence of infinities. 7449 if (!Subtarget.hasP9Vector() && (!HasNoInfs || !HasNoNaNs)) 7450 return Op; 7451 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get(); 7452 7453 EVT ResVT = Op.getValueType(); 7454 EVT CmpVT = Op.getOperand(0).getValueType(); 7455 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 7456 SDValue TV = Op.getOperand(2), FV = Op.getOperand(3); 7457 SDLoc dl(Op); 7458 7459 if (Subtarget.hasP9Vector() && LHS == TV && RHS == FV) { 7460 switch (CC) { 7461 default: 7462 // Not a min/max but with finite math, we may still be able to use fsel. 7463 if (HasNoInfs && HasNoNaNs) 7464 break; 7465 return Op; 7466 case ISD::SETOGT: 7467 case ISD::SETGT: 7468 return DAG.getNode(PPCISD::XSMAXCDP, dl, Op.getValueType(), LHS, RHS); 7469 case ISD::SETOLT: 7470 case ISD::SETLT: 7471 return DAG.getNode(PPCISD::XSMINCDP, dl, Op.getValueType(), LHS, RHS); 7472 } 7473 } 7474 7475 // TODO: Propagate flags from the select rather than global settings. 7476 SDNodeFlags Flags; 7477 Flags.setNoInfs(true); 7478 Flags.setNoNaNs(true); 7479 7480 // If the RHS of the comparison is a 0.0, we don't need to do the 7481 // subtraction at all. 7482 SDValue Sel1; 7483 if (isFloatingPointZero(RHS)) 7484 switch (CC) { 7485 default: break; // SETUO etc aren't handled by fsel. 7486 case ISD::SETNE: 7487 std::swap(TV, FV); 7488 LLVM_FALLTHROUGH; 7489 case ISD::SETEQ: 7490 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits 7491 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); 7492 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV); 7493 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits 7494 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1); 7495 return DAG.getNode(PPCISD::FSEL, dl, ResVT, 7496 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV); 7497 case ISD::SETULT: 7498 case ISD::SETLT: 7499 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt 7500 LLVM_FALLTHROUGH; 7501 case ISD::SETOGE: 7502 case ISD::SETGE: 7503 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits 7504 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); 7505 return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV); 7506 case ISD::SETUGT: 7507 case ISD::SETGT: 7508 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt 7509 LLVM_FALLTHROUGH; 7510 case ISD::SETOLE: 7511 case ISD::SETLE: 7512 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits 7513 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); 7514 return DAG.getNode(PPCISD::FSEL, dl, ResVT, 7515 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV); 7516 } 7517 7518 SDValue Cmp; 7519 switch (CC) { 7520 default: break; // SETUO etc aren't handled by fsel. 7521 case ISD::SETNE: 7522 std::swap(TV, FV); 7523 LLVM_FALLTHROUGH; 7524 case ISD::SETEQ: 7525 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags); 7526 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 7527 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 7528 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); 7529 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits 7530 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1); 7531 return DAG.getNode(PPCISD::FSEL, dl, ResVT, 7532 DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV); 7533 case ISD::SETULT: 7534 case ISD::SETLT: 7535 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags); 7536 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 7537 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 7538 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV); 7539 case ISD::SETOGE: 7540 case ISD::SETGE: 7541 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags); 7542 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 7543 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 7544 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); 7545 case ISD::SETUGT: 7546 case ISD::SETGT: 7547 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags); 7548 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 7549 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 7550 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV); 7551 case ISD::SETOLE: 7552 case ISD::SETLE: 7553 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags); 7554 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 7555 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 7556 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); 7557 } 7558 return Op; 7559 } 7560 7561 void PPCTargetLowering::LowerFP_TO_INTForReuse(SDValue Op, ReuseLoadInfo &RLI, 7562 SelectionDAG &DAG, 7563 const SDLoc &dl) const { 7564 assert(Op.getOperand(0).getValueType().isFloatingPoint()); 7565 SDValue Src = Op.getOperand(0); 7566 if (Src.getValueType() == MVT::f32) 7567 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src); 7568 7569 SDValue Tmp; 7570 switch (Op.getSimpleValueType().SimpleTy) { 7571 default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!"); 7572 case MVT::i32: 7573 Tmp = DAG.getNode( 7574 Op.getOpcode() == ISD::FP_TO_SINT 7575 ? PPCISD::FCTIWZ 7576 : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ), 7577 dl, MVT::f64, Src); 7578 break; 7579 case MVT::i64: 7580 assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) && 7581 "i64 FP_TO_UINT is supported only with FPCVT"); 7582 Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ : 7583 PPCISD::FCTIDUZ, 7584 dl, MVT::f64, Src); 7585 break; 7586 } 7587 7588 // Convert the FP value to an int value through memory. 7589 bool i32Stack = Op.getValueType() == MVT::i32 && Subtarget.hasSTFIWX() && 7590 (Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()); 7591 SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64); 7592 int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex(); 7593 MachinePointerInfo MPI = 7594 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI); 7595 7596 // Emit a store to the stack slot. 7597 SDValue Chain; 7598 if (i32Stack) { 7599 MachineFunction &MF = DAG.getMachineFunction(); 7600 MachineMemOperand *MMO = 7601 MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, 4); 7602 SDValue Ops[] = { DAG.getEntryNode(), Tmp, FIPtr }; 7603 Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl, 7604 DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO); 7605 } else 7606 Chain = DAG.getStore(DAG.getEntryNode(), dl, Tmp, FIPtr, MPI); 7607 7608 // Result is a load from the stack slot. If loading 4 bytes, make sure to 7609 // add in a bias on big endian. 7610 if (Op.getValueType() == MVT::i32 && !i32Stack) { 7611 FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr, 7612 DAG.getConstant(4, dl, FIPtr.getValueType())); 7613 MPI = MPI.getWithOffset(Subtarget.isLittleEndian() ? 0 : 4); 7614 } 7615 7616 RLI.Chain = Chain; 7617 RLI.Ptr = FIPtr; 7618 RLI.MPI = MPI; 7619 } 7620 7621 /// Custom lowers floating point to integer conversions to use 7622 /// the direct move instructions available in ISA 2.07 to avoid the 7623 /// need for load/store combinations. 7624 SDValue PPCTargetLowering::LowerFP_TO_INTDirectMove(SDValue Op, 7625 SelectionDAG &DAG, 7626 const SDLoc &dl) const { 7627 assert(Op.getOperand(0).getValueType().isFloatingPoint()); 7628 SDValue Src = Op.getOperand(0); 7629 7630 if (Src.getValueType() == MVT::f32) 7631 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src); 7632 7633 SDValue Tmp; 7634 switch (Op.getSimpleValueType().SimpleTy) { 7635 default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!"); 7636 case MVT::i32: 7637 Tmp = DAG.getNode( 7638 Op.getOpcode() == ISD::FP_TO_SINT 7639 ? PPCISD::FCTIWZ 7640 : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ), 7641 dl, MVT::f64, Src); 7642 Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i32, Tmp); 7643 break; 7644 case MVT::i64: 7645 assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) && 7646 "i64 FP_TO_UINT is supported only with FPCVT"); 7647 Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ : 7648 PPCISD::FCTIDUZ, 7649 dl, MVT::f64, Src); 7650 Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i64, Tmp); 7651 break; 7652 } 7653 return Tmp; 7654 } 7655 7656 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG, 7657 const SDLoc &dl) const { 7658 7659 // FP to INT conversions are legal for f128. 7660 if (EnableQuadPrecision && (Op->getOperand(0).getValueType() == MVT::f128)) 7661 return Op; 7662 7663 // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on 7664 // PPC (the libcall is not available). 7665 if (Op.getOperand(0).getValueType() == MVT::ppcf128) { 7666 if (Op.getValueType() == MVT::i32) { 7667 if (Op.getOpcode() == ISD::FP_TO_SINT) { 7668 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, 7669 MVT::f64, Op.getOperand(0), 7670 DAG.getIntPtrConstant(0, dl)); 7671 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, 7672 MVT::f64, Op.getOperand(0), 7673 DAG.getIntPtrConstant(1, dl)); 7674 7675 // Add the two halves of the long double in round-to-zero mode. 7676 SDValue Res = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi); 7677 7678 // Now use a smaller FP_TO_SINT. 7679 return DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Res); 7680 } 7681 if (Op.getOpcode() == ISD::FP_TO_UINT) { 7682 const uint64_t TwoE31[] = {0x41e0000000000000LL, 0}; 7683 APFloat APF = APFloat(APFloat::PPCDoubleDouble(), APInt(128, TwoE31)); 7684 SDValue Tmp = DAG.getConstantFP(APF, dl, MVT::ppcf128); 7685 // X>=2^31 ? (int)(X-2^31)+0x80000000 : (int)X 7686 // FIXME: generated code sucks. 7687 // TODO: Are there fast-math-flags to propagate to this FSUB? 7688 SDValue True = DAG.getNode(ISD::FSUB, dl, MVT::ppcf128, 7689 Op.getOperand(0), Tmp); 7690 True = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, True); 7691 True = DAG.getNode(ISD::ADD, dl, MVT::i32, True, 7692 DAG.getConstant(0x80000000, dl, MVT::i32)); 7693 SDValue False = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, 7694 Op.getOperand(0)); 7695 return DAG.getSelectCC(dl, Op.getOperand(0), Tmp, True, False, 7696 ISD::SETGE); 7697 } 7698 } 7699 7700 return SDValue(); 7701 } 7702 7703 if (Subtarget.hasDirectMove() && Subtarget.isPPC64()) 7704 return LowerFP_TO_INTDirectMove(Op, DAG, dl); 7705 7706 ReuseLoadInfo RLI; 7707 LowerFP_TO_INTForReuse(Op, RLI, DAG, dl); 7708 7709 return DAG.getLoad(Op.getValueType(), dl, RLI.Chain, RLI.Ptr, RLI.MPI, 7710 RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges); 7711 } 7712 7713 // We're trying to insert a regular store, S, and then a load, L. If the 7714 // incoming value, O, is a load, we might just be able to have our load use the 7715 // address used by O. However, we don't know if anything else will store to 7716 // that address before we can load from it. To prevent this situation, we need 7717 // to insert our load, L, into the chain as a peer of O. To do this, we give L 7718 // the same chain operand as O, we create a token factor from the chain results 7719 // of O and L, and we replace all uses of O's chain result with that token 7720 // factor (see spliceIntoChain below for this last part). 7721 bool PPCTargetLowering::canReuseLoadAddress(SDValue Op, EVT MemVT, 7722 ReuseLoadInfo &RLI, 7723 SelectionDAG &DAG, 7724 ISD::LoadExtType ET) const { 7725 SDLoc dl(Op); 7726 if (ET == ISD::NON_EXTLOAD && 7727 (Op.getOpcode() == ISD::FP_TO_UINT || 7728 Op.getOpcode() == ISD::FP_TO_SINT) && 7729 isOperationLegalOrCustom(Op.getOpcode(), 7730 Op.getOperand(0).getValueType())) { 7731 7732 LowerFP_TO_INTForReuse(Op, RLI, DAG, dl); 7733 return true; 7734 } 7735 7736 LoadSDNode *LD = dyn_cast<LoadSDNode>(Op); 7737 if (!LD || LD->getExtensionType() != ET || LD->isVolatile() || 7738 LD->isNonTemporal()) 7739 return false; 7740 if (LD->getMemoryVT() != MemVT) 7741 return false; 7742 7743 RLI.Ptr = LD->getBasePtr(); 7744 if (LD->isIndexed() && !LD->getOffset().isUndef()) { 7745 assert(LD->getAddressingMode() == ISD::PRE_INC && 7746 "Non-pre-inc AM on PPC?"); 7747 RLI.Ptr = DAG.getNode(ISD::ADD, dl, RLI.Ptr.getValueType(), RLI.Ptr, 7748 LD->getOffset()); 7749 } 7750 7751 RLI.Chain = LD->getChain(); 7752 RLI.MPI = LD->getPointerInfo(); 7753 RLI.IsDereferenceable = LD->isDereferenceable(); 7754 RLI.IsInvariant = LD->isInvariant(); 7755 RLI.Alignment = LD->getAlignment(); 7756 RLI.AAInfo = LD->getAAInfo(); 7757 RLI.Ranges = LD->getRanges(); 7758 7759 RLI.ResChain = SDValue(LD, LD->isIndexed() ? 2 : 1); 7760 return true; 7761 } 7762 7763 // Given the head of the old chain, ResChain, insert a token factor containing 7764 // it and NewResChain, and make users of ResChain now be users of that token 7765 // factor. 7766 // TODO: Remove and use DAG::makeEquivalentMemoryOrdering() instead. 7767 void PPCTargetLowering::spliceIntoChain(SDValue ResChain, 7768 SDValue NewResChain, 7769 SelectionDAG &DAG) const { 7770 if (!ResChain) 7771 return; 7772 7773 SDLoc dl(NewResChain); 7774 7775 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 7776 NewResChain, DAG.getUNDEF(MVT::Other)); 7777 assert(TF.getNode() != NewResChain.getNode() && 7778 "A new TF really is required here"); 7779 7780 DAG.ReplaceAllUsesOfValueWith(ResChain, TF); 7781 DAG.UpdateNodeOperands(TF.getNode(), ResChain, NewResChain); 7782 } 7783 7784 /// Analyze profitability of direct move 7785 /// prefer float load to int load plus direct move 7786 /// when there is no integer use of int load 7787 bool PPCTargetLowering::directMoveIsProfitable(const SDValue &Op) const { 7788 SDNode *Origin = Op.getOperand(0).getNode(); 7789 if (Origin->getOpcode() != ISD::LOAD) 7790 return true; 7791 7792 // If there is no LXSIBZX/LXSIHZX, like Power8, 7793 // prefer direct move if the memory size is 1 or 2 bytes. 7794 MachineMemOperand *MMO = cast<LoadSDNode>(Origin)->getMemOperand(); 7795 if (!Subtarget.hasP9Vector() && MMO->getSize() <= 2) 7796 return true; 7797 7798 for (SDNode::use_iterator UI = Origin->use_begin(), 7799 UE = Origin->use_end(); 7800 UI != UE; ++UI) { 7801 7802 // Only look at the users of the loaded value. 7803 if (UI.getUse().get().getResNo() != 0) 7804 continue; 7805 7806 if (UI->getOpcode() != ISD::SINT_TO_FP && 7807 UI->getOpcode() != ISD::UINT_TO_FP) 7808 return true; 7809 } 7810 7811 return false; 7812 } 7813 7814 /// Custom lowers integer to floating point conversions to use 7815 /// the direct move instructions available in ISA 2.07 to avoid the 7816 /// need for load/store combinations. 7817 SDValue PPCTargetLowering::LowerINT_TO_FPDirectMove(SDValue Op, 7818 SelectionDAG &DAG, 7819 const SDLoc &dl) const { 7820 assert((Op.getValueType() == MVT::f32 || 7821 Op.getValueType() == MVT::f64) && 7822 "Invalid floating point type as target of conversion"); 7823 assert(Subtarget.hasFPCVT() && 7824 "Int to FP conversions with direct moves require FPCVT"); 7825 SDValue FP; 7826 SDValue Src = Op.getOperand(0); 7827 bool SinglePrec = Op.getValueType() == MVT::f32; 7828 bool WordInt = Src.getSimpleValueType().SimpleTy == MVT::i32; 7829 bool Signed = Op.getOpcode() == ISD::SINT_TO_FP; 7830 unsigned ConvOp = Signed ? (SinglePrec ? PPCISD::FCFIDS : PPCISD::FCFID) : 7831 (SinglePrec ? PPCISD::FCFIDUS : PPCISD::FCFIDU); 7832 7833 if (WordInt) { 7834 FP = DAG.getNode(Signed ? PPCISD::MTVSRA : PPCISD::MTVSRZ, 7835 dl, MVT::f64, Src); 7836 FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP); 7837 } 7838 else { 7839 FP = DAG.getNode(PPCISD::MTVSRA, dl, MVT::f64, Src); 7840 FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP); 7841 } 7842 7843 return FP; 7844 } 7845 7846 static SDValue widenVec(SelectionDAG &DAG, SDValue Vec, const SDLoc &dl) { 7847 7848 EVT VecVT = Vec.getValueType(); 7849 assert(VecVT.isVector() && "Expected a vector type."); 7850 assert(VecVT.getSizeInBits() < 128 && "Vector is already full width."); 7851 7852 EVT EltVT = VecVT.getVectorElementType(); 7853 unsigned WideNumElts = 128 / EltVT.getSizeInBits(); 7854 EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts); 7855 7856 unsigned NumConcat = WideNumElts / VecVT.getVectorNumElements(); 7857 SmallVector<SDValue, 16> Ops(NumConcat); 7858 Ops[0] = Vec; 7859 SDValue UndefVec = DAG.getUNDEF(VecVT); 7860 for (unsigned i = 1; i < NumConcat; ++i) 7861 Ops[i] = UndefVec; 7862 7863 return DAG.getNode(ISD::CONCAT_VECTORS, dl, WideVT, Ops); 7864 } 7865 7866 SDValue PPCTargetLowering::LowerINT_TO_FPVector(SDValue Op, SelectionDAG &DAG, 7867 const SDLoc &dl) const { 7868 7869 unsigned Opc = Op.getOpcode(); 7870 assert((Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP) && 7871 "Unexpected conversion type"); 7872 assert((Op.getValueType() == MVT::v2f64 || Op.getValueType() == MVT::v4f32) && 7873 "Supports conversions to v2f64/v4f32 only."); 7874 7875 bool SignedConv = Opc == ISD::SINT_TO_FP; 7876 bool FourEltRes = Op.getValueType() == MVT::v4f32; 7877 7878 SDValue Wide = widenVec(DAG, Op.getOperand(0), dl); 7879 EVT WideVT = Wide.getValueType(); 7880 unsigned WideNumElts = WideVT.getVectorNumElements(); 7881 MVT IntermediateVT = FourEltRes ? MVT::v4i32 : MVT::v2i64; 7882 7883 SmallVector<int, 16> ShuffV; 7884 for (unsigned i = 0; i < WideNumElts; ++i) 7885 ShuffV.push_back(i + WideNumElts); 7886 7887 int Stride = FourEltRes ? WideNumElts / 4 : WideNumElts / 2; 7888 int SaveElts = FourEltRes ? 4 : 2; 7889 if (Subtarget.isLittleEndian()) 7890 for (int i = 0; i < SaveElts; i++) 7891 ShuffV[i * Stride] = i; 7892 else 7893 for (int i = 1; i <= SaveElts; i++) 7894 ShuffV[i * Stride - 1] = i - 1; 7895 7896 SDValue ShuffleSrc2 = 7897 SignedConv ? DAG.getUNDEF(WideVT) : DAG.getConstant(0, dl, WideVT); 7898 SDValue Arrange = DAG.getVectorShuffle(WideVT, dl, Wide, ShuffleSrc2, ShuffV); 7899 unsigned ExtendOp = 7900 SignedConv ? (unsigned)PPCISD::SExtVElems : (unsigned)ISD::BITCAST; 7901 7902 SDValue Extend; 7903 if (!Subtarget.hasP9Altivec() && SignedConv) { 7904 Arrange = DAG.getBitcast(IntermediateVT, Arrange); 7905 Extend = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, IntermediateVT, Arrange, 7906 DAG.getValueType(Op.getOperand(0).getValueType())); 7907 } else 7908 Extend = DAG.getNode(ExtendOp, dl, IntermediateVT, Arrange); 7909 7910 return DAG.getNode(Opc, dl, Op.getValueType(), Extend); 7911 } 7912 7913 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op, 7914 SelectionDAG &DAG) const { 7915 SDLoc dl(Op); 7916 7917 EVT InVT = Op.getOperand(0).getValueType(); 7918 EVT OutVT = Op.getValueType(); 7919 if (OutVT.isVector() && OutVT.isFloatingPoint() && 7920 isOperationCustom(Op.getOpcode(), InVT)) 7921 return LowerINT_TO_FPVector(Op, DAG, dl); 7922 7923 // Conversions to f128 are legal. 7924 if (EnableQuadPrecision && (Op.getValueType() == MVT::f128)) 7925 return Op; 7926 7927 if (Subtarget.hasQPX() && Op.getOperand(0).getValueType() == MVT::v4i1) { 7928 if (Op.getValueType() != MVT::v4f32 && Op.getValueType() != MVT::v4f64) 7929 return SDValue(); 7930 7931 SDValue Value = Op.getOperand(0); 7932 // The values are now known to be -1 (false) or 1 (true). To convert this 7933 // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5). 7934 // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5 7935 Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value); 7936 7937 SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64); 7938 7939 Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs); 7940 7941 if (Op.getValueType() != MVT::v4f64) 7942 Value = DAG.getNode(ISD::FP_ROUND, dl, 7943 Op.getValueType(), Value, 7944 DAG.getIntPtrConstant(1, dl)); 7945 return Value; 7946 } 7947 7948 // Don't handle ppc_fp128 here; let it be lowered to a libcall. 7949 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64) 7950 return SDValue(); 7951 7952 if (Op.getOperand(0).getValueType() == MVT::i1) 7953 return DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Op.getOperand(0), 7954 DAG.getConstantFP(1.0, dl, Op.getValueType()), 7955 DAG.getConstantFP(0.0, dl, Op.getValueType())); 7956 7957 // If we have direct moves, we can do all the conversion, skip the store/load 7958 // however, without FPCVT we can't do most conversions. 7959 if (Subtarget.hasDirectMove() && directMoveIsProfitable(Op) && 7960 Subtarget.isPPC64() && Subtarget.hasFPCVT()) 7961 return LowerINT_TO_FPDirectMove(Op, DAG, dl); 7962 7963 assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) && 7964 "UINT_TO_FP is supported only with FPCVT"); 7965 7966 // If we have FCFIDS, then use it when converting to single-precision. 7967 // Otherwise, convert to double-precision and then round. 7968 unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 7969 ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS 7970 : PPCISD::FCFIDS) 7971 : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU 7972 : PPCISD::FCFID); 7973 MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 7974 ? MVT::f32 7975 : MVT::f64; 7976 7977 if (Op.getOperand(0).getValueType() == MVT::i64) { 7978 SDValue SINT = Op.getOperand(0); 7979 // When converting to single-precision, we actually need to convert 7980 // to double-precision first and then round to single-precision. 7981 // To avoid double-rounding effects during that operation, we have 7982 // to prepare the input operand. Bits that might be truncated when 7983 // converting to double-precision are replaced by a bit that won't 7984 // be lost at this stage, but is below the single-precision rounding 7985 // position. 7986 // 7987 // However, if -enable-unsafe-fp-math is in effect, accept double 7988 // rounding to avoid the extra overhead. 7989 if (Op.getValueType() == MVT::f32 && 7990 !Subtarget.hasFPCVT() && 7991 !DAG.getTarget().Options.UnsafeFPMath) { 7992 7993 // Twiddle input to make sure the low 11 bits are zero. (If this 7994 // is the case, we are guaranteed the value will fit into the 53 bit 7995 // mantissa of an IEEE double-precision value without rounding.) 7996 // If any of those low 11 bits were not zero originally, make sure 7997 // bit 12 (value 2048) is set instead, so that the final rounding 7998 // to single-precision gets the correct result. 7999 SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64, 8000 SINT, DAG.getConstant(2047, dl, MVT::i64)); 8001 Round = DAG.getNode(ISD::ADD, dl, MVT::i64, 8002 Round, DAG.getConstant(2047, dl, MVT::i64)); 8003 Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT); 8004 Round = DAG.getNode(ISD::AND, dl, MVT::i64, 8005 Round, DAG.getConstant(-2048, dl, MVT::i64)); 8006 8007 // However, we cannot use that value unconditionally: if the magnitude 8008 // of the input value is small, the bit-twiddling we did above might 8009 // end up visibly changing the output. Fortunately, in that case, we 8010 // don't need to twiddle bits since the original input will convert 8011 // exactly to double-precision floating-point already. Therefore, 8012 // construct a conditional to use the original value if the top 11 8013 // bits are all sign-bit copies, and use the rounded value computed 8014 // above otherwise. 8015 SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64, 8016 SINT, DAG.getConstant(53, dl, MVT::i32)); 8017 Cond = DAG.getNode(ISD::ADD, dl, MVT::i64, 8018 Cond, DAG.getConstant(1, dl, MVT::i64)); 8019 Cond = DAG.getSetCC(dl, MVT::i32, 8020 Cond, DAG.getConstant(1, dl, MVT::i64), ISD::SETUGT); 8021 8022 SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT); 8023 } 8024 8025 ReuseLoadInfo RLI; 8026 SDValue Bits; 8027 8028 MachineFunction &MF = DAG.getMachineFunction(); 8029 if (canReuseLoadAddress(SINT, MVT::i64, RLI, DAG)) { 8030 Bits = DAG.getLoad(MVT::f64, dl, RLI.Chain, RLI.Ptr, RLI.MPI, 8031 RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges); 8032 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG); 8033 } else if (Subtarget.hasLFIWAX() && 8034 canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::SEXTLOAD)) { 8035 MachineMemOperand *MMO = 8036 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 8037 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 8038 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 8039 Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWAX, dl, 8040 DAG.getVTList(MVT::f64, MVT::Other), 8041 Ops, MVT::i32, MMO); 8042 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG); 8043 } else if (Subtarget.hasFPCVT() && 8044 canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::ZEXTLOAD)) { 8045 MachineMemOperand *MMO = 8046 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 8047 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 8048 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 8049 Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWZX, dl, 8050 DAG.getVTList(MVT::f64, MVT::Other), 8051 Ops, MVT::i32, MMO); 8052 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG); 8053 } else if (((Subtarget.hasLFIWAX() && 8054 SINT.getOpcode() == ISD::SIGN_EXTEND) || 8055 (Subtarget.hasFPCVT() && 8056 SINT.getOpcode() == ISD::ZERO_EXTEND)) && 8057 SINT.getOperand(0).getValueType() == MVT::i32) { 8058 MachineFrameInfo &MFI = MF.getFrameInfo(); 8059 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 8060 8061 int FrameIdx = MFI.CreateStackObject(4, 4, false); 8062 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 8063 8064 SDValue Store = 8065 DAG.getStore(DAG.getEntryNode(), dl, SINT.getOperand(0), FIdx, 8066 MachinePointerInfo::getFixedStack( 8067 DAG.getMachineFunction(), FrameIdx)); 8068 8069 assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 && 8070 "Expected an i32 store"); 8071 8072 RLI.Ptr = FIdx; 8073 RLI.Chain = Store; 8074 RLI.MPI = 8075 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 8076 RLI.Alignment = 4; 8077 8078 MachineMemOperand *MMO = 8079 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 8080 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 8081 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 8082 Bits = DAG.getMemIntrinsicNode(SINT.getOpcode() == ISD::ZERO_EXTEND ? 8083 PPCISD::LFIWZX : PPCISD::LFIWAX, 8084 dl, DAG.getVTList(MVT::f64, MVT::Other), 8085 Ops, MVT::i32, MMO); 8086 } else 8087 Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT); 8088 8089 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Bits); 8090 8091 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) 8092 FP = DAG.getNode(ISD::FP_ROUND, dl, 8093 MVT::f32, FP, DAG.getIntPtrConstant(0, dl)); 8094 return FP; 8095 } 8096 8097 assert(Op.getOperand(0).getValueType() == MVT::i32 && 8098 "Unhandled INT_TO_FP type in custom expander!"); 8099 // Since we only generate this in 64-bit mode, we can take advantage of 8100 // 64-bit registers. In particular, sign extend the input value into the 8101 // 64-bit register with extsw, store the WHOLE 64-bit value into the stack 8102 // then lfd it and fcfid it. 8103 MachineFunction &MF = DAG.getMachineFunction(); 8104 MachineFrameInfo &MFI = MF.getFrameInfo(); 8105 EVT PtrVT = getPointerTy(MF.getDataLayout()); 8106 8107 SDValue Ld; 8108 if (Subtarget.hasLFIWAX() || Subtarget.hasFPCVT()) { 8109 ReuseLoadInfo RLI; 8110 bool ReusingLoad; 8111 if (!(ReusingLoad = canReuseLoadAddress(Op.getOperand(0), MVT::i32, RLI, 8112 DAG))) { 8113 int FrameIdx = MFI.CreateStackObject(4, 4, false); 8114 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 8115 8116 SDValue Store = 8117 DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx, 8118 MachinePointerInfo::getFixedStack( 8119 DAG.getMachineFunction(), FrameIdx)); 8120 8121 assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 && 8122 "Expected an i32 store"); 8123 8124 RLI.Ptr = FIdx; 8125 RLI.Chain = Store; 8126 RLI.MPI = 8127 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 8128 RLI.Alignment = 4; 8129 } 8130 8131 MachineMemOperand *MMO = 8132 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 8133 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 8134 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 8135 Ld = DAG.getMemIntrinsicNode(Op.getOpcode() == ISD::UINT_TO_FP ? 8136 PPCISD::LFIWZX : PPCISD::LFIWAX, 8137 dl, DAG.getVTList(MVT::f64, MVT::Other), 8138 Ops, MVT::i32, MMO); 8139 if (ReusingLoad) 8140 spliceIntoChain(RLI.ResChain, Ld.getValue(1), DAG); 8141 } else { 8142 assert(Subtarget.isPPC64() && 8143 "i32->FP without LFIWAX supported only on PPC64"); 8144 8145 int FrameIdx = MFI.CreateStackObject(8, 8, false); 8146 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 8147 8148 SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64, 8149 Op.getOperand(0)); 8150 8151 // STD the extended value into the stack slot. 8152 SDValue Store = DAG.getStore( 8153 DAG.getEntryNode(), dl, Ext64, FIdx, 8154 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx)); 8155 8156 // Load the value as a double. 8157 Ld = DAG.getLoad( 8158 MVT::f64, dl, Store, FIdx, 8159 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx)); 8160 } 8161 8162 // FCFID it and return it. 8163 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Ld); 8164 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) 8165 FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP, 8166 DAG.getIntPtrConstant(0, dl)); 8167 return FP; 8168 } 8169 8170 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op, 8171 SelectionDAG &DAG) const { 8172 SDLoc dl(Op); 8173 /* 8174 The rounding mode is in bits 30:31 of FPSR, and has the following 8175 settings: 8176 00 Round to nearest 8177 01 Round to 0 8178 10 Round to +inf 8179 11 Round to -inf 8180 8181 FLT_ROUNDS, on the other hand, expects the following: 8182 -1 Undefined 8183 0 Round to 0 8184 1 Round to nearest 8185 2 Round to +inf 8186 3 Round to -inf 8187 8188 To perform the conversion, we do: 8189 ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1)) 8190 */ 8191 8192 MachineFunction &MF = DAG.getMachineFunction(); 8193 EVT VT = Op.getValueType(); 8194 EVT PtrVT = getPointerTy(MF.getDataLayout()); 8195 8196 // Save FP Control Word to register 8197 EVT NodeTys[] = { 8198 MVT::f64, // return register 8199 MVT::Glue // unused in this context 8200 }; 8201 SDValue Chain = DAG.getNode(PPCISD::MFFS, dl, NodeTys, None); 8202 8203 // Save FP register to stack slot 8204 int SSFI = MF.getFrameInfo().CreateStackObject(8, 8, false); 8205 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT); 8206 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Chain, StackSlot, 8207 MachinePointerInfo()); 8208 8209 // Load FP Control Word from low 32 bits of stack slot. 8210 SDValue Four = DAG.getConstant(4, dl, PtrVT); 8211 SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four); 8212 SDValue CWD = DAG.getLoad(MVT::i32, dl, Store, Addr, MachinePointerInfo()); 8213 8214 // Transform as necessary 8215 SDValue CWD1 = 8216 DAG.getNode(ISD::AND, dl, MVT::i32, 8217 CWD, DAG.getConstant(3, dl, MVT::i32)); 8218 SDValue CWD2 = 8219 DAG.getNode(ISD::SRL, dl, MVT::i32, 8220 DAG.getNode(ISD::AND, dl, MVT::i32, 8221 DAG.getNode(ISD::XOR, dl, MVT::i32, 8222 CWD, DAG.getConstant(3, dl, MVT::i32)), 8223 DAG.getConstant(3, dl, MVT::i32)), 8224 DAG.getConstant(1, dl, MVT::i32)); 8225 8226 SDValue RetVal = 8227 DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2); 8228 8229 return DAG.getNode((VT.getSizeInBits() < 16 ? 8230 ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal); 8231 } 8232 8233 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const { 8234 EVT VT = Op.getValueType(); 8235 unsigned BitWidth = VT.getSizeInBits(); 8236 SDLoc dl(Op); 8237 assert(Op.getNumOperands() == 3 && 8238 VT == Op.getOperand(1).getValueType() && 8239 "Unexpected SHL!"); 8240 8241 // Expand into a bunch of logical ops. Note that these ops 8242 // depend on the PPC behavior for oversized shift amounts. 8243 SDValue Lo = Op.getOperand(0); 8244 SDValue Hi = Op.getOperand(1); 8245 SDValue Amt = Op.getOperand(2); 8246 EVT AmtVT = Amt.getValueType(); 8247 8248 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, 8249 DAG.getConstant(BitWidth, dl, AmtVT), Amt); 8250 SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt); 8251 SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1); 8252 SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3); 8253 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, 8254 DAG.getConstant(-BitWidth, dl, AmtVT)); 8255 SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5); 8256 SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6); 8257 SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt); 8258 SDValue OutOps[] = { OutLo, OutHi }; 8259 return DAG.getMergeValues(OutOps, dl); 8260 } 8261 8262 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const { 8263 EVT VT = Op.getValueType(); 8264 SDLoc dl(Op); 8265 unsigned BitWidth = VT.getSizeInBits(); 8266 assert(Op.getNumOperands() == 3 && 8267 VT == Op.getOperand(1).getValueType() && 8268 "Unexpected SRL!"); 8269 8270 // Expand into a bunch of logical ops. Note that these ops 8271 // depend on the PPC behavior for oversized shift amounts. 8272 SDValue Lo = Op.getOperand(0); 8273 SDValue Hi = Op.getOperand(1); 8274 SDValue Amt = Op.getOperand(2); 8275 EVT AmtVT = Amt.getValueType(); 8276 8277 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, 8278 DAG.getConstant(BitWidth, dl, AmtVT), Amt); 8279 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt); 8280 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1); 8281 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3); 8282 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, 8283 DAG.getConstant(-BitWidth, dl, AmtVT)); 8284 SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5); 8285 SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6); 8286 SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt); 8287 SDValue OutOps[] = { OutLo, OutHi }; 8288 return DAG.getMergeValues(OutOps, dl); 8289 } 8290 8291 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const { 8292 SDLoc dl(Op); 8293 EVT VT = Op.getValueType(); 8294 unsigned BitWidth = VT.getSizeInBits(); 8295 assert(Op.getNumOperands() == 3 && 8296 VT == Op.getOperand(1).getValueType() && 8297 "Unexpected SRA!"); 8298 8299 // Expand into a bunch of logical ops, followed by a select_cc. 8300 SDValue Lo = Op.getOperand(0); 8301 SDValue Hi = Op.getOperand(1); 8302 SDValue Amt = Op.getOperand(2); 8303 EVT AmtVT = Amt.getValueType(); 8304 8305 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, 8306 DAG.getConstant(BitWidth, dl, AmtVT), Amt); 8307 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt); 8308 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1); 8309 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3); 8310 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, 8311 DAG.getConstant(-BitWidth, dl, AmtVT)); 8312 SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5); 8313 SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt); 8314 SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, dl, AmtVT), 8315 Tmp4, Tmp6, ISD::SETLE); 8316 SDValue OutOps[] = { OutLo, OutHi }; 8317 return DAG.getMergeValues(OutOps, dl); 8318 } 8319 8320 //===----------------------------------------------------------------------===// 8321 // Vector related lowering. 8322 // 8323 8324 /// BuildSplatI - Build a canonical splati of Val with an element size of 8325 /// SplatSize. Cast the result to VT. 8326 static SDValue BuildSplatI(int Val, unsigned SplatSize, EVT VT, 8327 SelectionDAG &DAG, const SDLoc &dl) { 8328 static const MVT VTys[] = { // canonical VT to use for each size. 8329 MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32 8330 }; 8331 8332 EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1]; 8333 8334 // Force vspltis[hw] -1 to vspltisb -1 to canonicalize. 8335 if (Val == -1) 8336 SplatSize = 1; 8337 8338 EVT CanonicalVT = VTys[SplatSize-1]; 8339 8340 // Build a canonical splat for this value. 8341 return DAG.getBitcast(ReqVT, DAG.getConstant(Val, dl, CanonicalVT)); 8342 } 8343 8344 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the 8345 /// specified intrinsic ID. 8346 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op, SelectionDAG &DAG, 8347 const SDLoc &dl, EVT DestVT = MVT::Other) { 8348 if (DestVT == MVT::Other) DestVT = Op.getValueType(); 8349 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 8350 DAG.getConstant(IID, dl, MVT::i32), Op); 8351 } 8352 8353 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the 8354 /// specified intrinsic ID. 8355 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS, 8356 SelectionDAG &DAG, const SDLoc &dl, 8357 EVT DestVT = MVT::Other) { 8358 if (DestVT == MVT::Other) DestVT = LHS.getValueType(); 8359 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 8360 DAG.getConstant(IID, dl, MVT::i32), LHS, RHS); 8361 } 8362 8363 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the 8364 /// specified intrinsic ID. 8365 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1, 8366 SDValue Op2, SelectionDAG &DAG, const SDLoc &dl, 8367 EVT DestVT = MVT::Other) { 8368 if (DestVT == MVT::Other) DestVT = Op0.getValueType(); 8369 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 8370 DAG.getConstant(IID, dl, MVT::i32), Op0, Op1, Op2); 8371 } 8372 8373 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified 8374 /// amount. The result has the specified value type. 8375 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt, EVT VT, 8376 SelectionDAG &DAG, const SDLoc &dl) { 8377 // Force LHS/RHS to be the right type. 8378 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS); 8379 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS); 8380 8381 int Ops[16]; 8382 for (unsigned i = 0; i != 16; ++i) 8383 Ops[i] = i + Amt; 8384 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops); 8385 return DAG.getNode(ISD::BITCAST, dl, VT, T); 8386 } 8387 8388 /// Do we have an efficient pattern in a .td file for this node? 8389 /// 8390 /// \param V - pointer to the BuildVectorSDNode being matched 8391 /// \param HasDirectMove - does this subtarget have VSR <-> GPR direct moves? 8392 /// 8393 /// There are some patterns where it is beneficial to keep a BUILD_VECTOR 8394 /// node as a BUILD_VECTOR node rather than expanding it. The patterns where 8395 /// the opposite is true (expansion is beneficial) are: 8396 /// - The node builds a vector out of integers that are not 32 or 64-bits 8397 /// - The node builds a vector out of constants 8398 /// - The node is a "load-and-splat" 8399 /// In all other cases, we will choose to keep the BUILD_VECTOR. 8400 static bool haveEfficientBuildVectorPattern(BuildVectorSDNode *V, 8401 bool HasDirectMove, 8402 bool HasP8Vector) { 8403 EVT VecVT = V->getValueType(0); 8404 bool RightType = VecVT == MVT::v2f64 || 8405 (HasP8Vector && VecVT == MVT::v4f32) || 8406 (HasDirectMove && (VecVT == MVT::v2i64 || VecVT == MVT::v4i32)); 8407 if (!RightType) 8408 return false; 8409 8410 bool IsSplat = true; 8411 bool IsLoad = false; 8412 SDValue Op0 = V->getOperand(0); 8413 8414 // This function is called in a block that confirms the node is not a constant 8415 // splat. So a constant BUILD_VECTOR here means the vector is built out of 8416 // different constants. 8417 if (V->isConstant()) 8418 return false; 8419 for (int i = 0, e = V->getNumOperands(); i < e; ++i) { 8420 if (V->getOperand(i).isUndef()) 8421 return false; 8422 // We want to expand nodes that represent load-and-splat even if the 8423 // loaded value is a floating point truncation or conversion to int. 8424 if (V->getOperand(i).getOpcode() == ISD::LOAD || 8425 (V->getOperand(i).getOpcode() == ISD::FP_ROUND && 8426 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) || 8427 (V->getOperand(i).getOpcode() == ISD::FP_TO_SINT && 8428 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) || 8429 (V->getOperand(i).getOpcode() == ISD::FP_TO_UINT && 8430 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD)) 8431 IsLoad = true; 8432 // If the operands are different or the input is not a load and has more 8433 // uses than just this BV node, then it isn't a splat. 8434 if (V->getOperand(i) != Op0 || 8435 (!IsLoad && !V->isOnlyUserOf(V->getOperand(i).getNode()))) 8436 IsSplat = false; 8437 } 8438 return !(IsSplat && IsLoad); 8439 } 8440 8441 // Lower BITCAST(f128, (build_pair i64, i64)) to BUILD_FP128. 8442 SDValue PPCTargetLowering::LowerBITCAST(SDValue Op, SelectionDAG &DAG) const { 8443 8444 SDLoc dl(Op); 8445 SDValue Op0 = Op->getOperand(0); 8446 8447 if (!EnableQuadPrecision || 8448 (Op.getValueType() != MVT::f128 ) || 8449 (Op0.getOpcode() != ISD::BUILD_PAIR) || 8450 (Op0.getOperand(0).getValueType() != MVT::i64) || 8451 (Op0.getOperand(1).getValueType() != MVT::i64)) 8452 return SDValue(); 8453 8454 return DAG.getNode(PPCISD::BUILD_FP128, dl, MVT::f128, Op0.getOperand(0), 8455 Op0.getOperand(1)); 8456 } 8457 8458 static const SDValue *getNormalLoadInput(const SDValue &Op) { 8459 const SDValue *InputLoad = &Op; 8460 if (InputLoad->getOpcode() == ISD::BITCAST) 8461 InputLoad = &InputLoad->getOperand(0); 8462 if (InputLoad->getOpcode() == ISD::SCALAR_TO_VECTOR) 8463 InputLoad = &InputLoad->getOperand(0); 8464 if (InputLoad->getOpcode() != ISD::LOAD) 8465 return nullptr; 8466 LoadSDNode *LD = cast<LoadSDNode>(*InputLoad); 8467 return ISD::isNormalLoad(LD) ? InputLoad : nullptr; 8468 } 8469 8470 // If this is a case we can't handle, return null and let the default 8471 // expansion code take care of it. If we CAN select this case, and if it 8472 // selects to a single instruction, return Op. Otherwise, if we can codegen 8473 // this case more efficiently than a constant pool load, lower it to the 8474 // sequence of ops that should be used. 8475 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op, 8476 SelectionDAG &DAG) const { 8477 SDLoc dl(Op); 8478 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode()); 8479 assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR"); 8480 8481 if (Subtarget.hasQPX() && Op.getValueType() == MVT::v4i1) { 8482 // We first build an i32 vector, load it into a QPX register, 8483 // then convert it to a floating-point vector and compare it 8484 // to a zero vector to get the boolean result. 8485 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 8486 int FrameIdx = MFI.CreateStackObject(16, 16, false); 8487 MachinePointerInfo PtrInfo = 8488 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 8489 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 8490 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 8491 8492 assert(BVN->getNumOperands() == 4 && 8493 "BUILD_VECTOR for v4i1 does not have 4 operands"); 8494 8495 bool IsConst = true; 8496 for (unsigned i = 0; i < 4; ++i) { 8497 if (BVN->getOperand(i).isUndef()) continue; 8498 if (!isa<ConstantSDNode>(BVN->getOperand(i))) { 8499 IsConst = false; 8500 break; 8501 } 8502 } 8503 8504 if (IsConst) { 8505 Constant *One = 8506 ConstantFP::get(Type::getFloatTy(*DAG.getContext()), 1.0); 8507 Constant *NegOne = 8508 ConstantFP::get(Type::getFloatTy(*DAG.getContext()), -1.0); 8509 8510 Constant *CV[4]; 8511 for (unsigned i = 0; i < 4; ++i) { 8512 if (BVN->getOperand(i).isUndef()) 8513 CV[i] = UndefValue::get(Type::getFloatTy(*DAG.getContext())); 8514 else if (isNullConstant(BVN->getOperand(i))) 8515 CV[i] = NegOne; 8516 else 8517 CV[i] = One; 8518 } 8519 8520 Constant *CP = ConstantVector::get(CV); 8521 SDValue CPIdx = DAG.getConstantPool(CP, getPointerTy(DAG.getDataLayout()), 8522 16 /* alignment */); 8523 8524 SDValue Ops[] = {DAG.getEntryNode(), CPIdx}; 8525 SDVTList VTs = DAG.getVTList({MVT::v4i1, /*chain*/ MVT::Other}); 8526 return DAG.getMemIntrinsicNode( 8527 PPCISD::QVLFSb, dl, VTs, Ops, MVT::v4f32, 8528 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 8529 } 8530 8531 SmallVector<SDValue, 4> Stores; 8532 for (unsigned i = 0; i < 4; ++i) { 8533 if (BVN->getOperand(i).isUndef()) continue; 8534 8535 unsigned Offset = 4*i; 8536 SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType()); 8537 Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx); 8538 8539 unsigned StoreSize = BVN->getOperand(i).getValueType().getStoreSize(); 8540 if (StoreSize > 4) { 8541 Stores.push_back( 8542 DAG.getTruncStore(DAG.getEntryNode(), dl, BVN->getOperand(i), Idx, 8543 PtrInfo.getWithOffset(Offset), MVT::i32)); 8544 } else { 8545 SDValue StoreValue = BVN->getOperand(i); 8546 if (StoreSize < 4) 8547 StoreValue = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, StoreValue); 8548 8549 Stores.push_back(DAG.getStore(DAG.getEntryNode(), dl, StoreValue, Idx, 8550 PtrInfo.getWithOffset(Offset))); 8551 } 8552 } 8553 8554 SDValue StoreChain; 8555 if (!Stores.empty()) 8556 StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores); 8557 else 8558 StoreChain = DAG.getEntryNode(); 8559 8560 // Now load from v4i32 into the QPX register; this will extend it to 8561 // v4i64 but not yet convert it to a floating point. Nevertheless, this 8562 // is typed as v4f64 because the QPX register integer states are not 8563 // explicitly represented. 8564 8565 SDValue Ops[] = {StoreChain, 8566 DAG.getConstant(Intrinsic::ppc_qpx_qvlfiwz, dl, MVT::i32), 8567 FIdx}; 8568 SDVTList VTs = DAG.getVTList({MVT::v4f64, /*chain*/ MVT::Other}); 8569 8570 SDValue LoadedVect = DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, 8571 dl, VTs, Ops, MVT::v4i32, PtrInfo); 8572 LoadedVect = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64, 8573 DAG.getConstant(Intrinsic::ppc_qpx_qvfcfidu, dl, MVT::i32), 8574 LoadedVect); 8575 8576 SDValue FPZeros = DAG.getConstantFP(0.0, dl, MVT::v4f64); 8577 8578 return DAG.getSetCC(dl, MVT::v4i1, LoadedVect, FPZeros, ISD::SETEQ); 8579 } 8580 8581 // All other QPX vectors are handled by generic code. 8582 if (Subtarget.hasQPX()) 8583 return SDValue(); 8584 8585 // Check if this is a splat of a constant value. 8586 APInt APSplatBits, APSplatUndef; 8587 unsigned SplatBitSize; 8588 bool HasAnyUndefs; 8589 if (! BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize, 8590 HasAnyUndefs, 0, !Subtarget.isLittleEndian()) || 8591 SplatBitSize > 32) { 8592 8593 const SDValue *InputLoad = getNormalLoadInput(Op.getOperand(0)); 8594 // Handle load-and-splat patterns as we have instructions that will do this 8595 // in one go. 8596 if (InputLoad && DAG.isSplatValue(Op, true)) { 8597 LoadSDNode *LD = cast<LoadSDNode>(*InputLoad); 8598 8599 // We have handling for 4 and 8 byte elements. 8600 unsigned ElementSize = LD->getMemoryVT().getScalarSizeInBits(); 8601 8602 // Checking for a single use of this load, we have to check for vector 8603 // width (128 bits) / ElementSize uses (since each operand of the 8604 // BUILD_VECTOR is a separate use of the value. 8605 if (InputLoad->getNode()->hasNUsesOfValue(128 / ElementSize, 0) && 8606 ((Subtarget.hasVSX() && ElementSize == 64) || 8607 (Subtarget.hasP9Vector() && ElementSize == 32))) { 8608 SDValue Ops[] = { 8609 LD->getChain(), // Chain 8610 LD->getBasePtr(), // Ptr 8611 DAG.getValueType(Op.getValueType()) // VT 8612 }; 8613 return 8614 DAG.getMemIntrinsicNode(PPCISD::LD_SPLAT, dl, 8615 DAG.getVTList(Op.getValueType(), MVT::Other), 8616 Ops, LD->getMemoryVT(), LD->getMemOperand()); 8617 } 8618 } 8619 8620 // BUILD_VECTOR nodes that are not constant splats of up to 32-bits can be 8621 // lowered to VSX instructions under certain conditions. 8622 // Without VSX, there is no pattern more efficient than expanding the node. 8623 if (Subtarget.hasVSX() && 8624 haveEfficientBuildVectorPattern(BVN, Subtarget.hasDirectMove(), 8625 Subtarget.hasP8Vector())) 8626 return Op; 8627 return SDValue(); 8628 } 8629 8630 unsigned SplatBits = APSplatBits.getZExtValue(); 8631 unsigned SplatUndef = APSplatUndef.getZExtValue(); 8632 unsigned SplatSize = SplatBitSize / 8; 8633 8634 // First, handle single instruction cases. 8635 8636 // All zeros? 8637 if (SplatBits == 0) { 8638 // Canonicalize all zero vectors to be v4i32. 8639 if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) { 8640 SDValue Z = DAG.getConstant(0, dl, MVT::v4i32); 8641 Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z); 8642 } 8643 return Op; 8644 } 8645 8646 // We have XXSPLTIB for constant splats one byte wide 8647 // FIXME: SplatBits is an unsigned int being cast to an int while passing it 8648 // as an argument to BuildSplatiI. Given SplatSize == 1 it is okay here. 8649 if (Subtarget.hasP9Vector() && SplatSize == 1) 8650 return BuildSplatI(SplatBits, SplatSize, Op.getValueType(), DAG, dl); 8651 8652 // If the sign extended value is in the range [-16,15], use VSPLTI[bhw]. 8653 int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >> 8654 (32-SplatBitSize)); 8655 if (SextVal >= -16 && SextVal <= 15) 8656 return BuildSplatI(SextVal, SplatSize, Op.getValueType(), DAG, dl); 8657 8658 // Two instruction sequences. 8659 8660 // If this value is in the range [-32,30] and is even, use: 8661 // VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2) 8662 // If this value is in the range [17,31] and is odd, use: 8663 // VSPLTI[bhw](val-16) - VSPLTI[bhw](-16) 8664 // If this value is in the range [-31,-17] and is odd, use: 8665 // VSPLTI[bhw](val+16) + VSPLTI[bhw](-16) 8666 // Note the last two are three-instruction sequences. 8667 if (SextVal >= -32 && SextVal <= 31) { 8668 // To avoid having these optimizations undone by constant folding, 8669 // we convert to a pseudo that will be expanded later into one of 8670 // the above forms. 8671 SDValue Elt = DAG.getConstant(SextVal, dl, MVT::i32); 8672 EVT VT = (SplatSize == 1 ? MVT::v16i8 : 8673 (SplatSize == 2 ? MVT::v8i16 : MVT::v4i32)); 8674 SDValue EltSize = DAG.getConstant(SplatSize, dl, MVT::i32); 8675 SDValue RetVal = DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize); 8676 if (VT == Op.getValueType()) 8677 return RetVal; 8678 else 8679 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), RetVal); 8680 } 8681 8682 // If this is 0x8000_0000 x 4, turn into vspltisw + vslw. If it is 8683 // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000). This is important 8684 // for fneg/fabs. 8685 if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) { 8686 // Make -1 and vspltisw -1: 8687 SDValue OnesV = BuildSplatI(-1, 4, MVT::v4i32, DAG, dl); 8688 8689 // Make the VSLW intrinsic, computing 0x8000_0000. 8690 SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV, 8691 OnesV, DAG, dl); 8692 8693 // xor by OnesV to invert it. 8694 Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV); 8695 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 8696 } 8697 8698 // Check to see if this is a wide variety of vsplti*, binop self cases. 8699 static const signed char SplatCsts[] = { 8700 -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7, 8701 -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16 8702 }; 8703 8704 for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) { 8705 // Indirect through the SplatCsts array so that we favor 'vsplti -1' for 8706 // cases which are ambiguous (e.g. formation of 0x8000_0000). 'vsplti -1' 8707 int i = SplatCsts[idx]; 8708 8709 // Figure out what shift amount will be used by altivec if shifted by i in 8710 // this splat size. 8711 unsigned TypeShiftAmt = i & (SplatBitSize-1); 8712 8713 // vsplti + shl self. 8714 if (SextVal == (int)((unsigned)i << TypeShiftAmt)) { 8715 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl); 8716 static const unsigned IIDs[] = { // Intrinsic to use for each size. 8717 Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0, 8718 Intrinsic::ppc_altivec_vslw 8719 }; 8720 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 8721 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 8722 } 8723 8724 // vsplti + srl self. 8725 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) { 8726 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl); 8727 static const unsigned IIDs[] = { // Intrinsic to use for each size. 8728 Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0, 8729 Intrinsic::ppc_altivec_vsrw 8730 }; 8731 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 8732 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 8733 } 8734 8735 // vsplti + sra self. 8736 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) { 8737 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl); 8738 static const unsigned IIDs[] = { // Intrinsic to use for each size. 8739 Intrinsic::ppc_altivec_vsrab, Intrinsic::ppc_altivec_vsrah, 0, 8740 Intrinsic::ppc_altivec_vsraw 8741 }; 8742 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 8743 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 8744 } 8745 8746 // vsplti + rol self. 8747 if (SextVal == (int)(((unsigned)i << TypeShiftAmt) | 8748 ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) { 8749 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl); 8750 static const unsigned IIDs[] = { // Intrinsic to use for each size. 8751 Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0, 8752 Intrinsic::ppc_altivec_vrlw 8753 }; 8754 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 8755 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 8756 } 8757 8758 // t = vsplti c, result = vsldoi t, t, 1 8759 if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) { 8760 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl); 8761 unsigned Amt = Subtarget.isLittleEndian() ? 15 : 1; 8762 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl); 8763 } 8764 // t = vsplti c, result = vsldoi t, t, 2 8765 if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) { 8766 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl); 8767 unsigned Amt = Subtarget.isLittleEndian() ? 14 : 2; 8768 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl); 8769 } 8770 // t = vsplti c, result = vsldoi t, t, 3 8771 if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) { 8772 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl); 8773 unsigned Amt = Subtarget.isLittleEndian() ? 13 : 3; 8774 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl); 8775 } 8776 } 8777 8778 return SDValue(); 8779 } 8780 8781 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit 8782 /// the specified operations to build the shuffle. 8783 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS, 8784 SDValue RHS, SelectionDAG &DAG, 8785 const SDLoc &dl) { 8786 unsigned OpNum = (PFEntry >> 26) & 0x0F; 8787 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1); 8788 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1); 8789 8790 enum { 8791 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3> 8792 OP_VMRGHW, 8793 OP_VMRGLW, 8794 OP_VSPLTISW0, 8795 OP_VSPLTISW1, 8796 OP_VSPLTISW2, 8797 OP_VSPLTISW3, 8798 OP_VSLDOI4, 8799 OP_VSLDOI8, 8800 OP_VSLDOI12 8801 }; 8802 8803 if (OpNum == OP_COPY) { 8804 if (LHSID == (1*9+2)*9+3) return LHS; 8805 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!"); 8806 return RHS; 8807 } 8808 8809 SDValue OpLHS, OpRHS; 8810 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl); 8811 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl); 8812 8813 int ShufIdxs[16]; 8814 switch (OpNum) { 8815 default: llvm_unreachable("Unknown i32 permute!"); 8816 case OP_VMRGHW: 8817 ShufIdxs[ 0] = 0; ShufIdxs[ 1] = 1; ShufIdxs[ 2] = 2; ShufIdxs[ 3] = 3; 8818 ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19; 8819 ShufIdxs[ 8] = 4; ShufIdxs[ 9] = 5; ShufIdxs[10] = 6; ShufIdxs[11] = 7; 8820 ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23; 8821 break; 8822 case OP_VMRGLW: 8823 ShufIdxs[ 0] = 8; ShufIdxs[ 1] = 9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11; 8824 ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27; 8825 ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15; 8826 ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31; 8827 break; 8828 case OP_VSPLTISW0: 8829 for (unsigned i = 0; i != 16; ++i) 8830 ShufIdxs[i] = (i&3)+0; 8831 break; 8832 case OP_VSPLTISW1: 8833 for (unsigned i = 0; i != 16; ++i) 8834 ShufIdxs[i] = (i&3)+4; 8835 break; 8836 case OP_VSPLTISW2: 8837 for (unsigned i = 0; i != 16; ++i) 8838 ShufIdxs[i] = (i&3)+8; 8839 break; 8840 case OP_VSPLTISW3: 8841 for (unsigned i = 0; i != 16; ++i) 8842 ShufIdxs[i] = (i&3)+12; 8843 break; 8844 case OP_VSLDOI4: 8845 return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl); 8846 case OP_VSLDOI8: 8847 return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl); 8848 case OP_VSLDOI12: 8849 return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl); 8850 } 8851 EVT VT = OpLHS.getValueType(); 8852 OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS); 8853 OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS); 8854 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs); 8855 return DAG.getNode(ISD::BITCAST, dl, VT, T); 8856 } 8857 8858 /// lowerToVINSERTB - Return the SDValue if this VECTOR_SHUFFLE can be handled 8859 /// by the VINSERTB instruction introduced in ISA 3.0, else just return default 8860 /// SDValue. 8861 SDValue PPCTargetLowering::lowerToVINSERTB(ShuffleVectorSDNode *N, 8862 SelectionDAG &DAG) const { 8863 const unsigned BytesInVector = 16; 8864 bool IsLE = Subtarget.isLittleEndian(); 8865 SDLoc dl(N); 8866 SDValue V1 = N->getOperand(0); 8867 SDValue V2 = N->getOperand(1); 8868 unsigned ShiftElts = 0, InsertAtByte = 0; 8869 bool Swap = false; 8870 8871 // Shifts required to get the byte we want at element 7. 8872 unsigned LittleEndianShifts[] = {8, 7, 6, 5, 4, 3, 2, 1, 8873 0, 15, 14, 13, 12, 11, 10, 9}; 8874 unsigned BigEndianShifts[] = {9, 10, 11, 12, 13, 14, 15, 0, 8875 1, 2, 3, 4, 5, 6, 7, 8}; 8876 8877 ArrayRef<int> Mask = N->getMask(); 8878 int OriginalOrder[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}; 8879 8880 // For each mask element, find out if we're just inserting something 8881 // from V2 into V1 or vice versa. 8882 // Possible permutations inserting an element from V2 into V1: 8883 // X, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 8884 // 0, X, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 8885 // ... 8886 // 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, X 8887 // Inserting from V1 into V2 will be similar, except mask range will be 8888 // [16,31]. 8889 8890 bool FoundCandidate = false; 8891 // If both vector operands for the shuffle are the same vector, the mask 8892 // will contain only elements from the first one and the second one will be 8893 // undef. 8894 unsigned VINSERTBSrcElem = IsLE ? 8 : 7; 8895 // Go through the mask of half-words to find an element that's being moved 8896 // from one vector to the other. 8897 for (unsigned i = 0; i < BytesInVector; ++i) { 8898 unsigned CurrentElement = Mask[i]; 8899 // If 2nd operand is undefined, we should only look for element 7 in the 8900 // Mask. 8901 if (V2.isUndef() && CurrentElement != VINSERTBSrcElem) 8902 continue; 8903 8904 bool OtherElementsInOrder = true; 8905 // Examine the other elements in the Mask to see if they're in original 8906 // order. 8907 for (unsigned j = 0; j < BytesInVector; ++j) { 8908 if (j == i) 8909 continue; 8910 // If CurrentElement is from V1 [0,15], then we the rest of the Mask to be 8911 // from V2 [16,31] and vice versa. Unless the 2nd operand is undefined, 8912 // in which we always assume we're always picking from the 1st operand. 8913 int MaskOffset = 8914 (!V2.isUndef() && CurrentElement < BytesInVector) ? BytesInVector : 0; 8915 if (Mask[j] != OriginalOrder[j] + MaskOffset) { 8916 OtherElementsInOrder = false; 8917 break; 8918 } 8919 } 8920 // If other elements are in original order, we record the number of shifts 8921 // we need to get the element we want into element 7. Also record which byte 8922 // in the vector we should insert into. 8923 if (OtherElementsInOrder) { 8924 // If 2nd operand is undefined, we assume no shifts and no swapping. 8925 if (V2.isUndef()) { 8926 ShiftElts = 0; 8927 Swap = false; 8928 } else { 8929 // Only need the last 4-bits for shifts because operands will be swapped if CurrentElement is >= 2^4. 8930 ShiftElts = IsLE ? LittleEndianShifts[CurrentElement & 0xF] 8931 : BigEndianShifts[CurrentElement & 0xF]; 8932 Swap = CurrentElement < BytesInVector; 8933 } 8934 InsertAtByte = IsLE ? BytesInVector - (i + 1) : i; 8935 FoundCandidate = true; 8936 break; 8937 } 8938 } 8939 8940 if (!FoundCandidate) 8941 return SDValue(); 8942 8943 // Candidate found, construct the proper SDAG sequence with VINSERTB, 8944 // optionally with VECSHL if shift is required. 8945 if (Swap) 8946 std::swap(V1, V2); 8947 if (V2.isUndef()) 8948 V2 = V1; 8949 if (ShiftElts) { 8950 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2, 8951 DAG.getConstant(ShiftElts, dl, MVT::i32)); 8952 return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, Shl, 8953 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 8954 } 8955 return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, V2, 8956 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 8957 } 8958 8959 /// lowerToVINSERTH - Return the SDValue if this VECTOR_SHUFFLE can be handled 8960 /// by the VINSERTH instruction introduced in ISA 3.0, else just return default 8961 /// SDValue. 8962 SDValue PPCTargetLowering::lowerToVINSERTH(ShuffleVectorSDNode *N, 8963 SelectionDAG &DAG) const { 8964 const unsigned NumHalfWords = 8; 8965 const unsigned BytesInVector = NumHalfWords * 2; 8966 // Check that the shuffle is on half-words. 8967 if (!isNByteElemShuffleMask(N, 2, 1)) 8968 return SDValue(); 8969 8970 bool IsLE = Subtarget.isLittleEndian(); 8971 SDLoc dl(N); 8972 SDValue V1 = N->getOperand(0); 8973 SDValue V2 = N->getOperand(1); 8974 unsigned ShiftElts = 0, InsertAtByte = 0; 8975 bool Swap = false; 8976 8977 // Shifts required to get the half-word we want at element 3. 8978 unsigned LittleEndianShifts[] = {4, 3, 2, 1, 0, 7, 6, 5}; 8979 unsigned BigEndianShifts[] = {5, 6, 7, 0, 1, 2, 3, 4}; 8980 8981 uint32_t Mask = 0; 8982 uint32_t OriginalOrderLow = 0x1234567; 8983 uint32_t OriginalOrderHigh = 0x89ABCDEF; 8984 // Now we look at mask elements 0,2,4,6,8,10,12,14. Pack the mask into a 8985 // 32-bit space, only need 4-bit nibbles per element. 8986 for (unsigned i = 0; i < NumHalfWords; ++i) { 8987 unsigned MaskShift = (NumHalfWords - 1 - i) * 4; 8988 Mask |= ((uint32_t)(N->getMaskElt(i * 2) / 2) << MaskShift); 8989 } 8990 8991 // For each mask element, find out if we're just inserting something 8992 // from V2 into V1 or vice versa. Possible permutations inserting an element 8993 // from V2 into V1: 8994 // X, 1, 2, 3, 4, 5, 6, 7 8995 // 0, X, 2, 3, 4, 5, 6, 7 8996 // 0, 1, X, 3, 4, 5, 6, 7 8997 // 0, 1, 2, X, 4, 5, 6, 7 8998 // 0, 1, 2, 3, X, 5, 6, 7 8999 // 0, 1, 2, 3, 4, X, 6, 7 9000 // 0, 1, 2, 3, 4, 5, X, 7 9001 // 0, 1, 2, 3, 4, 5, 6, X 9002 // Inserting from V1 into V2 will be similar, except mask range will be [8,15]. 9003 9004 bool FoundCandidate = false; 9005 // Go through the mask of half-words to find an element that's being moved 9006 // from one vector to the other. 9007 for (unsigned i = 0; i < NumHalfWords; ++i) { 9008 unsigned MaskShift = (NumHalfWords - 1 - i) * 4; 9009 uint32_t MaskOneElt = (Mask >> MaskShift) & 0xF; 9010 uint32_t MaskOtherElts = ~(0xF << MaskShift); 9011 uint32_t TargetOrder = 0x0; 9012 9013 // If both vector operands for the shuffle are the same vector, the mask 9014 // will contain only elements from the first one and the second one will be 9015 // undef. 9016 if (V2.isUndef()) { 9017 ShiftElts = 0; 9018 unsigned VINSERTHSrcElem = IsLE ? 4 : 3; 9019 TargetOrder = OriginalOrderLow; 9020 Swap = false; 9021 // Skip if not the correct element or mask of other elements don't equal 9022 // to our expected order. 9023 if (MaskOneElt == VINSERTHSrcElem && 9024 (Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) { 9025 InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2; 9026 FoundCandidate = true; 9027 break; 9028 } 9029 } else { // If both operands are defined. 9030 // Target order is [8,15] if the current mask is between [0,7]. 9031 TargetOrder = 9032 (MaskOneElt < NumHalfWords) ? OriginalOrderHigh : OriginalOrderLow; 9033 // Skip if mask of other elements don't equal our expected order. 9034 if ((Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) { 9035 // We only need the last 3 bits for the number of shifts. 9036 ShiftElts = IsLE ? LittleEndianShifts[MaskOneElt & 0x7] 9037 : BigEndianShifts[MaskOneElt & 0x7]; 9038 InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2; 9039 Swap = MaskOneElt < NumHalfWords; 9040 FoundCandidate = true; 9041 break; 9042 } 9043 } 9044 } 9045 9046 if (!FoundCandidate) 9047 return SDValue(); 9048 9049 // Candidate found, construct the proper SDAG sequence with VINSERTH, 9050 // optionally with VECSHL if shift is required. 9051 if (Swap) 9052 std::swap(V1, V2); 9053 if (V2.isUndef()) 9054 V2 = V1; 9055 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1); 9056 if (ShiftElts) { 9057 // Double ShiftElts because we're left shifting on v16i8 type. 9058 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2, 9059 DAG.getConstant(2 * ShiftElts, dl, MVT::i32)); 9060 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, Shl); 9061 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2, 9062 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9063 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 9064 } 9065 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2); 9066 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2, 9067 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9068 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 9069 } 9070 9071 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE. If this 9072 /// is a shuffle we can handle in a single instruction, return it. Otherwise, 9073 /// return the code it can be lowered into. Worst case, it can always be 9074 /// lowered into a vperm. 9075 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, 9076 SelectionDAG &DAG) const { 9077 SDLoc dl(Op); 9078 SDValue V1 = Op.getOperand(0); 9079 SDValue V2 = Op.getOperand(1); 9080 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op); 9081 EVT VT = Op.getValueType(); 9082 bool isLittleEndian = Subtarget.isLittleEndian(); 9083 9084 unsigned ShiftElts, InsertAtByte; 9085 bool Swap = false; 9086 9087 // If this is a load-and-splat, we can do that with a single instruction 9088 // in some cases. However if the load has multiple uses, we don't want to 9089 // combine it because that will just produce multiple loads. 9090 const SDValue *InputLoad = getNormalLoadInput(V1); 9091 if (InputLoad && Subtarget.hasVSX() && V2.isUndef() && 9092 (PPC::isSplatShuffleMask(SVOp, 4) || PPC::isSplatShuffleMask(SVOp, 8)) && 9093 InputLoad->hasOneUse()) { 9094 bool IsFourByte = PPC::isSplatShuffleMask(SVOp, 4); 9095 int SplatIdx = 9096 PPC::getSplatIdxForPPCMnemonics(SVOp, IsFourByte ? 4 : 8, DAG); 9097 9098 LoadSDNode *LD = cast<LoadSDNode>(*InputLoad); 9099 // For 4-byte load-and-splat, we need Power9. 9100 if ((IsFourByte && Subtarget.hasP9Vector()) || !IsFourByte) { 9101 uint64_t Offset = 0; 9102 if (IsFourByte) 9103 Offset = isLittleEndian ? (3 - SplatIdx) * 4 : SplatIdx * 4; 9104 else 9105 Offset = isLittleEndian ? (1 - SplatIdx) * 8 : SplatIdx * 8; 9106 SDValue BasePtr = LD->getBasePtr(); 9107 if (Offset != 0) 9108 BasePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()), 9109 BasePtr, DAG.getIntPtrConstant(Offset, dl)); 9110 SDValue Ops[] = { 9111 LD->getChain(), // Chain 9112 BasePtr, // BasePtr 9113 DAG.getValueType(Op.getValueType()) // VT 9114 }; 9115 SDVTList VTL = 9116 DAG.getVTList(IsFourByte ? MVT::v4i32 : MVT::v2i64, MVT::Other); 9117 SDValue LdSplt = 9118 DAG.getMemIntrinsicNode(PPCISD::LD_SPLAT, dl, VTL, 9119 Ops, LD->getMemoryVT(), LD->getMemOperand()); 9120 if (LdSplt.getValueType() != SVOp->getValueType(0)) 9121 LdSplt = DAG.getBitcast(SVOp->getValueType(0), LdSplt); 9122 return LdSplt; 9123 } 9124 } 9125 if (Subtarget.hasP9Vector() && 9126 PPC::isXXINSERTWMask(SVOp, ShiftElts, InsertAtByte, Swap, 9127 isLittleEndian)) { 9128 if (Swap) 9129 std::swap(V1, V2); 9130 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 9131 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2); 9132 if (ShiftElts) { 9133 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv2, Conv2, 9134 DAG.getConstant(ShiftElts, dl, MVT::i32)); 9135 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Shl, 9136 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9137 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 9138 } 9139 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Conv2, 9140 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9141 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 9142 } 9143 9144 if (Subtarget.hasP9Altivec()) { 9145 SDValue NewISDNode; 9146 if ((NewISDNode = lowerToVINSERTH(SVOp, DAG))) 9147 return NewISDNode; 9148 9149 if ((NewISDNode = lowerToVINSERTB(SVOp, DAG))) 9150 return NewISDNode; 9151 } 9152 9153 if (Subtarget.hasVSX() && 9154 PPC::isXXSLDWIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) { 9155 if (Swap) 9156 std::swap(V1, V2); 9157 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 9158 SDValue Conv2 = 9159 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2.isUndef() ? V1 : V2); 9160 9161 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv1, Conv2, 9162 DAG.getConstant(ShiftElts, dl, MVT::i32)); 9163 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Shl); 9164 } 9165 9166 if (Subtarget.hasVSX() && 9167 PPC::isXXPERMDIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) { 9168 if (Swap) 9169 std::swap(V1, V2); 9170 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1); 9171 SDValue Conv2 = 9172 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2.isUndef() ? V1 : V2); 9173 9174 SDValue PermDI = DAG.getNode(PPCISD::XXPERMDI, dl, MVT::v2i64, Conv1, Conv2, 9175 DAG.getConstant(ShiftElts, dl, MVT::i32)); 9176 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, PermDI); 9177 } 9178 9179 if (Subtarget.hasP9Vector()) { 9180 if (PPC::isXXBRHShuffleMask(SVOp)) { 9181 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1); 9182 SDValue ReveHWord = DAG.getNode(PPCISD::XXREVERSE, dl, MVT::v8i16, Conv); 9183 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveHWord); 9184 } else if (PPC::isXXBRWShuffleMask(SVOp)) { 9185 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 9186 SDValue ReveWord = DAG.getNode(PPCISD::XXREVERSE, dl, MVT::v4i32, Conv); 9187 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveWord); 9188 } else if (PPC::isXXBRDShuffleMask(SVOp)) { 9189 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1); 9190 SDValue ReveDWord = DAG.getNode(PPCISD::XXREVERSE, dl, MVT::v2i64, Conv); 9191 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveDWord); 9192 } else if (PPC::isXXBRQShuffleMask(SVOp)) { 9193 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, V1); 9194 SDValue ReveQWord = DAG.getNode(PPCISD::XXREVERSE, dl, MVT::v1i128, Conv); 9195 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveQWord); 9196 } 9197 } 9198 9199 if (Subtarget.hasVSX()) { 9200 if (V2.isUndef() && PPC::isSplatShuffleMask(SVOp, 4)) { 9201 int SplatIdx = PPC::getSplatIdxForPPCMnemonics(SVOp, 4, DAG); 9202 9203 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 9204 SDValue Splat = DAG.getNode(PPCISD::XXSPLT, dl, MVT::v4i32, Conv, 9205 DAG.getConstant(SplatIdx, dl, MVT::i32)); 9206 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Splat); 9207 } 9208 9209 // Left shifts of 8 bytes are actually swaps. Convert accordingly. 9210 if (V2.isUndef() && PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) == 8) { 9211 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1); 9212 SDValue Swap = DAG.getNode(PPCISD::SWAP_NO_CHAIN, dl, MVT::v2f64, Conv); 9213 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Swap); 9214 } 9215 } 9216 9217 if (Subtarget.hasQPX()) { 9218 if (VT.getVectorNumElements() != 4) 9219 return SDValue(); 9220 9221 if (V2.isUndef()) V2 = V1; 9222 9223 int AlignIdx = PPC::isQVALIGNIShuffleMask(SVOp); 9224 if (AlignIdx != -1) { 9225 return DAG.getNode(PPCISD::QVALIGNI, dl, VT, V1, V2, 9226 DAG.getConstant(AlignIdx, dl, MVT::i32)); 9227 } else if (SVOp->isSplat()) { 9228 int SplatIdx = SVOp->getSplatIndex(); 9229 if (SplatIdx >= 4) { 9230 std::swap(V1, V2); 9231 SplatIdx -= 4; 9232 } 9233 9234 return DAG.getNode(PPCISD::QVESPLATI, dl, VT, V1, 9235 DAG.getConstant(SplatIdx, dl, MVT::i32)); 9236 } 9237 9238 // Lower this into a qvgpci/qvfperm pair. 9239 9240 // Compute the qvgpci literal 9241 unsigned idx = 0; 9242 for (unsigned i = 0; i < 4; ++i) { 9243 int m = SVOp->getMaskElt(i); 9244 unsigned mm = m >= 0 ? (unsigned) m : i; 9245 idx |= mm << (3-i)*3; 9246 } 9247 9248 SDValue V3 = DAG.getNode(PPCISD::QVGPCI, dl, MVT::v4f64, 9249 DAG.getConstant(idx, dl, MVT::i32)); 9250 return DAG.getNode(PPCISD::QVFPERM, dl, VT, V1, V2, V3); 9251 } 9252 9253 // Cases that are handled by instructions that take permute immediates 9254 // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be 9255 // selected by the instruction selector. 9256 if (V2.isUndef()) { 9257 if (PPC::isSplatShuffleMask(SVOp, 1) || 9258 PPC::isSplatShuffleMask(SVOp, 2) || 9259 PPC::isSplatShuffleMask(SVOp, 4) || 9260 PPC::isVPKUWUMShuffleMask(SVOp, 1, DAG) || 9261 PPC::isVPKUHUMShuffleMask(SVOp, 1, DAG) || 9262 PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) != -1 || 9263 PPC::isVMRGLShuffleMask(SVOp, 1, 1, DAG) || 9264 PPC::isVMRGLShuffleMask(SVOp, 2, 1, DAG) || 9265 PPC::isVMRGLShuffleMask(SVOp, 4, 1, DAG) || 9266 PPC::isVMRGHShuffleMask(SVOp, 1, 1, DAG) || 9267 PPC::isVMRGHShuffleMask(SVOp, 2, 1, DAG) || 9268 PPC::isVMRGHShuffleMask(SVOp, 4, 1, DAG) || 9269 (Subtarget.hasP8Altivec() && ( 9270 PPC::isVPKUDUMShuffleMask(SVOp, 1, DAG) || 9271 PPC::isVMRGEOShuffleMask(SVOp, true, 1, DAG) || 9272 PPC::isVMRGEOShuffleMask(SVOp, false, 1, DAG)))) { 9273 return Op; 9274 } 9275 } 9276 9277 // Altivec has a variety of "shuffle immediates" that take two vector inputs 9278 // and produce a fixed permutation. If any of these match, do not lower to 9279 // VPERM. 9280 unsigned int ShuffleKind = isLittleEndian ? 2 : 0; 9281 if (PPC::isVPKUWUMShuffleMask(SVOp, ShuffleKind, DAG) || 9282 PPC::isVPKUHUMShuffleMask(SVOp, ShuffleKind, DAG) || 9283 PPC::isVSLDOIShuffleMask(SVOp, ShuffleKind, DAG) != -1 || 9284 PPC::isVMRGLShuffleMask(SVOp, 1, ShuffleKind, DAG) || 9285 PPC::isVMRGLShuffleMask(SVOp, 2, ShuffleKind, DAG) || 9286 PPC::isVMRGLShuffleMask(SVOp, 4, ShuffleKind, DAG) || 9287 PPC::isVMRGHShuffleMask(SVOp, 1, ShuffleKind, DAG) || 9288 PPC::isVMRGHShuffleMask(SVOp, 2, ShuffleKind, DAG) || 9289 PPC::isVMRGHShuffleMask(SVOp, 4, ShuffleKind, DAG) || 9290 (Subtarget.hasP8Altivec() && ( 9291 PPC::isVPKUDUMShuffleMask(SVOp, ShuffleKind, DAG) || 9292 PPC::isVMRGEOShuffleMask(SVOp, true, ShuffleKind, DAG) || 9293 PPC::isVMRGEOShuffleMask(SVOp, false, ShuffleKind, DAG)))) 9294 return Op; 9295 9296 // Check to see if this is a shuffle of 4-byte values. If so, we can use our 9297 // perfect shuffle table to emit an optimal matching sequence. 9298 ArrayRef<int> PermMask = SVOp->getMask(); 9299 9300 unsigned PFIndexes[4]; 9301 bool isFourElementShuffle = true; 9302 for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number 9303 unsigned EltNo = 8; // Start out undef. 9304 for (unsigned j = 0; j != 4; ++j) { // Intra-element byte. 9305 if (PermMask[i*4+j] < 0) 9306 continue; // Undef, ignore it. 9307 9308 unsigned ByteSource = PermMask[i*4+j]; 9309 if ((ByteSource & 3) != j) { 9310 isFourElementShuffle = false; 9311 break; 9312 } 9313 9314 if (EltNo == 8) { 9315 EltNo = ByteSource/4; 9316 } else if (EltNo != ByteSource/4) { 9317 isFourElementShuffle = false; 9318 break; 9319 } 9320 } 9321 PFIndexes[i] = EltNo; 9322 } 9323 9324 // If this shuffle can be expressed as a shuffle of 4-byte elements, use the 9325 // perfect shuffle vector to determine if it is cost effective to do this as 9326 // discrete instructions, or whether we should use a vperm. 9327 // For now, we skip this for little endian until such time as we have a 9328 // little-endian perfect shuffle table. 9329 if (isFourElementShuffle && !isLittleEndian) { 9330 // Compute the index in the perfect shuffle table. 9331 unsigned PFTableIndex = 9332 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3]; 9333 9334 unsigned PFEntry = PerfectShuffleTable[PFTableIndex]; 9335 unsigned Cost = (PFEntry >> 30); 9336 9337 // Determining when to avoid vperm is tricky. Many things affect the cost 9338 // of vperm, particularly how many times the perm mask needs to be computed. 9339 // For example, if the perm mask can be hoisted out of a loop or is already 9340 // used (perhaps because there are multiple permutes with the same shuffle 9341 // mask?) the vperm has a cost of 1. OTOH, hoisting the permute mask out of 9342 // the loop requires an extra register. 9343 // 9344 // As a compromise, we only emit discrete instructions if the shuffle can be 9345 // generated in 3 or fewer operations. When we have loop information 9346 // available, if this block is within a loop, we should avoid using vperm 9347 // for 3-operation perms and use a constant pool load instead. 9348 if (Cost < 3) 9349 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl); 9350 } 9351 9352 // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant 9353 // vector that will get spilled to the constant pool. 9354 if (V2.isUndef()) V2 = V1; 9355 9356 // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except 9357 // that it is in input element units, not in bytes. Convert now. 9358 9359 // For little endian, the order of the input vectors is reversed, and 9360 // the permutation mask is complemented with respect to 31. This is 9361 // necessary to produce proper semantics with the big-endian-biased vperm 9362 // instruction. 9363 EVT EltVT = V1.getValueType().getVectorElementType(); 9364 unsigned BytesPerElement = EltVT.getSizeInBits()/8; 9365 9366 SmallVector<SDValue, 16> ResultMask; 9367 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) { 9368 unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i]; 9369 9370 for (unsigned j = 0; j != BytesPerElement; ++j) 9371 if (isLittleEndian) 9372 ResultMask.push_back(DAG.getConstant(31 - (SrcElt*BytesPerElement + j), 9373 dl, MVT::i32)); 9374 else 9375 ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement + j, dl, 9376 MVT::i32)); 9377 } 9378 9379 SDValue VPermMask = DAG.getBuildVector(MVT::v16i8, dl, ResultMask); 9380 if (isLittleEndian) 9381 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(), 9382 V2, V1, VPermMask); 9383 else 9384 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(), 9385 V1, V2, VPermMask); 9386 } 9387 9388 /// getVectorCompareInfo - Given an intrinsic, return false if it is not a 9389 /// vector comparison. If it is, return true and fill in Opc/isDot with 9390 /// information about the intrinsic. 9391 static bool getVectorCompareInfo(SDValue Intrin, int &CompareOpc, 9392 bool &isDot, const PPCSubtarget &Subtarget) { 9393 unsigned IntrinsicID = 9394 cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue(); 9395 CompareOpc = -1; 9396 isDot = false; 9397 switch (IntrinsicID) { 9398 default: 9399 return false; 9400 // Comparison predicates. 9401 case Intrinsic::ppc_altivec_vcmpbfp_p: 9402 CompareOpc = 966; 9403 isDot = true; 9404 break; 9405 case Intrinsic::ppc_altivec_vcmpeqfp_p: 9406 CompareOpc = 198; 9407 isDot = true; 9408 break; 9409 case Intrinsic::ppc_altivec_vcmpequb_p: 9410 CompareOpc = 6; 9411 isDot = true; 9412 break; 9413 case Intrinsic::ppc_altivec_vcmpequh_p: 9414 CompareOpc = 70; 9415 isDot = true; 9416 break; 9417 case Intrinsic::ppc_altivec_vcmpequw_p: 9418 CompareOpc = 134; 9419 isDot = true; 9420 break; 9421 case Intrinsic::ppc_altivec_vcmpequd_p: 9422 if (Subtarget.hasP8Altivec()) { 9423 CompareOpc = 199; 9424 isDot = true; 9425 } else 9426 return false; 9427 break; 9428 case Intrinsic::ppc_altivec_vcmpneb_p: 9429 case Intrinsic::ppc_altivec_vcmpneh_p: 9430 case Intrinsic::ppc_altivec_vcmpnew_p: 9431 case Intrinsic::ppc_altivec_vcmpnezb_p: 9432 case Intrinsic::ppc_altivec_vcmpnezh_p: 9433 case Intrinsic::ppc_altivec_vcmpnezw_p: 9434 if (Subtarget.hasP9Altivec()) { 9435 switch (IntrinsicID) { 9436 default: 9437 llvm_unreachable("Unknown comparison intrinsic."); 9438 case Intrinsic::ppc_altivec_vcmpneb_p: 9439 CompareOpc = 7; 9440 break; 9441 case Intrinsic::ppc_altivec_vcmpneh_p: 9442 CompareOpc = 71; 9443 break; 9444 case Intrinsic::ppc_altivec_vcmpnew_p: 9445 CompareOpc = 135; 9446 break; 9447 case Intrinsic::ppc_altivec_vcmpnezb_p: 9448 CompareOpc = 263; 9449 break; 9450 case Intrinsic::ppc_altivec_vcmpnezh_p: 9451 CompareOpc = 327; 9452 break; 9453 case Intrinsic::ppc_altivec_vcmpnezw_p: 9454 CompareOpc = 391; 9455 break; 9456 } 9457 isDot = true; 9458 } else 9459 return false; 9460 break; 9461 case Intrinsic::ppc_altivec_vcmpgefp_p: 9462 CompareOpc = 454; 9463 isDot = true; 9464 break; 9465 case Intrinsic::ppc_altivec_vcmpgtfp_p: 9466 CompareOpc = 710; 9467 isDot = true; 9468 break; 9469 case Intrinsic::ppc_altivec_vcmpgtsb_p: 9470 CompareOpc = 774; 9471 isDot = true; 9472 break; 9473 case Intrinsic::ppc_altivec_vcmpgtsh_p: 9474 CompareOpc = 838; 9475 isDot = true; 9476 break; 9477 case Intrinsic::ppc_altivec_vcmpgtsw_p: 9478 CompareOpc = 902; 9479 isDot = true; 9480 break; 9481 case Intrinsic::ppc_altivec_vcmpgtsd_p: 9482 if (Subtarget.hasP8Altivec()) { 9483 CompareOpc = 967; 9484 isDot = true; 9485 } else 9486 return false; 9487 break; 9488 case Intrinsic::ppc_altivec_vcmpgtub_p: 9489 CompareOpc = 518; 9490 isDot = true; 9491 break; 9492 case Intrinsic::ppc_altivec_vcmpgtuh_p: 9493 CompareOpc = 582; 9494 isDot = true; 9495 break; 9496 case Intrinsic::ppc_altivec_vcmpgtuw_p: 9497 CompareOpc = 646; 9498 isDot = true; 9499 break; 9500 case Intrinsic::ppc_altivec_vcmpgtud_p: 9501 if (Subtarget.hasP8Altivec()) { 9502 CompareOpc = 711; 9503 isDot = true; 9504 } else 9505 return false; 9506 break; 9507 9508 // VSX predicate comparisons use the same infrastructure 9509 case Intrinsic::ppc_vsx_xvcmpeqdp_p: 9510 case Intrinsic::ppc_vsx_xvcmpgedp_p: 9511 case Intrinsic::ppc_vsx_xvcmpgtdp_p: 9512 case Intrinsic::ppc_vsx_xvcmpeqsp_p: 9513 case Intrinsic::ppc_vsx_xvcmpgesp_p: 9514 case Intrinsic::ppc_vsx_xvcmpgtsp_p: 9515 if (Subtarget.hasVSX()) { 9516 switch (IntrinsicID) { 9517 case Intrinsic::ppc_vsx_xvcmpeqdp_p: 9518 CompareOpc = 99; 9519 break; 9520 case Intrinsic::ppc_vsx_xvcmpgedp_p: 9521 CompareOpc = 115; 9522 break; 9523 case Intrinsic::ppc_vsx_xvcmpgtdp_p: 9524 CompareOpc = 107; 9525 break; 9526 case Intrinsic::ppc_vsx_xvcmpeqsp_p: 9527 CompareOpc = 67; 9528 break; 9529 case Intrinsic::ppc_vsx_xvcmpgesp_p: 9530 CompareOpc = 83; 9531 break; 9532 case Intrinsic::ppc_vsx_xvcmpgtsp_p: 9533 CompareOpc = 75; 9534 break; 9535 } 9536 isDot = true; 9537 } else 9538 return false; 9539 break; 9540 9541 // Normal Comparisons. 9542 case Intrinsic::ppc_altivec_vcmpbfp: 9543 CompareOpc = 966; 9544 break; 9545 case Intrinsic::ppc_altivec_vcmpeqfp: 9546 CompareOpc = 198; 9547 break; 9548 case Intrinsic::ppc_altivec_vcmpequb: 9549 CompareOpc = 6; 9550 break; 9551 case Intrinsic::ppc_altivec_vcmpequh: 9552 CompareOpc = 70; 9553 break; 9554 case Intrinsic::ppc_altivec_vcmpequw: 9555 CompareOpc = 134; 9556 break; 9557 case Intrinsic::ppc_altivec_vcmpequd: 9558 if (Subtarget.hasP8Altivec()) 9559 CompareOpc = 199; 9560 else 9561 return false; 9562 break; 9563 case Intrinsic::ppc_altivec_vcmpneb: 9564 case Intrinsic::ppc_altivec_vcmpneh: 9565 case Intrinsic::ppc_altivec_vcmpnew: 9566 case Intrinsic::ppc_altivec_vcmpnezb: 9567 case Intrinsic::ppc_altivec_vcmpnezh: 9568 case Intrinsic::ppc_altivec_vcmpnezw: 9569 if (Subtarget.hasP9Altivec()) 9570 switch (IntrinsicID) { 9571 default: 9572 llvm_unreachable("Unknown comparison intrinsic."); 9573 case Intrinsic::ppc_altivec_vcmpneb: 9574 CompareOpc = 7; 9575 break; 9576 case Intrinsic::ppc_altivec_vcmpneh: 9577 CompareOpc = 71; 9578 break; 9579 case Intrinsic::ppc_altivec_vcmpnew: 9580 CompareOpc = 135; 9581 break; 9582 case Intrinsic::ppc_altivec_vcmpnezb: 9583 CompareOpc = 263; 9584 break; 9585 case Intrinsic::ppc_altivec_vcmpnezh: 9586 CompareOpc = 327; 9587 break; 9588 case Intrinsic::ppc_altivec_vcmpnezw: 9589 CompareOpc = 391; 9590 break; 9591 } 9592 else 9593 return false; 9594 break; 9595 case Intrinsic::ppc_altivec_vcmpgefp: 9596 CompareOpc = 454; 9597 break; 9598 case Intrinsic::ppc_altivec_vcmpgtfp: 9599 CompareOpc = 710; 9600 break; 9601 case Intrinsic::ppc_altivec_vcmpgtsb: 9602 CompareOpc = 774; 9603 break; 9604 case Intrinsic::ppc_altivec_vcmpgtsh: 9605 CompareOpc = 838; 9606 break; 9607 case Intrinsic::ppc_altivec_vcmpgtsw: 9608 CompareOpc = 902; 9609 break; 9610 case Intrinsic::ppc_altivec_vcmpgtsd: 9611 if (Subtarget.hasP8Altivec()) 9612 CompareOpc = 967; 9613 else 9614 return false; 9615 break; 9616 case Intrinsic::ppc_altivec_vcmpgtub: 9617 CompareOpc = 518; 9618 break; 9619 case Intrinsic::ppc_altivec_vcmpgtuh: 9620 CompareOpc = 582; 9621 break; 9622 case Intrinsic::ppc_altivec_vcmpgtuw: 9623 CompareOpc = 646; 9624 break; 9625 case Intrinsic::ppc_altivec_vcmpgtud: 9626 if (Subtarget.hasP8Altivec()) 9627 CompareOpc = 711; 9628 else 9629 return false; 9630 break; 9631 } 9632 return true; 9633 } 9634 9635 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom 9636 /// lower, do it, otherwise return null. 9637 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 9638 SelectionDAG &DAG) const { 9639 unsigned IntrinsicID = 9640 cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 9641 9642 SDLoc dl(Op); 9643 9644 if (IntrinsicID == Intrinsic::thread_pointer) { 9645 // Reads the thread pointer register, used for __builtin_thread_pointer. 9646 if (Subtarget.isPPC64()) 9647 return DAG.getRegister(PPC::X13, MVT::i64); 9648 return DAG.getRegister(PPC::R2, MVT::i32); 9649 } 9650 9651 // If this is a lowered altivec predicate compare, CompareOpc is set to the 9652 // opcode number of the comparison. 9653 int CompareOpc; 9654 bool isDot; 9655 if (!getVectorCompareInfo(Op, CompareOpc, isDot, Subtarget)) 9656 return SDValue(); // Don't custom lower most intrinsics. 9657 9658 // If this is a non-dot comparison, make the VCMP node and we are done. 9659 if (!isDot) { 9660 SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(), 9661 Op.getOperand(1), Op.getOperand(2), 9662 DAG.getConstant(CompareOpc, dl, MVT::i32)); 9663 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp); 9664 } 9665 9666 // Create the PPCISD altivec 'dot' comparison node. 9667 SDValue Ops[] = { 9668 Op.getOperand(2), // LHS 9669 Op.getOperand(3), // RHS 9670 DAG.getConstant(CompareOpc, dl, MVT::i32) 9671 }; 9672 EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue }; 9673 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops); 9674 9675 // Now that we have the comparison, emit a copy from the CR to a GPR. 9676 // This is flagged to the above dot comparison. 9677 SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32, 9678 DAG.getRegister(PPC::CR6, MVT::i32), 9679 CompNode.getValue(1)); 9680 9681 // Unpack the result based on how the target uses it. 9682 unsigned BitNo; // Bit # of CR6. 9683 bool InvertBit; // Invert result? 9684 switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) { 9685 default: // Can't happen, don't crash on invalid number though. 9686 case 0: // Return the value of the EQ bit of CR6. 9687 BitNo = 0; InvertBit = false; 9688 break; 9689 case 1: // Return the inverted value of the EQ bit of CR6. 9690 BitNo = 0; InvertBit = true; 9691 break; 9692 case 2: // Return the value of the LT bit of CR6. 9693 BitNo = 2; InvertBit = false; 9694 break; 9695 case 3: // Return the inverted value of the LT bit of CR6. 9696 BitNo = 2; InvertBit = true; 9697 break; 9698 } 9699 9700 // Shift the bit into the low position. 9701 Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags, 9702 DAG.getConstant(8 - (3 - BitNo), dl, MVT::i32)); 9703 // Isolate the bit. 9704 Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags, 9705 DAG.getConstant(1, dl, MVT::i32)); 9706 9707 // If we are supposed to, toggle the bit. 9708 if (InvertBit) 9709 Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags, 9710 DAG.getConstant(1, dl, MVT::i32)); 9711 return Flags; 9712 } 9713 9714 SDValue PPCTargetLowering::LowerINTRINSIC_VOID(SDValue Op, 9715 SelectionDAG &DAG) const { 9716 // SelectionDAGBuilder::visitTargetIntrinsic may insert one extra chain to 9717 // the beginning of the argument list. 9718 int ArgStart = isa<ConstantSDNode>(Op.getOperand(0)) ? 0 : 1; 9719 SDLoc DL(Op); 9720 switch (cast<ConstantSDNode>(Op.getOperand(ArgStart))->getZExtValue()) { 9721 case Intrinsic::ppc_cfence: { 9722 assert(ArgStart == 1 && "llvm.ppc.cfence must carry a chain argument."); 9723 assert(Subtarget.isPPC64() && "Only 64-bit is supported for now."); 9724 return SDValue(DAG.getMachineNode(PPC::CFENCE8, DL, MVT::Other, 9725 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, 9726 Op.getOperand(ArgStart + 1)), 9727 Op.getOperand(0)), 9728 0); 9729 } 9730 default: 9731 break; 9732 } 9733 return SDValue(); 9734 } 9735 9736 SDValue PPCTargetLowering::LowerREM(SDValue Op, SelectionDAG &DAG) const { 9737 // Check for a DIV with the same operands as this REM. 9738 for (auto UI : Op.getOperand(1)->uses()) { 9739 if ((Op.getOpcode() == ISD::SREM && UI->getOpcode() == ISD::SDIV) || 9740 (Op.getOpcode() == ISD::UREM && UI->getOpcode() == ISD::UDIV)) 9741 if (UI->getOperand(0) == Op.getOperand(0) && 9742 UI->getOperand(1) == Op.getOperand(1)) 9743 return SDValue(); 9744 } 9745 return Op; 9746 } 9747 9748 // Lower scalar BSWAP64 to xxbrd. 9749 SDValue PPCTargetLowering::LowerBSWAP(SDValue Op, SelectionDAG &DAG) const { 9750 SDLoc dl(Op); 9751 // MTVSRDD 9752 Op = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i64, Op.getOperand(0), 9753 Op.getOperand(0)); 9754 // XXBRD 9755 Op = DAG.getNode(PPCISD::XXREVERSE, dl, MVT::v2i64, Op); 9756 // MFVSRD 9757 int VectorIndex = 0; 9758 if (Subtarget.isLittleEndian()) 9759 VectorIndex = 1; 9760 Op = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Op, 9761 DAG.getTargetConstant(VectorIndex, dl, MVT::i32)); 9762 return Op; 9763 } 9764 9765 // ATOMIC_CMP_SWAP for i8/i16 needs to zero-extend its input since it will be 9766 // compared to a value that is atomically loaded (atomic loads zero-extend). 9767 SDValue PPCTargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, 9768 SelectionDAG &DAG) const { 9769 assert(Op.getOpcode() == ISD::ATOMIC_CMP_SWAP && 9770 "Expecting an atomic compare-and-swap here."); 9771 SDLoc dl(Op); 9772 auto *AtomicNode = cast<AtomicSDNode>(Op.getNode()); 9773 EVT MemVT = AtomicNode->getMemoryVT(); 9774 if (MemVT.getSizeInBits() >= 32) 9775 return Op; 9776 9777 SDValue CmpOp = Op.getOperand(2); 9778 // If this is already correctly zero-extended, leave it alone. 9779 auto HighBits = APInt::getHighBitsSet(32, 32 - MemVT.getSizeInBits()); 9780 if (DAG.MaskedValueIsZero(CmpOp, HighBits)) 9781 return Op; 9782 9783 // Clear the high bits of the compare operand. 9784 unsigned MaskVal = (1 << MemVT.getSizeInBits()) - 1; 9785 SDValue NewCmpOp = 9786 DAG.getNode(ISD::AND, dl, MVT::i32, CmpOp, 9787 DAG.getConstant(MaskVal, dl, MVT::i32)); 9788 9789 // Replace the existing compare operand with the properly zero-extended one. 9790 SmallVector<SDValue, 4> Ops; 9791 for (int i = 0, e = AtomicNode->getNumOperands(); i < e; i++) 9792 Ops.push_back(AtomicNode->getOperand(i)); 9793 Ops[2] = NewCmpOp; 9794 MachineMemOperand *MMO = AtomicNode->getMemOperand(); 9795 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::Other); 9796 auto NodeTy = 9797 (MemVT == MVT::i8) ? PPCISD::ATOMIC_CMP_SWAP_8 : PPCISD::ATOMIC_CMP_SWAP_16; 9798 return DAG.getMemIntrinsicNode(NodeTy, dl, Tys, Ops, MemVT, MMO); 9799 } 9800 9801 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, 9802 SelectionDAG &DAG) const { 9803 SDLoc dl(Op); 9804 // Create a stack slot that is 16-byte aligned. 9805 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 9806 int FrameIdx = MFI.CreateStackObject(16, 16, false); 9807 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 9808 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 9809 9810 // Store the input value into Value#0 of the stack slot. 9811 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx, 9812 MachinePointerInfo()); 9813 // Load it out. 9814 return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo()); 9815 } 9816 9817 SDValue PPCTargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, 9818 SelectionDAG &DAG) const { 9819 assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && 9820 "Should only be called for ISD::INSERT_VECTOR_ELT"); 9821 9822 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(2)); 9823 // We have legal lowering for constant indices but not for variable ones. 9824 if (!C) 9825 return SDValue(); 9826 9827 EVT VT = Op.getValueType(); 9828 SDLoc dl(Op); 9829 SDValue V1 = Op.getOperand(0); 9830 SDValue V2 = Op.getOperand(1); 9831 // We can use MTVSRZ + VECINSERT for v8i16 and v16i8 types. 9832 if (VT == MVT::v8i16 || VT == MVT::v16i8) { 9833 SDValue Mtvsrz = DAG.getNode(PPCISD::MTVSRZ, dl, VT, V2); 9834 unsigned BytesInEachElement = VT.getVectorElementType().getSizeInBits() / 8; 9835 unsigned InsertAtElement = C->getZExtValue(); 9836 unsigned InsertAtByte = InsertAtElement * BytesInEachElement; 9837 if (Subtarget.isLittleEndian()) { 9838 InsertAtByte = (16 - BytesInEachElement) - InsertAtByte; 9839 } 9840 return DAG.getNode(PPCISD::VECINSERT, dl, VT, V1, Mtvsrz, 9841 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9842 } 9843 return Op; 9844 } 9845 9846 SDValue PPCTargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op, 9847 SelectionDAG &DAG) const { 9848 SDLoc dl(Op); 9849 SDNode *N = Op.getNode(); 9850 9851 assert(N->getOperand(0).getValueType() == MVT::v4i1 && 9852 "Unknown extract_vector_elt type"); 9853 9854 SDValue Value = N->getOperand(0); 9855 9856 // The first part of this is like the store lowering except that we don't 9857 // need to track the chain. 9858 9859 // The values are now known to be -1 (false) or 1 (true). To convert this 9860 // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5). 9861 // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5 9862 Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value); 9863 9864 // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to 9865 // understand how to form the extending load. 9866 SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64); 9867 9868 Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs); 9869 9870 // Now convert to an integer and store. 9871 Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64, 9872 DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32), 9873 Value); 9874 9875 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 9876 int FrameIdx = MFI.CreateStackObject(16, 16, false); 9877 MachinePointerInfo PtrInfo = 9878 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 9879 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 9880 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 9881 9882 SDValue StoreChain = DAG.getEntryNode(); 9883 SDValue Ops[] = {StoreChain, 9884 DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32), 9885 Value, FIdx}; 9886 SDVTList VTs = DAG.getVTList(/*chain*/ MVT::Other); 9887 9888 StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, 9889 dl, VTs, Ops, MVT::v4i32, PtrInfo); 9890 9891 // Extract the value requested. 9892 unsigned Offset = 4*cast<ConstantSDNode>(N->getOperand(1))->getZExtValue(); 9893 SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType()); 9894 Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx); 9895 9896 SDValue IntVal = 9897 DAG.getLoad(MVT::i32, dl, StoreChain, Idx, PtrInfo.getWithOffset(Offset)); 9898 9899 if (!Subtarget.useCRBits()) 9900 return IntVal; 9901 9902 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, IntVal); 9903 } 9904 9905 /// Lowering for QPX v4i1 loads 9906 SDValue PPCTargetLowering::LowerVectorLoad(SDValue Op, 9907 SelectionDAG &DAG) const { 9908 SDLoc dl(Op); 9909 LoadSDNode *LN = cast<LoadSDNode>(Op.getNode()); 9910 SDValue LoadChain = LN->getChain(); 9911 SDValue BasePtr = LN->getBasePtr(); 9912 9913 if (Op.getValueType() == MVT::v4f64 || 9914 Op.getValueType() == MVT::v4f32) { 9915 EVT MemVT = LN->getMemoryVT(); 9916 unsigned Alignment = LN->getAlignment(); 9917 9918 // If this load is properly aligned, then it is legal. 9919 if (Alignment >= MemVT.getStoreSize()) 9920 return Op; 9921 9922 EVT ScalarVT = Op.getValueType().getScalarType(), 9923 ScalarMemVT = MemVT.getScalarType(); 9924 unsigned Stride = ScalarMemVT.getStoreSize(); 9925 9926 SDValue Vals[4], LoadChains[4]; 9927 for (unsigned Idx = 0; Idx < 4; ++Idx) { 9928 SDValue Load; 9929 if (ScalarVT != ScalarMemVT) 9930 Load = DAG.getExtLoad(LN->getExtensionType(), dl, ScalarVT, LoadChain, 9931 BasePtr, 9932 LN->getPointerInfo().getWithOffset(Idx * Stride), 9933 ScalarMemVT, MinAlign(Alignment, Idx * Stride), 9934 LN->getMemOperand()->getFlags(), LN->getAAInfo()); 9935 else 9936 Load = DAG.getLoad(ScalarVT, dl, LoadChain, BasePtr, 9937 LN->getPointerInfo().getWithOffset(Idx * Stride), 9938 MinAlign(Alignment, Idx * Stride), 9939 LN->getMemOperand()->getFlags(), LN->getAAInfo()); 9940 9941 if (Idx == 0 && LN->isIndexed()) { 9942 assert(LN->getAddressingMode() == ISD::PRE_INC && 9943 "Unknown addressing mode on vector load"); 9944 Load = DAG.getIndexedLoad(Load, dl, BasePtr, LN->getOffset(), 9945 LN->getAddressingMode()); 9946 } 9947 9948 Vals[Idx] = Load; 9949 LoadChains[Idx] = Load.getValue(1); 9950 9951 BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, 9952 DAG.getConstant(Stride, dl, 9953 BasePtr.getValueType())); 9954 } 9955 9956 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains); 9957 SDValue Value = DAG.getBuildVector(Op.getValueType(), dl, Vals); 9958 9959 if (LN->isIndexed()) { 9960 SDValue RetOps[] = { Value, Vals[0].getValue(1), TF }; 9961 return DAG.getMergeValues(RetOps, dl); 9962 } 9963 9964 SDValue RetOps[] = { Value, TF }; 9965 return DAG.getMergeValues(RetOps, dl); 9966 } 9967 9968 assert(Op.getValueType() == MVT::v4i1 && "Unknown load to lower"); 9969 assert(LN->isUnindexed() && "Indexed v4i1 loads are not supported"); 9970 9971 // To lower v4i1 from a byte array, we load the byte elements of the 9972 // vector and then reuse the BUILD_VECTOR logic. 9973 9974 SDValue VectElmts[4], VectElmtChains[4]; 9975 for (unsigned i = 0; i < 4; ++i) { 9976 SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType()); 9977 Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx); 9978 9979 VectElmts[i] = DAG.getExtLoad( 9980 ISD::EXTLOAD, dl, MVT::i32, LoadChain, Idx, 9981 LN->getPointerInfo().getWithOffset(i), MVT::i8, 9982 /* Alignment = */ 1, LN->getMemOperand()->getFlags(), LN->getAAInfo()); 9983 VectElmtChains[i] = VectElmts[i].getValue(1); 9984 } 9985 9986 LoadChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, VectElmtChains); 9987 SDValue Value = DAG.getBuildVector(MVT::v4i1, dl, VectElmts); 9988 9989 SDValue RVals[] = { Value, LoadChain }; 9990 return DAG.getMergeValues(RVals, dl); 9991 } 9992 9993 /// Lowering for QPX v4i1 stores 9994 SDValue PPCTargetLowering::LowerVectorStore(SDValue Op, 9995 SelectionDAG &DAG) const { 9996 SDLoc dl(Op); 9997 StoreSDNode *SN = cast<StoreSDNode>(Op.getNode()); 9998 SDValue StoreChain = SN->getChain(); 9999 SDValue BasePtr = SN->getBasePtr(); 10000 SDValue Value = SN->getValue(); 10001 10002 if (Value.getValueType() == MVT::v4f64 || 10003 Value.getValueType() == MVT::v4f32) { 10004 EVT MemVT = SN->getMemoryVT(); 10005 unsigned Alignment = SN->getAlignment(); 10006 10007 // If this store is properly aligned, then it is legal. 10008 if (Alignment >= MemVT.getStoreSize()) 10009 return Op; 10010 10011 EVT ScalarVT = Value.getValueType().getScalarType(), 10012 ScalarMemVT = MemVT.getScalarType(); 10013 unsigned Stride = ScalarMemVT.getStoreSize(); 10014 10015 SDValue Stores[4]; 10016 for (unsigned Idx = 0; Idx < 4; ++Idx) { 10017 SDValue Ex = DAG.getNode( 10018 ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, Value, 10019 DAG.getConstant(Idx, dl, getVectorIdxTy(DAG.getDataLayout()))); 10020 SDValue Store; 10021 if (ScalarVT != ScalarMemVT) 10022 Store = 10023 DAG.getTruncStore(StoreChain, dl, Ex, BasePtr, 10024 SN->getPointerInfo().getWithOffset(Idx * Stride), 10025 ScalarMemVT, MinAlign(Alignment, Idx * Stride), 10026 SN->getMemOperand()->getFlags(), SN->getAAInfo()); 10027 else 10028 Store = DAG.getStore(StoreChain, dl, Ex, BasePtr, 10029 SN->getPointerInfo().getWithOffset(Idx * Stride), 10030 MinAlign(Alignment, Idx * Stride), 10031 SN->getMemOperand()->getFlags(), SN->getAAInfo()); 10032 10033 if (Idx == 0 && SN->isIndexed()) { 10034 assert(SN->getAddressingMode() == ISD::PRE_INC && 10035 "Unknown addressing mode on vector store"); 10036 Store = DAG.getIndexedStore(Store, dl, BasePtr, SN->getOffset(), 10037 SN->getAddressingMode()); 10038 } 10039 10040 BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, 10041 DAG.getConstant(Stride, dl, 10042 BasePtr.getValueType())); 10043 Stores[Idx] = Store; 10044 } 10045 10046 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores); 10047 10048 if (SN->isIndexed()) { 10049 SDValue RetOps[] = { TF, Stores[0].getValue(1) }; 10050 return DAG.getMergeValues(RetOps, dl); 10051 } 10052 10053 return TF; 10054 } 10055 10056 assert(SN->isUnindexed() && "Indexed v4i1 stores are not supported"); 10057 assert(Value.getValueType() == MVT::v4i1 && "Unknown store to lower"); 10058 10059 // The values are now known to be -1 (false) or 1 (true). To convert this 10060 // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5). 10061 // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5 10062 Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value); 10063 10064 // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to 10065 // understand how to form the extending load. 10066 SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64); 10067 10068 Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs); 10069 10070 // Now convert to an integer and store. 10071 Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64, 10072 DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32), 10073 Value); 10074 10075 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 10076 int FrameIdx = MFI.CreateStackObject(16, 16, false); 10077 MachinePointerInfo PtrInfo = 10078 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 10079 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 10080 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 10081 10082 SDValue Ops[] = {StoreChain, 10083 DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32), 10084 Value, FIdx}; 10085 SDVTList VTs = DAG.getVTList(/*chain*/ MVT::Other); 10086 10087 StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, 10088 dl, VTs, Ops, MVT::v4i32, PtrInfo); 10089 10090 // Move data into the byte array. 10091 SDValue Loads[4], LoadChains[4]; 10092 for (unsigned i = 0; i < 4; ++i) { 10093 unsigned Offset = 4*i; 10094 SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType()); 10095 Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx); 10096 10097 Loads[i] = DAG.getLoad(MVT::i32, dl, StoreChain, Idx, 10098 PtrInfo.getWithOffset(Offset)); 10099 LoadChains[i] = Loads[i].getValue(1); 10100 } 10101 10102 StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains); 10103 10104 SDValue Stores[4]; 10105 for (unsigned i = 0; i < 4; ++i) { 10106 SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType()); 10107 Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx); 10108 10109 Stores[i] = DAG.getTruncStore( 10110 StoreChain, dl, Loads[i], Idx, SN->getPointerInfo().getWithOffset(i), 10111 MVT::i8, /* Alignment = */ 1, SN->getMemOperand()->getFlags(), 10112 SN->getAAInfo()); 10113 } 10114 10115 StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores); 10116 10117 return StoreChain; 10118 } 10119 10120 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const { 10121 SDLoc dl(Op); 10122 if (Op.getValueType() == MVT::v4i32) { 10123 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 10124 10125 SDValue Zero = BuildSplatI( 0, 1, MVT::v4i32, DAG, dl); 10126 SDValue Neg16 = BuildSplatI(-16, 4, MVT::v4i32, DAG, dl);//+16 as shift amt. 10127 10128 SDValue RHSSwap = // = vrlw RHS, 16 10129 BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl); 10130 10131 // Shrinkify inputs to v8i16. 10132 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS); 10133 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS); 10134 RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap); 10135 10136 // Low parts multiplied together, generating 32-bit results (we ignore the 10137 // top parts). 10138 SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh, 10139 LHS, RHS, DAG, dl, MVT::v4i32); 10140 10141 SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm, 10142 LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32); 10143 // Shift the high parts up 16 bits. 10144 HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd, 10145 Neg16, DAG, dl); 10146 return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd); 10147 } else if (Op.getValueType() == MVT::v8i16) { 10148 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 10149 10150 SDValue Zero = BuildSplatI(0, 1, MVT::v8i16, DAG, dl); 10151 10152 return BuildIntrinsicOp(Intrinsic::ppc_altivec_vmladduhm, 10153 LHS, RHS, Zero, DAG, dl); 10154 } else if (Op.getValueType() == MVT::v16i8) { 10155 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 10156 bool isLittleEndian = Subtarget.isLittleEndian(); 10157 10158 // Multiply the even 8-bit parts, producing 16-bit sums. 10159 SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub, 10160 LHS, RHS, DAG, dl, MVT::v8i16); 10161 EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts); 10162 10163 // Multiply the odd 8-bit parts, producing 16-bit sums. 10164 SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub, 10165 LHS, RHS, DAG, dl, MVT::v8i16); 10166 OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts); 10167 10168 // Merge the results together. Because vmuleub and vmuloub are 10169 // instructions with a big-endian bias, we must reverse the 10170 // element numbering and reverse the meaning of "odd" and "even" 10171 // when generating little endian code. 10172 int Ops[16]; 10173 for (unsigned i = 0; i != 8; ++i) { 10174 if (isLittleEndian) { 10175 Ops[i*2 ] = 2*i; 10176 Ops[i*2+1] = 2*i+16; 10177 } else { 10178 Ops[i*2 ] = 2*i+1; 10179 Ops[i*2+1] = 2*i+1+16; 10180 } 10181 } 10182 if (isLittleEndian) 10183 return DAG.getVectorShuffle(MVT::v16i8, dl, OddParts, EvenParts, Ops); 10184 else 10185 return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops); 10186 } else { 10187 llvm_unreachable("Unknown mul to lower!"); 10188 } 10189 } 10190 10191 SDValue PPCTargetLowering::LowerABS(SDValue Op, SelectionDAG &DAG) const { 10192 10193 assert(Op.getOpcode() == ISD::ABS && "Should only be called for ISD::ABS"); 10194 10195 EVT VT = Op.getValueType(); 10196 assert(VT.isVector() && 10197 "Only set vector abs as custom, scalar abs shouldn't reach here!"); 10198 assert((VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 || 10199 VT == MVT::v16i8) && 10200 "Unexpected vector element type!"); 10201 assert((VT != MVT::v2i64 || Subtarget.hasP8Altivec()) && 10202 "Current subtarget doesn't support smax v2i64!"); 10203 10204 // For vector abs, it can be lowered to: 10205 // abs x 10206 // ==> 10207 // y = -x 10208 // smax(x, y) 10209 10210 SDLoc dl(Op); 10211 SDValue X = Op.getOperand(0); 10212 SDValue Zero = DAG.getConstant(0, dl, VT); 10213 SDValue Y = DAG.getNode(ISD::SUB, dl, VT, Zero, X); 10214 10215 // SMAX patch https://reviews.llvm.org/D47332 10216 // hasn't landed yet, so use intrinsic first here. 10217 // TODO: Should use SMAX directly once SMAX patch landed 10218 Intrinsic::ID BifID = Intrinsic::ppc_altivec_vmaxsw; 10219 if (VT == MVT::v2i64) 10220 BifID = Intrinsic::ppc_altivec_vmaxsd; 10221 else if (VT == MVT::v8i16) 10222 BifID = Intrinsic::ppc_altivec_vmaxsh; 10223 else if (VT == MVT::v16i8) 10224 BifID = Intrinsic::ppc_altivec_vmaxsb; 10225 10226 return BuildIntrinsicOp(BifID, X, Y, DAG, dl, VT); 10227 } 10228 10229 // Custom lowering for fpext vf32 to v2f64 10230 SDValue PPCTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const { 10231 10232 assert(Op.getOpcode() == ISD::FP_EXTEND && 10233 "Should only be called for ISD::FP_EXTEND"); 10234 10235 // We only want to custom lower an extend from v2f32 to v2f64. 10236 if (Op.getValueType() != MVT::v2f64 || 10237 Op.getOperand(0).getValueType() != MVT::v2f32) 10238 return SDValue(); 10239 10240 SDLoc dl(Op); 10241 SDValue Op0 = Op.getOperand(0); 10242 10243 switch (Op0.getOpcode()) { 10244 default: 10245 return SDValue(); 10246 case ISD::EXTRACT_SUBVECTOR: { 10247 assert(Op0.getNumOperands() == 2 && 10248 isa<ConstantSDNode>(Op0->getOperand(1)) && 10249 "Node should have 2 operands with second one being a constant!"); 10250 10251 if (Op0.getOperand(0).getValueType() != MVT::v4f32) 10252 return SDValue(); 10253 10254 // Custom lower is only done for high or low doubleword. 10255 int Idx = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue(); 10256 if (Idx % 2 != 0) 10257 return SDValue(); 10258 10259 // Since input is v4f32, at this point Idx is either 0 or 2. 10260 // Shift to get the doubleword position we want. 10261 int DWord = Idx >> 1; 10262 10263 // High and low word positions are different on little endian. 10264 if (Subtarget.isLittleEndian()) 10265 DWord ^= 0x1; 10266 10267 return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, 10268 Op0.getOperand(0), DAG.getConstant(DWord, dl, MVT::i32)); 10269 } 10270 case ISD::FADD: 10271 case ISD::FMUL: 10272 case ISD::FSUB: { 10273 SDValue NewLoad[2]; 10274 for (unsigned i = 0, ie = Op0.getNumOperands(); i != ie; ++i) { 10275 // Ensure both input are loads. 10276 SDValue LdOp = Op0.getOperand(i); 10277 if (LdOp.getOpcode() != ISD::LOAD) 10278 return SDValue(); 10279 // Generate new load node. 10280 LoadSDNode *LD = cast<LoadSDNode>(LdOp); 10281 SDValue LoadOps[] = {LD->getChain(), LD->getBasePtr()}; 10282 NewLoad[i] = DAG.getMemIntrinsicNode( 10283 PPCISD::LD_VSX_LH, dl, DAG.getVTList(MVT::v4f32, MVT::Other), LoadOps, 10284 LD->getMemoryVT(), LD->getMemOperand()); 10285 } 10286 SDValue NewOp = 10287 DAG.getNode(Op0.getOpcode(), SDLoc(Op0), MVT::v4f32, NewLoad[0], 10288 NewLoad[1], Op0.getNode()->getFlags()); 10289 return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, NewOp, 10290 DAG.getConstant(0, dl, MVT::i32)); 10291 } 10292 case ISD::LOAD: { 10293 LoadSDNode *LD = cast<LoadSDNode>(Op0); 10294 SDValue LoadOps[] = {LD->getChain(), LD->getBasePtr()}; 10295 SDValue NewLd = DAG.getMemIntrinsicNode( 10296 PPCISD::LD_VSX_LH, dl, DAG.getVTList(MVT::v4f32, MVT::Other), LoadOps, 10297 LD->getMemoryVT(), LD->getMemOperand()); 10298 return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, NewLd, 10299 DAG.getConstant(0, dl, MVT::i32)); 10300 } 10301 } 10302 llvm_unreachable("ERROR:Should return for all cases within swtich."); 10303 } 10304 10305 /// LowerOperation - Provide custom lowering hooks for some operations. 10306 /// 10307 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 10308 switch (Op.getOpcode()) { 10309 default: llvm_unreachable("Wasn't expecting to be able to lower this!"); 10310 case ISD::ConstantPool: return LowerConstantPool(Op, DAG); 10311 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG); 10312 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG); 10313 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG); 10314 case ISD::JumpTable: return LowerJumpTable(Op, DAG); 10315 case ISD::SETCC: return LowerSETCC(Op, DAG); 10316 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG); 10317 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG); 10318 10319 // Variable argument lowering. 10320 case ISD::VASTART: return LowerVASTART(Op, DAG); 10321 case ISD::VAARG: return LowerVAARG(Op, DAG); 10322 case ISD::VACOPY: return LowerVACOPY(Op, DAG); 10323 10324 case ISD::STACKRESTORE: return LowerSTACKRESTORE(Op, DAG); 10325 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG); 10326 case ISD::GET_DYNAMIC_AREA_OFFSET: 10327 return LowerGET_DYNAMIC_AREA_OFFSET(Op, DAG); 10328 10329 // Exception handling lowering. 10330 case ISD::EH_DWARF_CFA: return LowerEH_DWARF_CFA(Op, DAG); 10331 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG); 10332 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG); 10333 10334 case ISD::LOAD: return LowerLOAD(Op, DAG); 10335 case ISD::STORE: return LowerSTORE(Op, DAG); 10336 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG); 10337 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG); 10338 case ISD::FP_TO_UINT: 10339 case ISD::FP_TO_SINT: return LowerFP_TO_INT(Op, DAG, SDLoc(Op)); 10340 case ISD::UINT_TO_FP: 10341 case ISD::SINT_TO_FP: return LowerINT_TO_FP(Op, DAG); 10342 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG); 10343 10344 // Lower 64-bit shifts. 10345 case ISD::SHL_PARTS: return LowerSHL_PARTS(Op, DAG); 10346 case ISD::SRL_PARTS: return LowerSRL_PARTS(Op, DAG); 10347 case ISD::SRA_PARTS: return LowerSRA_PARTS(Op, DAG); 10348 10349 // Vector-related lowering. 10350 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG); 10351 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG); 10352 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG); 10353 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG); 10354 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG); 10355 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG); 10356 case ISD::MUL: return LowerMUL(Op, DAG); 10357 case ISD::ABS: return LowerABS(Op, DAG); 10358 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG); 10359 10360 // For counter-based loop handling. 10361 case ISD::INTRINSIC_W_CHAIN: return SDValue(); 10362 10363 case ISD::BITCAST: return LowerBITCAST(Op, DAG); 10364 10365 // Frame & Return address. 10366 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG); 10367 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG); 10368 10369 case ISD::INTRINSIC_VOID: 10370 return LowerINTRINSIC_VOID(Op, DAG); 10371 case ISD::SREM: 10372 case ISD::UREM: 10373 return LowerREM(Op, DAG); 10374 case ISD::BSWAP: 10375 return LowerBSWAP(Op, DAG); 10376 case ISD::ATOMIC_CMP_SWAP: 10377 return LowerATOMIC_CMP_SWAP(Op, DAG); 10378 } 10379 } 10380 10381 void PPCTargetLowering::ReplaceNodeResults(SDNode *N, 10382 SmallVectorImpl<SDValue>&Results, 10383 SelectionDAG &DAG) const { 10384 SDLoc dl(N); 10385 switch (N->getOpcode()) { 10386 default: 10387 llvm_unreachable("Do not know how to custom type legalize this operation!"); 10388 case ISD::READCYCLECOUNTER: { 10389 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other); 10390 SDValue RTB = DAG.getNode(PPCISD::READ_TIME_BASE, dl, VTs, N->getOperand(0)); 10391 10392 Results.push_back(RTB); 10393 Results.push_back(RTB.getValue(1)); 10394 Results.push_back(RTB.getValue(2)); 10395 break; 10396 } 10397 case ISD::INTRINSIC_W_CHAIN: { 10398 if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 10399 Intrinsic::loop_decrement) 10400 break; 10401 10402 assert(N->getValueType(0) == MVT::i1 && 10403 "Unexpected result type for CTR decrement intrinsic"); 10404 EVT SVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 10405 N->getValueType(0)); 10406 SDVTList VTs = DAG.getVTList(SVT, MVT::Other); 10407 SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0), 10408 N->getOperand(1)); 10409 10410 Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewInt)); 10411 Results.push_back(NewInt.getValue(1)); 10412 break; 10413 } 10414 case ISD::VAARG: { 10415 if (!Subtarget.isSVR4ABI() || Subtarget.isPPC64()) 10416 return; 10417 10418 EVT VT = N->getValueType(0); 10419 10420 if (VT == MVT::i64) { 10421 SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG); 10422 10423 Results.push_back(NewNode); 10424 Results.push_back(NewNode.getValue(1)); 10425 } 10426 return; 10427 } 10428 case ISD::FP_TO_SINT: 10429 case ISD::FP_TO_UINT: 10430 // LowerFP_TO_INT() can only handle f32 and f64. 10431 if (N->getOperand(0).getValueType() == MVT::ppcf128) 10432 return; 10433 Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl)); 10434 return; 10435 case ISD::TRUNCATE: { 10436 EVT TrgVT = N->getValueType(0); 10437 EVT OpVT = N->getOperand(0).getValueType(); 10438 if (TrgVT.isVector() && 10439 isOperationCustom(N->getOpcode(), TrgVT) && 10440 OpVT.getSizeInBits() <= 128 && 10441 isPowerOf2_32(OpVT.getVectorElementType().getSizeInBits())) 10442 Results.push_back(LowerTRUNCATEVector(SDValue(N, 0), DAG)); 10443 return; 10444 } 10445 case ISD::BITCAST: 10446 // Don't handle bitcast here. 10447 return; 10448 } 10449 } 10450 10451 //===----------------------------------------------------------------------===// 10452 // Other Lowering Code 10453 //===----------------------------------------------------------------------===// 10454 10455 static Instruction* callIntrinsic(IRBuilder<> &Builder, Intrinsic::ID Id) { 10456 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 10457 Function *Func = Intrinsic::getDeclaration(M, Id); 10458 return Builder.CreateCall(Func, {}); 10459 } 10460 10461 // The mappings for emitLeading/TrailingFence is taken from 10462 // http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html 10463 Instruction *PPCTargetLowering::emitLeadingFence(IRBuilder<> &Builder, 10464 Instruction *Inst, 10465 AtomicOrdering Ord) const { 10466 if (Ord == AtomicOrdering::SequentiallyConsistent) 10467 return callIntrinsic(Builder, Intrinsic::ppc_sync); 10468 if (isReleaseOrStronger(Ord)) 10469 return callIntrinsic(Builder, Intrinsic::ppc_lwsync); 10470 return nullptr; 10471 } 10472 10473 Instruction *PPCTargetLowering::emitTrailingFence(IRBuilder<> &Builder, 10474 Instruction *Inst, 10475 AtomicOrdering Ord) const { 10476 if (Inst->hasAtomicLoad() && isAcquireOrStronger(Ord)) { 10477 // See http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html and 10478 // http://www.rdrop.com/users/paulmck/scalability/paper/N2745r.2011.03.04a.html 10479 // and http://www.cl.cam.ac.uk/~pes20/cppppc/ for justification. 10480 if (isa<LoadInst>(Inst) && Subtarget.isPPC64()) 10481 return Builder.CreateCall( 10482 Intrinsic::getDeclaration( 10483 Builder.GetInsertBlock()->getParent()->getParent(), 10484 Intrinsic::ppc_cfence, {Inst->getType()}), 10485 {Inst}); 10486 // FIXME: Can use isync for rmw operation. 10487 return callIntrinsic(Builder, Intrinsic::ppc_lwsync); 10488 } 10489 return nullptr; 10490 } 10491 10492 MachineBasicBlock * 10493 PPCTargetLowering::EmitAtomicBinary(MachineInstr &MI, MachineBasicBlock *BB, 10494 unsigned AtomicSize, 10495 unsigned BinOpcode, 10496 unsigned CmpOpcode, 10497 unsigned CmpPred) const { 10498 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0. 10499 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 10500 10501 auto LoadMnemonic = PPC::LDARX; 10502 auto StoreMnemonic = PPC::STDCX; 10503 switch (AtomicSize) { 10504 default: 10505 llvm_unreachable("Unexpected size of atomic entity"); 10506 case 1: 10507 LoadMnemonic = PPC::LBARX; 10508 StoreMnemonic = PPC::STBCX; 10509 assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4"); 10510 break; 10511 case 2: 10512 LoadMnemonic = PPC::LHARX; 10513 StoreMnemonic = PPC::STHCX; 10514 assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4"); 10515 break; 10516 case 4: 10517 LoadMnemonic = PPC::LWARX; 10518 StoreMnemonic = PPC::STWCX; 10519 break; 10520 case 8: 10521 LoadMnemonic = PPC::LDARX; 10522 StoreMnemonic = PPC::STDCX; 10523 break; 10524 } 10525 10526 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 10527 MachineFunction *F = BB->getParent(); 10528 MachineFunction::iterator It = ++BB->getIterator(); 10529 10530 Register dest = MI.getOperand(0).getReg(); 10531 Register ptrA = MI.getOperand(1).getReg(); 10532 Register ptrB = MI.getOperand(2).getReg(); 10533 Register incr = MI.getOperand(3).getReg(); 10534 DebugLoc dl = MI.getDebugLoc(); 10535 10536 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB); 10537 MachineBasicBlock *loop2MBB = 10538 CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr; 10539 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 10540 F->insert(It, loopMBB); 10541 if (CmpOpcode) 10542 F->insert(It, loop2MBB); 10543 F->insert(It, exitMBB); 10544 exitMBB->splice(exitMBB->begin(), BB, 10545 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 10546 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 10547 10548 MachineRegisterInfo &RegInfo = F->getRegInfo(); 10549 Register TmpReg = (!BinOpcode) ? incr : 10550 RegInfo.createVirtualRegister( AtomicSize == 8 ? &PPC::G8RCRegClass 10551 : &PPC::GPRCRegClass); 10552 10553 // thisMBB: 10554 // ... 10555 // fallthrough --> loopMBB 10556 BB->addSuccessor(loopMBB); 10557 10558 // loopMBB: 10559 // l[wd]arx dest, ptr 10560 // add r0, dest, incr 10561 // st[wd]cx. r0, ptr 10562 // bne- loopMBB 10563 // fallthrough --> exitMBB 10564 10565 // For max/min... 10566 // loopMBB: 10567 // l[wd]arx dest, ptr 10568 // cmpl?[wd] incr, dest 10569 // bgt exitMBB 10570 // loop2MBB: 10571 // st[wd]cx. dest, ptr 10572 // bne- loopMBB 10573 // fallthrough --> exitMBB 10574 10575 BB = loopMBB; 10576 BuildMI(BB, dl, TII->get(LoadMnemonic), dest) 10577 .addReg(ptrA).addReg(ptrB); 10578 if (BinOpcode) 10579 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest); 10580 if (CmpOpcode) { 10581 // Signed comparisons of byte or halfword values must be sign-extended. 10582 if (CmpOpcode == PPC::CMPW && AtomicSize < 4) { 10583 Register ExtReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass); 10584 BuildMI(BB, dl, TII->get(AtomicSize == 1 ? PPC::EXTSB : PPC::EXTSH), 10585 ExtReg).addReg(dest); 10586 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0) 10587 .addReg(incr).addReg(ExtReg); 10588 } else 10589 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0) 10590 .addReg(incr).addReg(dest); 10591 10592 BuildMI(BB, dl, TII->get(PPC::BCC)) 10593 .addImm(CmpPred).addReg(PPC::CR0).addMBB(exitMBB); 10594 BB->addSuccessor(loop2MBB); 10595 BB->addSuccessor(exitMBB); 10596 BB = loop2MBB; 10597 } 10598 BuildMI(BB, dl, TII->get(StoreMnemonic)) 10599 .addReg(TmpReg).addReg(ptrA).addReg(ptrB); 10600 BuildMI(BB, dl, TII->get(PPC::BCC)) 10601 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB); 10602 BB->addSuccessor(loopMBB); 10603 BB->addSuccessor(exitMBB); 10604 10605 // exitMBB: 10606 // ... 10607 BB = exitMBB; 10608 return BB; 10609 } 10610 10611 MachineBasicBlock *PPCTargetLowering::EmitPartwordAtomicBinary( 10612 MachineInstr &MI, MachineBasicBlock *BB, 10613 bool is8bit, // operation 10614 unsigned BinOpcode, unsigned CmpOpcode, unsigned CmpPred) const { 10615 // If we support part-word atomic mnemonics, just use them 10616 if (Subtarget.hasPartwordAtomics()) 10617 return EmitAtomicBinary(MI, BB, is8bit ? 1 : 2, BinOpcode, CmpOpcode, 10618 CmpPred); 10619 10620 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0. 10621 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 10622 // In 64 bit mode we have to use 64 bits for addresses, even though the 10623 // lwarx/stwcx are 32 bits. With the 32-bit atomics we can use address 10624 // registers without caring whether they're 32 or 64, but here we're 10625 // doing actual arithmetic on the addresses. 10626 bool is64bit = Subtarget.isPPC64(); 10627 bool isLittleEndian = Subtarget.isLittleEndian(); 10628 unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO; 10629 10630 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 10631 MachineFunction *F = BB->getParent(); 10632 MachineFunction::iterator It = ++BB->getIterator(); 10633 10634 Register dest = MI.getOperand(0).getReg(); 10635 Register ptrA = MI.getOperand(1).getReg(); 10636 Register ptrB = MI.getOperand(2).getReg(); 10637 Register incr = MI.getOperand(3).getReg(); 10638 DebugLoc dl = MI.getDebugLoc(); 10639 10640 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB); 10641 MachineBasicBlock *loop2MBB = 10642 CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr; 10643 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 10644 F->insert(It, loopMBB); 10645 if (CmpOpcode) 10646 F->insert(It, loop2MBB); 10647 F->insert(It, exitMBB); 10648 exitMBB->splice(exitMBB->begin(), BB, 10649 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 10650 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 10651 10652 MachineRegisterInfo &RegInfo = F->getRegInfo(); 10653 const TargetRegisterClass *RC = 10654 is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 10655 const TargetRegisterClass *GPRC = &PPC::GPRCRegClass; 10656 10657 Register PtrReg = RegInfo.createVirtualRegister(RC); 10658 Register Shift1Reg = RegInfo.createVirtualRegister(GPRC); 10659 Register ShiftReg = 10660 isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC); 10661 Register Incr2Reg = RegInfo.createVirtualRegister(GPRC); 10662 Register MaskReg = RegInfo.createVirtualRegister(GPRC); 10663 Register Mask2Reg = RegInfo.createVirtualRegister(GPRC); 10664 Register Mask3Reg = RegInfo.createVirtualRegister(GPRC); 10665 Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC); 10666 Register Tmp3Reg = RegInfo.createVirtualRegister(GPRC); 10667 Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC); 10668 Register TmpDestReg = RegInfo.createVirtualRegister(GPRC); 10669 Register Ptr1Reg; 10670 Register TmpReg = 10671 (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(GPRC); 10672 10673 // thisMBB: 10674 // ... 10675 // fallthrough --> loopMBB 10676 BB->addSuccessor(loopMBB); 10677 10678 // The 4-byte load must be aligned, while a char or short may be 10679 // anywhere in the word. Hence all this nasty bookkeeping code. 10680 // add ptr1, ptrA, ptrB [copy if ptrA==0] 10681 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27] 10682 // xori shift, shift1, 24 [16] 10683 // rlwinm ptr, ptr1, 0, 0, 29 10684 // slw incr2, incr, shift 10685 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535] 10686 // slw mask, mask2, shift 10687 // loopMBB: 10688 // lwarx tmpDest, ptr 10689 // add tmp, tmpDest, incr2 10690 // andc tmp2, tmpDest, mask 10691 // and tmp3, tmp, mask 10692 // or tmp4, tmp3, tmp2 10693 // stwcx. tmp4, ptr 10694 // bne- loopMBB 10695 // fallthrough --> exitMBB 10696 // srw dest, tmpDest, shift 10697 if (ptrA != ZeroReg) { 10698 Ptr1Reg = RegInfo.createVirtualRegister(RC); 10699 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg) 10700 .addReg(ptrA) 10701 .addReg(ptrB); 10702 } else { 10703 Ptr1Reg = ptrB; 10704 } 10705 // We need use 32-bit subregister to avoid mismatch register class in 64-bit 10706 // mode. 10707 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg) 10708 .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0) 10709 .addImm(3) 10710 .addImm(27) 10711 .addImm(is8bit ? 28 : 27); 10712 if (!isLittleEndian) 10713 BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg) 10714 .addReg(Shift1Reg) 10715 .addImm(is8bit ? 24 : 16); 10716 if (is64bit) 10717 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg) 10718 .addReg(Ptr1Reg) 10719 .addImm(0) 10720 .addImm(61); 10721 else 10722 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg) 10723 .addReg(Ptr1Reg) 10724 .addImm(0) 10725 .addImm(0) 10726 .addImm(29); 10727 BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg).addReg(incr).addReg(ShiftReg); 10728 if (is8bit) 10729 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255); 10730 else { 10731 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0); 10732 BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg) 10733 .addReg(Mask3Reg) 10734 .addImm(65535); 10735 } 10736 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg) 10737 .addReg(Mask2Reg) 10738 .addReg(ShiftReg); 10739 10740 BB = loopMBB; 10741 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg) 10742 .addReg(ZeroReg) 10743 .addReg(PtrReg); 10744 if (BinOpcode) 10745 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg) 10746 .addReg(Incr2Reg) 10747 .addReg(TmpDestReg); 10748 BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg) 10749 .addReg(TmpDestReg) 10750 .addReg(MaskReg); 10751 BuildMI(BB, dl, TII->get(PPC::AND), Tmp3Reg).addReg(TmpReg).addReg(MaskReg); 10752 if (CmpOpcode) { 10753 // For unsigned comparisons, we can directly compare the shifted values. 10754 // For signed comparisons we shift and sign extend. 10755 Register SReg = RegInfo.createVirtualRegister(GPRC); 10756 BuildMI(BB, dl, TII->get(PPC::AND), SReg) 10757 .addReg(TmpDestReg) 10758 .addReg(MaskReg); 10759 unsigned ValueReg = SReg; 10760 unsigned CmpReg = Incr2Reg; 10761 if (CmpOpcode == PPC::CMPW) { 10762 ValueReg = RegInfo.createVirtualRegister(GPRC); 10763 BuildMI(BB, dl, TII->get(PPC::SRW), ValueReg) 10764 .addReg(SReg) 10765 .addReg(ShiftReg); 10766 Register ValueSReg = RegInfo.createVirtualRegister(GPRC); 10767 BuildMI(BB, dl, TII->get(is8bit ? PPC::EXTSB : PPC::EXTSH), ValueSReg) 10768 .addReg(ValueReg); 10769 ValueReg = ValueSReg; 10770 CmpReg = incr; 10771 } 10772 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0) 10773 .addReg(CmpReg) 10774 .addReg(ValueReg); 10775 BuildMI(BB, dl, TII->get(PPC::BCC)) 10776 .addImm(CmpPred) 10777 .addReg(PPC::CR0) 10778 .addMBB(exitMBB); 10779 BB->addSuccessor(loop2MBB); 10780 BB->addSuccessor(exitMBB); 10781 BB = loop2MBB; 10782 } 10783 BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg).addReg(Tmp3Reg).addReg(Tmp2Reg); 10784 BuildMI(BB, dl, TII->get(PPC::STWCX)) 10785 .addReg(Tmp4Reg) 10786 .addReg(ZeroReg) 10787 .addReg(PtrReg); 10788 BuildMI(BB, dl, TII->get(PPC::BCC)) 10789 .addImm(PPC::PRED_NE) 10790 .addReg(PPC::CR0) 10791 .addMBB(loopMBB); 10792 BB->addSuccessor(loopMBB); 10793 BB->addSuccessor(exitMBB); 10794 10795 // exitMBB: 10796 // ... 10797 BB = exitMBB; 10798 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest) 10799 .addReg(TmpDestReg) 10800 .addReg(ShiftReg); 10801 return BB; 10802 } 10803 10804 llvm::MachineBasicBlock * 10805 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr &MI, 10806 MachineBasicBlock *MBB) const { 10807 DebugLoc DL = MI.getDebugLoc(); 10808 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 10809 const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo(); 10810 10811 MachineFunction *MF = MBB->getParent(); 10812 MachineRegisterInfo &MRI = MF->getRegInfo(); 10813 10814 const BasicBlock *BB = MBB->getBasicBlock(); 10815 MachineFunction::iterator I = ++MBB->getIterator(); 10816 10817 Register DstReg = MI.getOperand(0).getReg(); 10818 const TargetRegisterClass *RC = MRI.getRegClass(DstReg); 10819 assert(TRI->isTypeLegalForClass(*RC, MVT::i32) && "Invalid destination!"); 10820 Register mainDstReg = MRI.createVirtualRegister(RC); 10821 Register restoreDstReg = MRI.createVirtualRegister(RC); 10822 10823 MVT PVT = getPointerTy(MF->getDataLayout()); 10824 assert((PVT == MVT::i64 || PVT == MVT::i32) && 10825 "Invalid Pointer Size!"); 10826 // For v = setjmp(buf), we generate 10827 // 10828 // thisMBB: 10829 // SjLjSetup mainMBB 10830 // bl mainMBB 10831 // v_restore = 1 10832 // b sinkMBB 10833 // 10834 // mainMBB: 10835 // buf[LabelOffset] = LR 10836 // v_main = 0 10837 // 10838 // sinkMBB: 10839 // v = phi(main, restore) 10840 // 10841 10842 MachineBasicBlock *thisMBB = MBB; 10843 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB); 10844 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB); 10845 MF->insert(I, mainMBB); 10846 MF->insert(I, sinkMBB); 10847 10848 MachineInstrBuilder MIB; 10849 10850 // Transfer the remainder of BB and its successor edges to sinkMBB. 10851 sinkMBB->splice(sinkMBB->begin(), MBB, 10852 std::next(MachineBasicBlock::iterator(MI)), MBB->end()); 10853 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB); 10854 10855 // Note that the structure of the jmp_buf used here is not compatible 10856 // with that used by libc, and is not designed to be. Specifically, it 10857 // stores only those 'reserved' registers that LLVM does not otherwise 10858 // understand how to spill. Also, by convention, by the time this 10859 // intrinsic is called, Clang has already stored the frame address in the 10860 // first slot of the buffer and stack address in the third. Following the 10861 // X86 target code, we'll store the jump address in the second slot. We also 10862 // need to save the TOC pointer (R2) to handle jumps between shared 10863 // libraries, and that will be stored in the fourth slot. The thread 10864 // identifier (R13) is not affected. 10865 10866 // thisMBB: 10867 const int64_t LabelOffset = 1 * PVT.getStoreSize(); 10868 const int64_t TOCOffset = 3 * PVT.getStoreSize(); 10869 const int64_t BPOffset = 4 * PVT.getStoreSize(); 10870 10871 // Prepare IP either in reg. 10872 const TargetRegisterClass *PtrRC = getRegClassFor(PVT); 10873 Register LabelReg = MRI.createVirtualRegister(PtrRC); 10874 Register BufReg = MI.getOperand(1).getReg(); 10875 10876 if (Subtarget.is64BitELFABI()) { 10877 setUsesTOCBasePtr(*MBB->getParent()); 10878 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD)) 10879 .addReg(PPC::X2) 10880 .addImm(TOCOffset) 10881 .addReg(BufReg) 10882 .cloneMemRefs(MI); 10883 } 10884 10885 // Naked functions never have a base pointer, and so we use r1. For all 10886 // other functions, this decision must be delayed until during PEI. 10887 unsigned BaseReg; 10888 if (MF->getFunction().hasFnAttribute(Attribute::Naked)) 10889 BaseReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1; 10890 else 10891 BaseReg = Subtarget.isPPC64() ? PPC::BP8 : PPC::BP; 10892 10893 MIB = BuildMI(*thisMBB, MI, DL, 10894 TII->get(Subtarget.isPPC64() ? PPC::STD : PPC::STW)) 10895 .addReg(BaseReg) 10896 .addImm(BPOffset) 10897 .addReg(BufReg) 10898 .cloneMemRefs(MI); 10899 10900 // Setup 10901 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB); 10902 MIB.addRegMask(TRI->getNoPreservedMask()); 10903 10904 BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1); 10905 10906 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup)) 10907 .addMBB(mainMBB); 10908 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB); 10909 10910 thisMBB->addSuccessor(mainMBB, BranchProbability::getZero()); 10911 thisMBB->addSuccessor(sinkMBB, BranchProbability::getOne()); 10912 10913 // mainMBB: 10914 // mainDstReg = 0 10915 MIB = 10916 BuildMI(mainMBB, DL, 10917 TII->get(Subtarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg); 10918 10919 // Store IP 10920 if (Subtarget.isPPC64()) { 10921 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD)) 10922 .addReg(LabelReg) 10923 .addImm(LabelOffset) 10924 .addReg(BufReg); 10925 } else { 10926 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW)) 10927 .addReg(LabelReg) 10928 .addImm(LabelOffset) 10929 .addReg(BufReg); 10930 } 10931 MIB.cloneMemRefs(MI); 10932 10933 BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0); 10934 mainMBB->addSuccessor(sinkMBB); 10935 10936 // sinkMBB: 10937 BuildMI(*sinkMBB, sinkMBB->begin(), DL, 10938 TII->get(PPC::PHI), DstReg) 10939 .addReg(mainDstReg).addMBB(mainMBB) 10940 .addReg(restoreDstReg).addMBB(thisMBB); 10941 10942 MI.eraseFromParent(); 10943 return sinkMBB; 10944 } 10945 10946 MachineBasicBlock * 10947 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr &MI, 10948 MachineBasicBlock *MBB) const { 10949 DebugLoc DL = MI.getDebugLoc(); 10950 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 10951 10952 MachineFunction *MF = MBB->getParent(); 10953 MachineRegisterInfo &MRI = MF->getRegInfo(); 10954 10955 MVT PVT = getPointerTy(MF->getDataLayout()); 10956 assert((PVT == MVT::i64 || PVT == MVT::i32) && 10957 "Invalid Pointer Size!"); 10958 10959 const TargetRegisterClass *RC = 10960 (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 10961 Register Tmp = MRI.createVirtualRegister(RC); 10962 // Since FP is only updated here but NOT referenced, it's treated as GPR. 10963 unsigned FP = (PVT == MVT::i64) ? PPC::X31 : PPC::R31; 10964 unsigned SP = (PVT == MVT::i64) ? PPC::X1 : PPC::R1; 10965 unsigned BP = 10966 (PVT == MVT::i64) 10967 ? PPC::X30 10968 : (Subtarget.isSVR4ABI() && isPositionIndependent() ? PPC::R29 10969 : PPC::R30); 10970 10971 MachineInstrBuilder MIB; 10972 10973 const int64_t LabelOffset = 1 * PVT.getStoreSize(); 10974 const int64_t SPOffset = 2 * PVT.getStoreSize(); 10975 const int64_t TOCOffset = 3 * PVT.getStoreSize(); 10976 const int64_t BPOffset = 4 * PVT.getStoreSize(); 10977 10978 Register BufReg = MI.getOperand(0).getReg(); 10979 10980 // Reload FP (the jumped-to function may not have had a 10981 // frame pointer, and if so, then its r31 will be restored 10982 // as necessary). 10983 if (PVT == MVT::i64) { 10984 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP) 10985 .addImm(0) 10986 .addReg(BufReg); 10987 } else { 10988 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP) 10989 .addImm(0) 10990 .addReg(BufReg); 10991 } 10992 MIB.cloneMemRefs(MI); 10993 10994 // Reload IP 10995 if (PVT == MVT::i64) { 10996 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp) 10997 .addImm(LabelOffset) 10998 .addReg(BufReg); 10999 } else { 11000 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp) 11001 .addImm(LabelOffset) 11002 .addReg(BufReg); 11003 } 11004 MIB.cloneMemRefs(MI); 11005 11006 // Reload SP 11007 if (PVT == MVT::i64) { 11008 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP) 11009 .addImm(SPOffset) 11010 .addReg(BufReg); 11011 } else { 11012 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP) 11013 .addImm(SPOffset) 11014 .addReg(BufReg); 11015 } 11016 MIB.cloneMemRefs(MI); 11017 11018 // Reload BP 11019 if (PVT == MVT::i64) { 11020 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP) 11021 .addImm(BPOffset) 11022 .addReg(BufReg); 11023 } else { 11024 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP) 11025 .addImm(BPOffset) 11026 .addReg(BufReg); 11027 } 11028 MIB.cloneMemRefs(MI); 11029 11030 // Reload TOC 11031 if (PVT == MVT::i64 && Subtarget.isSVR4ABI()) { 11032 setUsesTOCBasePtr(*MBB->getParent()); 11033 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2) 11034 .addImm(TOCOffset) 11035 .addReg(BufReg) 11036 .cloneMemRefs(MI); 11037 } 11038 11039 // Jump 11040 BuildMI(*MBB, MI, DL, 11041 TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp); 11042 BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR)); 11043 11044 MI.eraseFromParent(); 11045 return MBB; 11046 } 11047 11048 MachineBasicBlock * 11049 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI, 11050 MachineBasicBlock *BB) const { 11051 if (MI.getOpcode() == TargetOpcode::STACKMAP || 11052 MI.getOpcode() == TargetOpcode::PATCHPOINT) { 11053 if (Subtarget.is64BitELFABI() && 11054 MI.getOpcode() == TargetOpcode::PATCHPOINT) { 11055 // Call lowering should have added an r2 operand to indicate a dependence 11056 // on the TOC base pointer value. It can't however, because there is no 11057 // way to mark the dependence as implicit there, and so the stackmap code 11058 // will confuse it with a regular operand. Instead, add the dependence 11059 // here. 11060 MI.addOperand(MachineOperand::CreateReg(PPC::X2, false, true)); 11061 } 11062 11063 return emitPatchPoint(MI, BB); 11064 } 11065 11066 if (MI.getOpcode() == PPC::EH_SjLj_SetJmp32 || 11067 MI.getOpcode() == PPC::EH_SjLj_SetJmp64) { 11068 return emitEHSjLjSetJmp(MI, BB); 11069 } else if (MI.getOpcode() == PPC::EH_SjLj_LongJmp32 || 11070 MI.getOpcode() == PPC::EH_SjLj_LongJmp64) { 11071 return emitEHSjLjLongJmp(MI, BB); 11072 } 11073 11074 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 11075 11076 // To "insert" these instructions we actually have to insert their 11077 // control-flow patterns. 11078 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 11079 MachineFunction::iterator It = ++BB->getIterator(); 11080 11081 MachineFunction *F = BB->getParent(); 11082 11083 if (MI.getOpcode() == PPC::SELECT_CC_I4 || 11084 MI.getOpcode() == PPC::SELECT_CC_I8 || MI.getOpcode() == PPC::SELECT_I4 || 11085 MI.getOpcode() == PPC::SELECT_I8) { 11086 SmallVector<MachineOperand, 2> Cond; 11087 if (MI.getOpcode() == PPC::SELECT_CC_I4 || 11088 MI.getOpcode() == PPC::SELECT_CC_I8) 11089 Cond.push_back(MI.getOperand(4)); 11090 else 11091 Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET)); 11092 Cond.push_back(MI.getOperand(1)); 11093 11094 DebugLoc dl = MI.getDebugLoc(); 11095 TII->insertSelect(*BB, MI, dl, MI.getOperand(0).getReg(), Cond, 11096 MI.getOperand(2).getReg(), MI.getOperand(3).getReg()); 11097 } else if (MI.getOpcode() == PPC::SELECT_CC_F4 || 11098 MI.getOpcode() == PPC::SELECT_CC_F8 || 11099 MI.getOpcode() == PPC::SELECT_CC_F16 || 11100 MI.getOpcode() == PPC::SELECT_CC_QFRC || 11101 MI.getOpcode() == PPC::SELECT_CC_QSRC || 11102 MI.getOpcode() == PPC::SELECT_CC_QBRC || 11103 MI.getOpcode() == PPC::SELECT_CC_VRRC || 11104 MI.getOpcode() == PPC::SELECT_CC_VSFRC || 11105 MI.getOpcode() == PPC::SELECT_CC_VSSRC || 11106 MI.getOpcode() == PPC::SELECT_CC_VSRC || 11107 MI.getOpcode() == PPC::SELECT_CC_SPE4 || 11108 MI.getOpcode() == PPC::SELECT_CC_SPE || 11109 MI.getOpcode() == PPC::SELECT_F4 || 11110 MI.getOpcode() == PPC::SELECT_F8 || 11111 MI.getOpcode() == PPC::SELECT_F16 || 11112 MI.getOpcode() == PPC::SELECT_QFRC || 11113 MI.getOpcode() == PPC::SELECT_QSRC || 11114 MI.getOpcode() == PPC::SELECT_QBRC || 11115 MI.getOpcode() == PPC::SELECT_SPE || 11116 MI.getOpcode() == PPC::SELECT_SPE4 || 11117 MI.getOpcode() == PPC::SELECT_VRRC || 11118 MI.getOpcode() == PPC::SELECT_VSFRC || 11119 MI.getOpcode() == PPC::SELECT_VSSRC || 11120 MI.getOpcode() == PPC::SELECT_VSRC) { 11121 // The incoming instruction knows the destination vreg to set, the 11122 // condition code register to branch on, the true/false values to 11123 // select between, and a branch opcode to use. 11124 11125 // thisMBB: 11126 // ... 11127 // TrueVal = ... 11128 // cmpTY ccX, r1, r2 11129 // bCC copy1MBB 11130 // fallthrough --> copy0MBB 11131 MachineBasicBlock *thisMBB = BB; 11132 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB); 11133 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 11134 DebugLoc dl = MI.getDebugLoc(); 11135 F->insert(It, copy0MBB); 11136 F->insert(It, sinkMBB); 11137 11138 // Transfer the remainder of BB and its successor edges to sinkMBB. 11139 sinkMBB->splice(sinkMBB->begin(), BB, 11140 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 11141 sinkMBB->transferSuccessorsAndUpdatePHIs(BB); 11142 11143 // Next, add the true and fallthrough blocks as its successors. 11144 BB->addSuccessor(copy0MBB); 11145 BB->addSuccessor(sinkMBB); 11146 11147 if (MI.getOpcode() == PPC::SELECT_I4 || MI.getOpcode() == PPC::SELECT_I8 || 11148 MI.getOpcode() == PPC::SELECT_F4 || MI.getOpcode() == PPC::SELECT_F8 || 11149 MI.getOpcode() == PPC::SELECT_F16 || 11150 MI.getOpcode() == PPC::SELECT_SPE4 || 11151 MI.getOpcode() == PPC::SELECT_SPE || 11152 MI.getOpcode() == PPC::SELECT_QFRC || 11153 MI.getOpcode() == PPC::SELECT_QSRC || 11154 MI.getOpcode() == PPC::SELECT_QBRC || 11155 MI.getOpcode() == PPC::SELECT_VRRC || 11156 MI.getOpcode() == PPC::SELECT_VSFRC || 11157 MI.getOpcode() == PPC::SELECT_VSSRC || 11158 MI.getOpcode() == PPC::SELECT_VSRC) { 11159 BuildMI(BB, dl, TII->get(PPC::BC)) 11160 .addReg(MI.getOperand(1).getReg()) 11161 .addMBB(sinkMBB); 11162 } else { 11163 unsigned SelectPred = MI.getOperand(4).getImm(); 11164 BuildMI(BB, dl, TII->get(PPC::BCC)) 11165 .addImm(SelectPred) 11166 .addReg(MI.getOperand(1).getReg()) 11167 .addMBB(sinkMBB); 11168 } 11169 11170 // copy0MBB: 11171 // %FalseValue = ... 11172 // # fallthrough to sinkMBB 11173 BB = copy0MBB; 11174 11175 // Update machine-CFG edges 11176 BB->addSuccessor(sinkMBB); 11177 11178 // sinkMBB: 11179 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ] 11180 // ... 11181 BB = sinkMBB; 11182 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::PHI), MI.getOperand(0).getReg()) 11183 .addReg(MI.getOperand(3).getReg()) 11184 .addMBB(copy0MBB) 11185 .addReg(MI.getOperand(2).getReg()) 11186 .addMBB(thisMBB); 11187 } else if (MI.getOpcode() == PPC::ReadTB) { 11188 // To read the 64-bit time-base register on a 32-bit target, we read the 11189 // two halves. Should the counter have wrapped while it was being read, we 11190 // need to try again. 11191 // ... 11192 // readLoop: 11193 // mfspr Rx,TBU # load from TBU 11194 // mfspr Ry,TB # load from TB 11195 // mfspr Rz,TBU # load from TBU 11196 // cmpw crX,Rx,Rz # check if 'old'='new' 11197 // bne readLoop # branch if they're not equal 11198 // ... 11199 11200 MachineBasicBlock *readMBB = F->CreateMachineBasicBlock(LLVM_BB); 11201 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 11202 DebugLoc dl = MI.getDebugLoc(); 11203 F->insert(It, readMBB); 11204 F->insert(It, sinkMBB); 11205 11206 // Transfer the remainder of BB and its successor edges to sinkMBB. 11207 sinkMBB->splice(sinkMBB->begin(), BB, 11208 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 11209 sinkMBB->transferSuccessorsAndUpdatePHIs(BB); 11210 11211 BB->addSuccessor(readMBB); 11212 BB = readMBB; 11213 11214 MachineRegisterInfo &RegInfo = F->getRegInfo(); 11215 Register ReadAgainReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass); 11216 Register LoReg = MI.getOperand(0).getReg(); 11217 Register HiReg = MI.getOperand(1).getReg(); 11218 11219 BuildMI(BB, dl, TII->get(PPC::MFSPR), HiReg).addImm(269); 11220 BuildMI(BB, dl, TII->get(PPC::MFSPR), LoReg).addImm(268); 11221 BuildMI(BB, dl, TII->get(PPC::MFSPR), ReadAgainReg).addImm(269); 11222 11223 Register CmpReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass); 11224 11225 BuildMI(BB, dl, TII->get(PPC::CMPW), CmpReg) 11226 .addReg(HiReg) 11227 .addReg(ReadAgainReg); 11228 BuildMI(BB, dl, TII->get(PPC::BCC)) 11229 .addImm(PPC::PRED_NE) 11230 .addReg(CmpReg) 11231 .addMBB(readMBB); 11232 11233 BB->addSuccessor(readMBB); 11234 BB->addSuccessor(sinkMBB); 11235 } else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I8) 11236 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4); 11237 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I16) 11238 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4); 11239 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I32) 11240 BB = EmitAtomicBinary(MI, BB, 4, PPC::ADD4); 11241 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I64) 11242 BB = EmitAtomicBinary(MI, BB, 8, PPC::ADD8); 11243 11244 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I8) 11245 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND); 11246 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I16) 11247 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND); 11248 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I32) 11249 BB = EmitAtomicBinary(MI, BB, 4, PPC::AND); 11250 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I64) 11251 BB = EmitAtomicBinary(MI, BB, 8, PPC::AND8); 11252 11253 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I8) 11254 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR); 11255 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I16) 11256 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR); 11257 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I32) 11258 BB = EmitAtomicBinary(MI, BB, 4, PPC::OR); 11259 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I64) 11260 BB = EmitAtomicBinary(MI, BB, 8, PPC::OR8); 11261 11262 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I8) 11263 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR); 11264 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I16) 11265 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR); 11266 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I32) 11267 BB = EmitAtomicBinary(MI, BB, 4, PPC::XOR); 11268 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I64) 11269 BB = EmitAtomicBinary(MI, BB, 8, PPC::XOR8); 11270 11271 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I8) 11272 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::NAND); 11273 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I16) 11274 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::NAND); 11275 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I32) 11276 BB = EmitAtomicBinary(MI, BB, 4, PPC::NAND); 11277 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I64) 11278 BB = EmitAtomicBinary(MI, BB, 8, PPC::NAND8); 11279 11280 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I8) 11281 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF); 11282 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I16) 11283 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF); 11284 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I32) 11285 BB = EmitAtomicBinary(MI, BB, 4, PPC::SUBF); 11286 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I64) 11287 BB = EmitAtomicBinary(MI, BB, 8, PPC::SUBF8); 11288 11289 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I8) 11290 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_GE); 11291 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I16) 11292 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_GE); 11293 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I32) 11294 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_GE); 11295 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I64) 11296 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_GE); 11297 11298 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I8) 11299 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_LE); 11300 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I16) 11301 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_LE); 11302 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I32) 11303 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_LE); 11304 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I64) 11305 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_LE); 11306 11307 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I8) 11308 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_GE); 11309 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I16) 11310 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_GE); 11311 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I32) 11312 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_GE); 11313 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I64) 11314 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_GE); 11315 11316 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I8) 11317 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_LE); 11318 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I16) 11319 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_LE); 11320 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I32) 11321 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_LE); 11322 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I64) 11323 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_LE); 11324 11325 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I8) 11326 BB = EmitPartwordAtomicBinary(MI, BB, true, 0); 11327 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I16) 11328 BB = EmitPartwordAtomicBinary(MI, BB, false, 0); 11329 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I32) 11330 BB = EmitAtomicBinary(MI, BB, 4, 0); 11331 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I64) 11332 BB = EmitAtomicBinary(MI, BB, 8, 0); 11333 else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 || 11334 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64 || 11335 (Subtarget.hasPartwordAtomics() && 11336 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8) || 11337 (Subtarget.hasPartwordAtomics() && 11338 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16)) { 11339 bool is64bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64; 11340 11341 auto LoadMnemonic = PPC::LDARX; 11342 auto StoreMnemonic = PPC::STDCX; 11343 switch (MI.getOpcode()) { 11344 default: 11345 llvm_unreachable("Compare and swap of unknown size"); 11346 case PPC::ATOMIC_CMP_SWAP_I8: 11347 LoadMnemonic = PPC::LBARX; 11348 StoreMnemonic = PPC::STBCX; 11349 assert(Subtarget.hasPartwordAtomics() && "No support partword atomics."); 11350 break; 11351 case PPC::ATOMIC_CMP_SWAP_I16: 11352 LoadMnemonic = PPC::LHARX; 11353 StoreMnemonic = PPC::STHCX; 11354 assert(Subtarget.hasPartwordAtomics() && "No support partword atomics."); 11355 break; 11356 case PPC::ATOMIC_CMP_SWAP_I32: 11357 LoadMnemonic = PPC::LWARX; 11358 StoreMnemonic = PPC::STWCX; 11359 break; 11360 case PPC::ATOMIC_CMP_SWAP_I64: 11361 LoadMnemonic = PPC::LDARX; 11362 StoreMnemonic = PPC::STDCX; 11363 break; 11364 } 11365 Register dest = MI.getOperand(0).getReg(); 11366 Register ptrA = MI.getOperand(1).getReg(); 11367 Register ptrB = MI.getOperand(2).getReg(); 11368 Register oldval = MI.getOperand(3).getReg(); 11369 Register newval = MI.getOperand(4).getReg(); 11370 DebugLoc dl = MI.getDebugLoc(); 11371 11372 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB); 11373 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB); 11374 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB); 11375 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 11376 F->insert(It, loop1MBB); 11377 F->insert(It, loop2MBB); 11378 F->insert(It, midMBB); 11379 F->insert(It, exitMBB); 11380 exitMBB->splice(exitMBB->begin(), BB, 11381 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 11382 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 11383 11384 // thisMBB: 11385 // ... 11386 // fallthrough --> loopMBB 11387 BB->addSuccessor(loop1MBB); 11388 11389 // loop1MBB: 11390 // l[bhwd]arx dest, ptr 11391 // cmp[wd] dest, oldval 11392 // bne- midMBB 11393 // loop2MBB: 11394 // st[bhwd]cx. newval, ptr 11395 // bne- loopMBB 11396 // b exitBB 11397 // midMBB: 11398 // st[bhwd]cx. dest, ptr 11399 // exitBB: 11400 BB = loop1MBB; 11401 BuildMI(BB, dl, TII->get(LoadMnemonic), dest).addReg(ptrA).addReg(ptrB); 11402 BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0) 11403 .addReg(oldval) 11404 .addReg(dest); 11405 BuildMI(BB, dl, TII->get(PPC::BCC)) 11406 .addImm(PPC::PRED_NE) 11407 .addReg(PPC::CR0) 11408 .addMBB(midMBB); 11409 BB->addSuccessor(loop2MBB); 11410 BB->addSuccessor(midMBB); 11411 11412 BB = loop2MBB; 11413 BuildMI(BB, dl, TII->get(StoreMnemonic)) 11414 .addReg(newval) 11415 .addReg(ptrA) 11416 .addReg(ptrB); 11417 BuildMI(BB, dl, TII->get(PPC::BCC)) 11418 .addImm(PPC::PRED_NE) 11419 .addReg(PPC::CR0) 11420 .addMBB(loop1MBB); 11421 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB); 11422 BB->addSuccessor(loop1MBB); 11423 BB->addSuccessor(exitMBB); 11424 11425 BB = midMBB; 11426 BuildMI(BB, dl, TII->get(StoreMnemonic)) 11427 .addReg(dest) 11428 .addReg(ptrA) 11429 .addReg(ptrB); 11430 BB->addSuccessor(exitMBB); 11431 11432 // exitMBB: 11433 // ... 11434 BB = exitMBB; 11435 } else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 || 11436 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) { 11437 // We must use 64-bit registers for addresses when targeting 64-bit, 11438 // since we're actually doing arithmetic on them. Other registers 11439 // can be 32-bit. 11440 bool is64bit = Subtarget.isPPC64(); 11441 bool isLittleEndian = Subtarget.isLittleEndian(); 11442 bool is8bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8; 11443 11444 Register dest = MI.getOperand(0).getReg(); 11445 Register ptrA = MI.getOperand(1).getReg(); 11446 Register ptrB = MI.getOperand(2).getReg(); 11447 Register oldval = MI.getOperand(3).getReg(); 11448 Register newval = MI.getOperand(4).getReg(); 11449 DebugLoc dl = MI.getDebugLoc(); 11450 11451 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB); 11452 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB); 11453 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB); 11454 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 11455 F->insert(It, loop1MBB); 11456 F->insert(It, loop2MBB); 11457 F->insert(It, midMBB); 11458 F->insert(It, exitMBB); 11459 exitMBB->splice(exitMBB->begin(), BB, 11460 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 11461 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 11462 11463 MachineRegisterInfo &RegInfo = F->getRegInfo(); 11464 const TargetRegisterClass *RC = 11465 is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 11466 const TargetRegisterClass *GPRC = &PPC::GPRCRegClass; 11467 11468 Register PtrReg = RegInfo.createVirtualRegister(RC); 11469 Register Shift1Reg = RegInfo.createVirtualRegister(GPRC); 11470 Register ShiftReg = 11471 isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC); 11472 Register NewVal2Reg = RegInfo.createVirtualRegister(GPRC); 11473 Register NewVal3Reg = RegInfo.createVirtualRegister(GPRC); 11474 Register OldVal2Reg = RegInfo.createVirtualRegister(GPRC); 11475 Register OldVal3Reg = RegInfo.createVirtualRegister(GPRC); 11476 Register MaskReg = RegInfo.createVirtualRegister(GPRC); 11477 Register Mask2Reg = RegInfo.createVirtualRegister(GPRC); 11478 Register Mask3Reg = RegInfo.createVirtualRegister(GPRC); 11479 Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC); 11480 Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC); 11481 Register TmpDestReg = RegInfo.createVirtualRegister(GPRC); 11482 Register Ptr1Reg; 11483 Register TmpReg = RegInfo.createVirtualRegister(GPRC); 11484 Register ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO; 11485 // thisMBB: 11486 // ... 11487 // fallthrough --> loopMBB 11488 BB->addSuccessor(loop1MBB); 11489 11490 // The 4-byte load must be aligned, while a char or short may be 11491 // anywhere in the word. Hence all this nasty bookkeeping code. 11492 // add ptr1, ptrA, ptrB [copy if ptrA==0] 11493 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27] 11494 // xori shift, shift1, 24 [16] 11495 // rlwinm ptr, ptr1, 0, 0, 29 11496 // slw newval2, newval, shift 11497 // slw oldval2, oldval,shift 11498 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535] 11499 // slw mask, mask2, shift 11500 // and newval3, newval2, mask 11501 // and oldval3, oldval2, mask 11502 // loop1MBB: 11503 // lwarx tmpDest, ptr 11504 // and tmp, tmpDest, mask 11505 // cmpw tmp, oldval3 11506 // bne- midMBB 11507 // loop2MBB: 11508 // andc tmp2, tmpDest, mask 11509 // or tmp4, tmp2, newval3 11510 // stwcx. tmp4, ptr 11511 // bne- loop1MBB 11512 // b exitBB 11513 // midMBB: 11514 // stwcx. tmpDest, ptr 11515 // exitBB: 11516 // srw dest, tmpDest, shift 11517 if (ptrA != ZeroReg) { 11518 Ptr1Reg = RegInfo.createVirtualRegister(RC); 11519 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg) 11520 .addReg(ptrA) 11521 .addReg(ptrB); 11522 } else { 11523 Ptr1Reg = ptrB; 11524 } 11525 11526 // We need use 32-bit subregister to avoid mismatch register class in 64-bit 11527 // mode. 11528 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg) 11529 .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0) 11530 .addImm(3) 11531 .addImm(27) 11532 .addImm(is8bit ? 28 : 27); 11533 if (!isLittleEndian) 11534 BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg) 11535 .addReg(Shift1Reg) 11536 .addImm(is8bit ? 24 : 16); 11537 if (is64bit) 11538 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg) 11539 .addReg(Ptr1Reg) 11540 .addImm(0) 11541 .addImm(61); 11542 else 11543 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg) 11544 .addReg(Ptr1Reg) 11545 .addImm(0) 11546 .addImm(0) 11547 .addImm(29); 11548 BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg) 11549 .addReg(newval) 11550 .addReg(ShiftReg); 11551 BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg) 11552 .addReg(oldval) 11553 .addReg(ShiftReg); 11554 if (is8bit) 11555 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255); 11556 else { 11557 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0); 11558 BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg) 11559 .addReg(Mask3Reg) 11560 .addImm(65535); 11561 } 11562 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg) 11563 .addReg(Mask2Reg) 11564 .addReg(ShiftReg); 11565 BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg) 11566 .addReg(NewVal2Reg) 11567 .addReg(MaskReg); 11568 BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg) 11569 .addReg(OldVal2Reg) 11570 .addReg(MaskReg); 11571 11572 BB = loop1MBB; 11573 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg) 11574 .addReg(ZeroReg) 11575 .addReg(PtrReg); 11576 BuildMI(BB, dl, TII->get(PPC::AND), TmpReg) 11577 .addReg(TmpDestReg) 11578 .addReg(MaskReg); 11579 BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0) 11580 .addReg(TmpReg) 11581 .addReg(OldVal3Reg); 11582 BuildMI(BB, dl, TII->get(PPC::BCC)) 11583 .addImm(PPC::PRED_NE) 11584 .addReg(PPC::CR0) 11585 .addMBB(midMBB); 11586 BB->addSuccessor(loop2MBB); 11587 BB->addSuccessor(midMBB); 11588 11589 BB = loop2MBB; 11590 BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg) 11591 .addReg(TmpDestReg) 11592 .addReg(MaskReg); 11593 BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg) 11594 .addReg(Tmp2Reg) 11595 .addReg(NewVal3Reg); 11596 BuildMI(BB, dl, TII->get(PPC::STWCX)) 11597 .addReg(Tmp4Reg) 11598 .addReg(ZeroReg) 11599 .addReg(PtrReg); 11600 BuildMI(BB, dl, TII->get(PPC::BCC)) 11601 .addImm(PPC::PRED_NE) 11602 .addReg(PPC::CR0) 11603 .addMBB(loop1MBB); 11604 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB); 11605 BB->addSuccessor(loop1MBB); 11606 BB->addSuccessor(exitMBB); 11607 11608 BB = midMBB; 11609 BuildMI(BB, dl, TII->get(PPC::STWCX)) 11610 .addReg(TmpDestReg) 11611 .addReg(ZeroReg) 11612 .addReg(PtrReg); 11613 BB->addSuccessor(exitMBB); 11614 11615 // exitMBB: 11616 // ... 11617 BB = exitMBB; 11618 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest) 11619 .addReg(TmpReg) 11620 .addReg(ShiftReg); 11621 } else if (MI.getOpcode() == PPC::FADDrtz) { 11622 // This pseudo performs an FADD with rounding mode temporarily forced 11623 // to round-to-zero. We emit this via custom inserter since the FPSCR 11624 // is not modeled at the SelectionDAG level. 11625 Register Dest = MI.getOperand(0).getReg(); 11626 Register Src1 = MI.getOperand(1).getReg(); 11627 Register Src2 = MI.getOperand(2).getReg(); 11628 DebugLoc dl = MI.getDebugLoc(); 11629 11630 MachineRegisterInfo &RegInfo = F->getRegInfo(); 11631 Register MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass); 11632 11633 // Save FPSCR value. 11634 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg); 11635 11636 // Set rounding mode to round-to-zero. 11637 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1)).addImm(31); 11638 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0)).addImm(30); 11639 11640 // Perform addition. 11641 BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest).addReg(Src1).addReg(Src2); 11642 11643 // Restore FPSCR value. 11644 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSFb)).addImm(1).addReg(MFFSReg); 11645 } else if (MI.getOpcode() == PPC::ANDIo_1_EQ_BIT || 11646 MI.getOpcode() == PPC::ANDIo_1_GT_BIT || 11647 MI.getOpcode() == PPC::ANDIo_1_EQ_BIT8 || 11648 MI.getOpcode() == PPC::ANDIo_1_GT_BIT8) { 11649 unsigned Opcode = (MI.getOpcode() == PPC::ANDIo_1_EQ_BIT8 || 11650 MI.getOpcode() == PPC::ANDIo_1_GT_BIT8) 11651 ? PPC::ANDI8o 11652 : PPC::ANDIo; 11653 bool isEQ = (MI.getOpcode() == PPC::ANDIo_1_EQ_BIT || 11654 MI.getOpcode() == PPC::ANDIo_1_EQ_BIT8); 11655 11656 MachineRegisterInfo &RegInfo = F->getRegInfo(); 11657 Register Dest = RegInfo.createVirtualRegister( 11658 Opcode == PPC::ANDIo ? &PPC::GPRCRegClass : &PPC::G8RCRegClass); 11659 11660 DebugLoc dl = MI.getDebugLoc(); 11661 BuildMI(*BB, MI, dl, TII->get(Opcode), Dest) 11662 .addReg(MI.getOperand(1).getReg()) 11663 .addImm(1); 11664 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), 11665 MI.getOperand(0).getReg()) 11666 .addReg(isEQ ? PPC::CR0EQ : PPC::CR0GT); 11667 } else if (MI.getOpcode() == PPC::TCHECK_RET) { 11668 DebugLoc Dl = MI.getDebugLoc(); 11669 MachineRegisterInfo &RegInfo = F->getRegInfo(); 11670 Register CRReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass); 11671 BuildMI(*BB, MI, Dl, TII->get(PPC::TCHECK), CRReg); 11672 BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY), 11673 MI.getOperand(0).getReg()) 11674 .addReg(CRReg); 11675 } else if (MI.getOpcode() == PPC::TBEGIN_RET) { 11676 DebugLoc Dl = MI.getDebugLoc(); 11677 unsigned Imm = MI.getOperand(1).getImm(); 11678 BuildMI(*BB, MI, Dl, TII->get(PPC::TBEGIN)).addImm(Imm); 11679 BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY), 11680 MI.getOperand(0).getReg()) 11681 .addReg(PPC::CR0EQ); 11682 } else if (MI.getOpcode() == PPC::SETRNDi) { 11683 DebugLoc dl = MI.getDebugLoc(); 11684 Register OldFPSCRReg = MI.getOperand(0).getReg(); 11685 11686 // Save FPSCR value. 11687 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg); 11688 11689 // The floating point rounding mode is in the bits 62:63 of FPCSR, and has 11690 // the following settings: 11691 // 00 Round to nearest 11692 // 01 Round to 0 11693 // 10 Round to +inf 11694 // 11 Round to -inf 11695 11696 // When the operand is immediate, using the two least significant bits of 11697 // the immediate to set the bits 62:63 of FPSCR. 11698 unsigned Mode = MI.getOperand(1).getImm(); 11699 BuildMI(*BB, MI, dl, TII->get((Mode & 1) ? PPC::MTFSB1 : PPC::MTFSB0)) 11700 .addImm(31); 11701 11702 BuildMI(*BB, MI, dl, TII->get((Mode & 2) ? PPC::MTFSB1 : PPC::MTFSB0)) 11703 .addImm(30); 11704 } else if (MI.getOpcode() == PPC::SETRND) { 11705 DebugLoc dl = MI.getDebugLoc(); 11706 11707 // Copy register from F8RCRegClass::SrcReg to G8RCRegClass::DestReg 11708 // or copy register from G8RCRegClass::SrcReg to F8RCRegClass::DestReg. 11709 // If the target doesn't have DirectMove, we should use stack to do the 11710 // conversion, because the target doesn't have the instructions like mtvsrd 11711 // or mfvsrd to do this conversion directly. 11712 auto copyRegFromG8RCOrF8RC = [&] (unsigned DestReg, unsigned SrcReg) { 11713 if (Subtarget.hasDirectMove()) { 11714 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), DestReg) 11715 .addReg(SrcReg); 11716 } else { 11717 // Use stack to do the register copy. 11718 unsigned StoreOp = PPC::STD, LoadOp = PPC::LFD; 11719 MachineRegisterInfo &RegInfo = F->getRegInfo(); 11720 const TargetRegisterClass *RC = RegInfo.getRegClass(SrcReg); 11721 if (RC == &PPC::F8RCRegClass) { 11722 // Copy register from F8RCRegClass to G8RCRegclass. 11723 assert((RegInfo.getRegClass(DestReg) == &PPC::G8RCRegClass) && 11724 "Unsupported RegClass."); 11725 11726 StoreOp = PPC::STFD; 11727 LoadOp = PPC::LD; 11728 } else { 11729 // Copy register from G8RCRegClass to F8RCRegclass. 11730 assert((RegInfo.getRegClass(SrcReg) == &PPC::G8RCRegClass) && 11731 (RegInfo.getRegClass(DestReg) == &PPC::F8RCRegClass) && 11732 "Unsupported RegClass."); 11733 } 11734 11735 MachineFrameInfo &MFI = F->getFrameInfo(); 11736 int FrameIdx = MFI.CreateStackObject(8, 8, false); 11737 11738 MachineMemOperand *MMOStore = F->getMachineMemOperand( 11739 MachinePointerInfo::getFixedStack(*F, FrameIdx, 0), 11740 MachineMemOperand::MOStore, MFI.getObjectSize(FrameIdx), 11741 MFI.getObjectAlignment(FrameIdx)); 11742 11743 // Store the SrcReg into the stack. 11744 BuildMI(*BB, MI, dl, TII->get(StoreOp)) 11745 .addReg(SrcReg) 11746 .addImm(0) 11747 .addFrameIndex(FrameIdx) 11748 .addMemOperand(MMOStore); 11749 11750 MachineMemOperand *MMOLoad = F->getMachineMemOperand( 11751 MachinePointerInfo::getFixedStack(*F, FrameIdx, 0), 11752 MachineMemOperand::MOLoad, MFI.getObjectSize(FrameIdx), 11753 MFI.getObjectAlignment(FrameIdx)); 11754 11755 // Load from the stack where SrcReg is stored, and save to DestReg, 11756 // so we have done the RegClass conversion from RegClass::SrcReg to 11757 // RegClass::DestReg. 11758 BuildMI(*BB, MI, dl, TII->get(LoadOp), DestReg) 11759 .addImm(0) 11760 .addFrameIndex(FrameIdx) 11761 .addMemOperand(MMOLoad); 11762 } 11763 }; 11764 11765 Register OldFPSCRReg = MI.getOperand(0).getReg(); 11766 11767 // Save FPSCR value. 11768 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg); 11769 11770 // When the operand is gprc register, use two least significant bits of the 11771 // register and mtfsf instruction to set the bits 62:63 of FPSCR. 11772 // 11773 // copy OldFPSCRTmpReg, OldFPSCRReg 11774 // (INSERT_SUBREG ExtSrcReg, (IMPLICIT_DEF ImDefReg), SrcOp, 1) 11775 // rldimi NewFPSCRTmpReg, ExtSrcReg, OldFPSCRReg, 0, 62 11776 // copy NewFPSCRReg, NewFPSCRTmpReg 11777 // mtfsf 255, NewFPSCRReg 11778 MachineOperand SrcOp = MI.getOperand(1); 11779 MachineRegisterInfo &RegInfo = F->getRegInfo(); 11780 Register OldFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 11781 11782 copyRegFromG8RCOrF8RC(OldFPSCRTmpReg, OldFPSCRReg); 11783 11784 Register ImDefReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 11785 Register ExtSrcReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 11786 11787 // The first operand of INSERT_SUBREG should be a register which has 11788 // subregisters, we only care about its RegClass, so we should use an 11789 // IMPLICIT_DEF register. 11790 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::IMPLICIT_DEF), ImDefReg); 11791 BuildMI(*BB, MI, dl, TII->get(PPC::INSERT_SUBREG), ExtSrcReg) 11792 .addReg(ImDefReg) 11793 .add(SrcOp) 11794 .addImm(1); 11795 11796 Register NewFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 11797 BuildMI(*BB, MI, dl, TII->get(PPC::RLDIMI), NewFPSCRTmpReg) 11798 .addReg(OldFPSCRTmpReg) 11799 .addReg(ExtSrcReg) 11800 .addImm(0) 11801 .addImm(62); 11802 11803 Register NewFPSCRReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass); 11804 copyRegFromG8RCOrF8RC(NewFPSCRReg, NewFPSCRTmpReg); 11805 11806 // The mask 255 means that put the 32:63 bits of NewFPSCRReg to the 32:63 11807 // bits of FPSCR. 11808 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSF)) 11809 .addImm(255) 11810 .addReg(NewFPSCRReg) 11811 .addImm(0) 11812 .addImm(0); 11813 } else { 11814 llvm_unreachable("Unexpected instr type to insert"); 11815 } 11816 11817 MI.eraseFromParent(); // The pseudo instruction is gone now. 11818 return BB; 11819 } 11820 11821 //===----------------------------------------------------------------------===// 11822 // Target Optimization Hooks 11823 //===----------------------------------------------------------------------===// 11824 11825 static int getEstimateRefinementSteps(EVT VT, const PPCSubtarget &Subtarget) { 11826 // For the estimates, convergence is quadratic, so we essentially double the 11827 // number of digits correct after every iteration. For both FRE and FRSQRTE, 11828 // the minimum architected relative accuracy is 2^-5. When hasRecipPrec(), 11829 // this is 2^-14. IEEE float has 23 digits and double has 52 digits. 11830 int RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3; 11831 if (VT.getScalarType() == MVT::f64) 11832 RefinementSteps++; 11833 return RefinementSteps; 11834 } 11835 11836 SDValue PPCTargetLowering::getSqrtEstimate(SDValue Operand, SelectionDAG &DAG, 11837 int Enabled, int &RefinementSteps, 11838 bool &UseOneConstNR, 11839 bool Reciprocal) const { 11840 EVT VT = Operand.getValueType(); 11841 if ((VT == MVT::f32 && Subtarget.hasFRSQRTES()) || 11842 (VT == MVT::f64 && Subtarget.hasFRSQRTE()) || 11843 (VT == MVT::v4f32 && Subtarget.hasAltivec()) || 11844 (VT == MVT::v2f64 && Subtarget.hasVSX()) || 11845 (VT == MVT::v4f32 && Subtarget.hasQPX()) || 11846 (VT == MVT::v4f64 && Subtarget.hasQPX())) { 11847 if (RefinementSteps == ReciprocalEstimate::Unspecified) 11848 RefinementSteps = getEstimateRefinementSteps(VT, Subtarget); 11849 11850 // The Newton-Raphson computation with a single constant does not provide 11851 // enough accuracy on some CPUs. 11852 UseOneConstNR = !Subtarget.needsTwoConstNR(); 11853 return DAG.getNode(PPCISD::FRSQRTE, SDLoc(Operand), VT, Operand); 11854 } 11855 return SDValue(); 11856 } 11857 11858 SDValue PPCTargetLowering::getRecipEstimate(SDValue Operand, SelectionDAG &DAG, 11859 int Enabled, 11860 int &RefinementSteps) const { 11861 EVT VT = Operand.getValueType(); 11862 if ((VT == MVT::f32 && Subtarget.hasFRES()) || 11863 (VT == MVT::f64 && Subtarget.hasFRE()) || 11864 (VT == MVT::v4f32 && Subtarget.hasAltivec()) || 11865 (VT == MVT::v2f64 && Subtarget.hasVSX()) || 11866 (VT == MVT::v4f32 && Subtarget.hasQPX()) || 11867 (VT == MVT::v4f64 && Subtarget.hasQPX())) { 11868 if (RefinementSteps == ReciprocalEstimate::Unspecified) 11869 RefinementSteps = getEstimateRefinementSteps(VT, Subtarget); 11870 return DAG.getNode(PPCISD::FRE, SDLoc(Operand), VT, Operand); 11871 } 11872 return SDValue(); 11873 } 11874 11875 unsigned PPCTargetLowering::combineRepeatedFPDivisors() const { 11876 // Note: This functionality is used only when unsafe-fp-math is enabled, and 11877 // on cores with reciprocal estimates (which are used when unsafe-fp-math is 11878 // enabled for division), this functionality is redundant with the default 11879 // combiner logic (once the division -> reciprocal/multiply transformation 11880 // has taken place). As a result, this matters more for older cores than for 11881 // newer ones. 11882 11883 // Combine multiple FDIVs with the same divisor into multiple FMULs by the 11884 // reciprocal if there are two or more FDIVs (for embedded cores with only 11885 // one FP pipeline) for three or more FDIVs (for generic OOO cores). 11886 switch (Subtarget.getCPUDirective()) { 11887 default: 11888 return 3; 11889 case PPC::DIR_440: 11890 case PPC::DIR_A2: 11891 case PPC::DIR_E500: 11892 case PPC::DIR_E500mc: 11893 case PPC::DIR_E5500: 11894 return 2; 11895 } 11896 } 11897 11898 // isConsecutiveLSLoc needs to work even if all adds have not yet been 11899 // collapsed, and so we need to look through chains of them. 11900 static void getBaseWithConstantOffset(SDValue Loc, SDValue &Base, 11901 int64_t& Offset, SelectionDAG &DAG) { 11902 if (DAG.isBaseWithConstantOffset(Loc)) { 11903 Base = Loc.getOperand(0); 11904 Offset += cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue(); 11905 11906 // The base might itself be a base plus an offset, and if so, accumulate 11907 // that as well. 11908 getBaseWithConstantOffset(Loc.getOperand(0), Base, Offset, DAG); 11909 } 11910 } 11911 11912 static bool isConsecutiveLSLoc(SDValue Loc, EVT VT, LSBaseSDNode *Base, 11913 unsigned Bytes, int Dist, 11914 SelectionDAG &DAG) { 11915 if (VT.getSizeInBits() / 8 != Bytes) 11916 return false; 11917 11918 SDValue BaseLoc = Base->getBasePtr(); 11919 if (Loc.getOpcode() == ISD::FrameIndex) { 11920 if (BaseLoc.getOpcode() != ISD::FrameIndex) 11921 return false; 11922 const MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 11923 int FI = cast<FrameIndexSDNode>(Loc)->getIndex(); 11924 int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex(); 11925 int FS = MFI.getObjectSize(FI); 11926 int BFS = MFI.getObjectSize(BFI); 11927 if (FS != BFS || FS != (int)Bytes) return false; 11928 return MFI.getObjectOffset(FI) == (MFI.getObjectOffset(BFI) + Dist*Bytes); 11929 } 11930 11931 SDValue Base1 = Loc, Base2 = BaseLoc; 11932 int64_t Offset1 = 0, Offset2 = 0; 11933 getBaseWithConstantOffset(Loc, Base1, Offset1, DAG); 11934 getBaseWithConstantOffset(BaseLoc, Base2, Offset2, DAG); 11935 if (Base1 == Base2 && Offset1 == (Offset2 + Dist * Bytes)) 11936 return true; 11937 11938 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11939 const GlobalValue *GV1 = nullptr; 11940 const GlobalValue *GV2 = nullptr; 11941 Offset1 = 0; 11942 Offset2 = 0; 11943 bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1); 11944 bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2); 11945 if (isGA1 && isGA2 && GV1 == GV2) 11946 return Offset1 == (Offset2 + Dist*Bytes); 11947 return false; 11948 } 11949 11950 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does 11951 // not enforce equality of the chain operands. 11952 static bool isConsecutiveLS(SDNode *N, LSBaseSDNode *Base, 11953 unsigned Bytes, int Dist, 11954 SelectionDAG &DAG) { 11955 if (LSBaseSDNode *LS = dyn_cast<LSBaseSDNode>(N)) { 11956 EVT VT = LS->getMemoryVT(); 11957 SDValue Loc = LS->getBasePtr(); 11958 return isConsecutiveLSLoc(Loc, VT, Base, Bytes, Dist, DAG); 11959 } 11960 11961 if (N->getOpcode() == ISD::INTRINSIC_W_CHAIN) { 11962 EVT VT; 11963 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 11964 default: return false; 11965 case Intrinsic::ppc_qpx_qvlfd: 11966 case Intrinsic::ppc_qpx_qvlfda: 11967 VT = MVT::v4f64; 11968 break; 11969 case Intrinsic::ppc_qpx_qvlfs: 11970 case Intrinsic::ppc_qpx_qvlfsa: 11971 VT = MVT::v4f32; 11972 break; 11973 case Intrinsic::ppc_qpx_qvlfcd: 11974 case Intrinsic::ppc_qpx_qvlfcda: 11975 VT = MVT::v2f64; 11976 break; 11977 case Intrinsic::ppc_qpx_qvlfcs: 11978 case Intrinsic::ppc_qpx_qvlfcsa: 11979 VT = MVT::v2f32; 11980 break; 11981 case Intrinsic::ppc_qpx_qvlfiwa: 11982 case Intrinsic::ppc_qpx_qvlfiwz: 11983 case Intrinsic::ppc_altivec_lvx: 11984 case Intrinsic::ppc_altivec_lvxl: 11985 case Intrinsic::ppc_vsx_lxvw4x: 11986 case Intrinsic::ppc_vsx_lxvw4x_be: 11987 VT = MVT::v4i32; 11988 break; 11989 case Intrinsic::ppc_vsx_lxvd2x: 11990 case Intrinsic::ppc_vsx_lxvd2x_be: 11991 VT = MVT::v2f64; 11992 break; 11993 case Intrinsic::ppc_altivec_lvebx: 11994 VT = MVT::i8; 11995 break; 11996 case Intrinsic::ppc_altivec_lvehx: 11997 VT = MVT::i16; 11998 break; 11999 case Intrinsic::ppc_altivec_lvewx: 12000 VT = MVT::i32; 12001 break; 12002 } 12003 12004 return isConsecutiveLSLoc(N->getOperand(2), VT, Base, Bytes, Dist, DAG); 12005 } 12006 12007 if (N->getOpcode() == ISD::INTRINSIC_VOID) { 12008 EVT VT; 12009 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 12010 default: return false; 12011 case Intrinsic::ppc_qpx_qvstfd: 12012 case Intrinsic::ppc_qpx_qvstfda: 12013 VT = MVT::v4f64; 12014 break; 12015 case Intrinsic::ppc_qpx_qvstfs: 12016 case Intrinsic::ppc_qpx_qvstfsa: 12017 VT = MVT::v4f32; 12018 break; 12019 case Intrinsic::ppc_qpx_qvstfcd: 12020 case Intrinsic::ppc_qpx_qvstfcda: 12021 VT = MVT::v2f64; 12022 break; 12023 case Intrinsic::ppc_qpx_qvstfcs: 12024 case Intrinsic::ppc_qpx_qvstfcsa: 12025 VT = MVT::v2f32; 12026 break; 12027 case Intrinsic::ppc_qpx_qvstfiw: 12028 case Intrinsic::ppc_qpx_qvstfiwa: 12029 case Intrinsic::ppc_altivec_stvx: 12030 case Intrinsic::ppc_altivec_stvxl: 12031 case Intrinsic::ppc_vsx_stxvw4x: 12032 VT = MVT::v4i32; 12033 break; 12034 case Intrinsic::ppc_vsx_stxvd2x: 12035 VT = MVT::v2f64; 12036 break; 12037 case Intrinsic::ppc_vsx_stxvw4x_be: 12038 VT = MVT::v4i32; 12039 break; 12040 case Intrinsic::ppc_vsx_stxvd2x_be: 12041 VT = MVT::v2f64; 12042 break; 12043 case Intrinsic::ppc_altivec_stvebx: 12044 VT = MVT::i8; 12045 break; 12046 case Intrinsic::ppc_altivec_stvehx: 12047 VT = MVT::i16; 12048 break; 12049 case Intrinsic::ppc_altivec_stvewx: 12050 VT = MVT::i32; 12051 break; 12052 } 12053 12054 return isConsecutiveLSLoc(N->getOperand(3), VT, Base, Bytes, Dist, DAG); 12055 } 12056 12057 return false; 12058 } 12059 12060 // Return true is there is a nearyby consecutive load to the one provided 12061 // (regardless of alignment). We search up and down the chain, looking though 12062 // token factors and other loads (but nothing else). As a result, a true result 12063 // indicates that it is safe to create a new consecutive load adjacent to the 12064 // load provided. 12065 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) { 12066 SDValue Chain = LD->getChain(); 12067 EVT VT = LD->getMemoryVT(); 12068 12069 SmallSet<SDNode *, 16> LoadRoots; 12070 SmallVector<SDNode *, 8> Queue(1, Chain.getNode()); 12071 SmallSet<SDNode *, 16> Visited; 12072 12073 // First, search up the chain, branching to follow all token-factor operands. 12074 // If we find a consecutive load, then we're done, otherwise, record all 12075 // nodes just above the top-level loads and token factors. 12076 while (!Queue.empty()) { 12077 SDNode *ChainNext = Queue.pop_back_val(); 12078 if (!Visited.insert(ChainNext).second) 12079 continue; 12080 12081 if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(ChainNext)) { 12082 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG)) 12083 return true; 12084 12085 if (!Visited.count(ChainLD->getChain().getNode())) 12086 Queue.push_back(ChainLD->getChain().getNode()); 12087 } else if (ChainNext->getOpcode() == ISD::TokenFactor) { 12088 for (const SDUse &O : ChainNext->ops()) 12089 if (!Visited.count(O.getNode())) 12090 Queue.push_back(O.getNode()); 12091 } else 12092 LoadRoots.insert(ChainNext); 12093 } 12094 12095 // Second, search down the chain, starting from the top-level nodes recorded 12096 // in the first phase. These top-level nodes are the nodes just above all 12097 // loads and token factors. Starting with their uses, recursively look though 12098 // all loads (just the chain uses) and token factors to find a consecutive 12099 // load. 12100 Visited.clear(); 12101 Queue.clear(); 12102 12103 for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(), 12104 IE = LoadRoots.end(); I != IE; ++I) { 12105 Queue.push_back(*I); 12106 12107 while (!Queue.empty()) { 12108 SDNode *LoadRoot = Queue.pop_back_val(); 12109 if (!Visited.insert(LoadRoot).second) 12110 continue; 12111 12112 if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(LoadRoot)) 12113 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG)) 12114 return true; 12115 12116 for (SDNode::use_iterator UI = LoadRoot->use_begin(), 12117 UE = LoadRoot->use_end(); UI != UE; ++UI) 12118 if (((isa<MemSDNode>(*UI) && 12119 cast<MemSDNode>(*UI)->getChain().getNode() == LoadRoot) || 12120 UI->getOpcode() == ISD::TokenFactor) && !Visited.count(*UI)) 12121 Queue.push_back(*UI); 12122 } 12123 } 12124 12125 return false; 12126 } 12127 12128 /// This function is called when we have proved that a SETCC node can be replaced 12129 /// by subtraction (and other supporting instructions) so that the result of 12130 /// comparison is kept in a GPR instead of CR. This function is purely for 12131 /// codegen purposes and has some flags to guide the codegen process. 12132 static SDValue generateEquivalentSub(SDNode *N, int Size, bool Complement, 12133 bool Swap, SDLoc &DL, SelectionDAG &DAG) { 12134 assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected."); 12135 12136 // Zero extend the operands to the largest legal integer. Originally, they 12137 // must be of a strictly smaller size. 12138 auto Op0 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(0), 12139 DAG.getConstant(Size, DL, MVT::i32)); 12140 auto Op1 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1), 12141 DAG.getConstant(Size, DL, MVT::i32)); 12142 12143 // Swap if needed. Depends on the condition code. 12144 if (Swap) 12145 std::swap(Op0, Op1); 12146 12147 // Subtract extended integers. 12148 auto SubNode = DAG.getNode(ISD::SUB, DL, MVT::i64, Op0, Op1); 12149 12150 // Move the sign bit to the least significant position and zero out the rest. 12151 // Now the least significant bit carries the result of original comparison. 12152 auto Shifted = DAG.getNode(ISD::SRL, DL, MVT::i64, SubNode, 12153 DAG.getConstant(Size - 1, DL, MVT::i32)); 12154 auto Final = Shifted; 12155 12156 // Complement the result if needed. Based on the condition code. 12157 if (Complement) 12158 Final = DAG.getNode(ISD::XOR, DL, MVT::i64, Shifted, 12159 DAG.getConstant(1, DL, MVT::i64)); 12160 12161 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Final); 12162 } 12163 12164 SDValue PPCTargetLowering::ConvertSETCCToSubtract(SDNode *N, 12165 DAGCombinerInfo &DCI) const { 12166 assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected."); 12167 12168 SelectionDAG &DAG = DCI.DAG; 12169 SDLoc DL(N); 12170 12171 // Size of integers being compared has a critical role in the following 12172 // analysis, so we prefer to do this when all types are legal. 12173 if (!DCI.isAfterLegalizeDAG()) 12174 return SDValue(); 12175 12176 // If all users of SETCC extend its value to a legal integer type 12177 // then we replace SETCC with a subtraction 12178 for (SDNode::use_iterator UI = N->use_begin(), 12179 UE = N->use_end(); UI != UE; ++UI) { 12180 if (UI->getOpcode() != ISD::ZERO_EXTEND) 12181 return SDValue(); 12182 } 12183 12184 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 12185 auto OpSize = N->getOperand(0).getValueSizeInBits(); 12186 12187 unsigned Size = DAG.getDataLayout().getLargestLegalIntTypeSizeInBits(); 12188 12189 if (OpSize < Size) { 12190 switch (CC) { 12191 default: break; 12192 case ISD::SETULT: 12193 return generateEquivalentSub(N, Size, false, false, DL, DAG); 12194 case ISD::SETULE: 12195 return generateEquivalentSub(N, Size, true, true, DL, DAG); 12196 case ISD::SETUGT: 12197 return generateEquivalentSub(N, Size, false, true, DL, DAG); 12198 case ISD::SETUGE: 12199 return generateEquivalentSub(N, Size, true, false, DL, DAG); 12200 } 12201 } 12202 12203 return SDValue(); 12204 } 12205 12206 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N, 12207 DAGCombinerInfo &DCI) const { 12208 SelectionDAG &DAG = DCI.DAG; 12209 SDLoc dl(N); 12210 12211 assert(Subtarget.useCRBits() && "Expecting to be tracking CR bits"); 12212 // If we're tracking CR bits, we need to be careful that we don't have: 12213 // trunc(binary-ops(zext(x), zext(y))) 12214 // or 12215 // trunc(binary-ops(binary-ops(zext(x), zext(y)), ...) 12216 // such that we're unnecessarily moving things into GPRs when it would be 12217 // better to keep them in CR bits. 12218 12219 // Note that trunc here can be an actual i1 trunc, or can be the effective 12220 // truncation that comes from a setcc or select_cc. 12221 if (N->getOpcode() == ISD::TRUNCATE && 12222 N->getValueType(0) != MVT::i1) 12223 return SDValue(); 12224 12225 if (N->getOperand(0).getValueType() != MVT::i32 && 12226 N->getOperand(0).getValueType() != MVT::i64) 12227 return SDValue(); 12228 12229 if (N->getOpcode() == ISD::SETCC || 12230 N->getOpcode() == ISD::SELECT_CC) { 12231 // If we're looking at a comparison, then we need to make sure that the 12232 // high bits (all except for the first) don't matter the result. 12233 ISD::CondCode CC = 12234 cast<CondCodeSDNode>(N->getOperand( 12235 N->getOpcode() == ISD::SETCC ? 2 : 4))->get(); 12236 unsigned OpBits = N->getOperand(0).getValueSizeInBits(); 12237 12238 if (ISD::isSignedIntSetCC(CC)) { 12239 if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits || 12240 DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits) 12241 return SDValue(); 12242 } else if (ISD::isUnsignedIntSetCC(CC)) { 12243 if (!DAG.MaskedValueIsZero(N->getOperand(0), 12244 APInt::getHighBitsSet(OpBits, OpBits-1)) || 12245 !DAG.MaskedValueIsZero(N->getOperand(1), 12246 APInt::getHighBitsSet(OpBits, OpBits-1))) 12247 return (N->getOpcode() == ISD::SETCC ? ConvertSETCCToSubtract(N, DCI) 12248 : SDValue()); 12249 } else { 12250 // This is neither a signed nor an unsigned comparison, just make sure 12251 // that the high bits are equal. 12252 KnownBits Op1Known = DAG.computeKnownBits(N->getOperand(0)); 12253 KnownBits Op2Known = DAG.computeKnownBits(N->getOperand(1)); 12254 12255 // We don't really care about what is known about the first bit (if 12256 // anything), so clear it in all masks prior to comparing them. 12257 Op1Known.Zero.clearBit(0); Op1Known.One.clearBit(0); 12258 Op2Known.Zero.clearBit(0); Op2Known.One.clearBit(0); 12259 12260 if (Op1Known.Zero != Op2Known.Zero || Op1Known.One != Op2Known.One) 12261 return SDValue(); 12262 } 12263 } 12264 12265 // We now know that the higher-order bits are irrelevant, we just need to 12266 // make sure that all of the intermediate operations are bit operations, and 12267 // all inputs are extensions. 12268 if (N->getOperand(0).getOpcode() != ISD::AND && 12269 N->getOperand(0).getOpcode() != ISD::OR && 12270 N->getOperand(0).getOpcode() != ISD::XOR && 12271 N->getOperand(0).getOpcode() != ISD::SELECT && 12272 N->getOperand(0).getOpcode() != ISD::SELECT_CC && 12273 N->getOperand(0).getOpcode() != ISD::TRUNCATE && 12274 N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND && 12275 N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND && 12276 N->getOperand(0).getOpcode() != ISD::ANY_EXTEND) 12277 return SDValue(); 12278 12279 if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) && 12280 N->getOperand(1).getOpcode() != ISD::AND && 12281 N->getOperand(1).getOpcode() != ISD::OR && 12282 N->getOperand(1).getOpcode() != ISD::XOR && 12283 N->getOperand(1).getOpcode() != ISD::SELECT && 12284 N->getOperand(1).getOpcode() != ISD::SELECT_CC && 12285 N->getOperand(1).getOpcode() != ISD::TRUNCATE && 12286 N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND && 12287 N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND && 12288 N->getOperand(1).getOpcode() != ISD::ANY_EXTEND) 12289 return SDValue(); 12290 12291 SmallVector<SDValue, 4> Inputs; 12292 SmallVector<SDValue, 8> BinOps, PromOps; 12293 SmallPtrSet<SDNode *, 16> Visited; 12294 12295 for (unsigned i = 0; i < 2; ++i) { 12296 if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND || 12297 N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND || 12298 N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) && 12299 N->getOperand(i).getOperand(0).getValueType() == MVT::i1) || 12300 isa<ConstantSDNode>(N->getOperand(i))) 12301 Inputs.push_back(N->getOperand(i)); 12302 else 12303 BinOps.push_back(N->getOperand(i)); 12304 12305 if (N->getOpcode() == ISD::TRUNCATE) 12306 break; 12307 } 12308 12309 // Visit all inputs, collect all binary operations (and, or, xor and 12310 // select) that are all fed by extensions. 12311 while (!BinOps.empty()) { 12312 SDValue BinOp = BinOps.back(); 12313 BinOps.pop_back(); 12314 12315 if (!Visited.insert(BinOp.getNode()).second) 12316 continue; 12317 12318 PromOps.push_back(BinOp); 12319 12320 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) { 12321 // The condition of the select is not promoted. 12322 if (BinOp.getOpcode() == ISD::SELECT && i == 0) 12323 continue; 12324 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3) 12325 continue; 12326 12327 if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND || 12328 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND || 12329 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) && 12330 BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) || 12331 isa<ConstantSDNode>(BinOp.getOperand(i))) { 12332 Inputs.push_back(BinOp.getOperand(i)); 12333 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND || 12334 BinOp.getOperand(i).getOpcode() == ISD::OR || 12335 BinOp.getOperand(i).getOpcode() == ISD::XOR || 12336 BinOp.getOperand(i).getOpcode() == ISD::SELECT || 12337 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC || 12338 BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE || 12339 BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND || 12340 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND || 12341 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) { 12342 BinOps.push_back(BinOp.getOperand(i)); 12343 } else { 12344 // We have an input that is not an extension or another binary 12345 // operation; we'll abort this transformation. 12346 return SDValue(); 12347 } 12348 } 12349 } 12350 12351 // Make sure that this is a self-contained cluster of operations (which 12352 // is not quite the same thing as saying that everything has only one 12353 // use). 12354 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 12355 if (isa<ConstantSDNode>(Inputs[i])) 12356 continue; 12357 12358 for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(), 12359 UE = Inputs[i].getNode()->use_end(); 12360 UI != UE; ++UI) { 12361 SDNode *User = *UI; 12362 if (User != N && !Visited.count(User)) 12363 return SDValue(); 12364 12365 // Make sure that we're not going to promote the non-output-value 12366 // operand(s) or SELECT or SELECT_CC. 12367 // FIXME: Although we could sometimes handle this, and it does occur in 12368 // practice that one of the condition inputs to the select is also one of 12369 // the outputs, we currently can't deal with this. 12370 if (User->getOpcode() == ISD::SELECT) { 12371 if (User->getOperand(0) == Inputs[i]) 12372 return SDValue(); 12373 } else if (User->getOpcode() == ISD::SELECT_CC) { 12374 if (User->getOperand(0) == Inputs[i] || 12375 User->getOperand(1) == Inputs[i]) 12376 return SDValue(); 12377 } 12378 } 12379 } 12380 12381 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) { 12382 for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(), 12383 UE = PromOps[i].getNode()->use_end(); 12384 UI != UE; ++UI) { 12385 SDNode *User = *UI; 12386 if (User != N && !Visited.count(User)) 12387 return SDValue(); 12388 12389 // Make sure that we're not going to promote the non-output-value 12390 // operand(s) or SELECT or SELECT_CC. 12391 // FIXME: Although we could sometimes handle this, and it does occur in 12392 // practice that one of the condition inputs to the select is also one of 12393 // the outputs, we currently can't deal with this. 12394 if (User->getOpcode() == ISD::SELECT) { 12395 if (User->getOperand(0) == PromOps[i]) 12396 return SDValue(); 12397 } else if (User->getOpcode() == ISD::SELECT_CC) { 12398 if (User->getOperand(0) == PromOps[i] || 12399 User->getOperand(1) == PromOps[i]) 12400 return SDValue(); 12401 } 12402 } 12403 } 12404 12405 // Replace all inputs with the extension operand. 12406 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 12407 // Constants may have users outside the cluster of to-be-promoted nodes, 12408 // and so we need to replace those as we do the promotions. 12409 if (isa<ConstantSDNode>(Inputs[i])) 12410 continue; 12411 else 12412 DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0)); 12413 } 12414 12415 std::list<HandleSDNode> PromOpHandles; 12416 for (auto &PromOp : PromOps) 12417 PromOpHandles.emplace_back(PromOp); 12418 12419 // Replace all operations (these are all the same, but have a different 12420 // (i1) return type). DAG.getNode will validate that the types of 12421 // a binary operator match, so go through the list in reverse so that 12422 // we've likely promoted both operands first. Any intermediate truncations or 12423 // extensions disappear. 12424 while (!PromOpHandles.empty()) { 12425 SDValue PromOp = PromOpHandles.back().getValue(); 12426 PromOpHandles.pop_back(); 12427 12428 if (PromOp.getOpcode() == ISD::TRUNCATE || 12429 PromOp.getOpcode() == ISD::SIGN_EXTEND || 12430 PromOp.getOpcode() == ISD::ZERO_EXTEND || 12431 PromOp.getOpcode() == ISD::ANY_EXTEND) { 12432 if (!isa<ConstantSDNode>(PromOp.getOperand(0)) && 12433 PromOp.getOperand(0).getValueType() != MVT::i1) { 12434 // The operand is not yet ready (see comment below). 12435 PromOpHandles.emplace_front(PromOp); 12436 continue; 12437 } 12438 12439 SDValue RepValue = PromOp.getOperand(0); 12440 if (isa<ConstantSDNode>(RepValue)) 12441 RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue); 12442 12443 DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue); 12444 continue; 12445 } 12446 12447 unsigned C; 12448 switch (PromOp.getOpcode()) { 12449 default: C = 0; break; 12450 case ISD::SELECT: C = 1; break; 12451 case ISD::SELECT_CC: C = 2; break; 12452 } 12453 12454 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) && 12455 PromOp.getOperand(C).getValueType() != MVT::i1) || 12456 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) && 12457 PromOp.getOperand(C+1).getValueType() != MVT::i1)) { 12458 // The to-be-promoted operands of this node have not yet been 12459 // promoted (this should be rare because we're going through the 12460 // list backward, but if one of the operands has several users in 12461 // this cluster of to-be-promoted nodes, it is possible). 12462 PromOpHandles.emplace_front(PromOp); 12463 continue; 12464 } 12465 12466 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(), 12467 PromOp.getNode()->op_end()); 12468 12469 // If there are any constant inputs, make sure they're replaced now. 12470 for (unsigned i = 0; i < 2; ++i) 12471 if (isa<ConstantSDNode>(Ops[C+i])) 12472 Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]); 12473 12474 DAG.ReplaceAllUsesOfValueWith(PromOp, 12475 DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops)); 12476 } 12477 12478 // Now we're left with the initial truncation itself. 12479 if (N->getOpcode() == ISD::TRUNCATE) 12480 return N->getOperand(0); 12481 12482 // Otherwise, this is a comparison. The operands to be compared have just 12483 // changed type (to i1), but everything else is the same. 12484 return SDValue(N, 0); 12485 } 12486 12487 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N, 12488 DAGCombinerInfo &DCI) const { 12489 SelectionDAG &DAG = DCI.DAG; 12490 SDLoc dl(N); 12491 12492 // If we're tracking CR bits, we need to be careful that we don't have: 12493 // zext(binary-ops(trunc(x), trunc(y))) 12494 // or 12495 // zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...) 12496 // such that we're unnecessarily moving things into CR bits that can more 12497 // efficiently stay in GPRs. Note that if we're not certain that the high 12498 // bits are set as required by the final extension, we still may need to do 12499 // some masking to get the proper behavior. 12500 12501 // This same functionality is important on PPC64 when dealing with 12502 // 32-to-64-bit extensions; these occur often when 32-bit values are used as 12503 // the return values of functions. Because it is so similar, it is handled 12504 // here as well. 12505 12506 if (N->getValueType(0) != MVT::i32 && 12507 N->getValueType(0) != MVT::i64) 12508 return SDValue(); 12509 12510 if (!((N->getOperand(0).getValueType() == MVT::i1 && Subtarget.useCRBits()) || 12511 (N->getOperand(0).getValueType() == MVT::i32 && Subtarget.isPPC64()))) 12512 return SDValue(); 12513 12514 if (N->getOperand(0).getOpcode() != ISD::AND && 12515 N->getOperand(0).getOpcode() != ISD::OR && 12516 N->getOperand(0).getOpcode() != ISD::XOR && 12517 N->getOperand(0).getOpcode() != ISD::SELECT && 12518 N->getOperand(0).getOpcode() != ISD::SELECT_CC) 12519 return SDValue(); 12520 12521 SmallVector<SDValue, 4> Inputs; 12522 SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps; 12523 SmallPtrSet<SDNode *, 16> Visited; 12524 12525 // Visit all inputs, collect all binary operations (and, or, xor and 12526 // select) that are all fed by truncations. 12527 while (!BinOps.empty()) { 12528 SDValue BinOp = BinOps.back(); 12529 BinOps.pop_back(); 12530 12531 if (!Visited.insert(BinOp.getNode()).second) 12532 continue; 12533 12534 PromOps.push_back(BinOp); 12535 12536 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) { 12537 // The condition of the select is not promoted. 12538 if (BinOp.getOpcode() == ISD::SELECT && i == 0) 12539 continue; 12540 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3) 12541 continue; 12542 12543 if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE || 12544 isa<ConstantSDNode>(BinOp.getOperand(i))) { 12545 Inputs.push_back(BinOp.getOperand(i)); 12546 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND || 12547 BinOp.getOperand(i).getOpcode() == ISD::OR || 12548 BinOp.getOperand(i).getOpcode() == ISD::XOR || 12549 BinOp.getOperand(i).getOpcode() == ISD::SELECT || 12550 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) { 12551 BinOps.push_back(BinOp.getOperand(i)); 12552 } else { 12553 // We have an input that is not a truncation or another binary 12554 // operation; we'll abort this transformation. 12555 return SDValue(); 12556 } 12557 } 12558 } 12559 12560 // The operands of a select that must be truncated when the select is 12561 // promoted because the operand is actually part of the to-be-promoted set. 12562 DenseMap<SDNode *, EVT> SelectTruncOp[2]; 12563 12564 // Make sure that this is a self-contained cluster of operations (which 12565 // is not quite the same thing as saying that everything has only one 12566 // use). 12567 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 12568 if (isa<ConstantSDNode>(Inputs[i])) 12569 continue; 12570 12571 for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(), 12572 UE = Inputs[i].getNode()->use_end(); 12573 UI != UE; ++UI) { 12574 SDNode *User = *UI; 12575 if (User != N && !Visited.count(User)) 12576 return SDValue(); 12577 12578 // If we're going to promote the non-output-value operand(s) or SELECT or 12579 // SELECT_CC, record them for truncation. 12580 if (User->getOpcode() == ISD::SELECT) { 12581 if (User->getOperand(0) == Inputs[i]) 12582 SelectTruncOp[0].insert(std::make_pair(User, 12583 User->getOperand(0).getValueType())); 12584 } else if (User->getOpcode() == ISD::SELECT_CC) { 12585 if (User->getOperand(0) == Inputs[i]) 12586 SelectTruncOp[0].insert(std::make_pair(User, 12587 User->getOperand(0).getValueType())); 12588 if (User->getOperand(1) == Inputs[i]) 12589 SelectTruncOp[1].insert(std::make_pair(User, 12590 User->getOperand(1).getValueType())); 12591 } 12592 } 12593 } 12594 12595 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) { 12596 for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(), 12597 UE = PromOps[i].getNode()->use_end(); 12598 UI != UE; ++UI) { 12599 SDNode *User = *UI; 12600 if (User != N && !Visited.count(User)) 12601 return SDValue(); 12602 12603 // If we're going to promote the non-output-value operand(s) or SELECT or 12604 // SELECT_CC, record them for truncation. 12605 if (User->getOpcode() == ISD::SELECT) { 12606 if (User->getOperand(0) == PromOps[i]) 12607 SelectTruncOp[0].insert(std::make_pair(User, 12608 User->getOperand(0).getValueType())); 12609 } else if (User->getOpcode() == ISD::SELECT_CC) { 12610 if (User->getOperand(0) == PromOps[i]) 12611 SelectTruncOp[0].insert(std::make_pair(User, 12612 User->getOperand(0).getValueType())); 12613 if (User->getOperand(1) == PromOps[i]) 12614 SelectTruncOp[1].insert(std::make_pair(User, 12615 User->getOperand(1).getValueType())); 12616 } 12617 } 12618 } 12619 12620 unsigned PromBits = N->getOperand(0).getValueSizeInBits(); 12621 bool ReallyNeedsExt = false; 12622 if (N->getOpcode() != ISD::ANY_EXTEND) { 12623 // If all of the inputs are not already sign/zero extended, then 12624 // we'll still need to do that at the end. 12625 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 12626 if (isa<ConstantSDNode>(Inputs[i])) 12627 continue; 12628 12629 unsigned OpBits = 12630 Inputs[i].getOperand(0).getValueSizeInBits(); 12631 assert(PromBits < OpBits && "Truncation not to a smaller bit count?"); 12632 12633 if ((N->getOpcode() == ISD::ZERO_EXTEND && 12634 !DAG.MaskedValueIsZero(Inputs[i].getOperand(0), 12635 APInt::getHighBitsSet(OpBits, 12636 OpBits-PromBits))) || 12637 (N->getOpcode() == ISD::SIGN_EXTEND && 12638 DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) < 12639 (OpBits-(PromBits-1)))) { 12640 ReallyNeedsExt = true; 12641 break; 12642 } 12643 } 12644 } 12645 12646 // Replace all inputs, either with the truncation operand, or a 12647 // truncation or extension to the final output type. 12648 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 12649 // Constant inputs need to be replaced with the to-be-promoted nodes that 12650 // use them because they might have users outside of the cluster of 12651 // promoted nodes. 12652 if (isa<ConstantSDNode>(Inputs[i])) 12653 continue; 12654 12655 SDValue InSrc = Inputs[i].getOperand(0); 12656 if (Inputs[i].getValueType() == N->getValueType(0)) 12657 DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc); 12658 else if (N->getOpcode() == ISD::SIGN_EXTEND) 12659 DAG.ReplaceAllUsesOfValueWith(Inputs[i], 12660 DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0))); 12661 else if (N->getOpcode() == ISD::ZERO_EXTEND) 12662 DAG.ReplaceAllUsesOfValueWith(Inputs[i], 12663 DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0))); 12664 else 12665 DAG.ReplaceAllUsesOfValueWith(Inputs[i], 12666 DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0))); 12667 } 12668 12669 std::list<HandleSDNode> PromOpHandles; 12670 for (auto &PromOp : PromOps) 12671 PromOpHandles.emplace_back(PromOp); 12672 12673 // Replace all operations (these are all the same, but have a different 12674 // (promoted) return type). DAG.getNode will validate that the types of 12675 // a binary operator match, so go through the list in reverse so that 12676 // we've likely promoted both operands first. 12677 while (!PromOpHandles.empty()) { 12678 SDValue PromOp = PromOpHandles.back().getValue(); 12679 PromOpHandles.pop_back(); 12680 12681 unsigned C; 12682 switch (PromOp.getOpcode()) { 12683 default: C = 0; break; 12684 case ISD::SELECT: C = 1; break; 12685 case ISD::SELECT_CC: C = 2; break; 12686 } 12687 12688 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) && 12689 PromOp.getOperand(C).getValueType() != N->getValueType(0)) || 12690 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) && 12691 PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) { 12692 // The to-be-promoted operands of this node have not yet been 12693 // promoted (this should be rare because we're going through the 12694 // list backward, but if one of the operands has several users in 12695 // this cluster of to-be-promoted nodes, it is possible). 12696 PromOpHandles.emplace_front(PromOp); 12697 continue; 12698 } 12699 12700 // For SELECT and SELECT_CC nodes, we do a similar check for any 12701 // to-be-promoted comparison inputs. 12702 if (PromOp.getOpcode() == ISD::SELECT || 12703 PromOp.getOpcode() == ISD::SELECT_CC) { 12704 if ((SelectTruncOp[0].count(PromOp.getNode()) && 12705 PromOp.getOperand(0).getValueType() != N->getValueType(0)) || 12706 (SelectTruncOp[1].count(PromOp.getNode()) && 12707 PromOp.getOperand(1).getValueType() != N->getValueType(0))) { 12708 PromOpHandles.emplace_front(PromOp); 12709 continue; 12710 } 12711 } 12712 12713 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(), 12714 PromOp.getNode()->op_end()); 12715 12716 // If this node has constant inputs, then they'll need to be promoted here. 12717 for (unsigned i = 0; i < 2; ++i) { 12718 if (!isa<ConstantSDNode>(Ops[C+i])) 12719 continue; 12720 if (Ops[C+i].getValueType() == N->getValueType(0)) 12721 continue; 12722 12723 if (N->getOpcode() == ISD::SIGN_EXTEND) 12724 Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); 12725 else if (N->getOpcode() == ISD::ZERO_EXTEND) 12726 Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); 12727 else 12728 Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); 12729 } 12730 12731 // If we've promoted the comparison inputs of a SELECT or SELECT_CC, 12732 // truncate them again to the original value type. 12733 if (PromOp.getOpcode() == ISD::SELECT || 12734 PromOp.getOpcode() == ISD::SELECT_CC) { 12735 auto SI0 = SelectTruncOp[0].find(PromOp.getNode()); 12736 if (SI0 != SelectTruncOp[0].end()) 12737 Ops[0] = DAG.getNode(ISD::TRUNCATE, dl, SI0->second, Ops[0]); 12738 auto SI1 = SelectTruncOp[1].find(PromOp.getNode()); 12739 if (SI1 != SelectTruncOp[1].end()) 12740 Ops[1] = DAG.getNode(ISD::TRUNCATE, dl, SI1->second, Ops[1]); 12741 } 12742 12743 DAG.ReplaceAllUsesOfValueWith(PromOp, 12744 DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops)); 12745 } 12746 12747 // Now we're left with the initial extension itself. 12748 if (!ReallyNeedsExt) 12749 return N->getOperand(0); 12750 12751 // To zero extend, just mask off everything except for the first bit (in the 12752 // i1 case). 12753 if (N->getOpcode() == ISD::ZERO_EXTEND) 12754 return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0), 12755 DAG.getConstant(APInt::getLowBitsSet( 12756 N->getValueSizeInBits(0), PromBits), 12757 dl, N->getValueType(0))); 12758 12759 assert(N->getOpcode() == ISD::SIGN_EXTEND && 12760 "Invalid extension type"); 12761 EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0), DAG.getDataLayout()); 12762 SDValue ShiftCst = 12763 DAG.getConstant(N->getValueSizeInBits(0) - PromBits, dl, ShiftAmountTy); 12764 return DAG.getNode( 12765 ISD::SRA, dl, N->getValueType(0), 12766 DAG.getNode(ISD::SHL, dl, N->getValueType(0), N->getOperand(0), ShiftCst), 12767 ShiftCst); 12768 } 12769 12770 SDValue PPCTargetLowering::combineSetCC(SDNode *N, 12771 DAGCombinerInfo &DCI) const { 12772 assert(N->getOpcode() == ISD::SETCC && 12773 "Should be called with a SETCC node"); 12774 12775 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 12776 if (CC == ISD::SETNE || CC == ISD::SETEQ) { 12777 SDValue LHS = N->getOperand(0); 12778 SDValue RHS = N->getOperand(1); 12779 12780 // If there is a '0 - y' pattern, canonicalize the pattern to the RHS. 12781 if (LHS.getOpcode() == ISD::SUB && isNullConstant(LHS.getOperand(0)) && 12782 LHS.hasOneUse()) 12783 std::swap(LHS, RHS); 12784 12785 // x == 0-y --> x+y == 0 12786 // x != 0-y --> x+y != 0 12787 if (RHS.getOpcode() == ISD::SUB && isNullConstant(RHS.getOperand(0)) && 12788 RHS.hasOneUse()) { 12789 SDLoc DL(N); 12790 SelectionDAG &DAG = DCI.DAG; 12791 EVT VT = N->getValueType(0); 12792 EVT OpVT = LHS.getValueType(); 12793 SDValue Add = DAG.getNode(ISD::ADD, DL, OpVT, LHS, RHS.getOperand(1)); 12794 return DAG.getSetCC(DL, VT, Add, DAG.getConstant(0, DL, OpVT), CC); 12795 } 12796 } 12797 12798 return DAGCombineTruncBoolExt(N, DCI); 12799 } 12800 12801 // Is this an extending load from an f32 to an f64? 12802 static bool isFPExtLoad(SDValue Op) { 12803 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op.getNode())) 12804 return LD->getExtensionType() == ISD::EXTLOAD && 12805 Op.getValueType() == MVT::f64; 12806 return false; 12807 } 12808 12809 /// Reduces the number of fp-to-int conversion when building a vector. 12810 /// 12811 /// If this vector is built out of floating to integer conversions, 12812 /// transform it to a vector built out of floating point values followed by a 12813 /// single floating to integer conversion of the vector. 12814 /// Namely (build_vector (fptosi $A), (fptosi $B), ...) 12815 /// becomes (fptosi (build_vector ($A, $B, ...))) 12816 SDValue PPCTargetLowering:: 12817 combineElementTruncationToVectorTruncation(SDNode *N, 12818 DAGCombinerInfo &DCI) const { 12819 assert(N->getOpcode() == ISD::BUILD_VECTOR && 12820 "Should be called with a BUILD_VECTOR node"); 12821 12822 SelectionDAG &DAG = DCI.DAG; 12823 SDLoc dl(N); 12824 12825 SDValue FirstInput = N->getOperand(0); 12826 assert(FirstInput.getOpcode() == PPCISD::MFVSR && 12827 "The input operand must be an fp-to-int conversion."); 12828 12829 // This combine happens after legalization so the fp_to_[su]i nodes are 12830 // already converted to PPCSISD nodes. 12831 unsigned FirstConversion = FirstInput.getOperand(0).getOpcode(); 12832 if (FirstConversion == PPCISD::FCTIDZ || 12833 FirstConversion == PPCISD::FCTIDUZ || 12834 FirstConversion == PPCISD::FCTIWZ || 12835 FirstConversion == PPCISD::FCTIWUZ) { 12836 bool IsSplat = true; 12837 bool Is32Bit = FirstConversion == PPCISD::FCTIWZ || 12838 FirstConversion == PPCISD::FCTIWUZ; 12839 EVT SrcVT = FirstInput.getOperand(0).getValueType(); 12840 SmallVector<SDValue, 4> Ops; 12841 EVT TargetVT = N->getValueType(0); 12842 for (int i = 0, e = N->getNumOperands(); i < e; ++i) { 12843 SDValue NextOp = N->getOperand(i); 12844 if (NextOp.getOpcode() != PPCISD::MFVSR) 12845 return SDValue(); 12846 unsigned NextConversion = NextOp.getOperand(0).getOpcode(); 12847 if (NextConversion != FirstConversion) 12848 return SDValue(); 12849 // If we are converting to 32-bit integers, we need to add an FP_ROUND. 12850 // This is not valid if the input was originally double precision. It is 12851 // also not profitable to do unless this is an extending load in which 12852 // case doing this combine will allow us to combine consecutive loads. 12853 if (Is32Bit && !isFPExtLoad(NextOp.getOperand(0).getOperand(0))) 12854 return SDValue(); 12855 if (N->getOperand(i) != FirstInput) 12856 IsSplat = false; 12857 } 12858 12859 // If this is a splat, we leave it as-is since there will be only a single 12860 // fp-to-int conversion followed by a splat of the integer. This is better 12861 // for 32-bit and smaller ints and neutral for 64-bit ints. 12862 if (IsSplat) 12863 return SDValue(); 12864 12865 // Now that we know we have the right type of node, get its operands 12866 for (int i = 0, e = N->getNumOperands(); i < e; ++i) { 12867 SDValue In = N->getOperand(i).getOperand(0); 12868 if (Is32Bit) { 12869 // For 32-bit values, we need to add an FP_ROUND node (if we made it 12870 // here, we know that all inputs are extending loads so this is safe). 12871 if (In.isUndef()) 12872 Ops.push_back(DAG.getUNDEF(SrcVT)); 12873 else { 12874 SDValue Trunc = DAG.getNode(ISD::FP_ROUND, dl, 12875 MVT::f32, In.getOperand(0), 12876 DAG.getIntPtrConstant(1, dl)); 12877 Ops.push_back(Trunc); 12878 } 12879 } else 12880 Ops.push_back(In.isUndef() ? DAG.getUNDEF(SrcVT) : In.getOperand(0)); 12881 } 12882 12883 unsigned Opcode; 12884 if (FirstConversion == PPCISD::FCTIDZ || 12885 FirstConversion == PPCISD::FCTIWZ) 12886 Opcode = ISD::FP_TO_SINT; 12887 else 12888 Opcode = ISD::FP_TO_UINT; 12889 12890 EVT NewVT = TargetVT == MVT::v2i64 ? MVT::v2f64 : MVT::v4f32; 12891 SDValue BV = DAG.getBuildVector(NewVT, dl, Ops); 12892 return DAG.getNode(Opcode, dl, TargetVT, BV); 12893 } 12894 return SDValue(); 12895 } 12896 12897 /// Reduce the number of loads when building a vector. 12898 /// 12899 /// Building a vector out of multiple loads can be converted to a load 12900 /// of the vector type if the loads are consecutive. If the loads are 12901 /// consecutive but in descending order, a shuffle is added at the end 12902 /// to reorder the vector. 12903 static SDValue combineBVOfConsecutiveLoads(SDNode *N, SelectionDAG &DAG) { 12904 assert(N->getOpcode() == ISD::BUILD_VECTOR && 12905 "Should be called with a BUILD_VECTOR node"); 12906 12907 SDLoc dl(N); 12908 12909 // Return early for non byte-sized type, as they can't be consecutive. 12910 if (!N->getValueType(0).getVectorElementType().isByteSized()) 12911 return SDValue(); 12912 12913 bool InputsAreConsecutiveLoads = true; 12914 bool InputsAreReverseConsecutive = true; 12915 unsigned ElemSize = N->getValueType(0).getScalarType().getStoreSize(); 12916 SDValue FirstInput = N->getOperand(0); 12917 bool IsRoundOfExtLoad = false; 12918 12919 if (FirstInput.getOpcode() == ISD::FP_ROUND && 12920 FirstInput.getOperand(0).getOpcode() == ISD::LOAD) { 12921 LoadSDNode *LD = dyn_cast<LoadSDNode>(FirstInput.getOperand(0)); 12922 IsRoundOfExtLoad = LD->getExtensionType() == ISD::EXTLOAD; 12923 } 12924 // Not a build vector of (possibly fp_rounded) loads. 12925 if ((!IsRoundOfExtLoad && FirstInput.getOpcode() != ISD::LOAD) || 12926 N->getNumOperands() == 1) 12927 return SDValue(); 12928 12929 for (int i = 1, e = N->getNumOperands(); i < e; ++i) { 12930 // If any inputs are fp_round(extload), they all must be. 12931 if (IsRoundOfExtLoad && N->getOperand(i).getOpcode() != ISD::FP_ROUND) 12932 return SDValue(); 12933 12934 SDValue NextInput = IsRoundOfExtLoad ? N->getOperand(i).getOperand(0) : 12935 N->getOperand(i); 12936 if (NextInput.getOpcode() != ISD::LOAD) 12937 return SDValue(); 12938 12939 SDValue PreviousInput = 12940 IsRoundOfExtLoad ? N->getOperand(i-1).getOperand(0) : N->getOperand(i-1); 12941 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(PreviousInput); 12942 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(NextInput); 12943 12944 // If any inputs are fp_round(extload), they all must be. 12945 if (IsRoundOfExtLoad && LD2->getExtensionType() != ISD::EXTLOAD) 12946 return SDValue(); 12947 12948 if (!isConsecutiveLS(LD2, LD1, ElemSize, 1, DAG)) 12949 InputsAreConsecutiveLoads = false; 12950 if (!isConsecutiveLS(LD1, LD2, ElemSize, 1, DAG)) 12951 InputsAreReverseConsecutive = false; 12952 12953 // Exit early if the loads are neither consecutive nor reverse consecutive. 12954 if (!InputsAreConsecutiveLoads && !InputsAreReverseConsecutive) 12955 return SDValue(); 12956 } 12957 12958 assert(!(InputsAreConsecutiveLoads && InputsAreReverseConsecutive) && 12959 "The loads cannot be both consecutive and reverse consecutive."); 12960 12961 SDValue FirstLoadOp = 12962 IsRoundOfExtLoad ? FirstInput.getOperand(0) : FirstInput; 12963 SDValue LastLoadOp = 12964 IsRoundOfExtLoad ? N->getOperand(N->getNumOperands()-1).getOperand(0) : 12965 N->getOperand(N->getNumOperands()-1); 12966 12967 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(FirstLoadOp); 12968 LoadSDNode *LDL = dyn_cast<LoadSDNode>(LastLoadOp); 12969 if (InputsAreConsecutiveLoads) { 12970 assert(LD1 && "Input needs to be a LoadSDNode."); 12971 return DAG.getLoad(N->getValueType(0), dl, LD1->getChain(), 12972 LD1->getBasePtr(), LD1->getPointerInfo(), 12973 LD1->getAlignment()); 12974 } 12975 if (InputsAreReverseConsecutive) { 12976 assert(LDL && "Input needs to be a LoadSDNode."); 12977 SDValue Load = DAG.getLoad(N->getValueType(0), dl, LDL->getChain(), 12978 LDL->getBasePtr(), LDL->getPointerInfo(), 12979 LDL->getAlignment()); 12980 SmallVector<int, 16> Ops; 12981 for (int i = N->getNumOperands() - 1; i >= 0; i--) 12982 Ops.push_back(i); 12983 12984 return DAG.getVectorShuffle(N->getValueType(0), dl, Load, 12985 DAG.getUNDEF(N->getValueType(0)), Ops); 12986 } 12987 return SDValue(); 12988 } 12989 12990 // This function adds the required vector_shuffle needed to get 12991 // the elements of the vector extract in the correct position 12992 // as specified by the CorrectElems encoding. 12993 static SDValue addShuffleForVecExtend(SDNode *N, SelectionDAG &DAG, 12994 SDValue Input, uint64_t Elems, 12995 uint64_t CorrectElems) { 12996 SDLoc dl(N); 12997 12998 unsigned NumElems = Input.getValueType().getVectorNumElements(); 12999 SmallVector<int, 16> ShuffleMask(NumElems, -1); 13000 13001 // Knowing the element indices being extracted from the original 13002 // vector and the order in which they're being inserted, just put 13003 // them at element indices required for the instruction. 13004 for (unsigned i = 0; i < N->getNumOperands(); i++) { 13005 if (DAG.getDataLayout().isLittleEndian()) 13006 ShuffleMask[CorrectElems & 0xF] = Elems & 0xF; 13007 else 13008 ShuffleMask[(CorrectElems & 0xF0) >> 4] = (Elems & 0xF0) >> 4; 13009 CorrectElems = CorrectElems >> 8; 13010 Elems = Elems >> 8; 13011 } 13012 13013 SDValue Shuffle = 13014 DAG.getVectorShuffle(Input.getValueType(), dl, Input, 13015 DAG.getUNDEF(Input.getValueType()), ShuffleMask); 13016 13017 EVT Ty = N->getValueType(0); 13018 SDValue BV = DAG.getNode(PPCISD::SExtVElems, dl, Ty, Shuffle); 13019 return BV; 13020 } 13021 13022 // Look for build vector patterns where input operands come from sign 13023 // extended vector_extract elements of specific indices. If the correct indices 13024 // aren't used, add a vector shuffle to fix up the indices and create a new 13025 // PPCISD:SExtVElems node which selects the vector sign extend instructions 13026 // during instruction selection. 13027 static SDValue combineBVOfVecSExt(SDNode *N, SelectionDAG &DAG) { 13028 // This array encodes the indices that the vector sign extend instructions 13029 // extract from when extending from one type to another for both BE and LE. 13030 // The right nibble of each byte corresponds to the LE incides. 13031 // and the left nibble of each byte corresponds to the BE incides. 13032 // For example: 0x3074B8FC byte->word 13033 // For LE: the allowed indices are: 0x0,0x4,0x8,0xC 13034 // For BE: the allowed indices are: 0x3,0x7,0xB,0xF 13035 // For example: 0x000070F8 byte->double word 13036 // For LE: the allowed indices are: 0x0,0x8 13037 // For BE: the allowed indices are: 0x7,0xF 13038 uint64_t TargetElems[] = { 13039 0x3074B8FC, // b->w 13040 0x000070F8, // b->d 13041 0x10325476, // h->w 13042 0x00003074, // h->d 13043 0x00001032, // w->d 13044 }; 13045 13046 uint64_t Elems = 0; 13047 int Index; 13048 SDValue Input; 13049 13050 auto isSExtOfVecExtract = [&](SDValue Op) -> bool { 13051 if (!Op) 13052 return false; 13053 if (Op.getOpcode() != ISD::SIGN_EXTEND && 13054 Op.getOpcode() != ISD::SIGN_EXTEND_INREG) 13055 return false; 13056 13057 // A SIGN_EXTEND_INREG might be fed by an ANY_EXTEND to produce a value 13058 // of the right width. 13059 SDValue Extract = Op.getOperand(0); 13060 if (Extract.getOpcode() == ISD::ANY_EXTEND) 13061 Extract = Extract.getOperand(0); 13062 if (Extract.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 13063 return false; 13064 13065 ConstantSDNode *ExtOp = dyn_cast<ConstantSDNode>(Extract.getOperand(1)); 13066 if (!ExtOp) 13067 return false; 13068 13069 Index = ExtOp->getZExtValue(); 13070 if (Input && Input != Extract.getOperand(0)) 13071 return false; 13072 13073 if (!Input) 13074 Input = Extract.getOperand(0); 13075 13076 Elems = Elems << 8; 13077 Index = DAG.getDataLayout().isLittleEndian() ? Index : Index << 4; 13078 Elems |= Index; 13079 13080 return true; 13081 }; 13082 13083 // If the build vector operands aren't sign extended vector extracts, 13084 // of the same input vector, then return. 13085 for (unsigned i = 0; i < N->getNumOperands(); i++) { 13086 if (!isSExtOfVecExtract(N->getOperand(i))) { 13087 return SDValue(); 13088 } 13089 } 13090 13091 // If the vector extract indicies are not correct, add the appropriate 13092 // vector_shuffle. 13093 int TgtElemArrayIdx; 13094 int InputSize = Input.getValueType().getScalarSizeInBits(); 13095 int OutputSize = N->getValueType(0).getScalarSizeInBits(); 13096 if (InputSize + OutputSize == 40) 13097 TgtElemArrayIdx = 0; 13098 else if (InputSize + OutputSize == 72) 13099 TgtElemArrayIdx = 1; 13100 else if (InputSize + OutputSize == 48) 13101 TgtElemArrayIdx = 2; 13102 else if (InputSize + OutputSize == 80) 13103 TgtElemArrayIdx = 3; 13104 else if (InputSize + OutputSize == 96) 13105 TgtElemArrayIdx = 4; 13106 else 13107 return SDValue(); 13108 13109 uint64_t CorrectElems = TargetElems[TgtElemArrayIdx]; 13110 CorrectElems = DAG.getDataLayout().isLittleEndian() 13111 ? CorrectElems & 0x0F0F0F0F0F0F0F0F 13112 : CorrectElems & 0xF0F0F0F0F0F0F0F0; 13113 if (Elems != CorrectElems) { 13114 return addShuffleForVecExtend(N, DAG, Input, Elems, CorrectElems); 13115 } 13116 13117 // Regular lowering will catch cases where a shuffle is not needed. 13118 return SDValue(); 13119 } 13120 13121 SDValue PPCTargetLowering::DAGCombineBuildVector(SDNode *N, 13122 DAGCombinerInfo &DCI) const { 13123 assert(N->getOpcode() == ISD::BUILD_VECTOR && 13124 "Should be called with a BUILD_VECTOR node"); 13125 13126 SelectionDAG &DAG = DCI.DAG; 13127 SDLoc dl(N); 13128 13129 if (!Subtarget.hasVSX()) 13130 return SDValue(); 13131 13132 // The target independent DAG combiner will leave a build_vector of 13133 // float-to-int conversions intact. We can generate MUCH better code for 13134 // a float-to-int conversion of a vector of floats. 13135 SDValue FirstInput = N->getOperand(0); 13136 if (FirstInput.getOpcode() == PPCISD::MFVSR) { 13137 SDValue Reduced = combineElementTruncationToVectorTruncation(N, DCI); 13138 if (Reduced) 13139 return Reduced; 13140 } 13141 13142 // If we're building a vector out of consecutive loads, just load that 13143 // vector type. 13144 SDValue Reduced = combineBVOfConsecutiveLoads(N, DAG); 13145 if (Reduced) 13146 return Reduced; 13147 13148 // If we're building a vector out of extended elements from another vector 13149 // we have P9 vector integer extend instructions. The code assumes legal 13150 // input types (i.e. it can't handle things like v4i16) so do not run before 13151 // legalization. 13152 if (Subtarget.hasP9Altivec() && !DCI.isBeforeLegalize()) { 13153 Reduced = combineBVOfVecSExt(N, DAG); 13154 if (Reduced) 13155 return Reduced; 13156 } 13157 13158 13159 if (N->getValueType(0) != MVT::v2f64) 13160 return SDValue(); 13161 13162 // Looking for: 13163 // (build_vector ([su]int_to_fp (extractelt 0)), [su]int_to_fp (extractelt 1)) 13164 if (FirstInput.getOpcode() != ISD::SINT_TO_FP && 13165 FirstInput.getOpcode() != ISD::UINT_TO_FP) 13166 return SDValue(); 13167 if (N->getOperand(1).getOpcode() != ISD::SINT_TO_FP && 13168 N->getOperand(1).getOpcode() != ISD::UINT_TO_FP) 13169 return SDValue(); 13170 if (FirstInput.getOpcode() != N->getOperand(1).getOpcode()) 13171 return SDValue(); 13172 13173 SDValue Ext1 = FirstInput.getOperand(0); 13174 SDValue Ext2 = N->getOperand(1).getOperand(0); 13175 if(Ext1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 13176 Ext2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 13177 return SDValue(); 13178 13179 ConstantSDNode *Ext1Op = dyn_cast<ConstantSDNode>(Ext1.getOperand(1)); 13180 ConstantSDNode *Ext2Op = dyn_cast<ConstantSDNode>(Ext2.getOperand(1)); 13181 if (!Ext1Op || !Ext2Op) 13182 return SDValue(); 13183 if (Ext1.getOperand(0).getValueType() != MVT::v4i32 || 13184 Ext1.getOperand(0) != Ext2.getOperand(0)) 13185 return SDValue(); 13186 13187 int FirstElem = Ext1Op->getZExtValue(); 13188 int SecondElem = Ext2Op->getZExtValue(); 13189 int SubvecIdx; 13190 if (FirstElem == 0 && SecondElem == 1) 13191 SubvecIdx = Subtarget.isLittleEndian() ? 1 : 0; 13192 else if (FirstElem == 2 && SecondElem == 3) 13193 SubvecIdx = Subtarget.isLittleEndian() ? 0 : 1; 13194 else 13195 return SDValue(); 13196 13197 SDValue SrcVec = Ext1.getOperand(0); 13198 auto NodeType = (N->getOperand(1).getOpcode() == ISD::SINT_TO_FP) ? 13199 PPCISD::SINT_VEC_TO_FP : PPCISD::UINT_VEC_TO_FP; 13200 return DAG.getNode(NodeType, dl, MVT::v2f64, 13201 SrcVec, DAG.getIntPtrConstant(SubvecIdx, dl)); 13202 } 13203 13204 SDValue PPCTargetLowering::combineFPToIntToFP(SDNode *N, 13205 DAGCombinerInfo &DCI) const { 13206 assert((N->getOpcode() == ISD::SINT_TO_FP || 13207 N->getOpcode() == ISD::UINT_TO_FP) && 13208 "Need an int -> FP conversion node here"); 13209 13210 if (useSoftFloat() || !Subtarget.has64BitSupport()) 13211 return SDValue(); 13212 13213 SelectionDAG &DAG = DCI.DAG; 13214 SDLoc dl(N); 13215 SDValue Op(N, 0); 13216 13217 // Don't handle ppc_fp128 here or conversions that are out-of-range capable 13218 // from the hardware. 13219 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64) 13220 return SDValue(); 13221 if (Op.getOperand(0).getValueType().getSimpleVT() <= MVT(MVT::i1) || 13222 Op.getOperand(0).getValueType().getSimpleVT() > MVT(MVT::i64)) 13223 return SDValue(); 13224 13225 SDValue FirstOperand(Op.getOperand(0)); 13226 bool SubWordLoad = FirstOperand.getOpcode() == ISD::LOAD && 13227 (FirstOperand.getValueType() == MVT::i8 || 13228 FirstOperand.getValueType() == MVT::i16); 13229 if (Subtarget.hasP9Vector() && Subtarget.hasP9Altivec() && SubWordLoad) { 13230 bool Signed = N->getOpcode() == ISD::SINT_TO_FP; 13231 bool DstDouble = Op.getValueType() == MVT::f64; 13232 unsigned ConvOp = Signed ? 13233 (DstDouble ? PPCISD::FCFID : PPCISD::FCFIDS) : 13234 (DstDouble ? PPCISD::FCFIDU : PPCISD::FCFIDUS); 13235 SDValue WidthConst = 13236 DAG.getIntPtrConstant(FirstOperand.getValueType() == MVT::i8 ? 1 : 2, 13237 dl, false); 13238 LoadSDNode *LDN = cast<LoadSDNode>(FirstOperand.getNode()); 13239 SDValue Ops[] = { LDN->getChain(), LDN->getBasePtr(), WidthConst }; 13240 SDValue Ld = DAG.getMemIntrinsicNode(PPCISD::LXSIZX, dl, 13241 DAG.getVTList(MVT::f64, MVT::Other), 13242 Ops, MVT::i8, LDN->getMemOperand()); 13243 13244 // For signed conversion, we need to sign-extend the value in the VSR 13245 if (Signed) { 13246 SDValue ExtOps[] = { Ld, WidthConst }; 13247 SDValue Ext = DAG.getNode(PPCISD::VEXTS, dl, MVT::f64, ExtOps); 13248 return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ext); 13249 } else 13250 return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ld); 13251 } 13252 13253 13254 // For i32 intermediate values, unfortunately, the conversion functions 13255 // leave the upper 32 bits of the value are undefined. Within the set of 13256 // scalar instructions, we have no method for zero- or sign-extending the 13257 // value. Thus, we cannot handle i32 intermediate values here. 13258 if (Op.getOperand(0).getValueType() == MVT::i32) 13259 return SDValue(); 13260 13261 assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) && 13262 "UINT_TO_FP is supported only with FPCVT"); 13263 13264 // If we have FCFIDS, then use it when converting to single-precision. 13265 // Otherwise, convert to double-precision and then round. 13266 unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 13267 ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS 13268 : PPCISD::FCFIDS) 13269 : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU 13270 : PPCISD::FCFID); 13271 MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 13272 ? MVT::f32 13273 : MVT::f64; 13274 13275 // If we're converting from a float, to an int, and back to a float again, 13276 // then we don't need the store/load pair at all. 13277 if ((Op.getOperand(0).getOpcode() == ISD::FP_TO_UINT && 13278 Subtarget.hasFPCVT()) || 13279 (Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT)) { 13280 SDValue Src = Op.getOperand(0).getOperand(0); 13281 if (Src.getValueType() == MVT::f32) { 13282 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src); 13283 DCI.AddToWorklist(Src.getNode()); 13284 } else if (Src.getValueType() != MVT::f64) { 13285 // Make sure that we don't pick up a ppc_fp128 source value. 13286 return SDValue(); 13287 } 13288 13289 unsigned FCTOp = 13290 Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT ? PPCISD::FCTIDZ : 13291 PPCISD::FCTIDUZ; 13292 13293 SDValue Tmp = DAG.getNode(FCTOp, dl, MVT::f64, Src); 13294 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Tmp); 13295 13296 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) { 13297 FP = DAG.getNode(ISD::FP_ROUND, dl, 13298 MVT::f32, FP, DAG.getIntPtrConstant(0, dl)); 13299 DCI.AddToWorklist(FP.getNode()); 13300 } 13301 13302 return FP; 13303 } 13304 13305 return SDValue(); 13306 } 13307 13308 // expandVSXLoadForLE - Convert VSX loads (which may be intrinsics for 13309 // builtins) into loads with swaps. 13310 SDValue PPCTargetLowering::expandVSXLoadForLE(SDNode *N, 13311 DAGCombinerInfo &DCI) const { 13312 SelectionDAG &DAG = DCI.DAG; 13313 SDLoc dl(N); 13314 SDValue Chain; 13315 SDValue Base; 13316 MachineMemOperand *MMO; 13317 13318 switch (N->getOpcode()) { 13319 default: 13320 llvm_unreachable("Unexpected opcode for little endian VSX load"); 13321 case ISD::LOAD: { 13322 LoadSDNode *LD = cast<LoadSDNode>(N); 13323 Chain = LD->getChain(); 13324 Base = LD->getBasePtr(); 13325 MMO = LD->getMemOperand(); 13326 // If the MMO suggests this isn't a load of a full vector, leave 13327 // things alone. For a built-in, we have to make the change for 13328 // correctness, so if there is a size problem that will be a bug. 13329 if (MMO->getSize() < 16) 13330 return SDValue(); 13331 break; 13332 } 13333 case ISD::INTRINSIC_W_CHAIN: { 13334 MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N); 13335 Chain = Intrin->getChain(); 13336 // Similarly to the store case below, Intrin->getBasePtr() doesn't get 13337 // us what we want. Get operand 2 instead. 13338 Base = Intrin->getOperand(2); 13339 MMO = Intrin->getMemOperand(); 13340 break; 13341 } 13342 } 13343 13344 MVT VecTy = N->getValueType(0).getSimpleVT(); 13345 13346 // Do not expand to PPCISD::LXVD2X + PPCISD::XXSWAPD when the load is 13347 // aligned and the type is a vector with elements up to 4 bytes 13348 if (Subtarget.needsSwapsForVSXMemOps() && !(MMO->getAlignment()%16) 13349 && VecTy.getScalarSizeInBits() <= 32 ) { 13350 return SDValue(); 13351 } 13352 13353 SDValue LoadOps[] = { Chain, Base }; 13354 SDValue Load = DAG.getMemIntrinsicNode(PPCISD::LXVD2X, dl, 13355 DAG.getVTList(MVT::v2f64, MVT::Other), 13356 LoadOps, MVT::v2f64, MMO); 13357 13358 DCI.AddToWorklist(Load.getNode()); 13359 Chain = Load.getValue(1); 13360 SDValue Swap = DAG.getNode( 13361 PPCISD::XXSWAPD, dl, DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Load); 13362 DCI.AddToWorklist(Swap.getNode()); 13363 13364 // Add a bitcast if the resulting load type doesn't match v2f64. 13365 if (VecTy != MVT::v2f64) { 13366 SDValue N = DAG.getNode(ISD::BITCAST, dl, VecTy, Swap); 13367 DCI.AddToWorklist(N.getNode()); 13368 // Package {bitcast value, swap's chain} to match Load's shape. 13369 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VecTy, MVT::Other), 13370 N, Swap.getValue(1)); 13371 } 13372 13373 return Swap; 13374 } 13375 13376 // expandVSXStoreForLE - Convert VSX stores (which may be intrinsics for 13377 // builtins) into stores with swaps. 13378 SDValue PPCTargetLowering::expandVSXStoreForLE(SDNode *N, 13379 DAGCombinerInfo &DCI) const { 13380 SelectionDAG &DAG = DCI.DAG; 13381 SDLoc dl(N); 13382 SDValue Chain; 13383 SDValue Base; 13384 unsigned SrcOpnd; 13385 MachineMemOperand *MMO; 13386 13387 switch (N->getOpcode()) { 13388 default: 13389 llvm_unreachable("Unexpected opcode for little endian VSX store"); 13390 case ISD::STORE: { 13391 StoreSDNode *ST = cast<StoreSDNode>(N); 13392 Chain = ST->getChain(); 13393 Base = ST->getBasePtr(); 13394 MMO = ST->getMemOperand(); 13395 SrcOpnd = 1; 13396 // If the MMO suggests this isn't a store of a full vector, leave 13397 // things alone. For a built-in, we have to make the change for 13398 // correctness, so if there is a size problem that will be a bug. 13399 if (MMO->getSize() < 16) 13400 return SDValue(); 13401 break; 13402 } 13403 case ISD::INTRINSIC_VOID: { 13404 MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N); 13405 Chain = Intrin->getChain(); 13406 // Intrin->getBasePtr() oddly does not get what we want. 13407 Base = Intrin->getOperand(3); 13408 MMO = Intrin->getMemOperand(); 13409 SrcOpnd = 2; 13410 break; 13411 } 13412 } 13413 13414 SDValue Src = N->getOperand(SrcOpnd); 13415 MVT VecTy = Src.getValueType().getSimpleVT(); 13416 13417 // Do not expand to PPCISD::XXSWAPD and PPCISD::STXVD2X when the load is 13418 // aligned and the type is a vector with elements up to 4 bytes 13419 if (Subtarget.needsSwapsForVSXMemOps() && !(MMO->getAlignment()%16) 13420 && VecTy.getScalarSizeInBits() <= 32 ) { 13421 return SDValue(); 13422 } 13423 13424 // All stores are done as v2f64 and possible bit cast. 13425 if (VecTy != MVT::v2f64) { 13426 Src = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Src); 13427 DCI.AddToWorklist(Src.getNode()); 13428 } 13429 13430 SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl, 13431 DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Src); 13432 DCI.AddToWorklist(Swap.getNode()); 13433 Chain = Swap.getValue(1); 13434 SDValue StoreOps[] = { Chain, Swap, Base }; 13435 SDValue Store = DAG.getMemIntrinsicNode(PPCISD::STXVD2X, dl, 13436 DAG.getVTList(MVT::Other), 13437 StoreOps, VecTy, MMO); 13438 DCI.AddToWorklist(Store.getNode()); 13439 return Store; 13440 } 13441 13442 // Handle DAG combine for STORE (FP_TO_INT F). 13443 SDValue PPCTargetLowering::combineStoreFPToInt(SDNode *N, 13444 DAGCombinerInfo &DCI) const { 13445 13446 SelectionDAG &DAG = DCI.DAG; 13447 SDLoc dl(N); 13448 unsigned Opcode = N->getOperand(1).getOpcode(); 13449 13450 assert((Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT) 13451 && "Not a FP_TO_INT Instruction!"); 13452 13453 SDValue Val = N->getOperand(1).getOperand(0); 13454 EVT Op1VT = N->getOperand(1).getValueType(); 13455 EVT ResVT = Val.getValueType(); 13456 13457 // Floating point types smaller than 32 bits are not legal on Power. 13458 if (ResVT.getScalarSizeInBits() < 32) 13459 return SDValue(); 13460 13461 // Only perform combine for conversion to i64/i32 or power9 i16/i8. 13462 bool ValidTypeForStoreFltAsInt = 13463 (Op1VT == MVT::i32 || Op1VT == MVT::i64 || 13464 (Subtarget.hasP9Vector() && (Op1VT == MVT::i16 || Op1VT == MVT::i8))); 13465 13466 if (ResVT == MVT::ppcf128 || !Subtarget.hasP8Altivec() || 13467 cast<StoreSDNode>(N)->isTruncatingStore() || !ValidTypeForStoreFltAsInt) 13468 return SDValue(); 13469 13470 // Extend f32 values to f64 13471 if (ResVT.getScalarSizeInBits() == 32) { 13472 Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val); 13473 DCI.AddToWorklist(Val.getNode()); 13474 } 13475 13476 // Set signed or unsigned conversion opcode. 13477 unsigned ConvOpcode = (Opcode == ISD::FP_TO_SINT) ? 13478 PPCISD::FP_TO_SINT_IN_VSR : 13479 PPCISD::FP_TO_UINT_IN_VSR; 13480 13481 Val = DAG.getNode(ConvOpcode, 13482 dl, ResVT == MVT::f128 ? MVT::f128 : MVT::f64, Val); 13483 DCI.AddToWorklist(Val.getNode()); 13484 13485 // Set number of bytes being converted. 13486 unsigned ByteSize = Op1VT.getScalarSizeInBits() / 8; 13487 SDValue Ops[] = { N->getOperand(0), Val, N->getOperand(2), 13488 DAG.getIntPtrConstant(ByteSize, dl, false), 13489 DAG.getValueType(Op1VT) }; 13490 13491 Val = DAG.getMemIntrinsicNode(PPCISD::ST_VSR_SCAL_INT, dl, 13492 DAG.getVTList(MVT::Other), Ops, 13493 cast<StoreSDNode>(N)->getMemoryVT(), 13494 cast<StoreSDNode>(N)->getMemOperand()); 13495 13496 DCI.AddToWorklist(Val.getNode()); 13497 return Val; 13498 } 13499 13500 SDValue PPCTargetLowering::combineVReverseMemOP(ShuffleVectorSDNode *SVN, 13501 LSBaseSDNode *LSBase, 13502 DAGCombinerInfo &DCI) const { 13503 assert((ISD::isNormalLoad(LSBase) || ISD::isNormalStore(LSBase)) && 13504 "Not a reverse memop pattern!"); 13505 13506 auto IsElementReverse = [](const ShuffleVectorSDNode *SVN) -> bool { 13507 auto Mask = SVN->getMask(); 13508 int i = 0; 13509 auto I = Mask.rbegin(); 13510 auto E = Mask.rend(); 13511 13512 for (; I != E; ++I) { 13513 if (*I != i) 13514 return false; 13515 i++; 13516 } 13517 return true; 13518 }; 13519 13520 SelectionDAG &DAG = DCI.DAG; 13521 EVT VT = SVN->getValueType(0); 13522 13523 if (!isTypeLegal(VT) || !Subtarget.isLittleEndian() || !Subtarget.hasVSX()) 13524 return SDValue(); 13525 13526 // Before P9, we have PPCVSXSwapRemoval pass to hack the element order. 13527 // See comment in PPCVSXSwapRemoval.cpp. 13528 // It is conflict with PPCVSXSwapRemoval opt. So we don't do it. 13529 if (!Subtarget.hasP9Vector()) 13530 return SDValue(); 13531 13532 if(!IsElementReverse(SVN)) 13533 return SDValue(); 13534 13535 if (LSBase->getOpcode() == ISD::LOAD) { 13536 SDLoc dl(SVN); 13537 SDValue LoadOps[] = {LSBase->getChain(), LSBase->getBasePtr()}; 13538 return DAG.getMemIntrinsicNode( 13539 PPCISD::LOAD_VEC_BE, dl, DAG.getVTList(VT, MVT::Other), LoadOps, 13540 LSBase->getMemoryVT(), LSBase->getMemOperand()); 13541 } 13542 13543 if (LSBase->getOpcode() == ISD::STORE) { 13544 SDLoc dl(LSBase); 13545 SDValue StoreOps[] = {LSBase->getChain(), SVN->getOperand(0), 13546 LSBase->getBasePtr()}; 13547 return DAG.getMemIntrinsicNode( 13548 PPCISD::STORE_VEC_BE, dl, DAG.getVTList(MVT::Other), StoreOps, 13549 LSBase->getMemoryVT(), LSBase->getMemOperand()); 13550 } 13551 13552 llvm_unreachable("Expected a load or store node here"); 13553 } 13554 13555 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N, 13556 DAGCombinerInfo &DCI) const { 13557 SelectionDAG &DAG = DCI.DAG; 13558 SDLoc dl(N); 13559 switch (N->getOpcode()) { 13560 default: break; 13561 case ISD::ADD: 13562 return combineADD(N, DCI); 13563 case ISD::SHL: 13564 return combineSHL(N, DCI); 13565 case ISD::SRA: 13566 return combineSRA(N, DCI); 13567 case ISD::SRL: 13568 return combineSRL(N, DCI); 13569 case ISD::MUL: 13570 return combineMUL(N, DCI); 13571 case PPCISD::SHL: 13572 if (isNullConstant(N->getOperand(0))) // 0 << V -> 0. 13573 return N->getOperand(0); 13574 break; 13575 case PPCISD::SRL: 13576 if (isNullConstant(N->getOperand(0))) // 0 >>u V -> 0. 13577 return N->getOperand(0); 13578 break; 13579 case PPCISD::SRA: 13580 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) { 13581 if (C->isNullValue() || // 0 >>s V -> 0. 13582 C->isAllOnesValue()) // -1 >>s V -> -1. 13583 return N->getOperand(0); 13584 } 13585 break; 13586 case ISD::SIGN_EXTEND: 13587 case ISD::ZERO_EXTEND: 13588 case ISD::ANY_EXTEND: 13589 return DAGCombineExtBoolTrunc(N, DCI); 13590 case ISD::TRUNCATE: 13591 return combineTRUNCATE(N, DCI); 13592 case ISD::SETCC: 13593 if (SDValue CSCC = combineSetCC(N, DCI)) 13594 return CSCC; 13595 LLVM_FALLTHROUGH; 13596 case ISD::SELECT_CC: 13597 return DAGCombineTruncBoolExt(N, DCI); 13598 case ISD::SINT_TO_FP: 13599 case ISD::UINT_TO_FP: 13600 return combineFPToIntToFP(N, DCI); 13601 case ISD::VECTOR_SHUFFLE: 13602 if (ISD::isNormalLoad(N->getOperand(0).getNode())) { 13603 LSBaseSDNode* LSBase = cast<LSBaseSDNode>(N->getOperand(0)); 13604 return combineVReverseMemOP(cast<ShuffleVectorSDNode>(N), LSBase, DCI); 13605 } 13606 break; 13607 case ISD::STORE: { 13608 13609 EVT Op1VT = N->getOperand(1).getValueType(); 13610 unsigned Opcode = N->getOperand(1).getOpcode(); 13611 13612 if (Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT) { 13613 SDValue Val= combineStoreFPToInt(N, DCI); 13614 if (Val) 13615 return Val; 13616 } 13617 13618 if (Opcode == ISD::VECTOR_SHUFFLE && ISD::isNormalStore(N)) { 13619 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N->getOperand(1)); 13620 SDValue Val= combineVReverseMemOP(SVN, cast<LSBaseSDNode>(N), DCI); 13621 if (Val) 13622 return Val; 13623 } 13624 13625 // Turn STORE (BSWAP) -> sthbrx/stwbrx. 13626 if (cast<StoreSDNode>(N)->isUnindexed() && Opcode == ISD::BSWAP && 13627 N->getOperand(1).getNode()->hasOneUse() && 13628 (Op1VT == MVT::i32 || Op1VT == MVT::i16 || 13629 (Subtarget.hasLDBRX() && Subtarget.isPPC64() && Op1VT == MVT::i64))) { 13630 13631 // STBRX can only handle simple types and it makes no sense to store less 13632 // two bytes in byte-reversed order. 13633 EVT mVT = cast<StoreSDNode>(N)->getMemoryVT(); 13634 if (mVT.isExtended() || mVT.getSizeInBits() < 16) 13635 break; 13636 13637 SDValue BSwapOp = N->getOperand(1).getOperand(0); 13638 // Do an any-extend to 32-bits if this is a half-word input. 13639 if (BSwapOp.getValueType() == MVT::i16) 13640 BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp); 13641 13642 // If the type of BSWAP operand is wider than stored memory width 13643 // it need to be shifted to the right side before STBRX. 13644 if (Op1VT.bitsGT(mVT)) { 13645 int Shift = Op1VT.getSizeInBits() - mVT.getSizeInBits(); 13646 BSwapOp = DAG.getNode(ISD::SRL, dl, Op1VT, BSwapOp, 13647 DAG.getConstant(Shift, dl, MVT::i32)); 13648 // Need to truncate if this is a bswap of i64 stored as i32/i16. 13649 if (Op1VT == MVT::i64) 13650 BSwapOp = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BSwapOp); 13651 } 13652 13653 SDValue Ops[] = { 13654 N->getOperand(0), BSwapOp, N->getOperand(2), DAG.getValueType(mVT) 13655 }; 13656 return 13657 DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other), 13658 Ops, cast<StoreSDNode>(N)->getMemoryVT(), 13659 cast<StoreSDNode>(N)->getMemOperand()); 13660 } 13661 13662 // STORE Constant:i32<0> -> STORE<trunc to i32> Constant:i64<0> 13663 // So it can increase the chance of CSE constant construction. 13664 if (Subtarget.isPPC64() && !DCI.isBeforeLegalize() && 13665 isa<ConstantSDNode>(N->getOperand(1)) && Op1VT == MVT::i32) { 13666 // Need to sign-extended to 64-bits to handle negative values. 13667 EVT MemVT = cast<StoreSDNode>(N)->getMemoryVT(); 13668 uint64_t Val64 = SignExtend64(N->getConstantOperandVal(1), 13669 MemVT.getSizeInBits()); 13670 SDValue Const64 = DAG.getConstant(Val64, dl, MVT::i64); 13671 13672 // DAG.getTruncStore() can't be used here because it doesn't accept 13673 // the general (base + offset) addressing mode. 13674 // So we use UpdateNodeOperands and setTruncatingStore instead. 13675 DAG.UpdateNodeOperands(N, N->getOperand(0), Const64, N->getOperand(2), 13676 N->getOperand(3)); 13677 cast<StoreSDNode>(N)->setTruncatingStore(true); 13678 return SDValue(N, 0); 13679 } 13680 13681 // For little endian, VSX stores require generating xxswapd/lxvd2x. 13682 // Not needed on ISA 3.0 based CPUs since we have a non-permuting store. 13683 if (Op1VT.isSimple()) { 13684 MVT StoreVT = Op1VT.getSimpleVT(); 13685 if (Subtarget.needsSwapsForVSXMemOps() && 13686 (StoreVT == MVT::v2f64 || StoreVT == MVT::v2i64 || 13687 StoreVT == MVT::v4f32 || StoreVT == MVT::v4i32)) 13688 return expandVSXStoreForLE(N, DCI); 13689 } 13690 break; 13691 } 13692 case ISD::LOAD: { 13693 LoadSDNode *LD = cast<LoadSDNode>(N); 13694 EVT VT = LD->getValueType(0); 13695 13696 // For little endian, VSX loads require generating lxvd2x/xxswapd. 13697 // Not needed on ISA 3.0 based CPUs since we have a non-permuting load. 13698 if (VT.isSimple()) { 13699 MVT LoadVT = VT.getSimpleVT(); 13700 if (Subtarget.needsSwapsForVSXMemOps() && 13701 (LoadVT == MVT::v2f64 || LoadVT == MVT::v2i64 || 13702 LoadVT == MVT::v4f32 || LoadVT == MVT::v4i32)) 13703 return expandVSXLoadForLE(N, DCI); 13704 } 13705 13706 // We sometimes end up with a 64-bit integer load, from which we extract 13707 // two single-precision floating-point numbers. This happens with 13708 // std::complex<float>, and other similar structures, because of the way we 13709 // canonicalize structure copies. However, if we lack direct moves, 13710 // then the final bitcasts from the extracted integer values to the 13711 // floating-point numbers turn into store/load pairs. Even with direct moves, 13712 // just loading the two floating-point numbers is likely better. 13713 auto ReplaceTwoFloatLoad = [&]() { 13714 if (VT != MVT::i64) 13715 return false; 13716 13717 if (LD->getExtensionType() != ISD::NON_EXTLOAD || 13718 LD->isVolatile()) 13719 return false; 13720 13721 // We're looking for a sequence like this: 13722 // t13: i64,ch = load<LD8[%ref.tmp]> t0, t6, undef:i64 13723 // t16: i64 = srl t13, Constant:i32<32> 13724 // t17: i32 = truncate t16 13725 // t18: f32 = bitcast t17 13726 // t19: i32 = truncate t13 13727 // t20: f32 = bitcast t19 13728 13729 if (!LD->hasNUsesOfValue(2, 0)) 13730 return false; 13731 13732 auto UI = LD->use_begin(); 13733 while (UI.getUse().getResNo() != 0) ++UI; 13734 SDNode *Trunc = *UI++; 13735 while (UI.getUse().getResNo() != 0) ++UI; 13736 SDNode *RightShift = *UI; 13737 if (Trunc->getOpcode() != ISD::TRUNCATE) 13738 std::swap(Trunc, RightShift); 13739 13740 if (Trunc->getOpcode() != ISD::TRUNCATE || 13741 Trunc->getValueType(0) != MVT::i32 || 13742 !Trunc->hasOneUse()) 13743 return false; 13744 if (RightShift->getOpcode() != ISD::SRL || 13745 !isa<ConstantSDNode>(RightShift->getOperand(1)) || 13746 RightShift->getConstantOperandVal(1) != 32 || 13747 !RightShift->hasOneUse()) 13748 return false; 13749 13750 SDNode *Trunc2 = *RightShift->use_begin(); 13751 if (Trunc2->getOpcode() != ISD::TRUNCATE || 13752 Trunc2->getValueType(0) != MVT::i32 || 13753 !Trunc2->hasOneUse()) 13754 return false; 13755 13756 SDNode *Bitcast = *Trunc->use_begin(); 13757 SDNode *Bitcast2 = *Trunc2->use_begin(); 13758 13759 if (Bitcast->getOpcode() != ISD::BITCAST || 13760 Bitcast->getValueType(0) != MVT::f32) 13761 return false; 13762 if (Bitcast2->getOpcode() != ISD::BITCAST || 13763 Bitcast2->getValueType(0) != MVT::f32) 13764 return false; 13765 13766 if (Subtarget.isLittleEndian()) 13767 std::swap(Bitcast, Bitcast2); 13768 13769 // Bitcast has the second float (in memory-layout order) and Bitcast2 13770 // has the first one. 13771 13772 SDValue BasePtr = LD->getBasePtr(); 13773 if (LD->isIndexed()) { 13774 assert(LD->getAddressingMode() == ISD::PRE_INC && 13775 "Non-pre-inc AM on PPC?"); 13776 BasePtr = 13777 DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, 13778 LD->getOffset()); 13779 } 13780 13781 auto MMOFlags = 13782 LD->getMemOperand()->getFlags() & ~MachineMemOperand::MOVolatile; 13783 SDValue FloatLoad = DAG.getLoad(MVT::f32, dl, LD->getChain(), BasePtr, 13784 LD->getPointerInfo(), LD->getAlignment(), 13785 MMOFlags, LD->getAAInfo()); 13786 SDValue AddPtr = 13787 DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), 13788 BasePtr, DAG.getIntPtrConstant(4, dl)); 13789 SDValue FloatLoad2 = DAG.getLoad( 13790 MVT::f32, dl, SDValue(FloatLoad.getNode(), 1), AddPtr, 13791 LD->getPointerInfo().getWithOffset(4), 13792 MinAlign(LD->getAlignment(), 4), MMOFlags, LD->getAAInfo()); 13793 13794 if (LD->isIndexed()) { 13795 // Note that DAGCombine should re-form any pre-increment load(s) from 13796 // what is produced here if that makes sense. 13797 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), BasePtr); 13798 } 13799 13800 DCI.CombineTo(Bitcast2, FloatLoad); 13801 DCI.CombineTo(Bitcast, FloatLoad2); 13802 13803 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, LD->isIndexed() ? 2 : 1), 13804 SDValue(FloatLoad2.getNode(), 1)); 13805 return true; 13806 }; 13807 13808 if (ReplaceTwoFloatLoad()) 13809 return SDValue(N, 0); 13810 13811 EVT MemVT = LD->getMemoryVT(); 13812 Type *Ty = MemVT.getTypeForEVT(*DAG.getContext()); 13813 unsigned ABIAlignment = DAG.getDataLayout().getABITypeAlignment(Ty); 13814 Type *STy = MemVT.getScalarType().getTypeForEVT(*DAG.getContext()); 13815 unsigned ScalarABIAlignment = DAG.getDataLayout().getABITypeAlignment(STy); 13816 if (LD->isUnindexed() && VT.isVector() && 13817 ((Subtarget.hasAltivec() && ISD::isNON_EXTLoad(N) && 13818 // P8 and later hardware should just use LOAD. 13819 !Subtarget.hasP8Vector() && (VT == MVT::v16i8 || VT == MVT::v8i16 || 13820 VT == MVT::v4i32 || VT == MVT::v4f32)) || 13821 (Subtarget.hasQPX() && (VT == MVT::v4f64 || VT == MVT::v4f32) && 13822 LD->getAlignment() >= ScalarABIAlignment)) && 13823 LD->getAlignment() < ABIAlignment) { 13824 // This is a type-legal unaligned Altivec or QPX load. 13825 SDValue Chain = LD->getChain(); 13826 SDValue Ptr = LD->getBasePtr(); 13827 bool isLittleEndian = Subtarget.isLittleEndian(); 13828 13829 // This implements the loading of unaligned vectors as described in 13830 // the venerable Apple Velocity Engine overview. Specifically: 13831 // https://developer.apple.com/hardwaredrivers/ve/alignment.html 13832 // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html 13833 // 13834 // The general idea is to expand a sequence of one or more unaligned 13835 // loads into an alignment-based permutation-control instruction (lvsl 13836 // or lvsr), a series of regular vector loads (which always truncate 13837 // their input address to an aligned address), and a series of 13838 // permutations. The results of these permutations are the requested 13839 // loaded values. The trick is that the last "extra" load is not taken 13840 // from the address you might suspect (sizeof(vector) bytes after the 13841 // last requested load), but rather sizeof(vector) - 1 bytes after the 13842 // last requested vector. The point of this is to avoid a page fault if 13843 // the base address happened to be aligned. This works because if the 13844 // base address is aligned, then adding less than a full vector length 13845 // will cause the last vector in the sequence to be (re)loaded. 13846 // Otherwise, the next vector will be fetched as you might suspect was 13847 // necessary. 13848 13849 // We might be able to reuse the permutation generation from 13850 // a different base address offset from this one by an aligned amount. 13851 // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this 13852 // optimization later. 13853 Intrinsic::ID Intr, IntrLD, IntrPerm; 13854 MVT PermCntlTy, PermTy, LDTy; 13855 if (Subtarget.hasAltivec()) { 13856 Intr = isLittleEndian ? Intrinsic::ppc_altivec_lvsr : 13857 Intrinsic::ppc_altivec_lvsl; 13858 IntrLD = Intrinsic::ppc_altivec_lvx; 13859 IntrPerm = Intrinsic::ppc_altivec_vperm; 13860 PermCntlTy = MVT::v16i8; 13861 PermTy = MVT::v4i32; 13862 LDTy = MVT::v4i32; 13863 } else { 13864 Intr = MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlpcld : 13865 Intrinsic::ppc_qpx_qvlpcls; 13866 IntrLD = MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlfd : 13867 Intrinsic::ppc_qpx_qvlfs; 13868 IntrPerm = Intrinsic::ppc_qpx_qvfperm; 13869 PermCntlTy = MVT::v4f64; 13870 PermTy = MVT::v4f64; 13871 LDTy = MemVT.getSimpleVT(); 13872 } 13873 13874 SDValue PermCntl = BuildIntrinsicOp(Intr, Ptr, DAG, dl, PermCntlTy); 13875 13876 // Create the new MMO for the new base load. It is like the original MMO, 13877 // but represents an area in memory almost twice the vector size centered 13878 // on the original address. If the address is unaligned, we might start 13879 // reading up to (sizeof(vector)-1) bytes below the address of the 13880 // original unaligned load. 13881 MachineFunction &MF = DAG.getMachineFunction(); 13882 MachineMemOperand *BaseMMO = 13883 MF.getMachineMemOperand(LD->getMemOperand(), 13884 -(long)MemVT.getStoreSize()+1, 13885 2*MemVT.getStoreSize()-1); 13886 13887 // Create the new base load. 13888 SDValue LDXIntID = 13889 DAG.getTargetConstant(IntrLD, dl, getPointerTy(MF.getDataLayout())); 13890 SDValue BaseLoadOps[] = { Chain, LDXIntID, Ptr }; 13891 SDValue BaseLoad = 13892 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl, 13893 DAG.getVTList(PermTy, MVT::Other), 13894 BaseLoadOps, LDTy, BaseMMO); 13895 13896 // Note that the value of IncOffset (which is provided to the next 13897 // load's pointer info offset value, and thus used to calculate the 13898 // alignment), and the value of IncValue (which is actually used to 13899 // increment the pointer value) are different! This is because we 13900 // require the next load to appear to be aligned, even though it 13901 // is actually offset from the base pointer by a lesser amount. 13902 int IncOffset = VT.getSizeInBits() / 8; 13903 int IncValue = IncOffset; 13904 13905 // Walk (both up and down) the chain looking for another load at the real 13906 // (aligned) offset (the alignment of the other load does not matter in 13907 // this case). If found, then do not use the offset reduction trick, as 13908 // that will prevent the loads from being later combined (as they would 13909 // otherwise be duplicates). 13910 if (!findConsecutiveLoad(LD, DAG)) 13911 --IncValue; 13912 13913 SDValue Increment = 13914 DAG.getConstant(IncValue, dl, getPointerTy(MF.getDataLayout())); 13915 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment); 13916 13917 MachineMemOperand *ExtraMMO = 13918 MF.getMachineMemOperand(LD->getMemOperand(), 13919 1, 2*MemVT.getStoreSize()-1); 13920 SDValue ExtraLoadOps[] = { Chain, LDXIntID, Ptr }; 13921 SDValue ExtraLoad = 13922 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl, 13923 DAG.getVTList(PermTy, MVT::Other), 13924 ExtraLoadOps, LDTy, ExtraMMO); 13925 13926 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 13927 BaseLoad.getValue(1), ExtraLoad.getValue(1)); 13928 13929 // Because vperm has a big-endian bias, we must reverse the order 13930 // of the input vectors and complement the permute control vector 13931 // when generating little endian code. We have already handled the 13932 // latter by using lvsr instead of lvsl, so just reverse BaseLoad 13933 // and ExtraLoad here. 13934 SDValue Perm; 13935 if (isLittleEndian) 13936 Perm = BuildIntrinsicOp(IntrPerm, 13937 ExtraLoad, BaseLoad, PermCntl, DAG, dl); 13938 else 13939 Perm = BuildIntrinsicOp(IntrPerm, 13940 BaseLoad, ExtraLoad, PermCntl, DAG, dl); 13941 13942 if (VT != PermTy) 13943 Perm = Subtarget.hasAltivec() ? 13944 DAG.getNode(ISD::BITCAST, dl, VT, Perm) : 13945 DAG.getNode(ISD::FP_ROUND, dl, VT, Perm, // QPX 13946 DAG.getTargetConstant(1, dl, MVT::i64)); 13947 // second argument is 1 because this rounding 13948 // is always exact. 13949 13950 // The output of the permutation is our loaded result, the TokenFactor is 13951 // our new chain. 13952 DCI.CombineTo(N, Perm, TF); 13953 return SDValue(N, 0); 13954 } 13955 } 13956 break; 13957 case ISD::INTRINSIC_WO_CHAIN: { 13958 bool isLittleEndian = Subtarget.isLittleEndian(); 13959 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 13960 Intrinsic::ID Intr = (isLittleEndian ? Intrinsic::ppc_altivec_lvsr 13961 : Intrinsic::ppc_altivec_lvsl); 13962 if ((IID == Intr || 13963 IID == Intrinsic::ppc_qpx_qvlpcld || 13964 IID == Intrinsic::ppc_qpx_qvlpcls) && 13965 N->getOperand(1)->getOpcode() == ISD::ADD) { 13966 SDValue Add = N->getOperand(1); 13967 13968 int Bits = IID == Intrinsic::ppc_qpx_qvlpcld ? 13969 5 /* 32 byte alignment */ : 4 /* 16 byte alignment */; 13970 13971 if (DAG.MaskedValueIsZero(Add->getOperand(1), 13972 APInt::getAllOnesValue(Bits /* alignment */) 13973 .zext(Add.getScalarValueSizeInBits()))) { 13974 SDNode *BasePtr = Add->getOperand(0).getNode(); 13975 for (SDNode::use_iterator UI = BasePtr->use_begin(), 13976 UE = BasePtr->use_end(); 13977 UI != UE; ++UI) { 13978 if (UI->getOpcode() == ISD::INTRINSIC_WO_CHAIN && 13979 cast<ConstantSDNode>(UI->getOperand(0))->getZExtValue() == IID) { 13980 // We've found another LVSL/LVSR, and this address is an aligned 13981 // multiple of that one. The results will be the same, so use the 13982 // one we've just found instead. 13983 13984 return SDValue(*UI, 0); 13985 } 13986 } 13987 } 13988 13989 if (isa<ConstantSDNode>(Add->getOperand(1))) { 13990 SDNode *BasePtr = Add->getOperand(0).getNode(); 13991 for (SDNode::use_iterator UI = BasePtr->use_begin(), 13992 UE = BasePtr->use_end(); UI != UE; ++UI) { 13993 if (UI->getOpcode() == ISD::ADD && 13994 isa<ConstantSDNode>(UI->getOperand(1)) && 13995 (cast<ConstantSDNode>(Add->getOperand(1))->getZExtValue() - 13996 cast<ConstantSDNode>(UI->getOperand(1))->getZExtValue()) % 13997 (1ULL << Bits) == 0) { 13998 SDNode *OtherAdd = *UI; 13999 for (SDNode::use_iterator VI = OtherAdd->use_begin(), 14000 VE = OtherAdd->use_end(); VI != VE; ++VI) { 14001 if (VI->getOpcode() == ISD::INTRINSIC_WO_CHAIN && 14002 cast<ConstantSDNode>(VI->getOperand(0))->getZExtValue() == IID) { 14003 return SDValue(*VI, 0); 14004 } 14005 } 14006 } 14007 } 14008 } 14009 } 14010 14011 // Combine vmaxsw/h/b(a, a's negation) to abs(a) 14012 // Expose the vabsduw/h/b opportunity for down stream 14013 if (!DCI.isAfterLegalizeDAG() && Subtarget.hasP9Altivec() && 14014 (IID == Intrinsic::ppc_altivec_vmaxsw || 14015 IID == Intrinsic::ppc_altivec_vmaxsh || 14016 IID == Intrinsic::ppc_altivec_vmaxsb)) { 14017 SDValue V1 = N->getOperand(1); 14018 SDValue V2 = N->getOperand(2); 14019 if ((V1.getSimpleValueType() == MVT::v4i32 || 14020 V1.getSimpleValueType() == MVT::v8i16 || 14021 V1.getSimpleValueType() == MVT::v16i8) && 14022 V1.getSimpleValueType() == V2.getSimpleValueType()) { 14023 // (0-a, a) 14024 if (V1.getOpcode() == ISD::SUB && 14025 ISD::isBuildVectorAllZeros(V1.getOperand(0).getNode()) && 14026 V1.getOperand(1) == V2) { 14027 return DAG.getNode(ISD::ABS, dl, V2.getValueType(), V2); 14028 } 14029 // (a, 0-a) 14030 if (V2.getOpcode() == ISD::SUB && 14031 ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()) && 14032 V2.getOperand(1) == V1) { 14033 return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1); 14034 } 14035 // (x-y, y-x) 14036 if (V1.getOpcode() == ISD::SUB && V2.getOpcode() == ISD::SUB && 14037 V1.getOperand(0) == V2.getOperand(1) && 14038 V1.getOperand(1) == V2.getOperand(0)) { 14039 return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1); 14040 } 14041 } 14042 } 14043 } 14044 14045 break; 14046 case ISD::INTRINSIC_W_CHAIN: 14047 // For little endian, VSX loads require generating lxvd2x/xxswapd. 14048 // Not needed on ISA 3.0 based CPUs since we have a non-permuting load. 14049 if (Subtarget.needsSwapsForVSXMemOps()) { 14050 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 14051 default: 14052 break; 14053 case Intrinsic::ppc_vsx_lxvw4x: 14054 case Intrinsic::ppc_vsx_lxvd2x: 14055 return expandVSXLoadForLE(N, DCI); 14056 } 14057 } 14058 break; 14059 case ISD::INTRINSIC_VOID: 14060 // For little endian, VSX stores require generating xxswapd/stxvd2x. 14061 // Not needed on ISA 3.0 based CPUs since we have a non-permuting store. 14062 if (Subtarget.needsSwapsForVSXMemOps()) { 14063 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 14064 default: 14065 break; 14066 case Intrinsic::ppc_vsx_stxvw4x: 14067 case Intrinsic::ppc_vsx_stxvd2x: 14068 return expandVSXStoreForLE(N, DCI); 14069 } 14070 } 14071 break; 14072 case ISD::BSWAP: 14073 // Turn BSWAP (LOAD) -> lhbrx/lwbrx. 14074 if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) && 14075 N->getOperand(0).hasOneUse() && 14076 (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 || 14077 (Subtarget.hasLDBRX() && Subtarget.isPPC64() && 14078 N->getValueType(0) == MVT::i64))) { 14079 SDValue Load = N->getOperand(0); 14080 LoadSDNode *LD = cast<LoadSDNode>(Load); 14081 // Create the byte-swapping load. 14082 SDValue Ops[] = { 14083 LD->getChain(), // Chain 14084 LD->getBasePtr(), // Ptr 14085 DAG.getValueType(N->getValueType(0)) // VT 14086 }; 14087 SDValue BSLoad = 14088 DAG.getMemIntrinsicNode(PPCISD::LBRX, dl, 14089 DAG.getVTList(N->getValueType(0) == MVT::i64 ? 14090 MVT::i64 : MVT::i32, MVT::Other), 14091 Ops, LD->getMemoryVT(), LD->getMemOperand()); 14092 14093 // If this is an i16 load, insert the truncate. 14094 SDValue ResVal = BSLoad; 14095 if (N->getValueType(0) == MVT::i16) 14096 ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad); 14097 14098 // First, combine the bswap away. This makes the value produced by the 14099 // load dead. 14100 DCI.CombineTo(N, ResVal); 14101 14102 // Next, combine the load away, we give it a bogus result value but a real 14103 // chain result. The result value is dead because the bswap is dead. 14104 DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1)); 14105 14106 // Return N so it doesn't get rechecked! 14107 return SDValue(N, 0); 14108 } 14109 break; 14110 case PPCISD::VCMP: 14111 // If a VCMPo node already exists with exactly the same operands as this 14112 // node, use its result instead of this node (VCMPo computes both a CR6 and 14113 // a normal output). 14114 // 14115 if (!N->getOperand(0).hasOneUse() && 14116 !N->getOperand(1).hasOneUse() && 14117 !N->getOperand(2).hasOneUse()) { 14118 14119 // Scan all of the users of the LHS, looking for VCMPo's that match. 14120 SDNode *VCMPoNode = nullptr; 14121 14122 SDNode *LHSN = N->getOperand(0).getNode(); 14123 for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end(); 14124 UI != E; ++UI) 14125 if (UI->getOpcode() == PPCISD::VCMPo && 14126 UI->getOperand(1) == N->getOperand(1) && 14127 UI->getOperand(2) == N->getOperand(2) && 14128 UI->getOperand(0) == N->getOperand(0)) { 14129 VCMPoNode = *UI; 14130 break; 14131 } 14132 14133 // If there is no VCMPo node, or if the flag value has a single use, don't 14134 // transform this. 14135 if (!VCMPoNode || VCMPoNode->hasNUsesOfValue(0, 1)) 14136 break; 14137 14138 // Look at the (necessarily single) use of the flag value. If it has a 14139 // chain, this transformation is more complex. Note that multiple things 14140 // could use the value result, which we should ignore. 14141 SDNode *FlagUser = nullptr; 14142 for (SDNode::use_iterator UI = VCMPoNode->use_begin(); 14143 FlagUser == nullptr; ++UI) { 14144 assert(UI != VCMPoNode->use_end() && "Didn't find user!"); 14145 SDNode *User = *UI; 14146 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) { 14147 if (User->getOperand(i) == SDValue(VCMPoNode, 1)) { 14148 FlagUser = User; 14149 break; 14150 } 14151 } 14152 } 14153 14154 // If the user is a MFOCRF instruction, we know this is safe. 14155 // Otherwise we give up for right now. 14156 if (FlagUser->getOpcode() == PPCISD::MFOCRF) 14157 return SDValue(VCMPoNode, 0); 14158 } 14159 break; 14160 case ISD::BRCOND: { 14161 SDValue Cond = N->getOperand(1); 14162 SDValue Target = N->getOperand(2); 14163 14164 if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN && 14165 cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() == 14166 Intrinsic::loop_decrement) { 14167 14168 // We now need to make the intrinsic dead (it cannot be instruction 14169 // selected). 14170 DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0)); 14171 assert(Cond.getNode()->hasOneUse() && 14172 "Counter decrement has more than one use"); 14173 14174 return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other, 14175 N->getOperand(0), Target); 14176 } 14177 } 14178 break; 14179 case ISD::BR_CC: { 14180 // If this is a branch on an altivec predicate comparison, lower this so 14181 // that we don't have to do a MFOCRF: instead, branch directly on CR6. This 14182 // lowering is done pre-legalize, because the legalizer lowers the predicate 14183 // compare down to code that is difficult to reassemble. 14184 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get(); 14185 SDValue LHS = N->getOperand(2), RHS = N->getOperand(3); 14186 14187 // Sometimes the promoted value of the intrinsic is ANDed by some non-zero 14188 // value. If so, pass-through the AND to get to the intrinsic. 14189 if (LHS.getOpcode() == ISD::AND && 14190 LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN && 14191 cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() == 14192 Intrinsic::loop_decrement && 14193 isa<ConstantSDNode>(LHS.getOperand(1)) && 14194 !isNullConstant(LHS.getOperand(1))) 14195 LHS = LHS.getOperand(0); 14196 14197 if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN && 14198 cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() == 14199 Intrinsic::loop_decrement && 14200 isa<ConstantSDNode>(RHS)) { 14201 assert((CC == ISD::SETEQ || CC == ISD::SETNE) && 14202 "Counter decrement comparison is not EQ or NE"); 14203 14204 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue(); 14205 bool isBDNZ = (CC == ISD::SETEQ && Val) || 14206 (CC == ISD::SETNE && !Val); 14207 14208 // We now need to make the intrinsic dead (it cannot be instruction 14209 // selected). 14210 DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0)); 14211 assert(LHS.getNode()->hasOneUse() && 14212 "Counter decrement has more than one use"); 14213 14214 return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other, 14215 N->getOperand(0), N->getOperand(4)); 14216 } 14217 14218 int CompareOpc; 14219 bool isDot; 14220 14221 if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN && 14222 isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) && 14223 getVectorCompareInfo(LHS, CompareOpc, isDot, Subtarget)) { 14224 assert(isDot && "Can't compare against a vector result!"); 14225 14226 // If this is a comparison against something other than 0/1, then we know 14227 // that the condition is never/always true. 14228 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue(); 14229 if (Val != 0 && Val != 1) { 14230 if (CC == ISD::SETEQ) // Cond never true, remove branch. 14231 return N->getOperand(0); 14232 // Always !=, turn it into an unconditional branch. 14233 return DAG.getNode(ISD::BR, dl, MVT::Other, 14234 N->getOperand(0), N->getOperand(4)); 14235 } 14236 14237 bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0); 14238 14239 // Create the PPCISD altivec 'dot' comparison node. 14240 SDValue Ops[] = { 14241 LHS.getOperand(2), // LHS of compare 14242 LHS.getOperand(3), // RHS of compare 14243 DAG.getConstant(CompareOpc, dl, MVT::i32) 14244 }; 14245 EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue }; 14246 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops); 14247 14248 // Unpack the result based on how the target uses it. 14249 PPC::Predicate CompOpc; 14250 switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) { 14251 default: // Can't happen, don't crash on invalid number though. 14252 case 0: // Branch on the value of the EQ bit of CR6. 14253 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE; 14254 break; 14255 case 1: // Branch on the inverted value of the EQ bit of CR6. 14256 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ; 14257 break; 14258 case 2: // Branch on the value of the LT bit of CR6. 14259 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE; 14260 break; 14261 case 3: // Branch on the inverted value of the LT bit of CR6. 14262 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT; 14263 break; 14264 } 14265 14266 return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0), 14267 DAG.getConstant(CompOpc, dl, MVT::i32), 14268 DAG.getRegister(PPC::CR6, MVT::i32), 14269 N->getOperand(4), CompNode.getValue(1)); 14270 } 14271 break; 14272 } 14273 case ISD::BUILD_VECTOR: 14274 return DAGCombineBuildVector(N, DCI); 14275 case ISD::ABS: 14276 return combineABS(N, DCI); 14277 case ISD::VSELECT: 14278 return combineVSelect(N, DCI); 14279 } 14280 14281 return SDValue(); 14282 } 14283 14284 SDValue 14285 PPCTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor, 14286 SelectionDAG &DAG, 14287 SmallVectorImpl<SDNode *> &Created) const { 14288 // fold (sdiv X, pow2) 14289 EVT VT = N->getValueType(0); 14290 if (VT == MVT::i64 && !Subtarget.isPPC64()) 14291 return SDValue(); 14292 if ((VT != MVT::i32 && VT != MVT::i64) || 14293 !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2())) 14294 return SDValue(); 14295 14296 SDLoc DL(N); 14297 SDValue N0 = N->getOperand(0); 14298 14299 bool IsNegPow2 = (-Divisor).isPowerOf2(); 14300 unsigned Lg2 = (IsNegPow2 ? -Divisor : Divisor).countTrailingZeros(); 14301 SDValue ShiftAmt = DAG.getConstant(Lg2, DL, VT); 14302 14303 SDValue Op = DAG.getNode(PPCISD::SRA_ADDZE, DL, VT, N0, ShiftAmt); 14304 Created.push_back(Op.getNode()); 14305 14306 if (IsNegPow2) { 14307 Op = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Op); 14308 Created.push_back(Op.getNode()); 14309 } 14310 14311 return Op; 14312 } 14313 14314 //===----------------------------------------------------------------------===// 14315 // Inline Assembly Support 14316 //===----------------------------------------------------------------------===// 14317 14318 void PPCTargetLowering::computeKnownBitsForTargetNode(const SDValue Op, 14319 KnownBits &Known, 14320 const APInt &DemandedElts, 14321 const SelectionDAG &DAG, 14322 unsigned Depth) const { 14323 Known.resetAll(); 14324 switch (Op.getOpcode()) { 14325 default: break; 14326 case PPCISD::LBRX: { 14327 // lhbrx is known to have the top bits cleared out. 14328 if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16) 14329 Known.Zero = 0xFFFF0000; 14330 break; 14331 } 14332 case ISD::INTRINSIC_WO_CHAIN: { 14333 switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) { 14334 default: break; 14335 case Intrinsic::ppc_altivec_vcmpbfp_p: 14336 case Intrinsic::ppc_altivec_vcmpeqfp_p: 14337 case Intrinsic::ppc_altivec_vcmpequb_p: 14338 case Intrinsic::ppc_altivec_vcmpequh_p: 14339 case Intrinsic::ppc_altivec_vcmpequw_p: 14340 case Intrinsic::ppc_altivec_vcmpequd_p: 14341 case Intrinsic::ppc_altivec_vcmpgefp_p: 14342 case Intrinsic::ppc_altivec_vcmpgtfp_p: 14343 case Intrinsic::ppc_altivec_vcmpgtsb_p: 14344 case Intrinsic::ppc_altivec_vcmpgtsh_p: 14345 case Intrinsic::ppc_altivec_vcmpgtsw_p: 14346 case Intrinsic::ppc_altivec_vcmpgtsd_p: 14347 case Intrinsic::ppc_altivec_vcmpgtub_p: 14348 case Intrinsic::ppc_altivec_vcmpgtuh_p: 14349 case Intrinsic::ppc_altivec_vcmpgtuw_p: 14350 case Intrinsic::ppc_altivec_vcmpgtud_p: 14351 Known.Zero = ~1U; // All bits but the low one are known to be zero. 14352 break; 14353 } 14354 } 14355 } 14356 } 14357 14358 Align PPCTargetLowering::getPrefLoopAlignment(MachineLoop *ML) const { 14359 switch (Subtarget.getCPUDirective()) { 14360 default: break; 14361 case PPC::DIR_970: 14362 case PPC::DIR_PWR4: 14363 case PPC::DIR_PWR5: 14364 case PPC::DIR_PWR5X: 14365 case PPC::DIR_PWR6: 14366 case PPC::DIR_PWR6X: 14367 case PPC::DIR_PWR7: 14368 case PPC::DIR_PWR8: 14369 case PPC::DIR_PWR9: 14370 case PPC::DIR_PWR_FUTURE: { 14371 if (!ML) 14372 break; 14373 14374 if (!DisableInnermostLoopAlign32) { 14375 // If the nested loop is an innermost loop, prefer to a 32-byte alignment, 14376 // so that we can decrease cache misses and branch-prediction misses. 14377 // Actual alignment of the loop will depend on the hotness check and other 14378 // logic in alignBlocks. 14379 if (ML->getLoopDepth() > 1 && ML->getSubLoops().empty()) 14380 return Align(32); 14381 } 14382 14383 const PPCInstrInfo *TII = Subtarget.getInstrInfo(); 14384 14385 // For small loops (between 5 and 8 instructions), align to a 32-byte 14386 // boundary so that the entire loop fits in one instruction-cache line. 14387 uint64_t LoopSize = 0; 14388 for (auto I = ML->block_begin(), IE = ML->block_end(); I != IE; ++I) 14389 for (auto J = (*I)->begin(), JE = (*I)->end(); J != JE; ++J) { 14390 LoopSize += TII->getInstSizeInBytes(*J); 14391 if (LoopSize > 32) 14392 break; 14393 } 14394 14395 if (LoopSize > 16 && LoopSize <= 32) 14396 return Align(32); 14397 14398 break; 14399 } 14400 } 14401 14402 return TargetLowering::getPrefLoopAlignment(ML); 14403 } 14404 14405 /// getConstraintType - Given a constraint, return the type of 14406 /// constraint it is for this target. 14407 PPCTargetLowering::ConstraintType 14408 PPCTargetLowering::getConstraintType(StringRef Constraint) const { 14409 if (Constraint.size() == 1) { 14410 switch (Constraint[0]) { 14411 default: break; 14412 case 'b': 14413 case 'r': 14414 case 'f': 14415 case 'd': 14416 case 'v': 14417 case 'y': 14418 return C_RegisterClass; 14419 case 'Z': 14420 // FIXME: While Z does indicate a memory constraint, it specifically 14421 // indicates an r+r address (used in conjunction with the 'y' modifier 14422 // in the replacement string). Currently, we're forcing the base 14423 // register to be r0 in the asm printer (which is interpreted as zero) 14424 // and forming the complete address in the second register. This is 14425 // suboptimal. 14426 return C_Memory; 14427 } 14428 } else if (Constraint == "wc") { // individual CR bits. 14429 return C_RegisterClass; 14430 } else if (Constraint == "wa" || Constraint == "wd" || 14431 Constraint == "wf" || Constraint == "ws" || 14432 Constraint == "wi" || Constraint == "ww") { 14433 return C_RegisterClass; // VSX registers. 14434 } 14435 return TargetLowering::getConstraintType(Constraint); 14436 } 14437 14438 /// Examine constraint type and operand type and determine a weight value. 14439 /// This object must already have been set up with the operand type 14440 /// and the current alternative constraint selected. 14441 TargetLowering::ConstraintWeight 14442 PPCTargetLowering::getSingleConstraintMatchWeight( 14443 AsmOperandInfo &info, const char *constraint) const { 14444 ConstraintWeight weight = CW_Invalid; 14445 Value *CallOperandVal = info.CallOperandVal; 14446 // If we don't have a value, we can't do a match, 14447 // but allow it at the lowest weight. 14448 if (!CallOperandVal) 14449 return CW_Default; 14450 Type *type = CallOperandVal->getType(); 14451 14452 // Look at the constraint type. 14453 if (StringRef(constraint) == "wc" && type->isIntegerTy(1)) 14454 return CW_Register; // an individual CR bit. 14455 else if ((StringRef(constraint) == "wa" || 14456 StringRef(constraint) == "wd" || 14457 StringRef(constraint) == "wf") && 14458 type->isVectorTy()) 14459 return CW_Register; 14460 else if (StringRef(constraint) == "wi" && type->isIntegerTy(64)) 14461 return CW_Register; // just hold 64-bit integers data. 14462 else if (StringRef(constraint) == "ws" && type->isDoubleTy()) 14463 return CW_Register; 14464 else if (StringRef(constraint) == "ww" && type->isFloatTy()) 14465 return CW_Register; 14466 14467 switch (*constraint) { 14468 default: 14469 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint); 14470 break; 14471 case 'b': 14472 if (type->isIntegerTy()) 14473 weight = CW_Register; 14474 break; 14475 case 'f': 14476 if (type->isFloatTy()) 14477 weight = CW_Register; 14478 break; 14479 case 'd': 14480 if (type->isDoubleTy()) 14481 weight = CW_Register; 14482 break; 14483 case 'v': 14484 if (type->isVectorTy()) 14485 weight = CW_Register; 14486 break; 14487 case 'y': 14488 weight = CW_Register; 14489 break; 14490 case 'Z': 14491 weight = CW_Memory; 14492 break; 14493 } 14494 return weight; 14495 } 14496 14497 std::pair<unsigned, const TargetRegisterClass *> 14498 PPCTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, 14499 StringRef Constraint, 14500 MVT VT) const { 14501 if (Constraint.size() == 1) { 14502 // GCC RS6000 Constraint Letters 14503 switch (Constraint[0]) { 14504 case 'b': // R1-R31 14505 if (VT == MVT::i64 && Subtarget.isPPC64()) 14506 return std::make_pair(0U, &PPC::G8RC_NOX0RegClass); 14507 return std::make_pair(0U, &PPC::GPRC_NOR0RegClass); 14508 case 'r': // R0-R31 14509 if (VT == MVT::i64 && Subtarget.isPPC64()) 14510 return std::make_pair(0U, &PPC::G8RCRegClass); 14511 return std::make_pair(0U, &PPC::GPRCRegClass); 14512 // 'd' and 'f' constraints are both defined to be "the floating point 14513 // registers", where one is for 32-bit and the other for 64-bit. We don't 14514 // really care overly much here so just give them all the same reg classes. 14515 case 'd': 14516 case 'f': 14517 if (Subtarget.hasSPE()) { 14518 if (VT == MVT::f32 || VT == MVT::i32) 14519 return std::make_pair(0U, &PPC::GPRCRegClass); 14520 if (VT == MVT::f64 || VT == MVT::i64) 14521 return std::make_pair(0U, &PPC::SPERCRegClass); 14522 } else { 14523 if (VT == MVT::f32 || VT == MVT::i32) 14524 return std::make_pair(0U, &PPC::F4RCRegClass); 14525 if (VT == MVT::f64 || VT == MVT::i64) 14526 return std::make_pair(0U, &PPC::F8RCRegClass); 14527 if (VT == MVT::v4f64 && Subtarget.hasQPX()) 14528 return std::make_pair(0U, &PPC::QFRCRegClass); 14529 if (VT == MVT::v4f32 && Subtarget.hasQPX()) 14530 return std::make_pair(0U, &PPC::QSRCRegClass); 14531 } 14532 break; 14533 case 'v': 14534 if (VT == MVT::v4f64 && Subtarget.hasQPX()) 14535 return std::make_pair(0U, &PPC::QFRCRegClass); 14536 if (VT == MVT::v4f32 && Subtarget.hasQPX()) 14537 return std::make_pair(0U, &PPC::QSRCRegClass); 14538 if (Subtarget.hasAltivec()) 14539 return std::make_pair(0U, &PPC::VRRCRegClass); 14540 break; 14541 case 'y': // crrc 14542 return std::make_pair(0U, &PPC::CRRCRegClass); 14543 } 14544 } else if (Constraint == "wc" && Subtarget.useCRBits()) { 14545 // An individual CR bit. 14546 return std::make_pair(0U, &PPC::CRBITRCRegClass); 14547 } else if ((Constraint == "wa" || Constraint == "wd" || 14548 Constraint == "wf" || Constraint == "wi") && 14549 Subtarget.hasVSX()) { 14550 return std::make_pair(0U, &PPC::VSRCRegClass); 14551 } else if ((Constraint == "ws" || Constraint == "ww") && Subtarget.hasVSX()) { 14552 if (VT == MVT::f32 && Subtarget.hasP8Vector()) 14553 return std::make_pair(0U, &PPC::VSSRCRegClass); 14554 else 14555 return std::make_pair(0U, &PPC::VSFRCRegClass); 14556 } 14557 14558 // If we name a VSX register, we can't defer to the base class because it 14559 // will not recognize the correct register (their names will be VSL{0-31} 14560 // and V{0-31} so they won't match). So we match them here. 14561 if (Constraint.size() > 3 && Constraint[1] == 'v' && Constraint[2] == 's') { 14562 int VSNum = atoi(Constraint.data() + 3); 14563 assert(VSNum >= 0 && VSNum <= 63 && 14564 "Attempted to access a vsr out of range"); 14565 if (VSNum < 32) 14566 return std::make_pair(PPC::VSL0 + VSNum, &PPC::VSRCRegClass); 14567 return std::make_pair(PPC::V0 + VSNum - 32, &PPC::VSRCRegClass); 14568 } 14569 std::pair<unsigned, const TargetRegisterClass *> R = 14570 TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 14571 14572 // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers 14573 // (which we call X[0-9]+). If a 64-bit value has been requested, and a 14574 // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent 14575 // register. 14576 // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use 14577 // the AsmName field from *RegisterInfo.td, then this would not be necessary. 14578 if (R.first && VT == MVT::i64 && Subtarget.isPPC64() && 14579 PPC::GPRCRegClass.contains(R.first)) 14580 return std::make_pair(TRI->getMatchingSuperReg(R.first, 14581 PPC::sub_32, &PPC::G8RCRegClass), 14582 &PPC::G8RCRegClass); 14583 14584 // GCC accepts 'cc' as an alias for 'cr0', and we need to do the same. 14585 if (!R.second && StringRef("{cc}").equals_lower(Constraint)) { 14586 R.first = PPC::CR0; 14587 R.second = &PPC::CRRCRegClass; 14588 } 14589 14590 return R; 14591 } 14592 14593 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops 14594 /// vector. If it is invalid, don't add anything to Ops. 14595 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op, 14596 std::string &Constraint, 14597 std::vector<SDValue>&Ops, 14598 SelectionDAG &DAG) const { 14599 SDValue Result; 14600 14601 // Only support length 1 constraints. 14602 if (Constraint.length() > 1) return; 14603 14604 char Letter = Constraint[0]; 14605 switch (Letter) { 14606 default: break; 14607 case 'I': 14608 case 'J': 14609 case 'K': 14610 case 'L': 14611 case 'M': 14612 case 'N': 14613 case 'O': 14614 case 'P': { 14615 ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op); 14616 if (!CST) return; // Must be an immediate to match. 14617 SDLoc dl(Op); 14618 int64_t Value = CST->getSExtValue(); 14619 EVT TCVT = MVT::i64; // All constants taken to be 64 bits so that negative 14620 // numbers are printed as such. 14621 switch (Letter) { 14622 default: llvm_unreachable("Unknown constraint letter!"); 14623 case 'I': // "I" is a signed 16-bit constant. 14624 if (isInt<16>(Value)) 14625 Result = DAG.getTargetConstant(Value, dl, TCVT); 14626 break; 14627 case 'J': // "J" is a constant with only the high-order 16 bits nonzero. 14628 if (isShiftedUInt<16, 16>(Value)) 14629 Result = DAG.getTargetConstant(Value, dl, TCVT); 14630 break; 14631 case 'L': // "L" is a signed 16-bit constant shifted left 16 bits. 14632 if (isShiftedInt<16, 16>(Value)) 14633 Result = DAG.getTargetConstant(Value, dl, TCVT); 14634 break; 14635 case 'K': // "K" is a constant with only the low-order 16 bits nonzero. 14636 if (isUInt<16>(Value)) 14637 Result = DAG.getTargetConstant(Value, dl, TCVT); 14638 break; 14639 case 'M': // "M" is a constant that is greater than 31. 14640 if (Value > 31) 14641 Result = DAG.getTargetConstant(Value, dl, TCVT); 14642 break; 14643 case 'N': // "N" is a positive constant that is an exact power of two. 14644 if (Value > 0 && isPowerOf2_64(Value)) 14645 Result = DAG.getTargetConstant(Value, dl, TCVT); 14646 break; 14647 case 'O': // "O" is the constant zero. 14648 if (Value == 0) 14649 Result = DAG.getTargetConstant(Value, dl, TCVT); 14650 break; 14651 case 'P': // "P" is a constant whose negation is a signed 16-bit constant. 14652 if (isInt<16>(-Value)) 14653 Result = DAG.getTargetConstant(Value, dl, TCVT); 14654 break; 14655 } 14656 break; 14657 } 14658 } 14659 14660 if (Result.getNode()) { 14661 Ops.push_back(Result); 14662 return; 14663 } 14664 14665 // Handle standard constraint letters. 14666 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 14667 } 14668 14669 // isLegalAddressingMode - Return true if the addressing mode represented 14670 // by AM is legal for this target, for a load/store of the specified type. 14671 bool PPCTargetLowering::isLegalAddressingMode(const DataLayout &DL, 14672 const AddrMode &AM, Type *Ty, 14673 unsigned AS, Instruction *I) const { 14674 // PPC does not allow r+i addressing modes for vectors! 14675 if (Ty->isVectorTy() && AM.BaseOffs != 0) 14676 return false; 14677 14678 // PPC allows a sign-extended 16-bit immediate field. 14679 if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1) 14680 return false; 14681 14682 // No global is ever allowed as a base. 14683 if (AM.BaseGV) 14684 return false; 14685 14686 // PPC only support r+r, 14687 switch (AM.Scale) { 14688 case 0: // "r+i" or just "i", depending on HasBaseReg. 14689 break; 14690 case 1: 14691 if (AM.HasBaseReg && AM.BaseOffs) // "r+r+i" is not allowed. 14692 return false; 14693 // Otherwise we have r+r or r+i. 14694 break; 14695 case 2: 14696 if (AM.HasBaseReg || AM.BaseOffs) // 2*r+r or 2*r+i is not allowed. 14697 return false; 14698 // Allow 2*r as r+r. 14699 break; 14700 default: 14701 // No other scales are supported. 14702 return false; 14703 } 14704 14705 return true; 14706 } 14707 14708 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op, 14709 SelectionDAG &DAG) const { 14710 MachineFunction &MF = DAG.getMachineFunction(); 14711 MachineFrameInfo &MFI = MF.getFrameInfo(); 14712 MFI.setReturnAddressIsTaken(true); 14713 14714 if (verifyReturnAddressArgumentIsConstant(Op, DAG)) 14715 return SDValue(); 14716 14717 SDLoc dl(Op); 14718 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 14719 14720 // Make sure the function does not optimize away the store of the RA to 14721 // the stack. 14722 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 14723 FuncInfo->setLRStoreRequired(); 14724 bool isPPC64 = Subtarget.isPPC64(); 14725 auto PtrVT = getPointerTy(MF.getDataLayout()); 14726 14727 if (Depth > 0) { 14728 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG); 14729 SDValue Offset = 14730 DAG.getConstant(Subtarget.getFrameLowering()->getReturnSaveOffset(), dl, 14731 isPPC64 ? MVT::i64 : MVT::i32); 14732 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), 14733 DAG.getNode(ISD::ADD, dl, PtrVT, FrameAddr, Offset), 14734 MachinePointerInfo()); 14735 } 14736 14737 // Just load the return address off the stack. 14738 SDValue RetAddrFI = getReturnAddrFrameIndex(DAG); 14739 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), RetAddrFI, 14740 MachinePointerInfo()); 14741 } 14742 14743 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op, 14744 SelectionDAG &DAG) const { 14745 SDLoc dl(Op); 14746 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 14747 14748 MachineFunction &MF = DAG.getMachineFunction(); 14749 MachineFrameInfo &MFI = MF.getFrameInfo(); 14750 MFI.setFrameAddressIsTaken(true); 14751 14752 EVT PtrVT = getPointerTy(MF.getDataLayout()); 14753 bool isPPC64 = PtrVT == MVT::i64; 14754 14755 // Naked functions never have a frame pointer, and so we use r1. For all 14756 // other functions, this decision must be delayed until during PEI. 14757 unsigned FrameReg; 14758 if (MF.getFunction().hasFnAttribute(Attribute::Naked)) 14759 FrameReg = isPPC64 ? PPC::X1 : PPC::R1; 14760 else 14761 FrameReg = isPPC64 ? PPC::FP8 : PPC::FP; 14762 14763 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, 14764 PtrVT); 14765 while (Depth--) 14766 FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(), 14767 FrameAddr, MachinePointerInfo()); 14768 return FrameAddr; 14769 } 14770 14771 // FIXME? Maybe this could be a TableGen attribute on some registers and 14772 // this table could be generated automatically from RegInfo. 14773 Register PPCTargetLowering::getRegisterByName(const char* RegName, EVT VT, 14774 const MachineFunction &MF) const { 14775 bool isPPC64 = Subtarget.isPPC64(); 14776 bool IsDarwinABI = Subtarget.isDarwinABI(); 14777 14778 if ((isPPC64 && VT != MVT::i64 && VT != MVT::i32) || 14779 (!isPPC64 && VT != MVT::i32)) 14780 report_fatal_error("Invalid register global variable type"); 14781 14782 bool is64Bit = isPPC64 && VT == MVT::i64; 14783 Register Reg = StringSwitch<Register>(RegName) 14784 .Case("r1", is64Bit ? PPC::X1 : PPC::R1) 14785 .Case("r2", (IsDarwinABI || isPPC64) ? Register() : PPC::R2) 14786 .Case("r13", (!isPPC64 && IsDarwinABI) ? Register() : 14787 (is64Bit ? PPC::X13 : PPC::R13)) 14788 .Default(Register()); 14789 14790 if (Reg) 14791 return Reg; 14792 report_fatal_error("Invalid register name global variable"); 14793 } 14794 14795 bool PPCTargetLowering::isAccessedAsGotIndirect(SDValue GA) const { 14796 // 32-bit SVR4 ABI access everything as got-indirect. 14797 if (Subtarget.is32BitELFABI()) 14798 return true; 14799 14800 // AIX accesses everything indirectly through the TOC, which is similar to 14801 // the GOT. 14802 if (Subtarget.isAIXABI()) 14803 return true; 14804 14805 CodeModel::Model CModel = getTargetMachine().getCodeModel(); 14806 // If it is small or large code model, module locals are accessed 14807 // indirectly by loading their address from .toc/.got. 14808 if (CModel == CodeModel::Small || CModel == CodeModel::Large) 14809 return true; 14810 14811 // JumpTable and BlockAddress are accessed as got-indirect. 14812 if (isa<JumpTableSDNode>(GA) || isa<BlockAddressSDNode>(GA)) 14813 return true; 14814 14815 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(GA)) 14816 return Subtarget.isGVIndirectSymbol(G->getGlobal()); 14817 14818 return false; 14819 } 14820 14821 bool 14822 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 14823 // The PowerPC target isn't yet aware of offsets. 14824 return false; 14825 } 14826 14827 bool PPCTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 14828 const CallInst &I, 14829 MachineFunction &MF, 14830 unsigned Intrinsic) const { 14831 switch (Intrinsic) { 14832 case Intrinsic::ppc_qpx_qvlfd: 14833 case Intrinsic::ppc_qpx_qvlfs: 14834 case Intrinsic::ppc_qpx_qvlfcd: 14835 case Intrinsic::ppc_qpx_qvlfcs: 14836 case Intrinsic::ppc_qpx_qvlfiwa: 14837 case Intrinsic::ppc_qpx_qvlfiwz: 14838 case Intrinsic::ppc_altivec_lvx: 14839 case Intrinsic::ppc_altivec_lvxl: 14840 case Intrinsic::ppc_altivec_lvebx: 14841 case Intrinsic::ppc_altivec_lvehx: 14842 case Intrinsic::ppc_altivec_lvewx: 14843 case Intrinsic::ppc_vsx_lxvd2x: 14844 case Intrinsic::ppc_vsx_lxvw4x: { 14845 EVT VT; 14846 switch (Intrinsic) { 14847 case Intrinsic::ppc_altivec_lvebx: 14848 VT = MVT::i8; 14849 break; 14850 case Intrinsic::ppc_altivec_lvehx: 14851 VT = MVT::i16; 14852 break; 14853 case Intrinsic::ppc_altivec_lvewx: 14854 VT = MVT::i32; 14855 break; 14856 case Intrinsic::ppc_vsx_lxvd2x: 14857 VT = MVT::v2f64; 14858 break; 14859 case Intrinsic::ppc_qpx_qvlfd: 14860 VT = MVT::v4f64; 14861 break; 14862 case Intrinsic::ppc_qpx_qvlfs: 14863 VT = MVT::v4f32; 14864 break; 14865 case Intrinsic::ppc_qpx_qvlfcd: 14866 VT = MVT::v2f64; 14867 break; 14868 case Intrinsic::ppc_qpx_qvlfcs: 14869 VT = MVT::v2f32; 14870 break; 14871 default: 14872 VT = MVT::v4i32; 14873 break; 14874 } 14875 14876 Info.opc = ISD::INTRINSIC_W_CHAIN; 14877 Info.memVT = VT; 14878 Info.ptrVal = I.getArgOperand(0); 14879 Info.offset = -VT.getStoreSize()+1; 14880 Info.size = 2*VT.getStoreSize()-1; 14881 Info.align = Align::None(); 14882 Info.flags = MachineMemOperand::MOLoad; 14883 return true; 14884 } 14885 case Intrinsic::ppc_qpx_qvlfda: 14886 case Intrinsic::ppc_qpx_qvlfsa: 14887 case Intrinsic::ppc_qpx_qvlfcda: 14888 case Intrinsic::ppc_qpx_qvlfcsa: 14889 case Intrinsic::ppc_qpx_qvlfiwaa: 14890 case Intrinsic::ppc_qpx_qvlfiwza: { 14891 EVT VT; 14892 switch (Intrinsic) { 14893 case Intrinsic::ppc_qpx_qvlfda: 14894 VT = MVT::v4f64; 14895 break; 14896 case Intrinsic::ppc_qpx_qvlfsa: 14897 VT = MVT::v4f32; 14898 break; 14899 case Intrinsic::ppc_qpx_qvlfcda: 14900 VT = MVT::v2f64; 14901 break; 14902 case Intrinsic::ppc_qpx_qvlfcsa: 14903 VT = MVT::v2f32; 14904 break; 14905 default: 14906 VT = MVT::v4i32; 14907 break; 14908 } 14909 14910 Info.opc = ISD::INTRINSIC_W_CHAIN; 14911 Info.memVT = VT; 14912 Info.ptrVal = I.getArgOperand(0); 14913 Info.offset = 0; 14914 Info.size = VT.getStoreSize(); 14915 Info.align = Align::None(); 14916 Info.flags = MachineMemOperand::MOLoad; 14917 return true; 14918 } 14919 case Intrinsic::ppc_qpx_qvstfd: 14920 case Intrinsic::ppc_qpx_qvstfs: 14921 case Intrinsic::ppc_qpx_qvstfcd: 14922 case Intrinsic::ppc_qpx_qvstfcs: 14923 case Intrinsic::ppc_qpx_qvstfiw: 14924 case Intrinsic::ppc_altivec_stvx: 14925 case Intrinsic::ppc_altivec_stvxl: 14926 case Intrinsic::ppc_altivec_stvebx: 14927 case Intrinsic::ppc_altivec_stvehx: 14928 case Intrinsic::ppc_altivec_stvewx: 14929 case Intrinsic::ppc_vsx_stxvd2x: 14930 case Intrinsic::ppc_vsx_stxvw4x: { 14931 EVT VT; 14932 switch (Intrinsic) { 14933 case Intrinsic::ppc_altivec_stvebx: 14934 VT = MVT::i8; 14935 break; 14936 case Intrinsic::ppc_altivec_stvehx: 14937 VT = MVT::i16; 14938 break; 14939 case Intrinsic::ppc_altivec_stvewx: 14940 VT = MVT::i32; 14941 break; 14942 case Intrinsic::ppc_vsx_stxvd2x: 14943 VT = MVT::v2f64; 14944 break; 14945 case Intrinsic::ppc_qpx_qvstfd: 14946 VT = MVT::v4f64; 14947 break; 14948 case Intrinsic::ppc_qpx_qvstfs: 14949 VT = MVT::v4f32; 14950 break; 14951 case Intrinsic::ppc_qpx_qvstfcd: 14952 VT = MVT::v2f64; 14953 break; 14954 case Intrinsic::ppc_qpx_qvstfcs: 14955 VT = MVT::v2f32; 14956 break; 14957 default: 14958 VT = MVT::v4i32; 14959 break; 14960 } 14961 14962 Info.opc = ISD::INTRINSIC_VOID; 14963 Info.memVT = VT; 14964 Info.ptrVal = I.getArgOperand(1); 14965 Info.offset = -VT.getStoreSize()+1; 14966 Info.size = 2*VT.getStoreSize()-1; 14967 Info.align = Align::None(); 14968 Info.flags = MachineMemOperand::MOStore; 14969 return true; 14970 } 14971 case Intrinsic::ppc_qpx_qvstfda: 14972 case Intrinsic::ppc_qpx_qvstfsa: 14973 case Intrinsic::ppc_qpx_qvstfcda: 14974 case Intrinsic::ppc_qpx_qvstfcsa: 14975 case Intrinsic::ppc_qpx_qvstfiwa: { 14976 EVT VT; 14977 switch (Intrinsic) { 14978 case Intrinsic::ppc_qpx_qvstfda: 14979 VT = MVT::v4f64; 14980 break; 14981 case Intrinsic::ppc_qpx_qvstfsa: 14982 VT = MVT::v4f32; 14983 break; 14984 case Intrinsic::ppc_qpx_qvstfcda: 14985 VT = MVT::v2f64; 14986 break; 14987 case Intrinsic::ppc_qpx_qvstfcsa: 14988 VT = MVT::v2f32; 14989 break; 14990 default: 14991 VT = MVT::v4i32; 14992 break; 14993 } 14994 14995 Info.opc = ISD::INTRINSIC_VOID; 14996 Info.memVT = VT; 14997 Info.ptrVal = I.getArgOperand(1); 14998 Info.offset = 0; 14999 Info.size = VT.getStoreSize(); 15000 Info.align = Align::None(); 15001 Info.flags = MachineMemOperand::MOStore; 15002 return true; 15003 } 15004 default: 15005 break; 15006 } 15007 15008 return false; 15009 } 15010 15011 /// getOptimalMemOpType - Returns the target specific optimal type for load 15012 /// and store operations as a result of memset, memcpy, and memmove 15013 /// lowering. If DstAlign is zero that means it's safe to destination 15014 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it 15015 /// means there isn't a need to check it against alignment requirement, 15016 /// probably because the source does not need to be loaded. If 'IsMemset' is 15017 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that 15018 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy 15019 /// source is constant so it does not need to be loaded. 15020 /// It returns EVT::Other if the type should be determined using generic 15021 /// target-independent logic. 15022 EVT PPCTargetLowering::getOptimalMemOpType( 15023 uint64_t Size, unsigned DstAlign, unsigned SrcAlign, bool IsMemset, 15024 bool ZeroMemset, bool MemcpyStrSrc, 15025 const AttributeList &FuncAttributes) const { 15026 if (getTargetMachine().getOptLevel() != CodeGenOpt::None) { 15027 // When expanding a memset, require at least two QPX instructions to cover 15028 // the cost of loading the value to be stored from the constant pool. 15029 if (Subtarget.hasQPX() && Size >= 32 && (!IsMemset || Size >= 64) && 15030 (!SrcAlign || SrcAlign >= 32) && (!DstAlign || DstAlign >= 32) && 15031 !FuncAttributes.hasFnAttribute(Attribute::NoImplicitFloat)) { 15032 return MVT::v4f64; 15033 } 15034 15035 // We should use Altivec/VSX loads and stores when available. For unaligned 15036 // addresses, unaligned VSX loads are only fast starting with the P8. 15037 if (Subtarget.hasAltivec() && Size >= 16 && 15038 (((!SrcAlign || SrcAlign >= 16) && (!DstAlign || DstAlign >= 16)) || 15039 ((IsMemset && Subtarget.hasVSX()) || Subtarget.hasP8Vector()))) 15040 return MVT::v4i32; 15041 } 15042 15043 if (Subtarget.isPPC64()) { 15044 return MVT::i64; 15045 } 15046 15047 return MVT::i32; 15048 } 15049 15050 /// Returns true if it is beneficial to convert a load of a constant 15051 /// to just the constant itself. 15052 bool PPCTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 15053 Type *Ty) const { 15054 assert(Ty->isIntegerTy()); 15055 15056 unsigned BitSize = Ty->getPrimitiveSizeInBits(); 15057 return !(BitSize == 0 || BitSize > 64); 15058 } 15059 15060 bool PPCTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const { 15061 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy()) 15062 return false; 15063 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits(); 15064 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits(); 15065 return NumBits1 == 64 && NumBits2 == 32; 15066 } 15067 15068 bool PPCTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const { 15069 if (!VT1.isInteger() || !VT2.isInteger()) 15070 return false; 15071 unsigned NumBits1 = VT1.getSizeInBits(); 15072 unsigned NumBits2 = VT2.getSizeInBits(); 15073 return NumBits1 == 64 && NumBits2 == 32; 15074 } 15075 15076 bool PPCTargetLowering::isZExtFree(SDValue Val, EVT VT2) const { 15077 // Generally speaking, zexts are not free, but they are free when they can be 15078 // folded with other operations. 15079 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Val)) { 15080 EVT MemVT = LD->getMemoryVT(); 15081 if ((MemVT == MVT::i1 || MemVT == MVT::i8 || MemVT == MVT::i16 || 15082 (Subtarget.isPPC64() && MemVT == MVT::i32)) && 15083 (LD->getExtensionType() == ISD::NON_EXTLOAD || 15084 LD->getExtensionType() == ISD::ZEXTLOAD)) 15085 return true; 15086 } 15087 15088 // FIXME: Add other cases... 15089 // - 32-bit shifts with a zext to i64 15090 // - zext after ctlz, bswap, etc. 15091 // - zext after and by a constant mask 15092 15093 return TargetLowering::isZExtFree(Val, VT2); 15094 } 15095 15096 bool PPCTargetLowering::isFPExtFree(EVT DestVT, EVT SrcVT) const { 15097 assert(DestVT.isFloatingPoint() && SrcVT.isFloatingPoint() && 15098 "invalid fpext types"); 15099 // Extending to float128 is not free. 15100 if (DestVT == MVT::f128) 15101 return false; 15102 return true; 15103 } 15104 15105 bool PPCTargetLowering::isLegalICmpImmediate(int64_t Imm) const { 15106 return isInt<16>(Imm) || isUInt<16>(Imm); 15107 } 15108 15109 bool PPCTargetLowering::isLegalAddImmediate(int64_t Imm) const { 15110 return isInt<16>(Imm) || isUInt<16>(Imm); 15111 } 15112 15113 bool PPCTargetLowering::allowsMisalignedMemoryAccesses(EVT VT, 15114 unsigned, 15115 unsigned, 15116 MachineMemOperand::Flags, 15117 bool *Fast) const { 15118 if (DisablePPCUnaligned) 15119 return false; 15120 15121 // PowerPC supports unaligned memory access for simple non-vector types. 15122 // Although accessing unaligned addresses is not as efficient as accessing 15123 // aligned addresses, it is generally more efficient than manual expansion, 15124 // and generally only traps for software emulation when crossing page 15125 // boundaries. 15126 15127 if (!VT.isSimple()) 15128 return false; 15129 15130 if (VT.getSimpleVT().isVector()) { 15131 if (Subtarget.hasVSX()) { 15132 if (VT != MVT::v2f64 && VT != MVT::v2i64 && 15133 VT != MVT::v4f32 && VT != MVT::v4i32) 15134 return false; 15135 } else { 15136 return false; 15137 } 15138 } 15139 15140 if (VT == MVT::ppcf128) 15141 return false; 15142 15143 if (Fast) 15144 *Fast = true; 15145 15146 return true; 15147 } 15148 15149 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, 15150 EVT VT) const { 15151 VT = VT.getScalarType(); 15152 15153 if (!VT.isSimple()) 15154 return false; 15155 15156 switch (VT.getSimpleVT().SimpleTy) { 15157 case MVT::f32: 15158 case MVT::f64: 15159 return true; 15160 case MVT::f128: 15161 return (EnableQuadPrecision && Subtarget.hasP9Vector()); 15162 default: 15163 break; 15164 } 15165 15166 return false; 15167 } 15168 15169 const MCPhysReg * 15170 PPCTargetLowering::getScratchRegisters(CallingConv::ID) const { 15171 // LR is a callee-save register, but we must treat it as clobbered by any call 15172 // site. Hence we include LR in the scratch registers, which are in turn added 15173 // as implicit-defs for stackmaps and patchpoints. The same reasoning applies 15174 // to CTR, which is used by any indirect call. 15175 static const MCPhysReg ScratchRegs[] = { 15176 PPC::X12, PPC::LR8, PPC::CTR8, 0 15177 }; 15178 15179 return ScratchRegs; 15180 } 15181 15182 unsigned PPCTargetLowering::getExceptionPointerRegister( 15183 const Constant *PersonalityFn) const { 15184 return Subtarget.isPPC64() ? PPC::X3 : PPC::R3; 15185 } 15186 15187 unsigned PPCTargetLowering::getExceptionSelectorRegister( 15188 const Constant *PersonalityFn) const { 15189 return Subtarget.isPPC64() ? PPC::X4 : PPC::R4; 15190 } 15191 15192 bool 15193 PPCTargetLowering::shouldExpandBuildVectorWithShuffles( 15194 EVT VT , unsigned DefinedValues) const { 15195 if (VT == MVT::v2i64) 15196 return Subtarget.hasDirectMove(); // Don't need stack ops with direct moves 15197 15198 if (Subtarget.hasVSX() || Subtarget.hasQPX()) 15199 return true; 15200 15201 return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues); 15202 } 15203 15204 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const { 15205 if (DisableILPPref || Subtarget.enableMachineScheduler()) 15206 return TargetLowering::getSchedulingPreference(N); 15207 15208 return Sched::ILP; 15209 } 15210 15211 // Create a fast isel object. 15212 FastISel * 15213 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo, 15214 const TargetLibraryInfo *LibInfo) const { 15215 return PPC::createFastISel(FuncInfo, LibInfo); 15216 } 15217 15218 void PPCTargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const { 15219 if (Subtarget.isDarwinABI()) return; 15220 if (!Subtarget.isPPC64()) return; 15221 15222 // Update IsSplitCSR in PPCFunctionInfo 15223 PPCFunctionInfo *PFI = Entry->getParent()->getInfo<PPCFunctionInfo>(); 15224 PFI->setIsSplitCSR(true); 15225 } 15226 15227 void PPCTargetLowering::insertCopiesSplitCSR( 15228 MachineBasicBlock *Entry, 15229 const SmallVectorImpl<MachineBasicBlock *> &Exits) const { 15230 const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo(); 15231 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent()); 15232 if (!IStart) 15233 return; 15234 15235 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 15236 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo(); 15237 MachineBasicBlock::iterator MBBI = Entry->begin(); 15238 for (const MCPhysReg *I = IStart; *I; ++I) { 15239 const TargetRegisterClass *RC = nullptr; 15240 if (PPC::G8RCRegClass.contains(*I)) 15241 RC = &PPC::G8RCRegClass; 15242 else if (PPC::F8RCRegClass.contains(*I)) 15243 RC = &PPC::F8RCRegClass; 15244 else if (PPC::CRRCRegClass.contains(*I)) 15245 RC = &PPC::CRRCRegClass; 15246 else if (PPC::VRRCRegClass.contains(*I)) 15247 RC = &PPC::VRRCRegClass; 15248 else 15249 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 15250 15251 Register NewVR = MRI->createVirtualRegister(RC); 15252 // Create copy from CSR to a virtual register. 15253 // FIXME: this currently does not emit CFI pseudo-instructions, it works 15254 // fine for CXX_FAST_TLS since the C++-style TLS access functions should be 15255 // nounwind. If we want to generalize this later, we may need to emit 15256 // CFI pseudo-instructions. 15257 assert(Entry->getParent()->getFunction().hasFnAttribute( 15258 Attribute::NoUnwind) && 15259 "Function should be nounwind in insertCopiesSplitCSR!"); 15260 Entry->addLiveIn(*I); 15261 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR) 15262 .addReg(*I); 15263 15264 // Insert the copy-back instructions right before the terminator. 15265 for (auto *Exit : Exits) 15266 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(), 15267 TII->get(TargetOpcode::COPY), *I) 15268 .addReg(NewVR); 15269 } 15270 } 15271 15272 // Override to enable LOAD_STACK_GUARD lowering on Linux. 15273 bool PPCTargetLowering::useLoadStackGuardNode() const { 15274 if (!Subtarget.isTargetLinux()) 15275 return TargetLowering::useLoadStackGuardNode(); 15276 return true; 15277 } 15278 15279 // Override to disable global variable loading on Linux. 15280 void PPCTargetLowering::insertSSPDeclarations(Module &M) const { 15281 if (!Subtarget.isTargetLinux()) 15282 return TargetLowering::insertSSPDeclarations(M); 15283 } 15284 15285 bool PPCTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT, 15286 bool ForCodeSize) const { 15287 if (!VT.isSimple() || !Subtarget.hasVSX()) 15288 return false; 15289 15290 switch(VT.getSimpleVT().SimpleTy) { 15291 default: 15292 // For FP types that are currently not supported by PPC backend, return 15293 // false. Examples: f16, f80. 15294 return false; 15295 case MVT::f32: 15296 case MVT::f64: 15297 case MVT::ppcf128: 15298 return Imm.isPosZero(); 15299 } 15300 } 15301 15302 // For vector shift operation op, fold 15303 // (op x, (and y, ((1 << numbits(x)) - 1))) -> (target op x, y) 15304 static SDValue stripModuloOnShift(const TargetLowering &TLI, SDNode *N, 15305 SelectionDAG &DAG) { 15306 SDValue N0 = N->getOperand(0); 15307 SDValue N1 = N->getOperand(1); 15308 EVT VT = N0.getValueType(); 15309 unsigned OpSizeInBits = VT.getScalarSizeInBits(); 15310 unsigned Opcode = N->getOpcode(); 15311 unsigned TargetOpcode; 15312 15313 switch (Opcode) { 15314 default: 15315 llvm_unreachable("Unexpected shift operation"); 15316 case ISD::SHL: 15317 TargetOpcode = PPCISD::SHL; 15318 break; 15319 case ISD::SRL: 15320 TargetOpcode = PPCISD::SRL; 15321 break; 15322 case ISD::SRA: 15323 TargetOpcode = PPCISD::SRA; 15324 break; 15325 } 15326 15327 if (VT.isVector() && TLI.isOperationLegal(Opcode, VT) && 15328 N1->getOpcode() == ISD::AND) 15329 if (ConstantSDNode *Mask = isConstOrConstSplat(N1->getOperand(1))) 15330 if (Mask->getZExtValue() == OpSizeInBits - 1) 15331 return DAG.getNode(TargetOpcode, SDLoc(N), VT, N0, N1->getOperand(0)); 15332 15333 return SDValue(); 15334 } 15335 15336 SDValue PPCTargetLowering::combineSHL(SDNode *N, DAGCombinerInfo &DCI) const { 15337 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG)) 15338 return Value; 15339 15340 SDValue N0 = N->getOperand(0); 15341 ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N->getOperand(1)); 15342 if (!Subtarget.isISA3_0() || 15343 N0.getOpcode() != ISD::SIGN_EXTEND || 15344 N0.getOperand(0).getValueType() != MVT::i32 || 15345 CN1 == nullptr || N->getValueType(0) != MVT::i64) 15346 return SDValue(); 15347 15348 // We can't save an operation here if the value is already extended, and 15349 // the existing shift is easier to combine. 15350 SDValue ExtsSrc = N0.getOperand(0); 15351 if (ExtsSrc.getOpcode() == ISD::TRUNCATE && 15352 ExtsSrc.getOperand(0).getOpcode() == ISD::AssertSext) 15353 return SDValue(); 15354 15355 SDLoc DL(N0); 15356 SDValue ShiftBy = SDValue(CN1, 0); 15357 // We want the shift amount to be i32 on the extswli, but the shift could 15358 // have an i64. 15359 if (ShiftBy.getValueType() == MVT::i64) 15360 ShiftBy = DCI.DAG.getConstant(CN1->getZExtValue(), DL, MVT::i32); 15361 15362 return DCI.DAG.getNode(PPCISD::EXTSWSLI, DL, MVT::i64, N0->getOperand(0), 15363 ShiftBy); 15364 } 15365 15366 SDValue PPCTargetLowering::combineSRA(SDNode *N, DAGCombinerInfo &DCI) const { 15367 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG)) 15368 return Value; 15369 15370 return SDValue(); 15371 } 15372 15373 SDValue PPCTargetLowering::combineSRL(SDNode *N, DAGCombinerInfo &DCI) const { 15374 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG)) 15375 return Value; 15376 15377 return SDValue(); 15378 } 15379 15380 // Transform (add X, (zext(setne Z, C))) -> (addze X, (addic (addi Z, -C), -1)) 15381 // Transform (add X, (zext(sete Z, C))) -> (addze X, (subfic (addi Z, -C), 0)) 15382 // When C is zero, the equation (addi Z, -C) can be simplified to Z 15383 // Requirement: -C in [-32768, 32767], X and Z are MVT::i64 types 15384 static SDValue combineADDToADDZE(SDNode *N, SelectionDAG &DAG, 15385 const PPCSubtarget &Subtarget) { 15386 if (!Subtarget.isPPC64()) 15387 return SDValue(); 15388 15389 SDValue LHS = N->getOperand(0); 15390 SDValue RHS = N->getOperand(1); 15391 15392 auto isZextOfCompareWithConstant = [](SDValue Op) { 15393 if (Op.getOpcode() != ISD::ZERO_EXTEND || !Op.hasOneUse() || 15394 Op.getValueType() != MVT::i64) 15395 return false; 15396 15397 SDValue Cmp = Op.getOperand(0); 15398 if (Cmp.getOpcode() != ISD::SETCC || !Cmp.hasOneUse() || 15399 Cmp.getOperand(0).getValueType() != MVT::i64) 15400 return false; 15401 15402 if (auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1))) { 15403 int64_t NegConstant = 0 - Constant->getSExtValue(); 15404 // Due to the limitations of the addi instruction, 15405 // -C is required to be [-32768, 32767]. 15406 return isInt<16>(NegConstant); 15407 } 15408 15409 return false; 15410 }; 15411 15412 bool LHSHasPattern = isZextOfCompareWithConstant(LHS); 15413 bool RHSHasPattern = isZextOfCompareWithConstant(RHS); 15414 15415 // If there is a pattern, canonicalize a zext operand to the RHS. 15416 if (LHSHasPattern && !RHSHasPattern) 15417 std::swap(LHS, RHS); 15418 else if (!LHSHasPattern && !RHSHasPattern) 15419 return SDValue(); 15420 15421 SDLoc DL(N); 15422 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Glue); 15423 SDValue Cmp = RHS.getOperand(0); 15424 SDValue Z = Cmp.getOperand(0); 15425 auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1)); 15426 15427 assert(Constant && "Constant Should not be a null pointer."); 15428 int64_t NegConstant = 0 - Constant->getSExtValue(); 15429 15430 switch(cast<CondCodeSDNode>(Cmp.getOperand(2))->get()) { 15431 default: break; 15432 case ISD::SETNE: { 15433 // when C == 0 15434 // --> addze X, (addic Z, -1).carry 15435 // / 15436 // add X, (zext(setne Z, C))-- 15437 // \ when -32768 <= -C <= 32767 && C != 0 15438 // --> addze X, (addic (addi Z, -C), -1).carry 15439 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z, 15440 DAG.getConstant(NegConstant, DL, MVT::i64)); 15441 SDValue AddOrZ = NegConstant != 0 ? Add : Z; 15442 SDValue Addc = DAG.getNode(ISD::ADDC, DL, DAG.getVTList(MVT::i64, MVT::Glue), 15443 AddOrZ, DAG.getConstant(-1ULL, DL, MVT::i64)); 15444 return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64), 15445 SDValue(Addc.getNode(), 1)); 15446 } 15447 case ISD::SETEQ: { 15448 // when C == 0 15449 // --> addze X, (subfic Z, 0).carry 15450 // / 15451 // add X, (zext(sete Z, C))-- 15452 // \ when -32768 <= -C <= 32767 && C != 0 15453 // --> addze X, (subfic (addi Z, -C), 0).carry 15454 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z, 15455 DAG.getConstant(NegConstant, DL, MVT::i64)); 15456 SDValue AddOrZ = NegConstant != 0 ? Add : Z; 15457 SDValue Subc = DAG.getNode(ISD::SUBC, DL, DAG.getVTList(MVT::i64, MVT::Glue), 15458 DAG.getConstant(0, DL, MVT::i64), AddOrZ); 15459 return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64), 15460 SDValue(Subc.getNode(), 1)); 15461 } 15462 } 15463 15464 return SDValue(); 15465 } 15466 15467 SDValue PPCTargetLowering::combineADD(SDNode *N, DAGCombinerInfo &DCI) const { 15468 if (auto Value = combineADDToADDZE(N, DCI.DAG, Subtarget)) 15469 return Value; 15470 15471 return SDValue(); 15472 } 15473 15474 // Detect TRUNCATE operations on bitcasts of float128 values. 15475 // What we are looking for here is the situtation where we extract a subset 15476 // of bits from a 128 bit float. 15477 // This can be of two forms: 15478 // 1) BITCAST of f128 feeding TRUNCATE 15479 // 2) BITCAST of f128 feeding SRL (a shift) feeding TRUNCATE 15480 // The reason this is required is because we do not have a legal i128 type 15481 // and so we want to prevent having to store the f128 and then reload part 15482 // of it. 15483 SDValue PPCTargetLowering::combineTRUNCATE(SDNode *N, 15484 DAGCombinerInfo &DCI) const { 15485 // If we are using CRBits then try that first. 15486 if (Subtarget.useCRBits()) { 15487 // Check if CRBits did anything and return that if it did. 15488 if (SDValue CRTruncValue = DAGCombineTruncBoolExt(N, DCI)) 15489 return CRTruncValue; 15490 } 15491 15492 SDLoc dl(N); 15493 SDValue Op0 = N->getOperand(0); 15494 15495 // Looking for a truncate of i128 to i64. 15496 if (Op0.getValueType() != MVT::i128 || N->getValueType(0) != MVT::i64) 15497 return SDValue(); 15498 15499 int EltToExtract = DCI.DAG.getDataLayout().isBigEndian() ? 1 : 0; 15500 15501 // SRL feeding TRUNCATE. 15502 if (Op0.getOpcode() == ISD::SRL) { 15503 ConstantSDNode *ConstNode = dyn_cast<ConstantSDNode>(Op0.getOperand(1)); 15504 // The right shift has to be by 64 bits. 15505 if (!ConstNode || ConstNode->getZExtValue() != 64) 15506 return SDValue(); 15507 15508 // Switch the element number to extract. 15509 EltToExtract = EltToExtract ? 0 : 1; 15510 // Update Op0 past the SRL. 15511 Op0 = Op0.getOperand(0); 15512 } 15513 15514 // BITCAST feeding a TRUNCATE possibly via SRL. 15515 if (Op0.getOpcode() == ISD::BITCAST && 15516 Op0.getValueType() == MVT::i128 && 15517 Op0.getOperand(0).getValueType() == MVT::f128) { 15518 SDValue Bitcast = DCI.DAG.getBitcast(MVT::v2i64, Op0.getOperand(0)); 15519 return DCI.DAG.getNode( 15520 ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Bitcast, 15521 DCI.DAG.getTargetConstant(EltToExtract, dl, MVT::i32)); 15522 } 15523 return SDValue(); 15524 } 15525 15526 SDValue PPCTargetLowering::combineMUL(SDNode *N, DAGCombinerInfo &DCI) const { 15527 SelectionDAG &DAG = DCI.DAG; 15528 15529 ConstantSDNode *ConstOpOrElement = isConstOrConstSplat(N->getOperand(1)); 15530 if (!ConstOpOrElement) 15531 return SDValue(); 15532 15533 // An imul is usually smaller than the alternative sequence for legal type. 15534 if (DAG.getMachineFunction().getFunction().hasMinSize() && 15535 isOperationLegal(ISD::MUL, N->getValueType(0))) 15536 return SDValue(); 15537 15538 auto IsProfitable = [this](bool IsNeg, bool IsAddOne, EVT VT) -> bool { 15539 switch (this->Subtarget.getCPUDirective()) { 15540 default: 15541 // TODO: enhance the condition for subtarget before pwr8 15542 return false; 15543 case PPC::DIR_PWR8: 15544 // type mul add shl 15545 // scalar 4 1 1 15546 // vector 7 2 2 15547 return true; 15548 case PPC::DIR_PWR9: 15549 case PPC::DIR_PWR_FUTURE: 15550 // type mul add shl 15551 // scalar 5 2 2 15552 // vector 7 2 2 15553 15554 // The cycle RATIO of related operations are showed as a table above. 15555 // Because mul is 5(scalar)/7(vector), add/sub/shl are all 2 for both 15556 // scalar and vector type. For 2 instrs patterns, add/sub + shl 15557 // are 4, it is always profitable; but for 3 instrs patterns 15558 // (mul x, -(2^N + 1)) => -(add (shl x, N), x), sub + add + shl are 6. 15559 // So we should only do it for vector type. 15560 return IsAddOne && IsNeg ? VT.isVector() : true; 15561 } 15562 }; 15563 15564 EVT VT = N->getValueType(0); 15565 SDLoc DL(N); 15566 15567 const APInt &MulAmt = ConstOpOrElement->getAPIntValue(); 15568 bool IsNeg = MulAmt.isNegative(); 15569 APInt MulAmtAbs = MulAmt.abs(); 15570 15571 if ((MulAmtAbs - 1).isPowerOf2()) { 15572 // (mul x, 2^N + 1) => (add (shl x, N), x) 15573 // (mul x, -(2^N + 1)) => -(add (shl x, N), x) 15574 15575 if (!IsProfitable(IsNeg, true, VT)) 15576 return SDValue(); 15577 15578 SDValue Op0 = N->getOperand(0); 15579 SDValue Op1 = 15580 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0), 15581 DAG.getConstant((MulAmtAbs - 1).logBase2(), DL, VT)); 15582 SDValue Res = DAG.getNode(ISD::ADD, DL, VT, Op0, Op1); 15583 15584 if (!IsNeg) 15585 return Res; 15586 15587 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Res); 15588 } else if ((MulAmtAbs + 1).isPowerOf2()) { 15589 // (mul x, 2^N - 1) => (sub (shl x, N), x) 15590 // (mul x, -(2^N - 1)) => (sub x, (shl x, N)) 15591 15592 if (!IsProfitable(IsNeg, false, VT)) 15593 return SDValue(); 15594 15595 SDValue Op0 = N->getOperand(0); 15596 SDValue Op1 = 15597 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0), 15598 DAG.getConstant((MulAmtAbs + 1).logBase2(), DL, VT)); 15599 15600 if (!IsNeg) 15601 return DAG.getNode(ISD::SUB, DL, VT, Op1, Op0); 15602 else 15603 return DAG.getNode(ISD::SUB, DL, VT, Op0, Op1); 15604 15605 } else { 15606 return SDValue(); 15607 } 15608 } 15609 15610 bool PPCTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 15611 // Only duplicate to increase tail-calls for the 64bit SysV ABIs. 15612 if (!Subtarget.is64BitELFABI()) 15613 return false; 15614 15615 // If not a tail call then no need to proceed. 15616 if (!CI->isTailCall()) 15617 return false; 15618 15619 // If tail calls are disabled for the caller then we are done. 15620 const Function *Caller = CI->getParent()->getParent(); 15621 auto Attr = Caller->getFnAttribute("disable-tail-calls"); 15622 if (Attr.getValueAsString() == "true") 15623 return false; 15624 15625 // If sibling calls have been disabled and tail-calls aren't guaranteed 15626 // there is no reason to duplicate. 15627 auto &TM = getTargetMachine(); 15628 if (!TM.Options.GuaranteedTailCallOpt && DisableSCO) 15629 return false; 15630 15631 // Can't tail call a function called indirectly, or if it has variadic args. 15632 const Function *Callee = CI->getCalledFunction(); 15633 if (!Callee || Callee->isVarArg()) 15634 return false; 15635 15636 // Make sure the callee and caller calling conventions are eligible for tco. 15637 if (!areCallingConvEligibleForTCO_64SVR4(Caller->getCallingConv(), 15638 CI->getCallingConv())) 15639 return false; 15640 15641 // If the function is local then we have a good chance at tail-calling it 15642 return getTargetMachine().shouldAssumeDSOLocal(*Caller->getParent(), Callee); 15643 } 15644 15645 bool PPCTargetLowering::hasBitPreservingFPLogic(EVT VT) const { 15646 if (!Subtarget.hasVSX()) 15647 return false; 15648 if (Subtarget.hasP9Vector() && VT == MVT::f128) 15649 return true; 15650 return VT == MVT::f32 || VT == MVT::f64 || 15651 VT == MVT::v4f32 || VT == MVT::v2f64; 15652 } 15653 15654 bool PPCTargetLowering:: 15655 isMaskAndCmp0FoldingBeneficial(const Instruction &AndI) const { 15656 const Value *Mask = AndI.getOperand(1); 15657 // If the mask is suitable for andi. or andis. we should sink the and. 15658 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Mask)) { 15659 // Can't handle constants wider than 64-bits. 15660 if (CI->getBitWidth() > 64) 15661 return false; 15662 int64_t ConstVal = CI->getZExtValue(); 15663 return isUInt<16>(ConstVal) || 15664 (isUInt<16>(ConstVal >> 16) && !(ConstVal & 0xFFFF)); 15665 } 15666 15667 // For non-constant masks, we can always use the record-form and. 15668 return true; 15669 } 15670 15671 // Transform (abs (sub (zext a), (zext b))) to (vabsd a b 0) 15672 // Transform (abs (sub (zext a), (zext_invec b))) to (vabsd a b 0) 15673 // Transform (abs (sub (zext_invec a), (zext_invec b))) to (vabsd a b 0) 15674 // Transform (abs (sub (zext_invec a), (zext b))) to (vabsd a b 0) 15675 // Transform (abs (sub a, b) to (vabsd a b 1)) if a & b of type v4i32 15676 SDValue PPCTargetLowering::combineABS(SDNode *N, DAGCombinerInfo &DCI) const { 15677 assert((N->getOpcode() == ISD::ABS) && "Need ABS node here"); 15678 assert(Subtarget.hasP9Altivec() && 15679 "Only combine this when P9 altivec supported!"); 15680 EVT VT = N->getValueType(0); 15681 if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8) 15682 return SDValue(); 15683 15684 SelectionDAG &DAG = DCI.DAG; 15685 SDLoc dl(N); 15686 if (N->getOperand(0).getOpcode() == ISD::SUB) { 15687 // Even for signed integers, if it's known to be positive (as signed 15688 // integer) due to zero-extended inputs. 15689 unsigned SubOpcd0 = N->getOperand(0)->getOperand(0).getOpcode(); 15690 unsigned SubOpcd1 = N->getOperand(0)->getOperand(1).getOpcode(); 15691 if ((SubOpcd0 == ISD::ZERO_EXTEND || 15692 SubOpcd0 == ISD::ZERO_EXTEND_VECTOR_INREG) && 15693 (SubOpcd1 == ISD::ZERO_EXTEND || 15694 SubOpcd1 == ISD::ZERO_EXTEND_VECTOR_INREG)) { 15695 return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(), 15696 N->getOperand(0)->getOperand(0), 15697 N->getOperand(0)->getOperand(1), 15698 DAG.getTargetConstant(0, dl, MVT::i32)); 15699 } 15700 15701 // For type v4i32, it can be optimized with xvnegsp + vabsduw 15702 if (N->getOperand(0).getValueType() == MVT::v4i32 && 15703 N->getOperand(0).hasOneUse()) { 15704 return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(), 15705 N->getOperand(0)->getOperand(0), 15706 N->getOperand(0)->getOperand(1), 15707 DAG.getTargetConstant(1, dl, MVT::i32)); 15708 } 15709 } 15710 15711 return SDValue(); 15712 } 15713 15714 // For type v4i32/v8ii16/v16i8, transform 15715 // from (vselect (setcc a, b, setugt), (sub a, b), (sub b, a)) to (vabsd a, b) 15716 // from (vselect (setcc a, b, setuge), (sub a, b), (sub b, a)) to (vabsd a, b) 15717 // from (vselect (setcc a, b, setult), (sub b, a), (sub a, b)) to (vabsd a, b) 15718 // from (vselect (setcc a, b, setule), (sub b, a), (sub a, b)) to (vabsd a, b) 15719 SDValue PPCTargetLowering::combineVSelect(SDNode *N, 15720 DAGCombinerInfo &DCI) const { 15721 assert((N->getOpcode() == ISD::VSELECT) && "Need VSELECT node here"); 15722 assert(Subtarget.hasP9Altivec() && 15723 "Only combine this when P9 altivec supported!"); 15724 15725 SelectionDAG &DAG = DCI.DAG; 15726 SDLoc dl(N); 15727 SDValue Cond = N->getOperand(0); 15728 SDValue TrueOpnd = N->getOperand(1); 15729 SDValue FalseOpnd = N->getOperand(2); 15730 EVT VT = N->getOperand(1).getValueType(); 15731 15732 if (Cond.getOpcode() != ISD::SETCC || TrueOpnd.getOpcode() != ISD::SUB || 15733 FalseOpnd.getOpcode() != ISD::SUB) 15734 return SDValue(); 15735 15736 // ABSD only available for type v4i32/v8i16/v16i8 15737 if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8) 15738 return SDValue(); 15739 15740 // At least to save one more dependent computation 15741 if (!(Cond.hasOneUse() || TrueOpnd.hasOneUse() || FalseOpnd.hasOneUse())) 15742 return SDValue(); 15743 15744 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get(); 15745 15746 // Can only handle unsigned comparison here 15747 switch (CC) { 15748 default: 15749 return SDValue(); 15750 case ISD::SETUGT: 15751 case ISD::SETUGE: 15752 break; 15753 case ISD::SETULT: 15754 case ISD::SETULE: 15755 std::swap(TrueOpnd, FalseOpnd); 15756 break; 15757 } 15758 15759 SDValue CmpOpnd1 = Cond.getOperand(0); 15760 SDValue CmpOpnd2 = Cond.getOperand(1); 15761 15762 // SETCC CmpOpnd1 CmpOpnd2 cond 15763 // TrueOpnd = CmpOpnd1 - CmpOpnd2 15764 // FalseOpnd = CmpOpnd2 - CmpOpnd1 15765 if (TrueOpnd.getOperand(0) == CmpOpnd1 && 15766 TrueOpnd.getOperand(1) == CmpOpnd2 && 15767 FalseOpnd.getOperand(0) == CmpOpnd2 && 15768 FalseOpnd.getOperand(1) == CmpOpnd1) { 15769 return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(1).getValueType(), 15770 CmpOpnd1, CmpOpnd2, 15771 DAG.getTargetConstant(0, dl, MVT::i32)); 15772 } 15773 15774 return SDValue(); 15775 } 15776