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/CallingConv.h" 59 #include "llvm/IR/Constant.h" 60 #include "llvm/IR/Constants.h" 61 #include "llvm/IR/DataLayout.h" 62 #include "llvm/IR/DebugLoc.h" 63 #include "llvm/IR/DerivedTypes.h" 64 #include "llvm/IR/Function.h" 65 #include "llvm/IR/GlobalValue.h" 66 #include "llvm/IR/IRBuilder.h" 67 #include "llvm/IR/Instructions.h" 68 #include "llvm/IR/Intrinsics.h" 69 #include "llvm/IR/IntrinsicsPowerPC.h" 70 #include "llvm/IR/Module.h" 71 #include "llvm/IR/Type.h" 72 #include "llvm/IR/Use.h" 73 #include "llvm/IR/Value.h" 74 #include "llvm/MC/MCContext.h" 75 #include "llvm/MC/MCExpr.h" 76 #include "llvm/MC/MCRegisterInfo.h" 77 #include "llvm/MC/MCSymbolXCOFF.h" 78 #include "llvm/Support/AtomicOrdering.h" 79 #include "llvm/Support/BranchProbability.h" 80 #include "llvm/Support/Casting.h" 81 #include "llvm/Support/CodeGen.h" 82 #include "llvm/Support/CommandLine.h" 83 #include "llvm/Support/Compiler.h" 84 #include "llvm/Support/Debug.h" 85 #include "llvm/Support/ErrorHandling.h" 86 #include "llvm/Support/Format.h" 87 #include "llvm/Support/KnownBits.h" 88 #include "llvm/Support/MachineValueType.h" 89 #include "llvm/Support/MathExtras.h" 90 #include "llvm/Support/raw_ostream.h" 91 #include "llvm/Target/TargetMachine.h" 92 #include "llvm/Target/TargetOptions.h" 93 #include <algorithm> 94 #include <cassert> 95 #include <cstdint> 96 #include <iterator> 97 #include <list> 98 #include <utility> 99 #include <vector> 100 101 using namespace llvm; 102 103 #define DEBUG_TYPE "ppc-lowering" 104 105 static cl::opt<bool> DisablePPCPreinc("disable-ppc-preinc", 106 cl::desc("disable preincrement load/store generation on PPC"), cl::Hidden); 107 108 static cl::opt<bool> DisableILPPref("disable-ppc-ilp-pref", 109 cl::desc("disable setting the node scheduling preference to ILP on PPC"), cl::Hidden); 110 111 static cl::opt<bool> DisablePPCUnaligned("disable-ppc-unaligned", 112 cl::desc("disable unaligned load/store generation on PPC"), cl::Hidden); 113 114 static cl::opt<bool> DisableSCO("disable-ppc-sco", 115 cl::desc("disable sibling call optimization on ppc"), cl::Hidden); 116 117 static cl::opt<bool> DisableInnermostLoopAlign32("disable-ppc-innermost-loop-align32", 118 cl::desc("don't always align innermost loop to 32 bytes on ppc"), cl::Hidden); 119 120 static cl::opt<bool> EnableQuadPrecision("enable-ppc-quad-precision", 121 cl::desc("enable quad precision float support on ppc"), cl::Hidden); 122 123 static cl::opt<bool> UseAbsoluteJumpTables("ppc-use-absolute-jumptables", 124 cl::desc("use absolute jump tables on ppc"), cl::Hidden); 125 126 STATISTIC(NumTailCalls, "Number of tail calls"); 127 STATISTIC(NumSiblingCalls, "Number of sibling calls"); 128 129 static bool isNByteElemShuffleMask(ShuffleVectorSDNode *, unsigned, int); 130 131 static SDValue widenVec(SelectionDAG &DAG, SDValue Vec, const SDLoc &dl); 132 133 // FIXME: Remove this once the bug has been fixed! 134 extern cl::opt<bool> ANDIGlueBug; 135 136 PPCTargetLowering::PPCTargetLowering(const PPCTargetMachine &TM, 137 const PPCSubtarget &STI) 138 : TargetLowering(TM), Subtarget(STI) { 139 // On PPC32/64, arguments smaller than 4/8 bytes are extended, so all 140 // arguments are at least 4/8 bytes aligned. 141 bool isPPC64 = Subtarget.isPPC64(); 142 setMinStackArgumentAlignment(isPPC64 ? Align(8) : Align(4)); 143 144 // Set up the register classes. 145 addRegisterClass(MVT::i32, &PPC::GPRCRegClass); 146 if (!useSoftFloat()) { 147 if (hasSPE()) { 148 addRegisterClass(MVT::f32, &PPC::GPRCRegClass); 149 addRegisterClass(MVT::f64, &PPC::SPERCRegClass); 150 } else { 151 addRegisterClass(MVT::f32, &PPC::F4RCRegClass); 152 addRegisterClass(MVT::f64, &PPC::F8RCRegClass); 153 } 154 } 155 156 // Match BITREVERSE to customized fast code sequence in the td file. 157 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal); 158 setOperationAction(ISD::BITREVERSE, MVT::i64, Legal); 159 160 // Sub-word ATOMIC_CMP_SWAP need to ensure that the input is zero-extended. 161 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom); 162 163 // PowerPC has an i16 but no i8 (or i1) SEXTLOAD. 164 for (MVT VT : MVT::integer_valuetypes()) { 165 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote); 166 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i8, Expand); 167 } 168 169 if (Subtarget.isISA3_0()) { 170 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Legal); 171 setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Legal); 172 setTruncStoreAction(MVT::f64, MVT::f16, Legal); 173 setTruncStoreAction(MVT::f32, MVT::f16, Legal); 174 } else { 175 // No extending loads from f16 or HW conversions back and forth. 176 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand); 177 setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand); 178 setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand); 179 setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand); 180 setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand); 181 setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand); 182 setTruncStoreAction(MVT::f64, MVT::f16, Expand); 183 setTruncStoreAction(MVT::f32, MVT::f16, Expand); 184 } 185 186 setTruncStoreAction(MVT::f64, MVT::f32, Expand); 187 188 // PowerPC has pre-inc load and store's. 189 setIndexedLoadAction(ISD::PRE_INC, MVT::i1, Legal); 190 setIndexedLoadAction(ISD::PRE_INC, MVT::i8, Legal); 191 setIndexedLoadAction(ISD::PRE_INC, MVT::i16, Legal); 192 setIndexedLoadAction(ISD::PRE_INC, MVT::i32, Legal); 193 setIndexedLoadAction(ISD::PRE_INC, MVT::i64, Legal); 194 setIndexedStoreAction(ISD::PRE_INC, MVT::i1, Legal); 195 setIndexedStoreAction(ISD::PRE_INC, MVT::i8, Legal); 196 setIndexedStoreAction(ISD::PRE_INC, MVT::i16, Legal); 197 setIndexedStoreAction(ISD::PRE_INC, MVT::i32, Legal); 198 setIndexedStoreAction(ISD::PRE_INC, MVT::i64, Legal); 199 if (!Subtarget.hasSPE()) { 200 setIndexedLoadAction(ISD::PRE_INC, MVT::f32, Legal); 201 setIndexedLoadAction(ISD::PRE_INC, MVT::f64, Legal); 202 setIndexedStoreAction(ISD::PRE_INC, MVT::f32, Legal); 203 setIndexedStoreAction(ISD::PRE_INC, MVT::f64, Legal); 204 } 205 206 // PowerPC uses ADDC/ADDE/SUBC/SUBE to propagate carry. 207 const MVT ScalarIntVTs[] = { MVT::i32, MVT::i64 }; 208 for (MVT VT : ScalarIntVTs) { 209 setOperationAction(ISD::ADDC, VT, Legal); 210 setOperationAction(ISD::ADDE, VT, Legal); 211 setOperationAction(ISD::SUBC, VT, Legal); 212 setOperationAction(ISD::SUBE, VT, Legal); 213 } 214 215 if (Subtarget.useCRBits()) { 216 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); 217 218 if (isPPC64 || Subtarget.hasFPCVT()) { 219 setOperationAction(ISD::SINT_TO_FP, MVT::i1, Promote); 220 AddPromotedToType (ISD::SINT_TO_FP, MVT::i1, 221 isPPC64 ? MVT::i64 : MVT::i32); 222 setOperationAction(ISD::UINT_TO_FP, MVT::i1, Promote); 223 AddPromotedToType(ISD::UINT_TO_FP, MVT::i1, 224 isPPC64 ? MVT::i64 : MVT::i32); 225 } else { 226 setOperationAction(ISD::SINT_TO_FP, MVT::i1, Custom); 227 setOperationAction(ISD::UINT_TO_FP, MVT::i1, Custom); 228 } 229 230 // PowerPC does not support direct load/store of condition registers. 231 setOperationAction(ISD::LOAD, MVT::i1, Custom); 232 setOperationAction(ISD::STORE, MVT::i1, Custom); 233 234 // FIXME: Remove this once the ANDI glue bug is fixed: 235 if (ANDIGlueBug) 236 setOperationAction(ISD::TRUNCATE, MVT::i1, Custom); 237 238 for (MVT VT : MVT::integer_valuetypes()) { 239 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote); 240 setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote); 241 setTruncStoreAction(VT, MVT::i1, Expand); 242 } 243 244 addRegisterClass(MVT::i1, &PPC::CRBITRCRegClass); 245 } 246 247 // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on 248 // PPC (the libcall is not available). 249 setOperationAction(ISD::FP_TO_SINT, MVT::ppcf128, Custom); 250 setOperationAction(ISD::FP_TO_UINT, MVT::ppcf128, Custom); 251 252 // We do not currently implement these libm ops for PowerPC. 253 setOperationAction(ISD::FFLOOR, MVT::ppcf128, Expand); 254 setOperationAction(ISD::FCEIL, MVT::ppcf128, Expand); 255 setOperationAction(ISD::FTRUNC, MVT::ppcf128, Expand); 256 setOperationAction(ISD::FRINT, MVT::ppcf128, Expand); 257 setOperationAction(ISD::FNEARBYINT, MVT::ppcf128, Expand); 258 setOperationAction(ISD::FREM, MVT::ppcf128, Expand); 259 260 // PowerPC has no SREM/UREM instructions unless we are on P9 261 // On P9 we may use a hardware instruction to compute the remainder. 262 // The instructions are not legalized directly because in the cases where the 263 // result of both the remainder and the division is required it is more 264 // efficient to compute the remainder from the result of the division rather 265 // than use the remainder instruction. 266 if (Subtarget.isISA3_0()) { 267 setOperationAction(ISD::SREM, MVT::i32, Custom); 268 setOperationAction(ISD::UREM, MVT::i32, Custom); 269 setOperationAction(ISD::SREM, MVT::i64, Custom); 270 setOperationAction(ISD::UREM, MVT::i64, Custom); 271 } else { 272 setOperationAction(ISD::SREM, MVT::i32, Expand); 273 setOperationAction(ISD::UREM, MVT::i32, Expand); 274 setOperationAction(ISD::SREM, MVT::i64, Expand); 275 setOperationAction(ISD::UREM, MVT::i64, Expand); 276 } 277 278 // Don't use SMUL_LOHI/UMUL_LOHI or SDIVREM/UDIVREM to lower SREM/UREM. 279 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand); 280 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand); 281 setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand); 282 setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand); 283 setOperationAction(ISD::UDIVREM, MVT::i32, Expand); 284 setOperationAction(ISD::SDIVREM, MVT::i32, Expand); 285 setOperationAction(ISD::UDIVREM, MVT::i64, Expand); 286 setOperationAction(ISD::SDIVREM, MVT::i64, Expand); 287 288 // Handle constrained floating-point operations of scalar. 289 // TODO: Handle SPE specific operation. 290 setOperationAction(ISD::STRICT_FADD, MVT::f32, Legal); 291 setOperationAction(ISD::STRICT_FSUB, MVT::f32, Legal); 292 setOperationAction(ISD::STRICT_FMUL, MVT::f32, Legal); 293 setOperationAction(ISD::STRICT_FDIV, MVT::f32, Legal); 294 setOperationAction(ISD::STRICT_FMA, MVT::f32, Legal); 295 296 setOperationAction(ISD::STRICT_FADD, MVT::f64, Legal); 297 setOperationAction(ISD::STRICT_FSUB, MVT::f64, Legal); 298 setOperationAction(ISD::STRICT_FMUL, MVT::f64, Legal); 299 setOperationAction(ISD::STRICT_FDIV, MVT::f64, Legal); 300 setOperationAction(ISD::STRICT_FMA, MVT::f64, Legal); 301 302 if (Subtarget.hasFSQRT()) { 303 setOperationAction(ISD::STRICT_FSQRT, MVT::f32, Legal); 304 setOperationAction(ISD::STRICT_FSQRT, MVT::f64, Legal); 305 } 306 307 // We don't support sin/cos/sqrt/fmod/pow 308 setOperationAction(ISD::FSIN , MVT::f64, Expand); 309 setOperationAction(ISD::FCOS , MVT::f64, Expand); 310 setOperationAction(ISD::FSINCOS, MVT::f64, Expand); 311 setOperationAction(ISD::FREM , MVT::f64, Expand); 312 setOperationAction(ISD::FPOW , MVT::f64, Expand); 313 setOperationAction(ISD::FSIN , MVT::f32, Expand); 314 setOperationAction(ISD::FCOS , MVT::f32, Expand); 315 setOperationAction(ISD::FSINCOS, MVT::f32, Expand); 316 setOperationAction(ISD::FREM , MVT::f32, Expand); 317 setOperationAction(ISD::FPOW , MVT::f32, Expand); 318 if (Subtarget.hasSPE()) { 319 setOperationAction(ISD::FMA , MVT::f64, Expand); 320 setOperationAction(ISD::FMA , MVT::f32, Expand); 321 } else { 322 setOperationAction(ISD::FMA , MVT::f64, Legal); 323 setOperationAction(ISD::FMA , MVT::f32, Legal); 324 } 325 326 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom); 327 328 // If we're enabling GP optimizations, use hardware square root 329 if (!Subtarget.hasFSQRT() && 330 !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTE() && 331 Subtarget.hasFRE())) 332 setOperationAction(ISD::FSQRT, MVT::f64, Expand); 333 334 if (!Subtarget.hasFSQRT() && 335 !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTES() && 336 Subtarget.hasFRES())) 337 setOperationAction(ISD::FSQRT, MVT::f32, Expand); 338 339 if (Subtarget.hasFCPSGN()) { 340 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Legal); 341 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Legal); 342 } else { 343 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand); 344 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand); 345 } 346 347 if (Subtarget.hasFPRND()) { 348 setOperationAction(ISD::FFLOOR, MVT::f64, Legal); 349 setOperationAction(ISD::FCEIL, MVT::f64, Legal); 350 setOperationAction(ISD::FTRUNC, MVT::f64, Legal); 351 setOperationAction(ISD::FROUND, MVT::f64, Legal); 352 353 setOperationAction(ISD::FFLOOR, MVT::f32, Legal); 354 setOperationAction(ISD::FCEIL, MVT::f32, Legal); 355 setOperationAction(ISD::FTRUNC, MVT::f32, Legal); 356 setOperationAction(ISD::FROUND, MVT::f32, Legal); 357 } 358 359 // PowerPC does not have BSWAP, but we can use vector BSWAP instruction xxbrd 360 // to speed up scalar BSWAP64. 361 // CTPOP or CTTZ were introduced in P8/P9 respectively 362 setOperationAction(ISD::BSWAP, MVT::i32 , Expand); 363 if (Subtarget.hasP9Vector()) 364 setOperationAction(ISD::BSWAP, MVT::i64 , Custom); 365 else 366 setOperationAction(ISD::BSWAP, MVT::i64 , Expand); 367 if (Subtarget.isISA3_0()) { 368 setOperationAction(ISD::CTTZ , MVT::i32 , Legal); 369 setOperationAction(ISD::CTTZ , MVT::i64 , Legal); 370 } else { 371 setOperationAction(ISD::CTTZ , MVT::i32 , Expand); 372 setOperationAction(ISD::CTTZ , MVT::i64 , Expand); 373 } 374 375 if (Subtarget.hasPOPCNTD() == PPCSubtarget::POPCNTD_Fast) { 376 setOperationAction(ISD::CTPOP, MVT::i32 , Legal); 377 setOperationAction(ISD::CTPOP, MVT::i64 , Legal); 378 } else { 379 setOperationAction(ISD::CTPOP, MVT::i32 , Expand); 380 setOperationAction(ISD::CTPOP, MVT::i64 , Expand); 381 } 382 383 // PowerPC does not have ROTR 384 setOperationAction(ISD::ROTR, MVT::i32 , Expand); 385 setOperationAction(ISD::ROTR, MVT::i64 , Expand); 386 387 if (!Subtarget.useCRBits()) { 388 // PowerPC does not have Select 389 setOperationAction(ISD::SELECT, MVT::i32, Expand); 390 setOperationAction(ISD::SELECT, MVT::i64, Expand); 391 setOperationAction(ISD::SELECT, MVT::f32, Expand); 392 setOperationAction(ISD::SELECT, MVT::f64, Expand); 393 } 394 395 // PowerPC wants to turn select_cc of FP into fsel when possible. 396 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom); 397 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom); 398 399 // PowerPC wants to optimize integer setcc a bit 400 if (!Subtarget.useCRBits()) 401 setOperationAction(ISD::SETCC, MVT::i32, Custom); 402 403 // PowerPC does not have BRCOND which requires SetCC 404 if (!Subtarget.useCRBits()) 405 setOperationAction(ISD::BRCOND, MVT::Other, Expand); 406 407 setOperationAction(ISD::BR_JT, MVT::Other, Expand); 408 409 if (Subtarget.hasSPE()) { 410 // SPE has built-in conversions 411 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Legal); 412 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Legal); 413 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Legal); 414 } else { 415 // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores. 416 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 417 418 // PowerPC does not have [U|S]INT_TO_FP 419 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Expand); 420 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand); 421 } 422 423 if (Subtarget.hasDirectMove() && isPPC64) { 424 setOperationAction(ISD::BITCAST, MVT::f32, Legal); 425 setOperationAction(ISD::BITCAST, MVT::i32, Legal); 426 setOperationAction(ISD::BITCAST, MVT::i64, Legal); 427 setOperationAction(ISD::BITCAST, MVT::f64, Legal); 428 if (TM.Options.UnsafeFPMath) { 429 setOperationAction(ISD::LRINT, MVT::f64, Legal); 430 setOperationAction(ISD::LRINT, MVT::f32, Legal); 431 setOperationAction(ISD::LLRINT, MVT::f64, Legal); 432 setOperationAction(ISD::LLRINT, MVT::f32, Legal); 433 setOperationAction(ISD::LROUND, MVT::f64, Legal); 434 setOperationAction(ISD::LROUND, MVT::f32, Legal); 435 setOperationAction(ISD::LLROUND, MVT::f64, Legal); 436 setOperationAction(ISD::LLROUND, MVT::f32, Legal); 437 } 438 } else { 439 setOperationAction(ISD::BITCAST, MVT::f32, Expand); 440 setOperationAction(ISD::BITCAST, MVT::i32, Expand); 441 setOperationAction(ISD::BITCAST, MVT::i64, Expand); 442 setOperationAction(ISD::BITCAST, MVT::f64, Expand); 443 } 444 445 // We cannot sextinreg(i1). Expand to shifts. 446 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); 447 448 // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support 449 // SjLj exception handling but a light-weight setjmp/longjmp replacement to 450 // support continuation, user-level threading, and etc.. As a result, no 451 // other SjLj exception interfaces are implemented and please don't build 452 // your own exception handling based on them. 453 // LLVM/Clang supports zero-cost DWARF exception handling. 454 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom); 455 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom); 456 457 // We want to legalize GlobalAddress and ConstantPool nodes into the 458 // appropriate instructions to materialize the address. 459 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom); 460 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom); 461 setOperationAction(ISD::BlockAddress, MVT::i32, Custom); 462 setOperationAction(ISD::ConstantPool, MVT::i32, Custom); 463 setOperationAction(ISD::JumpTable, MVT::i32, Custom); 464 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom); 465 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom); 466 setOperationAction(ISD::BlockAddress, MVT::i64, Custom); 467 setOperationAction(ISD::ConstantPool, MVT::i64, Custom); 468 setOperationAction(ISD::JumpTable, MVT::i64, Custom); 469 470 // TRAP is legal. 471 setOperationAction(ISD::TRAP, MVT::Other, Legal); 472 473 // TRAMPOLINE is custom lowered. 474 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom); 475 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom); 476 477 // VASTART needs to be custom lowered to use the VarArgsFrameIndex 478 setOperationAction(ISD::VASTART , MVT::Other, Custom); 479 480 if (Subtarget.is64BitELFABI()) { 481 // VAARG always uses double-word chunks, so promote anything smaller. 482 setOperationAction(ISD::VAARG, MVT::i1, Promote); 483 AddPromotedToType(ISD::VAARG, MVT::i1, MVT::i64); 484 setOperationAction(ISD::VAARG, MVT::i8, Promote); 485 AddPromotedToType(ISD::VAARG, MVT::i8, MVT::i64); 486 setOperationAction(ISD::VAARG, MVT::i16, Promote); 487 AddPromotedToType(ISD::VAARG, MVT::i16, MVT::i64); 488 setOperationAction(ISD::VAARG, MVT::i32, Promote); 489 AddPromotedToType(ISD::VAARG, MVT::i32, MVT::i64); 490 setOperationAction(ISD::VAARG, MVT::Other, Expand); 491 } else if (Subtarget.is32BitELFABI()) { 492 // VAARG is custom lowered with the 32-bit SVR4 ABI. 493 setOperationAction(ISD::VAARG, MVT::Other, Custom); 494 setOperationAction(ISD::VAARG, MVT::i64, Custom); 495 } else 496 setOperationAction(ISD::VAARG, MVT::Other, Expand); 497 498 // VACOPY is custom lowered with the 32-bit SVR4 ABI. 499 if (Subtarget.is32BitELFABI()) 500 setOperationAction(ISD::VACOPY , MVT::Other, Custom); 501 else 502 setOperationAction(ISD::VACOPY , MVT::Other, Expand); 503 504 // Use the default implementation. 505 setOperationAction(ISD::VAEND , MVT::Other, Expand); 506 setOperationAction(ISD::STACKSAVE , MVT::Other, Expand); 507 setOperationAction(ISD::STACKRESTORE , MVT::Other, Custom); 508 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32 , Custom); 509 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64 , Custom); 510 setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i32, Custom); 511 setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i64, Custom); 512 setOperationAction(ISD::EH_DWARF_CFA, MVT::i32, Custom); 513 setOperationAction(ISD::EH_DWARF_CFA, MVT::i64, Custom); 514 515 // We want to custom lower some of our intrinsics. 516 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 517 518 // To handle counter-based loop conditions. 519 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i1, Custom); 520 521 setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom); 522 setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom); 523 setOperationAction(ISD::INTRINSIC_VOID, MVT::i32, Custom); 524 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom); 525 526 // Comparisons that require checking two conditions. 527 if (Subtarget.hasSPE()) { 528 setCondCodeAction(ISD::SETO, MVT::f32, Expand); 529 setCondCodeAction(ISD::SETO, MVT::f64, Expand); 530 setCondCodeAction(ISD::SETUO, MVT::f32, Expand); 531 setCondCodeAction(ISD::SETUO, MVT::f64, Expand); 532 } 533 setCondCodeAction(ISD::SETULT, MVT::f32, Expand); 534 setCondCodeAction(ISD::SETULT, MVT::f64, Expand); 535 setCondCodeAction(ISD::SETUGT, MVT::f32, Expand); 536 setCondCodeAction(ISD::SETUGT, MVT::f64, Expand); 537 setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand); 538 setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand); 539 setCondCodeAction(ISD::SETOGE, MVT::f32, Expand); 540 setCondCodeAction(ISD::SETOGE, MVT::f64, Expand); 541 setCondCodeAction(ISD::SETOLE, MVT::f32, Expand); 542 setCondCodeAction(ISD::SETOLE, MVT::f64, Expand); 543 setCondCodeAction(ISD::SETONE, MVT::f32, Expand); 544 setCondCodeAction(ISD::SETONE, MVT::f64, Expand); 545 546 if (Subtarget.has64BitSupport()) { 547 // They also have instructions for converting between i64 and fp. 548 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom); 549 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand); 550 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom); 551 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand); 552 // This is just the low 32 bits of a (signed) fp->i64 conversion. 553 // We cannot do this with Promote because i64 is not a legal type. 554 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 555 556 if (Subtarget.hasLFIWAX() || Subtarget.isPPC64()) 557 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom); 558 } else { 559 // PowerPC does not have FP_TO_UINT on 32-bit implementations. 560 if (Subtarget.hasSPE()) 561 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Legal); 562 else 563 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand); 564 } 565 566 // With the instructions enabled under FPCVT, we can do everything. 567 if (Subtarget.hasFPCVT()) { 568 if (Subtarget.has64BitSupport()) { 569 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom); 570 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom); 571 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom); 572 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom); 573 } 574 575 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 576 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 577 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom); 578 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom); 579 } 580 581 if (Subtarget.use64BitRegs()) { 582 // 64-bit PowerPC implementations can support i64 types directly 583 addRegisterClass(MVT::i64, &PPC::G8RCRegClass); 584 // BUILD_PAIR can't be handled natively, and should be expanded to shl/or 585 setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand); 586 // 64-bit PowerPC wants to expand i128 shifts itself. 587 setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom); 588 setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom); 589 setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom); 590 } else { 591 // 32-bit PowerPC wants to expand i64 shifts itself. 592 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom); 593 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom); 594 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom); 595 } 596 597 if (Subtarget.hasVSX()) { 598 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f64, Legal); 599 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f32, Legal); 600 setOperationAction(ISD::FMINNUM_IEEE, MVT::f64, Legal); 601 setOperationAction(ISD::FMINNUM_IEEE, MVT::f32, Legal); 602 } 603 604 if (Subtarget.hasAltivec()) { 605 for (MVT VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32 }) { 606 setOperationAction(ISD::SADDSAT, VT, Legal); 607 setOperationAction(ISD::SSUBSAT, VT, Legal); 608 setOperationAction(ISD::UADDSAT, VT, Legal); 609 setOperationAction(ISD::USUBSAT, VT, Legal); 610 } 611 // First set operation action for all vector types to expand. Then we 612 // will selectively turn on ones that can be effectively codegen'd. 613 for (MVT VT : MVT::fixedlen_vector_valuetypes()) { 614 // add/sub are legal for all supported vector VT's. 615 setOperationAction(ISD::ADD, VT, Legal); 616 setOperationAction(ISD::SUB, VT, Legal); 617 618 // For v2i64, these are only valid with P8Vector. This is corrected after 619 // the loop. 620 if (VT.getSizeInBits() <= 128 && VT.getScalarSizeInBits() <= 64) { 621 setOperationAction(ISD::SMAX, VT, Legal); 622 setOperationAction(ISD::SMIN, VT, Legal); 623 setOperationAction(ISD::UMAX, VT, Legal); 624 setOperationAction(ISD::UMIN, VT, Legal); 625 } 626 else { 627 setOperationAction(ISD::SMAX, VT, Expand); 628 setOperationAction(ISD::SMIN, VT, Expand); 629 setOperationAction(ISD::UMAX, VT, Expand); 630 setOperationAction(ISD::UMIN, VT, Expand); 631 } 632 633 if (Subtarget.hasVSX()) { 634 setOperationAction(ISD::FMAXNUM, VT, Legal); 635 setOperationAction(ISD::FMINNUM, VT, Legal); 636 } 637 638 // Vector instructions introduced in P8 639 if (Subtarget.hasP8Altivec() && (VT.SimpleTy != MVT::v1i128)) { 640 setOperationAction(ISD::CTPOP, VT, Legal); 641 setOperationAction(ISD::CTLZ, VT, Legal); 642 } 643 else { 644 setOperationAction(ISD::CTPOP, VT, Expand); 645 setOperationAction(ISD::CTLZ, VT, Expand); 646 } 647 648 // Vector instructions introduced in P9 649 if (Subtarget.hasP9Altivec() && (VT.SimpleTy != MVT::v1i128)) 650 setOperationAction(ISD::CTTZ, VT, Legal); 651 else 652 setOperationAction(ISD::CTTZ, VT, Expand); 653 654 // We promote all shuffles to v16i8. 655 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Promote); 656 AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8); 657 658 // We promote all non-typed operations to v4i32. 659 setOperationAction(ISD::AND , VT, Promote); 660 AddPromotedToType (ISD::AND , VT, MVT::v4i32); 661 setOperationAction(ISD::OR , VT, Promote); 662 AddPromotedToType (ISD::OR , VT, MVT::v4i32); 663 setOperationAction(ISD::XOR , VT, Promote); 664 AddPromotedToType (ISD::XOR , VT, MVT::v4i32); 665 setOperationAction(ISD::LOAD , VT, Promote); 666 AddPromotedToType (ISD::LOAD , VT, MVT::v4i32); 667 setOperationAction(ISD::SELECT, VT, Promote); 668 AddPromotedToType (ISD::SELECT, VT, MVT::v4i32); 669 setOperationAction(ISD::VSELECT, VT, Legal); 670 setOperationAction(ISD::SELECT_CC, VT, Promote); 671 AddPromotedToType (ISD::SELECT_CC, VT, MVT::v4i32); 672 setOperationAction(ISD::STORE, VT, Promote); 673 AddPromotedToType (ISD::STORE, VT, MVT::v4i32); 674 675 // No other operations are legal. 676 setOperationAction(ISD::MUL , VT, Expand); 677 setOperationAction(ISD::SDIV, VT, Expand); 678 setOperationAction(ISD::SREM, VT, Expand); 679 setOperationAction(ISD::UDIV, VT, Expand); 680 setOperationAction(ISD::UREM, VT, Expand); 681 setOperationAction(ISD::FDIV, VT, Expand); 682 setOperationAction(ISD::FREM, VT, Expand); 683 setOperationAction(ISD::FNEG, VT, Expand); 684 setOperationAction(ISD::FSQRT, VT, Expand); 685 setOperationAction(ISD::FLOG, VT, Expand); 686 setOperationAction(ISD::FLOG10, VT, Expand); 687 setOperationAction(ISD::FLOG2, VT, Expand); 688 setOperationAction(ISD::FEXP, VT, Expand); 689 setOperationAction(ISD::FEXP2, VT, Expand); 690 setOperationAction(ISD::FSIN, VT, Expand); 691 setOperationAction(ISD::FCOS, VT, Expand); 692 setOperationAction(ISD::FABS, VT, Expand); 693 setOperationAction(ISD::FFLOOR, VT, Expand); 694 setOperationAction(ISD::FCEIL, VT, Expand); 695 setOperationAction(ISD::FTRUNC, VT, Expand); 696 setOperationAction(ISD::FRINT, VT, Expand); 697 setOperationAction(ISD::FNEARBYINT, VT, Expand); 698 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand); 699 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand); 700 setOperationAction(ISD::BUILD_VECTOR, VT, Expand); 701 setOperationAction(ISD::MULHU, VT, Expand); 702 setOperationAction(ISD::MULHS, VT, Expand); 703 setOperationAction(ISD::UMUL_LOHI, VT, Expand); 704 setOperationAction(ISD::SMUL_LOHI, VT, Expand); 705 setOperationAction(ISD::UDIVREM, VT, Expand); 706 setOperationAction(ISD::SDIVREM, VT, Expand); 707 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand); 708 setOperationAction(ISD::FPOW, VT, Expand); 709 setOperationAction(ISD::BSWAP, VT, Expand); 710 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand); 711 setOperationAction(ISD::ROTL, VT, Expand); 712 setOperationAction(ISD::ROTR, VT, Expand); 713 714 for (MVT InnerVT : MVT::fixedlen_vector_valuetypes()) { 715 setTruncStoreAction(VT, InnerVT, Expand); 716 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand); 717 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand); 718 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand); 719 } 720 } 721 setOperationAction(ISD::SELECT_CC, MVT::v4i32, Expand); 722 if (!Subtarget.hasP8Vector()) { 723 setOperationAction(ISD::SMAX, MVT::v2i64, Expand); 724 setOperationAction(ISD::SMIN, MVT::v2i64, Expand); 725 setOperationAction(ISD::UMAX, MVT::v2i64, Expand); 726 setOperationAction(ISD::UMIN, MVT::v2i64, Expand); 727 } 728 729 for (auto VT : {MVT::v2i64, MVT::v4i32, MVT::v8i16, MVT::v16i8}) 730 setOperationAction(ISD::ABS, VT, Custom); 731 732 // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle 733 // with merges, splats, etc. 734 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom); 735 736 // Vector truncates to sub-word integer that fit in an Altivec/VSX register 737 // are cheap, so handle them before they get expanded to scalar. 738 setOperationAction(ISD::TRUNCATE, MVT::v8i8, Custom); 739 setOperationAction(ISD::TRUNCATE, MVT::v4i8, Custom); 740 setOperationAction(ISD::TRUNCATE, MVT::v2i8, Custom); 741 setOperationAction(ISD::TRUNCATE, MVT::v4i16, Custom); 742 setOperationAction(ISD::TRUNCATE, MVT::v2i16, Custom); 743 744 setOperationAction(ISD::AND , MVT::v4i32, Legal); 745 setOperationAction(ISD::OR , MVT::v4i32, Legal); 746 setOperationAction(ISD::XOR , MVT::v4i32, Legal); 747 setOperationAction(ISD::LOAD , MVT::v4i32, Legal); 748 setOperationAction(ISD::SELECT, MVT::v4i32, 749 Subtarget.useCRBits() ? Legal : Expand); 750 setOperationAction(ISD::STORE , MVT::v4i32, Legal); 751 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal); 752 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal); 753 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal); 754 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal); 755 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal); 756 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal); 757 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal); 758 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal); 759 760 // Without hasP8Altivec set, v2i64 SMAX isn't available. 761 // But ABS custom lowering requires SMAX support. 762 if (!Subtarget.hasP8Altivec()) 763 setOperationAction(ISD::ABS, MVT::v2i64, Expand); 764 765 // With hasAltivec set, we can lower ISD::ROTL to vrl(b|h|w). 766 if (Subtarget.hasAltivec()) 767 for (auto VT : {MVT::v4i32, MVT::v8i16, MVT::v16i8}) 768 setOperationAction(ISD::ROTL, VT, Legal); 769 // With hasP8Altivec set, we can lower ISD::ROTL to vrld. 770 if (Subtarget.hasP8Altivec()) 771 setOperationAction(ISD::ROTL, MVT::v2i64, Legal); 772 773 addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass); 774 addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass); 775 addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass); 776 addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass); 777 778 setOperationAction(ISD::MUL, MVT::v4f32, Legal); 779 setOperationAction(ISD::FMA, MVT::v4f32, Legal); 780 781 if (TM.Options.UnsafeFPMath || Subtarget.hasVSX()) { 782 setOperationAction(ISD::FDIV, MVT::v4f32, Legal); 783 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal); 784 } 785 786 if (Subtarget.hasP8Altivec()) 787 setOperationAction(ISD::MUL, MVT::v4i32, Legal); 788 else 789 setOperationAction(ISD::MUL, MVT::v4i32, Custom); 790 791 setOperationAction(ISD::MUL, MVT::v8i16, Legal); 792 setOperationAction(ISD::MUL, MVT::v16i8, Custom); 793 794 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom); 795 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom); 796 797 setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom); 798 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom); 799 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom); 800 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom); 801 802 // Altivec does not contain unordered floating-point compare instructions 803 setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand); 804 setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand); 805 setCondCodeAction(ISD::SETO, MVT::v4f32, Expand); 806 setCondCodeAction(ISD::SETONE, MVT::v4f32, Expand); 807 808 if (Subtarget.hasVSX()) { 809 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal); 810 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal); 811 if (Subtarget.hasP8Vector()) { 812 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal); 813 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Legal); 814 } 815 if (Subtarget.hasDirectMove() && isPPC64) { 816 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Legal); 817 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Legal); 818 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Legal); 819 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i64, Legal); 820 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Legal); 821 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Legal); 822 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Legal); 823 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal); 824 } 825 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal); 826 827 // The nearbyint variants are not allowed to raise the inexact exception 828 // so we can only code-gen them with unsafe math. 829 if (TM.Options.UnsafeFPMath) { 830 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal); 831 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal); 832 } 833 834 setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal); 835 setOperationAction(ISD::FCEIL, MVT::v2f64, Legal); 836 setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal); 837 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal); 838 setOperationAction(ISD::FRINT, MVT::v2f64, Legal); 839 setOperationAction(ISD::FROUND, MVT::v2f64, Legal); 840 setOperationAction(ISD::FROUND, MVT::f64, Legal); 841 setOperationAction(ISD::FRINT, MVT::f64, Legal); 842 843 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal); 844 setOperationAction(ISD::FRINT, MVT::v4f32, Legal); 845 setOperationAction(ISD::FROUND, MVT::v4f32, Legal); 846 setOperationAction(ISD::FROUND, MVT::f32, Legal); 847 setOperationAction(ISD::FRINT, MVT::f32, Legal); 848 849 setOperationAction(ISD::MUL, MVT::v2f64, Legal); 850 setOperationAction(ISD::FMA, MVT::v2f64, Legal); 851 852 setOperationAction(ISD::FDIV, MVT::v2f64, Legal); 853 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal); 854 855 // Share the Altivec comparison restrictions. 856 setCondCodeAction(ISD::SETUO, MVT::v2f64, Expand); 857 setCondCodeAction(ISD::SETUEQ, MVT::v2f64, Expand); 858 setCondCodeAction(ISD::SETO, MVT::v2f64, Expand); 859 setCondCodeAction(ISD::SETONE, MVT::v2f64, Expand); 860 861 setOperationAction(ISD::LOAD, MVT::v2f64, Legal); 862 setOperationAction(ISD::STORE, MVT::v2f64, Legal); 863 864 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Legal); 865 866 if (Subtarget.hasP8Vector()) 867 addRegisterClass(MVT::f32, &PPC::VSSRCRegClass); 868 869 addRegisterClass(MVT::f64, &PPC::VSFRCRegClass); 870 871 addRegisterClass(MVT::v4i32, &PPC::VSRCRegClass); 872 addRegisterClass(MVT::v4f32, &PPC::VSRCRegClass); 873 addRegisterClass(MVT::v2f64, &PPC::VSRCRegClass); 874 875 if (Subtarget.hasP8Altivec()) { 876 setOperationAction(ISD::SHL, MVT::v2i64, Legal); 877 setOperationAction(ISD::SRA, MVT::v2i64, Legal); 878 setOperationAction(ISD::SRL, MVT::v2i64, Legal); 879 880 // 128 bit shifts can be accomplished via 3 instructions for SHL and 881 // SRL, but not for SRA because of the instructions available: 882 // VS{RL} and VS{RL}O. However due to direct move costs, it's not worth 883 // doing 884 setOperationAction(ISD::SHL, MVT::v1i128, Expand); 885 setOperationAction(ISD::SRL, MVT::v1i128, Expand); 886 setOperationAction(ISD::SRA, MVT::v1i128, Expand); 887 888 setOperationAction(ISD::SETCC, MVT::v2i64, Legal); 889 } 890 else { 891 setOperationAction(ISD::SHL, MVT::v2i64, Expand); 892 setOperationAction(ISD::SRA, MVT::v2i64, Expand); 893 setOperationAction(ISD::SRL, MVT::v2i64, Expand); 894 895 setOperationAction(ISD::SETCC, MVT::v2i64, Custom); 896 897 // VSX v2i64 only supports non-arithmetic operations. 898 setOperationAction(ISD::ADD, MVT::v2i64, Expand); 899 setOperationAction(ISD::SUB, MVT::v2i64, Expand); 900 } 901 902 setOperationAction(ISD::LOAD, MVT::v2i64, Promote); 903 AddPromotedToType (ISD::LOAD, MVT::v2i64, MVT::v2f64); 904 setOperationAction(ISD::STORE, MVT::v2i64, Promote); 905 AddPromotedToType (ISD::STORE, MVT::v2i64, MVT::v2f64); 906 907 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Legal); 908 909 setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal); 910 setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal); 911 setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal); 912 setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal); 913 914 // Custom handling for partial vectors of integers converted to 915 // floating point. We already have optimal handling for v2i32 through 916 // the DAG combine, so those aren't necessary. 917 setOperationAction(ISD::UINT_TO_FP, MVT::v2i8, Custom); 918 setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Custom); 919 setOperationAction(ISD::UINT_TO_FP, MVT::v2i16, Custom); 920 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom); 921 setOperationAction(ISD::SINT_TO_FP, MVT::v2i8, Custom); 922 setOperationAction(ISD::SINT_TO_FP, MVT::v4i8, Custom); 923 setOperationAction(ISD::SINT_TO_FP, MVT::v2i16, Custom); 924 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom); 925 926 setOperationAction(ISD::FNEG, MVT::v4f32, Legal); 927 setOperationAction(ISD::FNEG, MVT::v2f64, Legal); 928 setOperationAction(ISD::FABS, MVT::v4f32, Legal); 929 setOperationAction(ISD::FABS, MVT::v2f64, Legal); 930 setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Legal); 931 setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Legal); 932 933 if (Subtarget.hasDirectMove()) 934 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom); 935 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom); 936 937 // Handle constrained floating-point operations of vector. 938 // The predictor is `hasVSX` because altivec instruction has 939 // no exception but VSX vector instruction has. 940 setOperationAction(ISD::STRICT_FADD, MVT::v4f32, Legal); 941 setOperationAction(ISD::STRICT_FSUB, MVT::v4f32, Legal); 942 setOperationAction(ISD::STRICT_FMUL, MVT::v4f32, Legal); 943 setOperationAction(ISD::STRICT_FDIV, MVT::v4f32, Legal); 944 setOperationAction(ISD::STRICT_FMA, MVT::v4f32, Legal); 945 setOperationAction(ISD::STRICT_FSQRT, MVT::v4f32, Legal); 946 setOperationAction(ISD::STRICT_FMAXNUM, MVT::v4f32, Legal); 947 setOperationAction(ISD::STRICT_FMINNUM, MVT::v4f32, Legal); 948 949 setOperationAction(ISD::STRICT_FADD, MVT::v2f64, Legal); 950 setOperationAction(ISD::STRICT_FSUB, MVT::v2f64, Legal); 951 setOperationAction(ISD::STRICT_FMUL, MVT::v2f64, Legal); 952 setOperationAction(ISD::STRICT_FDIV, MVT::v2f64, Legal); 953 setOperationAction(ISD::STRICT_FMA, MVT::v2f64, Legal); 954 setOperationAction(ISD::STRICT_FSQRT, MVT::v2f64, Legal); 955 setOperationAction(ISD::STRICT_FMAXNUM, MVT::v2f64, Legal); 956 setOperationAction(ISD::STRICT_FMINNUM, MVT::v2f64, Legal); 957 958 addRegisterClass(MVT::v2i64, &PPC::VSRCRegClass); 959 } 960 961 if (Subtarget.hasP8Altivec()) { 962 addRegisterClass(MVT::v2i64, &PPC::VRRCRegClass); 963 addRegisterClass(MVT::v1i128, &PPC::VRRCRegClass); 964 } 965 966 if (Subtarget.hasP9Vector()) { 967 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom); 968 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom); 969 970 // 128 bit shifts can be accomplished via 3 instructions for SHL and 971 // SRL, but not for SRA because of the instructions available: 972 // VS{RL} and VS{RL}O. 973 setOperationAction(ISD::SHL, MVT::v1i128, Legal); 974 setOperationAction(ISD::SRL, MVT::v1i128, Legal); 975 setOperationAction(ISD::SRA, MVT::v1i128, Expand); 976 977 if (EnableQuadPrecision) { 978 addRegisterClass(MVT::f128, &PPC::VRRCRegClass); 979 setOperationAction(ISD::FADD, MVT::f128, Legal); 980 setOperationAction(ISD::FSUB, MVT::f128, Legal); 981 setOperationAction(ISD::FDIV, MVT::f128, Legal); 982 setOperationAction(ISD::FMUL, MVT::f128, Legal); 983 setOperationAction(ISD::FP_EXTEND, MVT::f128, Legal); 984 // No extending loads to f128 on PPC. 985 for (MVT FPT : MVT::fp_valuetypes()) 986 setLoadExtAction(ISD::EXTLOAD, MVT::f128, FPT, Expand); 987 setOperationAction(ISD::FMA, MVT::f128, Legal); 988 setCondCodeAction(ISD::SETULT, MVT::f128, Expand); 989 setCondCodeAction(ISD::SETUGT, MVT::f128, Expand); 990 setCondCodeAction(ISD::SETUEQ, MVT::f128, Expand); 991 setCondCodeAction(ISD::SETOGE, MVT::f128, Expand); 992 setCondCodeAction(ISD::SETOLE, MVT::f128, Expand); 993 setCondCodeAction(ISD::SETONE, MVT::f128, Expand); 994 995 setOperationAction(ISD::FTRUNC, MVT::f128, Legal); 996 setOperationAction(ISD::FRINT, MVT::f128, Legal); 997 setOperationAction(ISD::FFLOOR, MVT::f128, Legal); 998 setOperationAction(ISD::FCEIL, MVT::f128, Legal); 999 setOperationAction(ISD::FNEARBYINT, MVT::f128, Legal); 1000 setOperationAction(ISD::FROUND, MVT::f128, Legal); 1001 1002 setOperationAction(ISD::SELECT, MVT::f128, Expand); 1003 setOperationAction(ISD::FP_ROUND, MVT::f64, Legal); 1004 setOperationAction(ISD::FP_ROUND, MVT::f32, Legal); 1005 setTruncStoreAction(MVT::f128, MVT::f64, Expand); 1006 setTruncStoreAction(MVT::f128, MVT::f32, Expand); 1007 setOperationAction(ISD::BITCAST, MVT::i128, Custom); 1008 // No implementation for these ops for PowerPC. 1009 setOperationAction(ISD::FSIN , MVT::f128, Expand); 1010 setOperationAction(ISD::FCOS , MVT::f128, Expand); 1011 setOperationAction(ISD::FPOW, MVT::f128, Expand); 1012 setOperationAction(ISD::FPOWI, MVT::f128, Expand); 1013 setOperationAction(ISD::FREM, MVT::f128, Expand); 1014 1015 // Handle constrained floating-point operations of fp128 1016 setOperationAction(ISD::STRICT_FADD, MVT::f128, Legal); 1017 setOperationAction(ISD::STRICT_FSUB, MVT::f128, Legal); 1018 setOperationAction(ISD::STRICT_FMUL, MVT::f128, Legal); 1019 setOperationAction(ISD::STRICT_FDIV, MVT::f128, Legal); 1020 setOperationAction(ISD::STRICT_FMA, MVT::f128, Legal); 1021 setOperationAction(ISD::STRICT_FSQRT, MVT::f128, Legal); 1022 } 1023 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom); 1024 setOperationAction(ISD::BSWAP, MVT::v8i16, Legal); 1025 setOperationAction(ISD::BSWAP, MVT::v4i32, Legal); 1026 setOperationAction(ISD::BSWAP, MVT::v2i64, Legal); 1027 setOperationAction(ISD::BSWAP, MVT::v1i128, Legal); 1028 } 1029 1030 if (Subtarget.hasP9Altivec()) { 1031 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom); 1032 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom); 1033 1034 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Legal); 1035 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Legal); 1036 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i32, Legal); 1037 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Legal); 1038 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Legal); 1039 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i32, Legal); 1040 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i64, Legal); 1041 } 1042 } 1043 1044 if (Subtarget.hasQPX()) { 1045 setOperationAction(ISD::FADD, MVT::v4f64, Legal); 1046 setOperationAction(ISD::FSUB, MVT::v4f64, Legal); 1047 setOperationAction(ISD::FMUL, MVT::v4f64, Legal); 1048 setOperationAction(ISD::FREM, MVT::v4f64, Expand); 1049 1050 setOperationAction(ISD::FCOPYSIGN, MVT::v4f64, Legal); 1051 setOperationAction(ISD::FGETSIGN, MVT::v4f64, Expand); 1052 1053 setOperationAction(ISD::LOAD , MVT::v4f64, Custom); 1054 setOperationAction(ISD::STORE , MVT::v4f64, Custom); 1055 1056 setTruncStoreAction(MVT::v4f64, MVT::v4f32, Custom); 1057 setLoadExtAction(ISD::EXTLOAD, MVT::v4f64, MVT::v4f32, Custom); 1058 1059 if (!Subtarget.useCRBits()) 1060 setOperationAction(ISD::SELECT, MVT::v4f64, Expand); 1061 setOperationAction(ISD::VSELECT, MVT::v4f64, Legal); 1062 1063 setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f64, Legal); 1064 setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f64, Expand); 1065 setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f64, Expand); 1066 setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f64, Expand); 1067 setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f64, Custom); 1068 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f64, Legal); 1069 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f64, Custom); 1070 1071 setOperationAction(ISD::FP_TO_SINT , MVT::v4f64, Legal); 1072 setOperationAction(ISD::FP_TO_UINT , MVT::v4f64, Expand); 1073 1074 setOperationAction(ISD::FP_ROUND , MVT::v4f32, Legal); 1075 setOperationAction(ISD::FP_EXTEND, MVT::v4f64, Legal); 1076 1077 setOperationAction(ISD::FNEG , MVT::v4f64, Legal); 1078 setOperationAction(ISD::FABS , MVT::v4f64, Legal); 1079 setOperationAction(ISD::FSIN , MVT::v4f64, Expand); 1080 setOperationAction(ISD::FCOS , MVT::v4f64, Expand); 1081 setOperationAction(ISD::FPOW , MVT::v4f64, Expand); 1082 setOperationAction(ISD::FLOG , MVT::v4f64, Expand); 1083 setOperationAction(ISD::FLOG2 , MVT::v4f64, Expand); 1084 setOperationAction(ISD::FLOG10 , MVT::v4f64, Expand); 1085 setOperationAction(ISD::FEXP , MVT::v4f64, Expand); 1086 setOperationAction(ISD::FEXP2 , MVT::v4f64, Expand); 1087 1088 setOperationAction(ISD::FMINNUM, MVT::v4f64, Legal); 1089 setOperationAction(ISD::FMAXNUM, MVT::v4f64, Legal); 1090 1091 setIndexedLoadAction(ISD::PRE_INC, MVT::v4f64, Legal); 1092 setIndexedStoreAction(ISD::PRE_INC, MVT::v4f64, Legal); 1093 1094 addRegisterClass(MVT::v4f64, &PPC::QFRCRegClass); 1095 1096 setOperationAction(ISD::FADD, MVT::v4f32, Legal); 1097 setOperationAction(ISD::FSUB, MVT::v4f32, Legal); 1098 setOperationAction(ISD::FMUL, MVT::v4f32, Legal); 1099 setOperationAction(ISD::FREM, MVT::v4f32, Expand); 1100 1101 setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Legal); 1102 setOperationAction(ISD::FGETSIGN, MVT::v4f32, Expand); 1103 1104 setOperationAction(ISD::LOAD , MVT::v4f32, Custom); 1105 setOperationAction(ISD::STORE , MVT::v4f32, Custom); 1106 1107 if (!Subtarget.useCRBits()) 1108 setOperationAction(ISD::SELECT, MVT::v4f32, Expand); 1109 setOperationAction(ISD::VSELECT, MVT::v4f32, Legal); 1110 1111 setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f32, Legal); 1112 setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f32, Expand); 1113 setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f32, Expand); 1114 setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f32, Expand); 1115 setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f32, Custom); 1116 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal); 1117 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom); 1118 1119 setOperationAction(ISD::FP_TO_SINT , MVT::v4f32, Legal); 1120 setOperationAction(ISD::FP_TO_UINT , MVT::v4f32, Expand); 1121 1122 setOperationAction(ISD::FNEG , MVT::v4f32, Legal); 1123 setOperationAction(ISD::FABS , MVT::v4f32, Legal); 1124 setOperationAction(ISD::FSIN , MVT::v4f32, Expand); 1125 setOperationAction(ISD::FCOS , MVT::v4f32, Expand); 1126 setOperationAction(ISD::FPOW , MVT::v4f32, Expand); 1127 setOperationAction(ISD::FLOG , MVT::v4f32, Expand); 1128 setOperationAction(ISD::FLOG2 , MVT::v4f32, Expand); 1129 setOperationAction(ISD::FLOG10 , MVT::v4f32, Expand); 1130 setOperationAction(ISD::FEXP , MVT::v4f32, Expand); 1131 setOperationAction(ISD::FEXP2 , MVT::v4f32, Expand); 1132 1133 setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal); 1134 setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal); 1135 1136 setIndexedLoadAction(ISD::PRE_INC, MVT::v4f32, Legal); 1137 setIndexedStoreAction(ISD::PRE_INC, MVT::v4f32, Legal); 1138 1139 addRegisterClass(MVT::v4f32, &PPC::QSRCRegClass); 1140 1141 setOperationAction(ISD::AND , MVT::v4i1, Legal); 1142 setOperationAction(ISD::OR , MVT::v4i1, Legal); 1143 setOperationAction(ISD::XOR , MVT::v4i1, Legal); 1144 1145 if (!Subtarget.useCRBits()) 1146 setOperationAction(ISD::SELECT, MVT::v4i1, Expand); 1147 setOperationAction(ISD::VSELECT, MVT::v4i1, Legal); 1148 1149 setOperationAction(ISD::LOAD , MVT::v4i1, Custom); 1150 setOperationAction(ISD::STORE , MVT::v4i1, Custom); 1151 1152 setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4i1, Custom); 1153 setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4i1, Expand); 1154 setOperationAction(ISD::CONCAT_VECTORS , MVT::v4i1, Expand); 1155 setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4i1, Expand); 1156 setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4i1, Custom); 1157 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i1, Expand); 1158 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i1, Custom); 1159 1160 setOperationAction(ISD::SINT_TO_FP, MVT::v4i1, Custom); 1161 setOperationAction(ISD::UINT_TO_FP, MVT::v4i1, Custom); 1162 1163 addRegisterClass(MVT::v4i1, &PPC::QBRCRegClass); 1164 1165 setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal); 1166 setOperationAction(ISD::FCEIL, MVT::v4f64, Legal); 1167 setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal); 1168 setOperationAction(ISD::FROUND, MVT::v4f64, Legal); 1169 1170 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal); 1171 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal); 1172 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal); 1173 setOperationAction(ISD::FROUND, MVT::v4f32, Legal); 1174 1175 setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Expand); 1176 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand); 1177 1178 // These need to set FE_INEXACT, and so cannot be vectorized here. 1179 setOperationAction(ISD::FRINT, MVT::v4f64, Expand); 1180 setOperationAction(ISD::FRINT, MVT::v4f32, Expand); 1181 1182 if (TM.Options.UnsafeFPMath) { 1183 setOperationAction(ISD::FDIV, MVT::v4f64, Legal); 1184 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal); 1185 1186 setOperationAction(ISD::FDIV, MVT::v4f32, Legal); 1187 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal); 1188 } else { 1189 setOperationAction(ISD::FDIV, MVT::v4f64, Expand); 1190 setOperationAction(ISD::FSQRT, MVT::v4f64, Expand); 1191 1192 setOperationAction(ISD::FDIV, MVT::v4f32, Expand); 1193 setOperationAction(ISD::FSQRT, MVT::v4f32, Expand); 1194 } 1195 1196 // TODO: Handle constrained floating-point operations of v4f64 1197 } 1198 1199 if (Subtarget.has64BitSupport()) 1200 setOperationAction(ISD::PREFETCH, MVT::Other, Legal); 1201 1202 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, isPPC64 ? Legal : Custom); 1203 1204 if (!isPPC64) { 1205 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Expand); 1206 setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand); 1207 } 1208 1209 setBooleanContents(ZeroOrOneBooleanContent); 1210 1211 if (Subtarget.hasAltivec()) { 1212 // Altivec instructions set fields to all zeros or all ones. 1213 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent); 1214 } 1215 1216 if (!isPPC64) { 1217 // These libcalls are not available in 32-bit. 1218 setLibcallName(RTLIB::SHL_I128, nullptr); 1219 setLibcallName(RTLIB::SRL_I128, nullptr); 1220 setLibcallName(RTLIB::SRA_I128, nullptr); 1221 } 1222 1223 setStackPointerRegisterToSaveRestore(isPPC64 ? PPC::X1 : PPC::R1); 1224 1225 // We have target-specific dag combine patterns for the following nodes: 1226 setTargetDAGCombine(ISD::ADD); 1227 setTargetDAGCombine(ISD::SHL); 1228 setTargetDAGCombine(ISD::SRA); 1229 setTargetDAGCombine(ISD::SRL); 1230 setTargetDAGCombine(ISD::MUL); 1231 setTargetDAGCombine(ISD::SINT_TO_FP); 1232 setTargetDAGCombine(ISD::BUILD_VECTOR); 1233 if (Subtarget.hasFPCVT()) 1234 setTargetDAGCombine(ISD::UINT_TO_FP); 1235 setTargetDAGCombine(ISD::LOAD); 1236 setTargetDAGCombine(ISD::STORE); 1237 setTargetDAGCombine(ISD::BR_CC); 1238 if (Subtarget.useCRBits()) 1239 setTargetDAGCombine(ISD::BRCOND); 1240 setTargetDAGCombine(ISD::BSWAP); 1241 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN); 1242 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN); 1243 setTargetDAGCombine(ISD::INTRINSIC_VOID); 1244 1245 setTargetDAGCombine(ISD::SIGN_EXTEND); 1246 setTargetDAGCombine(ISD::ZERO_EXTEND); 1247 setTargetDAGCombine(ISD::ANY_EXTEND); 1248 1249 setTargetDAGCombine(ISD::TRUNCATE); 1250 setTargetDAGCombine(ISD::VECTOR_SHUFFLE); 1251 1252 1253 if (Subtarget.useCRBits()) { 1254 setTargetDAGCombine(ISD::TRUNCATE); 1255 setTargetDAGCombine(ISD::SETCC); 1256 setTargetDAGCombine(ISD::SELECT_CC); 1257 } 1258 1259 // Use reciprocal estimates. 1260 if (TM.Options.UnsafeFPMath) { 1261 setTargetDAGCombine(ISD::FDIV); 1262 setTargetDAGCombine(ISD::FSQRT); 1263 } 1264 1265 if (Subtarget.hasP9Altivec()) { 1266 setTargetDAGCombine(ISD::ABS); 1267 setTargetDAGCombine(ISD::VSELECT); 1268 } 1269 1270 if (EnableQuadPrecision) { 1271 setLibcallName(RTLIB::LOG_F128, "logf128"); 1272 setLibcallName(RTLIB::LOG2_F128, "log2f128"); 1273 setLibcallName(RTLIB::LOG10_F128, "log10f128"); 1274 setLibcallName(RTLIB::EXP_F128, "expf128"); 1275 setLibcallName(RTLIB::EXP2_F128, "exp2f128"); 1276 setLibcallName(RTLIB::SIN_F128, "sinf128"); 1277 setLibcallName(RTLIB::COS_F128, "cosf128"); 1278 setLibcallName(RTLIB::POW_F128, "powf128"); 1279 setLibcallName(RTLIB::FMIN_F128, "fminf128"); 1280 setLibcallName(RTLIB::FMAX_F128, "fmaxf128"); 1281 setLibcallName(RTLIB::POWI_F128, "__powikf2"); 1282 setLibcallName(RTLIB::REM_F128, "fmodf128"); 1283 } 1284 1285 // With 32 condition bits, we don't need to sink (and duplicate) compares 1286 // aggressively in CodeGenPrep. 1287 if (Subtarget.useCRBits()) { 1288 setHasMultipleConditionRegisters(); 1289 setJumpIsExpensive(); 1290 } 1291 1292 setMinFunctionAlignment(Align(4)); 1293 1294 switch (Subtarget.getCPUDirective()) { 1295 default: break; 1296 case PPC::DIR_970: 1297 case PPC::DIR_A2: 1298 case PPC::DIR_E500: 1299 case PPC::DIR_E500mc: 1300 case PPC::DIR_E5500: 1301 case PPC::DIR_PWR4: 1302 case PPC::DIR_PWR5: 1303 case PPC::DIR_PWR5X: 1304 case PPC::DIR_PWR6: 1305 case PPC::DIR_PWR6X: 1306 case PPC::DIR_PWR7: 1307 case PPC::DIR_PWR8: 1308 case PPC::DIR_PWR9: 1309 case PPC::DIR_PWR10: 1310 case PPC::DIR_PWR_FUTURE: 1311 setPrefLoopAlignment(Align(16)); 1312 setPrefFunctionAlignment(Align(16)); 1313 break; 1314 } 1315 1316 if (Subtarget.enableMachineScheduler()) 1317 setSchedulingPreference(Sched::Source); 1318 else 1319 setSchedulingPreference(Sched::Hybrid); 1320 1321 computeRegisterProperties(STI.getRegisterInfo()); 1322 1323 // The Freescale cores do better with aggressive inlining of memcpy and 1324 // friends. GCC uses same threshold of 128 bytes (= 32 word stores). 1325 if (Subtarget.getCPUDirective() == PPC::DIR_E500mc || 1326 Subtarget.getCPUDirective() == PPC::DIR_E5500) { 1327 MaxStoresPerMemset = 32; 1328 MaxStoresPerMemsetOptSize = 16; 1329 MaxStoresPerMemcpy = 32; 1330 MaxStoresPerMemcpyOptSize = 8; 1331 MaxStoresPerMemmove = 32; 1332 MaxStoresPerMemmoveOptSize = 8; 1333 } else if (Subtarget.getCPUDirective() == PPC::DIR_A2) { 1334 // The A2 also benefits from (very) aggressive inlining of memcpy and 1335 // friends. The overhead of a the function call, even when warm, can be 1336 // over one hundred cycles. 1337 MaxStoresPerMemset = 128; 1338 MaxStoresPerMemcpy = 128; 1339 MaxStoresPerMemmove = 128; 1340 MaxLoadsPerMemcmp = 128; 1341 } else { 1342 MaxLoadsPerMemcmp = 8; 1343 MaxLoadsPerMemcmpOptSize = 4; 1344 } 1345 1346 // Let the subtarget (CPU) decide if a predictable select is more expensive 1347 // than the corresponding branch. This information is used in CGP to decide 1348 // when to convert selects into branches. 1349 PredictableSelectIsExpensive = Subtarget.isPredictableSelectIsExpensive(); 1350 } 1351 1352 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine 1353 /// the desired ByVal argument alignment. 1354 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign, 1355 unsigned MaxMaxAlign) { 1356 if (MaxAlign == MaxMaxAlign) 1357 return; 1358 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) { 1359 if (MaxMaxAlign >= 32 && 1360 VTy->getPrimitiveSizeInBits().getFixedSize() >= 256) 1361 MaxAlign = 32; 1362 else if (VTy->getPrimitiveSizeInBits().getFixedSize() >= 128 && 1363 MaxAlign < 16) 1364 MaxAlign = 16; 1365 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) { 1366 unsigned EltAlign = 0; 1367 getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign); 1368 if (EltAlign > MaxAlign) 1369 MaxAlign = EltAlign; 1370 } else if (StructType *STy = dyn_cast<StructType>(Ty)) { 1371 for (auto *EltTy : STy->elements()) { 1372 unsigned EltAlign = 0; 1373 getMaxByValAlign(EltTy, EltAlign, MaxMaxAlign); 1374 if (EltAlign > MaxAlign) 1375 MaxAlign = EltAlign; 1376 if (MaxAlign == MaxMaxAlign) 1377 break; 1378 } 1379 } 1380 } 1381 1382 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate 1383 /// function arguments in the caller parameter area. 1384 unsigned PPCTargetLowering::getByValTypeAlignment(Type *Ty, 1385 const DataLayout &DL) const { 1386 // 16byte and wider vectors are passed on 16byte boundary. 1387 // The rest is 8 on PPC64 and 4 on PPC32 boundary. 1388 unsigned Align = Subtarget.isPPC64() ? 8 : 4; 1389 if (Subtarget.hasAltivec() || Subtarget.hasQPX()) 1390 getMaxByValAlign(Ty, Align, Subtarget.hasQPX() ? 32 : 16); 1391 return Align; 1392 } 1393 1394 bool PPCTargetLowering::useSoftFloat() const { 1395 return Subtarget.useSoftFloat(); 1396 } 1397 1398 bool PPCTargetLowering::hasSPE() const { 1399 return Subtarget.hasSPE(); 1400 } 1401 1402 bool PPCTargetLowering::preferIncOfAddToSubOfNot(EVT VT) const { 1403 return VT.isScalarInteger(); 1404 } 1405 1406 /// isMulhCheaperThanMulShift - Return true if a mulh[s|u] node for a specific 1407 /// type is cheaper than a multiply followed by a shift. 1408 /// This is true for words and doublewords on 64-bit PowerPC. 1409 bool PPCTargetLowering::isMulhCheaperThanMulShift(EVT Type) const { 1410 if (Subtarget.isPPC64() && (isOperationLegal(ISD::MULHS, Type) || 1411 isOperationLegal(ISD::MULHU, Type))) 1412 return true; 1413 return TargetLowering::isMulhCheaperThanMulShift(Type); 1414 } 1415 1416 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const { 1417 switch ((PPCISD::NodeType)Opcode) { 1418 case PPCISD::FIRST_NUMBER: break; 1419 case PPCISD::FSEL: return "PPCISD::FSEL"; 1420 case PPCISD::XSMAXCDP: return "PPCISD::XSMAXCDP"; 1421 case PPCISD::XSMINCDP: return "PPCISD::XSMINCDP"; 1422 case PPCISD::FCFID: return "PPCISD::FCFID"; 1423 case PPCISD::FCFIDU: return "PPCISD::FCFIDU"; 1424 case PPCISD::FCFIDS: return "PPCISD::FCFIDS"; 1425 case PPCISD::FCFIDUS: return "PPCISD::FCFIDUS"; 1426 case PPCISD::FCTIDZ: return "PPCISD::FCTIDZ"; 1427 case PPCISD::FCTIWZ: return "PPCISD::FCTIWZ"; 1428 case PPCISD::FCTIDUZ: return "PPCISD::FCTIDUZ"; 1429 case PPCISD::FCTIWUZ: return "PPCISD::FCTIWUZ"; 1430 case PPCISD::FP_TO_UINT_IN_VSR: 1431 return "PPCISD::FP_TO_UINT_IN_VSR,"; 1432 case PPCISD::FP_TO_SINT_IN_VSR: 1433 return "PPCISD::FP_TO_SINT_IN_VSR"; 1434 case PPCISD::FRE: return "PPCISD::FRE"; 1435 case PPCISD::FRSQRTE: return "PPCISD::FRSQRTE"; 1436 case PPCISD::STFIWX: return "PPCISD::STFIWX"; 1437 case PPCISD::VMADDFP: return "PPCISD::VMADDFP"; 1438 case PPCISD::VNMSUBFP: return "PPCISD::VNMSUBFP"; 1439 case PPCISD::VPERM: return "PPCISD::VPERM"; 1440 case PPCISD::XXSPLT: return "PPCISD::XXSPLT"; 1441 case PPCISD::VECINSERT: return "PPCISD::VECINSERT"; 1442 case PPCISD::XXPERMDI: return "PPCISD::XXPERMDI"; 1443 case PPCISD::VECSHL: return "PPCISD::VECSHL"; 1444 case PPCISD::CMPB: return "PPCISD::CMPB"; 1445 case PPCISD::Hi: return "PPCISD::Hi"; 1446 case PPCISD::Lo: return "PPCISD::Lo"; 1447 case PPCISD::TOC_ENTRY: return "PPCISD::TOC_ENTRY"; 1448 case PPCISD::ATOMIC_CMP_SWAP_8: return "PPCISD::ATOMIC_CMP_SWAP_8"; 1449 case PPCISD::ATOMIC_CMP_SWAP_16: return "PPCISD::ATOMIC_CMP_SWAP_16"; 1450 case PPCISD::DYNALLOC: return "PPCISD::DYNALLOC"; 1451 case PPCISD::DYNAREAOFFSET: return "PPCISD::DYNAREAOFFSET"; 1452 case PPCISD::GlobalBaseReg: return "PPCISD::GlobalBaseReg"; 1453 case PPCISD::SRL: return "PPCISD::SRL"; 1454 case PPCISD::SRA: return "PPCISD::SRA"; 1455 case PPCISD::SHL: return "PPCISD::SHL"; 1456 case PPCISD::SRA_ADDZE: return "PPCISD::SRA_ADDZE"; 1457 case PPCISD::CALL: return "PPCISD::CALL"; 1458 case PPCISD::CALL_NOP: return "PPCISD::CALL_NOP"; 1459 case PPCISD::CALL_NOTOC: return "PPCISD::CALL_NOTOC"; 1460 case PPCISD::MTCTR: return "PPCISD::MTCTR"; 1461 case PPCISD::BCTRL: return "PPCISD::BCTRL"; 1462 case PPCISD::BCTRL_LOAD_TOC: return "PPCISD::BCTRL_LOAD_TOC"; 1463 case PPCISD::RET_FLAG: return "PPCISD::RET_FLAG"; 1464 case PPCISD::READ_TIME_BASE: return "PPCISD::READ_TIME_BASE"; 1465 case PPCISD::EH_SJLJ_SETJMP: return "PPCISD::EH_SJLJ_SETJMP"; 1466 case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP"; 1467 case PPCISD::MFOCRF: return "PPCISD::MFOCRF"; 1468 case PPCISD::MFVSR: return "PPCISD::MFVSR"; 1469 case PPCISD::MTVSRA: return "PPCISD::MTVSRA"; 1470 case PPCISD::MTVSRZ: return "PPCISD::MTVSRZ"; 1471 case PPCISD::SINT_VEC_TO_FP: return "PPCISD::SINT_VEC_TO_FP"; 1472 case PPCISD::UINT_VEC_TO_FP: return "PPCISD::UINT_VEC_TO_FP"; 1473 case PPCISD::ANDI_rec_1_EQ_BIT: 1474 return "PPCISD::ANDI_rec_1_EQ_BIT"; 1475 case PPCISD::ANDI_rec_1_GT_BIT: 1476 return "PPCISD::ANDI_rec_1_GT_BIT"; 1477 case PPCISD::VCMP: return "PPCISD::VCMP"; 1478 case PPCISD::VCMPo: return "PPCISD::VCMPo"; 1479 case PPCISD::LBRX: return "PPCISD::LBRX"; 1480 case PPCISD::STBRX: return "PPCISD::STBRX"; 1481 case PPCISD::LFIWAX: return "PPCISD::LFIWAX"; 1482 case PPCISD::LFIWZX: return "PPCISD::LFIWZX"; 1483 case PPCISD::LXSIZX: return "PPCISD::LXSIZX"; 1484 case PPCISD::STXSIX: return "PPCISD::STXSIX"; 1485 case PPCISD::VEXTS: return "PPCISD::VEXTS"; 1486 case PPCISD::LXVD2X: return "PPCISD::LXVD2X"; 1487 case PPCISD::STXVD2X: return "PPCISD::STXVD2X"; 1488 case PPCISD::LOAD_VEC_BE: return "PPCISD::LOAD_VEC_BE"; 1489 case PPCISD::STORE_VEC_BE: return "PPCISD::STORE_VEC_BE"; 1490 case PPCISD::ST_VSR_SCAL_INT: 1491 return "PPCISD::ST_VSR_SCAL_INT"; 1492 case PPCISD::COND_BRANCH: return "PPCISD::COND_BRANCH"; 1493 case PPCISD::BDNZ: return "PPCISD::BDNZ"; 1494 case PPCISD::BDZ: return "PPCISD::BDZ"; 1495 case PPCISD::MFFS: return "PPCISD::MFFS"; 1496 case PPCISD::FADDRTZ: return "PPCISD::FADDRTZ"; 1497 case PPCISD::TC_RETURN: return "PPCISD::TC_RETURN"; 1498 case PPCISD::CR6SET: return "PPCISD::CR6SET"; 1499 case PPCISD::CR6UNSET: return "PPCISD::CR6UNSET"; 1500 case PPCISD::PPC32_GOT: return "PPCISD::PPC32_GOT"; 1501 case PPCISD::PPC32_PICGOT: return "PPCISD::PPC32_PICGOT"; 1502 case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA"; 1503 case PPCISD::LD_GOT_TPREL_L: return "PPCISD::LD_GOT_TPREL_L"; 1504 case PPCISD::ADD_TLS: return "PPCISD::ADD_TLS"; 1505 case PPCISD::ADDIS_TLSGD_HA: return "PPCISD::ADDIS_TLSGD_HA"; 1506 case PPCISD::ADDI_TLSGD_L: return "PPCISD::ADDI_TLSGD_L"; 1507 case PPCISD::GET_TLS_ADDR: return "PPCISD::GET_TLS_ADDR"; 1508 case PPCISD::ADDI_TLSGD_L_ADDR: return "PPCISD::ADDI_TLSGD_L_ADDR"; 1509 case PPCISD::ADDIS_TLSLD_HA: return "PPCISD::ADDIS_TLSLD_HA"; 1510 case PPCISD::ADDI_TLSLD_L: return "PPCISD::ADDI_TLSLD_L"; 1511 case PPCISD::GET_TLSLD_ADDR: return "PPCISD::GET_TLSLD_ADDR"; 1512 case PPCISD::ADDI_TLSLD_L_ADDR: return "PPCISD::ADDI_TLSLD_L_ADDR"; 1513 case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA"; 1514 case PPCISD::ADDI_DTPREL_L: return "PPCISD::ADDI_DTPREL_L"; 1515 case PPCISD::VADD_SPLAT: return "PPCISD::VADD_SPLAT"; 1516 case PPCISD::SC: return "PPCISD::SC"; 1517 case PPCISD::CLRBHRB: return "PPCISD::CLRBHRB"; 1518 case PPCISD::MFBHRBE: return "PPCISD::MFBHRBE"; 1519 case PPCISD::RFEBB: return "PPCISD::RFEBB"; 1520 case PPCISD::XXSWAPD: return "PPCISD::XXSWAPD"; 1521 case PPCISD::SWAP_NO_CHAIN: return "PPCISD::SWAP_NO_CHAIN"; 1522 case PPCISD::VABSD: return "PPCISD::VABSD"; 1523 case PPCISD::QVFPERM: return "PPCISD::QVFPERM"; 1524 case PPCISD::QVGPCI: return "PPCISD::QVGPCI"; 1525 case PPCISD::QVALIGNI: return "PPCISD::QVALIGNI"; 1526 case PPCISD::QVESPLATI: return "PPCISD::QVESPLATI"; 1527 case PPCISD::QBFLT: return "PPCISD::QBFLT"; 1528 case PPCISD::QVLFSb: return "PPCISD::QVLFSb"; 1529 case PPCISD::BUILD_FP128: return "PPCISD::BUILD_FP128"; 1530 case PPCISD::BUILD_SPE64: return "PPCISD::BUILD_SPE64"; 1531 case PPCISD::EXTRACT_SPE: return "PPCISD::EXTRACT_SPE"; 1532 case PPCISD::EXTSWSLI: return "PPCISD::EXTSWSLI"; 1533 case PPCISD::LD_VSX_LH: return "PPCISD::LD_VSX_LH"; 1534 case PPCISD::FP_EXTEND_HALF: return "PPCISD::FP_EXTEND_HALF"; 1535 case PPCISD::MAT_PCREL_ADDR: return "PPCISD::MAT_PCREL_ADDR"; 1536 case PPCISD::LD_SPLAT: return "PPCISD::LD_SPLAT"; 1537 } 1538 return nullptr; 1539 } 1540 1541 EVT PPCTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &C, 1542 EVT VT) const { 1543 if (!VT.isVector()) 1544 return Subtarget.useCRBits() ? MVT::i1 : MVT::i32; 1545 1546 if (Subtarget.hasQPX()) 1547 return EVT::getVectorVT(C, MVT::i1, VT.getVectorNumElements()); 1548 1549 return VT.changeVectorElementTypeToInteger(); 1550 } 1551 1552 bool PPCTargetLowering::enableAggressiveFMAFusion(EVT VT) const { 1553 assert(VT.isFloatingPoint() && "Non-floating-point FMA?"); 1554 return true; 1555 } 1556 1557 //===----------------------------------------------------------------------===// 1558 // Node matching predicates, for use by the tblgen matching code. 1559 //===----------------------------------------------------------------------===// 1560 1561 /// isFloatingPointZero - Return true if this is 0.0 or -0.0. 1562 static bool isFloatingPointZero(SDValue Op) { 1563 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) 1564 return CFP->getValueAPF().isZero(); 1565 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) { 1566 // Maybe this has already been legalized into the constant pool? 1567 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1))) 1568 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal())) 1569 return CFP->getValueAPF().isZero(); 1570 } 1571 return false; 1572 } 1573 1574 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode. Return 1575 /// true if Op is undef or if it matches the specified value. 1576 static bool isConstantOrUndef(int Op, int Val) { 1577 return Op < 0 || Op == Val; 1578 } 1579 1580 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a 1581 /// VPKUHUM instruction. 1582 /// The ShuffleKind distinguishes between big-endian operations with 1583 /// two different inputs (0), either-endian operations with two identical 1584 /// inputs (1), and little-endian operations with two different inputs (2). 1585 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td). 1586 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind, 1587 SelectionDAG &DAG) { 1588 bool IsLE = DAG.getDataLayout().isLittleEndian(); 1589 if (ShuffleKind == 0) { 1590 if (IsLE) 1591 return false; 1592 for (unsigned i = 0; i != 16; ++i) 1593 if (!isConstantOrUndef(N->getMaskElt(i), i*2+1)) 1594 return false; 1595 } else if (ShuffleKind == 2) { 1596 if (!IsLE) 1597 return false; 1598 for (unsigned i = 0; i != 16; ++i) 1599 if (!isConstantOrUndef(N->getMaskElt(i), i*2)) 1600 return false; 1601 } else if (ShuffleKind == 1) { 1602 unsigned j = IsLE ? 0 : 1; 1603 for (unsigned i = 0; i != 8; ++i) 1604 if (!isConstantOrUndef(N->getMaskElt(i), i*2+j) || 1605 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j)) 1606 return false; 1607 } 1608 return true; 1609 } 1610 1611 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a 1612 /// VPKUWUM instruction. 1613 /// The ShuffleKind distinguishes between big-endian operations with 1614 /// two different inputs (0), either-endian operations with two identical 1615 /// inputs (1), and little-endian operations with two different inputs (2). 1616 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td). 1617 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind, 1618 SelectionDAG &DAG) { 1619 bool IsLE = DAG.getDataLayout().isLittleEndian(); 1620 if (ShuffleKind == 0) { 1621 if (IsLE) 1622 return false; 1623 for (unsigned i = 0; i != 16; i += 2) 1624 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+2) || 1625 !isConstantOrUndef(N->getMaskElt(i+1), i*2+3)) 1626 return false; 1627 } else if (ShuffleKind == 2) { 1628 if (!IsLE) 1629 return false; 1630 for (unsigned i = 0; i != 16; i += 2) 1631 if (!isConstantOrUndef(N->getMaskElt(i ), i*2) || 1632 !isConstantOrUndef(N->getMaskElt(i+1), i*2+1)) 1633 return false; 1634 } else if (ShuffleKind == 1) { 1635 unsigned j = IsLE ? 0 : 2; 1636 for (unsigned i = 0; i != 8; i += 2) 1637 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+j) || 1638 !isConstantOrUndef(N->getMaskElt(i+1), i*2+j+1) || 1639 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j) || 1640 !isConstantOrUndef(N->getMaskElt(i+9), i*2+j+1)) 1641 return false; 1642 } 1643 return true; 1644 } 1645 1646 /// isVPKUDUMShuffleMask - Return true if this is the shuffle mask for a 1647 /// VPKUDUM instruction, AND the VPKUDUM instruction exists for the 1648 /// current subtarget. 1649 /// 1650 /// The ShuffleKind distinguishes between big-endian operations with 1651 /// two different inputs (0), either-endian operations with two identical 1652 /// inputs (1), and little-endian operations with two different inputs (2). 1653 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td). 1654 bool PPC::isVPKUDUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind, 1655 SelectionDAG &DAG) { 1656 const PPCSubtarget& Subtarget = 1657 static_cast<const PPCSubtarget&>(DAG.getSubtarget()); 1658 if (!Subtarget.hasP8Vector()) 1659 return false; 1660 1661 bool IsLE = DAG.getDataLayout().isLittleEndian(); 1662 if (ShuffleKind == 0) { 1663 if (IsLE) 1664 return false; 1665 for (unsigned i = 0; i != 16; i += 4) 1666 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+4) || 1667 !isConstantOrUndef(N->getMaskElt(i+1), i*2+5) || 1668 !isConstantOrUndef(N->getMaskElt(i+2), i*2+6) || 1669 !isConstantOrUndef(N->getMaskElt(i+3), i*2+7)) 1670 return false; 1671 } else if (ShuffleKind == 2) { 1672 if (!IsLE) 1673 return false; 1674 for (unsigned i = 0; i != 16; i += 4) 1675 if (!isConstantOrUndef(N->getMaskElt(i ), i*2) || 1676 !isConstantOrUndef(N->getMaskElt(i+1), i*2+1) || 1677 !isConstantOrUndef(N->getMaskElt(i+2), i*2+2) || 1678 !isConstantOrUndef(N->getMaskElt(i+3), i*2+3)) 1679 return false; 1680 } else if (ShuffleKind == 1) { 1681 unsigned j = IsLE ? 0 : 4; 1682 for (unsigned i = 0; i != 8; i += 4) 1683 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+j) || 1684 !isConstantOrUndef(N->getMaskElt(i+1), i*2+j+1) || 1685 !isConstantOrUndef(N->getMaskElt(i+2), i*2+j+2) || 1686 !isConstantOrUndef(N->getMaskElt(i+3), i*2+j+3) || 1687 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j) || 1688 !isConstantOrUndef(N->getMaskElt(i+9), i*2+j+1) || 1689 !isConstantOrUndef(N->getMaskElt(i+10), i*2+j+2) || 1690 !isConstantOrUndef(N->getMaskElt(i+11), i*2+j+3)) 1691 return false; 1692 } 1693 return true; 1694 } 1695 1696 /// isVMerge - Common function, used to match vmrg* shuffles. 1697 /// 1698 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize, 1699 unsigned LHSStart, unsigned RHSStart) { 1700 if (N->getValueType(0) != MVT::v16i8) 1701 return false; 1702 assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) && 1703 "Unsupported merge size!"); 1704 1705 for (unsigned i = 0; i != 8/UnitSize; ++i) // Step over units 1706 for (unsigned j = 0; j != UnitSize; ++j) { // Step over bytes within unit 1707 if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j), 1708 LHSStart+j+i*UnitSize) || 1709 !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j), 1710 RHSStart+j+i*UnitSize)) 1711 return false; 1712 } 1713 return true; 1714 } 1715 1716 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for 1717 /// a VMRGL* instruction with the specified unit size (1,2 or 4 bytes). 1718 /// The ShuffleKind distinguishes between big-endian merges with two 1719 /// different inputs (0), either-endian merges with two identical inputs (1), 1720 /// and little-endian merges with two different inputs (2). For the latter, 1721 /// the input operands are swapped (see PPCInstrAltivec.td). 1722 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize, 1723 unsigned ShuffleKind, SelectionDAG &DAG) { 1724 if (DAG.getDataLayout().isLittleEndian()) { 1725 if (ShuffleKind == 1) // unary 1726 return isVMerge(N, UnitSize, 0, 0); 1727 else if (ShuffleKind == 2) // swapped 1728 return isVMerge(N, UnitSize, 0, 16); 1729 else 1730 return false; 1731 } else { 1732 if (ShuffleKind == 1) // unary 1733 return isVMerge(N, UnitSize, 8, 8); 1734 else if (ShuffleKind == 0) // normal 1735 return isVMerge(N, UnitSize, 8, 24); 1736 else 1737 return false; 1738 } 1739 } 1740 1741 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for 1742 /// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes). 1743 /// The ShuffleKind distinguishes between big-endian merges with two 1744 /// different inputs (0), either-endian merges with two identical inputs (1), 1745 /// and little-endian merges with two different inputs (2). For the latter, 1746 /// the input operands are swapped (see PPCInstrAltivec.td). 1747 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize, 1748 unsigned ShuffleKind, SelectionDAG &DAG) { 1749 if (DAG.getDataLayout().isLittleEndian()) { 1750 if (ShuffleKind == 1) // unary 1751 return isVMerge(N, UnitSize, 8, 8); 1752 else if (ShuffleKind == 2) // swapped 1753 return isVMerge(N, UnitSize, 8, 24); 1754 else 1755 return false; 1756 } else { 1757 if (ShuffleKind == 1) // unary 1758 return isVMerge(N, UnitSize, 0, 0); 1759 else if (ShuffleKind == 0) // normal 1760 return isVMerge(N, UnitSize, 0, 16); 1761 else 1762 return false; 1763 } 1764 } 1765 1766 /** 1767 * Common function used to match vmrgew and vmrgow shuffles 1768 * 1769 * The indexOffset determines whether to look for even or odd words in 1770 * the shuffle mask. This is based on the of the endianness of the target 1771 * machine. 1772 * - Little Endian: 1773 * - Use offset of 0 to check for odd elements 1774 * - Use offset of 4 to check for even elements 1775 * - Big Endian: 1776 * - Use offset of 0 to check for even elements 1777 * - Use offset of 4 to check for odd elements 1778 * A detailed description of the vector element ordering for little endian and 1779 * big endian can be found at 1780 * http://www.ibm.com/developerworks/library/l-ibm-xl-c-cpp-compiler/index.html 1781 * Targeting your applications - what little endian and big endian IBM XL C/C++ 1782 * compiler differences mean to you 1783 * 1784 * The mask to the shuffle vector instruction specifies the indices of the 1785 * elements from the two input vectors to place in the result. The elements are 1786 * numbered in array-access order, starting with the first vector. These vectors 1787 * are always of type v16i8, thus each vector will contain 16 elements of size 1788 * 8. More info on the shuffle vector can be found in the 1789 * http://llvm.org/docs/LangRef.html#shufflevector-instruction 1790 * Language Reference. 1791 * 1792 * The RHSStartValue indicates whether the same input vectors are used (unary) 1793 * or two different input vectors are used, based on the following: 1794 * - If the instruction uses the same vector for both inputs, the range of the 1795 * indices will be 0 to 15. In this case, the RHSStart value passed should 1796 * be 0. 1797 * - If the instruction has two different vectors then the range of the 1798 * indices will be 0 to 31. In this case, the RHSStart value passed should 1799 * be 16 (indices 0-15 specify elements in the first vector while indices 16 1800 * to 31 specify elements in the second vector). 1801 * 1802 * \param[in] N The shuffle vector SD Node to analyze 1803 * \param[in] IndexOffset Specifies whether to look for even or odd elements 1804 * \param[in] RHSStartValue Specifies the starting index for the righthand input 1805 * vector to the shuffle_vector instruction 1806 * \return true iff this shuffle vector represents an even or odd word merge 1807 */ 1808 static bool isVMerge(ShuffleVectorSDNode *N, unsigned IndexOffset, 1809 unsigned RHSStartValue) { 1810 if (N->getValueType(0) != MVT::v16i8) 1811 return false; 1812 1813 for (unsigned i = 0; i < 2; ++i) 1814 for (unsigned j = 0; j < 4; ++j) 1815 if (!isConstantOrUndef(N->getMaskElt(i*4+j), 1816 i*RHSStartValue+j+IndexOffset) || 1817 !isConstantOrUndef(N->getMaskElt(i*4+j+8), 1818 i*RHSStartValue+j+IndexOffset+8)) 1819 return false; 1820 return true; 1821 } 1822 1823 /** 1824 * Determine if the specified shuffle mask is suitable for the vmrgew or 1825 * vmrgow instructions. 1826 * 1827 * \param[in] N The shuffle vector SD Node to analyze 1828 * \param[in] CheckEven Check for an even merge (true) or an odd merge (false) 1829 * \param[in] ShuffleKind Identify the type of merge: 1830 * - 0 = big-endian merge with two different inputs; 1831 * - 1 = either-endian merge with two identical inputs; 1832 * - 2 = little-endian merge with two different inputs (inputs are swapped for 1833 * little-endian merges). 1834 * \param[in] DAG The current SelectionDAG 1835 * \return true iff this shuffle mask 1836 */ 1837 bool PPC::isVMRGEOShuffleMask(ShuffleVectorSDNode *N, bool CheckEven, 1838 unsigned ShuffleKind, SelectionDAG &DAG) { 1839 if (DAG.getDataLayout().isLittleEndian()) { 1840 unsigned indexOffset = CheckEven ? 4 : 0; 1841 if (ShuffleKind == 1) // Unary 1842 return isVMerge(N, indexOffset, 0); 1843 else if (ShuffleKind == 2) // swapped 1844 return isVMerge(N, indexOffset, 16); 1845 else 1846 return false; 1847 } 1848 else { 1849 unsigned indexOffset = CheckEven ? 0 : 4; 1850 if (ShuffleKind == 1) // Unary 1851 return isVMerge(N, indexOffset, 0); 1852 else if (ShuffleKind == 0) // Normal 1853 return isVMerge(N, indexOffset, 16); 1854 else 1855 return false; 1856 } 1857 return false; 1858 } 1859 1860 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift 1861 /// amount, otherwise return -1. 1862 /// The ShuffleKind distinguishes between big-endian operations with two 1863 /// different inputs (0), either-endian operations with two identical inputs 1864 /// (1), and little-endian operations with two different inputs (2). For the 1865 /// latter, the input operands are swapped (see PPCInstrAltivec.td). 1866 int PPC::isVSLDOIShuffleMask(SDNode *N, unsigned ShuffleKind, 1867 SelectionDAG &DAG) { 1868 if (N->getValueType(0) != MVT::v16i8) 1869 return -1; 1870 1871 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 1872 1873 // Find the first non-undef value in the shuffle mask. 1874 unsigned i; 1875 for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i) 1876 /*search*/; 1877 1878 if (i == 16) return -1; // all undef. 1879 1880 // Otherwise, check to see if the rest of the elements are consecutively 1881 // numbered from this value. 1882 unsigned ShiftAmt = SVOp->getMaskElt(i); 1883 if (ShiftAmt < i) return -1; 1884 1885 ShiftAmt -= i; 1886 bool isLE = DAG.getDataLayout().isLittleEndian(); 1887 1888 if ((ShuffleKind == 0 && !isLE) || (ShuffleKind == 2 && isLE)) { 1889 // Check the rest of the elements to see if they are consecutive. 1890 for (++i; i != 16; ++i) 1891 if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i)) 1892 return -1; 1893 } else if (ShuffleKind == 1) { 1894 // Check the rest of the elements to see if they are consecutive. 1895 for (++i; i != 16; ++i) 1896 if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15)) 1897 return -1; 1898 } else 1899 return -1; 1900 1901 if (isLE) 1902 ShiftAmt = 16 - ShiftAmt; 1903 1904 return ShiftAmt; 1905 } 1906 1907 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand 1908 /// specifies a splat of a single element that is suitable for input to 1909 /// one of the splat operations (VSPLTB/VSPLTH/VSPLTW/XXSPLTW/LXVDSX/etc.). 1910 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) { 1911 assert(N->getValueType(0) == MVT::v16i8 && isPowerOf2_32(EltSize) && 1912 EltSize <= 8 && "Can only handle 1,2,4,8 byte element sizes"); 1913 1914 // The consecutive indices need to specify an element, not part of two 1915 // different elements. So abandon ship early if this isn't the case. 1916 if (N->getMaskElt(0) % EltSize != 0) 1917 return false; 1918 1919 // This is a splat operation if each element of the permute is the same, and 1920 // if the value doesn't reference the second vector. 1921 unsigned ElementBase = N->getMaskElt(0); 1922 1923 // FIXME: Handle UNDEF elements too! 1924 if (ElementBase >= 16) 1925 return false; 1926 1927 // Check that the indices are consecutive, in the case of a multi-byte element 1928 // splatted with a v16i8 mask. 1929 for (unsigned i = 1; i != EltSize; ++i) 1930 if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase)) 1931 return false; 1932 1933 for (unsigned i = EltSize, e = 16; i != e; i += EltSize) { 1934 if (N->getMaskElt(i) < 0) continue; 1935 for (unsigned j = 0; j != EltSize; ++j) 1936 if (N->getMaskElt(i+j) != N->getMaskElt(j)) 1937 return false; 1938 } 1939 return true; 1940 } 1941 1942 /// Check that the mask is shuffling N byte elements. Within each N byte 1943 /// element of the mask, the indices could be either in increasing or 1944 /// decreasing order as long as they are consecutive. 1945 /// \param[in] N the shuffle vector SD Node to analyze 1946 /// \param[in] Width the element width in bytes, could be 2/4/8/16 (HalfWord/ 1947 /// Word/DoubleWord/QuadWord). 1948 /// \param[in] StepLen the delta indices number among the N byte element, if 1949 /// the mask is in increasing/decreasing order then it is 1/-1. 1950 /// \return true iff the mask is shuffling N byte elements. 1951 static bool isNByteElemShuffleMask(ShuffleVectorSDNode *N, unsigned Width, 1952 int StepLen) { 1953 assert((Width == 2 || Width == 4 || Width == 8 || Width == 16) && 1954 "Unexpected element width."); 1955 assert((StepLen == 1 || StepLen == -1) && "Unexpected element width."); 1956 1957 unsigned NumOfElem = 16 / Width; 1958 unsigned MaskVal[16]; // Width is never greater than 16 1959 for (unsigned i = 0; i < NumOfElem; ++i) { 1960 MaskVal[0] = N->getMaskElt(i * Width); 1961 if ((StepLen == 1) && (MaskVal[0] % Width)) { 1962 return false; 1963 } else if ((StepLen == -1) && ((MaskVal[0] + 1) % Width)) { 1964 return false; 1965 } 1966 1967 for (unsigned int j = 1; j < Width; ++j) { 1968 MaskVal[j] = N->getMaskElt(i * Width + j); 1969 if (MaskVal[j] != MaskVal[j-1] + StepLen) { 1970 return false; 1971 } 1972 } 1973 } 1974 1975 return true; 1976 } 1977 1978 bool PPC::isXXINSERTWMask(ShuffleVectorSDNode *N, unsigned &ShiftElts, 1979 unsigned &InsertAtByte, bool &Swap, bool IsLE) { 1980 if (!isNByteElemShuffleMask(N, 4, 1)) 1981 return false; 1982 1983 // Now we look at mask elements 0,4,8,12 1984 unsigned M0 = N->getMaskElt(0) / 4; 1985 unsigned M1 = N->getMaskElt(4) / 4; 1986 unsigned M2 = N->getMaskElt(8) / 4; 1987 unsigned M3 = N->getMaskElt(12) / 4; 1988 unsigned LittleEndianShifts[] = { 2, 1, 0, 3 }; 1989 unsigned BigEndianShifts[] = { 3, 0, 1, 2 }; 1990 1991 // Below, let H and L be arbitrary elements of the shuffle mask 1992 // where H is in the range [4,7] and L is in the range [0,3]. 1993 // H, 1, 2, 3 or L, 5, 6, 7 1994 if ((M0 > 3 && M1 == 1 && M2 == 2 && M3 == 3) || 1995 (M0 < 4 && M1 == 5 && M2 == 6 && M3 == 7)) { 1996 ShiftElts = IsLE ? LittleEndianShifts[M0 & 0x3] : BigEndianShifts[M0 & 0x3]; 1997 InsertAtByte = IsLE ? 12 : 0; 1998 Swap = M0 < 4; 1999 return true; 2000 } 2001 // 0, H, 2, 3 or 4, L, 6, 7 2002 if ((M1 > 3 && M0 == 0 && M2 == 2 && M3 == 3) || 2003 (M1 < 4 && M0 == 4 && M2 == 6 && M3 == 7)) { 2004 ShiftElts = IsLE ? LittleEndianShifts[M1 & 0x3] : BigEndianShifts[M1 & 0x3]; 2005 InsertAtByte = IsLE ? 8 : 4; 2006 Swap = M1 < 4; 2007 return true; 2008 } 2009 // 0, 1, H, 3 or 4, 5, L, 7 2010 if ((M2 > 3 && M0 == 0 && M1 == 1 && M3 == 3) || 2011 (M2 < 4 && M0 == 4 && M1 == 5 && M3 == 7)) { 2012 ShiftElts = IsLE ? LittleEndianShifts[M2 & 0x3] : BigEndianShifts[M2 & 0x3]; 2013 InsertAtByte = IsLE ? 4 : 8; 2014 Swap = M2 < 4; 2015 return true; 2016 } 2017 // 0, 1, 2, H or 4, 5, 6, L 2018 if ((M3 > 3 && M0 == 0 && M1 == 1 && M2 == 2) || 2019 (M3 < 4 && M0 == 4 && M1 == 5 && M2 == 6)) { 2020 ShiftElts = IsLE ? LittleEndianShifts[M3 & 0x3] : BigEndianShifts[M3 & 0x3]; 2021 InsertAtByte = IsLE ? 0 : 12; 2022 Swap = M3 < 4; 2023 return true; 2024 } 2025 2026 // If both vector operands for the shuffle are the same vector, the mask will 2027 // contain only elements from the first one and the second one will be undef. 2028 if (N->getOperand(1).isUndef()) { 2029 ShiftElts = 0; 2030 Swap = true; 2031 unsigned XXINSERTWSrcElem = IsLE ? 2 : 1; 2032 if (M0 == XXINSERTWSrcElem && M1 == 1 && M2 == 2 && M3 == 3) { 2033 InsertAtByte = IsLE ? 12 : 0; 2034 return true; 2035 } 2036 if (M0 == 0 && M1 == XXINSERTWSrcElem && M2 == 2 && M3 == 3) { 2037 InsertAtByte = IsLE ? 8 : 4; 2038 return true; 2039 } 2040 if (M0 == 0 && M1 == 1 && M2 == XXINSERTWSrcElem && M3 == 3) { 2041 InsertAtByte = IsLE ? 4 : 8; 2042 return true; 2043 } 2044 if (M0 == 0 && M1 == 1 && M2 == 2 && M3 == XXINSERTWSrcElem) { 2045 InsertAtByte = IsLE ? 0 : 12; 2046 return true; 2047 } 2048 } 2049 2050 return false; 2051 } 2052 2053 bool PPC::isXXSLDWIShuffleMask(ShuffleVectorSDNode *N, unsigned &ShiftElts, 2054 bool &Swap, bool IsLE) { 2055 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8"); 2056 // Ensure each byte index of the word is consecutive. 2057 if (!isNByteElemShuffleMask(N, 4, 1)) 2058 return false; 2059 2060 // Now we look at mask elements 0,4,8,12, which are the beginning of words. 2061 unsigned M0 = N->getMaskElt(0) / 4; 2062 unsigned M1 = N->getMaskElt(4) / 4; 2063 unsigned M2 = N->getMaskElt(8) / 4; 2064 unsigned M3 = N->getMaskElt(12) / 4; 2065 2066 // If both vector operands for the shuffle are the same vector, the mask will 2067 // contain only elements from the first one and the second one will be undef. 2068 if (N->getOperand(1).isUndef()) { 2069 assert(M0 < 4 && "Indexing into an undef vector?"); 2070 if (M1 != (M0 + 1) % 4 || M2 != (M1 + 1) % 4 || M3 != (M2 + 1) % 4) 2071 return false; 2072 2073 ShiftElts = IsLE ? (4 - M0) % 4 : M0; 2074 Swap = false; 2075 return true; 2076 } 2077 2078 // Ensure each word index of the ShuffleVector Mask is consecutive. 2079 if (M1 != (M0 + 1) % 8 || M2 != (M1 + 1) % 8 || M3 != (M2 + 1) % 8) 2080 return false; 2081 2082 if (IsLE) { 2083 if (M0 == 0 || M0 == 7 || M0 == 6 || M0 == 5) { 2084 // Input vectors don't need to be swapped if the leading element 2085 // of the result is one of the 3 left elements of the second vector 2086 // (or if there is no shift to be done at all). 2087 Swap = false; 2088 ShiftElts = (8 - M0) % 8; 2089 } else if (M0 == 4 || M0 == 3 || M0 == 2 || M0 == 1) { 2090 // Input vectors need to be swapped if the leading element 2091 // of the result is one of the 3 left elements of the first vector 2092 // (or if we're shifting by 4 - thereby simply swapping the vectors). 2093 Swap = true; 2094 ShiftElts = (4 - M0) % 4; 2095 } 2096 2097 return true; 2098 } else { // BE 2099 if (M0 == 0 || M0 == 1 || M0 == 2 || M0 == 3) { 2100 // Input vectors don't need to be swapped if the leading element 2101 // of the result is one of the 4 elements of the first vector. 2102 Swap = false; 2103 ShiftElts = M0; 2104 } else if (M0 == 4 || M0 == 5 || M0 == 6 || M0 == 7) { 2105 // Input vectors need to be swapped if the leading element 2106 // of the result is one of the 4 elements of the right vector. 2107 Swap = true; 2108 ShiftElts = M0 - 4; 2109 } 2110 2111 return true; 2112 } 2113 } 2114 2115 bool static isXXBRShuffleMaskHelper(ShuffleVectorSDNode *N, int Width) { 2116 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8"); 2117 2118 if (!isNByteElemShuffleMask(N, Width, -1)) 2119 return false; 2120 2121 for (int i = 0; i < 16; i += Width) 2122 if (N->getMaskElt(i) != i + Width - 1) 2123 return false; 2124 2125 return true; 2126 } 2127 2128 bool PPC::isXXBRHShuffleMask(ShuffleVectorSDNode *N) { 2129 return isXXBRShuffleMaskHelper(N, 2); 2130 } 2131 2132 bool PPC::isXXBRWShuffleMask(ShuffleVectorSDNode *N) { 2133 return isXXBRShuffleMaskHelper(N, 4); 2134 } 2135 2136 bool PPC::isXXBRDShuffleMask(ShuffleVectorSDNode *N) { 2137 return isXXBRShuffleMaskHelper(N, 8); 2138 } 2139 2140 bool PPC::isXXBRQShuffleMask(ShuffleVectorSDNode *N) { 2141 return isXXBRShuffleMaskHelper(N, 16); 2142 } 2143 2144 /// Can node \p N be lowered to an XXPERMDI instruction? If so, set \p Swap 2145 /// if the inputs to the instruction should be swapped and set \p DM to the 2146 /// value for the immediate. 2147 /// Specifically, set \p Swap to true only if \p N can be lowered to XXPERMDI 2148 /// AND element 0 of the result comes from the first input (LE) or second input 2149 /// (BE). Set \p DM to the calculated result (0-3) only if \p N can be lowered. 2150 /// \return true iff the given mask of shuffle node \p N is a XXPERMDI shuffle 2151 /// mask. 2152 bool PPC::isXXPERMDIShuffleMask(ShuffleVectorSDNode *N, unsigned &DM, 2153 bool &Swap, bool IsLE) { 2154 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8"); 2155 2156 // Ensure each byte index of the double word is consecutive. 2157 if (!isNByteElemShuffleMask(N, 8, 1)) 2158 return false; 2159 2160 unsigned M0 = N->getMaskElt(0) / 8; 2161 unsigned M1 = N->getMaskElt(8) / 8; 2162 assert(((M0 | M1) < 4) && "A mask element out of bounds?"); 2163 2164 // If both vector operands for the shuffle are the same vector, the mask will 2165 // contain only elements from the first one and the second one will be undef. 2166 if (N->getOperand(1).isUndef()) { 2167 if ((M0 | M1) < 2) { 2168 DM = IsLE ? (((~M1) & 1) << 1) + ((~M0) & 1) : (M0 << 1) + (M1 & 1); 2169 Swap = false; 2170 return true; 2171 } else 2172 return false; 2173 } 2174 2175 if (IsLE) { 2176 if (M0 > 1 && M1 < 2) { 2177 Swap = false; 2178 } else if (M0 < 2 && M1 > 1) { 2179 M0 = (M0 + 2) % 4; 2180 M1 = (M1 + 2) % 4; 2181 Swap = true; 2182 } else 2183 return false; 2184 2185 // Note: if control flow comes here that means Swap is already set above 2186 DM = (((~M1) & 1) << 1) + ((~M0) & 1); 2187 return true; 2188 } else { // BE 2189 if (M0 < 2 && M1 > 1) { 2190 Swap = false; 2191 } else if (M0 > 1 && M1 < 2) { 2192 M0 = (M0 + 2) % 4; 2193 M1 = (M1 + 2) % 4; 2194 Swap = true; 2195 } else 2196 return false; 2197 2198 // Note: if control flow comes here that means Swap is already set above 2199 DM = (M0 << 1) + (M1 & 1); 2200 return true; 2201 } 2202 } 2203 2204 2205 /// getSplatIdxForPPCMnemonics - Return the splat index as a value that is 2206 /// appropriate for PPC mnemonics (which have a big endian bias - namely 2207 /// elements are counted from the left of the vector register). 2208 unsigned PPC::getSplatIdxForPPCMnemonics(SDNode *N, unsigned EltSize, 2209 SelectionDAG &DAG) { 2210 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 2211 assert(isSplatShuffleMask(SVOp, EltSize)); 2212 if (DAG.getDataLayout().isLittleEndian()) 2213 return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize); 2214 else 2215 return SVOp->getMaskElt(0) / EltSize; 2216 } 2217 2218 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed 2219 /// by using a vspltis[bhw] instruction of the specified element size, return 2220 /// the constant being splatted. The ByteSize field indicates the number of 2221 /// bytes of each element [124] -> [bhw]. 2222 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) { 2223 SDValue OpVal(nullptr, 0); 2224 2225 // If ByteSize of the splat is bigger than the element size of the 2226 // build_vector, then we have a case where we are checking for a splat where 2227 // multiple elements of the buildvector are folded together into a single 2228 // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8). 2229 unsigned EltSize = 16/N->getNumOperands(); 2230 if (EltSize < ByteSize) { 2231 unsigned Multiple = ByteSize/EltSize; // Number of BV entries per spltval. 2232 SDValue UniquedVals[4]; 2233 assert(Multiple > 1 && Multiple <= 4 && "How can this happen?"); 2234 2235 // See if all of the elements in the buildvector agree across. 2236 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 2237 if (N->getOperand(i).isUndef()) continue; 2238 // If the element isn't a constant, bail fully out. 2239 if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue(); 2240 2241 if (!UniquedVals[i&(Multiple-1)].getNode()) 2242 UniquedVals[i&(Multiple-1)] = N->getOperand(i); 2243 else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i)) 2244 return SDValue(); // no match. 2245 } 2246 2247 // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains 2248 // either constant or undef values that are identical for each chunk. See 2249 // if these chunks can form into a larger vspltis*. 2250 2251 // Check to see if all of the leading entries are either 0 or -1. If 2252 // neither, then this won't fit into the immediate field. 2253 bool LeadingZero = true; 2254 bool LeadingOnes = true; 2255 for (unsigned i = 0; i != Multiple-1; ++i) { 2256 if (!UniquedVals[i].getNode()) continue; // Must have been undefs. 2257 2258 LeadingZero &= isNullConstant(UniquedVals[i]); 2259 LeadingOnes &= isAllOnesConstant(UniquedVals[i]); 2260 } 2261 // Finally, check the least significant entry. 2262 if (LeadingZero) { 2263 if (!UniquedVals[Multiple-1].getNode()) 2264 return DAG.getTargetConstant(0, SDLoc(N), MVT::i32); // 0,0,0,undef 2265 int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue(); 2266 if (Val < 16) // 0,0,0,4 -> vspltisw(4) 2267 return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32); 2268 } 2269 if (LeadingOnes) { 2270 if (!UniquedVals[Multiple-1].getNode()) 2271 return DAG.getTargetConstant(~0U, SDLoc(N), MVT::i32); // -1,-1,-1,undef 2272 int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue(); 2273 if (Val >= -16) // -1,-1,-1,-2 -> vspltisw(-2) 2274 return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32); 2275 } 2276 2277 return SDValue(); 2278 } 2279 2280 // Check to see if this buildvec has a single non-undef value in its elements. 2281 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 2282 if (N->getOperand(i).isUndef()) continue; 2283 if (!OpVal.getNode()) 2284 OpVal = N->getOperand(i); 2285 else if (OpVal != N->getOperand(i)) 2286 return SDValue(); 2287 } 2288 2289 if (!OpVal.getNode()) return SDValue(); // All UNDEF: use implicit def. 2290 2291 unsigned ValSizeInBytes = EltSize; 2292 uint64_t Value = 0; 2293 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) { 2294 Value = CN->getZExtValue(); 2295 } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) { 2296 assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!"); 2297 Value = FloatToBits(CN->getValueAPF().convertToFloat()); 2298 } 2299 2300 // If the splat value is larger than the element value, then we can never do 2301 // this splat. The only case that we could fit the replicated bits into our 2302 // immediate field for would be zero, and we prefer to use vxor for it. 2303 if (ValSizeInBytes < ByteSize) return SDValue(); 2304 2305 // If the element value is larger than the splat value, check if it consists 2306 // of a repeated bit pattern of size ByteSize. 2307 if (!APInt(ValSizeInBytes * 8, Value).isSplat(ByteSize * 8)) 2308 return SDValue(); 2309 2310 // Properly sign extend the value. 2311 int MaskVal = SignExtend32(Value, ByteSize * 8); 2312 2313 // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros. 2314 if (MaskVal == 0) return SDValue(); 2315 2316 // Finally, if this value fits in a 5 bit sext field, return it 2317 if (SignExtend32<5>(MaskVal) == MaskVal) 2318 return DAG.getTargetConstant(MaskVal, SDLoc(N), MVT::i32); 2319 return SDValue(); 2320 } 2321 2322 /// isQVALIGNIShuffleMask - If this is a qvaligni shuffle mask, return the shift 2323 /// amount, otherwise return -1. 2324 int PPC::isQVALIGNIShuffleMask(SDNode *N) { 2325 EVT VT = N->getValueType(0); 2326 if (VT != MVT::v4f64 && VT != MVT::v4f32 && VT != MVT::v4i1) 2327 return -1; 2328 2329 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 2330 2331 // Find the first non-undef value in the shuffle mask. 2332 unsigned i; 2333 for (i = 0; i != 4 && SVOp->getMaskElt(i) < 0; ++i) 2334 /*search*/; 2335 2336 if (i == 4) return -1; // all undef. 2337 2338 // Otherwise, check to see if the rest of the elements are consecutively 2339 // numbered from this value. 2340 unsigned ShiftAmt = SVOp->getMaskElt(i); 2341 if (ShiftAmt < i) return -1; 2342 ShiftAmt -= i; 2343 2344 // Check the rest of the elements to see if they are consecutive. 2345 for (++i; i != 4; ++i) 2346 if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i)) 2347 return -1; 2348 2349 return ShiftAmt; 2350 } 2351 2352 //===----------------------------------------------------------------------===// 2353 // Addressing Mode Selection 2354 //===----------------------------------------------------------------------===// 2355 2356 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit 2357 /// or 64-bit immediate, and if the value can be accurately represented as a 2358 /// sign extension from a 16-bit value. If so, this returns true and the 2359 /// immediate. 2360 bool llvm::isIntS16Immediate(SDNode *N, int16_t &Imm) { 2361 if (!isa<ConstantSDNode>(N)) 2362 return false; 2363 2364 Imm = (int16_t)cast<ConstantSDNode>(N)->getZExtValue(); 2365 if (N->getValueType(0) == MVT::i32) 2366 return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue(); 2367 else 2368 return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue(); 2369 } 2370 bool llvm::isIntS16Immediate(SDValue Op, int16_t &Imm) { 2371 return isIntS16Immediate(Op.getNode(), Imm); 2372 } 2373 2374 2375 /// SelectAddressEVXRegReg - Given the specified address, check to see if it can 2376 /// be represented as an indexed [r+r] operation. 2377 bool PPCTargetLowering::SelectAddressEVXRegReg(SDValue N, SDValue &Base, 2378 SDValue &Index, 2379 SelectionDAG &DAG) const { 2380 for (SDNode::use_iterator UI = N->use_begin(), E = N->use_end(); 2381 UI != E; ++UI) { 2382 if (MemSDNode *Memop = dyn_cast<MemSDNode>(*UI)) { 2383 if (Memop->getMemoryVT() == MVT::f64) { 2384 Base = N.getOperand(0); 2385 Index = N.getOperand(1); 2386 return true; 2387 } 2388 } 2389 } 2390 return false; 2391 } 2392 2393 /// SelectAddressRegReg - Given the specified addressed, check to see if it 2394 /// can be represented as an indexed [r+r] operation. Returns false if it 2395 /// can be more efficiently represented as [r+imm]. If \p EncodingAlignment is 2396 /// non-zero and N can be represented by a base register plus a signed 16-bit 2397 /// displacement, make a more precise judgement by checking (displacement % \p 2398 /// EncodingAlignment). 2399 bool PPCTargetLowering::SelectAddressRegReg(SDValue N, SDValue &Base, 2400 SDValue &Index, SelectionDAG &DAG, 2401 unsigned EncodingAlignment) const { 2402 // If we have a PC Relative target flag don't select as [reg+reg]. It will be 2403 // a [pc+imm]. 2404 if (SelectAddressPCRel(N, Base)) 2405 return false; 2406 2407 int16_t imm = 0; 2408 if (N.getOpcode() == ISD::ADD) { 2409 // Is there any SPE load/store (f64), which can't handle 16bit offset? 2410 // SPE load/store can only handle 8-bit offsets. 2411 if (hasSPE() && SelectAddressEVXRegReg(N, Base, Index, DAG)) 2412 return true; 2413 if (isIntS16Immediate(N.getOperand(1), imm) && 2414 (!EncodingAlignment || !(imm % EncodingAlignment))) 2415 return false; // r+i 2416 if (N.getOperand(1).getOpcode() == PPCISD::Lo) 2417 return false; // r+i 2418 2419 Base = N.getOperand(0); 2420 Index = N.getOperand(1); 2421 return true; 2422 } else if (N.getOpcode() == ISD::OR) { 2423 if (isIntS16Immediate(N.getOperand(1), imm) && 2424 (!EncodingAlignment || !(imm % EncodingAlignment))) 2425 return false; // r+i can fold it if we can. 2426 2427 // If this is an or of disjoint bitfields, we can codegen this as an add 2428 // (for better address arithmetic) if the LHS and RHS of the OR are provably 2429 // disjoint. 2430 KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0)); 2431 2432 if (LHSKnown.Zero.getBoolValue()) { 2433 KnownBits RHSKnown = DAG.computeKnownBits(N.getOperand(1)); 2434 // If all of the bits are known zero on the LHS or RHS, the add won't 2435 // carry. 2436 if (~(LHSKnown.Zero | RHSKnown.Zero) == 0) { 2437 Base = N.getOperand(0); 2438 Index = N.getOperand(1); 2439 return true; 2440 } 2441 } 2442 } 2443 2444 return false; 2445 } 2446 2447 // If we happen to be doing an i64 load or store into a stack slot that has 2448 // less than a 4-byte alignment, then the frame-index elimination may need to 2449 // use an indexed load or store instruction (because the offset may not be a 2450 // multiple of 4). The extra register needed to hold the offset comes from the 2451 // register scavenger, and it is possible that the scavenger will need to use 2452 // an emergency spill slot. As a result, we need to make sure that a spill slot 2453 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned 2454 // stack slot. 2455 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) { 2456 // FIXME: This does not handle the LWA case. 2457 if (VT != MVT::i64) 2458 return; 2459 2460 // NOTE: We'll exclude negative FIs here, which come from argument 2461 // lowering, because there are no known test cases triggering this problem 2462 // using packed structures (or similar). We can remove this exclusion if 2463 // we find such a test case. The reason why this is so test-case driven is 2464 // because this entire 'fixup' is only to prevent crashes (from the 2465 // register scavenger) on not-really-valid inputs. For example, if we have: 2466 // %a = alloca i1 2467 // %b = bitcast i1* %a to i64* 2468 // store i64* a, i64 b 2469 // then the store should really be marked as 'align 1', but is not. If it 2470 // were marked as 'align 1' then the indexed form would have been 2471 // instruction-selected initially, and the problem this 'fixup' is preventing 2472 // won't happen regardless. 2473 if (FrameIdx < 0) 2474 return; 2475 2476 MachineFunction &MF = DAG.getMachineFunction(); 2477 MachineFrameInfo &MFI = MF.getFrameInfo(); 2478 2479 if (MFI.getObjectAlign(FrameIdx) >= Align(4)) 2480 return; 2481 2482 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 2483 FuncInfo->setHasNonRISpills(); 2484 } 2485 2486 /// Returns true if the address N can be represented by a base register plus 2487 /// a signed 16-bit displacement [r+imm], and if it is not better 2488 /// represented as reg+reg. If \p EncodingAlignment is non-zero, only accept 2489 /// displacements that are multiples of that value. 2490 bool PPCTargetLowering::SelectAddressRegImm(SDValue N, SDValue &Disp, 2491 SDValue &Base, 2492 SelectionDAG &DAG, 2493 unsigned EncodingAlignment) const { 2494 // FIXME dl should come from parent load or store, not from address 2495 SDLoc dl(N); 2496 2497 // If we have a PC Relative target flag don't select as [reg+imm]. It will be 2498 // a [pc+imm]. 2499 if (SelectAddressPCRel(N, Base)) 2500 return false; 2501 2502 // If this can be more profitably realized as r+r, fail. 2503 if (SelectAddressRegReg(N, Disp, Base, DAG, EncodingAlignment)) 2504 return false; 2505 2506 if (N.getOpcode() == ISD::ADD) { 2507 int16_t imm = 0; 2508 if (isIntS16Immediate(N.getOperand(1), imm) && 2509 (!EncodingAlignment || (imm % EncodingAlignment) == 0)) { 2510 Disp = DAG.getTargetConstant(imm, dl, N.getValueType()); 2511 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) { 2512 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2513 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 2514 } else { 2515 Base = N.getOperand(0); 2516 } 2517 return true; // [r+i] 2518 } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) { 2519 // Match LOAD (ADD (X, Lo(G))). 2520 assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue() 2521 && "Cannot handle constant offsets yet!"); 2522 Disp = N.getOperand(1).getOperand(0); // The global address. 2523 assert(Disp.getOpcode() == ISD::TargetGlobalAddress || 2524 Disp.getOpcode() == ISD::TargetGlobalTLSAddress || 2525 Disp.getOpcode() == ISD::TargetConstantPool || 2526 Disp.getOpcode() == ISD::TargetJumpTable); 2527 Base = N.getOperand(0); 2528 return true; // [&g+r] 2529 } 2530 } else if (N.getOpcode() == ISD::OR) { 2531 int16_t imm = 0; 2532 if (isIntS16Immediate(N.getOperand(1), imm) && 2533 (!EncodingAlignment || (imm % EncodingAlignment) == 0)) { 2534 // If this is an or of disjoint bitfields, we can codegen this as an add 2535 // (for better address arithmetic) if the LHS and RHS of the OR are 2536 // provably disjoint. 2537 KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0)); 2538 2539 if ((LHSKnown.Zero.getZExtValue()|~(uint64_t)imm) == ~0ULL) { 2540 // If all of the bits are known zero on the LHS or RHS, the add won't 2541 // carry. 2542 if (FrameIndexSDNode *FI = 2543 dyn_cast<FrameIndexSDNode>(N.getOperand(0))) { 2544 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2545 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 2546 } else { 2547 Base = N.getOperand(0); 2548 } 2549 Disp = DAG.getTargetConstant(imm, dl, N.getValueType()); 2550 return true; 2551 } 2552 } 2553 } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) { 2554 // Loading from a constant address. 2555 2556 // If this address fits entirely in a 16-bit sext immediate field, codegen 2557 // this as "d, 0" 2558 int16_t Imm; 2559 if (isIntS16Immediate(CN, Imm) && 2560 (!EncodingAlignment || (Imm % EncodingAlignment) == 0)) { 2561 Disp = DAG.getTargetConstant(Imm, dl, CN->getValueType(0)); 2562 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO, 2563 CN->getValueType(0)); 2564 return true; 2565 } 2566 2567 // Handle 32-bit sext immediates with LIS + addr mode. 2568 if ((CN->getValueType(0) == MVT::i32 || 2569 (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) && 2570 (!EncodingAlignment || (CN->getZExtValue() % EncodingAlignment) == 0)) { 2571 int Addr = (int)CN->getZExtValue(); 2572 2573 // Otherwise, break this down into an LIS + disp. 2574 Disp = DAG.getTargetConstant((short)Addr, dl, MVT::i32); 2575 2576 Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, dl, 2577 MVT::i32); 2578 unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8; 2579 Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0); 2580 return true; 2581 } 2582 } 2583 2584 Disp = DAG.getTargetConstant(0, dl, getPointerTy(DAG.getDataLayout())); 2585 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) { 2586 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2587 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 2588 } else 2589 Base = N; 2590 return true; // [r+0] 2591 } 2592 2593 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be 2594 /// represented as an indexed [r+r] operation. 2595 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base, 2596 SDValue &Index, 2597 SelectionDAG &DAG) const { 2598 // Check to see if we can easily represent this as an [r+r] address. This 2599 // will fail if it thinks that the address is more profitably represented as 2600 // reg+imm, e.g. where imm = 0. 2601 if (SelectAddressRegReg(N, Base, Index, DAG)) 2602 return true; 2603 2604 // If the address is the result of an add, we will utilize the fact that the 2605 // address calculation includes an implicit add. However, we can reduce 2606 // register pressure if we do not materialize a constant just for use as the 2607 // index register. We only get rid of the add if it is not an add of a 2608 // value and a 16-bit signed constant and both have a single use. 2609 int16_t imm = 0; 2610 if (N.getOpcode() == ISD::ADD && 2611 (!isIntS16Immediate(N.getOperand(1), imm) || 2612 !N.getOperand(1).hasOneUse() || !N.getOperand(0).hasOneUse())) { 2613 Base = N.getOperand(0); 2614 Index = N.getOperand(1); 2615 return true; 2616 } 2617 2618 // Otherwise, do it the hard way, using R0 as the base register. 2619 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO, 2620 N.getValueType()); 2621 Index = N; 2622 return true; 2623 } 2624 2625 template <typename Ty> static bool isValidPCRelNode(SDValue N) { 2626 Ty *PCRelCand = dyn_cast<Ty>(N); 2627 return PCRelCand && (PCRelCand->getTargetFlags() & PPCII::MO_PCREL_FLAG); 2628 } 2629 2630 /// Returns true if this address is a PC Relative address. 2631 /// PC Relative addresses are marked with the flag PPCII::MO_PCREL_FLAG 2632 /// or if the node opcode is PPCISD::MAT_PCREL_ADDR. 2633 bool PPCTargetLowering::SelectAddressPCRel(SDValue N, SDValue &Base) const { 2634 // This is a materialize PC Relative node. Always select this as PC Relative. 2635 Base = N; 2636 if (N.getOpcode() == PPCISD::MAT_PCREL_ADDR) 2637 return true; 2638 if (isValidPCRelNode<ConstantPoolSDNode>(N) || 2639 isValidPCRelNode<GlobalAddressSDNode>(N) || 2640 isValidPCRelNode<JumpTableSDNode>(N) || 2641 isValidPCRelNode<BlockAddressSDNode>(N)) 2642 return true; 2643 return false; 2644 } 2645 2646 /// Returns true if we should use a direct load into vector instruction 2647 /// (such as lxsd or lfd), instead of a load into gpr + direct move sequence. 2648 static bool usePartialVectorLoads(SDNode *N, const PPCSubtarget& ST) { 2649 2650 // If there are any other uses other than scalar to vector, then we should 2651 // keep it as a scalar load -> direct move pattern to prevent multiple 2652 // loads. 2653 LoadSDNode *LD = dyn_cast<LoadSDNode>(N); 2654 if (!LD) 2655 return false; 2656 2657 EVT MemVT = LD->getMemoryVT(); 2658 if (!MemVT.isSimple()) 2659 return false; 2660 switch(MemVT.getSimpleVT().SimpleTy) { 2661 case MVT::i64: 2662 break; 2663 case MVT::i32: 2664 if (!ST.hasP8Vector()) 2665 return false; 2666 break; 2667 case MVT::i16: 2668 case MVT::i8: 2669 if (!ST.hasP9Vector()) 2670 return false; 2671 break; 2672 default: 2673 return false; 2674 } 2675 2676 SDValue LoadedVal(N, 0); 2677 if (!LoadedVal.hasOneUse()) 2678 return false; 2679 2680 for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end(); 2681 UI != UE; ++UI) 2682 if (UI.getUse().get().getResNo() == 0 && 2683 UI->getOpcode() != ISD::SCALAR_TO_VECTOR) 2684 return false; 2685 2686 return true; 2687 } 2688 2689 /// getPreIndexedAddressParts - returns true by value, base pointer and 2690 /// offset pointer and addressing mode by reference if the node's address 2691 /// can be legally represented as pre-indexed load / store address. 2692 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base, 2693 SDValue &Offset, 2694 ISD::MemIndexedMode &AM, 2695 SelectionDAG &DAG) const { 2696 if (DisablePPCPreinc) return false; 2697 2698 bool isLoad = true; 2699 SDValue Ptr; 2700 EVT VT; 2701 unsigned Alignment; 2702 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 2703 Ptr = LD->getBasePtr(); 2704 VT = LD->getMemoryVT(); 2705 Alignment = LD->getAlignment(); 2706 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 2707 Ptr = ST->getBasePtr(); 2708 VT = ST->getMemoryVT(); 2709 Alignment = ST->getAlignment(); 2710 isLoad = false; 2711 } else 2712 return false; 2713 2714 // Do not generate pre-inc forms for specific loads that feed scalar_to_vector 2715 // instructions because we can fold these into a more efficient instruction 2716 // instead, (such as LXSD). 2717 if (isLoad && usePartialVectorLoads(N, Subtarget)) { 2718 return false; 2719 } 2720 2721 // PowerPC doesn't have preinc load/store instructions for vectors (except 2722 // for QPX, which does have preinc r+r forms). 2723 if (VT.isVector()) { 2724 if (!Subtarget.hasQPX() || (VT != MVT::v4f64 && VT != MVT::v4f32)) { 2725 return false; 2726 } else if (SelectAddressRegRegOnly(Ptr, Offset, Base, DAG)) { 2727 AM = ISD::PRE_INC; 2728 return true; 2729 } 2730 } 2731 2732 if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) { 2733 // Common code will reject creating a pre-inc form if the base pointer 2734 // is a frame index, or if N is a store and the base pointer is either 2735 // the same as or a predecessor of the value being stored. Check for 2736 // those situations here, and try with swapped Base/Offset instead. 2737 bool Swap = false; 2738 2739 if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base)) 2740 Swap = true; 2741 else if (!isLoad) { 2742 SDValue Val = cast<StoreSDNode>(N)->getValue(); 2743 if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode())) 2744 Swap = true; 2745 } 2746 2747 if (Swap) 2748 std::swap(Base, Offset); 2749 2750 AM = ISD::PRE_INC; 2751 return true; 2752 } 2753 2754 // LDU/STU can only handle immediates that are a multiple of 4. 2755 if (VT != MVT::i64) { 2756 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, 0)) 2757 return false; 2758 } else { 2759 // LDU/STU need an address with at least 4-byte alignment. 2760 if (Alignment < 4) 2761 return false; 2762 2763 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, 4)) 2764 return false; 2765 } 2766 2767 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 2768 // PPC64 doesn't have lwau, but it does have lwaux. Reject preinc load of 2769 // sext i32 to i64 when addr mode is r+i. 2770 if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 && 2771 LD->getExtensionType() == ISD::SEXTLOAD && 2772 isa<ConstantSDNode>(Offset)) 2773 return false; 2774 } 2775 2776 AM = ISD::PRE_INC; 2777 return true; 2778 } 2779 2780 //===----------------------------------------------------------------------===// 2781 // LowerOperation implementation 2782 //===----------------------------------------------------------------------===// 2783 2784 /// Return true if we should reference labels using a PICBase, set the HiOpFlags 2785 /// and LoOpFlags to the target MO flags. 2786 static void getLabelAccessInfo(bool IsPIC, const PPCSubtarget &Subtarget, 2787 unsigned &HiOpFlags, unsigned &LoOpFlags, 2788 const GlobalValue *GV = nullptr) { 2789 HiOpFlags = PPCII::MO_HA; 2790 LoOpFlags = PPCII::MO_LO; 2791 2792 // Don't use the pic base if not in PIC relocation model. 2793 if (IsPIC) { 2794 HiOpFlags |= PPCII::MO_PIC_FLAG; 2795 LoOpFlags |= PPCII::MO_PIC_FLAG; 2796 } 2797 } 2798 2799 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC, 2800 SelectionDAG &DAG) { 2801 SDLoc DL(HiPart); 2802 EVT PtrVT = HiPart.getValueType(); 2803 SDValue Zero = DAG.getConstant(0, DL, PtrVT); 2804 2805 SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero); 2806 SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero); 2807 2808 // With PIC, the first instruction is actually "GR+hi(&G)". 2809 if (isPIC) 2810 Hi = DAG.getNode(ISD::ADD, DL, PtrVT, 2811 DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi); 2812 2813 // Generate non-pic code that has direct accesses to the constant pool. 2814 // The address of the global is just (hi(&g)+lo(&g)). 2815 return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo); 2816 } 2817 2818 static void setUsesTOCBasePtr(MachineFunction &MF) { 2819 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 2820 FuncInfo->setUsesTOCBasePtr(); 2821 } 2822 2823 static void setUsesTOCBasePtr(SelectionDAG &DAG) { 2824 setUsesTOCBasePtr(DAG.getMachineFunction()); 2825 } 2826 2827 SDValue PPCTargetLowering::getTOCEntry(SelectionDAG &DAG, const SDLoc &dl, 2828 SDValue GA) const { 2829 const bool Is64Bit = Subtarget.isPPC64(); 2830 EVT VT = Is64Bit ? MVT::i64 : MVT::i32; 2831 SDValue Reg = Is64Bit ? DAG.getRegister(PPC::X2, VT) 2832 : Subtarget.isAIXABI() 2833 ? DAG.getRegister(PPC::R2, VT) 2834 : DAG.getNode(PPCISD::GlobalBaseReg, dl, VT); 2835 SDValue Ops[] = { GA, Reg }; 2836 return DAG.getMemIntrinsicNode( 2837 PPCISD::TOC_ENTRY, dl, DAG.getVTList(VT, MVT::Other), Ops, VT, 2838 MachinePointerInfo::getGOT(DAG.getMachineFunction()), None, 2839 MachineMemOperand::MOLoad); 2840 } 2841 2842 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op, 2843 SelectionDAG &DAG) const { 2844 EVT PtrVT = Op.getValueType(); 2845 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op); 2846 const Constant *C = CP->getConstVal(); 2847 2848 // 64-bit SVR4 ABI and AIX ABI code are always position-independent. 2849 // The actual address of the GlobalValue is stored in the TOC. 2850 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) { 2851 if (Subtarget.isUsingPCRelativeCalls()) { 2852 SDLoc DL(CP); 2853 EVT Ty = getPointerTy(DAG.getDataLayout()); 2854 SDValue ConstPool = DAG.getTargetConstantPool( 2855 C, Ty, CP->getAlign(), CP->getOffset(), PPCII::MO_PCREL_FLAG); 2856 return DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, ConstPool); 2857 } 2858 setUsesTOCBasePtr(DAG); 2859 SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0); 2860 return getTOCEntry(DAG, SDLoc(CP), GA); 2861 } 2862 2863 unsigned MOHiFlag, MOLoFlag; 2864 bool IsPIC = isPositionIndependent(); 2865 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag); 2866 2867 if (IsPIC && Subtarget.isSVR4ABI()) { 2868 SDValue GA = 2869 DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), PPCII::MO_PIC_FLAG); 2870 return getTOCEntry(DAG, SDLoc(CP), GA); 2871 } 2872 2873 SDValue CPIHi = 2874 DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0, MOHiFlag); 2875 SDValue CPILo = 2876 DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0, MOLoFlag); 2877 return LowerLabelRef(CPIHi, CPILo, IsPIC, DAG); 2878 } 2879 2880 // For 64-bit PowerPC, prefer the more compact relative encodings. 2881 // This trades 32 bits per jump table entry for one or two instructions 2882 // on the jump site. 2883 unsigned PPCTargetLowering::getJumpTableEncoding() const { 2884 if (isJumpTableRelative()) 2885 return MachineJumpTableInfo::EK_LabelDifference32; 2886 2887 return TargetLowering::getJumpTableEncoding(); 2888 } 2889 2890 bool PPCTargetLowering::isJumpTableRelative() const { 2891 if (UseAbsoluteJumpTables) 2892 return false; 2893 if (Subtarget.isPPC64() || Subtarget.isAIXABI()) 2894 return true; 2895 return TargetLowering::isJumpTableRelative(); 2896 } 2897 2898 SDValue PPCTargetLowering::getPICJumpTableRelocBase(SDValue Table, 2899 SelectionDAG &DAG) const { 2900 if (!Subtarget.isPPC64() || Subtarget.isAIXABI()) 2901 return TargetLowering::getPICJumpTableRelocBase(Table, DAG); 2902 2903 switch (getTargetMachine().getCodeModel()) { 2904 case CodeModel::Small: 2905 case CodeModel::Medium: 2906 return TargetLowering::getPICJumpTableRelocBase(Table, DAG); 2907 default: 2908 return DAG.getNode(PPCISD::GlobalBaseReg, SDLoc(), 2909 getPointerTy(DAG.getDataLayout())); 2910 } 2911 } 2912 2913 const MCExpr * 2914 PPCTargetLowering::getPICJumpTableRelocBaseExpr(const MachineFunction *MF, 2915 unsigned JTI, 2916 MCContext &Ctx) const { 2917 if (!Subtarget.isPPC64() || Subtarget.isAIXABI()) 2918 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx); 2919 2920 switch (getTargetMachine().getCodeModel()) { 2921 case CodeModel::Small: 2922 case CodeModel::Medium: 2923 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx); 2924 default: 2925 return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx); 2926 } 2927 } 2928 2929 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const { 2930 EVT PtrVT = Op.getValueType(); 2931 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op); 2932 2933 // isUsingPCRelativeCalls() returns true when PCRelative is enabled 2934 if (Subtarget.isUsingPCRelativeCalls()) { 2935 SDLoc DL(JT); 2936 EVT Ty = getPointerTy(DAG.getDataLayout()); 2937 SDValue GA = 2938 DAG.getTargetJumpTable(JT->getIndex(), Ty, PPCII::MO_PCREL_FLAG); 2939 SDValue MatAddr = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA); 2940 return MatAddr; 2941 } 2942 2943 // 64-bit SVR4 ABI and AIX ABI code are always position-independent. 2944 // The actual address of the GlobalValue is stored in the TOC. 2945 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) { 2946 setUsesTOCBasePtr(DAG); 2947 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT); 2948 return getTOCEntry(DAG, SDLoc(JT), GA); 2949 } 2950 2951 unsigned MOHiFlag, MOLoFlag; 2952 bool IsPIC = isPositionIndependent(); 2953 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag); 2954 2955 if (IsPIC && Subtarget.isSVR4ABI()) { 2956 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, 2957 PPCII::MO_PIC_FLAG); 2958 return getTOCEntry(DAG, SDLoc(GA), GA); 2959 } 2960 2961 SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag); 2962 SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag); 2963 return LowerLabelRef(JTIHi, JTILo, IsPIC, DAG); 2964 } 2965 2966 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op, 2967 SelectionDAG &DAG) const { 2968 EVT PtrVT = Op.getValueType(); 2969 BlockAddressSDNode *BASDN = cast<BlockAddressSDNode>(Op); 2970 const BlockAddress *BA = BASDN->getBlockAddress(); 2971 2972 // isUsingPCRelativeCalls() returns true when PCRelative is enabled 2973 if (Subtarget.isUsingPCRelativeCalls()) { 2974 SDLoc DL(BASDN); 2975 EVT Ty = getPointerTy(DAG.getDataLayout()); 2976 SDValue GA = DAG.getTargetBlockAddress(BA, Ty, BASDN->getOffset(), 2977 PPCII::MO_PCREL_FLAG); 2978 SDValue MatAddr = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA); 2979 return MatAddr; 2980 } 2981 2982 // 64-bit SVR4 ABI and AIX ABI code are always position-independent. 2983 // The actual BlockAddress is stored in the TOC. 2984 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) { 2985 setUsesTOCBasePtr(DAG); 2986 SDValue GA = DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset()); 2987 return getTOCEntry(DAG, SDLoc(BASDN), GA); 2988 } 2989 2990 // 32-bit position-independent ELF stores the BlockAddress in the .got. 2991 if (Subtarget.is32BitELFABI() && isPositionIndependent()) 2992 return getTOCEntry( 2993 DAG, SDLoc(BASDN), 2994 DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset())); 2995 2996 unsigned MOHiFlag, MOLoFlag; 2997 bool IsPIC = isPositionIndependent(); 2998 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag); 2999 SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag); 3000 SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag); 3001 return LowerLabelRef(TgtBAHi, TgtBALo, IsPIC, DAG); 3002 } 3003 3004 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op, 3005 SelectionDAG &DAG) const { 3006 // FIXME: TLS addresses currently use medium model code sequences, 3007 // which is the most useful form. Eventually support for small and 3008 // large models could be added if users need it, at the cost of 3009 // additional complexity. 3010 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op); 3011 if (DAG.getTarget().useEmulatedTLS()) 3012 return LowerToTLSEmulatedModel(GA, DAG); 3013 3014 SDLoc dl(GA); 3015 const GlobalValue *GV = GA->getGlobal(); 3016 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3017 bool is64bit = Subtarget.isPPC64(); 3018 const Module *M = DAG.getMachineFunction().getFunction().getParent(); 3019 PICLevel::Level picLevel = M->getPICLevel(); 3020 3021 const TargetMachine &TM = getTargetMachine(); 3022 TLSModel::Model Model = TM.getTLSModel(GV); 3023 3024 if (Model == TLSModel::LocalExec) { 3025 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 3026 PPCII::MO_TPREL_HA); 3027 SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 3028 PPCII::MO_TPREL_LO); 3029 SDValue TLSReg = is64bit ? DAG.getRegister(PPC::X13, MVT::i64) 3030 : DAG.getRegister(PPC::R2, MVT::i32); 3031 3032 SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg); 3033 return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi); 3034 } 3035 3036 if (Model == TLSModel::InitialExec) { 3037 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0); 3038 SDValue TGATLS = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 3039 PPCII::MO_TLS); 3040 SDValue GOTPtr; 3041 if (is64bit) { 3042 setUsesTOCBasePtr(DAG); 3043 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64); 3044 GOTPtr = DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl, 3045 PtrVT, GOTReg, TGA); 3046 } else { 3047 if (!TM.isPositionIndependent()) 3048 GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT); 3049 else if (picLevel == PICLevel::SmallPIC) 3050 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT); 3051 else 3052 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT); 3053 } 3054 SDValue TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl, 3055 PtrVT, TGA, GOTPtr); 3056 return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS); 3057 } 3058 3059 if (Model == TLSModel::GeneralDynamic) { 3060 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0); 3061 SDValue GOTPtr; 3062 if (is64bit) { 3063 setUsesTOCBasePtr(DAG); 3064 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64); 3065 GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT, 3066 GOTReg, TGA); 3067 } else { 3068 if (picLevel == PICLevel::SmallPIC) 3069 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT); 3070 else 3071 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT); 3072 } 3073 return DAG.getNode(PPCISD::ADDI_TLSGD_L_ADDR, dl, PtrVT, 3074 GOTPtr, TGA, TGA); 3075 } 3076 3077 if (Model == TLSModel::LocalDynamic) { 3078 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0); 3079 SDValue GOTPtr; 3080 if (is64bit) { 3081 setUsesTOCBasePtr(DAG); 3082 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64); 3083 GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT, 3084 GOTReg, TGA); 3085 } else { 3086 if (picLevel == PICLevel::SmallPIC) 3087 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT); 3088 else 3089 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT); 3090 } 3091 SDValue TLSAddr = DAG.getNode(PPCISD::ADDI_TLSLD_L_ADDR, dl, 3092 PtrVT, GOTPtr, TGA, TGA); 3093 SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl, 3094 PtrVT, TLSAddr, TGA); 3095 return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA); 3096 } 3097 3098 llvm_unreachable("Unknown TLS model!"); 3099 } 3100 3101 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op, 3102 SelectionDAG &DAG) const { 3103 EVT PtrVT = Op.getValueType(); 3104 GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op); 3105 SDLoc DL(GSDN); 3106 const GlobalValue *GV = GSDN->getGlobal(); 3107 3108 // 64-bit SVR4 ABI & AIX ABI code is always position-independent. 3109 // The actual address of the GlobalValue is stored in the TOC. 3110 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) { 3111 if (Subtarget.isUsingPCRelativeCalls()) { 3112 EVT Ty = getPointerTy(DAG.getDataLayout()); 3113 if (isAccessedAsGotIndirect(Op)) { 3114 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, Ty, GSDN->getOffset(), 3115 PPCII::MO_PCREL_FLAG | 3116 PPCII::MO_GOT_FLAG); 3117 SDValue MatPCRel = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA); 3118 SDValue Load = DAG.getLoad(MVT::i64, DL, DAG.getEntryNode(), MatPCRel, 3119 MachinePointerInfo()); 3120 return Load; 3121 } else { 3122 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, Ty, GSDN->getOffset(), 3123 PPCII::MO_PCREL_FLAG); 3124 return DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA); 3125 } 3126 } 3127 setUsesTOCBasePtr(DAG); 3128 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset()); 3129 return getTOCEntry(DAG, DL, GA); 3130 } 3131 3132 unsigned MOHiFlag, MOLoFlag; 3133 bool IsPIC = isPositionIndependent(); 3134 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag, GV); 3135 3136 if (IsPIC && Subtarget.isSVR4ABI()) { 3137 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 3138 GSDN->getOffset(), 3139 PPCII::MO_PIC_FLAG); 3140 return getTOCEntry(DAG, DL, GA); 3141 } 3142 3143 SDValue GAHi = 3144 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag); 3145 SDValue GALo = 3146 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag); 3147 3148 return LowerLabelRef(GAHi, GALo, IsPIC, DAG); 3149 } 3150 3151 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const { 3152 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get(); 3153 SDLoc dl(Op); 3154 3155 if (Op.getValueType() == MVT::v2i64) { 3156 // When the operands themselves are v2i64 values, we need to do something 3157 // special because VSX has no underlying comparison operations for these. 3158 if (Op.getOperand(0).getValueType() == MVT::v2i64) { 3159 // Equality can be handled by casting to the legal type for Altivec 3160 // comparisons, everything else needs to be expanded. 3161 if (CC == ISD::SETEQ || CC == ISD::SETNE) { 3162 return DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, 3163 DAG.getSetCC(dl, MVT::v4i32, 3164 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0)), 3165 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(1)), 3166 CC)); 3167 } 3168 3169 return SDValue(); 3170 } 3171 3172 // We handle most of these in the usual way. 3173 return Op; 3174 } 3175 3176 // If we're comparing for equality to zero, expose the fact that this is 3177 // implemented as a ctlz/srl pair on ppc, so that the dag combiner can 3178 // fold the new nodes. 3179 if (SDValue V = lowerCmpEqZeroToCtlzSrl(Op, DAG)) 3180 return V; 3181 3182 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 3183 // Leave comparisons against 0 and -1 alone for now, since they're usually 3184 // optimized. FIXME: revisit this when we can custom lower all setcc 3185 // optimizations. 3186 if (C->isAllOnesValue() || C->isNullValue()) 3187 return SDValue(); 3188 } 3189 3190 // If we have an integer seteq/setne, turn it into a compare against zero 3191 // by xor'ing the rhs with the lhs, which is faster than setting a 3192 // condition register, reading it back out, and masking the correct bit. The 3193 // normal approach here uses sub to do this instead of xor. Using xor exposes 3194 // the result to other bit-twiddling opportunities. 3195 EVT LHSVT = Op.getOperand(0).getValueType(); 3196 if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) { 3197 EVT VT = Op.getValueType(); 3198 SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0), 3199 Op.getOperand(1)); 3200 return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, dl, LHSVT), CC); 3201 } 3202 return SDValue(); 3203 } 3204 3205 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const { 3206 SDNode *Node = Op.getNode(); 3207 EVT VT = Node->getValueType(0); 3208 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3209 SDValue InChain = Node->getOperand(0); 3210 SDValue VAListPtr = Node->getOperand(1); 3211 const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue(); 3212 SDLoc dl(Node); 3213 3214 assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only"); 3215 3216 // gpr_index 3217 SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain, 3218 VAListPtr, MachinePointerInfo(SV), MVT::i8); 3219 InChain = GprIndex.getValue(1); 3220 3221 if (VT == MVT::i64) { 3222 // Check if GprIndex is even 3223 SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex, 3224 DAG.getConstant(1, dl, MVT::i32)); 3225 SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd, 3226 DAG.getConstant(0, dl, MVT::i32), ISD::SETNE); 3227 SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex, 3228 DAG.getConstant(1, dl, MVT::i32)); 3229 // Align GprIndex to be even if it isn't 3230 GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne, 3231 GprIndex); 3232 } 3233 3234 // fpr index is 1 byte after gpr 3235 SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, 3236 DAG.getConstant(1, dl, MVT::i32)); 3237 3238 // fpr 3239 SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain, 3240 FprPtr, MachinePointerInfo(SV), MVT::i8); 3241 InChain = FprIndex.getValue(1); 3242 3243 SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, 3244 DAG.getConstant(8, dl, MVT::i32)); 3245 3246 SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, 3247 DAG.getConstant(4, dl, MVT::i32)); 3248 3249 // areas 3250 SDValue OverflowArea = 3251 DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr, MachinePointerInfo()); 3252 InChain = OverflowArea.getValue(1); 3253 3254 SDValue RegSaveArea = 3255 DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr, MachinePointerInfo()); 3256 InChain = RegSaveArea.getValue(1); 3257 3258 // select overflow_area if index > 8 3259 SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex, 3260 DAG.getConstant(8, dl, MVT::i32), ISD::SETLT); 3261 3262 // adjustment constant gpr_index * 4/8 3263 SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32, 3264 VT.isInteger() ? GprIndex : FprIndex, 3265 DAG.getConstant(VT.isInteger() ? 4 : 8, dl, 3266 MVT::i32)); 3267 3268 // OurReg = RegSaveArea + RegConstant 3269 SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea, 3270 RegConstant); 3271 3272 // Floating types are 32 bytes into RegSaveArea 3273 if (VT.isFloatingPoint()) 3274 OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg, 3275 DAG.getConstant(32, dl, MVT::i32)); 3276 3277 // increase {f,g}pr_index by 1 (or 2 if VT is i64) 3278 SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32, 3279 VT.isInteger() ? GprIndex : FprIndex, 3280 DAG.getConstant(VT == MVT::i64 ? 2 : 1, dl, 3281 MVT::i32)); 3282 3283 InChain = DAG.getTruncStore(InChain, dl, IndexPlus1, 3284 VT.isInteger() ? VAListPtr : FprPtr, 3285 MachinePointerInfo(SV), MVT::i8); 3286 3287 // determine if we should load from reg_save_area or overflow_area 3288 SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea); 3289 3290 // increase overflow_area by 4/8 if gpr/fpr > 8 3291 SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea, 3292 DAG.getConstant(VT.isInteger() ? 4 : 8, 3293 dl, MVT::i32)); 3294 3295 OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea, 3296 OverflowAreaPlusN); 3297 3298 InChain = DAG.getTruncStore(InChain, dl, OverflowArea, OverflowAreaPtr, 3299 MachinePointerInfo(), MVT::i32); 3300 3301 return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo()); 3302 } 3303 3304 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const { 3305 assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only"); 3306 3307 // We have to copy the entire va_list struct: 3308 // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte 3309 return DAG.getMemcpy(Op.getOperand(0), Op, Op.getOperand(1), Op.getOperand(2), 3310 DAG.getConstant(12, SDLoc(Op), MVT::i32), Align(8), 3311 false, true, false, MachinePointerInfo(), 3312 MachinePointerInfo()); 3313 } 3314 3315 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op, 3316 SelectionDAG &DAG) const { 3317 if (Subtarget.isAIXABI()) 3318 report_fatal_error("ADJUST_TRAMPOLINE operation is not supported on AIX."); 3319 3320 return Op.getOperand(0); 3321 } 3322 3323 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op, 3324 SelectionDAG &DAG) const { 3325 if (Subtarget.isAIXABI()) 3326 report_fatal_error("INIT_TRAMPOLINE operation is not supported on AIX."); 3327 3328 SDValue Chain = Op.getOperand(0); 3329 SDValue Trmp = Op.getOperand(1); // trampoline 3330 SDValue FPtr = Op.getOperand(2); // nested function 3331 SDValue Nest = Op.getOperand(3); // 'nest' parameter value 3332 SDLoc dl(Op); 3333 3334 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3335 bool isPPC64 = (PtrVT == MVT::i64); 3336 Type *IntPtrTy = DAG.getDataLayout().getIntPtrType(*DAG.getContext()); 3337 3338 TargetLowering::ArgListTy Args; 3339 TargetLowering::ArgListEntry Entry; 3340 3341 Entry.Ty = IntPtrTy; 3342 Entry.Node = Trmp; Args.push_back(Entry); 3343 3344 // TrampSize == (isPPC64 ? 48 : 40); 3345 Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40, dl, 3346 isPPC64 ? MVT::i64 : MVT::i32); 3347 Args.push_back(Entry); 3348 3349 Entry.Node = FPtr; Args.push_back(Entry); 3350 Entry.Node = Nest; Args.push_back(Entry); 3351 3352 // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg) 3353 TargetLowering::CallLoweringInfo CLI(DAG); 3354 CLI.setDebugLoc(dl).setChain(Chain).setLibCallee( 3355 CallingConv::C, Type::getVoidTy(*DAG.getContext()), 3356 DAG.getExternalSymbol("__trampoline_setup", PtrVT), std::move(Args)); 3357 3358 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 3359 return CallResult.second; 3360 } 3361 3362 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const { 3363 MachineFunction &MF = DAG.getMachineFunction(); 3364 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 3365 EVT PtrVT = getPointerTy(MF.getDataLayout()); 3366 3367 SDLoc dl(Op); 3368 3369 if (Subtarget.isPPC64() || Subtarget.isAIXABI()) { 3370 // vastart just stores the address of the VarArgsFrameIndex slot into the 3371 // memory location argument. 3372 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 3373 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 3374 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1), 3375 MachinePointerInfo(SV)); 3376 } 3377 3378 // For the 32-bit SVR4 ABI we follow the layout of the va_list struct. 3379 // We suppose the given va_list is already allocated. 3380 // 3381 // typedef struct { 3382 // char gpr; /* index into the array of 8 GPRs 3383 // * stored in the register save area 3384 // * gpr=0 corresponds to r3, 3385 // * gpr=1 to r4, etc. 3386 // */ 3387 // char fpr; /* index into the array of 8 FPRs 3388 // * stored in the register save area 3389 // * fpr=0 corresponds to f1, 3390 // * fpr=1 to f2, etc. 3391 // */ 3392 // char *overflow_arg_area; 3393 // /* location on stack that holds 3394 // * the next overflow argument 3395 // */ 3396 // char *reg_save_area; 3397 // /* where r3:r10 and f1:f8 (if saved) 3398 // * are stored 3399 // */ 3400 // } va_list[1]; 3401 3402 SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), dl, MVT::i32); 3403 SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), dl, MVT::i32); 3404 SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(), 3405 PtrVT); 3406 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), 3407 PtrVT); 3408 3409 uint64_t FrameOffset = PtrVT.getSizeInBits()/8; 3410 SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, dl, PtrVT); 3411 3412 uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1; 3413 SDValue ConstStackOffset = DAG.getConstant(StackOffset, dl, PtrVT); 3414 3415 uint64_t FPROffset = 1; 3416 SDValue ConstFPROffset = DAG.getConstant(FPROffset, dl, PtrVT); 3417 3418 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 3419 3420 // Store first byte : number of int regs 3421 SDValue firstStore = 3422 DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR, Op.getOperand(1), 3423 MachinePointerInfo(SV), MVT::i8); 3424 uint64_t nextOffset = FPROffset; 3425 SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1), 3426 ConstFPROffset); 3427 3428 // Store second byte : number of float regs 3429 SDValue secondStore = 3430 DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr, 3431 MachinePointerInfo(SV, nextOffset), MVT::i8); 3432 nextOffset += StackOffset; 3433 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset); 3434 3435 // Store second word : arguments given on stack 3436 SDValue thirdStore = DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr, 3437 MachinePointerInfo(SV, nextOffset)); 3438 nextOffset += FrameOffset; 3439 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset); 3440 3441 // Store third word : arguments given in registers 3442 return DAG.getStore(thirdStore, dl, FR, nextPtr, 3443 MachinePointerInfo(SV, nextOffset)); 3444 } 3445 3446 /// FPR - The set of FP registers that should be allocated for arguments 3447 /// on Darwin and AIX. 3448 static const MCPhysReg FPR[] = {PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, 3449 PPC::F6, PPC::F7, PPC::F8, PPC::F9, PPC::F10, 3450 PPC::F11, PPC::F12, PPC::F13}; 3451 3452 /// QFPR - The set of QPX registers that should be allocated for arguments. 3453 static const MCPhysReg QFPR[] = { 3454 PPC::QF1, PPC::QF2, PPC::QF3, PPC::QF4, PPC::QF5, PPC::QF6, PPC::QF7, 3455 PPC::QF8, PPC::QF9, PPC::QF10, PPC::QF11, PPC::QF12, PPC::QF13}; 3456 3457 /// CalculateStackSlotSize - Calculates the size reserved for this argument on 3458 /// the stack. 3459 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags, 3460 unsigned PtrByteSize) { 3461 unsigned ArgSize = ArgVT.getStoreSize(); 3462 if (Flags.isByVal()) 3463 ArgSize = Flags.getByValSize(); 3464 3465 // Round up to multiples of the pointer size, except for array members, 3466 // which are always packed. 3467 if (!Flags.isInConsecutiveRegs()) 3468 ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3469 3470 return ArgSize; 3471 } 3472 3473 /// CalculateStackSlotAlignment - Calculates the alignment of this argument 3474 /// on the stack. 3475 static Align CalculateStackSlotAlignment(EVT ArgVT, EVT OrigVT, 3476 ISD::ArgFlagsTy Flags, 3477 unsigned PtrByteSize) { 3478 Align Alignment(PtrByteSize); 3479 3480 // Altivec parameters are padded to a 16 byte boundary. 3481 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 || 3482 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 || 3483 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 || 3484 ArgVT == MVT::v1i128 || ArgVT == MVT::f128) 3485 Alignment = Align(16); 3486 // QPX vector types stored in double-precision are padded to a 32 byte 3487 // boundary. 3488 else if (ArgVT == MVT::v4f64 || ArgVT == MVT::v4i1) 3489 Alignment = Align(32); 3490 3491 // ByVal parameters are aligned as requested. 3492 if (Flags.isByVal()) { 3493 auto BVAlign = Flags.getNonZeroByValAlign(); 3494 if (BVAlign > PtrByteSize) { 3495 if (BVAlign.value() % PtrByteSize != 0) 3496 llvm_unreachable( 3497 "ByVal alignment is not a multiple of the pointer size"); 3498 3499 Alignment = BVAlign; 3500 } 3501 } 3502 3503 // Array members are always packed to their original alignment. 3504 if (Flags.isInConsecutiveRegs()) { 3505 // If the array member was split into multiple registers, the first 3506 // needs to be aligned to the size of the full type. (Except for 3507 // ppcf128, which is only aligned as its f64 components.) 3508 if (Flags.isSplit() && OrigVT != MVT::ppcf128) 3509 Alignment = Align(OrigVT.getStoreSize()); 3510 else 3511 Alignment = Align(ArgVT.getStoreSize()); 3512 } 3513 3514 return Alignment; 3515 } 3516 3517 /// CalculateStackSlotUsed - Return whether this argument will use its 3518 /// stack slot (instead of being passed in registers). ArgOffset, 3519 /// AvailableFPRs, and AvailableVRs must hold the current argument 3520 /// position, and will be updated to account for this argument. 3521 static bool CalculateStackSlotUsed(EVT ArgVT, EVT OrigVT, 3522 ISD::ArgFlagsTy Flags, 3523 unsigned PtrByteSize, 3524 unsigned LinkageSize, 3525 unsigned ParamAreaSize, 3526 unsigned &ArgOffset, 3527 unsigned &AvailableFPRs, 3528 unsigned &AvailableVRs, bool HasQPX) { 3529 bool UseMemory = false; 3530 3531 // Respect alignment of argument on the stack. 3532 Align Alignment = 3533 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize); 3534 ArgOffset = alignTo(ArgOffset, Alignment); 3535 // If there's no space left in the argument save area, we must 3536 // use memory (this check also catches zero-sized arguments). 3537 if (ArgOffset >= LinkageSize + ParamAreaSize) 3538 UseMemory = true; 3539 3540 // Allocate argument on the stack. 3541 ArgOffset += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize); 3542 if (Flags.isInConsecutiveRegsLast()) 3543 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3544 // If we overran the argument save area, we must use memory 3545 // (this check catches arguments passed partially in memory) 3546 if (ArgOffset > LinkageSize + ParamAreaSize) 3547 UseMemory = true; 3548 3549 // However, if the argument is actually passed in an FPR or a VR, 3550 // we don't use memory after all. 3551 if (!Flags.isByVal()) { 3552 if (ArgVT == MVT::f32 || ArgVT == MVT::f64 || 3553 // QPX registers overlap with the scalar FP registers. 3554 (HasQPX && (ArgVT == MVT::v4f32 || 3555 ArgVT == MVT::v4f64 || 3556 ArgVT == MVT::v4i1))) 3557 if (AvailableFPRs > 0) { 3558 --AvailableFPRs; 3559 return false; 3560 } 3561 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 || 3562 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 || 3563 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 || 3564 ArgVT == MVT::v1i128 || ArgVT == MVT::f128) 3565 if (AvailableVRs > 0) { 3566 --AvailableVRs; 3567 return false; 3568 } 3569 } 3570 3571 return UseMemory; 3572 } 3573 3574 /// EnsureStackAlignment - Round stack frame size up from NumBytes to 3575 /// ensure minimum alignment required for target. 3576 static unsigned EnsureStackAlignment(const PPCFrameLowering *Lowering, 3577 unsigned NumBytes) { 3578 return alignTo(NumBytes, Lowering->getStackAlign()); 3579 } 3580 3581 SDValue PPCTargetLowering::LowerFormalArguments( 3582 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3583 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3584 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3585 if (Subtarget.isAIXABI()) 3586 return LowerFormalArguments_AIX(Chain, CallConv, isVarArg, Ins, dl, DAG, 3587 InVals); 3588 if (Subtarget.is64BitELFABI()) 3589 return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins, dl, DAG, 3590 InVals); 3591 if (Subtarget.is32BitELFABI()) 3592 return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins, dl, DAG, 3593 InVals); 3594 3595 return LowerFormalArguments_Darwin(Chain, CallConv, isVarArg, Ins, dl, DAG, 3596 InVals); 3597 } 3598 3599 SDValue PPCTargetLowering::LowerFormalArguments_32SVR4( 3600 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3601 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3602 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3603 3604 // 32-bit SVR4 ABI Stack Frame Layout: 3605 // +-----------------------------------+ 3606 // +--> | Back chain | 3607 // | +-----------------------------------+ 3608 // | | Floating-point register save area | 3609 // | +-----------------------------------+ 3610 // | | General register save area | 3611 // | +-----------------------------------+ 3612 // | | CR save word | 3613 // | +-----------------------------------+ 3614 // | | VRSAVE save word | 3615 // | +-----------------------------------+ 3616 // | | Alignment padding | 3617 // | +-----------------------------------+ 3618 // | | Vector register save area | 3619 // | +-----------------------------------+ 3620 // | | Local variable space | 3621 // | +-----------------------------------+ 3622 // | | Parameter list area | 3623 // | +-----------------------------------+ 3624 // | | LR save word | 3625 // | +-----------------------------------+ 3626 // SP--> +--- | Back chain | 3627 // +-----------------------------------+ 3628 // 3629 // Specifications: 3630 // System V Application Binary Interface PowerPC Processor Supplement 3631 // AltiVec Technology Programming Interface Manual 3632 3633 MachineFunction &MF = DAG.getMachineFunction(); 3634 MachineFrameInfo &MFI = MF.getFrameInfo(); 3635 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 3636 3637 EVT PtrVT = getPointerTy(MF.getDataLayout()); 3638 // Potential tail calls could cause overwriting of argument stack slots. 3639 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt && 3640 (CallConv == CallingConv::Fast)); 3641 unsigned PtrByteSize = 4; 3642 3643 // Assign locations to all of the incoming arguments. 3644 SmallVector<CCValAssign, 16> ArgLocs; 3645 PPCCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 3646 *DAG.getContext()); 3647 3648 // Reserve space for the linkage area on the stack. 3649 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 3650 CCInfo.AllocateStack(LinkageSize, PtrByteSize); 3651 if (useSoftFloat()) 3652 CCInfo.PreAnalyzeFormalArguments(Ins); 3653 3654 CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4); 3655 CCInfo.clearWasPPCF128(); 3656 3657 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 3658 CCValAssign &VA = ArgLocs[i]; 3659 3660 // Arguments stored in registers. 3661 if (VA.isRegLoc()) { 3662 const TargetRegisterClass *RC; 3663 EVT ValVT = VA.getValVT(); 3664 3665 switch (ValVT.getSimpleVT().SimpleTy) { 3666 default: 3667 llvm_unreachable("ValVT not supported by formal arguments Lowering"); 3668 case MVT::i1: 3669 case MVT::i32: 3670 RC = &PPC::GPRCRegClass; 3671 break; 3672 case MVT::f32: 3673 if (Subtarget.hasP8Vector()) 3674 RC = &PPC::VSSRCRegClass; 3675 else if (Subtarget.hasSPE()) 3676 RC = &PPC::GPRCRegClass; 3677 else 3678 RC = &PPC::F4RCRegClass; 3679 break; 3680 case MVT::f64: 3681 if (Subtarget.hasVSX()) 3682 RC = &PPC::VSFRCRegClass; 3683 else if (Subtarget.hasSPE()) 3684 // SPE passes doubles in GPR pairs. 3685 RC = &PPC::GPRCRegClass; 3686 else 3687 RC = &PPC::F8RCRegClass; 3688 break; 3689 case MVT::v16i8: 3690 case MVT::v8i16: 3691 case MVT::v4i32: 3692 RC = &PPC::VRRCRegClass; 3693 break; 3694 case MVT::v4f32: 3695 RC = Subtarget.hasQPX() ? &PPC::QSRCRegClass : &PPC::VRRCRegClass; 3696 break; 3697 case MVT::v2f64: 3698 case MVT::v2i64: 3699 RC = &PPC::VRRCRegClass; 3700 break; 3701 case MVT::v4f64: 3702 RC = &PPC::QFRCRegClass; 3703 break; 3704 case MVT::v4i1: 3705 RC = &PPC::QBRCRegClass; 3706 break; 3707 } 3708 3709 SDValue ArgValue; 3710 // Transform the arguments stored in physical registers into 3711 // virtual ones. 3712 if (VA.getLocVT() == MVT::f64 && Subtarget.hasSPE()) { 3713 assert(i + 1 < e && "No second half of double precision argument"); 3714 unsigned RegLo = MF.addLiveIn(VA.getLocReg(), RC); 3715 unsigned RegHi = MF.addLiveIn(ArgLocs[++i].getLocReg(), RC); 3716 SDValue ArgValueLo = DAG.getCopyFromReg(Chain, dl, RegLo, MVT::i32); 3717 SDValue ArgValueHi = DAG.getCopyFromReg(Chain, dl, RegHi, MVT::i32); 3718 if (!Subtarget.isLittleEndian()) 3719 std::swap (ArgValueLo, ArgValueHi); 3720 ArgValue = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, ArgValueLo, 3721 ArgValueHi); 3722 } else { 3723 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC); 3724 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, 3725 ValVT == MVT::i1 ? MVT::i32 : ValVT); 3726 if (ValVT == MVT::i1) 3727 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue); 3728 } 3729 3730 InVals.push_back(ArgValue); 3731 } else { 3732 // Argument stored in memory. 3733 assert(VA.isMemLoc()); 3734 3735 // Get the extended size of the argument type in stack 3736 unsigned ArgSize = VA.getLocVT().getStoreSize(); 3737 // Get the actual size of the argument type 3738 unsigned ObjSize = VA.getValVT().getStoreSize(); 3739 unsigned ArgOffset = VA.getLocMemOffset(); 3740 // Stack objects in PPC32 are right justified. 3741 ArgOffset += ArgSize - ObjSize; 3742 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, isImmutable); 3743 3744 // Create load nodes to retrieve arguments from the stack. 3745 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3746 InVals.push_back( 3747 DAG.getLoad(VA.getValVT(), dl, Chain, FIN, MachinePointerInfo())); 3748 } 3749 } 3750 3751 // Assign locations to all of the incoming aggregate by value arguments. 3752 // Aggregates passed by value are stored in the local variable space of the 3753 // caller's stack frame, right above the parameter list area. 3754 SmallVector<CCValAssign, 16> ByValArgLocs; 3755 CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(), 3756 ByValArgLocs, *DAG.getContext()); 3757 3758 // Reserve stack space for the allocations in CCInfo. 3759 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize); 3760 3761 CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal); 3762 3763 // Area that is at least reserved in the caller of this function. 3764 unsigned MinReservedArea = CCByValInfo.getNextStackOffset(); 3765 MinReservedArea = std::max(MinReservedArea, LinkageSize); 3766 3767 // Set the size that is at least reserved in caller of this function. Tail 3768 // call optimized function's reserved stack space needs to be aligned so that 3769 // taking the difference between two stack areas will result in an aligned 3770 // stack. 3771 MinReservedArea = 3772 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea); 3773 FuncInfo->setMinReservedArea(MinReservedArea); 3774 3775 SmallVector<SDValue, 8> MemOps; 3776 3777 // If the function takes variable number of arguments, make a frame index for 3778 // the start of the first vararg value... for expansion of llvm.va_start. 3779 if (isVarArg) { 3780 static const MCPhysReg GPArgRegs[] = { 3781 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 3782 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 3783 }; 3784 const unsigned NumGPArgRegs = array_lengthof(GPArgRegs); 3785 3786 static const MCPhysReg FPArgRegs[] = { 3787 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7, 3788 PPC::F8 3789 }; 3790 unsigned NumFPArgRegs = array_lengthof(FPArgRegs); 3791 3792 if (useSoftFloat() || hasSPE()) 3793 NumFPArgRegs = 0; 3794 3795 FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs)); 3796 FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs)); 3797 3798 // Make room for NumGPArgRegs and NumFPArgRegs. 3799 int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 + 3800 NumFPArgRegs * MVT(MVT::f64).getSizeInBits()/8; 3801 3802 FuncInfo->setVarArgsStackOffset( 3803 MFI.CreateFixedObject(PtrVT.getSizeInBits()/8, 3804 CCInfo.getNextStackOffset(), true)); 3805 3806 FuncInfo->setVarArgsFrameIndex(MFI.CreateStackObject(Depth, 8, false)); 3807 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 3808 3809 // The fixed integer arguments of a variadic function are stored to the 3810 // VarArgsFrameIndex on the stack so that they may be loaded by 3811 // dereferencing the result of va_next. 3812 for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) { 3813 // Get an existing live-in vreg, or add a new one. 3814 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]); 3815 if (!VReg) 3816 VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass); 3817 3818 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 3819 SDValue Store = 3820 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 3821 MemOps.push_back(Store); 3822 // Increment the address by four for the next argument to store 3823 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT); 3824 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 3825 } 3826 3827 // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6 3828 // is set. 3829 // The double arguments are stored to the VarArgsFrameIndex 3830 // on the stack. 3831 for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) { 3832 // Get an existing live-in vreg, or add a new one. 3833 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]); 3834 if (!VReg) 3835 VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass); 3836 3837 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64); 3838 SDValue Store = 3839 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 3840 MemOps.push_back(Store); 3841 // Increment the address by eight for the next argument to store 3842 SDValue PtrOff = DAG.getConstant(MVT(MVT::f64).getSizeInBits()/8, dl, 3843 PtrVT); 3844 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 3845 } 3846 } 3847 3848 if (!MemOps.empty()) 3849 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 3850 3851 return Chain; 3852 } 3853 3854 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote 3855 // value to MVT::i64 and then truncate to the correct register size. 3856 SDValue PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags, 3857 EVT ObjectVT, SelectionDAG &DAG, 3858 SDValue ArgVal, 3859 const SDLoc &dl) const { 3860 if (Flags.isSExt()) 3861 ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal, 3862 DAG.getValueType(ObjectVT)); 3863 else if (Flags.isZExt()) 3864 ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal, 3865 DAG.getValueType(ObjectVT)); 3866 3867 return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal); 3868 } 3869 3870 SDValue PPCTargetLowering::LowerFormalArguments_64SVR4( 3871 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3872 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3873 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3874 // TODO: add description of PPC stack frame format, or at least some docs. 3875 // 3876 bool isELFv2ABI = Subtarget.isELFv2ABI(); 3877 bool isLittleEndian = Subtarget.isLittleEndian(); 3878 MachineFunction &MF = DAG.getMachineFunction(); 3879 MachineFrameInfo &MFI = MF.getFrameInfo(); 3880 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 3881 3882 assert(!(CallConv == CallingConv::Fast && isVarArg) && 3883 "fastcc not supported on varargs functions"); 3884 3885 EVT PtrVT = getPointerTy(MF.getDataLayout()); 3886 // Potential tail calls could cause overwriting of argument stack slots. 3887 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt && 3888 (CallConv == CallingConv::Fast)); 3889 unsigned PtrByteSize = 8; 3890 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 3891 3892 static const MCPhysReg GPR[] = { 3893 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 3894 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 3895 }; 3896 static const MCPhysReg VR[] = { 3897 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 3898 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 3899 }; 3900 3901 const unsigned Num_GPR_Regs = array_lengthof(GPR); 3902 const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13; 3903 const unsigned Num_VR_Regs = array_lengthof(VR); 3904 const unsigned Num_QFPR_Regs = Num_FPR_Regs; 3905 3906 // Do a first pass over the arguments to determine whether the ABI 3907 // guarantees that our caller has allocated the parameter save area 3908 // on its stack frame. In the ELFv1 ABI, this is always the case; 3909 // in the ELFv2 ABI, it is true if this is a vararg function or if 3910 // any parameter is located in a stack slot. 3911 3912 bool HasParameterArea = !isELFv2ABI || isVarArg; 3913 unsigned ParamAreaSize = Num_GPR_Regs * PtrByteSize; 3914 unsigned NumBytes = LinkageSize; 3915 unsigned AvailableFPRs = Num_FPR_Regs; 3916 unsigned AvailableVRs = Num_VR_Regs; 3917 for (unsigned i = 0, e = Ins.size(); i != e; ++i) { 3918 if (Ins[i].Flags.isNest()) 3919 continue; 3920 3921 if (CalculateStackSlotUsed(Ins[i].VT, Ins[i].ArgVT, Ins[i].Flags, 3922 PtrByteSize, LinkageSize, ParamAreaSize, 3923 NumBytes, AvailableFPRs, AvailableVRs, 3924 Subtarget.hasQPX())) 3925 HasParameterArea = true; 3926 } 3927 3928 // Add DAG nodes to load the arguments or copy them out of registers. On 3929 // entry to a function on PPC, the arguments start after the linkage area, 3930 // although the first ones are often in registers. 3931 3932 unsigned ArgOffset = LinkageSize; 3933 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 3934 unsigned &QFPR_idx = FPR_idx; 3935 SmallVector<SDValue, 8> MemOps; 3936 Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin(); 3937 unsigned CurArgIdx = 0; 3938 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) { 3939 SDValue ArgVal; 3940 bool needsLoad = false; 3941 EVT ObjectVT = Ins[ArgNo].VT; 3942 EVT OrigVT = Ins[ArgNo].ArgVT; 3943 unsigned ObjSize = ObjectVT.getStoreSize(); 3944 unsigned ArgSize = ObjSize; 3945 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags; 3946 if (Ins[ArgNo].isOrigArg()) { 3947 std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx); 3948 CurArgIdx = Ins[ArgNo].getOrigArgIndex(); 3949 } 3950 // We re-align the argument offset for each argument, except when using the 3951 // fast calling convention, when we need to make sure we do that only when 3952 // we'll actually use a stack slot. 3953 unsigned CurArgOffset; 3954 Align Alignment; 3955 auto ComputeArgOffset = [&]() { 3956 /* Respect alignment of argument on the stack. */ 3957 Alignment = 3958 CalculateStackSlotAlignment(ObjectVT, OrigVT, Flags, PtrByteSize); 3959 ArgOffset = alignTo(ArgOffset, Alignment); 3960 CurArgOffset = ArgOffset; 3961 }; 3962 3963 if (CallConv != CallingConv::Fast) { 3964 ComputeArgOffset(); 3965 3966 /* Compute GPR index associated with argument offset. */ 3967 GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize; 3968 GPR_idx = std::min(GPR_idx, Num_GPR_Regs); 3969 } 3970 3971 // FIXME the codegen can be much improved in some cases. 3972 // We do not have to keep everything in memory. 3973 if (Flags.isByVal()) { 3974 assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit"); 3975 3976 if (CallConv == CallingConv::Fast) 3977 ComputeArgOffset(); 3978 3979 // ObjSize is the true size, ArgSize rounded up to multiple of registers. 3980 ObjSize = Flags.getByValSize(); 3981 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3982 // Empty aggregate parameters do not take up registers. Examples: 3983 // struct { } a; 3984 // union { } b; 3985 // int c[0]; 3986 // etc. However, we have to provide a place-holder in InVals, so 3987 // pretend we have an 8-byte item at the current address for that 3988 // purpose. 3989 if (!ObjSize) { 3990 int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true); 3991 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3992 InVals.push_back(FIN); 3993 continue; 3994 } 3995 3996 // Create a stack object covering all stack doublewords occupied 3997 // by the argument. If the argument is (fully or partially) on 3998 // the stack, or if the argument is fully in registers but the 3999 // caller has allocated the parameter save anyway, we can refer 4000 // directly to the caller's stack frame. Otherwise, create a 4001 // local copy in our own frame. 4002 int FI; 4003 if (HasParameterArea || 4004 ArgSize + ArgOffset > LinkageSize + Num_GPR_Regs * PtrByteSize) 4005 FI = MFI.CreateFixedObject(ArgSize, ArgOffset, false, true); 4006 else 4007 FI = MFI.CreateStackObject(ArgSize, Alignment, false); 4008 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4009 4010 // Handle aggregates smaller than 8 bytes. 4011 if (ObjSize < PtrByteSize) { 4012 // The value of the object is its address, which differs from the 4013 // address of the enclosing doubleword on big-endian systems. 4014 SDValue Arg = FIN; 4015 if (!isLittleEndian) { 4016 SDValue ArgOff = DAG.getConstant(PtrByteSize - ObjSize, dl, PtrVT); 4017 Arg = DAG.getNode(ISD::ADD, dl, ArgOff.getValueType(), Arg, ArgOff); 4018 } 4019 InVals.push_back(Arg); 4020 4021 if (GPR_idx != Num_GPR_Regs) { 4022 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass); 4023 FuncInfo->addLiveInAttr(VReg, Flags); 4024 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4025 SDValue Store; 4026 4027 if (ObjSize==1 || ObjSize==2 || ObjSize==4) { 4028 EVT ObjType = (ObjSize == 1 ? MVT::i8 : 4029 (ObjSize == 2 ? MVT::i16 : MVT::i32)); 4030 Store = DAG.getTruncStore(Val.getValue(1), dl, Val, Arg, 4031 MachinePointerInfo(&*FuncArg), ObjType); 4032 } else { 4033 // For sizes that don't fit a truncating store (3, 5, 6, 7), 4034 // store the whole register as-is to the parameter save area 4035 // slot. 4036 Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, 4037 MachinePointerInfo(&*FuncArg)); 4038 } 4039 4040 MemOps.push_back(Store); 4041 } 4042 // Whether we copied from a register or not, advance the offset 4043 // into the parameter save area by a full doubleword. 4044 ArgOffset += PtrByteSize; 4045 continue; 4046 } 4047 4048 // The value of the object is its address, which is the address of 4049 // its first stack doubleword. 4050 InVals.push_back(FIN); 4051 4052 // Store whatever pieces of the object are in registers to memory. 4053 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) { 4054 if (GPR_idx == Num_GPR_Regs) 4055 break; 4056 4057 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4058 FuncInfo->addLiveInAttr(VReg, Flags); 4059 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4060 SDValue Addr = FIN; 4061 if (j) { 4062 SDValue Off = DAG.getConstant(j, dl, PtrVT); 4063 Addr = DAG.getNode(ISD::ADD, dl, Off.getValueType(), Addr, Off); 4064 } 4065 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, Addr, 4066 MachinePointerInfo(&*FuncArg, j)); 4067 MemOps.push_back(Store); 4068 ++GPR_idx; 4069 } 4070 ArgOffset += ArgSize; 4071 continue; 4072 } 4073 4074 switch (ObjectVT.getSimpleVT().SimpleTy) { 4075 default: llvm_unreachable("Unhandled argument type!"); 4076 case MVT::i1: 4077 case MVT::i32: 4078 case MVT::i64: 4079 if (Flags.isNest()) { 4080 // The 'nest' parameter, if any, is passed in R11. 4081 unsigned VReg = MF.addLiveIn(PPC::X11, &PPC::G8RCRegClass); 4082 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 4083 4084 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1) 4085 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl); 4086 4087 break; 4088 } 4089 4090 // These can be scalar arguments or elements of an integer array type 4091 // passed directly. Clang may use those instead of "byval" aggregate 4092 // types to avoid forcing arguments to memory unnecessarily. 4093 if (GPR_idx != Num_GPR_Regs) { 4094 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass); 4095 FuncInfo->addLiveInAttr(VReg, Flags); 4096 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 4097 4098 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1) 4099 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote 4100 // value to MVT::i64 and then truncate to the correct register size. 4101 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl); 4102 } else { 4103 if (CallConv == CallingConv::Fast) 4104 ComputeArgOffset(); 4105 4106 needsLoad = true; 4107 ArgSize = PtrByteSize; 4108 } 4109 if (CallConv != CallingConv::Fast || needsLoad) 4110 ArgOffset += 8; 4111 break; 4112 4113 case MVT::f32: 4114 case MVT::f64: 4115 // These can be scalar arguments or elements of a float array type 4116 // passed directly. The latter are used to implement ELFv2 homogenous 4117 // float aggregates. 4118 if (FPR_idx != Num_FPR_Regs) { 4119 unsigned VReg; 4120 4121 if (ObjectVT == MVT::f32) 4122 VReg = MF.addLiveIn(FPR[FPR_idx], 4123 Subtarget.hasP8Vector() 4124 ? &PPC::VSSRCRegClass 4125 : &PPC::F4RCRegClass); 4126 else 4127 VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX() 4128 ? &PPC::VSFRCRegClass 4129 : &PPC::F8RCRegClass); 4130 4131 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 4132 ++FPR_idx; 4133 } else if (GPR_idx != Num_GPR_Regs && CallConv != CallingConv::Fast) { 4134 // FIXME: We may want to re-enable this for CallingConv::Fast on the P8 4135 // once we support fp <-> gpr moves. 4136 4137 // This can only ever happen in the presence of f32 array types, 4138 // since otherwise we never run out of FPRs before running out 4139 // of GPRs. 4140 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass); 4141 FuncInfo->addLiveInAttr(VReg, Flags); 4142 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 4143 4144 if (ObjectVT == MVT::f32) { 4145 if ((ArgOffset % PtrByteSize) == (isLittleEndian ? 4 : 0)) 4146 ArgVal = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgVal, 4147 DAG.getConstant(32, dl, MVT::i32)); 4148 ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal); 4149 } 4150 4151 ArgVal = DAG.getNode(ISD::BITCAST, dl, ObjectVT, ArgVal); 4152 } else { 4153 if (CallConv == CallingConv::Fast) 4154 ComputeArgOffset(); 4155 4156 needsLoad = true; 4157 } 4158 4159 // When passing an array of floats, the array occupies consecutive 4160 // space in the argument area; only round up to the next doubleword 4161 // at the end of the array. Otherwise, each float takes 8 bytes. 4162 if (CallConv != CallingConv::Fast || needsLoad) { 4163 ArgSize = Flags.isInConsecutiveRegs() ? ObjSize : PtrByteSize; 4164 ArgOffset += ArgSize; 4165 if (Flags.isInConsecutiveRegsLast()) 4166 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 4167 } 4168 break; 4169 case MVT::v4f32: 4170 case MVT::v4i32: 4171 case MVT::v8i16: 4172 case MVT::v16i8: 4173 case MVT::v2f64: 4174 case MVT::v2i64: 4175 case MVT::v1i128: 4176 case MVT::f128: 4177 if (!Subtarget.hasQPX()) { 4178 // These can be scalar arguments or elements of a vector array type 4179 // passed directly. The latter are used to implement ELFv2 homogenous 4180 // vector aggregates. 4181 if (VR_idx != Num_VR_Regs) { 4182 unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass); 4183 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 4184 ++VR_idx; 4185 } else { 4186 if (CallConv == CallingConv::Fast) 4187 ComputeArgOffset(); 4188 needsLoad = true; 4189 } 4190 if (CallConv != CallingConv::Fast || needsLoad) 4191 ArgOffset += 16; 4192 break; 4193 } // not QPX 4194 4195 assert(ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 && 4196 "Invalid QPX parameter type"); 4197 LLVM_FALLTHROUGH; 4198 4199 case MVT::v4f64: 4200 case MVT::v4i1: 4201 // QPX vectors are treated like their scalar floating-point subregisters 4202 // (except that they're larger). 4203 unsigned Sz = ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 ? 16 : 32; 4204 if (QFPR_idx != Num_QFPR_Regs) { 4205 const TargetRegisterClass *RC; 4206 switch (ObjectVT.getSimpleVT().SimpleTy) { 4207 case MVT::v4f64: RC = &PPC::QFRCRegClass; break; 4208 case MVT::v4f32: RC = &PPC::QSRCRegClass; break; 4209 default: RC = &PPC::QBRCRegClass; break; 4210 } 4211 4212 unsigned VReg = MF.addLiveIn(QFPR[QFPR_idx], RC); 4213 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 4214 ++QFPR_idx; 4215 } else { 4216 if (CallConv == CallingConv::Fast) 4217 ComputeArgOffset(); 4218 needsLoad = true; 4219 } 4220 if (CallConv != CallingConv::Fast || needsLoad) 4221 ArgOffset += Sz; 4222 break; 4223 } 4224 4225 // We need to load the argument to a virtual register if we determined 4226 // above that we ran out of physical registers of the appropriate type. 4227 if (needsLoad) { 4228 if (ObjSize < ArgSize && !isLittleEndian) 4229 CurArgOffset += ArgSize - ObjSize; 4230 int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, isImmutable); 4231 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4232 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo()); 4233 } 4234 4235 InVals.push_back(ArgVal); 4236 } 4237 4238 // Area that is at least reserved in the caller of this function. 4239 unsigned MinReservedArea; 4240 if (HasParameterArea) 4241 MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize); 4242 else 4243 MinReservedArea = LinkageSize; 4244 4245 // Set the size that is at least reserved in caller of this function. Tail 4246 // call optimized functions' reserved stack space needs to be aligned so that 4247 // taking the difference between two stack areas will result in an aligned 4248 // stack. 4249 MinReservedArea = 4250 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea); 4251 FuncInfo->setMinReservedArea(MinReservedArea); 4252 4253 // If the function takes variable number of arguments, make a frame index for 4254 // the start of the first vararg value... for expansion of llvm.va_start. 4255 if (isVarArg) { 4256 int Depth = ArgOffset; 4257 4258 FuncInfo->setVarArgsFrameIndex( 4259 MFI.CreateFixedObject(PtrByteSize, Depth, true)); 4260 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 4261 4262 // If this function is vararg, store any remaining integer argument regs 4263 // to their spots on the stack so that they may be loaded by dereferencing 4264 // the result of va_next. 4265 for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize; 4266 GPR_idx < Num_GPR_Regs; ++GPR_idx) { 4267 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4268 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4269 SDValue Store = 4270 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 4271 MemOps.push_back(Store); 4272 // Increment the address by four for the next argument to store 4273 SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT); 4274 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 4275 } 4276 } 4277 4278 if (!MemOps.empty()) 4279 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 4280 4281 return Chain; 4282 } 4283 4284 SDValue PPCTargetLowering::LowerFormalArguments_Darwin( 4285 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 4286 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 4287 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 4288 // TODO: add description of PPC stack frame format, or at least some docs. 4289 // 4290 MachineFunction &MF = DAG.getMachineFunction(); 4291 MachineFrameInfo &MFI = MF.getFrameInfo(); 4292 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 4293 4294 EVT PtrVT = getPointerTy(MF.getDataLayout()); 4295 bool isPPC64 = PtrVT == MVT::i64; 4296 // Potential tail calls could cause overwriting of argument stack slots. 4297 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt && 4298 (CallConv == CallingConv::Fast)); 4299 unsigned PtrByteSize = isPPC64 ? 8 : 4; 4300 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 4301 unsigned ArgOffset = LinkageSize; 4302 // Area that is at least reserved in caller of this function. 4303 unsigned MinReservedArea = ArgOffset; 4304 4305 static const MCPhysReg GPR_32[] = { // 32-bit registers. 4306 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 4307 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 4308 }; 4309 static const MCPhysReg GPR_64[] = { // 64-bit registers. 4310 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 4311 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 4312 }; 4313 static const MCPhysReg VR[] = { 4314 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 4315 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 4316 }; 4317 4318 const unsigned Num_GPR_Regs = array_lengthof(GPR_32); 4319 const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13; 4320 const unsigned Num_VR_Regs = array_lengthof( VR); 4321 4322 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 4323 4324 const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32; 4325 4326 // In 32-bit non-varargs functions, the stack space for vectors is after the 4327 // stack space for non-vectors. We do not use this space unless we have 4328 // too many vectors to fit in registers, something that only occurs in 4329 // constructed examples:), but we have to walk the arglist to figure 4330 // that out...for the pathological case, compute VecArgOffset as the 4331 // start of the vector parameter area. Computing VecArgOffset is the 4332 // entire point of the following loop. 4333 unsigned VecArgOffset = ArgOffset; 4334 if (!isVarArg && !isPPC64) { 4335 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; 4336 ++ArgNo) { 4337 EVT ObjectVT = Ins[ArgNo].VT; 4338 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags; 4339 4340 if (Flags.isByVal()) { 4341 // ObjSize is the true size, ArgSize rounded up to multiple of regs. 4342 unsigned ObjSize = Flags.getByValSize(); 4343 unsigned ArgSize = 4344 ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 4345 VecArgOffset += ArgSize; 4346 continue; 4347 } 4348 4349 switch(ObjectVT.getSimpleVT().SimpleTy) { 4350 default: llvm_unreachable("Unhandled argument type!"); 4351 case MVT::i1: 4352 case MVT::i32: 4353 case MVT::f32: 4354 VecArgOffset += 4; 4355 break; 4356 case MVT::i64: // PPC64 4357 case MVT::f64: 4358 // FIXME: We are guaranteed to be !isPPC64 at this point. 4359 // Does MVT::i64 apply? 4360 VecArgOffset += 8; 4361 break; 4362 case MVT::v4f32: 4363 case MVT::v4i32: 4364 case MVT::v8i16: 4365 case MVT::v16i8: 4366 // Nothing to do, we're only looking at Nonvector args here. 4367 break; 4368 } 4369 } 4370 } 4371 // We've found where the vector parameter area in memory is. Skip the 4372 // first 12 parameters; these don't use that memory. 4373 VecArgOffset = ((VecArgOffset+15)/16)*16; 4374 VecArgOffset += 12*16; 4375 4376 // Add DAG nodes to load the arguments or copy them out of registers. On 4377 // entry to a function on PPC, the arguments start after the linkage area, 4378 // although the first ones are often in registers. 4379 4380 SmallVector<SDValue, 8> MemOps; 4381 unsigned nAltivecParamsAtEnd = 0; 4382 Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin(); 4383 unsigned CurArgIdx = 0; 4384 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) { 4385 SDValue ArgVal; 4386 bool needsLoad = false; 4387 EVT ObjectVT = Ins[ArgNo].VT; 4388 unsigned ObjSize = ObjectVT.getSizeInBits()/8; 4389 unsigned ArgSize = ObjSize; 4390 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags; 4391 if (Ins[ArgNo].isOrigArg()) { 4392 std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx); 4393 CurArgIdx = Ins[ArgNo].getOrigArgIndex(); 4394 } 4395 unsigned CurArgOffset = ArgOffset; 4396 4397 // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary. 4398 if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 || 4399 ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) { 4400 if (isVarArg || isPPC64) { 4401 MinReservedArea = ((MinReservedArea+15)/16)*16; 4402 MinReservedArea += CalculateStackSlotSize(ObjectVT, 4403 Flags, 4404 PtrByteSize); 4405 } else nAltivecParamsAtEnd++; 4406 } else 4407 // Calculate min reserved area. 4408 MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT, 4409 Flags, 4410 PtrByteSize); 4411 4412 // FIXME the codegen can be much improved in some cases. 4413 // We do not have to keep everything in memory. 4414 if (Flags.isByVal()) { 4415 assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit"); 4416 4417 // ObjSize is the true size, ArgSize rounded up to multiple of registers. 4418 ObjSize = Flags.getByValSize(); 4419 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 4420 // Objects of size 1 and 2 are right justified, everything else is 4421 // left justified. This means the memory address is adjusted forwards. 4422 if (ObjSize==1 || ObjSize==2) { 4423 CurArgOffset = CurArgOffset + (4 - ObjSize); 4424 } 4425 // The value of the object is its address. 4426 int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, false, true); 4427 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4428 InVals.push_back(FIN); 4429 if (ObjSize==1 || ObjSize==2) { 4430 if (GPR_idx != Num_GPR_Regs) { 4431 unsigned VReg; 4432 if (isPPC64) 4433 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4434 else 4435 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 4436 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4437 EVT ObjType = ObjSize == 1 ? MVT::i8 : MVT::i16; 4438 SDValue Store = 4439 DAG.getTruncStore(Val.getValue(1), dl, Val, FIN, 4440 MachinePointerInfo(&*FuncArg), ObjType); 4441 MemOps.push_back(Store); 4442 ++GPR_idx; 4443 } 4444 4445 ArgOffset += PtrByteSize; 4446 4447 continue; 4448 } 4449 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) { 4450 // Store whatever pieces of the object are in registers 4451 // to memory. ArgOffset will be the address of the beginning 4452 // of the object. 4453 if (GPR_idx != Num_GPR_Regs) { 4454 unsigned VReg; 4455 if (isPPC64) 4456 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4457 else 4458 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 4459 int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true); 4460 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4461 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4462 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, 4463 MachinePointerInfo(&*FuncArg, j)); 4464 MemOps.push_back(Store); 4465 ++GPR_idx; 4466 ArgOffset += PtrByteSize; 4467 } else { 4468 ArgOffset += ArgSize - (ArgOffset-CurArgOffset); 4469 break; 4470 } 4471 } 4472 continue; 4473 } 4474 4475 switch (ObjectVT.getSimpleVT().SimpleTy) { 4476 default: llvm_unreachable("Unhandled argument type!"); 4477 case MVT::i1: 4478 case MVT::i32: 4479 if (!isPPC64) { 4480 if (GPR_idx != Num_GPR_Regs) { 4481 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 4482 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32); 4483 4484 if (ObjectVT == MVT::i1) 4485 ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgVal); 4486 4487 ++GPR_idx; 4488 } else { 4489 needsLoad = true; 4490 ArgSize = PtrByteSize; 4491 } 4492 // All int arguments reserve stack space in the Darwin ABI. 4493 ArgOffset += PtrByteSize; 4494 break; 4495 } 4496 LLVM_FALLTHROUGH; 4497 case MVT::i64: // PPC64 4498 if (GPR_idx != Num_GPR_Regs) { 4499 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4500 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 4501 4502 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1) 4503 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote 4504 // value to MVT::i64 and then truncate to the correct register size. 4505 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl); 4506 4507 ++GPR_idx; 4508 } else { 4509 needsLoad = true; 4510 ArgSize = PtrByteSize; 4511 } 4512 // All int arguments reserve stack space in the Darwin ABI. 4513 ArgOffset += 8; 4514 break; 4515 4516 case MVT::f32: 4517 case MVT::f64: 4518 // Every 4 bytes of argument space consumes one of the GPRs available for 4519 // argument passing. 4520 if (GPR_idx != Num_GPR_Regs) { 4521 ++GPR_idx; 4522 if (ObjSize == 8 && GPR_idx != Num_GPR_Regs && !isPPC64) 4523 ++GPR_idx; 4524 } 4525 if (FPR_idx != Num_FPR_Regs) { 4526 unsigned VReg; 4527 4528 if (ObjectVT == MVT::f32) 4529 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass); 4530 else 4531 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass); 4532 4533 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 4534 ++FPR_idx; 4535 } else { 4536 needsLoad = true; 4537 } 4538 4539 // All FP arguments reserve stack space in the Darwin ABI. 4540 ArgOffset += isPPC64 ? 8 : ObjSize; 4541 break; 4542 case MVT::v4f32: 4543 case MVT::v4i32: 4544 case MVT::v8i16: 4545 case MVT::v16i8: 4546 // Note that vector arguments in registers don't reserve stack space, 4547 // except in varargs functions. 4548 if (VR_idx != Num_VR_Regs) { 4549 unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass); 4550 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 4551 if (isVarArg) { 4552 while ((ArgOffset % 16) != 0) { 4553 ArgOffset += PtrByteSize; 4554 if (GPR_idx != Num_GPR_Regs) 4555 GPR_idx++; 4556 } 4557 ArgOffset += 16; 4558 GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64? 4559 } 4560 ++VR_idx; 4561 } else { 4562 if (!isVarArg && !isPPC64) { 4563 // Vectors go after all the nonvectors. 4564 CurArgOffset = VecArgOffset; 4565 VecArgOffset += 16; 4566 } else { 4567 // Vectors are aligned. 4568 ArgOffset = ((ArgOffset+15)/16)*16; 4569 CurArgOffset = ArgOffset; 4570 ArgOffset += 16; 4571 } 4572 needsLoad = true; 4573 } 4574 break; 4575 } 4576 4577 // We need to load the argument to a virtual register if we determined above 4578 // that we ran out of physical registers of the appropriate type. 4579 if (needsLoad) { 4580 int FI = MFI.CreateFixedObject(ObjSize, 4581 CurArgOffset + (ArgSize - ObjSize), 4582 isImmutable); 4583 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4584 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo()); 4585 } 4586 4587 InVals.push_back(ArgVal); 4588 } 4589 4590 // Allow for Altivec parameters at the end, if needed. 4591 if (nAltivecParamsAtEnd) { 4592 MinReservedArea = ((MinReservedArea+15)/16)*16; 4593 MinReservedArea += 16*nAltivecParamsAtEnd; 4594 } 4595 4596 // Area that is at least reserved in the caller of this function. 4597 MinReservedArea = std::max(MinReservedArea, LinkageSize + 8 * PtrByteSize); 4598 4599 // Set the size that is at least reserved in caller of this function. Tail 4600 // call optimized functions' reserved stack space needs to be aligned so that 4601 // taking the difference between two stack areas will result in an aligned 4602 // stack. 4603 MinReservedArea = 4604 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea); 4605 FuncInfo->setMinReservedArea(MinReservedArea); 4606 4607 // If the function takes variable number of arguments, make a frame index for 4608 // the start of the first vararg value... for expansion of llvm.va_start. 4609 if (isVarArg) { 4610 int Depth = ArgOffset; 4611 4612 FuncInfo->setVarArgsFrameIndex( 4613 MFI.CreateFixedObject(PtrVT.getSizeInBits()/8, 4614 Depth, true)); 4615 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 4616 4617 // If this function is vararg, store any remaining integer argument regs 4618 // to their spots on the stack so that they may be loaded by dereferencing 4619 // the result of va_next. 4620 for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) { 4621 unsigned VReg; 4622 4623 if (isPPC64) 4624 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4625 else 4626 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 4627 4628 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4629 SDValue Store = 4630 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 4631 MemOps.push_back(Store); 4632 // Increment the address by four for the next argument to store 4633 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT); 4634 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 4635 } 4636 } 4637 4638 if (!MemOps.empty()) 4639 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 4640 4641 return Chain; 4642 } 4643 4644 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be 4645 /// adjusted to accommodate the arguments for the tailcall. 4646 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall, 4647 unsigned ParamSize) { 4648 4649 if (!isTailCall) return 0; 4650 4651 PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>(); 4652 unsigned CallerMinReservedArea = FI->getMinReservedArea(); 4653 int SPDiff = (int)CallerMinReservedArea - (int)ParamSize; 4654 // Remember only if the new adjustment is bigger. 4655 if (SPDiff < FI->getTailCallSPDelta()) 4656 FI->setTailCallSPDelta(SPDiff); 4657 4658 return SPDiff; 4659 } 4660 4661 static bool isFunctionGlobalAddress(SDValue Callee); 4662 4663 static bool 4664 callsShareTOCBase(const Function *Caller, SDValue Callee, 4665 const TargetMachine &TM) { 4666 // Callee is either a GlobalAddress or an ExternalSymbol. ExternalSymbols 4667 // don't have enough information to determine if the caller and calle share 4668 // the same TOC base, so we have to pessimistically assume they don't for 4669 // correctness. 4670 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee); 4671 if (!G) 4672 return false; 4673 4674 const GlobalValue *GV = G->getGlobal(); 4675 // The medium and large code models are expected to provide a sufficiently 4676 // large TOC to provide all data addressing needs of a module with a 4677 // single TOC. Since each module will be addressed with a single TOC then we 4678 // only need to check that caller and callee don't cross dso boundaries. 4679 if (CodeModel::Medium == TM.getCodeModel() || 4680 CodeModel::Large == TM.getCodeModel()) 4681 return TM.shouldAssumeDSOLocal(*Caller->getParent(), GV); 4682 4683 // Otherwise we need to ensure callee and caller are in the same section, 4684 // since the linker may allocate multiple TOCs, and we don't know which 4685 // sections will belong to the same TOC base. 4686 4687 if (!GV->isStrongDefinitionForLinker()) 4688 return false; 4689 4690 // Any explicitly-specified sections and section prefixes must also match. 4691 // Also, if we're using -ffunction-sections, then each function is always in 4692 // a different section (the same is true for COMDAT functions). 4693 if (TM.getFunctionSections() || GV->hasComdat() || Caller->hasComdat() || 4694 GV->getSection() != Caller->getSection()) 4695 return false; 4696 if (const auto *F = dyn_cast<Function>(GV)) { 4697 if (F->getSectionPrefix() != Caller->getSectionPrefix()) 4698 return false; 4699 } 4700 4701 // If the callee might be interposed, then we can't assume the ultimate call 4702 // target will be in the same section. Even in cases where we can assume that 4703 // interposition won't happen, in any case where the linker might insert a 4704 // stub to allow for interposition, we must generate code as though 4705 // interposition might occur. To understand why this matters, consider a 4706 // situation where: a -> b -> c where the arrows indicate calls. b and c are 4707 // in the same section, but a is in a different module (i.e. has a different 4708 // TOC base pointer). If the linker allows for interposition between b and c, 4709 // then it will generate a stub for the call edge between b and c which will 4710 // save the TOC pointer into the designated stack slot allocated by b. If we 4711 // return true here, and therefore allow a tail call between b and c, that 4712 // stack slot won't exist and the b -> c stub will end up saving b'c TOC base 4713 // pointer into the stack slot allocated by a (where the a -> b stub saved 4714 // a's TOC base pointer). If we're not considering a tail call, but rather, 4715 // whether a nop is needed after the call instruction in b, because the linker 4716 // will insert a stub, it might complain about a missing nop if we omit it 4717 // (although many don't complain in this case). 4718 if (!TM.shouldAssumeDSOLocal(*Caller->getParent(), GV)) 4719 return false; 4720 4721 return true; 4722 } 4723 4724 static bool 4725 needStackSlotPassParameters(const PPCSubtarget &Subtarget, 4726 const SmallVectorImpl<ISD::OutputArg> &Outs) { 4727 assert(Subtarget.is64BitELFABI()); 4728 4729 const unsigned PtrByteSize = 8; 4730 const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 4731 4732 static const MCPhysReg GPR[] = { 4733 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 4734 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 4735 }; 4736 static const MCPhysReg VR[] = { 4737 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 4738 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 4739 }; 4740 4741 const unsigned NumGPRs = array_lengthof(GPR); 4742 const unsigned NumFPRs = 13; 4743 const unsigned NumVRs = array_lengthof(VR); 4744 const unsigned ParamAreaSize = NumGPRs * PtrByteSize; 4745 4746 unsigned NumBytes = LinkageSize; 4747 unsigned AvailableFPRs = NumFPRs; 4748 unsigned AvailableVRs = NumVRs; 4749 4750 for (const ISD::OutputArg& Param : Outs) { 4751 if (Param.Flags.isNest()) continue; 4752 4753 if (CalculateStackSlotUsed(Param.VT, Param.ArgVT, Param.Flags, 4754 PtrByteSize, LinkageSize, ParamAreaSize, 4755 NumBytes, AvailableFPRs, AvailableVRs, 4756 Subtarget.hasQPX())) 4757 return true; 4758 } 4759 return false; 4760 } 4761 4762 static bool hasSameArgumentList(const Function *CallerFn, const CallBase &CB) { 4763 if (CB.arg_size() != CallerFn->arg_size()) 4764 return false; 4765 4766 auto CalleeArgIter = CB.arg_begin(); 4767 auto CalleeArgEnd = CB.arg_end(); 4768 Function::const_arg_iterator CallerArgIter = CallerFn->arg_begin(); 4769 4770 for (; CalleeArgIter != CalleeArgEnd; ++CalleeArgIter, ++CallerArgIter) { 4771 const Value* CalleeArg = *CalleeArgIter; 4772 const Value* CallerArg = &(*CallerArgIter); 4773 if (CalleeArg == CallerArg) 4774 continue; 4775 4776 // e.g. @caller([4 x i64] %a, [4 x i64] %b) { 4777 // tail call @callee([4 x i64] undef, [4 x i64] %b) 4778 // } 4779 // 1st argument of callee is undef and has the same type as caller. 4780 if (CalleeArg->getType() == CallerArg->getType() && 4781 isa<UndefValue>(CalleeArg)) 4782 continue; 4783 4784 return false; 4785 } 4786 4787 return true; 4788 } 4789 4790 // Returns true if TCO is possible between the callers and callees 4791 // calling conventions. 4792 static bool 4793 areCallingConvEligibleForTCO_64SVR4(CallingConv::ID CallerCC, 4794 CallingConv::ID CalleeCC) { 4795 // Tail calls are possible with fastcc and ccc. 4796 auto isTailCallableCC = [] (CallingConv::ID CC){ 4797 return CC == CallingConv::C || CC == CallingConv::Fast; 4798 }; 4799 if (!isTailCallableCC(CallerCC) || !isTailCallableCC(CalleeCC)) 4800 return false; 4801 4802 // We can safely tail call both fastcc and ccc callees from a c calling 4803 // convention caller. If the caller is fastcc, we may have less stack space 4804 // than a non-fastcc caller with the same signature so disable tail-calls in 4805 // that case. 4806 return CallerCC == CallingConv::C || CallerCC == CalleeCC; 4807 } 4808 4809 bool PPCTargetLowering::IsEligibleForTailCallOptimization_64SVR4( 4810 SDValue Callee, CallingConv::ID CalleeCC, const CallBase *CB, bool isVarArg, 4811 const SmallVectorImpl<ISD::OutputArg> &Outs, 4812 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const { 4813 bool TailCallOpt = getTargetMachine().Options.GuaranteedTailCallOpt; 4814 4815 if (DisableSCO && !TailCallOpt) return false; 4816 4817 // Variadic argument functions are not supported. 4818 if (isVarArg) return false; 4819 4820 auto &Caller = DAG.getMachineFunction().getFunction(); 4821 // Check that the calling conventions are compatible for tco. 4822 if (!areCallingConvEligibleForTCO_64SVR4(Caller.getCallingConv(), CalleeCC)) 4823 return false; 4824 4825 // Caller contains any byval parameter is not supported. 4826 if (any_of(Ins, [](const ISD::InputArg &IA) { return IA.Flags.isByVal(); })) 4827 return false; 4828 4829 // Callee contains any byval parameter is not supported, too. 4830 // Note: This is a quick work around, because in some cases, e.g. 4831 // caller's stack size > callee's stack size, we are still able to apply 4832 // sibling call optimization. For example, gcc is able to do SCO for caller1 4833 // in the following example, but not for caller2. 4834 // struct test { 4835 // long int a; 4836 // char ary[56]; 4837 // } gTest; 4838 // __attribute__((noinline)) int callee(struct test v, struct test *b) { 4839 // b->a = v.a; 4840 // return 0; 4841 // } 4842 // void caller1(struct test a, struct test c, struct test *b) { 4843 // callee(gTest, b); } 4844 // void caller2(struct test *b) { callee(gTest, b); } 4845 if (any_of(Outs, [](const ISD::OutputArg& OA) { return OA.Flags.isByVal(); })) 4846 return false; 4847 4848 // If callee and caller use different calling conventions, we cannot pass 4849 // parameters on stack since offsets for the parameter area may be different. 4850 if (Caller.getCallingConv() != CalleeCC && 4851 needStackSlotPassParameters(Subtarget, Outs)) 4852 return false; 4853 4854 // All variants of 64-bit ELF ABIs without PC-Relative addressing require that 4855 // the caller and callee share the same TOC for TCO/SCO. If the caller and 4856 // callee potentially have different TOC bases then we cannot tail call since 4857 // we need to restore the TOC pointer after the call. 4858 // ref: https://bugzilla.mozilla.org/show_bug.cgi?id=973977 4859 // We cannot guarantee this for indirect calls or calls to external functions. 4860 // When PC-Relative addressing is used, the concept of the TOC is no longer 4861 // applicable so this check is not required. 4862 // Check first for indirect calls. 4863 if (!Subtarget.isUsingPCRelativeCalls() && 4864 !isFunctionGlobalAddress(Callee) && !isa<ExternalSymbolSDNode>(Callee)) 4865 return false; 4866 4867 // Check if we share the TOC base. 4868 if (!Subtarget.isUsingPCRelativeCalls() && 4869 !callsShareTOCBase(&Caller, Callee, getTargetMachine())) 4870 return false; 4871 4872 // TCO allows altering callee ABI, so we don't have to check further. 4873 if (CalleeCC == CallingConv::Fast && TailCallOpt) 4874 return true; 4875 4876 if (DisableSCO) return false; 4877 4878 // If callee use the same argument list that caller is using, then we can 4879 // apply SCO on this case. If it is not, then we need to check if callee needs 4880 // stack for passing arguments. 4881 // PC Relative tail calls may not have a CallBase. 4882 // If there is no CallBase we cannot verify if we have the same argument 4883 // list so assume that we don't have the same argument list. 4884 if (CB && !hasSameArgumentList(&Caller, *CB) && 4885 needStackSlotPassParameters(Subtarget, Outs)) 4886 return false; 4887 else if (!CB && needStackSlotPassParameters(Subtarget, Outs)) 4888 return false; 4889 4890 return true; 4891 } 4892 4893 /// IsEligibleForTailCallOptimization - Check whether the call is eligible 4894 /// for tail call optimization. Targets which want to do tail call 4895 /// optimization should implement this function. 4896 bool 4897 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee, 4898 CallingConv::ID CalleeCC, 4899 bool isVarArg, 4900 const SmallVectorImpl<ISD::InputArg> &Ins, 4901 SelectionDAG& DAG) const { 4902 if (!getTargetMachine().Options.GuaranteedTailCallOpt) 4903 return false; 4904 4905 // Variable argument functions are not supported. 4906 if (isVarArg) 4907 return false; 4908 4909 MachineFunction &MF = DAG.getMachineFunction(); 4910 CallingConv::ID CallerCC = MF.getFunction().getCallingConv(); 4911 if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) { 4912 // Functions containing by val parameters are not supported. 4913 for (unsigned i = 0; i != Ins.size(); i++) { 4914 ISD::ArgFlagsTy Flags = Ins[i].Flags; 4915 if (Flags.isByVal()) return false; 4916 } 4917 4918 // Non-PIC/GOT tail calls are supported. 4919 if (getTargetMachine().getRelocationModel() != Reloc::PIC_) 4920 return true; 4921 4922 // At the moment we can only do local tail calls (in same module, hidden 4923 // or protected) if we are generating PIC. 4924 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) 4925 return G->getGlobal()->hasHiddenVisibility() 4926 || G->getGlobal()->hasProtectedVisibility(); 4927 } 4928 4929 return false; 4930 } 4931 4932 /// isCallCompatibleAddress - Return the immediate to use if the specified 4933 /// 32-bit value is representable in the immediate field of a BxA instruction. 4934 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) { 4935 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op); 4936 if (!C) return nullptr; 4937 4938 int Addr = C->getZExtValue(); 4939 if ((Addr & 3) != 0 || // Low 2 bits are implicitly zero. 4940 SignExtend32<26>(Addr) != Addr) 4941 return nullptr; // Top 6 bits have to be sext of immediate. 4942 4943 return DAG 4944 .getConstant( 4945 (int)C->getZExtValue() >> 2, SDLoc(Op), 4946 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout())) 4947 .getNode(); 4948 } 4949 4950 namespace { 4951 4952 struct TailCallArgumentInfo { 4953 SDValue Arg; 4954 SDValue FrameIdxOp; 4955 int FrameIdx = 0; 4956 4957 TailCallArgumentInfo() = default; 4958 }; 4959 4960 } // end anonymous namespace 4961 4962 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot. 4963 static void StoreTailCallArgumentsToStackSlot( 4964 SelectionDAG &DAG, SDValue Chain, 4965 const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs, 4966 SmallVectorImpl<SDValue> &MemOpChains, const SDLoc &dl) { 4967 for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) { 4968 SDValue Arg = TailCallArgs[i].Arg; 4969 SDValue FIN = TailCallArgs[i].FrameIdxOp; 4970 int FI = TailCallArgs[i].FrameIdx; 4971 // Store relative to framepointer. 4972 MemOpChains.push_back(DAG.getStore( 4973 Chain, dl, Arg, FIN, 4974 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI))); 4975 } 4976 } 4977 4978 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to 4979 /// the appropriate stack slot for the tail call optimized function call. 4980 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG, SDValue Chain, 4981 SDValue OldRetAddr, SDValue OldFP, 4982 int SPDiff, const SDLoc &dl) { 4983 if (SPDiff) { 4984 // Calculate the new stack slot for the return address. 4985 MachineFunction &MF = DAG.getMachineFunction(); 4986 const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>(); 4987 const PPCFrameLowering *FL = Subtarget.getFrameLowering(); 4988 bool isPPC64 = Subtarget.isPPC64(); 4989 int SlotSize = isPPC64 ? 8 : 4; 4990 int NewRetAddrLoc = SPDiff + FL->getReturnSaveOffset(); 4991 int NewRetAddr = MF.getFrameInfo().CreateFixedObject(SlotSize, 4992 NewRetAddrLoc, true); 4993 EVT VT = isPPC64 ? MVT::i64 : MVT::i32; 4994 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT); 4995 Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx, 4996 MachinePointerInfo::getFixedStack(MF, NewRetAddr)); 4997 } 4998 return Chain; 4999 } 5000 5001 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate 5002 /// the position of the argument. 5003 static void 5004 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64, 5005 SDValue Arg, int SPDiff, unsigned ArgOffset, 5006 SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) { 5007 int Offset = ArgOffset + SPDiff; 5008 uint32_t OpSize = (Arg.getValueSizeInBits() + 7) / 8; 5009 int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true); 5010 EVT VT = isPPC64 ? MVT::i64 : MVT::i32; 5011 SDValue FIN = DAG.getFrameIndex(FI, VT); 5012 TailCallArgumentInfo Info; 5013 Info.Arg = Arg; 5014 Info.FrameIdxOp = FIN; 5015 Info.FrameIdx = FI; 5016 TailCallArguments.push_back(Info); 5017 } 5018 5019 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address 5020 /// stack slot. Returns the chain as result and the loaded frame pointers in 5021 /// LROpOut/FPOpout. Used when tail calling. 5022 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr( 5023 SelectionDAG &DAG, int SPDiff, SDValue Chain, SDValue &LROpOut, 5024 SDValue &FPOpOut, const SDLoc &dl) const { 5025 if (SPDiff) { 5026 // Load the LR and FP stack slot for later adjusting. 5027 EVT VT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32; 5028 LROpOut = getReturnAddrFrameIndex(DAG); 5029 LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo()); 5030 Chain = SDValue(LROpOut.getNode(), 1); 5031 } 5032 return Chain; 5033 } 5034 5035 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified 5036 /// by "Src" to address "Dst" of size "Size". Alignment information is 5037 /// specified by the specific parameter attribute. The copy will be passed as 5038 /// a byval function parameter. 5039 /// Sometimes what we are copying is the end of a larger object, the part that 5040 /// does not fit in registers. 5041 static SDValue CreateCopyOfByValArgument(SDValue Src, SDValue Dst, 5042 SDValue Chain, ISD::ArgFlagsTy Flags, 5043 SelectionDAG &DAG, const SDLoc &dl) { 5044 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32); 5045 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, 5046 Flags.getNonZeroByValAlign(), false, false, false, 5047 MachinePointerInfo(), MachinePointerInfo()); 5048 } 5049 5050 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of 5051 /// tail calls. 5052 static void LowerMemOpCallTo( 5053 SelectionDAG &DAG, MachineFunction &MF, SDValue Chain, SDValue Arg, 5054 SDValue PtrOff, int SPDiff, unsigned ArgOffset, bool isPPC64, 5055 bool isTailCall, bool isVector, SmallVectorImpl<SDValue> &MemOpChains, 5056 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments, const SDLoc &dl) { 5057 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 5058 if (!isTailCall) { 5059 if (isVector) { 5060 SDValue StackPtr; 5061 if (isPPC64) 5062 StackPtr = DAG.getRegister(PPC::X1, MVT::i64); 5063 else 5064 StackPtr = DAG.getRegister(PPC::R1, MVT::i32); 5065 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, 5066 DAG.getConstant(ArgOffset, dl, PtrVT)); 5067 } 5068 MemOpChains.push_back( 5069 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo())); 5070 // Calculate and remember argument location. 5071 } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset, 5072 TailCallArguments); 5073 } 5074 5075 static void 5076 PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain, 5077 const SDLoc &dl, int SPDiff, unsigned NumBytes, SDValue LROp, 5078 SDValue FPOp, 5079 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) { 5080 // Emit a sequence of copyto/copyfrom virtual registers for arguments that 5081 // might overwrite each other in case of tail call optimization. 5082 SmallVector<SDValue, 8> MemOpChains2; 5083 // Do not flag preceding copytoreg stuff together with the following stuff. 5084 InFlag = SDValue(); 5085 StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments, 5086 MemOpChains2, dl); 5087 if (!MemOpChains2.empty()) 5088 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2); 5089 5090 // Store the return address to the appropriate stack slot. 5091 Chain = EmitTailCallStoreFPAndRetAddr(DAG, Chain, LROp, FPOp, SPDiff, dl); 5092 5093 // Emit callseq_end just before tailcall node. 5094 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true), 5095 DAG.getIntPtrConstant(0, dl, true), InFlag, dl); 5096 InFlag = Chain.getValue(1); 5097 } 5098 5099 // Is this global address that of a function that can be called by name? (as 5100 // opposed to something that must hold a descriptor for an indirect call). 5101 static bool isFunctionGlobalAddress(SDValue Callee) { 5102 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 5103 if (Callee.getOpcode() == ISD::GlobalTLSAddress || 5104 Callee.getOpcode() == ISD::TargetGlobalTLSAddress) 5105 return false; 5106 5107 return G->getGlobal()->getValueType()->isFunctionTy(); 5108 } 5109 5110 return false; 5111 } 5112 5113 SDValue PPCTargetLowering::LowerCallResult( 5114 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg, 5115 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 5116 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 5117 SmallVector<CCValAssign, 16> RVLocs; 5118 CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 5119 *DAG.getContext()); 5120 5121 CCRetInfo.AnalyzeCallResult( 5122 Ins, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold) 5123 ? RetCC_PPC_Cold 5124 : RetCC_PPC); 5125 5126 // Copy all of the result registers out of their specified physreg. 5127 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) { 5128 CCValAssign &VA = RVLocs[i]; 5129 assert(VA.isRegLoc() && "Can only return in registers!"); 5130 5131 SDValue Val; 5132 5133 if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) { 5134 SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, 5135 InFlag); 5136 Chain = Lo.getValue(1); 5137 InFlag = Lo.getValue(2); 5138 VA = RVLocs[++i]; // skip ahead to next loc 5139 SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, 5140 InFlag); 5141 Chain = Hi.getValue(1); 5142 InFlag = Hi.getValue(2); 5143 if (!Subtarget.isLittleEndian()) 5144 std::swap (Lo, Hi); 5145 Val = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, Lo, Hi); 5146 } else { 5147 Val = DAG.getCopyFromReg(Chain, dl, 5148 VA.getLocReg(), VA.getLocVT(), InFlag); 5149 Chain = Val.getValue(1); 5150 InFlag = Val.getValue(2); 5151 } 5152 5153 switch (VA.getLocInfo()) { 5154 default: llvm_unreachable("Unknown loc info!"); 5155 case CCValAssign::Full: break; 5156 case CCValAssign::AExt: 5157 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val); 5158 break; 5159 case CCValAssign::ZExt: 5160 Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val, 5161 DAG.getValueType(VA.getValVT())); 5162 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val); 5163 break; 5164 case CCValAssign::SExt: 5165 Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val, 5166 DAG.getValueType(VA.getValVT())); 5167 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val); 5168 break; 5169 } 5170 5171 InVals.push_back(Val); 5172 } 5173 5174 return Chain; 5175 } 5176 5177 static bool isIndirectCall(const SDValue &Callee, SelectionDAG &DAG, 5178 const PPCSubtarget &Subtarget, bool isPatchPoint) { 5179 // PatchPoint calls are not indirect. 5180 if (isPatchPoint) 5181 return false; 5182 5183 if (isFunctionGlobalAddress(Callee) || dyn_cast<ExternalSymbolSDNode>(Callee)) 5184 return false; 5185 5186 // Darwin, and 32-bit ELF can use a BLA. The descriptor based ABIs can not 5187 // becuase the immediate function pointer points to a descriptor instead of 5188 // a function entry point. The ELFv2 ABI cannot use a BLA because the function 5189 // pointer immediate points to the global entry point, while the BLA would 5190 // need to jump to the local entry point (see rL211174). 5191 if (!Subtarget.usesFunctionDescriptors() && !Subtarget.isELFv2ABI() && 5192 isBLACompatibleAddress(Callee, DAG)) 5193 return false; 5194 5195 return true; 5196 } 5197 5198 // AIX and 64-bit ELF ABIs w/o PCRel require a TOC save/restore around calls. 5199 static inline bool isTOCSaveRestoreRequired(const PPCSubtarget &Subtarget) { 5200 return Subtarget.isAIXABI() || 5201 (Subtarget.is64BitELFABI() && !Subtarget.isUsingPCRelativeCalls()); 5202 } 5203 5204 static unsigned getCallOpcode(PPCTargetLowering::CallFlags CFlags, 5205 const Function &Caller, 5206 const SDValue &Callee, 5207 const PPCSubtarget &Subtarget, 5208 const TargetMachine &TM) { 5209 if (CFlags.IsTailCall) 5210 return PPCISD::TC_RETURN; 5211 5212 // This is a call through a function pointer. 5213 if (CFlags.IsIndirect) { 5214 // AIX and the 64-bit ELF ABIs need to maintain the TOC pointer accross 5215 // indirect calls. The save of the caller's TOC pointer to the stack will be 5216 // inserted into the DAG as part of call lowering. The restore of the TOC 5217 // pointer is modeled by using a pseudo instruction for the call opcode that 5218 // represents the 2 instruction sequence of an indirect branch and link, 5219 // immediately followed by a load of the TOC pointer from the the stack save 5220 // slot into gpr2. For 64-bit ELFv2 ABI with PCRel, do not restore the TOC 5221 // as it is not saved or used. 5222 return isTOCSaveRestoreRequired(Subtarget) ? PPCISD::BCTRL_LOAD_TOC 5223 : PPCISD::BCTRL; 5224 } 5225 5226 if (Subtarget.isUsingPCRelativeCalls()) { 5227 assert(Subtarget.is64BitELFABI() && "PC Relative is only on ELF ABI."); 5228 return PPCISD::CALL_NOTOC; 5229 } 5230 5231 // The ABIs that maintain a TOC pointer accross calls need to have a nop 5232 // immediately following the call instruction if the caller and callee may 5233 // have different TOC bases. At link time if the linker determines the calls 5234 // may not share a TOC base, the call is redirected to a trampoline inserted 5235 // by the linker. The trampoline will (among other things) save the callers 5236 // TOC pointer at an ABI designated offset in the linkage area and the linker 5237 // will rewrite the nop to be a load of the TOC pointer from the linkage area 5238 // into gpr2. 5239 if (Subtarget.isAIXABI() || Subtarget.is64BitELFABI()) 5240 return callsShareTOCBase(&Caller, Callee, TM) ? PPCISD::CALL 5241 : PPCISD::CALL_NOP; 5242 5243 return PPCISD::CALL; 5244 } 5245 5246 static SDValue transformCallee(const SDValue &Callee, SelectionDAG &DAG, 5247 const SDLoc &dl, const PPCSubtarget &Subtarget) { 5248 if (!Subtarget.usesFunctionDescriptors() && !Subtarget.isELFv2ABI()) 5249 if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG)) 5250 return SDValue(Dest, 0); 5251 5252 // Returns true if the callee is local, and false otherwise. 5253 auto isLocalCallee = [&]() { 5254 const GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee); 5255 const Module *Mod = DAG.getMachineFunction().getFunction().getParent(); 5256 const GlobalValue *GV = G ? G->getGlobal() : nullptr; 5257 5258 return DAG.getTarget().shouldAssumeDSOLocal(*Mod, GV) && 5259 !dyn_cast_or_null<GlobalIFunc>(GV); 5260 }; 5261 5262 // The PLT is only used in 32-bit ELF PIC mode. Attempting to use the PLT in 5263 // a static relocation model causes some versions of GNU LD (2.17.50, at 5264 // least) to force BSS-PLT, instead of secure-PLT, even if all objects are 5265 // built with secure-PLT. 5266 bool UsePlt = 5267 Subtarget.is32BitELFABI() && !isLocalCallee() && 5268 Subtarget.getTargetMachine().getRelocationModel() == Reloc::PIC_; 5269 5270 // On AIX, direct function calls reference the symbol for the function's 5271 // entry point, which is named by prepending a "." before the function's 5272 // C-linkage name. 5273 const auto getAIXFuncEntryPointSymbolSDNode = 5274 [&](StringRef FuncName, bool IsDeclaration, 5275 const XCOFF::StorageClass &SC) { 5276 auto &Context = DAG.getMachineFunction().getMMI().getContext(); 5277 5278 MCSymbolXCOFF *S = cast<MCSymbolXCOFF>( 5279 Context.getOrCreateSymbol(Twine(".") + Twine(FuncName))); 5280 5281 if (IsDeclaration && !S->hasRepresentedCsectSet()) { 5282 // On AIX, an undefined symbol needs to be associated with a 5283 // MCSectionXCOFF to get the correct storage mapping class. 5284 // In this case, XCOFF::XMC_PR. 5285 MCSectionXCOFF *Sec = Context.getXCOFFSection( 5286 S->getName(), XCOFF::XMC_PR, XCOFF::XTY_ER, SC, 5287 SectionKind::getMetadata()); 5288 S->setRepresentedCsect(Sec); 5289 } 5290 5291 MVT PtrVT = 5292 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 5293 return DAG.getMCSymbol(S, PtrVT); 5294 }; 5295 5296 if (isFunctionGlobalAddress(Callee)) { 5297 const GlobalAddressSDNode *G = cast<GlobalAddressSDNode>(Callee); 5298 const GlobalValue *GV = G->getGlobal(); 5299 5300 if (!Subtarget.isAIXABI()) 5301 return DAG.getTargetGlobalAddress(GV, dl, Callee.getValueType(), 0, 5302 UsePlt ? PPCII::MO_PLT : 0); 5303 5304 assert(!isa<GlobalIFunc>(GV) && "IFunc is not supported on AIX."); 5305 const GlobalObject *GO = cast<GlobalObject>(GV); 5306 const XCOFF::StorageClass SC = 5307 TargetLoweringObjectFileXCOFF::getStorageClassForGlobal(GO); 5308 return getAIXFuncEntryPointSymbolSDNode(GO->getName(), GO->isDeclaration(), 5309 SC); 5310 } 5311 5312 if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) { 5313 const char *SymName = S->getSymbol(); 5314 if (!Subtarget.isAIXABI()) 5315 return DAG.getTargetExternalSymbol(SymName, Callee.getValueType(), 5316 UsePlt ? PPCII::MO_PLT : 0); 5317 5318 // If there exists a user-declared function whose name is the same as the 5319 // ExternalSymbol's, then we pick up the user-declared version. 5320 const Module *Mod = DAG.getMachineFunction().getFunction().getParent(); 5321 if (const Function *F = 5322 dyn_cast_or_null<Function>(Mod->getNamedValue(SymName))) { 5323 const XCOFF::StorageClass SC = 5324 TargetLoweringObjectFileXCOFF::getStorageClassForGlobal(F); 5325 return getAIXFuncEntryPointSymbolSDNode(F->getName(), F->isDeclaration(), 5326 SC); 5327 } 5328 5329 return getAIXFuncEntryPointSymbolSDNode(SymName, true, XCOFF::C_EXT); 5330 } 5331 5332 // No transformation needed. 5333 assert(Callee.getNode() && "What no callee?"); 5334 return Callee; 5335 } 5336 5337 static SDValue getOutputChainFromCallSeq(SDValue CallSeqStart) { 5338 assert(CallSeqStart.getOpcode() == ISD::CALLSEQ_START && 5339 "Expected a CALLSEQ_STARTSDNode."); 5340 5341 // The last operand is the chain, except when the node has glue. If the node 5342 // has glue, then the last operand is the glue, and the chain is the second 5343 // last operand. 5344 SDValue LastValue = CallSeqStart.getValue(CallSeqStart->getNumValues() - 1); 5345 if (LastValue.getValueType() != MVT::Glue) 5346 return LastValue; 5347 5348 return CallSeqStart.getValue(CallSeqStart->getNumValues() - 2); 5349 } 5350 5351 // Creates the node that moves a functions address into the count register 5352 // to prepare for an indirect call instruction. 5353 static void prepareIndirectCall(SelectionDAG &DAG, SDValue &Callee, 5354 SDValue &Glue, SDValue &Chain, 5355 const SDLoc &dl) { 5356 SDValue MTCTROps[] = {Chain, Callee, Glue}; 5357 EVT ReturnTypes[] = {MVT::Other, MVT::Glue}; 5358 Chain = DAG.getNode(PPCISD::MTCTR, dl, makeArrayRef(ReturnTypes, 2), 5359 makeArrayRef(MTCTROps, Glue.getNode() ? 3 : 2)); 5360 // The glue is the second value produced. 5361 Glue = Chain.getValue(1); 5362 } 5363 5364 static void prepareDescriptorIndirectCall(SelectionDAG &DAG, SDValue &Callee, 5365 SDValue &Glue, SDValue &Chain, 5366 SDValue CallSeqStart, 5367 const CallBase *CB, const SDLoc &dl, 5368 bool hasNest, 5369 const PPCSubtarget &Subtarget) { 5370 // Function pointers in the 64-bit SVR4 ABI do not point to the function 5371 // entry point, but to the function descriptor (the function entry point 5372 // address is part of the function descriptor though). 5373 // The function descriptor is a three doubleword structure with the 5374 // following fields: function entry point, TOC base address and 5375 // environment pointer. 5376 // Thus for a call through a function pointer, the following actions need 5377 // to be performed: 5378 // 1. Save the TOC of the caller in the TOC save area of its stack 5379 // frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()). 5380 // 2. Load the address of the function entry point from the function 5381 // descriptor. 5382 // 3. Load the TOC of the callee from the function descriptor into r2. 5383 // 4. Load the environment pointer from the function descriptor into 5384 // r11. 5385 // 5. Branch to the function entry point address. 5386 // 6. On return of the callee, the TOC of the caller needs to be 5387 // restored (this is done in FinishCall()). 5388 // 5389 // The loads are scheduled at the beginning of the call sequence, and the 5390 // register copies are flagged together to ensure that no other 5391 // operations can be scheduled in between. E.g. without flagging the 5392 // copies together, a TOC access in the caller could be scheduled between 5393 // the assignment of the callee TOC and the branch to the callee, which leads 5394 // to incorrect code. 5395 5396 // Start by loading the function address from the descriptor. 5397 SDValue LDChain = getOutputChainFromCallSeq(CallSeqStart); 5398 auto MMOFlags = Subtarget.hasInvariantFunctionDescriptors() 5399 ? (MachineMemOperand::MODereferenceable | 5400 MachineMemOperand::MOInvariant) 5401 : MachineMemOperand::MONone; 5402 5403 MachinePointerInfo MPI(CB ? CB->getCalledOperand() : nullptr); 5404 5405 // Registers used in building the DAG. 5406 const MCRegister EnvPtrReg = Subtarget.getEnvironmentPointerRegister(); 5407 const MCRegister TOCReg = Subtarget.getTOCPointerRegister(); 5408 5409 // Offsets of descriptor members. 5410 const unsigned TOCAnchorOffset = Subtarget.descriptorTOCAnchorOffset(); 5411 const unsigned EnvPtrOffset = Subtarget.descriptorEnvironmentPointerOffset(); 5412 5413 const MVT RegVT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32; 5414 const unsigned Alignment = Subtarget.isPPC64() ? 8 : 4; 5415 5416 // One load for the functions entry point address. 5417 SDValue LoadFuncPtr = DAG.getLoad(RegVT, dl, LDChain, Callee, MPI, 5418 Alignment, MMOFlags); 5419 5420 // One for loading the TOC anchor for the module that contains the called 5421 // function. 5422 SDValue TOCOff = DAG.getIntPtrConstant(TOCAnchorOffset, dl); 5423 SDValue AddTOC = DAG.getNode(ISD::ADD, dl, RegVT, Callee, TOCOff); 5424 SDValue TOCPtr = 5425 DAG.getLoad(RegVT, dl, LDChain, AddTOC, 5426 MPI.getWithOffset(TOCAnchorOffset), Alignment, MMOFlags); 5427 5428 // One for loading the environment pointer. 5429 SDValue PtrOff = DAG.getIntPtrConstant(EnvPtrOffset, dl); 5430 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, RegVT, Callee, PtrOff); 5431 SDValue LoadEnvPtr = 5432 DAG.getLoad(RegVT, dl, LDChain, AddPtr, 5433 MPI.getWithOffset(EnvPtrOffset), Alignment, MMOFlags); 5434 5435 5436 // Then copy the newly loaded TOC anchor to the TOC pointer. 5437 SDValue TOCVal = DAG.getCopyToReg(Chain, dl, TOCReg, TOCPtr, Glue); 5438 Chain = TOCVal.getValue(0); 5439 Glue = TOCVal.getValue(1); 5440 5441 // If the function call has an explicit 'nest' parameter, it takes the 5442 // place of the environment pointer. 5443 assert((!hasNest || !Subtarget.isAIXABI()) && 5444 "Nest parameter is not supported on AIX."); 5445 if (!hasNest) { 5446 SDValue EnvVal = DAG.getCopyToReg(Chain, dl, EnvPtrReg, LoadEnvPtr, Glue); 5447 Chain = EnvVal.getValue(0); 5448 Glue = EnvVal.getValue(1); 5449 } 5450 5451 // The rest of the indirect call sequence is the same as the non-descriptor 5452 // DAG. 5453 prepareIndirectCall(DAG, LoadFuncPtr, Glue, Chain, dl); 5454 } 5455 5456 static void 5457 buildCallOperands(SmallVectorImpl<SDValue> &Ops, 5458 PPCTargetLowering::CallFlags CFlags, const SDLoc &dl, 5459 SelectionDAG &DAG, 5460 SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, 5461 SDValue Glue, SDValue Chain, SDValue &Callee, int SPDiff, 5462 const PPCSubtarget &Subtarget) { 5463 const bool IsPPC64 = Subtarget.isPPC64(); 5464 // MVT for a general purpose register. 5465 const MVT RegVT = IsPPC64 ? MVT::i64 : MVT::i32; 5466 5467 // First operand is always the chain. 5468 Ops.push_back(Chain); 5469 5470 // If it's a direct call pass the callee as the second operand. 5471 if (!CFlags.IsIndirect) 5472 Ops.push_back(Callee); 5473 else { 5474 assert(!CFlags.IsPatchPoint && "Patch point calls are not indirect."); 5475 5476 // For the TOC based ABIs, we have saved the TOC pointer to the linkage area 5477 // on the stack (this would have been done in `LowerCall_64SVR4` or 5478 // `LowerCall_AIX`). The call instruction is a pseudo instruction that 5479 // represents both the indirect branch and a load that restores the TOC 5480 // pointer from the linkage area. The operand for the TOC restore is an add 5481 // of the TOC save offset to the stack pointer. This must be the second 5482 // operand: after the chain input but before any other variadic arguments. 5483 // For 64-bit ELFv2 ABI with PCRel, do not restore the TOC as it is not 5484 // saved or used. 5485 if (isTOCSaveRestoreRequired(Subtarget)) { 5486 const MCRegister StackPtrReg = Subtarget.getStackPointerRegister(); 5487 5488 SDValue StackPtr = DAG.getRegister(StackPtrReg, RegVT); 5489 unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset(); 5490 SDValue TOCOff = DAG.getIntPtrConstant(TOCSaveOffset, dl); 5491 SDValue AddTOC = DAG.getNode(ISD::ADD, dl, RegVT, StackPtr, TOCOff); 5492 Ops.push_back(AddTOC); 5493 } 5494 5495 // Add the register used for the environment pointer. 5496 if (Subtarget.usesFunctionDescriptors() && !CFlags.HasNest) 5497 Ops.push_back(DAG.getRegister(Subtarget.getEnvironmentPointerRegister(), 5498 RegVT)); 5499 5500 5501 // Add CTR register as callee so a bctr can be emitted later. 5502 if (CFlags.IsTailCall) 5503 Ops.push_back(DAG.getRegister(IsPPC64 ? PPC::CTR8 : PPC::CTR, RegVT)); 5504 } 5505 5506 // If this is a tail call add stack pointer delta. 5507 if (CFlags.IsTailCall) 5508 Ops.push_back(DAG.getConstant(SPDiff, dl, MVT::i32)); 5509 5510 // Add argument registers to the end of the list so that they are known live 5511 // into the call. 5512 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) 5513 Ops.push_back(DAG.getRegister(RegsToPass[i].first, 5514 RegsToPass[i].second.getValueType())); 5515 5516 // We cannot add R2/X2 as an operand here for PATCHPOINT, because there is 5517 // no way to mark dependencies as implicit here. 5518 // We will add the R2/X2 dependency in EmitInstrWithCustomInserter. 5519 if ((Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) && 5520 !CFlags.IsPatchPoint && !Subtarget.isUsingPCRelativeCalls()) 5521 Ops.push_back(DAG.getRegister(Subtarget.getTOCPointerRegister(), RegVT)); 5522 5523 // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls 5524 if (CFlags.IsVarArg && Subtarget.is32BitELFABI()) 5525 Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32)); 5526 5527 // Add a register mask operand representing the call-preserved registers. 5528 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo(); 5529 const uint32_t *Mask = 5530 TRI->getCallPreservedMask(DAG.getMachineFunction(), CFlags.CallConv); 5531 assert(Mask && "Missing call preserved mask for calling convention"); 5532 Ops.push_back(DAG.getRegisterMask(Mask)); 5533 5534 // If the glue is valid, it is the last operand. 5535 if (Glue.getNode()) 5536 Ops.push_back(Glue); 5537 } 5538 5539 SDValue PPCTargetLowering::FinishCall( 5540 CallFlags CFlags, const SDLoc &dl, SelectionDAG &DAG, 5541 SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, SDValue Glue, 5542 SDValue Chain, SDValue CallSeqStart, SDValue &Callee, int SPDiff, 5543 unsigned NumBytes, const SmallVectorImpl<ISD::InputArg> &Ins, 5544 SmallVectorImpl<SDValue> &InVals, const CallBase *CB) const { 5545 5546 if ((Subtarget.is64BitELFABI() && !Subtarget.isUsingPCRelativeCalls()) || 5547 Subtarget.isAIXABI()) 5548 setUsesTOCBasePtr(DAG); 5549 5550 unsigned CallOpc = 5551 getCallOpcode(CFlags, DAG.getMachineFunction().getFunction(), Callee, 5552 Subtarget, DAG.getTarget()); 5553 5554 if (!CFlags.IsIndirect) 5555 Callee = transformCallee(Callee, DAG, dl, Subtarget); 5556 else if (Subtarget.usesFunctionDescriptors()) 5557 prepareDescriptorIndirectCall(DAG, Callee, Glue, Chain, CallSeqStart, CB, 5558 dl, CFlags.HasNest, Subtarget); 5559 else 5560 prepareIndirectCall(DAG, Callee, Glue, Chain, dl); 5561 5562 // Build the operand list for the call instruction. 5563 SmallVector<SDValue, 8> Ops; 5564 buildCallOperands(Ops, CFlags, dl, DAG, RegsToPass, Glue, Chain, Callee, 5565 SPDiff, Subtarget); 5566 5567 // Emit tail call. 5568 if (CFlags.IsTailCall) { 5569 // Indirect tail call when using PC Relative calls do not have the same 5570 // constraints. 5571 assert(((Callee.getOpcode() == ISD::Register && 5572 cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) || 5573 Callee.getOpcode() == ISD::TargetExternalSymbol || 5574 Callee.getOpcode() == ISD::TargetGlobalAddress || 5575 isa<ConstantSDNode>(Callee) || 5576 (CFlags.IsIndirect && Subtarget.isUsingPCRelativeCalls())) && 5577 "Expecting a global address, external symbol, absolute value, " 5578 "register or an indirect tail call when PC Relative calls are " 5579 "used."); 5580 // PC Relative calls also use TC_RETURN as the way to mark tail calls. 5581 assert(CallOpc == PPCISD::TC_RETURN && 5582 "Unexpected call opcode for a tail call."); 5583 DAG.getMachineFunction().getFrameInfo().setHasTailCall(); 5584 return DAG.getNode(CallOpc, dl, MVT::Other, Ops); 5585 } 5586 5587 std::array<EVT, 2> ReturnTypes = {{MVT::Other, MVT::Glue}}; 5588 Chain = DAG.getNode(CallOpc, dl, ReturnTypes, Ops); 5589 Glue = Chain.getValue(1); 5590 5591 // When performing tail call optimization the callee pops its arguments off 5592 // the stack. Account for this here so these bytes can be pushed back on in 5593 // PPCFrameLowering::eliminateCallFramePseudoInstr. 5594 int BytesCalleePops = (CFlags.CallConv == CallingConv::Fast && 5595 getTargetMachine().Options.GuaranteedTailCallOpt) 5596 ? NumBytes 5597 : 0; 5598 5599 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true), 5600 DAG.getIntPtrConstant(BytesCalleePops, dl, true), 5601 Glue, dl); 5602 Glue = Chain.getValue(1); 5603 5604 return LowerCallResult(Chain, Glue, CFlags.CallConv, CFlags.IsVarArg, Ins, dl, 5605 DAG, InVals); 5606 } 5607 5608 SDValue 5609 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI, 5610 SmallVectorImpl<SDValue> &InVals) const { 5611 SelectionDAG &DAG = CLI.DAG; 5612 SDLoc &dl = CLI.DL; 5613 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs; 5614 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals; 5615 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins; 5616 SDValue Chain = CLI.Chain; 5617 SDValue Callee = CLI.Callee; 5618 bool &isTailCall = CLI.IsTailCall; 5619 CallingConv::ID CallConv = CLI.CallConv; 5620 bool isVarArg = CLI.IsVarArg; 5621 bool isPatchPoint = CLI.IsPatchPoint; 5622 const CallBase *CB = CLI.CB; 5623 5624 if (isTailCall) { 5625 if (Subtarget.useLongCalls() && !(CB && CB->isMustTailCall())) 5626 isTailCall = false; 5627 else if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) 5628 isTailCall = IsEligibleForTailCallOptimization_64SVR4( 5629 Callee, CallConv, CB, isVarArg, Outs, Ins, DAG); 5630 else 5631 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg, 5632 Ins, DAG); 5633 if (isTailCall) { 5634 ++NumTailCalls; 5635 if (!getTargetMachine().Options.GuaranteedTailCallOpt) 5636 ++NumSiblingCalls; 5637 5638 // PC Relative calls no longer guarantee that the callee is a Global 5639 // Address Node. The callee could be an indirect tail call in which 5640 // case the SDValue for the callee could be a load (to load the address 5641 // of a function pointer) or it may be a register copy (to move the 5642 // address of the callee from a function parameter into a virtual 5643 // register). It may also be an ExternalSymbolSDNode (ex memcopy). 5644 assert((Subtarget.isUsingPCRelativeCalls() || 5645 isa<GlobalAddressSDNode>(Callee)) && 5646 "Callee should be an llvm::Function object."); 5647 5648 LLVM_DEBUG(dbgs() << "TCO caller: " << DAG.getMachineFunction().getName() 5649 << "\nTCO callee: "); 5650 LLVM_DEBUG(Callee.dump()); 5651 } 5652 } 5653 5654 if (!isTailCall && CB && CB->isMustTailCall()) 5655 report_fatal_error("failed to perform tail call elimination on a call " 5656 "site marked musttail"); 5657 5658 // When long calls (i.e. indirect calls) are always used, calls are always 5659 // made via function pointer. If we have a function name, first translate it 5660 // into a pointer. 5661 if (Subtarget.useLongCalls() && isa<GlobalAddressSDNode>(Callee) && 5662 !isTailCall) 5663 Callee = LowerGlobalAddress(Callee, DAG); 5664 5665 CallFlags CFlags( 5666 CallConv, isTailCall, isVarArg, isPatchPoint, 5667 isIndirectCall(Callee, DAG, Subtarget, isPatchPoint), 5668 // hasNest 5669 Subtarget.is64BitELFABI() && 5670 any_of(Outs, [](ISD::OutputArg Arg) { return Arg.Flags.isNest(); })); 5671 5672 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) 5673 return LowerCall_64SVR4(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG, 5674 InVals, CB); 5675 5676 if (Subtarget.isSVR4ABI()) 5677 return LowerCall_32SVR4(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG, 5678 InVals, CB); 5679 5680 if (Subtarget.isAIXABI()) 5681 return LowerCall_AIX(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG, 5682 InVals, CB); 5683 5684 return LowerCall_Darwin(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG, 5685 InVals, CB); 5686 } 5687 5688 SDValue PPCTargetLowering::LowerCall_32SVR4( 5689 SDValue Chain, SDValue Callee, CallFlags CFlags, 5690 const SmallVectorImpl<ISD::OutputArg> &Outs, 5691 const SmallVectorImpl<SDValue> &OutVals, 5692 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 5693 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 5694 const CallBase *CB) const { 5695 // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description 5696 // of the 32-bit SVR4 ABI stack frame layout. 5697 5698 const CallingConv::ID CallConv = CFlags.CallConv; 5699 const bool IsVarArg = CFlags.IsVarArg; 5700 const bool IsTailCall = CFlags.IsTailCall; 5701 5702 assert((CallConv == CallingConv::C || 5703 CallConv == CallingConv::Cold || 5704 CallConv == CallingConv::Fast) && "Unknown calling convention!"); 5705 5706 unsigned PtrByteSize = 4; 5707 5708 MachineFunction &MF = DAG.getMachineFunction(); 5709 5710 // Mark this function as potentially containing a function that contains a 5711 // tail call. As a consequence the frame pointer will be used for dynamicalloc 5712 // and restoring the callers stack pointer in this functions epilog. This is 5713 // done because by tail calling the called function might overwrite the value 5714 // in this function's (MF) stack pointer stack slot 0(SP). 5715 if (getTargetMachine().Options.GuaranteedTailCallOpt && 5716 CallConv == CallingConv::Fast) 5717 MF.getInfo<PPCFunctionInfo>()->setHasFastCall(); 5718 5719 // Count how many bytes are to be pushed on the stack, including the linkage 5720 // area, parameter list area and the part of the local variable space which 5721 // contains copies of aggregates which are passed by value. 5722 5723 // Assign locations to all of the outgoing arguments. 5724 SmallVector<CCValAssign, 16> ArgLocs; 5725 PPCCCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 5726 5727 // Reserve space for the linkage area on the stack. 5728 CCInfo.AllocateStack(Subtarget.getFrameLowering()->getLinkageSize(), 5729 PtrByteSize); 5730 if (useSoftFloat()) 5731 CCInfo.PreAnalyzeCallOperands(Outs); 5732 5733 if (IsVarArg) { 5734 // Handle fixed and variable vector arguments differently. 5735 // Fixed vector arguments go into registers as long as registers are 5736 // available. Variable vector arguments always go into memory. 5737 unsigned NumArgs = Outs.size(); 5738 5739 for (unsigned i = 0; i != NumArgs; ++i) { 5740 MVT ArgVT = Outs[i].VT; 5741 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 5742 bool Result; 5743 5744 if (Outs[i].IsFixed) { 5745 Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, 5746 CCInfo); 5747 } else { 5748 Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full, 5749 ArgFlags, CCInfo); 5750 } 5751 5752 if (Result) { 5753 #ifndef NDEBUG 5754 errs() << "Call operand #" << i << " has unhandled type " 5755 << EVT(ArgVT).getEVTString() << "\n"; 5756 #endif 5757 llvm_unreachable(nullptr); 5758 } 5759 } 5760 } else { 5761 // All arguments are treated the same. 5762 CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4); 5763 } 5764 CCInfo.clearWasPPCF128(); 5765 5766 // Assign locations to all of the outgoing aggregate by value arguments. 5767 SmallVector<CCValAssign, 16> ByValArgLocs; 5768 CCState CCByValInfo(CallConv, IsVarArg, MF, ByValArgLocs, *DAG.getContext()); 5769 5770 // Reserve stack space for the allocations in CCInfo. 5771 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize); 5772 5773 CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal); 5774 5775 // Size of the linkage area, parameter list area and the part of the local 5776 // space variable where copies of aggregates which are passed by value are 5777 // stored. 5778 unsigned NumBytes = CCByValInfo.getNextStackOffset(); 5779 5780 // Calculate by how many bytes the stack has to be adjusted in case of tail 5781 // call optimization. 5782 int SPDiff = CalculateTailCallSPDiff(DAG, IsTailCall, NumBytes); 5783 5784 // Adjust the stack pointer for the new arguments... 5785 // These operations are automatically eliminated by the prolog/epilog pass 5786 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 5787 SDValue CallSeqStart = Chain; 5788 5789 // Load the return address and frame pointer so it can be moved somewhere else 5790 // later. 5791 SDValue LROp, FPOp; 5792 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl); 5793 5794 // Set up a copy of the stack pointer for use loading and storing any 5795 // arguments that may not fit in the registers available for argument 5796 // passing. 5797 SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32); 5798 5799 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 5800 SmallVector<TailCallArgumentInfo, 8> TailCallArguments; 5801 SmallVector<SDValue, 8> MemOpChains; 5802 5803 bool seenFloatArg = false; 5804 // Walk the register/memloc assignments, inserting copies/loads. 5805 // i - Tracks the index into the list of registers allocated for the call 5806 // RealArgIdx - Tracks the index into the list of actual function arguments 5807 // j - Tracks the index into the list of byval arguments 5808 for (unsigned i = 0, RealArgIdx = 0, j = 0, e = ArgLocs.size(); 5809 i != e; 5810 ++i, ++RealArgIdx) { 5811 CCValAssign &VA = ArgLocs[i]; 5812 SDValue Arg = OutVals[RealArgIdx]; 5813 ISD::ArgFlagsTy Flags = Outs[RealArgIdx].Flags; 5814 5815 if (Flags.isByVal()) { 5816 // Argument is an aggregate which is passed by value, thus we need to 5817 // create a copy of it in the local variable space of the current stack 5818 // frame (which is the stack frame of the caller) and pass the address of 5819 // this copy to the callee. 5820 assert((j < ByValArgLocs.size()) && "Index out of bounds!"); 5821 CCValAssign &ByValVA = ByValArgLocs[j++]; 5822 assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!"); 5823 5824 // Memory reserved in the local variable space of the callers stack frame. 5825 unsigned LocMemOffset = ByValVA.getLocMemOffset(); 5826 5827 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 5828 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()), 5829 StackPtr, PtrOff); 5830 5831 // Create a copy of the argument in the local area of the current 5832 // stack frame. 5833 SDValue MemcpyCall = 5834 CreateCopyOfByValArgument(Arg, PtrOff, 5835 CallSeqStart.getNode()->getOperand(0), 5836 Flags, DAG, dl); 5837 5838 // This must go outside the CALLSEQ_START..END. 5839 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, NumBytes, 0, 5840 SDLoc(MemcpyCall)); 5841 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(), 5842 NewCallSeqStart.getNode()); 5843 Chain = CallSeqStart = NewCallSeqStart; 5844 5845 // Pass the address of the aggregate copy on the stack either in a 5846 // physical register or in the parameter list area of the current stack 5847 // frame to the callee. 5848 Arg = PtrOff; 5849 } 5850 5851 // When useCRBits() is true, there can be i1 arguments. 5852 // It is because getRegisterType(MVT::i1) => MVT::i1, 5853 // and for other integer types getRegisterType() => MVT::i32. 5854 // Extend i1 and ensure callee will get i32. 5855 if (Arg.getValueType() == MVT::i1) 5856 Arg = DAG.getNode(Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, 5857 dl, MVT::i32, Arg); 5858 5859 if (VA.isRegLoc()) { 5860 seenFloatArg |= VA.getLocVT().isFloatingPoint(); 5861 // Put argument in a physical register. 5862 if (Subtarget.hasSPE() && Arg.getValueType() == MVT::f64) { 5863 bool IsLE = Subtarget.isLittleEndian(); 5864 SDValue SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg, 5865 DAG.getIntPtrConstant(IsLE ? 0 : 1, dl)); 5866 RegsToPass.push_back(std::make_pair(VA.getLocReg(), SVal.getValue(0))); 5867 SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg, 5868 DAG.getIntPtrConstant(IsLE ? 1 : 0, dl)); 5869 RegsToPass.push_back(std::make_pair(ArgLocs[++i].getLocReg(), 5870 SVal.getValue(0))); 5871 } else 5872 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 5873 } else { 5874 // Put argument in the parameter list area of the current stack frame. 5875 assert(VA.isMemLoc()); 5876 unsigned LocMemOffset = VA.getLocMemOffset(); 5877 5878 if (!IsTailCall) { 5879 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 5880 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()), 5881 StackPtr, PtrOff); 5882 5883 MemOpChains.push_back( 5884 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo())); 5885 } else { 5886 // Calculate and remember argument location. 5887 CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset, 5888 TailCallArguments); 5889 } 5890 } 5891 } 5892 5893 if (!MemOpChains.empty()) 5894 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 5895 5896 // Build a sequence of copy-to-reg nodes chained together with token chain 5897 // and flag operands which copy the outgoing args into the appropriate regs. 5898 SDValue InFlag; 5899 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 5900 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 5901 RegsToPass[i].second, InFlag); 5902 InFlag = Chain.getValue(1); 5903 } 5904 5905 // Set CR bit 6 to true if this is a vararg call with floating args passed in 5906 // registers. 5907 if (IsVarArg) { 5908 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue); 5909 SDValue Ops[] = { Chain, InFlag }; 5910 5911 Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET, 5912 dl, VTs, makeArrayRef(Ops, InFlag.getNode() ? 2 : 1)); 5913 5914 InFlag = Chain.getValue(1); 5915 } 5916 5917 if (IsTailCall) 5918 PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp, 5919 TailCallArguments); 5920 5921 return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart, 5922 Callee, SPDiff, NumBytes, Ins, InVals, CB); 5923 } 5924 5925 // Copy an argument into memory, being careful to do this outside the 5926 // call sequence for the call to which the argument belongs. 5927 SDValue PPCTargetLowering::createMemcpyOutsideCallSeq( 5928 SDValue Arg, SDValue PtrOff, SDValue CallSeqStart, ISD::ArgFlagsTy Flags, 5929 SelectionDAG &DAG, const SDLoc &dl) const { 5930 SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff, 5931 CallSeqStart.getNode()->getOperand(0), 5932 Flags, DAG, dl); 5933 // The MEMCPY must go outside the CALLSEQ_START..END. 5934 int64_t FrameSize = CallSeqStart.getConstantOperandVal(1); 5935 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, FrameSize, 0, 5936 SDLoc(MemcpyCall)); 5937 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(), 5938 NewCallSeqStart.getNode()); 5939 return NewCallSeqStart; 5940 } 5941 5942 SDValue PPCTargetLowering::LowerCall_64SVR4( 5943 SDValue Chain, SDValue Callee, CallFlags CFlags, 5944 const SmallVectorImpl<ISD::OutputArg> &Outs, 5945 const SmallVectorImpl<SDValue> &OutVals, 5946 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 5947 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 5948 const CallBase *CB) const { 5949 bool isELFv2ABI = Subtarget.isELFv2ABI(); 5950 bool isLittleEndian = Subtarget.isLittleEndian(); 5951 unsigned NumOps = Outs.size(); 5952 bool IsSibCall = false; 5953 bool IsFastCall = CFlags.CallConv == CallingConv::Fast; 5954 5955 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 5956 unsigned PtrByteSize = 8; 5957 5958 MachineFunction &MF = DAG.getMachineFunction(); 5959 5960 if (CFlags.IsTailCall && !getTargetMachine().Options.GuaranteedTailCallOpt) 5961 IsSibCall = true; 5962 5963 // Mark this function as potentially containing a function that contains a 5964 // tail call. As a consequence the frame pointer will be used for dynamicalloc 5965 // and restoring the callers stack pointer in this functions epilog. This is 5966 // done because by tail calling the called function might overwrite the value 5967 // in this function's (MF) stack pointer stack slot 0(SP). 5968 if (getTargetMachine().Options.GuaranteedTailCallOpt && IsFastCall) 5969 MF.getInfo<PPCFunctionInfo>()->setHasFastCall(); 5970 5971 assert(!(IsFastCall && CFlags.IsVarArg) && 5972 "fastcc not supported on varargs functions"); 5973 5974 // Count how many bytes are to be pushed on the stack, including the linkage 5975 // area, and parameter passing area. On ELFv1, the linkage area is 48 bytes 5976 // reserved space for [SP][CR][LR][2 x unused][TOC]; on ELFv2, the linkage 5977 // area is 32 bytes reserved space for [SP][CR][LR][TOC]. 5978 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 5979 unsigned NumBytes = LinkageSize; 5980 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 5981 unsigned &QFPR_idx = FPR_idx; 5982 5983 static const MCPhysReg GPR[] = { 5984 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 5985 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 5986 }; 5987 static const MCPhysReg VR[] = { 5988 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 5989 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 5990 }; 5991 5992 const unsigned NumGPRs = array_lengthof(GPR); 5993 const unsigned NumFPRs = useSoftFloat() ? 0 : 13; 5994 const unsigned NumVRs = array_lengthof(VR); 5995 const unsigned NumQFPRs = NumFPRs; 5996 5997 // On ELFv2, we can avoid allocating the parameter area if all the arguments 5998 // can be passed to the callee in registers. 5999 // For the fast calling convention, there is another check below. 6000 // Note: We should keep consistent with LowerFormalArguments_64SVR4() 6001 bool HasParameterArea = !isELFv2ABI || CFlags.IsVarArg || IsFastCall; 6002 if (!HasParameterArea) { 6003 unsigned ParamAreaSize = NumGPRs * PtrByteSize; 6004 unsigned AvailableFPRs = NumFPRs; 6005 unsigned AvailableVRs = NumVRs; 6006 unsigned NumBytesTmp = NumBytes; 6007 for (unsigned i = 0; i != NumOps; ++i) { 6008 if (Outs[i].Flags.isNest()) continue; 6009 if (CalculateStackSlotUsed(Outs[i].VT, Outs[i].ArgVT, Outs[i].Flags, 6010 PtrByteSize, LinkageSize, ParamAreaSize, 6011 NumBytesTmp, AvailableFPRs, AvailableVRs, 6012 Subtarget.hasQPX())) 6013 HasParameterArea = true; 6014 } 6015 } 6016 6017 // When using the fast calling convention, we don't provide backing for 6018 // arguments that will be in registers. 6019 unsigned NumGPRsUsed = 0, NumFPRsUsed = 0, NumVRsUsed = 0; 6020 6021 // Avoid allocating parameter area for fastcc functions if all the arguments 6022 // can be passed in the registers. 6023 if (IsFastCall) 6024 HasParameterArea = false; 6025 6026 // Add up all the space actually used. 6027 for (unsigned i = 0; i != NumOps; ++i) { 6028 ISD::ArgFlagsTy Flags = Outs[i].Flags; 6029 EVT ArgVT = Outs[i].VT; 6030 EVT OrigVT = Outs[i].ArgVT; 6031 6032 if (Flags.isNest()) 6033 continue; 6034 6035 if (IsFastCall) { 6036 if (Flags.isByVal()) { 6037 NumGPRsUsed += (Flags.getByValSize()+7)/8; 6038 if (NumGPRsUsed > NumGPRs) 6039 HasParameterArea = true; 6040 } else { 6041 switch (ArgVT.getSimpleVT().SimpleTy) { 6042 default: llvm_unreachable("Unexpected ValueType for argument!"); 6043 case MVT::i1: 6044 case MVT::i32: 6045 case MVT::i64: 6046 if (++NumGPRsUsed <= NumGPRs) 6047 continue; 6048 break; 6049 case MVT::v4i32: 6050 case MVT::v8i16: 6051 case MVT::v16i8: 6052 case MVT::v2f64: 6053 case MVT::v2i64: 6054 case MVT::v1i128: 6055 case MVT::f128: 6056 if (++NumVRsUsed <= NumVRs) 6057 continue; 6058 break; 6059 case MVT::v4f32: 6060 // When using QPX, this is handled like a FP register, otherwise, it 6061 // is an Altivec register. 6062 if (Subtarget.hasQPX()) { 6063 if (++NumFPRsUsed <= NumFPRs) 6064 continue; 6065 } else { 6066 if (++NumVRsUsed <= NumVRs) 6067 continue; 6068 } 6069 break; 6070 case MVT::f32: 6071 case MVT::f64: 6072 case MVT::v4f64: // QPX 6073 case MVT::v4i1: // QPX 6074 if (++NumFPRsUsed <= NumFPRs) 6075 continue; 6076 break; 6077 } 6078 HasParameterArea = true; 6079 } 6080 } 6081 6082 /* Respect alignment of argument on the stack. */ 6083 auto Alignement = 6084 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize); 6085 NumBytes = alignTo(NumBytes, Alignement); 6086 6087 NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize); 6088 if (Flags.isInConsecutiveRegsLast()) 6089 NumBytes = ((NumBytes + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 6090 } 6091 6092 unsigned NumBytesActuallyUsed = NumBytes; 6093 6094 // In the old ELFv1 ABI, 6095 // the prolog code of the callee may store up to 8 GPR argument registers to 6096 // the stack, allowing va_start to index over them in memory if its varargs. 6097 // Because we cannot tell if this is needed on the caller side, we have to 6098 // conservatively assume that it is needed. As such, make sure we have at 6099 // least enough stack space for the caller to store the 8 GPRs. 6100 // In the ELFv2 ABI, we allocate the parameter area iff a callee 6101 // really requires memory operands, e.g. a vararg function. 6102 if (HasParameterArea) 6103 NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize); 6104 else 6105 NumBytes = LinkageSize; 6106 6107 // Tail call needs the stack to be aligned. 6108 if (getTargetMachine().Options.GuaranteedTailCallOpt && IsFastCall) 6109 NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes); 6110 6111 int SPDiff = 0; 6112 6113 // Calculate by how many bytes the stack has to be adjusted in case of tail 6114 // call optimization. 6115 if (!IsSibCall) 6116 SPDiff = CalculateTailCallSPDiff(DAG, CFlags.IsTailCall, NumBytes); 6117 6118 // To protect arguments on the stack from being clobbered in a tail call, 6119 // force all the loads to happen before doing any other lowering. 6120 if (CFlags.IsTailCall) 6121 Chain = DAG.getStackArgumentTokenFactor(Chain); 6122 6123 // Adjust the stack pointer for the new arguments... 6124 // These operations are automatically eliminated by the prolog/epilog pass 6125 if (!IsSibCall) 6126 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 6127 SDValue CallSeqStart = Chain; 6128 6129 // Load the return address and frame pointer so it can be move somewhere else 6130 // later. 6131 SDValue LROp, FPOp; 6132 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl); 6133 6134 // Set up a copy of the stack pointer for use loading and storing any 6135 // arguments that may not fit in the registers available for argument 6136 // passing. 6137 SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64); 6138 6139 // Figure out which arguments are going to go in registers, and which in 6140 // memory. Also, if this is a vararg function, floating point operations 6141 // must be stored to our stack, and loaded into integer regs as well, if 6142 // any integer regs are available for argument passing. 6143 unsigned ArgOffset = LinkageSize; 6144 6145 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 6146 SmallVector<TailCallArgumentInfo, 8> TailCallArguments; 6147 6148 SmallVector<SDValue, 8> MemOpChains; 6149 for (unsigned i = 0; i != NumOps; ++i) { 6150 SDValue Arg = OutVals[i]; 6151 ISD::ArgFlagsTy Flags = Outs[i].Flags; 6152 EVT ArgVT = Outs[i].VT; 6153 EVT OrigVT = Outs[i].ArgVT; 6154 6155 // PtrOff will be used to store the current argument to the stack if a 6156 // register cannot be found for it. 6157 SDValue PtrOff; 6158 6159 // We re-align the argument offset for each argument, except when using the 6160 // fast calling convention, when we need to make sure we do that only when 6161 // we'll actually use a stack slot. 6162 auto ComputePtrOff = [&]() { 6163 /* Respect alignment of argument on the stack. */ 6164 auto Alignment = 6165 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize); 6166 ArgOffset = alignTo(ArgOffset, Alignment); 6167 6168 PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType()); 6169 6170 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 6171 }; 6172 6173 if (!IsFastCall) { 6174 ComputePtrOff(); 6175 6176 /* Compute GPR index associated with argument offset. */ 6177 GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize; 6178 GPR_idx = std::min(GPR_idx, NumGPRs); 6179 } 6180 6181 // Promote integers to 64-bit values. 6182 if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) { 6183 // FIXME: Should this use ANY_EXTEND if neither sext nor zext? 6184 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 6185 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg); 6186 } 6187 6188 // FIXME memcpy is used way more than necessary. Correctness first. 6189 // Note: "by value" is code for passing a structure by value, not 6190 // basic types. 6191 if (Flags.isByVal()) { 6192 // Note: Size includes alignment padding, so 6193 // struct x { short a; char b; } 6194 // will have Size = 4. With #pragma pack(1), it will have Size = 3. 6195 // These are the proper values we need for right-justifying the 6196 // aggregate in a parameter register. 6197 unsigned Size = Flags.getByValSize(); 6198 6199 // An empty aggregate parameter takes up no storage and no 6200 // registers. 6201 if (Size == 0) 6202 continue; 6203 6204 if (IsFastCall) 6205 ComputePtrOff(); 6206 6207 // All aggregates smaller than 8 bytes must be passed right-justified. 6208 if (Size==1 || Size==2 || Size==4) { 6209 EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32); 6210 if (GPR_idx != NumGPRs) { 6211 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg, 6212 MachinePointerInfo(), VT); 6213 MemOpChains.push_back(Load.getValue(1)); 6214 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6215 6216 ArgOffset += PtrByteSize; 6217 continue; 6218 } 6219 } 6220 6221 if (GPR_idx == NumGPRs && Size < 8) { 6222 SDValue AddPtr = PtrOff; 6223 if (!isLittleEndian) { 6224 SDValue Const = DAG.getConstant(PtrByteSize - Size, dl, 6225 PtrOff.getValueType()); 6226 AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const); 6227 } 6228 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr, 6229 CallSeqStart, 6230 Flags, DAG, dl); 6231 ArgOffset += PtrByteSize; 6232 continue; 6233 } 6234 // Copy entire object into memory. There are cases where gcc-generated 6235 // code assumes it is there, even if it could be put entirely into 6236 // registers. (This is not what the doc says.) 6237 6238 // FIXME: The above statement is likely due to a misunderstanding of the 6239 // documents. All arguments must be copied into the parameter area BY 6240 // THE CALLEE in the event that the callee takes the address of any 6241 // formal argument. That has not yet been implemented. However, it is 6242 // reasonable to use the stack area as a staging area for the register 6243 // load. 6244 6245 // Skip this for small aggregates, as we will use the same slot for a 6246 // right-justified copy, below. 6247 if (Size >= 8) 6248 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff, 6249 CallSeqStart, 6250 Flags, DAG, dl); 6251 6252 // When a register is available, pass a small aggregate right-justified. 6253 if (Size < 8 && GPR_idx != NumGPRs) { 6254 // The easiest way to get this right-justified in a register 6255 // is to copy the structure into the rightmost portion of a 6256 // local variable slot, then load the whole slot into the 6257 // register. 6258 // FIXME: The memcpy seems to produce pretty awful code for 6259 // small aggregates, particularly for packed ones. 6260 // FIXME: It would be preferable to use the slot in the 6261 // parameter save area instead of a new local variable. 6262 SDValue AddPtr = PtrOff; 6263 if (!isLittleEndian) { 6264 SDValue Const = DAG.getConstant(8 - Size, dl, PtrOff.getValueType()); 6265 AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const); 6266 } 6267 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr, 6268 CallSeqStart, 6269 Flags, DAG, dl); 6270 6271 // Load the slot into the register. 6272 SDValue Load = 6273 DAG.getLoad(PtrVT, dl, Chain, PtrOff, MachinePointerInfo()); 6274 MemOpChains.push_back(Load.getValue(1)); 6275 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6276 6277 // Done with this argument. 6278 ArgOffset += PtrByteSize; 6279 continue; 6280 } 6281 6282 // For aggregates larger than PtrByteSize, copy the pieces of the 6283 // object that fit into registers from the parameter save area. 6284 for (unsigned j=0; j<Size; j+=PtrByteSize) { 6285 SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType()); 6286 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const); 6287 if (GPR_idx != NumGPRs) { 6288 SDValue Load = 6289 DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo()); 6290 MemOpChains.push_back(Load.getValue(1)); 6291 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6292 ArgOffset += PtrByteSize; 6293 } else { 6294 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize; 6295 break; 6296 } 6297 } 6298 continue; 6299 } 6300 6301 switch (Arg.getSimpleValueType().SimpleTy) { 6302 default: llvm_unreachable("Unexpected ValueType for argument!"); 6303 case MVT::i1: 6304 case MVT::i32: 6305 case MVT::i64: 6306 if (Flags.isNest()) { 6307 // The 'nest' parameter, if any, is passed in R11. 6308 RegsToPass.push_back(std::make_pair(PPC::X11, Arg)); 6309 break; 6310 } 6311 6312 // These can be scalar arguments or elements of an integer array type 6313 // passed directly. Clang may use those instead of "byval" aggregate 6314 // types to avoid forcing arguments to memory unnecessarily. 6315 if (GPR_idx != NumGPRs) { 6316 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg)); 6317 } else { 6318 if (IsFastCall) 6319 ComputePtrOff(); 6320 6321 assert(HasParameterArea && 6322 "Parameter area must exist to pass an argument in memory."); 6323 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6324 true, CFlags.IsTailCall, false, MemOpChains, 6325 TailCallArguments, dl); 6326 if (IsFastCall) 6327 ArgOffset += PtrByteSize; 6328 } 6329 if (!IsFastCall) 6330 ArgOffset += PtrByteSize; 6331 break; 6332 case MVT::f32: 6333 case MVT::f64: { 6334 // These can be scalar arguments or elements of a float array type 6335 // passed directly. The latter are used to implement ELFv2 homogenous 6336 // float aggregates. 6337 6338 // Named arguments go into FPRs first, and once they overflow, the 6339 // remaining arguments go into GPRs and then the parameter save area. 6340 // Unnamed arguments for vararg functions always go to GPRs and 6341 // then the parameter save area. For now, put all arguments to vararg 6342 // routines always in both locations (FPR *and* GPR or stack slot). 6343 bool NeedGPROrStack = CFlags.IsVarArg || FPR_idx == NumFPRs; 6344 bool NeededLoad = false; 6345 6346 // First load the argument into the next available FPR. 6347 if (FPR_idx != NumFPRs) 6348 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg)); 6349 6350 // Next, load the argument into GPR or stack slot if needed. 6351 if (!NeedGPROrStack) 6352 ; 6353 else if (GPR_idx != NumGPRs && !IsFastCall) { 6354 // FIXME: We may want to re-enable this for CallingConv::Fast on the P8 6355 // once we support fp <-> gpr moves. 6356 6357 // In the non-vararg case, this can only ever happen in the 6358 // presence of f32 array types, since otherwise we never run 6359 // out of FPRs before running out of GPRs. 6360 SDValue ArgVal; 6361 6362 // Double values are always passed in a single GPR. 6363 if (Arg.getValueType() != MVT::f32) { 6364 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg); 6365 6366 // Non-array float values are extended and passed in a GPR. 6367 } else if (!Flags.isInConsecutiveRegs()) { 6368 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg); 6369 ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal); 6370 6371 // If we have an array of floats, we collect every odd element 6372 // together with its predecessor into one GPR. 6373 } else if (ArgOffset % PtrByteSize != 0) { 6374 SDValue Lo, Hi; 6375 Lo = DAG.getNode(ISD::BITCAST, dl, MVT::i32, OutVals[i - 1]); 6376 Hi = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg); 6377 if (!isLittleEndian) 6378 std::swap(Lo, Hi); 6379 ArgVal = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi); 6380 6381 // The final element, if even, goes into the first half of a GPR. 6382 } else if (Flags.isInConsecutiveRegsLast()) { 6383 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg); 6384 ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal); 6385 if (!isLittleEndian) 6386 ArgVal = DAG.getNode(ISD::SHL, dl, MVT::i64, ArgVal, 6387 DAG.getConstant(32, dl, MVT::i32)); 6388 6389 // Non-final even elements are skipped; they will be handled 6390 // together the with subsequent argument on the next go-around. 6391 } else 6392 ArgVal = SDValue(); 6393 6394 if (ArgVal.getNode()) 6395 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], ArgVal)); 6396 } else { 6397 if (IsFastCall) 6398 ComputePtrOff(); 6399 6400 // Single-precision floating-point values are mapped to the 6401 // second (rightmost) word of the stack doubleword. 6402 if (Arg.getValueType() == MVT::f32 && 6403 !isLittleEndian && !Flags.isInConsecutiveRegs()) { 6404 SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType()); 6405 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour); 6406 } 6407 6408 assert(HasParameterArea && 6409 "Parameter area must exist to pass an argument in memory."); 6410 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6411 true, CFlags.IsTailCall, false, MemOpChains, 6412 TailCallArguments, dl); 6413 6414 NeededLoad = true; 6415 } 6416 // When passing an array of floats, the array occupies consecutive 6417 // space in the argument area; only round up to the next doubleword 6418 // at the end of the array. Otherwise, each float takes 8 bytes. 6419 if (!IsFastCall || NeededLoad) { 6420 ArgOffset += (Arg.getValueType() == MVT::f32 && 6421 Flags.isInConsecutiveRegs()) ? 4 : 8; 6422 if (Flags.isInConsecutiveRegsLast()) 6423 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 6424 } 6425 break; 6426 } 6427 case MVT::v4f32: 6428 case MVT::v4i32: 6429 case MVT::v8i16: 6430 case MVT::v16i8: 6431 case MVT::v2f64: 6432 case MVT::v2i64: 6433 case MVT::v1i128: 6434 case MVT::f128: 6435 if (!Subtarget.hasQPX()) { 6436 // These can be scalar arguments or elements of a vector array type 6437 // passed directly. The latter are used to implement ELFv2 homogenous 6438 // vector aggregates. 6439 6440 // For a varargs call, named arguments go into VRs or on the stack as 6441 // usual; unnamed arguments always go to the stack or the corresponding 6442 // GPRs when within range. For now, we always put the value in both 6443 // locations (or even all three). 6444 if (CFlags.IsVarArg) { 6445 assert(HasParameterArea && 6446 "Parameter area must exist if we have a varargs call."); 6447 // We could elide this store in the case where the object fits 6448 // entirely in R registers. Maybe later. 6449 SDValue Store = 6450 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 6451 MemOpChains.push_back(Store); 6452 if (VR_idx != NumVRs) { 6453 SDValue Load = 6454 DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo()); 6455 MemOpChains.push_back(Load.getValue(1)); 6456 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load)); 6457 } 6458 ArgOffset += 16; 6459 for (unsigned i=0; i<16; i+=PtrByteSize) { 6460 if (GPR_idx == NumGPRs) 6461 break; 6462 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, 6463 DAG.getConstant(i, dl, PtrVT)); 6464 SDValue Load = 6465 DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo()); 6466 MemOpChains.push_back(Load.getValue(1)); 6467 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6468 } 6469 break; 6470 } 6471 6472 // Non-varargs Altivec params go into VRs or on the stack. 6473 if (VR_idx != NumVRs) { 6474 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg)); 6475 } else { 6476 if (IsFastCall) 6477 ComputePtrOff(); 6478 6479 assert(HasParameterArea && 6480 "Parameter area must exist to pass an argument in memory."); 6481 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6482 true, CFlags.IsTailCall, true, MemOpChains, 6483 TailCallArguments, dl); 6484 if (IsFastCall) 6485 ArgOffset += 16; 6486 } 6487 6488 if (!IsFastCall) 6489 ArgOffset += 16; 6490 break; 6491 } // not QPX 6492 6493 assert(Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32 && 6494 "Invalid QPX parameter type"); 6495 6496 LLVM_FALLTHROUGH; 6497 case MVT::v4f64: 6498 case MVT::v4i1: { 6499 bool IsF32 = Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32; 6500 if (CFlags.IsVarArg) { 6501 assert(HasParameterArea && 6502 "Parameter area must exist if we have a varargs call."); 6503 // We could elide this store in the case where the object fits 6504 // entirely in R registers. Maybe later. 6505 SDValue Store = 6506 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 6507 MemOpChains.push_back(Store); 6508 if (QFPR_idx != NumQFPRs) { 6509 SDValue Load = DAG.getLoad(IsF32 ? MVT::v4f32 : MVT::v4f64, dl, Store, 6510 PtrOff, MachinePointerInfo()); 6511 MemOpChains.push_back(Load.getValue(1)); 6512 RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Load)); 6513 } 6514 ArgOffset += (IsF32 ? 16 : 32); 6515 for (unsigned i = 0; i < (IsF32 ? 16U : 32U); i += PtrByteSize) { 6516 if (GPR_idx == NumGPRs) 6517 break; 6518 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, 6519 DAG.getConstant(i, dl, PtrVT)); 6520 SDValue Load = 6521 DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo()); 6522 MemOpChains.push_back(Load.getValue(1)); 6523 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6524 } 6525 break; 6526 } 6527 6528 // Non-varargs QPX params go into registers or on the stack. 6529 if (QFPR_idx != NumQFPRs) { 6530 RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Arg)); 6531 } else { 6532 if (IsFastCall) 6533 ComputePtrOff(); 6534 6535 assert(HasParameterArea && 6536 "Parameter area must exist to pass an argument in memory."); 6537 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6538 true, CFlags.IsTailCall, true, MemOpChains, 6539 TailCallArguments, dl); 6540 if (IsFastCall) 6541 ArgOffset += (IsF32 ? 16 : 32); 6542 } 6543 6544 if (!IsFastCall) 6545 ArgOffset += (IsF32 ? 16 : 32); 6546 break; 6547 } 6548 } 6549 } 6550 6551 assert((!HasParameterArea || NumBytesActuallyUsed == ArgOffset) && 6552 "mismatch in size of parameter area"); 6553 (void)NumBytesActuallyUsed; 6554 6555 if (!MemOpChains.empty()) 6556 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 6557 6558 // Check if this is an indirect call (MTCTR/BCTRL). 6559 // See prepareDescriptorIndirectCall and buildCallOperands for more 6560 // information about calls through function pointers in the 64-bit SVR4 ABI. 6561 if (CFlags.IsIndirect) { 6562 // For 64-bit ELFv2 ABI with PCRel, do not save the TOC of the 6563 // caller in the TOC save area. 6564 if (isTOCSaveRestoreRequired(Subtarget)) { 6565 assert(!CFlags.IsTailCall && "Indirect tails calls not supported"); 6566 // Load r2 into a virtual register and store it to the TOC save area. 6567 setUsesTOCBasePtr(DAG); 6568 SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64); 6569 // TOC save area offset. 6570 unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset(); 6571 SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl); 6572 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 6573 Chain = DAG.getStore(Val.getValue(1), dl, Val, AddPtr, 6574 MachinePointerInfo::getStack( 6575 DAG.getMachineFunction(), TOCSaveOffset)); 6576 } 6577 // In the ELFv2 ABI, R12 must contain the address of an indirect callee. 6578 // This does not mean the MTCTR instruction must use R12; it's easier 6579 // to model this as an extra parameter, so do that. 6580 if (isELFv2ABI && !CFlags.IsPatchPoint) 6581 RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee)); 6582 } 6583 6584 // Build a sequence of copy-to-reg nodes chained together with token chain 6585 // and flag operands which copy the outgoing args into the appropriate regs. 6586 SDValue InFlag; 6587 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 6588 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 6589 RegsToPass[i].second, InFlag); 6590 InFlag = Chain.getValue(1); 6591 } 6592 6593 if (CFlags.IsTailCall && !IsSibCall) 6594 PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp, 6595 TailCallArguments); 6596 6597 return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart, 6598 Callee, SPDiff, NumBytes, Ins, InVals, CB); 6599 } 6600 6601 SDValue PPCTargetLowering::LowerCall_Darwin( 6602 SDValue Chain, SDValue Callee, CallFlags CFlags, 6603 const SmallVectorImpl<ISD::OutputArg> &Outs, 6604 const SmallVectorImpl<SDValue> &OutVals, 6605 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 6606 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 6607 const CallBase *CB) const { 6608 unsigned NumOps = Outs.size(); 6609 6610 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 6611 bool isPPC64 = PtrVT == MVT::i64; 6612 unsigned PtrByteSize = isPPC64 ? 8 : 4; 6613 6614 MachineFunction &MF = DAG.getMachineFunction(); 6615 6616 // Mark this function as potentially containing a function that contains a 6617 // tail call. As a consequence the frame pointer will be used for dynamicalloc 6618 // and restoring the callers stack pointer in this functions epilog. This is 6619 // done because by tail calling the called function might overwrite the value 6620 // in this function's (MF) stack pointer stack slot 0(SP). 6621 if (getTargetMachine().Options.GuaranteedTailCallOpt && 6622 CFlags.CallConv == CallingConv::Fast) 6623 MF.getInfo<PPCFunctionInfo>()->setHasFastCall(); 6624 6625 // Count how many bytes are to be pushed on the stack, including the linkage 6626 // area, and parameter passing area. We start with 24/48 bytes, which is 6627 // prereserved space for [SP][CR][LR][3 x unused]. 6628 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 6629 unsigned NumBytes = LinkageSize; 6630 6631 // Add up all the space actually used. 6632 // In 32-bit non-varargs calls, Altivec parameters all go at the end; usually 6633 // they all go in registers, but we must reserve stack space for them for 6634 // possible use by the caller. In varargs or 64-bit calls, parameters are 6635 // assigned stack space in order, with padding so Altivec parameters are 6636 // 16-byte aligned. 6637 unsigned nAltivecParamsAtEnd = 0; 6638 for (unsigned i = 0; i != NumOps; ++i) { 6639 ISD::ArgFlagsTy Flags = Outs[i].Flags; 6640 EVT ArgVT = Outs[i].VT; 6641 // Varargs Altivec parameters are padded to a 16 byte boundary. 6642 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 || 6643 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 || 6644 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64) { 6645 if (!CFlags.IsVarArg && !isPPC64) { 6646 // Non-varargs Altivec parameters go after all the non-Altivec 6647 // parameters; handle those later so we know how much padding we need. 6648 nAltivecParamsAtEnd++; 6649 continue; 6650 } 6651 // Varargs and 64-bit Altivec parameters are padded to 16 byte boundary. 6652 NumBytes = ((NumBytes+15)/16)*16; 6653 } 6654 NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize); 6655 } 6656 6657 // Allow for Altivec parameters at the end, if needed. 6658 if (nAltivecParamsAtEnd) { 6659 NumBytes = ((NumBytes+15)/16)*16; 6660 NumBytes += 16*nAltivecParamsAtEnd; 6661 } 6662 6663 // The prolog code of the callee may store up to 8 GPR argument registers to 6664 // the stack, allowing va_start to index over them in memory if its varargs. 6665 // Because we cannot tell if this is needed on the caller side, we have to 6666 // conservatively assume that it is needed. As such, make sure we have at 6667 // least enough stack space for the caller to store the 8 GPRs. 6668 NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize); 6669 6670 // Tail call needs the stack to be aligned. 6671 if (getTargetMachine().Options.GuaranteedTailCallOpt && 6672 CFlags.CallConv == CallingConv::Fast) 6673 NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes); 6674 6675 // Calculate by how many bytes the stack has to be adjusted in case of tail 6676 // call optimization. 6677 int SPDiff = CalculateTailCallSPDiff(DAG, CFlags.IsTailCall, NumBytes); 6678 6679 // To protect arguments on the stack from being clobbered in a tail call, 6680 // force all the loads to happen before doing any other lowering. 6681 if (CFlags.IsTailCall) 6682 Chain = DAG.getStackArgumentTokenFactor(Chain); 6683 6684 // Adjust the stack pointer for the new arguments... 6685 // These operations are automatically eliminated by the prolog/epilog pass 6686 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 6687 SDValue CallSeqStart = Chain; 6688 6689 // Load the return address and frame pointer so it can be move somewhere else 6690 // later. 6691 SDValue LROp, FPOp; 6692 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl); 6693 6694 // Set up a copy of the stack pointer for use loading and storing any 6695 // arguments that may not fit in the registers available for argument 6696 // passing. 6697 SDValue StackPtr; 6698 if (isPPC64) 6699 StackPtr = DAG.getRegister(PPC::X1, MVT::i64); 6700 else 6701 StackPtr = DAG.getRegister(PPC::R1, MVT::i32); 6702 6703 // Figure out which arguments are going to go in registers, and which in 6704 // memory. Also, if this is a vararg function, floating point operations 6705 // must be stored to our stack, and loaded into integer regs as well, if 6706 // any integer regs are available for argument passing. 6707 unsigned ArgOffset = LinkageSize; 6708 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 6709 6710 static const MCPhysReg GPR_32[] = { // 32-bit registers. 6711 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 6712 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 6713 }; 6714 static const MCPhysReg GPR_64[] = { // 64-bit registers. 6715 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 6716 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 6717 }; 6718 static const MCPhysReg VR[] = { 6719 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 6720 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 6721 }; 6722 const unsigned NumGPRs = array_lengthof(GPR_32); 6723 const unsigned NumFPRs = 13; 6724 const unsigned NumVRs = array_lengthof(VR); 6725 6726 const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32; 6727 6728 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 6729 SmallVector<TailCallArgumentInfo, 8> TailCallArguments; 6730 6731 SmallVector<SDValue, 8> MemOpChains; 6732 for (unsigned i = 0; i != NumOps; ++i) { 6733 SDValue Arg = OutVals[i]; 6734 ISD::ArgFlagsTy Flags = Outs[i].Flags; 6735 6736 // PtrOff will be used to store the current argument to the stack if a 6737 // register cannot be found for it. 6738 SDValue PtrOff; 6739 6740 PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType()); 6741 6742 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 6743 6744 // On PPC64, promote integers to 64-bit values. 6745 if (isPPC64 && Arg.getValueType() == MVT::i32) { 6746 // FIXME: Should this use ANY_EXTEND if neither sext nor zext? 6747 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 6748 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg); 6749 } 6750 6751 // FIXME memcpy is used way more than necessary. Correctness first. 6752 // Note: "by value" is code for passing a structure by value, not 6753 // basic types. 6754 if (Flags.isByVal()) { 6755 unsigned Size = Flags.getByValSize(); 6756 // Very small objects are passed right-justified. Everything else is 6757 // passed left-justified. 6758 if (Size==1 || Size==2) { 6759 EVT VT = (Size==1) ? MVT::i8 : MVT::i16; 6760 if (GPR_idx != NumGPRs) { 6761 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg, 6762 MachinePointerInfo(), VT); 6763 MemOpChains.push_back(Load.getValue(1)); 6764 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6765 6766 ArgOffset += PtrByteSize; 6767 } else { 6768 SDValue Const = DAG.getConstant(PtrByteSize - Size, dl, 6769 PtrOff.getValueType()); 6770 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const); 6771 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr, 6772 CallSeqStart, 6773 Flags, DAG, dl); 6774 ArgOffset += PtrByteSize; 6775 } 6776 continue; 6777 } 6778 // Copy entire object into memory. There are cases where gcc-generated 6779 // code assumes it is there, even if it could be put entirely into 6780 // registers. (This is not what the doc says.) 6781 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff, 6782 CallSeqStart, 6783 Flags, DAG, dl); 6784 6785 // For small aggregates (Darwin only) and aggregates >= PtrByteSize, 6786 // copy the pieces of the object that fit into registers from the 6787 // parameter save area. 6788 for (unsigned j=0; j<Size; j+=PtrByteSize) { 6789 SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType()); 6790 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const); 6791 if (GPR_idx != NumGPRs) { 6792 SDValue Load = 6793 DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo()); 6794 MemOpChains.push_back(Load.getValue(1)); 6795 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6796 ArgOffset += PtrByteSize; 6797 } else { 6798 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize; 6799 break; 6800 } 6801 } 6802 continue; 6803 } 6804 6805 switch (Arg.getSimpleValueType().SimpleTy) { 6806 default: llvm_unreachable("Unexpected ValueType for argument!"); 6807 case MVT::i1: 6808 case MVT::i32: 6809 case MVT::i64: 6810 if (GPR_idx != NumGPRs) { 6811 if (Arg.getValueType() == MVT::i1) 6812 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, PtrVT, Arg); 6813 6814 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg)); 6815 } else { 6816 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6817 isPPC64, CFlags.IsTailCall, false, MemOpChains, 6818 TailCallArguments, dl); 6819 } 6820 ArgOffset += PtrByteSize; 6821 break; 6822 case MVT::f32: 6823 case MVT::f64: 6824 if (FPR_idx != NumFPRs) { 6825 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg)); 6826 6827 if (CFlags.IsVarArg) { 6828 SDValue Store = 6829 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 6830 MemOpChains.push_back(Store); 6831 6832 // Float varargs are always shadowed in available integer registers 6833 if (GPR_idx != NumGPRs) { 6834 SDValue Load = 6835 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo()); 6836 MemOpChains.push_back(Load.getValue(1)); 6837 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6838 } 6839 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && !isPPC64){ 6840 SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType()); 6841 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour); 6842 SDValue Load = 6843 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo()); 6844 MemOpChains.push_back(Load.getValue(1)); 6845 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6846 } 6847 } else { 6848 // If we have any FPRs remaining, we may also have GPRs remaining. 6849 // Args passed in FPRs consume either 1 (f32) or 2 (f64) available 6850 // GPRs. 6851 if (GPR_idx != NumGPRs) 6852 ++GPR_idx; 6853 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && 6854 !isPPC64) // PPC64 has 64-bit GPR's obviously :) 6855 ++GPR_idx; 6856 } 6857 } else 6858 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6859 isPPC64, CFlags.IsTailCall, false, MemOpChains, 6860 TailCallArguments, dl); 6861 if (isPPC64) 6862 ArgOffset += 8; 6863 else 6864 ArgOffset += Arg.getValueType() == MVT::f32 ? 4 : 8; 6865 break; 6866 case MVT::v4f32: 6867 case MVT::v4i32: 6868 case MVT::v8i16: 6869 case MVT::v16i8: 6870 if (CFlags.IsVarArg) { 6871 // These go aligned on the stack, or in the corresponding R registers 6872 // when within range. The Darwin PPC ABI doc claims they also go in 6873 // V registers; in fact gcc does this only for arguments that are 6874 // prototyped, not for those that match the ... We do it for all 6875 // arguments, seems to work. 6876 while (ArgOffset % 16 !=0) { 6877 ArgOffset += PtrByteSize; 6878 if (GPR_idx != NumGPRs) 6879 GPR_idx++; 6880 } 6881 // We could elide this store in the case where the object fits 6882 // entirely in R registers. Maybe later. 6883 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, 6884 DAG.getConstant(ArgOffset, dl, PtrVT)); 6885 SDValue Store = 6886 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 6887 MemOpChains.push_back(Store); 6888 if (VR_idx != NumVRs) { 6889 SDValue Load = 6890 DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo()); 6891 MemOpChains.push_back(Load.getValue(1)); 6892 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load)); 6893 } 6894 ArgOffset += 16; 6895 for (unsigned i=0; i<16; i+=PtrByteSize) { 6896 if (GPR_idx == NumGPRs) 6897 break; 6898 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, 6899 DAG.getConstant(i, dl, PtrVT)); 6900 SDValue Load = 6901 DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo()); 6902 MemOpChains.push_back(Load.getValue(1)); 6903 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6904 } 6905 break; 6906 } 6907 6908 // Non-varargs Altivec params generally go in registers, but have 6909 // stack space allocated at the end. 6910 if (VR_idx != NumVRs) { 6911 // Doesn't have GPR space allocated. 6912 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg)); 6913 } else if (nAltivecParamsAtEnd==0) { 6914 // We are emitting Altivec params in order. 6915 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6916 isPPC64, CFlags.IsTailCall, true, MemOpChains, 6917 TailCallArguments, dl); 6918 ArgOffset += 16; 6919 } 6920 break; 6921 } 6922 } 6923 // If all Altivec parameters fit in registers, as they usually do, 6924 // they get stack space following the non-Altivec parameters. We 6925 // don't track this here because nobody below needs it. 6926 // If there are more Altivec parameters than fit in registers emit 6927 // the stores here. 6928 if (!CFlags.IsVarArg && nAltivecParamsAtEnd > NumVRs) { 6929 unsigned j = 0; 6930 // Offset is aligned; skip 1st 12 params which go in V registers. 6931 ArgOffset = ((ArgOffset+15)/16)*16; 6932 ArgOffset += 12*16; 6933 for (unsigned i = 0; i != NumOps; ++i) { 6934 SDValue Arg = OutVals[i]; 6935 EVT ArgType = Outs[i].VT; 6936 if (ArgType==MVT::v4f32 || ArgType==MVT::v4i32 || 6937 ArgType==MVT::v8i16 || ArgType==MVT::v16i8) { 6938 if (++j > NumVRs) { 6939 SDValue PtrOff; 6940 // We are emitting Altivec params in order. 6941 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6942 isPPC64, CFlags.IsTailCall, true, MemOpChains, 6943 TailCallArguments, dl); 6944 ArgOffset += 16; 6945 } 6946 } 6947 } 6948 } 6949 6950 if (!MemOpChains.empty()) 6951 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 6952 6953 // On Darwin, R12 must contain the address of an indirect callee. This does 6954 // not mean the MTCTR instruction must use R12; it's easier to model this as 6955 // an extra parameter, so do that. 6956 if (CFlags.IsIndirect) { 6957 assert(!CFlags.IsTailCall && "Indirect tail-calls not supported."); 6958 RegsToPass.push_back(std::make_pair((unsigned)(isPPC64 ? PPC::X12 : 6959 PPC::R12), Callee)); 6960 } 6961 6962 // Build a sequence of copy-to-reg nodes chained together with token chain 6963 // and flag operands which copy the outgoing args into the appropriate regs. 6964 SDValue InFlag; 6965 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 6966 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 6967 RegsToPass[i].second, InFlag); 6968 InFlag = Chain.getValue(1); 6969 } 6970 6971 if (CFlags.IsTailCall) 6972 PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp, 6973 TailCallArguments); 6974 6975 return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart, 6976 Callee, SPDiff, NumBytes, Ins, InVals, CB); 6977 } 6978 6979 static bool CC_AIX(unsigned ValNo, MVT ValVT, MVT LocVT, 6980 CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags, 6981 CCState &State) { 6982 6983 const PPCSubtarget &Subtarget = static_cast<const PPCSubtarget &>( 6984 State.getMachineFunction().getSubtarget()); 6985 const bool IsPPC64 = Subtarget.isPPC64(); 6986 const unsigned PtrByteSize = IsPPC64 ? 8 : 4; 6987 const MVT RegVT = IsPPC64 ? MVT::i64 : MVT::i32; 6988 6989 assert((!ValVT.isInteger() || 6990 (ValVT.getSizeInBits() <= RegVT.getSizeInBits())) && 6991 "Integer argument exceeds register size: should have been legalized"); 6992 6993 if (ValVT == MVT::f128) 6994 report_fatal_error("f128 is unimplemented on AIX."); 6995 6996 if (ArgFlags.isNest()) 6997 report_fatal_error("Nest arguments are unimplemented."); 6998 6999 if (ValVT.isVector() || LocVT.isVector()) 7000 report_fatal_error("Vector arguments are unimplemented on AIX."); 7001 7002 static const MCPhysReg GPR_32[] = {// 32-bit registers. 7003 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 7004 PPC::R7, PPC::R8, PPC::R9, PPC::R10}; 7005 static const MCPhysReg GPR_64[] = {// 64-bit registers. 7006 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 7007 PPC::X7, PPC::X8, PPC::X9, PPC::X10}; 7008 7009 if (ArgFlags.isByVal()) { 7010 if (ArgFlags.getNonZeroByValAlign() > PtrByteSize) 7011 report_fatal_error("Pass-by-value arguments with alignment greater than " 7012 "register width are not supported."); 7013 7014 const unsigned ByValSize = ArgFlags.getByValSize(); 7015 7016 // An empty aggregate parameter takes up no storage and no registers, 7017 // but needs a MemLoc for a stack slot for the formal arguments side. 7018 if (ByValSize == 0) { 7019 State.addLoc(CCValAssign::getMem(ValNo, MVT::INVALID_SIMPLE_VALUE_TYPE, 7020 State.getNextStackOffset(), RegVT, 7021 LocInfo)); 7022 return false; 7023 } 7024 7025 const unsigned StackSize = alignTo(ByValSize, PtrByteSize); 7026 unsigned Offset = State.AllocateStack(StackSize, PtrByteSize); 7027 for (const unsigned E = Offset + StackSize; Offset < E; 7028 Offset += PtrByteSize) { 7029 if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32)) 7030 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, RegVT, LocInfo)); 7031 else { 7032 State.addLoc(CCValAssign::getMem(ValNo, MVT::INVALID_SIMPLE_VALUE_TYPE, 7033 Offset, MVT::INVALID_SIMPLE_VALUE_TYPE, 7034 LocInfo)); 7035 break; 7036 } 7037 } 7038 return false; 7039 } 7040 7041 // Arguments always reserve parameter save area. 7042 switch (ValVT.SimpleTy) { 7043 default: 7044 report_fatal_error("Unhandled value type for argument."); 7045 case MVT::i64: 7046 // i64 arguments should have been split to i32 for PPC32. 7047 assert(IsPPC64 && "PPC32 should have split i64 values."); 7048 LLVM_FALLTHROUGH; 7049 case MVT::i1: 7050 case MVT::i32: { 7051 const unsigned Offset = State.AllocateStack(PtrByteSize, PtrByteSize); 7052 // AIX integer arguments are always passed in register width. 7053 if (ValVT.getSizeInBits() < RegVT.getSizeInBits()) 7054 LocInfo = ArgFlags.isSExt() ? CCValAssign::LocInfo::SExt 7055 : CCValAssign::LocInfo::ZExt; 7056 if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32)) 7057 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, RegVT, LocInfo)); 7058 else 7059 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, RegVT, LocInfo)); 7060 7061 return false; 7062 } 7063 case MVT::f32: 7064 case MVT::f64: { 7065 // Parameter save area (PSA) is reserved even if the float passes in fpr. 7066 const unsigned StoreSize = LocVT.getStoreSize(); 7067 // Floats are always 4-byte aligned in the PSA on AIX. 7068 // This includes f64 in 64-bit mode for ABI compatibility. 7069 const unsigned Offset = State.AllocateStack(IsPPC64 ? 8 : StoreSize, 4); 7070 unsigned FReg = State.AllocateReg(FPR); 7071 if (FReg) 7072 State.addLoc(CCValAssign::getReg(ValNo, ValVT, FReg, LocVT, LocInfo)); 7073 7074 // Reserve and initialize GPRs or initialize the PSA as required. 7075 for (unsigned I = 0; I < StoreSize; I += PtrByteSize) { 7076 if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32)) { 7077 assert(FReg && "An FPR should be available when a GPR is reserved."); 7078 if (State.isVarArg()) { 7079 // Successfully reserved GPRs are only initialized for vararg calls. 7080 // Custom handling is required for: 7081 // f64 in PPC32 needs to be split into 2 GPRs. 7082 // f32 in PPC64 needs to occupy only lower 32 bits of 64-bit GPR. 7083 State.addLoc( 7084 CCValAssign::getCustomReg(ValNo, ValVT, Reg, RegVT, LocInfo)); 7085 } 7086 } else { 7087 // If there are insufficient GPRs, the PSA needs to be initialized. 7088 // Initialization occurs even if an FPR was initialized for 7089 // compatibility with the AIX XL compiler. The full memory for the 7090 // argument will be initialized even if a prior word is saved in GPR. 7091 // A custom memLoc is used when the argument also passes in FPR so 7092 // that the callee handling can skip over it easily. 7093 State.addLoc( 7094 FReg ? CCValAssign::getCustomMem(ValNo, ValVT, Offset, LocVT, 7095 LocInfo) 7096 : CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo)); 7097 break; 7098 } 7099 } 7100 7101 return false; 7102 } 7103 } 7104 return true; 7105 } 7106 7107 static const TargetRegisterClass *getRegClassForSVT(MVT::SimpleValueType SVT, 7108 bool IsPPC64) { 7109 assert((IsPPC64 || SVT != MVT::i64) && 7110 "i64 should have been split for 32-bit codegen."); 7111 7112 switch (SVT) { 7113 default: 7114 report_fatal_error("Unexpected value type for formal argument"); 7115 case MVT::i1: 7116 case MVT::i32: 7117 case MVT::i64: 7118 return IsPPC64 ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 7119 case MVT::f32: 7120 return &PPC::F4RCRegClass; 7121 case MVT::f64: 7122 return &PPC::F8RCRegClass; 7123 } 7124 } 7125 7126 static SDValue truncateScalarIntegerArg(ISD::ArgFlagsTy Flags, EVT ValVT, 7127 SelectionDAG &DAG, SDValue ArgValue, 7128 MVT LocVT, const SDLoc &dl) { 7129 assert(ValVT.isScalarInteger() && LocVT.isScalarInteger()); 7130 assert(ValVT.getSizeInBits() < LocVT.getSizeInBits()); 7131 7132 if (Flags.isSExt()) 7133 ArgValue = DAG.getNode(ISD::AssertSext, dl, LocVT, ArgValue, 7134 DAG.getValueType(ValVT)); 7135 else if (Flags.isZExt()) 7136 ArgValue = DAG.getNode(ISD::AssertZext, dl, LocVT, ArgValue, 7137 DAG.getValueType(ValVT)); 7138 7139 return DAG.getNode(ISD::TRUNCATE, dl, ValVT, ArgValue); 7140 } 7141 7142 static unsigned mapArgRegToOffsetAIX(unsigned Reg, const PPCFrameLowering *FL) { 7143 const unsigned LASize = FL->getLinkageSize(); 7144 7145 if (PPC::GPRCRegClass.contains(Reg)) { 7146 assert(Reg >= PPC::R3 && Reg <= PPC::R10 && 7147 "Reg must be a valid argument register!"); 7148 return LASize + 4 * (Reg - PPC::R3); 7149 } 7150 7151 if (PPC::G8RCRegClass.contains(Reg)) { 7152 assert(Reg >= PPC::X3 && Reg <= PPC::X10 && 7153 "Reg must be a valid argument register!"); 7154 return LASize + 8 * (Reg - PPC::X3); 7155 } 7156 7157 llvm_unreachable("Only general purpose registers expected."); 7158 } 7159 7160 SDValue PPCTargetLowering::LowerFormalArguments_AIX( 7161 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 7162 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 7163 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 7164 7165 assert((CallConv == CallingConv::C || CallConv == CallingConv::Cold || 7166 CallConv == CallingConv::Fast) && 7167 "Unexpected calling convention!"); 7168 7169 if (getTargetMachine().Options.GuaranteedTailCallOpt) 7170 report_fatal_error("Tail call support is unimplemented on AIX."); 7171 7172 if (useSoftFloat()) 7173 report_fatal_error("Soft float support is unimplemented on AIX."); 7174 7175 const PPCSubtarget &Subtarget = 7176 static_cast<const PPCSubtarget &>(DAG.getSubtarget()); 7177 if (Subtarget.hasQPX()) 7178 report_fatal_error("QPX support is not supported on AIX."); 7179 7180 const bool IsPPC64 = Subtarget.isPPC64(); 7181 const unsigned PtrByteSize = IsPPC64 ? 8 : 4; 7182 7183 // Assign locations to all of the incoming arguments. 7184 SmallVector<CCValAssign, 16> ArgLocs; 7185 MachineFunction &MF = DAG.getMachineFunction(); 7186 MachineFrameInfo &MFI = MF.getFrameInfo(); 7187 CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext()); 7188 7189 const EVT PtrVT = getPointerTy(MF.getDataLayout()); 7190 // Reserve space for the linkage area on the stack. 7191 const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 7192 CCInfo.AllocateStack(LinkageSize, PtrByteSize); 7193 CCInfo.AnalyzeFormalArguments(Ins, CC_AIX); 7194 7195 SmallVector<SDValue, 8> MemOps; 7196 7197 for (size_t I = 0, End = ArgLocs.size(); I != End; /* No increment here */) { 7198 CCValAssign &VA = ArgLocs[I++]; 7199 MVT LocVT = VA.getLocVT(); 7200 ISD::ArgFlagsTy Flags = Ins[VA.getValNo()].Flags; 7201 7202 // For compatibility with the AIX XL compiler, the float args in the 7203 // parameter save area are initialized even if the argument is available 7204 // in register. The caller is required to initialize both the register 7205 // and memory, however, the callee can choose to expect it in either. 7206 // The memloc is dismissed here because the argument is retrieved from 7207 // the register. 7208 if (VA.isMemLoc() && VA.needsCustom()) 7209 continue; 7210 7211 if (Flags.isByVal() && VA.isMemLoc()) { 7212 const unsigned Size = 7213 alignTo(Flags.getByValSize() ? Flags.getByValSize() : PtrByteSize, 7214 PtrByteSize); 7215 const int FI = MF.getFrameInfo().CreateFixedObject( 7216 Size, VA.getLocMemOffset(), /* IsImmutable */ false, 7217 /* IsAliased */ true); 7218 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 7219 InVals.push_back(FIN); 7220 7221 continue; 7222 } 7223 7224 if (Flags.isByVal()) { 7225 assert(VA.isRegLoc() && "MemLocs should already be handled."); 7226 7227 const MCPhysReg ArgReg = VA.getLocReg(); 7228 const PPCFrameLowering *FL = Subtarget.getFrameLowering(); 7229 7230 if (Flags.getNonZeroByValAlign() > PtrByteSize) 7231 report_fatal_error("Over aligned byvals not supported yet."); 7232 7233 const unsigned StackSize = alignTo(Flags.getByValSize(), PtrByteSize); 7234 const int FI = MF.getFrameInfo().CreateFixedObject( 7235 StackSize, mapArgRegToOffsetAIX(ArgReg, FL), /* IsImmutable */ false, 7236 /* IsAliased */ true); 7237 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 7238 InVals.push_back(FIN); 7239 7240 // Add live ins for all the RegLocs for the same ByVal. 7241 const TargetRegisterClass *RegClass = 7242 IsPPC64 ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 7243 7244 auto HandleRegLoc = [&, RegClass, LocVT](const MCPhysReg PhysReg, 7245 unsigned Offset) { 7246 const unsigned VReg = MF.addLiveIn(PhysReg, RegClass); 7247 // Since the callers side has left justified the aggregate in the 7248 // register, we can simply store the entire register into the stack 7249 // slot. 7250 SDValue CopyFrom = DAG.getCopyFromReg(Chain, dl, VReg, LocVT); 7251 // The store to the fixedstack object is needed becuase accessing a 7252 // field of the ByVal will use a gep and load. Ideally we will optimize 7253 // to extracting the value from the register directly, and elide the 7254 // stores when the arguments address is not taken, but that will need to 7255 // be future work. 7256 SDValue Store = 7257 DAG.getStore(CopyFrom.getValue(1), dl, CopyFrom, 7258 DAG.getObjectPtrOffset(dl, FIN, Offset), 7259 MachinePointerInfo::getFixedStack(MF, FI, Offset)); 7260 7261 MemOps.push_back(Store); 7262 }; 7263 7264 unsigned Offset = 0; 7265 HandleRegLoc(VA.getLocReg(), Offset); 7266 Offset += PtrByteSize; 7267 for (; Offset != StackSize && ArgLocs[I].isRegLoc(); 7268 Offset += PtrByteSize) { 7269 assert(ArgLocs[I].getValNo() == VA.getValNo() && 7270 "RegLocs should be for ByVal argument."); 7271 7272 const CCValAssign RL = ArgLocs[I++]; 7273 HandleRegLoc(RL.getLocReg(), Offset); 7274 } 7275 7276 if (Offset != StackSize) { 7277 assert(ArgLocs[I].getValNo() == VA.getValNo() && 7278 "Expected MemLoc for remaining bytes."); 7279 assert(ArgLocs[I].isMemLoc() && "Expected MemLoc for remaining bytes."); 7280 // Consume the MemLoc.The InVal has already been emitted, so nothing 7281 // more needs to be done. 7282 ++I; 7283 } 7284 7285 continue; 7286 } 7287 7288 EVT ValVT = VA.getValVT(); 7289 if (VA.isRegLoc() && !VA.needsCustom()) { 7290 MVT::SimpleValueType SVT = ValVT.getSimpleVT().SimpleTy; 7291 unsigned VReg = 7292 MF.addLiveIn(VA.getLocReg(), getRegClassForSVT(SVT, IsPPC64)); 7293 SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, VReg, LocVT); 7294 if (ValVT.isScalarInteger() && 7295 (ValVT.getSizeInBits() < LocVT.getSizeInBits())) { 7296 ArgValue = 7297 truncateScalarIntegerArg(Flags, ValVT, DAG, ArgValue, LocVT, dl); 7298 } 7299 InVals.push_back(ArgValue); 7300 continue; 7301 } 7302 if (VA.isMemLoc()) { 7303 const unsigned LocSize = LocVT.getStoreSize(); 7304 const unsigned ValSize = ValVT.getStoreSize(); 7305 assert((ValSize <= LocSize) && 7306 "Object size is larger than size of MemLoc"); 7307 int CurArgOffset = VA.getLocMemOffset(); 7308 // Objects are right-justified because AIX is big-endian. 7309 if (LocSize > ValSize) 7310 CurArgOffset += LocSize - ValSize; 7311 // Potential tail calls could cause overwriting of argument stack slots. 7312 const bool IsImmutable = 7313 !(getTargetMachine().Options.GuaranteedTailCallOpt && 7314 (CallConv == CallingConv::Fast)); 7315 int FI = MFI.CreateFixedObject(ValSize, CurArgOffset, IsImmutable); 7316 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 7317 SDValue ArgValue = 7318 DAG.getLoad(ValVT, dl, Chain, FIN, MachinePointerInfo()); 7319 InVals.push_back(ArgValue); 7320 continue; 7321 } 7322 } 7323 7324 // On AIX a minimum of 8 words is saved to the parameter save area. 7325 const unsigned MinParameterSaveArea = 8 * PtrByteSize; 7326 // Area that is at least reserved in the caller of this function. 7327 unsigned CallerReservedArea = 7328 std::max(CCInfo.getNextStackOffset(), LinkageSize + MinParameterSaveArea); 7329 7330 // Set the size that is at least reserved in caller of this function. Tail 7331 // call optimized function's reserved stack space needs to be aligned so 7332 // that taking the difference between two stack areas will result in an 7333 // aligned stack. 7334 CallerReservedArea = 7335 EnsureStackAlignment(Subtarget.getFrameLowering(), CallerReservedArea); 7336 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 7337 FuncInfo->setMinReservedArea(CallerReservedArea); 7338 7339 if (isVarArg) { 7340 FuncInfo->setVarArgsFrameIndex( 7341 MFI.CreateFixedObject(PtrByteSize, CCInfo.getNextStackOffset(), true)); 7342 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 7343 7344 static const MCPhysReg GPR_32[] = {PPC::R3, PPC::R4, PPC::R5, PPC::R6, 7345 PPC::R7, PPC::R8, PPC::R9, PPC::R10}; 7346 7347 static const MCPhysReg GPR_64[] = {PPC::X3, PPC::X4, PPC::X5, PPC::X6, 7348 PPC::X7, PPC::X8, PPC::X9, PPC::X10}; 7349 const unsigned NumGPArgRegs = array_lengthof(IsPPC64 ? GPR_64 : GPR_32); 7350 7351 // The fixed integer arguments of a variadic function are stored to the 7352 // VarArgsFrameIndex on the stack so that they may be loaded by 7353 // dereferencing the result of va_next. 7354 for (unsigned GPRIndex = 7355 (CCInfo.getNextStackOffset() - LinkageSize) / PtrByteSize; 7356 GPRIndex < NumGPArgRegs; ++GPRIndex) { 7357 7358 const unsigned VReg = 7359 IsPPC64 ? MF.addLiveIn(GPR_64[GPRIndex], &PPC::G8RCRegClass) 7360 : MF.addLiveIn(GPR_32[GPRIndex], &PPC::GPRCRegClass); 7361 7362 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 7363 SDValue Store = 7364 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 7365 MemOps.push_back(Store); 7366 // Increment the address for the next argument to store. 7367 SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT); 7368 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 7369 } 7370 } 7371 7372 if (!MemOps.empty()) 7373 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 7374 7375 return Chain; 7376 } 7377 7378 SDValue PPCTargetLowering::LowerCall_AIX( 7379 SDValue Chain, SDValue Callee, CallFlags CFlags, 7380 const SmallVectorImpl<ISD::OutputArg> &Outs, 7381 const SmallVectorImpl<SDValue> &OutVals, 7382 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 7383 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 7384 const CallBase *CB) const { 7385 7386 assert((CFlags.CallConv == CallingConv::C || 7387 CFlags.CallConv == CallingConv::Cold || 7388 CFlags.CallConv == CallingConv::Fast) && 7389 "Unexpected calling convention!"); 7390 7391 if (CFlags.IsPatchPoint) 7392 report_fatal_error("This call type is unimplemented on AIX."); 7393 7394 const PPCSubtarget& Subtarget = 7395 static_cast<const PPCSubtarget&>(DAG.getSubtarget()); 7396 if (Subtarget.hasQPX()) 7397 report_fatal_error("QPX is not supported on AIX."); 7398 if (Subtarget.hasAltivec()) 7399 report_fatal_error("Altivec support is unimplemented on AIX."); 7400 7401 MachineFunction &MF = DAG.getMachineFunction(); 7402 SmallVector<CCValAssign, 16> ArgLocs; 7403 CCState CCInfo(CFlags.CallConv, CFlags.IsVarArg, MF, ArgLocs, 7404 *DAG.getContext()); 7405 7406 // Reserve space for the linkage save area (LSA) on the stack. 7407 // In both PPC32 and PPC64 there are 6 reserved slots in the LSA: 7408 // [SP][CR][LR][2 x reserved][TOC]. 7409 // The LSA is 24 bytes (6x4) in PPC32 and 48 bytes (6x8) in PPC64. 7410 const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 7411 const bool IsPPC64 = Subtarget.isPPC64(); 7412 const EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7413 const unsigned PtrByteSize = IsPPC64 ? 8 : 4; 7414 CCInfo.AllocateStack(LinkageSize, PtrByteSize); 7415 CCInfo.AnalyzeCallOperands(Outs, CC_AIX); 7416 7417 // The prolog code of the callee may store up to 8 GPR argument registers to 7418 // the stack, allowing va_start to index over them in memory if the callee 7419 // is variadic. 7420 // Because we cannot tell if this is needed on the caller side, we have to 7421 // conservatively assume that it is needed. As such, make sure we have at 7422 // least enough stack space for the caller to store the 8 GPRs. 7423 const unsigned MinParameterSaveAreaSize = 8 * PtrByteSize; 7424 const unsigned NumBytes = std::max(LinkageSize + MinParameterSaveAreaSize, 7425 CCInfo.getNextStackOffset()); 7426 7427 // Adjust the stack pointer for the new arguments... 7428 // These operations are automatically eliminated by the prolog/epilog pass. 7429 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 7430 SDValue CallSeqStart = Chain; 7431 7432 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 7433 SmallVector<SDValue, 8> MemOpChains; 7434 7435 // Set up a copy of the stack pointer for loading and storing any 7436 // arguments that may not fit in the registers available for argument 7437 // passing. 7438 const SDValue StackPtr = IsPPC64 ? DAG.getRegister(PPC::X1, MVT::i64) 7439 : DAG.getRegister(PPC::R1, MVT::i32); 7440 7441 for (unsigned I = 0, E = ArgLocs.size(); I != E;) { 7442 const unsigned ValNo = ArgLocs[I].getValNo(); 7443 SDValue Arg = OutVals[ValNo]; 7444 ISD::ArgFlagsTy Flags = Outs[ValNo].Flags; 7445 7446 if (Flags.isByVal()) { 7447 const unsigned ByValSize = Flags.getByValSize(); 7448 7449 // Nothing to do for zero-sized ByVals on the caller side. 7450 if (!ByValSize) { 7451 ++I; 7452 continue; 7453 } 7454 7455 auto GetLoad = [&](EVT VT, unsigned LoadOffset) { 7456 return DAG.getExtLoad(ISD::ZEXTLOAD, dl, PtrVT, Chain, 7457 (LoadOffset != 0) 7458 ? DAG.getObjectPtrOffset(dl, Arg, LoadOffset) 7459 : Arg, 7460 MachinePointerInfo(), VT); 7461 }; 7462 7463 unsigned LoadOffset = 0; 7464 7465 // Initialize registers, which are fully occupied by the by-val argument. 7466 while (LoadOffset + PtrByteSize <= ByValSize && ArgLocs[I].isRegLoc()) { 7467 SDValue Load = GetLoad(PtrVT, LoadOffset); 7468 MemOpChains.push_back(Load.getValue(1)); 7469 LoadOffset += PtrByteSize; 7470 const CCValAssign &ByValVA = ArgLocs[I++]; 7471 assert(ByValVA.getValNo() == ValNo && 7472 "Unexpected location for pass-by-value argument."); 7473 RegsToPass.push_back(std::make_pair(ByValVA.getLocReg(), Load)); 7474 } 7475 7476 if (LoadOffset == ByValSize) 7477 continue; 7478 7479 // There must be one more loc to handle the remainder. 7480 assert(ArgLocs[I].getValNo() == ValNo && 7481 "Expected additional location for by-value argument."); 7482 7483 if (ArgLocs[I].isMemLoc()) { 7484 assert(LoadOffset < ByValSize && "Unexpected memloc for by-val arg."); 7485 const CCValAssign &ByValVA = ArgLocs[I++]; 7486 ISD::ArgFlagsTy MemcpyFlags = Flags; 7487 // Only memcpy the bytes that don't pass in register. 7488 MemcpyFlags.setByValSize(ByValSize - LoadOffset); 7489 Chain = CallSeqStart = createMemcpyOutsideCallSeq( 7490 (LoadOffset != 0) ? DAG.getObjectPtrOffset(dl, Arg, LoadOffset) 7491 : Arg, 7492 DAG.getObjectPtrOffset(dl, StackPtr, ByValVA.getLocMemOffset()), 7493 CallSeqStart, MemcpyFlags, DAG, dl); 7494 continue; 7495 } 7496 7497 // Initialize the final register residue. 7498 // Any residue that occupies the final by-val arg register must be 7499 // left-justified on AIX. Loads must be a power-of-2 size and cannot be 7500 // larger than the ByValSize. For example: a 7 byte by-val arg requires 4, 7501 // 2 and 1 byte loads. 7502 const unsigned ResidueBytes = ByValSize % PtrByteSize; 7503 assert(ResidueBytes != 0 && LoadOffset + PtrByteSize > ByValSize && 7504 "Unexpected register residue for by-value argument."); 7505 SDValue ResidueVal; 7506 for (unsigned Bytes = 0; Bytes != ResidueBytes;) { 7507 const unsigned N = PowerOf2Floor(ResidueBytes - Bytes); 7508 const MVT VT = 7509 N == 1 ? MVT::i8 7510 : ((N == 2) ? MVT::i16 : (N == 4 ? MVT::i32 : MVT::i64)); 7511 SDValue Load = GetLoad(VT, LoadOffset); 7512 MemOpChains.push_back(Load.getValue(1)); 7513 LoadOffset += N; 7514 Bytes += N; 7515 7516 // By-val arguments are passed left-justfied in register. 7517 // Every load here needs to be shifted, otherwise a full register load 7518 // should have been used. 7519 assert(PtrVT.getSimpleVT().getSizeInBits() > (Bytes * 8) && 7520 "Unexpected load emitted during handling of pass-by-value " 7521 "argument."); 7522 unsigned NumSHLBits = PtrVT.getSimpleVT().getSizeInBits() - (Bytes * 8); 7523 EVT ShiftAmountTy = 7524 getShiftAmountTy(Load->getValueType(0), DAG.getDataLayout()); 7525 SDValue SHLAmt = DAG.getConstant(NumSHLBits, dl, ShiftAmountTy); 7526 SDValue ShiftedLoad = 7527 DAG.getNode(ISD::SHL, dl, Load.getValueType(), Load, SHLAmt); 7528 ResidueVal = ResidueVal ? DAG.getNode(ISD::OR, dl, PtrVT, ResidueVal, 7529 ShiftedLoad) 7530 : ShiftedLoad; 7531 } 7532 7533 const CCValAssign &ByValVA = ArgLocs[I++]; 7534 RegsToPass.push_back(std::make_pair(ByValVA.getLocReg(), ResidueVal)); 7535 continue; 7536 } 7537 7538 CCValAssign &VA = ArgLocs[I++]; 7539 const MVT LocVT = VA.getLocVT(); 7540 const MVT ValVT = VA.getValVT(); 7541 7542 switch (VA.getLocInfo()) { 7543 default: 7544 report_fatal_error("Unexpected argument extension type."); 7545 case CCValAssign::Full: 7546 break; 7547 case CCValAssign::ZExt: 7548 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg); 7549 break; 7550 case CCValAssign::SExt: 7551 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg); 7552 break; 7553 } 7554 7555 if (VA.isRegLoc() && !VA.needsCustom()) { 7556 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 7557 continue; 7558 } 7559 7560 if (VA.isMemLoc()) { 7561 SDValue PtrOff = 7562 DAG.getConstant(VA.getLocMemOffset(), dl, StackPtr.getValueType()); 7563 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 7564 MemOpChains.push_back( 7565 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo())); 7566 7567 continue; 7568 } 7569 7570 // Custom handling is used for GPR initializations for vararg float 7571 // arguments. 7572 assert(VA.isRegLoc() && VA.needsCustom() && CFlags.IsVarArg && 7573 ValVT.isFloatingPoint() && LocVT.isInteger() && 7574 "Unexpected register handling for calling convention."); 7575 7576 SDValue ArgAsInt = 7577 DAG.getBitcast(MVT::getIntegerVT(ValVT.getSizeInBits()), Arg); 7578 7579 if (Arg.getValueType().getStoreSize() == LocVT.getStoreSize()) 7580 // f32 in 32-bit GPR 7581 // f64 in 64-bit GPR 7582 RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgAsInt)); 7583 else if (Arg.getValueType().getSizeInBits() < LocVT.getSizeInBits()) 7584 // f32 in 64-bit GPR. 7585 RegsToPass.push_back(std::make_pair( 7586 VA.getLocReg(), DAG.getZExtOrTrunc(ArgAsInt, dl, LocVT))); 7587 else { 7588 // f64 in two 32-bit GPRs 7589 // The 2 GPRs are marked custom and expected to be adjacent in ArgLocs. 7590 assert(Arg.getValueType() == MVT::f64 && CFlags.IsVarArg && !IsPPC64 && 7591 "Unexpected custom register for argument!"); 7592 CCValAssign &GPR1 = VA; 7593 SDValue MSWAsI64 = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgAsInt, 7594 DAG.getConstant(32, dl, MVT::i8)); 7595 RegsToPass.push_back(std::make_pair( 7596 GPR1.getLocReg(), DAG.getZExtOrTrunc(MSWAsI64, dl, MVT::i32))); 7597 7598 if (I != E) { 7599 // If only 1 GPR was available, there will only be one custom GPR and 7600 // the argument will also pass in memory. 7601 CCValAssign &PeekArg = ArgLocs[I]; 7602 if (PeekArg.isRegLoc() && PeekArg.getValNo() == PeekArg.getValNo()) { 7603 assert(PeekArg.needsCustom() && "A second custom GPR is expected."); 7604 CCValAssign &GPR2 = ArgLocs[I++]; 7605 RegsToPass.push_back(std::make_pair( 7606 GPR2.getLocReg(), DAG.getZExtOrTrunc(ArgAsInt, dl, MVT::i32))); 7607 } 7608 } 7609 } 7610 } 7611 7612 if (!MemOpChains.empty()) 7613 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 7614 7615 // For indirect calls, we need to save the TOC base to the stack for 7616 // restoration after the call. 7617 if (CFlags.IsIndirect) { 7618 assert(!CFlags.IsTailCall && "Indirect tail-calls not supported."); 7619 const MCRegister TOCBaseReg = Subtarget.getTOCPointerRegister(); 7620 const MCRegister StackPtrReg = Subtarget.getStackPointerRegister(); 7621 const MVT PtrVT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32; 7622 const unsigned TOCSaveOffset = 7623 Subtarget.getFrameLowering()->getTOCSaveOffset(); 7624 7625 setUsesTOCBasePtr(DAG); 7626 SDValue Val = DAG.getCopyFromReg(Chain, dl, TOCBaseReg, PtrVT); 7627 SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl); 7628 SDValue StackPtr = DAG.getRegister(StackPtrReg, PtrVT); 7629 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 7630 Chain = DAG.getStore( 7631 Val.getValue(1), dl, Val, AddPtr, 7632 MachinePointerInfo::getStack(DAG.getMachineFunction(), TOCSaveOffset)); 7633 } 7634 7635 // Build a sequence of copy-to-reg nodes chained together with token chain 7636 // and flag operands which copy the outgoing args into the appropriate regs. 7637 SDValue InFlag; 7638 for (auto Reg : RegsToPass) { 7639 Chain = DAG.getCopyToReg(Chain, dl, Reg.first, Reg.second, InFlag); 7640 InFlag = Chain.getValue(1); 7641 } 7642 7643 const int SPDiff = 0; 7644 return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart, 7645 Callee, SPDiff, NumBytes, Ins, InVals, CB); 7646 } 7647 7648 bool 7649 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv, 7650 MachineFunction &MF, bool isVarArg, 7651 const SmallVectorImpl<ISD::OutputArg> &Outs, 7652 LLVMContext &Context) const { 7653 SmallVector<CCValAssign, 16> RVLocs; 7654 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context); 7655 return CCInfo.CheckReturn( 7656 Outs, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold) 7657 ? RetCC_PPC_Cold 7658 : RetCC_PPC); 7659 } 7660 7661 SDValue 7662 PPCTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 7663 bool isVarArg, 7664 const SmallVectorImpl<ISD::OutputArg> &Outs, 7665 const SmallVectorImpl<SDValue> &OutVals, 7666 const SDLoc &dl, SelectionDAG &DAG) const { 7667 SmallVector<CCValAssign, 16> RVLocs; 7668 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 7669 *DAG.getContext()); 7670 CCInfo.AnalyzeReturn(Outs, 7671 (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold) 7672 ? RetCC_PPC_Cold 7673 : RetCC_PPC); 7674 7675 SDValue Flag; 7676 SmallVector<SDValue, 4> RetOps(1, Chain); 7677 7678 // Copy the result values into the output registers. 7679 for (unsigned i = 0, RealResIdx = 0; i != RVLocs.size(); ++i, ++RealResIdx) { 7680 CCValAssign &VA = RVLocs[i]; 7681 assert(VA.isRegLoc() && "Can only return in registers!"); 7682 7683 SDValue Arg = OutVals[RealResIdx]; 7684 7685 switch (VA.getLocInfo()) { 7686 default: llvm_unreachable("Unknown loc info!"); 7687 case CCValAssign::Full: break; 7688 case CCValAssign::AExt: 7689 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg); 7690 break; 7691 case CCValAssign::ZExt: 7692 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg); 7693 break; 7694 case CCValAssign::SExt: 7695 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg); 7696 break; 7697 } 7698 if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) { 7699 bool isLittleEndian = Subtarget.isLittleEndian(); 7700 // Legalize ret f64 -> ret 2 x i32. 7701 SDValue SVal = 7702 DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg, 7703 DAG.getIntPtrConstant(isLittleEndian ? 0 : 1, dl)); 7704 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Flag); 7705 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 7706 SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg, 7707 DAG.getIntPtrConstant(isLittleEndian ? 1 : 0, dl)); 7708 Flag = Chain.getValue(1); 7709 VA = RVLocs[++i]; // skip ahead to next loc 7710 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Flag); 7711 } else 7712 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag); 7713 Flag = Chain.getValue(1); 7714 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 7715 } 7716 7717 RetOps[0] = Chain; // Update chain. 7718 7719 // Add the flag if we have it. 7720 if (Flag.getNode()) 7721 RetOps.push_back(Flag); 7722 7723 return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, RetOps); 7724 } 7725 7726 SDValue 7727 PPCTargetLowering::LowerGET_DYNAMIC_AREA_OFFSET(SDValue Op, 7728 SelectionDAG &DAG) const { 7729 SDLoc dl(Op); 7730 7731 // Get the correct type for integers. 7732 EVT IntVT = Op.getValueType(); 7733 7734 // Get the inputs. 7735 SDValue Chain = Op.getOperand(0); 7736 SDValue FPSIdx = getFramePointerFrameIndex(DAG); 7737 // Build a DYNAREAOFFSET node. 7738 SDValue Ops[2] = {Chain, FPSIdx}; 7739 SDVTList VTs = DAG.getVTList(IntVT); 7740 return DAG.getNode(PPCISD::DYNAREAOFFSET, dl, VTs, Ops); 7741 } 7742 7743 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op, 7744 SelectionDAG &DAG) const { 7745 // When we pop the dynamic allocation we need to restore the SP link. 7746 SDLoc dl(Op); 7747 7748 // Get the correct type for pointers. 7749 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7750 7751 // Construct the stack pointer operand. 7752 bool isPPC64 = Subtarget.isPPC64(); 7753 unsigned SP = isPPC64 ? PPC::X1 : PPC::R1; 7754 SDValue StackPtr = DAG.getRegister(SP, PtrVT); 7755 7756 // Get the operands for the STACKRESTORE. 7757 SDValue Chain = Op.getOperand(0); 7758 SDValue SaveSP = Op.getOperand(1); 7759 7760 // Load the old link SP. 7761 SDValue LoadLinkSP = 7762 DAG.getLoad(PtrVT, dl, Chain, StackPtr, MachinePointerInfo()); 7763 7764 // Restore the stack pointer. 7765 Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP); 7766 7767 // Store the old link SP. 7768 return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo()); 7769 } 7770 7771 SDValue PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG &DAG) const { 7772 MachineFunction &MF = DAG.getMachineFunction(); 7773 bool isPPC64 = Subtarget.isPPC64(); 7774 EVT PtrVT = getPointerTy(MF.getDataLayout()); 7775 7776 // Get current frame pointer save index. The users of this index will be 7777 // primarily DYNALLOC instructions. 7778 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>(); 7779 int RASI = FI->getReturnAddrSaveIndex(); 7780 7781 // If the frame pointer save index hasn't been defined yet. 7782 if (!RASI) { 7783 // Find out what the fix offset of the frame pointer save area. 7784 int LROffset = Subtarget.getFrameLowering()->getReturnSaveOffset(); 7785 // Allocate the frame index for frame pointer save area. 7786 RASI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, LROffset, false); 7787 // Save the result. 7788 FI->setReturnAddrSaveIndex(RASI); 7789 } 7790 return DAG.getFrameIndex(RASI, PtrVT); 7791 } 7792 7793 SDValue 7794 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const { 7795 MachineFunction &MF = DAG.getMachineFunction(); 7796 bool isPPC64 = Subtarget.isPPC64(); 7797 EVT PtrVT = getPointerTy(MF.getDataLayout()); 7798 7799 // Get current frame pointer save index. The users of this index will be 7800 // primarily DYNALLOC instructions. 7801 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>(); 7802 int FPSI = FI->getFramePointerSaveIndex(); 7803 7804 // If the frame pointer save index hasn't been defined yet. 7805 if (!FPSI) { 7806 // Find out what the fix offset of the frame pointer save area. 7807 int FPOffset = Subtarget.getFrameLowering()->getFramePointerSaveOffset(); 7808 // Allocate the frame index for frame pointer save area. 7809 FPSI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, FPOffset, true); 7810 // Save the result. 7811 FI->setFramePointerSaveIndex(FPSI); 7812 } 7813 return DAG.getFrameIndex(FPSI, PtrVT); 7814 } 7815 7816 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, 7817 SelectionDAG &DAG) const { 7818 // Get the inputs. 7819 SDValue Chain = Op.getOperand(0); 7820 SDValue Size = Op.getOperand(1); 7821 SDLoc dl(Op); 7822 7823 // Get the correct type for pointers. 7824 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7825 // Negate the size. 7826 SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT, 7827 DAG.getConstant(0, dl, PtrVT), Size); 7828 // Construct a node for the frame pointer save index. 7829 SDValue FPSIdx = getFramePointerFrameIndex(DAG); 7830 // Build a DYNALLOC node. 7831 SDValue Ops[3] = { Chain, NegSize, FPSIdx }; 7832 SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other); 7833 return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops); 7834 } 7835 7836 SDValue PPCTargetLowering::LowerEH_DWARF_CFA(SDValue Op, 7837 SelectionDAG &DAG) const { 7838 MachineFunction &MF = DAG.getMachineFunction(); 7839 7840 bool isPPC64 = Subtarget.isPPC64(); 7841 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7842 7843 int FI = MF.getFrameInfo().CreateFixedObject(isPPC64 ? 8 : 4, 0, false); 7844 return DAG.getFrameIndex(FI, PtrVT); 7845 } 7846 7847 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op, 7848 SelectionDAG &DAG) const { 7849 SDLoc DL(Op); 7850 return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL, 7851 DAG.getVTList(MVT::i32, MVT::Other), 7852 Op.getOperand(0), Op.getOperand(1)); 7853 } 7854 7855 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op, 7856 SelectionDAG &DAG) const { 7857 SDLoc DL(Op); 7858 return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other, 7859 Op.getOperand(0), Op.getOperand(1)); 7860 } 7861 7862 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const { 7863 if (Op.getValueType().isVector()) 7864 return LowerVectorLoad(Op, DAG); 7865 7866 assert(Op.getValueType() == MVT::i1 && 7867 "Custom lowering only for i1 loads"); 7868 7869 // First, load 8 bits into 32 bits, then truncate to 1 bit. 7870 7871 SDLoc dl(Op); 7872 LoadSDNode *LD = cast<LoadSDNode>(Op); 7873 7874 SDValue Chain = LD->getChain(); 7875 SDValue BasePtr = LD->getBasePtr(); 7876 MachineMemOperand *MMO = LD->getMemOperand(); 7877 7878 SDValue NewLD = 7879 DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(DAG.getDataLayout()), Chain, 7880 BasePtr, MVT::i8, MMO); 7881 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD); 7882 7883 SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) }; 7884 return DAG.getMergeValues(Ops, dl); 7885 } 7886 7887 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const { 7888 if (Op.getOperand(1).getValueType().isVector()) 7889 return LowerVectorStore(Op, DAG); 7890 7891 assert(Op.getOperand(1).getValueType() == MVT::i1 && 7892 "Custom lowering only for i1 stores"); 7893 7894 // First, zero extend to 32 bits, then use a truncating store to 8 bits. 7895 7896 SDLoc dl(Op); 7897 StoreSDNode *ST = cast<StoreSDNode>(Op); 7898 7899 SDValue Chain = ST->getChain(); 7900 SDValue BasePtr = ST->getBasePtr(); 7901 SDValue Value = ST->getValue(); 7902 MachineMemOperand *MMO = ST->getMemOperand(); 7903 7904 Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(DAG.getDataLayout()), 7905 Value); 7906 return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO); 7907 } 7908 7909 // FIXME: Remove this once the ANDI glue bug is fixed: 7910 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const { 7911 assert(Op.getValueType() == MVT::i1 && 7912 "Custom lowering only for i1 results"); 7913 7914 SDLoc DL(Op); 7915 return DAG.getNode(PPCISD::ANDI_rec_1_GT_BIT, DL, MVT::i1, Op.getOperand(0)); 7916 } 7917 7918 SDValue PPCTargetLowering::LowerTRUNCATEVector(SDValue Op, 7919 SelectionDAG &DAG) const { 7920 7921 // Implements a vector truncate that fits in a vector register as a shuffle. 7922 // We want to legalize vector truncates down to where the source fits in 7923 // a vector register (and target is therefore smaller than vector register 7924 // size). At that point legalization will try to custom lower the sub-legal 7925 // result and get here - where we can contain the truncate as a single target 7926 // operation. 7927 7928 // For example a trunc <2 x i16> to <2 x i8> could be visualized as follows: 7929 // <MSB1|LSB1, MSB2|LSB2> to <LSB1, LSB2> 7930 // 7931 // We will implement it for big-endian ordering as this (where x denotes 7932 // undefined): 7933 // < MSB1|LSB1, MSB2|LSB2, uu, uu, uu, uu, uu, uu> to 7934 // < LSB1, LSB2, u, u, u, u, u, u, u, u, u, u, u, u, u, u> 7935 // 7936 // The same operation in little-endian ordering will be: 7937 // <uu, uu, uu, uu, uu, uu, LSB2|MSB2, LSB1|MSB1> to 7938 // <u, u, u, u, u, u, u, u, u, u, u, u, u, u, LSB2, LSB1> 7939 7940 assert(Op.getValueType().isVector() && "Vector type expected."); 7941 7942 SDLoc DL(Op); 7943 SDValue N1 = Op.getOperand(0); 7944 unsigned SrcSize = N1.getValueType().getSizeInBits(); 7945 assert(SrcSize <= 128 && "Source must fit in an Altivec/VSX vector"); 7946 SDValue WideSrc = SrcSize == 128 ? N1 : widenVec(DAG, N1, DL); 7947 7948 EVT TrgVT = Op.getValueType(); 7949 unsigned TrgNumElts = TrgVT.getVectorNumElements(); 7950 EVT EltVT = TrgVT.getVectorElementType(); 7951 unsigned WideNumElts = 128 / EltVT.getSizeInBits(); 7952 EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts); 7953 7954 // First list the elements we want to keep. 7955 unsigned SizeMult = SrcSize / TrgVT.getSizeInBits(); 7956 SmallVector<int, 16> ShuffV; 7957 if (Subtarget.isLittleEndian()) 7958 for (unsigned i = 0; i < TrgNumElts; ++i) 7959 ShuffV.push_back(i * SizeMult); 7960 else 7961 for (unsigned i = 1; i <= TrgNumElts; ++i) 7962 ShuffV.push_back(i * SizeMult - 1); 7963 7964 // Populate the remaining elements with undefs. 7965 for (unsigned i = TrgNumElts; i < WideNumElts; ++i) 7966 // ShuffV.push_back(i + WideNumElts); 7967 ShuffV.push_back(WideNumElts + 1); 7968 7969 SDValue Conv = DAG.getNode(ISD::BITCAST, DL, WideVT, WideSrc); 7970 return DAG.getVectorShuffle(WideVT, DL, Conv, DAG.getUNDEF(WideVT), ShuffV); 7971 } 7972 7973 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when 7974 /// possible. 7975 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const { 7976 // Not FP? Not a fsel. 7977 if (!Op.getOperand(0).getValueType().isFloatingPoint() || 7978 !Op.getOperand(2).getValueType().isFloatingPoint()) 7979 return Op; 7980 7981 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get(); 7982 7983 EVT ResVT = Op.getValueType(); 7984 EVT CmpVT = Op.getOperand(0).getValueType(); 7985 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 7986 SDValue TV = Op.getOperand(2), FV = Op.getOperand(3); 7987 SDLoc dl(Op); 7988 SDNodeFlags Flags = Op.getNode()->getFlags(); 7989 7990 // We have xsmaxcdp/xsmincdp which are OK to emit even in the 7991 // presence of infinities. 7992 if (Subtarget.hasP9Vector() && LHS == TV && RHS == FV) { 7993 switch (CC) { 7994 default: 7995 break; 7996 case ISD::SETOGT: 7997 case ISD::SETGT: 7998 return DAG.getNode(PPCISD::XSMAXCDP, dl, Op.getValueType(), LHS, RHS); 7999 case ISD::SETOLT: 8000 case ISD::SETLT: 8001 return DAG.getNode(PPCISD::XSMINCDP, dl, Op.getValueType(), LHS, RHS); 8002 } 8003 } 8004 8005 // We might be able to do better than this under some circumstances, but in 8006 // general, fsel-based lowering of select is a finite-math-only optimization. 8007 // For more information, see section F.3 of the 2.06 ISA specification. 8008 // With ISA 3.0 8009 if ((!DAG.getTarget().Options.NoInfsFPMath && !Flags.hasNoInfs()) || 8010 (!DAG.getTarget().Options.NoNaNsFPMath && !Flags.hasNoNaNs())) 8011 return Op; 8012 8013 // If the RHS of the comparison is a 0.0, we don't need to do the 8014 // subtraction at all. 8015 SDValue Sel1; 8016 if (isFloatingPointZero(RHS)) 8017 switch (CC) { 8018 default: break; // SETUO etc aren't handled by fsel. 8019 case ISD::SETNE: 8020 std::swap(TV, FV); 8021 LLVM_FALLTHROUGH; 8022 case ISD::SETEQ: 8023 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits 8024 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); 8025 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV); 8026 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits 8027 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1); 8028 return DAG.getNode(PPCISD::FSEL, dl, ResVT, 8029 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV); 8030 case ISD::SETULT: 8031 case ISD::SETLT: 8032 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt 8033 LLVM_FALLTHROUGH; 8034 case ISD::SETOGE: 8035 case ISD::SETGE: 8036 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits 8037 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); 8038 return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV); 8039 case ISD::SETUGT: 8040 case ISD::SETGT: 8041 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt 8042 LLVM_FALLTHROUGH; 8043 case ISD::SETOLE: 8044 case ISD::SETLE: 8045 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits 8046 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); 8047 return DAG.getNode(PPCISD::FSEL, dl, ResVT, 8048 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV); 8049 } 8050 8051 SDValue Cmp; 8052 switch (CC) { 8053 default: break; // SETUO etc aren't handled by fsel. 8054 case ISD::SETNE: 8055 std::swap(TV, FV); 8056 LLVM_FALLTHROUGH; 8057 case ISD::SETEQ: 8058 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags); 8059 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 8060 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 8061 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); 8062 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits 8063 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1); 8064 return DAG.getNode(PPCISD::FSEL, dl, ResVT, 8065 DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV); 8066 case ISD::SETULT: 8067 case ISD::SETLT: 8068 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags); 8069 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 8070 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 8071 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV); 8072 case ISD::SETOGE: 8073 case ISD::SETGE: 8074 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags); 8075 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 8076 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 8077 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); 8078 case ISD::SETUGT: 8079 case ISD::SETGT: 8080 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags); 8081 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 8082 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 8083 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV); 8084 case ISD::SETOLE: 8085 case ISD::SETLE: 8086 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags); 8087 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 8088 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 8089 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); 8090 } 8091 return Op; 8092 } 8093 8094 void PPCTargetLowering::LowerFP_TO_INTForReuse(SDValue Op, ReuseLoadInfo &RLI, 8095 SelectionDAG &DAG, 8096 const SDLoc &dl) const { 8097 assert(Op.getOperand(0).getValueType().isFloatingPoint()); 8098 SDValue Src = Op.getOperand(0); 8099 if (Src.getValueType() == MVT::f32) 8100 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src); 8101 8102 SDValue Tmp; 8103 switch (Op.getSimpleValueType().SimpleTy) { 8104 default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!"); 8105 case MVT::i32: 8106 Tmp = DAG.getNode( 8107 Op.getOpcode() == ISD::FP_TO_SINT 8108 ? PPCISD::FCTIWZ 8109 : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ), 8110 dl, MVT::f64, Src); 8111 break; 8112 case MVT::i64: 8113 assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) && 8114 "i64 FP_TO_UINT is supported only with FPCVT"); 8115 Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ : 8116 PPCISD::FCTIDUZ, 8117 dl, MVT::f64, Src); 8118 break; 8119 } 8120 8121 // Convert the FP value to an int value through memory. 8122 bool i32Stack = Op.getValueType() == MVT::i32 && Subtarget.hasSTFIWX() && 8123 (Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()); 8124 SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64); 8125 int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex(); 8126 MachinePointerInfo MPI = 8127 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI); 8128 8129 // Emit a store to the stack slot. 8130 SDValue Chain; 8131 Align Alignment(DAG.getEVTAlign(Tmp.getValueType())); 8132 if (i32Stack) { 8133 MachineFunction &MF = DAG.getMachineFunction(); 8134 Alignment = Align(4); 8135 MachineMemOperand *MMO = 8136 MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, Alignment); 8137 SDValue Ops[] = { DAG.getEntryNode(), Tmp, FIPtr }; 8138 Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl, 8139 DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO); 8140 } else 8141 Chain = DAG.getStore(DAG.getEntryNode(), dl, Tmp, FIPtr, MPI, Alignment); 8142 8143 // Result is a load from the stack slot. If loading 4 bytes, make sure to 8144 // add in a bias on big endian. 8145 if (Op.getValueType() == MVT::i32 && !i32Stack) { 8146 FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr, 8147 DAG.getConstant(4, dl, FIPtr.getValueType())); 8148 MPI = MPI.getWithOffset(Subtarget.isLittleEndian() ? 0 : 4); 8149 } 8150 8151 RLI.Chain = Chain; 8152 RLI.Ptr = FIPtr; 8153 RLI.MPI = MPI; 8154 RLI.Alignment = Alignment; 8155 } 8156 8157 /// Custom lowers floating point to integer conversions to use 8158 /// the direct move instructions available in ISA 2.07 to avoid the 8159 /// need for load/store combinations. 8160 SDValue PPCTargetLowering::LowerFP_TO_INTDirectMove(SDValue Op, 8161 SelectionDAG &DAG, 8162 const SDLoc &dl) const { 8163 assert(Op.getOperand(0).getValueType().isFloatingPoint()); 8164 SDValue Src = Op.getOperand(0); 8165 8166 if (Src.getValueType() == MVT::f32) 8167 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src); 8168 8169 SDValue Tmp; 8170 switch (Op.getSimpleValueType().SimpleTy) { 8171 default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!"); 8172 case MVT::i32: 8173 Tmp = DAG.getNode( 8174 Op.getOpcode() == ISD::FP_TO_SINT 8175 ? PPCISD::FCTIWZ 8176 : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ), 8177 dl, MVT::f64, Src); 8178 Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i32, Tmp); 8179 break; 8180 case MVT::i64: 8181 assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) && 8182 "i64 FP_TO_UINT is supported only with FPCVT"); 8183 Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ : 8184 PPCISD::FCTIDUZ, 8185 dl, MVT::f64, Src); 8186 Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i64, Tmp); 8187 break; 8188 } 8189 return Tmp; 8190 } 8191 8192 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG, 8193 const SDLoc &dl) const { 8194 8195 // FP to INT conversions are legal for f128. 8196 if (EnableQuadPrecision && (Op->getOperand(0).getValueType() == MVT::f128)) 8197 return Op; 8198 8199 // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on 8200 // PPC (the libcall is not available). 8201 if (Op.getOperand(0).getValueType() == MVT::ppcf128) { 8202 if (Op.getValueType() == MVT::i32) { 8203 if (Op.getOpcode() == ISD::FP_TO_SINT) { 8204 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, 8205 MVT::f64, Op.getOperand(0), 8206 DAG.getIntPtrConstant(0, dl)); 8207 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, 8208 MVT::f64, Op.getOperand(0), 8209 DAG.getIntPtrConstant(1, dl)); 8210 8211 // Add the two halves of the long double in round-to-zero mode. 8212 SDValue Res = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi); 8213 8214 // Now use a smaller FP_TO_SINT. 8215 return DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Res); 8216 } 8217 if (Op.getOpcode() == ISD::FP_TO_UINT) { 8218 const uint64_t TwoE31[] = {0x41e0000000000000LL, 0}; 8219 APFloat APF = APFloat(APFloat::PPCDoubleDouble(), APInt(128, TwoE31)); 8220 SDValue Tmp = DAG.getConstantFP(APF, dl, MVT::ppcf128); 8221 // X>=2^31 ? (int)(X-2^31)+0x80000000 : (int)X 8222 // FIXME: generated code sucks. 8223 // TODO: Are there fast-math-flags to propagate to this FSUB? 8224 SDValue True = DAG.getNode(ISD::FSUB, dl, MVT::ppcf128, 8225 Op.getOperand(0), Tmp); 8226 True = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, True); 8227 True = DAG.getNode(ISD::ADD, dl, MVT::i32, True, 8228 DAG.getConstant(0x80000000, dl, MVT::i32)); 8229 SDValue False = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, 8230 Op.getOperand(0)); 8231 return DAG.getSelectCC(dl, Op.getOperand(0), Tmp, True, False, 8232 ISD::SETGE); 8233 } 8234 } 8235 8236 return SDValue(); 8237 } 8238 8239 if (Subtarget.hasDirectMove() && Subtarget.isPPC64()) 8240 return LowerFP_TO_INTDirectMove(Op, DAG, dl); 8241 8242 ReuseLoadInfo RLI; 8243 LowerFP_TO_INTForReuse(Op, RLI, DAG, dl); 8244 8245 return DAG.getLoad(Op.getValueType(), dl, RLI.Chain, RLI.Ptr, RLI.MPI, 8246 RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges); 8247 } 8248 8249 // We're trying to insert a regular store, S, and then a load, L. If the 8250 // incoming value, O, is a load, we might just be able to have our load use the 8251 // address used by O. However, we don't know if anything else will store to 8252 // that address before we can load from it. To prevent this situation, we need 8253 // to insert our load, L, into the chain as a peer of O. To do this, we give L 8254 // the same chain operand as O, we create a token factor from the chain results 8255 // of O and L, and we replace all uses of O's chain result with that token 8256 // factor (see spliceIntoChain below for this last part). 8257 bool PPCTargetLowering::canReuseLoadAddress(SDValue Op, EVT MemVT, 8258 ReuseLoadInfo &RLI, 8259 SelectionDAG &DAG, 8260 ISD::LoadExtType ET) const { 8261 SDLoc dl(Op); 8262 bool ValidFPToUint = Op.getOpcode() == ISD::FP_TO_UINT && 8263 (Subtarget.hasFPCVT() || Op.getValueType() == MVT::i32); 8264 if (ET == ISD::NON_EXTLOAD && 8265 (ValidFPToUint || Op.getOpcode() == ISD::FP_TO_SINT) && 8266 isOperationLegalOrCustom(Op.getOpcode(), 8267 Op.getOperand(0).getValueType())) { 8268 8269 LowerFP_TO_INTForReuse(Op, RLI, DAG, dl); 8270 return true; 8271 } 8272 8273 LoadSDNode *LD = dyn_cast<LoadSDNode>(Op); 8274 if (!LD || LD->getExtensionType() != ET || LD->isVolatile() || 8275 LD->isNonTemporal()) 8276 return false; 8277 if (LD->getMemoryVT() != MemVT) 8278 return false; 8279 8280 RLI.Ptr = LD->getBasePtr(); 8281 if (LD->isIndexed() && !LD->getOffset().isUndef()) { 8282 assert(LD->getAddressingMode() == ISD::PRE_INC && 8283 "Non-pre-inc AM on PPC?"); 8284 RLI.Ptr = DAG.getNode(ISD::ADD, dl, RLI.Ptr.getValueType(), RLI.Ptr, 8285 LD->getOffset()); 8286 } 8287 8288 RLI.Chain = LD->getChain(); 8289 RLI.MPI = LD->getPointerInfo(); 8290 RLI.IsDereferenceable = LD->isDereferenceable(); 8291 RLI.IsInvariant = LD->isInvariant(); 8292 RLI.Alignment = LD->getAlign(); 8293 RLI.AAInfo = LD->getAAInfo(); 8294 RLI.Ranges = LD->getRanges(); 8295 8296 RLI.ResChain = SDValue(LD, LD->isIndexed() ? 2 : 1); 8297 return true; 8298 } 8299 8300 // Given the head of the old chain, ResChain, insert a token factor containing 8301 // it and NewResChain, and make users of ResChain now be users of that token 8302 // factor. 8303 // TODO: Remove and use DAG::makeEquivalentMemoryOrdering() instead. 8304 void PPCTargetLowering::spliceIntoChain(SDValue ResChain, 8305 SDValue NewResChain, 8306 SelectionDAG &DAG) const { 8307 if (!ResChain) 8308 return; 8309 8310 SDLoc dl(NewResChain); 8311 8312 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 8313 NewResChain, DAG.getUNDEF(MVT::Other)); 8314 assert(TF.getNode() != NewResChain.getNode() && 8315 "A new TF really is required here"); 8316 8317 DAG.ReplaceAllUsesOfValueWith(ResChain, TF); 8318 DAG.UpdateNodeOperands(TF.getNode(), ResChain, NewResChain); 8319 } 8320 8321 /// Analyze profitability of direct move 8322 /// prefer float load to int load plus direct move 8323 /// when there is no integer use of int load 8324 bool PPCTargetLowering::directMoveIsProfitable(const SDValue &Op) const { 8325 SDNode *Origin = Op.getOperand(0).getNode(); 8326 if (Origin->getOpcode() != ISD::LOAD) 8327 return true; 8328 8329 // If there is no LXSIBZX/LXSIHZX, like Power8, 8330 // prefer direct move if the memory size is 1 or 2 bytes. 8331 MachineMemOperand *MMO = cast<LoadSDNode>(Origin)->getMemOperand(); 8332 if (!Subtarget.hasP9Vector() && MMO->getSize() <= 2) 8333 return true; 8334 8335 for (SDNode::use_iterator UI = Origin->use_begin(), 8336 UE = Origin->use_end(); 8337 UI != UE; ++UI) { 8338 8339 // Only look at the users of the loaded value. 8340 if (UI.getUse().get().getResNo() != 0) 8341 continue; 8342 8343 if (UI->getOpcode() != ISD::SINT_TO_FP && 8344 UI->getOpcode() != ISD::UINT_TO_FP) 8345 return true; 8346 } 8347 8348 return false; 8349 } 8350 8351 /// Custom lowers integer to floating point conversions to use 8352 /// the direct move instructions available in ISA 2.07 to avoid the 8353 /// need for load/store combinations. 8354 SDValue PPCTargetLowering::LowerINT_TO_FPDirectMove(SDValue Op, 8355 SelectionDAG &DAG, 8356 const SDLoc &dl) const { 8357 assert((Op.getValueType() == MVT::f32 || 8358 Op.getValueType() == MVT::f64) && 8359 "Invalid floating point type as target of conversion"); 8360 assert(Subtarget.hasFPCVT() && 8361 "Int to FP conversions with direct moves require FPCVT"); 8362 SDValue FP; 8363 SDValue Src = Op.getOperand(0); 8364 bool SinglePrec = Op.getValueType() == MVT::f32; 8365 bool WordInt = Src.getSimpleValueType().SimpleTy == MVT::i32; 8366 bool Signed = Op.getOpcode() == ISD::SINT_TO_FP; 8367 unsigned ConvOp = Signed ? (SinglePrec ? PPCISD::FCFIDS : PPCISD::FCFID) : 8368 (SinglePrec ? PPCISD::FCFIDUS : PPCISD::FCFIDU); 8369 8370 if (WordInt) { 8371 FP = DAG.getNode(Signed ? PPCISD::MTVSRA : PPCISD::MTVSRZ, 8372 dl, MVT::f64, Src); 8373 FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP); 8374 } 8375 else { 8376 FP = DAG.getNode(PPCISD::MTVSRA, dl, MVT::f64, Src); 8377 FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP); 8378 } 8379 8380 return FP; 8381 } 8382 8383 static SDValue widenVec(SelectionDAG &DAG, SDValue Vec, const SDLoc &dl) { 8384 8385 EVT VecVT = Vec.getValueType(); 8386 assert(VecVT.isVector() && "Expected a vector type."); 8387 assert(VecVT.getSizeInBits() < 128 && "Vector is already full width."); 8388 8389 EVT EltVT = VecVT.getVectorElementType(); 8390 unsigned WideNumElts = 128 / EltVT.getSizeInBits(); 8391 EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts); 8392 8393 unsigned NumConcat = WideNumElts / VecVT.getVectorNumElements(); 8394 SmallVector<SDValue, 16> Ops(NumConcat); 8395 Ops[0] = Vec; 8396 SDValue UndefVec = DAG.getUNDEF(VecVT); 8397 for (unsigned i = 1; i < NumConcat; ++i) 8398 Ops[i] = UndefVec; 8399 8400 return DAG.getNode(ISD::CONCAT_VECTORS, dl, WideVT, Ops); 8401 } 8402 8403 SDValue PPCTargetLowering::LowerINT_TO_FPVector(SDValue Op, SelectionDAG &DAG, 8404 const SDLoc &dl) const { 8405 8406 unsigned Opc = Op.getOpcode(); 8407 assert((Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP) && 8408 "Unexpected conversion type"); 8409 assert((Op.getValueType() == MVT::v2f64 || Op.getValueType() == MVT::v4f32) && 8410 "Supports conversions to v2f64/v4f32 only."); 8411 8412 bool SignedConv = Opc == ISD::SINT_TO_FP; 8413 bool FourEltRes = Op.getValueType() == MVT::v4f32; 8414 8415 SDValue Wide = widenVec(DAG, Op.getOperand(0), dl); 8416 EVT WideVT = Wide.getValueType(); 8417 unsigned WideNumElts = WideVT.getVectorNumElements(); 8418 MVT IntermediateVT = FourEltRes ? MVT::v4i32 : MVT::v2i64; 8419 8420 SmallVector<int, 16> ShuffV; 8421 for (unsigned i = 0; i < WideNumElts; ++i) 8422 ShuffV.push_back(i + WideNumElts); 8423 8424 int Stride = FourEltRes ? WideNumElts / 4 : WideNumElts / 2; 8425 int SaveElts = FourEltRes ? 4 : 2; 8426 if (Subtarget.isLittleEndian()) 8427 for (int i = 0; i < SaveElts; i++) 8428 ShuffV[i * Stride] = i; 8429 else 8430 for (int i = 1; i <= SaveElts; i++) 8431 ShuffV[i * Stride - 1] = i - 1; 8432 8433 SDValue ShuffleSrc2 = 8434 SignedConv ? DAG.getUNDEF(WideVT) : DAG.getConstant(0, dl, WideVT); 8435 SDValue Arrange = DAG.getVectorShuffle(WideVT, dl, Wide, ShuffleSrc2, ShuffV); 8436 8437 SDValue Extend; 8438 if (SignedConv) { 8439 Arrange = DAG.getBitcast(IntermediateVT, Arrange); 8440 EVT ExtVT = Op.getOperand(0).getValueType(); 8441 if (Subtarget.hasP9Altivec()) 8442 ExtVT = EVT::getVectorVT(*DAG.getContext(), WideVT.getVectorElementType(), 8443 IntermediateVT.getVectorNumElements()); 8444 8445 Extend = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, IntermediateVT, Arrange, 8446 DAG.getValueType(ExtVT)); 8447 } else 8448 Extend = DAG.getNode(ISD::BITCAST, dl, IntermediateVT, Arrange); 8449 8450 return DAG.getNode(Opc, dl, Op.getValueType(), Extend); 8451 } 8452 8453 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op, 8454 SelectionDAG &DAG) const { 8455 SDLoc dl(Op); 8456 8457 EVT InVT = Op.getOperand(0).getValueType(); 8458 EVT OutVT = Op.getValueType(); 8459 if (OutVT.isVector() && OutVT.isFloatingPoint() && 8460 isOperationCustom(Op.getOpcode(), InVT)) 8461 return LowerINT_TO_FPVector(Op, DAG, dl); 8462 8463 // Conversions to f128 are legal. 8464 if (EnableQuadPrecision && (Op.getValueType() == MVT::f128)) 8465 return Op; 8466 8467 if (Subtarget.hasQPX() && Op.getOperand(0).getValueType() == MVT::v4i1) { 8468 if (Op.getValueType() != MVT::v4f32 && Op.getValueType() != MVT::v4f64) 8469 return SDValue(); 8470 8471 SDValue Value = Op.getOperand(0); 8472 // The values are now known to be -1 (false) or 1 (true). To convert this 8473 // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5). 8474 // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5 8475 Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value); 8476 8477 SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64); 8478 8479 Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs); 8480 8481 if (Op.getValueType() != MVT::v4f64) 8482 Value = DAG.getNode(ISD::FP_ROUND, dl, 8483 Op.getValueType(), Value, 8484 DAG.getIntPtrConstant(1, dl)); 8485 return Value; 8486 } 8487 8488 // Don't handle ppc_fp128 here; let it be lowered to a libcall. 8489 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64) 8490 return SDValue(); 8491 8492 if (Op.getOperand(0).getValueType() == MVT::i1) 8493 return DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Op.getOperand(0), 8494 DAG.getConstantFP(1.0, dl, Op.getValueType()), 8495 DAG.getConstantFP(0.0, dl, Op.getValueType())); 8496 8497 // If we have direct moves, we can do all the conversion, skip the store/load 8498 // however, without FPCVT we can't do most conversions. 8499 if (Subtarget.hasDirectMove() && directMoveIsProfitable(Op) && 8500 Subtarget.isPPC64() && Subtarget.hasFPCVT()) 8501 return LowerINT_TO_FPDirectMove(Op, DAG, dl); 8502 8503 assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) && 8504 "UINT_TO_FP is supported only with FPCVT"); 8505 8506 // If we have FCFIDS, then use it when converting to single-precision. 8507 // Otherwise, convert to double-precision and then round. 8508 unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 8509 ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS 8510 : PPCISD::FCFIDS) 8511 : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU 8512 : PPCISD::FCFID); 8513 MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 8514 ? MVT::f32 8515 : MVT::f64; 8516 8517 if (Op.getOperand(0).getValueType() == MVT::i64) { 8518 SDValue SINT = Op.getOperand(0); 8519 // When converting to single-precision, we actually need to convert 8520 // to double-precision first and then round to single-precision. 8521 // To avoid double-rounding effects during that operation, we have 8522 // to prepare the input operand. Bits that might be truncated when 8523 // converting to double-precision are replaced by a bit that won't 8524 // be lost at this stage, but is below the single-precision rounding 8525 // position. 8526 // 8527 // However, if -enable-unsafe-fp-math is in effect, accept double 8528 // rounding to avoid the extra overhead. 8529 if (Op.getValueType() == MVT::f32 && 8530 !Subtarget.hasFPCVT() && 8531 !DAG.getTarget().Options.UnsafeFPMath) { 8532 8533 // Twiddle input to make sure the low 11 bits are zero. (If this 8534 // is the case, we are guaranteed the value will fit into the 53 bit 8535 // mantissa of an IEEE double-precision value without rounding.) 8536 // If any of those low 11 bits were not zero originally, make sure 8537 // bit 12 (value 2048) is set instead, so that the final rounding 8538 // to single-precision gets the correct result. 8539 SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64, 8540 SINT, DAG.getConstant(2047, dl, MVT::i64)); 8541 Round = DAG.getNode(ISD::ADD, dl, MVT::i64, 8542 Round, DAG.getConstant(2047, dl, MVT::i64)); 8543 Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT); 8544 Round = DAG.getNode(ISD::AND, dl, MVT::i64, 8545 Round, DAG.getConstant(-2048, dl, MVT::i64)); 8546 8547 // However, we cannot use that value unconditionally: if the magnitude 8548 // of the input value is small, the bit-twiddling we did above might 8549 // end up visibly changing the output. Fortunately, in that case, we 8550 // don't need to twiddle bits since the original input will convert 8551 // exactly to double-precision floating-point already. Therefore, 8552 // construct a conditional to use the original value if the top 11 8553 // bits are all sign-bit copies, and use the rounded value computed 8554 // above otherwise. 8555 SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64, 8556 SINT, DAG.getConstant(53, dl, MVT::i32)); 8557 Cond = DAG.getNode(ISD::ADD, dl, MVT::i64, 8558 Cond, DAG.getConstant(1, dl, MVT::i64)); 8559 Cond = DAG.getSetCC( 8560 dl, 8561 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::i64), 8562 Cond, DAG.getConstant(1, dl, MVT::i64), ISD::SETUGT); 8563 8564 SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT); 8565 } 8566 8567 ReuseLoadInfo RLI; 8568 SDValue Bits; 8569 8570 MachineFunction &MF = DAG.getMachineFunction(); 8571 if (canReuseLoadAddress(SINT, MVT::i64, RLI, DAG)) { 8572 Bits = DAG.getLoad(MVT::f64, dl, RLI.Chain, RLI.Ptr, RLI.MPI, 8573 RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges); 8574 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG); 8575 } else if (Subtarget.hasLFIWAX() && 8576 canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::SEXTLOAD)) { 8577 MachineMemOperand *MMO = 8578 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 8579 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 8580 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 8581 Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWAX, dl, 8582 DAG.getVTList(MVT::f64, MVT::Other), 8583 Ops, MVT::i32, MMO); 8584 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG); 8585 } else if (Subtarget.hasFPCVT() && 8586 canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::ZEXTLOAD)) { 8587 MachineMemOperand *MMO = 8588 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 8589 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 8590 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 8591 Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWZX, dl, 8592 DAG.getVTList(MVT::f64, MVT::Other), 8593 Ops, MVT::i32, MMO); 8594 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG); 8595 } else if (((Subtarget.hasLFIWAX() && 8596 SINT.getOpcode() == ISD::SIGN_EXTEND) || 8597 (Subtarget.hasFPCVT() && 8598 SINT.getOpcode() == ISD::ZERO_EXTEND)) && 8599 SINT.getOperand(0).getValueType() == MVT::i32) { 8600 MachineFrameInfo &MFI = MF.getFrameInfo(); 8601 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 8602 8603 int FrameIdx = MFI.CreateStackObject(4, 4, false); 8604 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 8605 8606 SDValue Store = 8607 DAG.getStore(DAG.getEntryNode(), dl, SINT.getOperand(0), FIdx, 8608 MachinePointerInfo::getFixedStack( 8609 DAG.getMachineFunction(), FrameIdx)); 8610 8611 assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 && 8612 "Expected an i32 store"); 8613 8614 RLI.Ptr = FIdx; 8615 RLI.Chain = Store; 8616 RLI.MPI = 8617 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 8618 RLI.Alignment = Align(4); 8619 8620 MachineMemOperand *MMO = 8621 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 8622 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 8623 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 8624 Bits = DAG.getMemIntrinsicNode(SINT.getOpcode() == ISD::ZERO_EXTEND ? 8625 PPCISD::LFIWZX : PPCISD::LFIWAX, 8626 dl, DAG.getVTList(MVT::f64, MVT::Other), 8627 Ops, MVT::i32, MMO); 8628 } else 8629 Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT); 8630 8631 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Bits); 8632 8633 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) 8634 FP = DAG.getNode(ISD::FP_ROUND, dl, 8635 MVT::f32, FP, DAG.getIntPtrConstant(0, dl)); 8636 return FP; 8637 } 8638 8639 assert(Op.getOperand(0).getValueType() == MVT::i32 && 8640 "Unhandled INT_TO_FP type in custom expander!"); 8641 // Since we only generate this in 64-bit mode, we can take advantage of 8642 // 64-bit registers. In particular, sign extend the input value into the 8643 // 64-bit register with extsw, store the WHOLE 64-bit value into the stack 8644 // then lfd it and fcfid it. 8645 MachineFunction &MF = DAG.getMachineFunction(); 8646 MachineFrameInfo &MFI = MF.getFrameInfo(); 8647 EVT PtrVT = getPointerTy(MF.getDataLayout()); 8648 8649 SDValue Ld; 8650 if (Subtarget.hasLFIWAX() || Subtarget.hasFPCVT()) { 8651 ReuseLoadInfo RLI; 8652 bool ReusingLoad; 8653 if (!(ReusingLoad = canReuseLoadAddress(Op.getOperand(0), MVT::i32, RLI, 8654 DAG))) { 8655 int FrameIdx = MFI.CreateStackObject(4, 4, false); 8656 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 8657 8658 SDValue Store = 8659 DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx, 8660 MachinePointerInfo::getFixedStack( 8661 DAG.getMachineFunction(), FrameIdx)); 8662 8663 assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 && 8664 "Expected an i32 store"); 8665 8666 RLI.Ptr = FIdx; 8667 RLI.Chain = Store; 8668 RLI.MPI = 8669 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 8670 RLI.Alignment = Align(4); 8671 } 8672 8673 MachineMemOperand *MMO = 8674 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 8675 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 8676 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 8677 Ld = DAG.getMemIntrinsicNode(Op.getOpcode() == ISD::UINT_TO_FP ? 8678 PPCISD::LFIWZX : PPCISD::LFIWAX, 8679 dl, DAG.getVTList(MVT::f64, MVT::Other), 8680 Ops, MVT::i32, MMO); 8681 if (ReusingLoad) 8682 spliceIntoChain(RLI.ResChain, Ld.getValue(1), DAG); 8683 } else { 8684 assert(Subtarget.isPPC64() && 8685 "i32->FP without LFIWAX supported only on PPC64"); 8686 8687 int FrameIdx = MFI.CreateStackObject(8, 8, false); 8688 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 8689 8690 SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64, 8691 Op.getOperand(0)); 8692 8693 // STD the extended value into the stack slot. 8694 SDValue Store = DAG.getStore( 8695 DAG.getEntryNode(), dl, Ext64, FIdx, 8696 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx)); 8697 8698 // Load the value as a double. 8699 Ld = DAG.getLoad( 8700 MVT::f64, dl, Store, FIdx, 8701 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx)); 8702 } 8703 8704 // FCFID it and return it. 8705 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Ld); 8706 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) 8707 FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP, 8708 DAG.getIntPtrConstant(0, dl)); 8709 return FP; 8710 } 8711 8712 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op, 8713 SelectionDAG &DAG) const { 8714 SDLoc dl(Op); 8715 /* 8716 The rounding mode is in bits 30:31 of FPSR, and has the following 8717 settings: 8718 00 Round to nearest 8719 01 Round to 0 8720 10 Round to +inf 8721 11 Round to -inf 8722 8723 FLT_ROUNDS, on the other hand, expects the following: 8724 -1 Undefined 8725 0 Round to 0 8726 1 Round to nearest 8727 2 Round to +inf 8728 3 Round to -inf 8729 8730 To perform the conversion, we do: 8731 ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1)) 8732 */ 8733 8734 MachineFunction &MF = DAG.getMachineFunction(); 8735 EVT VT = Op.getValueType(); 8736 EVT PtrVT = getPointerTy(MF.getDataLayout()); 8737 8738 // Save FP Control Word to register 8739 SDValue Chain = Op.getOperand(0); 8740 SDValue MFFS = DAG.getNode(PPCISD::MFFS, dl, {MVT::f64, MVT::Other}, Chain); 8741 Chain = MFFS.getValue(1); 8742 8743 // Save FP register to stack slot 8744 int SSFI = MF.getFrameInfo().CreateStackObject(8, 8, false); 8745 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT); 8746 Chain = DAG.getStore(Chain, dl, MFFS, StackSlot, MachinePointerInfo()); 8747 8748 // Load FP Control Word from low 32 bits of stack slot. 8749 SDValue Four = DAG.getConstant(4, dl, PtrVT); 8750 SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four); 8751 SDValue CWD = DAG.getLoad(MVT::i32, dl, Chain, Addr, MachinePointerInfo()); 8752 Chain = CWD.getValue(1); 8753 8754 // Transform as necessary 8755 SDValue CWD1 = 8756 DAG.getNode(ISD::AND, dl, MVT::i32, 8757 CWD, DAG.getConstant(3, dl, MVT::i32)); 8758 SDValue CWD2 = 8759 DAG.getNode(ISD::SRL, dl, MVT::i32, 8760 DAG.getNode(ISD::AND, dl, MVT::i32, 8761 DAG.getNode(ISD::XOR, dl, MVT::i32, 8762 CWD, DAG.getConstant(3, dl, MVT::i32)), 8763 DAG.getConstant(3, dl, MVT::i32)), 8764 DAG.getConstant(1, dl, MVT::i32)); 8765 8766 SDValue RetVal = 8767 DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2); 8768 8769 RetVal = 8770 DAG.getNode((VT.getSizeInBits() < 16 ? ISD::TRUNCATE : ISD::ZERO_EXTEND), 8771 dl, VT, RetVal); 8772 8773 return DAG.getMergeValues({RetVal, Chain}, dl); 8774 } 8775 8776 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const { 8777 EVT VT = Op.getValueType(); 8778 unsigned BitWidth = VT.getSizeInBits(); 8779 SDLoc dl(Op); 8780 assert(Op.getNumOperands() == 3 && 8781 VT == Op.getOperand(1).getValueType() && 8782 "Unexpected SHL!"); 8783 8784 // Expand into a bunch of logical ops. Note that these ops 8785 // depend on the PPC behavior for oversized shift amounts. 8786 SDValue Lo = Op.getOperand(0); 8787 SDValue Hi = Op.getOperand(1); 8788 SDValue Amt = Op.getOperand(2); 8789 EVT AmtVT = Amt.getValueType(); 8790 8791 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, 8792 DAG.getConstant(BitWidth, dl, AmtVT), Amt); 8793 SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt); 8794 SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1); 8795 SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3); 8796 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, 8797 DAG.getConstant(-BitWidth, dl, AmtVT)); 8798 SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5); 8799 SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6); 8800 SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt); 8801 SDValue OutOps[] = { OutLo, OutHi }; 8802 return DAG.getMergeValues(OutOps, dl); 8803 } 8804 8805 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const { 8806 EVT VT = Op.getValueType(); 8807 SDLoc dl(Op); 8808 unsigned BitWidth = VT.getSizeInBits(); 8809 assert(Op.getNumOperands() == 3 && 8810 VT == Op.getOperand(1).getValueType() && 8811 "Unexpected SRL!"); 8812 8813 // Expand into a bunch of logical ops. Note that these ops 8814 // depend on the PPC behavior for oversized shift amounts. 8815 SDValue Lo = Op.getOperand(0); 8816 SDValue Hi = Op.getOperand(1); 8817 SDValue Amt = Op.getOperand(2); 8818 EVT AmtVT = Amt.getValueType(); 8819 8820 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, 8821 DAG.getConstant(BitWidth, dl, AmtVT), Amt); 8822 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt); 8823 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1); 8824 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3); 8825 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, 8826 DAG.getConstant(-BitWidth, dl, AmtVT)); 8827 SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5); 8828 SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6); 8829 SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt); 8830 SDValue OutOps[] = { OutLo, OutHi }; 8831 return DAG.getMergeValues(OutOps, dl); 8832 } 8833 8834 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const { 8835 SDLoc dl(Op); 8836 EVT VT = Op.getValueType(); 8837 unsigned BitWidth = VT.getSizeInBits(); 8838 assert(Op.getNumOperands() == 3 && 8839 VT == Op.getOperand(1).getValueType() && 8840 "Unexpected SRA!"); 8841 8842 // Expand into a bunch of logical ops, followed by a select_cc. 8843 SDValue Lo = Op.getOperand(0); 8844 SDValue Hi = Op.getOperand(1); 8845 SDValue Amt = Op.getOperand(2); 8846 EVT AmtVT = Amt.getValueType(); 8847 8848 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, 8849 DAG.getConstant(BitWidth, dl, AmtVT), Amt); 8850 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt); 8851 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1); 8852 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3); 8853 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, 8854 DAG.getConstant(-BitWidth, dl, AmtVT)); 8855 SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5); 8856 SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt); 8857 SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, dl, AmtVT), 8858 Tmp4, Tmp6, ISD::SETLE); 8859 SDValue OutOps[] = { OutLo, OutHi }; 8860 return DAG.getMergeValues(OutOps, dl); 8861 } 8862 8863 //===----------------------------------------------------------------------===// 8864 // Vector related lowering. 8865 // 8866 8867 /// BuildSplatI - Build a canonical splati of Val with an element size of 8868 /// SplatSize. Cast the result to VT. 8869 static SDValue BuildSplatI(int Val, unsigned SplatSize, EVT VT, 8870 SelectionDAG &DAG, const SDLoc &dl) { 8871 static const MVT VTys[] = { // canonical VT to use for each size. 8872 MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32 8873 }; 8874 8875 EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1]; 8876 8877 // Force vspltis[hw] -1 to vspltisb -1 to canonicalize. 8878 if (Val == -1) 8879 SplatSize = 1; 8880 8881 EVT CanonicalVT = VTys[SplatSize-1]; 8882 8883 // Build a canonical splat for this value. 8884 return DAG.getBitcast(ReqVT, DAG.getConstant(Val, dl, CanonicalVT)); 8885 } 8886 8887 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the 8888 /// specified intrinsic ID. 8889 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op, SelectionDAG &DAG, 8890 const SDLoc &dl, EVT DestVT = MVT::Other) { 8891 if (DestVT == MVT::Other) DestVT = Op.getValueType(); 8892 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 8893 DAG.getConstant(IID, dl, MVT::i32), Op); 8894 } 8895 8896 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the 8897 /// specified intrinsic ID. 8898 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS, 8899 SelectionDAG &DAG, const SDLoc &dl, 8900 EVT DestVT = MVT::Other) { 8901 if (DestVT == MVT::Other) DestVT = LHS.getValueType(); 8902 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 8903 DAG.getConstant(IID, dl, MVT::i32), LHS, RHS); 8904 } 8905 8906 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the 8907 /// specified intrinsic ID. 8908 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1, 8909 SDValue Op2, SelectionDAG &DAG, const SDLoc &dl, 8910 EVT DestVT = MVT::Other) { 8911 if (DestVT == MVT::Other) DestVT = Op0.getValueType(); 8912 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 8913 DAG.getConstant(IID, dl, MVT::i32), Op0, Op1, Op2); 8914 } 8915 8916 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified 8917 /// amount. The result has the specified value type. 8918 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt, EVT VT, 8919 SelectionDAG &DAG, const SDLoc &dl) { 8920 // Force LHS/RHS to be the right type. 8921 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS); 8922 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS); 8923 8924 int Ops[16]; 8925 for (unsigned i = 0; i != 16; ++i) 8926 Ops[i] = i + Amt; 8927 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops); 8928 return DAG.getNode(ISD::BITCAST, dl, VT, T); 8929 } 8930 8931 /// Do we have an efficient pattern in a .td file for this node? 8932 /// 8933 /// \param V - pointer to the BuildVectorSDNode being matched 8934 /// \param HasDirectMove - does this subtarget have VSR <-> GPR direct moves? 8935 /// 8936 /// There are some patterns where it is beneficial to keep a BUILD_VECTOR 8937 /// node as a BUILD_VECTOR node rather than expanding it. The patterns where 8938 /// the opposite is true (expansion is beneficial) are: 8939 /// - The node builds a vector out of integers that are not 32 or 64-bits 8940 /// - The node builds a vector out of constants 8941 /// - The node is a "load-and-splat" 8942 /// In all other cases, we will choose to keep the BUILD_VECTOR. 8943 static bool haveEfficientBuildVectorPattern(BuildVectorSDNode *V, 8944 bool HasDirectMove, 8945 bool HasP8Vector) { 8946 EVT VecVT = V->getValueType(0); 8947 bool RightType = VecVT == MVT::v2f64 || 8948 (HasP8Vector && VecVT == MVT::v4f32) || 8949 (HasDirectMove && (VecVT == MVT::v2i64 || VecVT == MVT::v4i32)); 8950 if (!RightType) 8951 return false; 8952 8953 bool IsSplat = true; 8954 bool IsLoad = false; 8955 SDValue Op0 = V->getOperand(0); 8956 8957 // This function is called in a block that confirms the node is not a constant 8958 // splat. So a constant BUILD_VECTOR here means the vector is built out of 8959 // different constants. 8960 if (V->isConstant()) 8961 return false; 8962 for (int i = 0, e = V->getNumOperands(); i < e; ++i) { 8963 if (V->getOperand(i).isUndef()) 8964 return false; 8965 // We want to expand nodes that represent load-and-splat even if the 8966 // loaded value is a floating point truncation or conversion to int. 8967 if (V->getOperand(i).getOpcode() == ISD::LOAD || 8968 (V->getOperand(i).getOpcode() == ISD::FP_ROUND && 8969 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) || 8970 (V->getOperand(i).getOpcode() == ISD::FP_TO_SINT && 8971 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) || 8972 (V->getOperand(i).getOpcode() == ISD::FP_TO_UINT && 8973 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD)) 8974 IsLoad = true; 8975 // If the operands are different or the input is not a load and has more 8976 // uses than just this BV node, then it isn't a splat. 8977 if (V->getOperand(i) != Op0 || 8978 (!IsLoad && !V->isOnlyUserOf(V->getOperand(i).getNode()))) 8979 IsSplat = false; 8980 } 8981 return !(IsSplat && IsLoad); 8982 } 8983 8984 // Lower BITCAST(f128, (build_pair i64, i64)) to BUILD_FP128. 8985 SDValue PPCTargetLowering::LowerBITCAST(SDValue Op, SelectionDAG &DAG) const { 8986 8987 SDLoc dl(Op); 8988 SDValue Op0 = Op->getOperand(0); 8989 8990 if (!EnableQuadPrecision || 8991 (Op.getValueType() != MVT::f128 ) || 8992 (Op0.getOpcode() != ISD::BUILD_PAIR) || 8993 (Op0.getOperand(0).getValueType() != MVT::i64) || 8994 (Op0.getOperand(1).getValueType() != MVT::i64)) 8995 return SDValue(); 8996 8997 return DAG.getNode(PPCISD::BUILD_FP128, dl, MVT::f128, Op0.getOperand(0), 8998 Op0.getOperand(1)); 8999 } 9000 9001 static const SDValue *getNormalLoadInput(const SDValue &Op) { 9002 const SDValue *InputLoad = &Op; 9003 if (InputLoad->getOpcode() == ISD::BITCAST) 9004 InputLoad = &InputLoad->getOperand(0); 9005 if (InputLoad->getOpcode() == ISD::SCALAR_TO_VECTOR) 9006 InputLoad = &InputLoad->getOperand(0); 9007 if (InputLoad->getOpcode() != ISD::LOAD) 9008 return nullptr; 9009 LoadSDNode *LD = cast<LoadSDNode>(*InputLoad); 9010 return ISD::isNormalLoad(LD) ? InputLoad : nullptr; 9011 } 9012 9013 // If this is a case we can't handle, return null and let the default 9014 // expansion code take care of it. If we CAN select this case, and if it 9015 // selects to a single instruction, return Op. Otherwise, if we can codegen 9016 // this case more efficiently than a constant pool load, lower it to the 9017 // sequence of ops that should be used. 9018 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op, 9019 SelectionDAG &DAG) const { 9020 SDLoc dl(Op); 9021 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode()); 9022 assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR"); 9023 9024 if (Subtarget.hasQPX() && Op.getValueType() == MVT::v4i1) { 9025 // We first build an i32 vector, load it into a QPX register, 9026 // then convert it to a floating-point vector and compare it 9027 // to a zero vector to get the boolean result. 9028 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 9029 int FrameIdx = MFI.CreateStackObject(16, 16, false); 9030 MachinePointerInfo PtrInfo = 9031 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 9032 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 9033 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 9034 9035 assert(BVN->getNumOperands() == 4 && 9036 "BUILD_VECTOR for v4i1 does not have 4 operands"); 9037 9038 bool IsConst = true; 9039 for (unsigned i = 0; i < 4; ++i) { 9040 if (BVN->getOperand(i).isUndef()) continue; 9041 if (!isa<ConstantSDNode>(BVN->getOperand(i))) { 9042 IsConst = false; 9043 break; 9044 } 9045 } 9046 9047 if (IsConst) { 9048 Constant *One = 9049 ConstantFP::get(Type::getFloatTy(*DAG.getContext()), 1.0); 9050 Constant *NegOne = 9051 ConstantFP::get(Type::getFloatTy(*DAG.getContext()), -1.0); 9052 9053 Constant *CV[4]; 9054 for (unsigned i = 0; i < 4; ++i) { 9055 if (BVN->getOperand(i).isUndef()) 9056 CV[i] = UndefValue::get(Type::getFloatTy(*DAG.getContext())); 9057 else if (isNullConstant(BVN->getOperand(i))) 9058 CV[i] = NegOne; 9059 else 9060 CV[i] = One; 9061 } 9062 9063 Constant *CP = ConstantVector::get(CV); 9064 SDValue CPIdx = 9065 DAG.getConstantPool(CP, getPointerTy(DAG.getDataLayout()), Align(16)); 9066 9067 SDValue Ops[] = {DAG.getEntryNode(), CPIdx}; 9068 SDVTList VTs = DAG.getVTList({MVT::v4i1, /*chain*/ MVT::Other}); 9069 return DAG.getMemIntrinsicNode( 9070 PPCISD::QVLFSb, dl, VTs, Ops, MVT::v4f32, 9071 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 9072 } 9073 9074 SmallVector<SDValue, 4> Stores; 9075 for (unsigned i = 0; i < 4; ++i) { 9076 if (BVN->getOperand(i).isUndef()) continue; 9077 9078 unsigned Offset = 4*i; 9079 SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType()); 9080 Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx); 9081 9082 unsigned StoreSize = BVN->getOperand(i).getValueType().getStoreSize(); 9083 if (StoreSize > 4) { 9084 Stores.push_back( 9085 DAG.getTruncStore(DAG.getEntryNode(), dl, BVN->getOperand(i), Idx, 9086 PtrInfo.getWithOffset(Offset), MVT::i32)); 9087 } else { 9088 SDValue StoreValue = BVN->getOperand(i); 9089 if (StoreSize < 4) 9090 StoreValue = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, StoreValue); 9091 9092 Stores.push_back(DAG.getStore(DAG.getEntryNode(), dl, StoreValue, Idx, 9093 PtrInfo.getWithOffset(Offset))); 9094 } 9095 } 9096 9097 SDValue StoreChain; 9098 if (!Stores.empty()) 9099 StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores); 9100 else 9101 StoreChain = DAG.getEntryNode(); 9102 9103 // Now load from v4i32 into the QPX register; this will extend it to 9104 // v4i64 but not yet convert it to a floating point. Nevertheless, this 9105 // is typed as v4f64 because the QPX register integer states are not 9106 // explicitly represented. 9107 9108 SDValue Ops[] = {StoreChain, 9109 DAG.getConstant(Intrinsic::ppc_qpx_qvlfiwz, dl, MVT::i32), 9110 FIdx}; 9111 SDVTList VTs = DAG.getVTList({MVT::v4f64, /*chain*/ MVT::Other}); 9112 9113 SDValue LoadedVect = DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, 9114 dl, VTs, Ops, MVT::v4i32, PtrInfo); 9115 LoadedVect = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64, 9116 DAG.getConstant(Intrinsic::ppc_qpx_qvfcfidu, dl, MVT::i32), 9117 LoadedVect); 9118 9119 SDValue FPZeros = DAG.getConstantFP(0.0, dl, MVT::v4f64); 9120 9121 return DAG.getSetCC(dl, MVT::v4i1, LoadedVect, FPZeros, ISD::SETEQ); 9122 } 9123 9124 // All other QPX vectors are handled by generic code. 9125 if (Subtarget.hasQPX()) 9126 return SDValue(); 9127 9128 // Check if this is a splat of a constant value. 9129 APInt APSplatBits, APSplatUndef; 9130 unsigned SplatBitSize; 9131 bool HasAnyUndefs; 9132 if (! BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize, 9133 HasAnyUndefs, 0, !Subtarget.isLittleEndian()) || 9134 SplatBitSize > 32) { 9135 9136 const SDValue *InputLoad = getNormalLoadInput(Op.getOperand(0)); 9137 // Handle load-and-splat patterns as we have instructions that will do this 9138 // in one go. 9139 if (InputLoad && DAG.isSplatValue(Op, true)) { 9140 LoadSDNode *LD = cast<LoadSDNode>(*InputLoad); 9141 9142 // We have handling for 4 and 8 byte elements. 9143 unsigned ElementSize = LD->getMemoryVT().getScalarSizeInBits(); 9144 9145 // Checking for a single use of this load, we have to check for vector 9146 // width (128 bits) / ElementSize uses (since each operand of the 9147 // BUILD_VECTOR is a separate use of the value. 9148 if (InputLoad->getNode()->hasNUsesOfValue(128 / ElementSize, 0) && 9149 ((Subtarget.hasVSX() && ElementSize == 64) || 9150 (Subtarget.hasP9Vector() && ElementSize == 32))) { 9151 SDValue Ops[] = { 9152 LD->getChain(), // Chain 9153 LD->getBasePtr(), // Ptr 9154 DAG.getValueType(Op.getValueType()) // VT 9155 }; 9156 return 9157 DAG.getMemIntrinsicNode(PPCISD::LD_SPLAT, dl, 9158 DAG.getVTList(Op.getValueType(), MVT::Other), 9159 Ops, LD->getMemoryVT(), LD->getMemOperand()); 9160 } 9161 } 9162 9163 // BUILD_VECTOR nodes that are not constant splats of up to 32-bits can be 9164 // lowered to VSX instructions under certain conditions. 9165 // Without VSX, there is no pattern more efficient than expanding the node. 9166 if (Subtarget.hasVSX() && 9167 haveEfficientBuildVectorPattern(BVN, Subtarget.hasDirectMove(), 9168 Subtarget.hasP8Vector())) 9169 return Op; 9170 return SDValue(); 9171 } 9172 9173 unsigned SplatBits = APSplatBits.getZExtValue(); 9174 unsigned SplatUndef = APSplatUndef.getZExtValue(); 9175 unsigned SplatSize = SplatBitSize / 8; 9176 9177 // First, handle single instruction cases. 9178 9179 // All zeros? 9180 if (SplatBits == 0) { 9181 // Canonicalize all zero vectors to be v4i32. 9182 if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) { 9183 SDValue Z = DAG.getConstant(0, dl, MVT::v4i32); 9184 Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z); 9185 } 9186 return Op; 9187 } 9188 9189 // We have XXSPLTIB for constant splats one byte wide 9190 // FIXME: SplatBits is an unsigned int being cast to an int while passing it 9191 // as an argument to BuildSplatiI. Given SplatSize == 1 it is okay here. 9192 if (Subtarget.hasP9Vector() && SplatSize == 1) 9193 return BuildSplatI(SplatBits, SplatSize, Op.getValueType(), DAG, dl); 9194 9195 // If the sign extended value is in the range [-16,15], use VSPLTI[bhw]. 9196 int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >> 9197 (32-SplatBitSize)); 9198 if (SextVal >= -16 && SextVal <= 15) 9199 return BuildSplatI(SextVal, SplatSize, Op.getValueType(), DAG, dl); 9200 9201 // Two instruction sequences. 9202 9203 // If this value is in the range [-32,30] and is even, use: 9204 // VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2) 9205 // If this value is in the range [17,31] and is odd, use: 9206 // VSPLTI[bhw](val-16) - VSPLTI[bhw](-16) 9207 // If this value is in the range [-31,-17] and is odd, use: 9208 // VSPLTI[bhw](val+16) + VSPLTI[bhw](-16) 9209 // Note the last two are three-instruction sequences. 9210 if (SextVal >= -32 && SextVal <= 31) { 9211 // To avoid having these optimizations undone by constant folding, 9212 // we convert to a pseudo that will be expanded later into one of 9213 // the above forms. 9214 SDValue Elt = DAG.getConstant(SextVal, dl, MVT::i32); 9215 EVT VT = (SplatSize == 1 ? MVT::v16i8 : 9216 (SplatSize == 2 ? MVT::v8i16 : MVT::v4i32)); 9217 SDValue EltSize = DAG.getConstant(SplatSize, dl, MVT::i32); 9218 SDValue RetVal = DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize); 9219 if (VT == Op.getValueType()) 9220 return RetVal; 9221 else 9222 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), RetVal); 9223 } 9224 9225 // If this is 0x8000_0000 x 4, turn into vspltisw + vslw. If it is 9226 // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000). This is important 9227 // for fneg/fabs. 9228 if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) { 9229 // Make -1 and vspltisw -1: 9230 SDValue OnesV = BuildSplatI(-1, 4, MVT::v4i32, DAG, dl); 9231 9232 // Make the VSLW intrinsic, computing 0x8000_0000. 9233 SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV, 9234 OnesV, DAG, dl); 9235 9236 // xor by OnesV to invert it. 9237 Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV); 9238 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 9239 } 9240 9241 // Check to see if this is a wide variety of vsplti*, binop self cases. 9242 static const signed char SplatCsts[] = { 9243 -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7, 9244 -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16 9245 }; 9246 9247 for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) { 9248 // Indirect through the SplatCsts array so that we favor 'vsplti -1' for 9249 // cases which are ambiguous (e.g. formation of 0x8000_0000). 'vsplti -1' 9250 int i = SplatCsts[idx]; 9251 9252 // Figure out what shift amount will be used by altivec if shifted by i in 9253 // this splat size. 9254 unsigned TypeShiftAmt = i & (SplatBitSize-1); 9255 9256 // vsplti + shl self. 9257 if (SextVal == (int)((unsigned)i << TypeShiftAmt)) { 9258 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl); 9259 static const unsigned IIDs[] = { // Intrinsic to use for each size. 9260 Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0, 9261 Intrinsic::ppc_altivec_vslw 9262 }; 9263 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 9264 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 9265 } 9266 9267 // vsplti + srl self. 9268 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) { 9269 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl); 9270 static const unsigned IIDs[] = { // Intrinsic to use for each size. 9271 Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0, 9272 Intrinsic::ppc_altivec_vsrw 9273 }; 9274 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 9275 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 9276 } 9277 9278 // vsplti + sra self. 9279 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) { 9280 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl); 9281 static const unsigned IIDs[] = { // Intrinsic to use for each size. 9282 Intrinsic::ppc_altivec_vsrab, Intrinsic::ppc_altivec_vsrah, 0, 9283 Intrinsic::ppc_altivec_vsraw 9284 }; 9285 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 9286 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 9287 } 9288 9289 // vsplti + rol self. 9290 if (SextVal == (int)(((unsigned)i << TypeShiftAmt) | 9291 ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) { 9292 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl); 9293 static const unsigned IIDs[] = { // Intrinsic to use for each size. 9294 Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0, 9295 Intrinsic::ppc_altivec_vrlw 9296 }; 9297 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 9298 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 9299 } 9300 9301 // t = vsplti c, result = vsldoi t, t, 1 9302 if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) { 9303 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl); 9304 unsigned Amt = Subtarget.isLittleEndian() ? 15 : 1; 9305 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl); 9306 } 9307 // t = vsplti c, result = vsldoi t, t, 2 9308 if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) { 9309 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl); 9310 unsigned Amt = Subtarget.isLittleEndian() ? 14 : 2; 9311 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl); 9312 } 9313 // t = vsplti c, result = vsldoi t, t, 3 9314 if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) { 9315 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl); 9316 unsigned Amt = Subtarget.isLittleEndian() ? 13 : 3; 9317 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl); 9318 } 9319 } 9320 9321 return SDValue(); 9322 } 9323 9324 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit 9325 /// the specified operations to build the shuffle. 9326 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS, 9327 SDValue RHS, SelectionDAG &DAG, 9328 const SDLoc &dl) { 9329 unsigned OpNum = (PFEntry >> 26) & 0x0F; 9330 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1); 9331 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1); 9332 9333 enum { 9334 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3> 9335 OP_VMRGHW, 9336 OP_VMRGLW, 9337 OP_VSPLTISW0, 9338 OP_VSPLTISW1, 9339 OP_VSPLTISW2, 9340 OP_VSPLTISW3, 9341 OP_VSLDOI4, 9342 OP_VSLDOI8, 9343 OP_VSLDOI12 9344 }; 9345 9346 if (OpNum == OP_COPY) { 9347 if (LHSID == (1*9+2)*9+3) return LHS; 9348 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!"); 9349 return RHS; 9350 } 9351 9352 SDValue OpLHS, OpRHS; 9353 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl); 9354 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl); 9355 9356 int ShufIdxs[16]; 9357 switch (OpNum) { 9358 default: llvm_unreachable("Unknown i32 permute!"); 9359 case OP_VMRGHW: 9360 ShufIdxs[ 0] = 0; ShufIdxs[ 1] = 1; ShufIdxs[ 2] = 2; ShufIdxs[ 3] = 3; 9361 ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19; 9362 ShufIdxs[ 8] = 4; ShufIdxs[ 9] = 5; ShufIdxs[10] = 6; ShufIdxs[11] = 7; 9363 ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23; 9364 break; 9365 case OP_VMRGLW: 9366 ShufIdxs[ 0] = 8; ShufIdxs[ 1] = 9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11; 9367 ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27; 9368 ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15; 9369 ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31; 9370 break; 9371 case OP_VSPLTISW0: 9372 for (unsigned i = 0; i != 16; ++i) 9373 ShufIdxs[i] = (i&3)+0; 9374 break; 9375 case OP_VSPLTISW1: 9376 for (unsigned i = 0; i != 16; ++i) 9377 ShufIdxs[i] = (i&3)+4; 9378 break; 9379 case OP_VSPLTISW2: 9380 for (unsigned i = 0; i != 16; ++i) 9381 ShufIdxs[i] = (i&3)+8; 9382 break; 9383 case OP_VSPLTISW3: 9384 for (unsigned i = 0; i != 16; ++i) 9385 ShufIdxs[i] = (i&3)+12; 9386 break; 9387 case OP_VSLDOI4: 9388 return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl); 9389 case OP_VSLDOI8: 9390 return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl); 9391 case OP_VSLDOI12: 9392 return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl); 9393 } 9394 EVT VT = OpLHS.getValueType(); 9395 OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS); 9396 OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS); 9397 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs); 9398 return DAG.getNode(ISD::BITCAST, dl, VT, T); 9399 } 9400 9401 /// lowerToVINSERTB - Return the SDValue if this VECTOR_SHUFFLE can be handled 9402 /// by the VINSERTB instruction introduced in ISA 3.0, else just return default 9403 /// SDValue. 9404 SDValue PPCTargetLowering::lowerToVINSERTB(ShuffleVectorSDNode *N, 9405 SelectionDAG &DAG) const { 9406 const unsigned BytesInVector = 16; 9407 bool IsLE = Subtarget.isLittleEndian(); 9408 SDLoc dl(N); 9409 SDValue V1 = N->getOperand(0); 9410 SDValue V2 = N->getOperand(1); 9411 unsigned ShiftElts = 0, InsertAtByte = 0; 9412 bool Swap = false; 9413 9414 // Shifts required to get the byte we want at element 7. 9415 unsigned LittleEndianShifts[] = {8, 7, 6, 5, 4, 3, 2, 1, 9416 0, 15, 14, 13, 12, 11, 10, 9}; 9417 unsigned BigEndianShifts[] = {9, 10, 11, 12, 13, 14, 15, 0, 9418 1, 2, 3, 4, 5, 6, 7, 8}; 9419 9420 ArrayRef<int> Mask = N->getMask(); 9421 int OriginalOrder[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}; 9422 9423 // For each mask element, find out if we're just inserting something 9424 // from V2 into V1 or vice versa. 9425 // Possible permutations inserting an element from V2 into V1: 9426 // X, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 9427 // 0, X, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 9428 // ... 9429 // 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, X 9430 // Inserting from V1 into V2 will be similar, except mask range will be 9431 // [16,31]. 9432 9433 bool FoundCandidate = false; 9434 // If both vector operands for the shuffle are the same vector, the mask 9435 // will contain only elements from the first one and the second one will be 9436 // undef. 9437 unsigned VINSERTBSrcElem = IsLE ? 8 : 7; 9438 // Go through the mask of half-words to find an element that's being moved 9439 // from one vector to the other. 9440 for (unsigned i = 0; i < BytesInVector; ++i) { 9441 unsigned CurrentElement = Mask[i]; 9442 // If 2nd operand is undefined, we should only look for element 7 in the 9443 // Mask. 9444 if (V2.isUndef() && CurrentElement != VINSERTBSrcElem) 9445 continue; 9446 9447 bool OtherElementsInOrder = true; 9448 // Examine the other elements in the Mask to see if they're in original 9449 // order. 9450 for (unsigned j = 0; j < BytesInVector; ++j) { 9451 if (j == i) 9452 continue; 9453 // If CurrentElement is from V1 [0,15], then we the rest of the Mask to be 9454 // from V2 [16,31] and vice versa. Unless the 2nd operand is undefined, 9455 // in which we always assume we're always picking from the 1st operand. 9456 int MaskOffset = 9457 (!V2.isUndef() && CurrentElement < BytesInVector) ? BytesInVector : 0; 9458 if (Mask[j] != OriginalOrder[j] + MaskOffset) { 9459 OtherElementsInOrder = false; 9460 break; 9461 } 9462 } 9463 // If other elements are in original order, we record the number of shifts 9464 // we need to get the element we want into element 7. Also record which byte 9465 // in the vector we should insert into. 9466 if (OtherElementsInOrder) { 9467 // If 2nd operand is undefined, we assume no shifts and no swapping. 9468 if (V2.isUndef()) { 9469 ShiftElts = 0; 9470 Swap = false; 9471 } else { 9472 // Only need the last 4-bits for shifts because operands will be swapped if CurrentElement is >= 2^4. 9473 ShiftElts = IsLE ? LittleEndianShifts[CurrentElement & 0xF] 9474 : BigEndianShifts[CurrentElement & 0xF]; 9475 Swap = CurrentElement < BytesInVector; 9476 } 9477 InsertAtByte = IsLE ? BytesInVector - (i + 1) : i; 9478 FoundCandidate = true; 9479 break; 9480 } 9481 } 9482 9483 if (!FoundCandidate) 9484 return SDValue(); 9485 9486 // Candidate found, construct the proper SDAG sequence with VINSERTB, 9487 // optionally with VECSHL if shift is required. 9488 if (Swap) 9489 std::swap(V1, V2); 9490 if (V2.isUndef()) 9491 V2 = V1; 9492 if (ShiftElts) { 9493 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2, 9494 DAG.getConstant(ShiftElts, dl, MVT::i32)); 9495 return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, Shl, 9496 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9497 } 9498 return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, V2, 9499 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9500 } 9501 9502 /// lowerToVINSERTH - Return the SDValue if this VECTOR_SHUFFLE can be handled 9503 /// by the VINSERTH instruction introduced in ISA 3.0, else just return default 9504 /// SDValue. 9505 SDValue PPCTargetLowering::lowerToVINSERTH(ShuffleVectorSDNode *N, 9506 SelectionDAG &DAG) const { 9507 const unsigned NumHalfWords = 8; 9508 const unsigned BytesInVector = NumHalfWords * 2; 9509 // Check that the shuffle is on half-words. 9510 if (!isNByteElemShuffleMask(N, 2, 1)) 9511 return SDValue(); 9512 9513 bool IsLE = Subtarget.isLittleEndian(); 9514 SDLoc dl(N); 9515 SDValue V1 = N->getOperand(0); 9516 SDValue V2 = N->getOperand(1); 9517 unsigned ShiftElts = 0, InsertAtByte = 0; 9518 bool Swap = false; 9519 9520 // Shifts required to get the half-word we want at element 3. 9521 unsigned LittleEndianShifts[] = {4, 3, 2, 1, 0, 7, 6, 5}; 9522 unsigned BigEndianShifts[] = {5, 6, 7, 0, 1, 2, 3, 4}; 9523 9524 uint32_t Mask = 0; 9525 uint32_t OriginalOrderLow = 0x1234567; 9526 uint32_t OriginalOrderHigh = 0x89ABCDEF; 9527 // Now we look at mask elements 0,2,4,6,8,10,12,14. Pack the mask into a 9528 // 32-bit space, only need 4-bit nibbles per element. 9529 for (unsigned i = 0; i < NumHalfWords; ++i) { 9530 unsigned MaskShift = (NumHalfWords - 1 - i) * 4; 9531 Mask |= ((uint32_t)(N->getMaskElt(i * 2) / 2) << MaskShift); 9532 } 9533 9534 // For each mask element, find out if we're just inserting something 9535 // from V2 into V1 or vice versa. Possible permutations inserting an element 9536 // from V2 into V1: 9537 // X, 1, 2, 3, 4, 5, 6, 7 9538 // 0, X, 2, 3, 4, 5, 6, 7 9539 // 0, 1, X, 3, 4, 5, 6, 7 9540 // 0, 1, 2, X, 4, 5, 6, 7 9541 // 0, 1, 2, 3, X, 5, 6, 7 9542 // 0, 1, 2, 3, 4, X, 6, 7 9543 // 0, 1, 2, 3, 4, 5, X, 7 9544 // 0, 1, 2, 3, 4, 5, 6, X 9545 // Inserting from V1 into V2 will be similar, except mask range will be [8,15]. 9546 9547 bool FoundCandidate = false; 9548 // Go through the mask of half-words to find an element that's being moved 9549 // from one vector to the other. 9550 for (unsigned i = 0; i < NumHalfWords; ++i) { 9551 unsigned MaskShift = (NumHalfWords - 1 - i) * 4; 9552 uint32_t MaskOneElt = (Mask >> MaskShift) & 0xF; 9553 uint32_t MaskOtherElts = ~(0xF << MaskShift); 9554 uint32_t TargetOrder = 0x0; 9555 9556 // If both vector operands for the shuffle are the same vector, the mask 9557 // will contain only elements from the first one and the second one will be 9558 // undef. 9559 if (V2.isUndef()) { 9560 ShiftElts = 0; 9561 unsigned VINSERTHSrcElem = IsLE ? 4 : 3; 9562 TargetOrder = OriginalOrderLow; 9563 Swap = false; 9564 // Skip if not the correct element or mask of other elements don't equal 9565 // to our expected order. 9566 if (MaskOneElt == VINSERTHSrcElem && 9567 (Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) { 9568 InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2; 9569 FoundCandidate = true; 9570 break; 9571 } 9572 } else { // If both operands are defined. 9573 // Target order is [8,15] if the current mask is between [0,7]. 9574 TargetOrder = 9575 (MaskOneElt < NumHalfWords) ? OriginalOrderHigh : OriginalOrderLow; 9576 // Skip if mask of other elements don't equal our expected order. 9577 if ((Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) { 9578 // We only need the last 3 bits for the number of shifts. 9579 ShiftElts = IsLE ? LittleEndianShifts[MaskOneElt & 0x7] 9580 : BigEndianShifts[MaskOneElt & 0x7]; 9581 InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2; 9582 Swap = MaskOneElt < NumHalfWords; 9583 FoundCandidate = true; 9584 break; 9585 } 9586 } 9587 } 9588 9589 if (!FoundCandidate) 9590 return SDValue(); 9591 9592 // Candidate found, construct the proper SDAG sequence with VINSERTH, 9593 // optionally with VECSHL if shift is required. 9594 if (Swap) 9595 std::swap(V1, V2); 9596 if (V2.isUndef()) 9597 V2 = V1; 9598 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1); 9599 if (ShiftElts) { 9600 // Double ShiftElts because we're left shifting on v16i8 type. 9601 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2, 9602 DAG.getConstant(2 * ShiftElts, dl, MVT::i32)); 9603 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, Shl); 9604 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2, 9605 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9606 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 9607 } 9608 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2); 9609 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2, 9610 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9611 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 9612 } 9613 9614 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE. If this 9615 /// is a shuffle we can handle in a single instruction, return it. Otherwise, 9616 /// return the code it can be lowered into. Worst case, it can always be 9617 /// lowered into a vperm. 9618 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, 9619 SelectionDAG &DAG) const { 9620 SDLoc dl(Op); 9621 SDValue V1 = Op.getOperand(0); 9622 SDValue V2 = Op.getOperand(1); 9623 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op); 9624 EVT VT = Op.getValueType(); 9625 bool isLittleEndian = Subtarget.isLittleEndian(); 9626 9627 unsigned ShiftElts, InsertAtByte; 9628 bool Swap = false; 9629 9630 // If this is a load-and-splat, we can do that with a single instruction 9631 // in some cases. However if the load has multiple uses, we don't want to 9632 // combine it because that will just produce multiple loads. 9633 const SDValue *InputLoad = getNormalLoadInput(V1); 9634 if (InputLoad && Subtarget.hasVSX() && V2.isUndef() && 9635 (PPC::isSplatShuffleMask(SVOp, 4) || PPC::isSplatShuffleMask(SVOp, 8)) && 9636 InputLoad->hasOneUse()) { 9637 bool IsFourByte = PPC::isSplatShuffleMask(SVOp, 4); 9638 int SplatIdx = 9639 PPC::getSplatIdxForPPCMnemonics(SVOp, IsFourByte ? 4 : 8, DAG); 9640 9641 LoadSDNode *LD = cast<LoadSDNode>(*InputLoad); 9642 // For 4-byte load-and-splat, we need Power9. 9643 if ((IsFourByte && Subtarget.hasP9Vector()) || !IsFourByte) { 9644 uint64_t Offset = 0; 9645 if (IsFourByte) 9646 Offset = isLittleEndian ? (3 - SplatIdx) * 4 : SplatIdx * 4; 9647 else 9648 Offset = isLittleEndian ? (1 - SplatIdx) * 8 : SplatIdx * 8; 9649 SDValue BasePtr = LD->getBasePtr(); 9650 if (Offset != 0) 9651 BasePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()), 9652 BasePtr, DAG.getIntPtrConstant(Offset, dl)); 9653 SDValue Ops[] = { 9654 LD->getChain(), // Chain 9655 BasePtr, // BasePtr 9656 DAG.getValueType(Op.getValueType()) // VT 9657 }; 9658 SDVTList VTL = 9659 DAG.getVTList(IsFourByte ? MVT::v4i32 : MVT::v2i64, MVT::Other); 9660 SDValue LdSplt = 9661 DAG.getMemIntrinsicNode(PPCISD::LD_SPLAT, dl, VTL, 9662 Ops, LD->getMemoryVT(), LD->getMemOperand()); 9663 if (LdSplt.getValueType() != SVOp->getValueType(0)) 9664 LdSplt = DAG.getBitcast(SVOp->getValueType(0), LdSplt); 9665 return LdSplt; 9666 } 9667 } 9668 if (Subtarget.hasP9Vector() && 9669 PPC::isXXINSERTWMask(SVOp, ShiftElts, InsertAtByte, Swap, 9670 isLittleEndian)) { 9671 if (Swap) 9672 std::swap(V1, V2); 9673 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 9674 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2); 9675 if (ShiftElts) { 9676 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv2, Conv2, 9677 DAG.getConstant(ShiftElts, dl, MVT::i32)); 9678 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Shl, 9679 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9680 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 9681 } 9682 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Conv2, 9683 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9684 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 9685 } 9686 9687 if (Subtarget.hasP9Altivec()) { 9688 SDValue NewISDNode; 9689 if ((NewISDNode = lowerToVINSERTH(SVOp, DAG))) 9690 return NewISDNode; 9691 9692 if ((NewISDNode = lowerToVINSERTB(SVOp, DAG))) 9693 return NewISDNode; 9694 } 9695 9696 if (Subtarget.hasVSX() && 9697 PPC::isXXSLDWIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) { 9698 if (Swap) 9699 std::swap(V1, V2); 9700 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 9701 SDValue Conv2 = 9702 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2.isUndef() ? V1 : V2); 9703 9704 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv1, Conv2, 9705 DAG.getConstant(ShiftElts, dl, MVT::i32)); 9706 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Shl); 9707 } 9708 9709 if (Subtarget.hasVSX() && 9710 PPC::isXXPERMDIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) { 9711 if (Swap) 9712 std::swap(V1, V2); 9713 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1); 9714 SDValue Conv2 = 9715 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2.isUndef() ? V1 : V2); 9716 9717 SDValue PermDI = DAG.getNode(PPCISD::XXPERMDI, dl, MVT::v2i64, Conv1, Conv2, 9718 DAG.getConstant(ShiftElts, dl, MVT::i32)); 9719 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, PermDI); 9720 } 9721 9722 if (Subtarget.hasP9Vector()) { 9723 if (PPC::isXXBRHShuffleMask(SVOp)) { 9724 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1); 9725 SDValue ReveHWord = DAG.getNode(ISD::BSWAP, dl, MVT::v8i16, Conv); 9726 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveHWord); 9727 } else if (PPC::isXXBRWShuffleMask(SVOp)) { 9728 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 9729 SDValue ReveWord = DAG.getNode(ISD::BSWAP, dl, MVT::v4i32, Conv); 9730 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveWord); 9731 } else if (PPC::isXXBRDShuffleMask(SVOp)) { 9732 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1); 9733 SDValue ReveDWord = DAG.getNode(ISD::BSWAP, dl, MVT::v2i64, Conv); 9734 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveDWord); 9735 } else if (PPC::isXXBRQShuffleMask(SVOp)) { 9736 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, V1); 9737 SDValue ReveQWord = DAG.getNode(ISD::BSWAP, dl, MVT::v1i128, Conv); 9738 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveQWord); 9739 } 9740 } 9741 9742 if (Subtarget.hasVSX()) { 9743 if (V2.isUndef() && PPC::isSplatShuffleMask(SVOp, 4)) { 9744 int SplatIdx = PPC::getSplatIdxForPPCMnemonics(SVOp, 4, DAG); 9745 9746 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 9747 SDValue Splat = DAG.getNode(PPCISD::XXSPLT, dl, MVT::v4i32, Conv, 9748 DAG.getConstant(SplatIdx, dl, MVT::i32)); 9749 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Splat); 9750 } 9751 9752 // Left shifts of 8 bytes are actually swaps. Convert accordingly. 9753 if (V2.isUndef() && PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) == 8) { 9754 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1); 9755 SDValue Swap = DAG.getNode(PPCISD::SWAP_NO_CHAIN, dl, MVT::v2f64, Conv); 9756 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Swap); 9757 } 9758 } 9759 9760 if (Subtarget.hasQPX()) { 9761 if (VT.getVectorNumElements() != 4) 9762 return SDValue(); 9763 9764 if (V2.isUndef()) V2 = V1; 9765 9766 int AlignIdx = PPC::isQVALIGNIShuffleMask(SVOp); 9767 if (AlignIdx != -1) { 9768 return DAG.getNode(PPCISD::QVALIGNI, dl, VT, V1, V2, 9769 DAG.getConstant(AlignIdx, dl, MVT::i32)); 9770 } else if (SVOp->isSplat()) { 9771 int SplatIdx = SVOp->getSplatIndex(); 9772 if (SplatIdx >= 4) { 9773 std::swap(V1, V2); 9774 SplatIdx -= 4; 9775 } 9776 9777 return DAG.getNode(PPCISD::QVESPLATI, dl, VT, V1, 9778 DAG.getConstant(SplatIdx, dl, MVT::i32)); 9779 } 9780 9781 // Lower this into a qvgpci/qvfperm pair. 9782 9783 // Compute the qvgpci literal 9784 unsigned idx = 0; 9785 for (unsigned i = 0; i < 4; ++i) { 9786 int m = SVOp->getMaskElt(i); 9787 unsigned mm = m >= 0 ? (unsigned) m : i; 9788 idx |= mm << (3-i)*3; 9789 } 9790 9791 SDValue V3 = DAG.getNode(PPCISD::QVGPCI, dl, MVT::v4f64, 9792 DAG.getConstant(idx, dl, MVT::i32)); 9793 return DAG.getNode(PPCISD::QVFPERM, dl, VT, V1, V2, V3); 9794 } 9795 9796 // Cases that are handled by instructions that take permute immediates 9797 // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be 9798 // selected by the instruction selector. 9799 if (V2.isUndef()) { 9800 if (PPC::isSplatShuffleMask(SVOp, 1) || 9801 PPC::isSplatShuffleMask(SVOp, 2) || 9802 PPC::isSplatShuffleMask(SVOp, 4) || 9803 PPC::isVPKUWUMShuffleMask(SVOp, 1, DAG) || 9804 PPC::isVPKUHUMShuffleMask(SVOp, 1, DAG) || 9805 PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) != -1 || 9806 PPC::isVMRGLShuffleMask(SVOp, 1, 1, DAG) || 9807 PPC::isVMRGLShuffleMask(SVOp, 2, 1, DAG) || 9808 PPC::isVMRGLShuffleMask(SVOp, 4, 1, DAG) || 9809 PPC::isVMRGHShuffleMask(SVOp, 1, 1, DAG) || 9810 PPC::isVMRGHShuffleMask(SVOp, 2, 1, DAG) || 9811 PPC::isVMRGHShuffleMask(SVOp, 4, 1, DAG) || 9812 (Subtarget.hasP8Altivec() && ( 9813 PPC::isVPKUDUMShuffleMask(SVOp, 1, DAG) || 9814 PPC::isVMRGEOShuffleMask(SVOp, true, 1, DAG) || 9815 PPC::isVMRGEOShuffleMask(SVOp, false, 1, DAG)))) { 9816 return Op; 9817 } 9818 } 9819 9820 // Altivec has a variety of "shuffle immediates" that take two vector inputs 9821 // and produce a fixed permutation. If any of these match, do not lower to 9822 // VPERM. 9823 unsigned int ShuffleKind = isLittleEndian ? 2 : 0; 9824 if (PPC::isVPKUWUMShuffleMask(SVOp, ShuffleKind, DAG) || 9825 PPC::isVPKUHUMShuffleMask(SVOp, ShuffleKind, DAG) || 9826 PPC::isVSLDOIShuffleMask(SVOp, ShuffleKind, DAG) != -1 || 9827 PPC::isVMRGLShuffleMask(SVOp, 1, ShuffleKind, DAG) || 9828 PPC::isVMRGLShuffleMask(SVOp, 2, ShuffleKind, DAG) || 9829 PPC::isVMRGLShuffleMask(SVOp, 4, ShuffleKind, DAG) || 9830 PPC::isVMRGHShuffleMask(SVOp, 1, ShuffleKind, DAG) || 9831 PPC::isVMRGHShuffleMask(SVOp, 2, ShuffleKind, DAG) || 9832 PPC::isVMRGHShuffleMask(SVOp, 4, ShuffleKind, DAG) || 9833 (Subtarget.hasP8Altivec() && ( 9834 PPC::isVPKUDUMShuffleMask(SVOp, ShuffleKind, DAG) || 9835 PPC::isVMRGEOShuffleMask(SVOp, true, ShuffleKind, DAG) || 9836 PPC::isVMRGEOShuffleMask(SVOp, false, ShuffleKind, DAG)))) 9837 return Op; 9838 9839 // Check to see if this is a shuffle of 4-byte values. If so, we can use our 9840 // perfect shuffle table to emit an optimal matching sequence. 9841 ArrayRef<int> PermMask = SVOp->getMask(); 9842 9843 unsigned PFIndexes[4]; 9844 bool isFourElementShuffle = true; 9845 for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number 9846 unsigned EltNo = 8; // Start out undef. 9847 for (unsigned j = 0; j != 4; ++j) { // Intra-element byte. 9848 if (PermMask[i*4+j] < 0) 9849 continue; // Undef, ignore it. 9850 9851 unsigned ByteSource = PermMask[i*4+j]; 9852 if ((ByteSource & 3) != j) { 9853 isFourElementShuffle = false; 9854 break; 9855 } 9856 9857 if (EltNo == 8) { 9858 EltNo = ByteSource/4; 9859 } else if (EltNo != ByteSource/4) { 9860 isFourElementShuffle = false; 9861 break; 9862 } 9863 } 9864 PFIndexes[i] = EltNo; 9865 } 9866 9867 // If this shuffle can be expressed as a shuffle of 4-byte elements, use the 9868 // perfect shuffle vector to determine if it is cost effective to do this as 9869 // discrete instructions, or whether we should use a vperm. 9870 // For now, we skip this for little endian until such time as we have a 9871 // little-endian perfect shuffle table. 9872 if (isFourElementShuffle && !isLittleEndian) { 9873 // Compute the index in the perfect shuffle table. 9874 unsigned PFTableIndex = 9875 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3]; 9876 9877 unsigned PFEntry = PerfectShuffleTable[PFTableIndex]; 9878 unsigned Cost = (PFEntry >> 30); 9879 9880 // Determining when to avoid vperm is tricky. Many things affect the cost 9881 // of vperm, particularly how many times the perm mask needs to be computed. 9882 // For example, if the perm mask can be hoisted out of a loop or is already 9883 // used (perhaps because there are multiple permutes with the same shuffle 9884 // mask?) the vperm has a cost of 1. OTOH, hoisting the permute mask out of 9885 // the loop requires an extra register. 9886 // 9887 // As a compromise, we only emit discrete instructions if the shuffle can be 9888 // generated in 3 or fewer operations. When we have loop information 9889 // available, if this block is within a loop, we should avoid using vperm 9890 // for 3-operation perms and use a constant pool load instead. 9891 if (Cost < 3) 9892 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl); 9893 } 9894 9895 // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant 9896 // vector that will get spilled to the constant pool. 9897 if (V2.isUndef()) V2 = V1; 9898 9899 // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except 9900 // that it is in input element units, not in bytes. Convert now. 9901 9902 // For little endian, the order of the input vectors is reversed, and 9903 // the permutation mask is complemented with respect to 31. This is 9904 // necessary to produce proper semantics with the big-endian-biased vperm 9905 // instruction. 9906 EVT EltVT = V1.getValueType().getVectorElementType(); 9907 unsigned BytesPerElement = EltVT.getSizeInBits()/8; 9908 9909 SmallVector<SDValue, 16> ResultMask; 9910 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) { 9911 unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i]; 9912 9913 for (unsigned j = 0; j != BytesPerElement; ++j) 9914 if (isLittleEndian) 9915 ResultMask.push_back(DAG.getConstant(31 - (SrcElt*BytesPerElement + j), 9916 dl, MVT::i32)); 9917 else 9918 ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement + j, dl, 9919 MVT::i32)); 9920 } 9921 9922 SDValue VPermMask = DAG.getBuildVector(MVT::v16i8, dl, ResultMask); 9923 if (isLittleEndian) 9924 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(), 9925 V2, V1, VPermMask); 9926 else 9927 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(), 9928 V1, V2, VPermMask); 9929 } 9930 9931 /// getVectorCompareInfo - Given an intrinsic, return false if it is not a 9932 /// vector comparison. If it is, return true and fill in Opc/isDot with 9933 /// information about the intrinsic. 9934 static bool getVectorCompareInfo(SDValue Intrin, int &CompareOpc, 9935 bool &isDot, const PPCSubtarget &Subtarget) { 9936 unsigned IntrinsicID = 9937 cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue(); 9938 CompareOpc = -1; 9939 isDot = false; 9940 switch (IntrinsicID) { 9941 default: 9942 return false; 9943 // Comparison predicates. 9944 case Intrinsic::ppc_altivec_vcmpbfp_p: 9945 CompareOpc = 966; 9946 isDot = true; 9947 break; 9948 case Intrinsic::ppc_altivec_vcmpeqfp_p: 9949 CompareOpc = 198; 9950 isDot = true; 9951 break; 9952 case Intrinsic::ppc_altivec_vcmpequb_p: 9953 CompareOpc = 6; 9954 isDot = true; 9955 break; 9956 case Intrinsic::ppc_altivec_vcmpequh_p: 9957 CompareOpc = 70; 9958 isDot = true; 9959 break; 9960 case Intrinsic::ppc_altivec_vcmpequw_p: 9961 CompareOpc = 134; 9962 isDot = true; 9963 break; 9964 case Intrinsic::ppc_altivec_vcmpequd_p: 9965 if (Subtarget.hasP8Altivec()) { 9966 CompareOpc = 199; 9967 isDot = true; 9968 } else 9969 return false; 9970 break; 9971 case Intrinsic::ppc_altivec_vcmpneb_p: 9972 case Intrinsic::ppc_altivec_vcmpneh_p: 9973 case Intrinsic::ppc_altivec_vcmpnew_p: 9974 case Intrinsic::ppc_altivec_vcmpnezb_p: 9975 case Intrinsic::ppc_altivec_vcmpnezh_p: 9976 case Intrinsic::ppc_altivec_vcmpnezw_p: 9977 if (Subtarget.hasP9Altivec()) { 9978 switch (IntrinsicID) { 9979 default: 9980 llvm_unreachable("Unknown comparison intrinsic."); 9981 case Intrinsic::ppc_altivec_vcmpneb_p: 9982 CompareOpc = 7; 9983 break; 9984 case Intrinsic::ppc_altivec_vcmpneh_p: 9985 CompareOpc = 71; 9986 break; 9987 case Intrinsic::ppc_altivec_vcmpnew_p: 9988 CompareOpc = 135; 9989 break; 9990 case Intrinsic::ppc_altivec_vcmpnezb_p: 9991 CompareOpc = 263; 9992 break; 9993 case Intrinsic::ppc_altivec_vcmpnezh_p: 9994 CompareOpc = 327; 9995 break; 9996 case Intrinsic::ppc_altivec_vcmpnezw_p: 9997 CompareOpc = 391; 9998 break; 9999 } 10000 isDot = true; 10001 } else 10002 return false; 10003 break; 10004 case Intrinsic::ppc_altivec_vcmpgefp_p: 10005 CompareOpc = 454; 10006 isDot = true; 10007 break; 10008 case Intrinsic::ppc_altivec_vcmpgtfp_p: 10009 CompareOpc = 710; 10010 isDot = true; 10011 break; 10012 case Intrinsic::ppc_altivec_vcmpgtsb_p: 10013 CompareOpc = 774; 10014 isDot = true; 10015 break; 10016 case Intrinsic::ppc_altivec_vcmpgtsh_p: 10017 CompareOpc = 838; 10018 isDot = true; 10019 break; 10020 case Intrinsic::ppc_altivec_vcmpgtsw_p: 10021 CompareOpc = 902; 10022 isDot = true; 10023 break; 10024 case Intrinsic::ppc_altivec_vcmpgtsd_p: 10025 if (Subtarget.hasP8Altivec()) { 10026 CompareOpc = 967; 10027 isDot = true; 10028 } else 10029 return false; 10030 break; 10031 case Intrinsic::ppc_altivec_vcmpgtub_p: 10032 CompareOpc = 518; 10033 isDot = true; 10034 break; 10035 case Intrinsic::ppc_altivec_vcmpgtuh_p: 10036 CompareOpc = 582; 10037 isDot = true; 10038 break; 10039 case Intrinsic::ppc_altivec_vcmpgtuw_p: 10040 CompareOpc = 646; 10041 isDot = true; 10042 break; 10043 case Intrinsic::ppc_altivec_vcmpgtud_p: 10044 if (Subtarget.hasP8Altivec()) { 10045 CompareOpc = 711; 10046 isDot = true; 10047 } else 10048 return false; 10049 break; 10050 10051 // VSX predicate comparisons use the same infrastructure 10052 case Intrinsic::ppc_vsx_xvcmpeqdp_p: 10053 case Intrinsic::ppc_vsx_xvcmpgedp_p: 10054 case Intrinsic::ppc_vsx_xvcmpgtdp_p: 10055 case Intrinsic::ppc_vsx_xvcmpeqsp_p: 10056 case Intrinsic::ppc_vsx_xvcmpgesp_p: 10057 case Intrinsic::ppc_vsx_xvcmpgtsp_p: 10058 if (Subtarget.hasVSX()) { 10059 switch (IntrinsicID) { 10060 case Intrinsic::ppc_vsx_xvcmpeqdp_p: 10061 CompareOpc = 99; 10062 break; 10063 case Intrinsic::ppc_vsx_xvcmpgedp_p: 10064 CompareOpc = 115; 10065 break; 10066 case Intrinsic::ppc_vsx_xvcmpgtdp_p: 10067 CompareOpc = 107; 10068 break; 10069 case Intrinsic::ppc_vsx_xvcmpeqsp_p: 10070 CompareOpc = 67; 10071 break; 10072 case Intrinsic::ppc_vsx_xvcmpgesp_p: 10073 CompareOpc = 83; 10074 break; 10075 case Intrinsic::ppc_vsx_xvcmpgtsp_p: 10076 CompareOpc = 75; 10077 break; 10078 } 10079 isDot = true; 10080 } else 10081 return false; 10082 break; 10083 10084 // Normal Comparisons. 10085 case Intrinsic::ppc_altivec_vcmpbfp: 10086 CompareOpc = 966; 10087 break; 10088 case Intrinsic::ppc_altivec_vcmpeqfp: 10089 CompareOpc = 198; 10090 break; 10091 case Intrinsic::ppc_altivec_vcmpequb: 10092 CompareOpc = 6; 10093 break; 10094 case Intrinsic::ppc_altivec_vcmpequh: 10095 CompareOpc = 70; 10096 break; 10097 case Intrinsic::ppc_altivec_vcmpequw: 10098 CompareOpc = 134; 10099 break; 10100 case Intrinsic::ppc_altivec_vcmpequd: 10101 if (Subtarget.hasP8Altivec()) 10102 CompareOpc = 199; 10103 else 10104 return false; 10105 break; 10106 case Intrinsic::ppc_altivec_vcmpneb: 10107 case Intrinsic::ppc_altivec_vcmpneh: 10108 case Intrinsic::ppc_altivec_vcmpnew: 10109 case Intrinsic::ppc_altivec_vcmpnezb: 10110 case Intrinsic::ppc_altivec_vcmpnezh: 10111 case Intrinsic::ppc_altivec_vcmpnezw: 10112 if (Subtarget.hasP9Altivec()) 10113 switch (IntrinsicID) { 10114 default: 10115 llvm_unreachable("Unknown comparison intrinsic."); 10116 case Intrinsic::ppc_altivec_vcmpneb: 10117 CompareOpc = 7; 10118 break; 10119 case Intrinsic::ppc_altivec_vcmpneh: 10120 CompareOpc = 71; 10121 break; 10122 case Intrinsic::ppc_altivec_vcmpnew: 10123 CompareOpc = 135; 10124 break; 10125 case Intrinsic::ppc_altivec_vcmpnezb: 10126 CompareOpc = 263; 10127 break; 10128 case Intrinsic::ppc_altivec_vcmpnezh: 10129 CompareOpc = 327; 10130 break; 10131 case Intrinsic::ppc_altivec_vcmpnezw: 10132 CompareOpc = 391; 10133 break; 10134 } 10135 else 10136 return false; 10137 break; 10138 case Intrinsic::ppc_altivec_vcmpgefp: 10139 CompareOpc = 454; 10140 break; 10141 case Intrinsic::ppc_altivec_vcmpgtfp: 10142 CompareOpc = 710; 10143 break; 10144 case Intrinsic::ppc_altivec_vcmpgtsb: 10145 CompareOpc = 774; 10146 break; 10147 case Intrinsic::ppc_altivec_vcmpgtsh: 10148 CompareOpc = 838; 10149 break; 10150 case Intrinsic::ppc_altivec_vcmpgtsw: 10151 CompareOpc = 902; 10152 break; 10153 case Intrinsic::ppc_altivec_vcmpgtsd: 10154 if (Subtarget.hasP8Altivec()) 10155 CompareOpc = 967; 10156 else 10157 return false; 10158 break; 10159 case Intrinsic::ppc_altivec_vcmpgtub: 10160 CompareOpc = 518; 10161 break; 10162 case Intrinsic::ppc_altivec_vcmpgtuh: 10163 CompareOpc = 582; 10164 break; 10165 case Intrinsic::ppc_altivec_vcmpgtuw: 10166 CompareOpc = 646; 10167 break; 10168 case Intrinsic::ppc_altivec_vcmpgtud: 10169 if (Subtarget.hasP8Altivec()) 10170 CompareOpc = 711; 10171 else 10172 return false; 10173 break; 10174 } 10175 return true; 10176 } 10177 10178 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom 10179 /// lower, do it, otherwise return null. 10180 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 10181 SelectionDAG &DAG) const { 10182 unsigned IntrinsicID = 10183 cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 10184 10185 SDLoc dl(Op); 10186 10187 if (IntrinsicID == Intrinsic::thread_pointer) { 10188 // Reads the thread pointer register, used for __builtin_thread_pointer. 10189 if (Subtarget.isPPC64()) 10190 return DAG.getRegister(PPC::X13, MVT::i64); 10191 return DAG.getRegister(PPC::R2, MVT::i32); 10192 } 10193 10194 // If this is a lowered altivec predicate compare, CompareOpc is set to the 10195 // opcode number of the comparison. 10196 int CompareOpc; 10197 bool isDot; 10198 if (!getVectorCompareInfo(Op, CompareOpc, isDot, Subtarget)) 10199 return SDValue(); // Don't custom lower most intrinsics. 10200 10201 // If this is a non-dot comparison, make the VCMP node and we are done. 10202 if (!isDot) { 10203 SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(), 10204 Op.getOperand(1), Op.getOperand(2), 10205 DAG.getConstant(CompareOpc, dl, MVT::i32)); 10206 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp); 10207 } 10208 10209 // Create the PPCISD altivec 'dot' comparison node. 10210 SDValue Ops[] = { 10211 Op.getOperand(2), // LHS 10212 Op.getOperand(3), // RHS 10213 DAG.getConstant(CompareOpc, dl, MVT::i32) 10214 }; 10215 EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue }; 10216 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops); 10217 10218 // Now that we have the comparison, emit a copy from the CR to a GPR. 10219 // This is flagged to the above dot comparison. 10220 SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32, 10221 DAG.getRegister(PPC::CR6, MVT::i32), 10222 CompNode.getValue(1)); 10223 10224 // Unpack the result based on how the target uses it. 10225 unsigned BitNo; // Bit # of CR6. 10226 bool InvertBit; // Invert result? 10227 switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) { 10228 default: // Can't happen, don't crash on invalid number though. 10229 case 0: // Return the value of the EQ bit of CR6. 10230 BitNo = 0; InvertBit = false; 10231 break; 10232 case 1: // Return the inverted value of the EQ bit of CR6. 10233 BitNo = 0; InvertBit = true; 10234 break; 10235 case 2: // Return the value of the LT bit of CR6. 10236 BitNo = 2; InvertBit = false; 10237 break; 10238 case 3: // Return the inverted value of the LT bit of CR6. 10239 BitNo = 2; InvertBit = true; 10240 break; 10241 } 10242 10243 // Shift the bit into the low position. 10244 Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags, 10245 DAG.getConstant(8 - (3 - BitNo), dl, MVT::i32)); 10246 // Isolate the bit. 10247 Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags, 10248 DAG.getConstant(1, dl, MVT::i32)); 10249 10250 // If we are supposed to, toggle the bit. 10251 if (InvertBit) 10252 Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags, 10253 DAG.getConstant(1, dl, MVT::i32)); 10254 return Flags; 10255 } 10256 10257 SDValue PPCTargetLowering::LowerINTRINSIC_VOID(SDValue Op, 10258 SelectionDAG &DAG) const { 10259 // SelectionDAGBuilder::visitTargetIntrinsic may insert one extra chain to 10260 // the beginning of the argument list. 10261 int ArgStart = isa<ConstantSDNode>(Op.getOperand(0)) ? 0 : 1; 10262 SDLoc DL(Op); 10263 switch (cast<ConstantSDNode>(Op.getOperand(ArgStart))->getZExtValue()) { 10264 case Intrinsic::ppc_cfence: { 10265 assert(ArgStart == 1 && "llvm.ppc.cfence must carry a chain argument."); 10266 assert(Subtarget.isPPC64() && "Only 64-bit is supported for now."); 10267 return SDValue(DAG.getMachineNode(PPC::CFENCE8, DL, MVT::Other, 10268 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, 10269 Op.getOperand(ArgStart + 1)), 10270 Op.getOperand(0)), 10271 0); 10272 } 10273 default: 10274 break; 10275 } 10276 return SDValue(); 10277 } 10278 10279 SDValue PPCTargetLowering::LowerREM(SDValue Op, SelectionDAG &DAG) const { 10280 // Check for a DIV with the same operands as this REM. 10281 for (auto UI : Op.getOperand(1)->uses()) { 10282 if ((Op.getOpcode() == ISD::SREM && UI->getOpcode() == ISD::SDIV) || 10283 (Op.getOpcode() == ISD::UREM && UI->getOpcode() == ISD::UDIV)) 10284 if (UI->getOperand(0) == Op.getOperand(0) && 10285 UI->getOperand(1) == Op.getOperand(1)) 10286 return SDValue(); 10287 } 10288 return Op; 10289 } 10290 10291 // Lower scalar BSWAP64 to xxbrd. 10292 SDValue PPCTargetLowering::LowerBSWAP(SDValue Op, SelectionDAG &DAG) const { 10293 SDLoc dl(Op); 10294 // MTVSRDD 10295 Op = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i64, Op.getOperand(0), 10296 Op.getOperand(0)); 10297 // XXBRD 10298 Op = DAG.getNode(ISD::BSWAP, dl, MVT::v2i64, Op); 10299 // MFVSRD 10300 int VectorIndex = 0; 10301 if (Subtarget.isLittleEndian()) 10302 VectorIndex = 1; 10303 Op = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Op, 10304 DAG.getTargetConstant(VectorIndex, dl, MVT::i32)); 10305 return Op; 10306 } 10307 10308 // ATOMIC_CMP_SWAP for i8/i16 needs to zero-extend its input since it will be 10309 // compared to a value that is atomically loaded (atomic loads zero-extend). 10310 SDValue PPCTargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, 10311 SelectionDAG &DAG) const { 10312 assert(Op.getOpcode() == ISD::ATOMIC_CMP_SWAP && 10313 "Expecting an atomic compare-and-swap here."); 10314 SDLoc dl(Op); 10315 auto *AtomicNode = cast<AtomicSDNode>(Op.getNode()); 10316 EVT MemVT = AtomicNode->getMemoryVT(); 10317 if (MemVT.getSizeInBits() >= 32) 10318 return Op; 10319 10320 SDValue CmpOp = Op.getOperand(2); 10321 // If this is already correctly zero-extended, leave it alone. 10322 auto HighBits = APInt::getHighBitsSet(32, 32 - MemVT.getSizeInBits()); 10323 if (DAG.MaskedValueIsZero(CmpOp, HighBits)) 10324 return Op; 10325 10326 // Clear the high bits of the compare operand. 10327 unsigned MaskVal = (1 << MemVT.getSizeInBits()) - 1; 10328 SDValue NewCmpOp = 10329 DAG.getNode(ISD::AND, dl, MVT::i32, CmpOp, 10330 DAG.getConstant(MaskVal, dl, MVT::i32)); 10331 10332 // Replace the existing compare operand with the properly zero-extended one. 10333 SmallVector<SDValue, 4> Ops; 10334 for (int i = 0, e = AtomicNode->getNumOperands(); i < e; i++) 10335 Ops.push_back(AtomicNode->getOperand(i)); 10336 Ops[2] = NewCmpOp; 10337 MachineMemOperand *MMO = AtomicNode->getMemOperand(); 10338 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::Other); 10339 auto NodeTy = 10340 (MemVT == MVT::i8) ? PPCISD::ATOMIC_CMP_SWAP_8 : PPCISD::ATOMIC_CMP_SWAP_16; 10341 return DAG.getMemIntrinsicNode(NodeTy, dl, Tys, Ops, MemVT, MMO); 10342 } 10343 10344 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, 10345 SelectionDAG &DAG) const { 10346 SDLoc dl(Op); 10347 // Create a stack slot that is 16-byte aligned. 10348 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 10349 int FrameIdx = MFI.CreateStackObject(16, 16, false); 10350 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 10351 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 10352 10353 // Store the input value into Value#0 of the stack slot. 10354 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx, 10355 MachinePointerInfo()); 10356 // Load it out. 10357 return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo()); 10358 } 10359 10360 SDValue PPCTargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, 10361 SelectionDAG &DAG) const { 10362 assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && 10363 "Should only be called for ISD::INSERT_VECTOR_ELT"); 10364 10365 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(2)); 10366 // We have legal lowering for constant indices but not for variable ones. 10367 if (!C) 10368 return SDValue(); 10369 10370 EVT VT = Op.getValueType(); 10371 SDLoc dl(Op); 10372 SDValue V1 = Op.getOperand(0); 10373 SDValue V2 = Op.getOperand(1); 10374 // We can use MTVSRZ + VECINSERT for v8i16 and v16i8 types. 10375 if (VT == MVT::v8i16 || VT == MVT::v16i8) { 10376 SDValue Mtvsrz = DAG.getNode(PPCISD::MTVSRZ, dl, VT, V2); 10377 unsigned BytesInEachElement = VT.getVectorElementType().getSizeInBits() / 8; 10378 unsigned InsertAtElement = C->getZExtValue(); 10379 unsigned InsertAtByte = InsertAtElement * BytesInEachElement; 10380 if (Subtarget.isLittleEndian()) { 10381 InsertAtByte = (16 - BytesInEachElement) - InsertAtByte; 10382 } 10383 return DAG.getNode(PPCISD::VECINSERT, dl, VT, V1, Mtvsrz, 10384 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 10385 } 10386 return Op; 10387 } 10388 10389 SDValue PPCTargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op, 10390 SelectionDAG &DAG) const { 10391 SDLoc dl(Op); 10392 SDNode *N = Op.getNode(); 10393 10394 assert(N->getOperand(0).getValueType() == MVT::v4i1 && 10395 "Unknown extract_vector_elt type"); 10396 10397 SDValue Value = N->getOperand(0); 10398 10399 // The first part of this is like the store lowering except that we don't 10400 // need to track the chain. 10401 10402 // The values are now known to be -1 (false) or 1 (true). To convert this 10403 // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5). 10404 // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5 10405 Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value); 10406 10407 // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to 10408 // understand how to form the extending load. 10409 SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64); 10410 10411 Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs); 10412 10413 // Now convert to an integer and store. 10414 Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64, 10415 DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32), 10416 Value); 10417 10418 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 10419 int FrameIdx = MFI.CreateStackObject(16, 16, false); 10420 MachinePointerInfo PtrInfo = 10421 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 10422 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 10423 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 10424 10425 SDValue StoreChain = DAG.getEntryNode(); 10426 SDValue Ops[] = {StoreChain, 10427 DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32), 10428 Value, FIdx}; 10429 SDVTList VTs = DAG.getVTList(/*chain*/ MVT::Other); 10430 10431 StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, 10432 dl, VTs, Ops, MVT::v4i32, PtrInfo); 10433 10434 // Extract the value requested. 10435 unsigned Offset = 4*cast<ConstantSDNode>(N->getOperand(1))->getZExtValue(); 10436 SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType()); 10437 Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx); 10438 10439 SDValue IntVal = 10440 DAG.getLoad(MVT::i32, dl, StoreChain, Idx, PtrInfo.getWithOffset(Offset)); 10441 10442 if (!Subtarget.useCRBits()) 10443 return IntVal; 10444 10445 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, IntVal); 10446 } 10447 10448 /// Lowering for QPX v4i1 loads 10449 SDValue PPCTargetLowering::LowerVectorLoad(SDValue Op, 10450 SelectionDAG &DAG) const { 10451 SDLoc dl(Op); 10452 LoadSDNode *LN = cast<LoadSDNode>(Op.getNode()); 10453 SDValue LoadChain = LN->getChain(); 10454 SDValue BasePtr = LN->getBasePtr(); 10455 10456 if (Op.getValueType() == MVT::v4f64 || 10457 Op.getValueType() == MVT::v4f32) { 10458 EVT MemVT = LN->getMemoryVT(); 10459 unsigned Alignment = LN->getAlignment(); 10460 10461 // If this load is properly aligned, then it is legal. 10462 if (Alignment >= MemVT.getStoreSize()) 10463 return Op; 10464 10465 EVT ScalarVT = Op.getValueType().getScalarType(), 10466 ScalarMemVT = MemVT.getScalarType(); 10467 unsigned Stride = ScalarMemVT.getStoreSize(); 10468 10469 SDValue Vals[4], LoadChains[4]; 10470 for (unsigned Idx = 0; Idx < 4; ++Idx) { 10471 SDValue Load; 10472 if (ScalarVT != ScalarMemVT) 10473 Load = DAG.getExtLoad(LN->getExtensionType(), dl, ScalarVT, LoadChain, 10474 BasePtr, 10475 LN->getPointerInfo().getWithOffset(Idx * Stride), 10476 ScalarMemVT, MinAlign(Alignment, Idx * Stride), 10477 LN->getMemOperand()->getFlags(), LN->getAAInfo()); 10478 else 10479 Load = DAG.getLoad(ScalarVT, dl, LoadChain, BasePtr, 10480 LN->getPointerInfo().getWithOffset(Idx * Stride), 10481 MinAlign(Alignment, Idx * Stride), 10482 LN->getMemOperand()->getFlags(), LN->getAAInfo()); 10483 10484 if (Idx == 0 && LN->isIndexed()) { 10485 assert(LN->getAddressingMode() == ISD::PRE_INC && 10486 "Unknown addressing mode on vector load"); 10487 Load = DAG.getIndexedLoad(Load, dl, BasePtr, LN->getOffset(), 10488 LN->getAddressingMode()); 10489 } 10490 10491 Vals[Idx] = Load; 10492 LoadChains[Idx] = Load.getValue(1); 10493 10494 BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, 10495 DAG.getConstant(Stride, dl, 10496 BasePtr.getValueType())); 10497 } 10498 10499 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains); 10500 SDValue Value = DAG.getBuildVector(Op.getValueType(), dl, Vals); 10501 10502 if (LN->isIndexed()) { 10503 SDValue RetOps[] = { Value, Vals[0].getValue(1), TF }; 10504 return DAG.getMergeValues(RetOps, dl); 10505 } 10506 10507 SDValue RetOps[] = { Value, TF }; 10508 return DAG.getMergeValues(RetOps, dl); 10509 } 10510 10511 assert(Op.getValueType() == MVT::v4i1 && "Unknown load to lower"); 10512 assert(LN->isUnindexed() && "Indexed v4i1 loads are not supported"); 10513 10514 // To lower v4i1 from a byte array, we load the byte elements of the 10515 // vector and then reuse the BUILD_VECTOR logic. 10516 10517 SDValue VectElmts[4], VectElmtChains[4]; 10518 for (unsigned i = 0; i < 4; ++i) { 10519 SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType()); 10520 Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx); 10521 10522 VectElmts[i] = DAG.getExtLoad( 10523 ISD::EXTLOAD, dl, MVT::i32, LoadChain, Idx, 10524 LN->getPointerInfo().getWithOffset(i), MVT::i8, 10525 /* Alignment = */ 1, LN->getMemOperand()->getFlags(), LN->getAAInfo()); 10526 VectElmtChains[i] = VectElmts[i].getValue(1); 10527 } 10528 10529 LoadChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, VectElmtChains); 10530 SDValue Value = DAG.getBuildVector(MVT::v4i1, dl, VectElmts); 10531 10532 SDValue RVals[] = { Value, LoadChain }; 10533 return DAG.getMergeValues(RVals, dl); 10534 } 10535 10536 /// Lowering for QPX v4i1 stores 10537 SDValue PPCTargetLowering::LowerVectorStore(SDValue Op, 10538 SelectionDAG &DAG) const { 10539 SDLoc dl(Op); 10540 StoreSDNode *SN = cast<StoreSDNode>(Op.getNode()); 10541 SDValue StoreChain = SN->getChain(); 10542 SDValue BasePtr = SN->getBasePtr(); 10543 SDValue Value = SN->getValue(); 10544 10545 if (Value.getValueType() == MVT::v4f64 || 10546 Value.getValueType() == MVT::v4f32) { 10547 EVT MemVT = SN->getMemoryVT(); 10548 unsigned Alignment = SN->getAlignment(); 10549 10550 // If this store is properly aligned, then it is legal. 10551 if (Alignment >= MemVT.getStoreSize()) 10552 return Op; 10553 10554 EVT ScalarVT = Value.getValueType().getScalarType(), 10555 ScalarMemVT = MemVT.getScalarType(); 10556 unsigned Stride = ScalarMemVT.getStoreSize(); 10557 10558 SDValue Stores[4]; 10559 for (unsigned Idx = 0; Idx < 4; ++Idx) { 10560 SDValue Ex = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, Value, 10561 DAG.getVectorIdxConstant(Idx, dl)); 10562 SDValue Store; 10563 if (ScalarVT != ScalarMemVT) 10564 Store = 10565 DAG.getTruncStore(StoreChain, dl, Ex, BasePtr, 10566 SN->getPointerInfo().getWithOffset(Idx * Stride), 10567 ScalarMemVT, MinAlign(Alignment, Idx * Stride), 10568 SN->getMemOperand()->getFlags(), SN->getAAInfo()); 10569 else 10570 Store = DAG.getStore(StoreChain, dl, Ex, BasePtr, 10571 SN->getPointerInfo().getWithOffset(Idx * Stride), 10572 MinAlign(Alignment, Idx * Stride), 10573 SN->getMemOperand()->getFlags(), SN->getAAInfo()); 10574 10575 if (Idx == 0 && SN->isIndexed()) { 10576 assert(SN->getAddressingMode() == ISD::PRE_INC && 10577 "Unknown addressing mode on vector store"); 10578 Store = DAG.getIndexedStore(Store, dl, BasePtr, SN->getOffset(), 10579 SN->getAddressingMode()); 10580 } 10581 10582 BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, 10583 DAG.getConstant(Stride, dl, 10584 BasePtr.getValueType())); 10585 Stores[Idx] = Store; 10586 } 10587 10588 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores); 10589 10590 if (SN->isIndexed()) { 10591 SDValue RetOps[] = { TF, Stores[0].getValue(1) }; 10592 return DAG.getMergeValues(RetOps, dl); 10593 } 10594 10595 return TF; 10596 } 10597 10598 assert(SN->isUnindexed() && "Indexed v4i1 stores are not supported"); 10599 assert(Value.getValueType() == MVT::v4i1 && "Unknown store to lower"); 10600 10601 // The values are now known to be -1 (false) or 1 (true). To convert this 10602 // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5). 10603 // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5 10604 Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value); 10605 10606 // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to 10607 // understand how to form the extending load. 10608 SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64); 10609 10610 Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs); 10611 10612 // Now convert to an integer and store. 10613 Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64, 10614 DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32), 10615 Value); 10616 10617 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 10618 int FrameIdx = MFI.CreateStackObject(16, 16, false); 10619 MachinePointerInfo PtrInfo = 10620 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 10621 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 10622 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 10623 10624 SDValue Ops[] = {StoreChain, 10625 DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32), 10626 Value, FIdx}; 10627 SDVTList VTs = DAG.getVTList(/*chain*/ MVT::Other); 10628 10629 StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, 10630 dl, VTs, Ops, MVT::v4i32, PtrInfo); 10631 10632 // Move data into the byte array. 10633 SDValue Loads[4], LoadChains[4]; 10634 for (unsigned i = 0; i < 4; ++i) { 10635 unsigned Offset = 4*i; 10636 SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType()); 10637 Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx); 10638 10639 Loads[i] = DAG.getLoad(MVT::i32, dl, StoreChain, Idx, 10640 PtrInfo.getWithOffset(Offset)); 10641 LoadChains[i] = Loads[i].getValue(1); 10642 } 10643 10644 StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains); 10645 10646 SDValue Stores[4]; 10647 for (unsigned i = 0; i < 4; ++i) { 10648 SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType()); 10649 Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx); 10650 10651 Stores[i] = DAG.getTruncStore( 10652 StoreChain, dl, Loads[i], Idx, SN->getPointerInfo().getWithOffset(i), 10653 MVT::i8, /* Alignment = */ 1, SN->getMemOperand()->getFlags(), 10654 SN->getAAInfo()); 10655 } 10656 10657 StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores); 10658 10659 return StoreChain; 10660 } 10661 10662 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const { 10663 SDLoc dl(Op); 10664 if (Op.getValueType() == MVT::v4i32) { 10665 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 10666 10667 SDValue Zero = BuildSplatI( 0, 1, MVT::v4i32, DAG, dl); 10668 SDValue Neg16 = BuildSplatI(-16, 4, MVT::v4i32, DAG, dl);//+16 as shift amt. 10669 10670 SDValue RHSSwap = // = vrlw RHS, 16 10671 BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl); 10672 10673 // Shrinkify inputs to v8i16. 10674 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS); 10675 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS); 10676 RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap); 10677 10678 // Low parts multiplied together, generating 32-bit results (we ignore the 10679 // top parts). 10680 SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh, 10681 LHS, RHS, DAG, dl, MVT::v4i32); 10682 10683 SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm, 10684 LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32); 10685 // Shift the high parts up 16 bits. 10686 HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd, 10687 Neg16, DAG, dl); 10688 return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd); 10689 } else if (Op.getValueType() == MVT::v16i8) { 10690 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 10691 bool isLittleEndian = Subtarget.isLittleEndian(); 10692 10693 // Multiply the even 8-bit parts, producing 16-bit sums. 10694 SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub, 10695 LHS, RHS, DAG, dl, MVT::v8i16); 10696 EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts); 10697 10698 // Multiply the odd 8-bit parts, producing 16-bit sums. 10699 SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub, 10700 LHS, RHS, DAG, dl, MVT::v8i16); 10701 OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts); 10702 10703 // Merge the results together. Because vmuleub and vmuloub are 10704 // instructions with a big-endian bias, we must reverse the 10705 // element numbering and reverse the meaning of "odd" and "even" 10706 // when generating little endian code. 10707 int Ops[16]; 10708 for (unsigned i = 0; i != 8; ++i) { 10709 if (isLittleEndian) { 10710 Ops[i*2 ] = 2*i; 10711 Ops[i*2+1] = 2*i+16; 10712 } else { 10713 Ops[i*2 ] = 2*i+1; 10714 Ops[i*2+1] = 2*i+1+16; 10715 } 10716 } 10717 if (isLittleEndian) 10718 return DAG.getVectorShuffle(MVT::v16i8, dl, OddParts, EvenParts, Ops); 10719 else 10720 return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops); 10721 } else { 10722 llvm_unreachable("Unknown mul to lower!"); 10723 } 10724 } 10725 10726 SDValue PPCTargetLowering::LowerABS(SDValue Op, SelectionDAG &DAG) const { 10727 10728 assert(Op.getOpcode() == ISD::ABS && "Should only be called for ISD::ABS"); 10729 10730 EVT VT = Op.getValueType(); 10731 assert(VT.isVector() && 10732 "Only set vector abs as custom, scalar abs shouldn't reach here!"); 10733 assert((VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 || 10734 VT == MVT::v16i8) && 10735 "Unexpected vector element type!"); 10736 assert((VT != MVT::v2i64 || Subtarget.hasP8Altivec()) && 10737 "Current subtarget doesn't support smax v2i64!"); 10738 10739 // For vector abs, it can be lowered to: 10740 // abs x 10741 // ==> 10742 // y = -x 10743 // smax(x, y) 10744 10745 SDLoc dl(Op); 10746 SDValue X = Op.getOperand(0); 10747 SDValue Zero = DAG.getConstant(0, dl, VT); 10748 SDValue Y = DAG.getNode(ISD::SUB, dl, VT, Zero, X); 10749 10750 // SMAX patch https://reviews.llvm.org/D47332 10751 // hasn't landed yet, so use intrinsic first here. 10752 // TODO: Should use SMAX directly once SMAX patch landed 10753 Intrinsic::ID BifID = Intrinsic::ppc_altivec_vmaxsw; 10754 if (VT == MVT::v2i64) 10755 BifID = Intrinsic::ppc_altivec_vmaxsd; 10756 else if (VT == MVT::v8i16) 10757 BifID = Intrinsic::ppc_altivec_vmaxsh; 10758 else if (VT == MVT::v16i8) 10759 BifID = Intrinsic::ppc_altivec_vmaxsb; 10760 10761 return BuildIntrinsicOp(BifID, X, Y, DAG, dl, VT); 10762 } 10763 10764 // Custom lowering for fpext vf32 to v2f64 10765 SDValue PPCTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const { 10766 10767 assert(Op.getOpcode() == ISD::FP_EXTEND && 10768 "Should only be called for ISD::FP_EXTEND"); 10769 10770 // FIXME: handle extends from half precision float vectors on P9. 10771 // We only want to custom lower an extend from v2f32 to v2f64. 10772 if (Op.getValueType() != MVT::v2f64 || 10773 Op.getOperand(0).getValueType() != MVT::v2f32) 10774 return SDValue(); 10775 10776 SDLoc dl(Op); 10777 SDValue Op0 = Op.getOperand(0); 10778 10779 switch (Op0.getOpcode()) { 10780 default: 10781 return SDValue(); 10782 case ISD::EXTRACT_SUBVECTOR: { 10783 assert(Op0.getNumOperands() == 2 && 10784 isa<ConstantSDNode>(Op0->getOperand(1)) && 10785 "Node should have 2 operands with second one being a constant!"); 10786 10787 if (Op0.getOperand(0).getValueType() != MVT::v4f32) 10788 return SDValue(); 10789 10790 // Custom lower is only done for high or low doubleword. 10791 int Idx = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue(); 10792 if (Idx % 2 != 0) 10793 return SDValue(); 10794 10795 // Since input is v4f32, at this point Idx is either 0 or 2. 10796 // Shift to get the doubleword position we want. 10797 int DWord = Idx >> 1; 10798 10799 // High and low word positions are different on little endian. 10800 if (Subtarget.isLittleEndian()) 10801 DWord ^= 0x1; 10802 10803 return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, 10804 Op0.getOperand(0), DAG.getConstant(DWord, dl, MVT::i32)); 10805 } 10806 case ISD::FADD: 10807 case ISD::FMUL: 10808 case ISD::FSUB: { 10809 SDValue NewLoad[2]; 10810 for (unsigned i = 0, ie = Op0.getNumOperands(); i != ie; ++i) { 10811 // Ensure both input are loads. 10812 SDValue LdOp = Op0.getOperand(i); 10813 if (LdOp.getOpcode() != ISD::LOAD) 10814 return SDValue(); 10815 // Generate new load node. 10816 LoadSDNode *LD = cast<LoadSDNode>(LdOp); 10817 SDValue LoadOps[] = {LD->getChain(), LD->getBasePtr()}; 10818 NewLoad[i] = DAG.getMemIntrinsicNode( 10819 PPCISD::LD_VSX_LH, dl, DAG.getVTList(MVT::v4f32, MVT::Other), LoadOps, 10820 LD->getMemoryVT(), LD->getMemOperand()); 10821 } 10822 SDValue NewOp = 10823 DAG.getNode(Op0.getOpcode(), SDLoc(Op0), MVT::v4f32, NewLoad[0], 10824 NewLoad[1], Op0.getNode()->getFlags()); 10825 return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, NewOp, 10826 DAG.getConstant(0, dl, MVT::i32)); 10827 } 10828 case ISD::LOAD: { 10829 LoadSDNode *LD = cast<LoadSDNode>(Op0); 10830 SDValue LoadOps[] = {LD->getChain(), LD->getBasePtr()}; 10831 SDValue NewLd = DAG.getMemIntrinsicNode( 10832 PPCISD::LD_VSX_LH, dl, DAG.getVTList(MVT::v4f32, MVT::Other), LoadOps, 10833 LD->getMemoryVT(), LD->getMemOperand()); 10834 return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, NewLd, 10835 DAG.getConstant(0, dl, MVT::i32)); 10836 } 10837 } 10838 llvm_unreachable("ERROR:Should return for all cases within swtich."); 10839 } 10840 10841 /// LowerOperation - Provide custom lowering hooks for some operations. 10842 /// 10843 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 10844 switch (Op.getOpcode()) { 10845 default: llvm_unreachable("Wasn't expecting to be able to lower this!"); 10846 case ISD::ConstantPool: return LowerConstantPool(Op, DAG); 10847 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG); 10848 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG); 10849 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG); 10850 case ISD::JumpTable: return LowerJumpTable(Op, DAG); 10851 case ISD::SETCC: return LowerSETCC(Op, DAG); 10852 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG); 10853 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG); 10854 10855 // Variable argument lowering. 10856 case ISD::VASTART: return LowerVASTART(Op, DAG); 10857 case ISD::VAARG: return LowerVAARG(Op, DAG); 10858 case ISD::VACOPY: return LowerVACOPY(Op, DAG); 10859 10860 case ISD::STACKRESTORE: return LowerSTACKRESTORE(Op, DAG); 10861 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG); 10862 case ISD::GET_DYNAMIC_AREA_OFFSET: 10863 return LowerGET_DYNAMIC_AREA_OFFSET(Op, DAG); 10864 10865 // Exception handling lowering. 10866 case ISD::EH_DWARF_CFA: return LowerEH_DWARF_CFA(Op, DAG); 10867 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG); 10868 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG); 10869 10870 case ISD::LOAD: return LowerLOAD(Op, DAG); 10871 case ISD::STORE: return LowerSTORE(Op, DAG); 10872 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG); 10873 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG); 10874 case ISD::FP_TO_UINT: 10875 case ISD::FP_TO_SINT: return LowerFP_TO_INT(Op, DAG, SDLoc(Op)); 10876 case ISD::UINT_TO_FP: 10877 case ISD::SINT_TO_FP: return LowerINT_TO_FP(Op, DAG); 10878 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG); 10879 10880 // Lower 64-bit shifts. 10881 case ISD::SHL_PARTS: return LowerSHL_PARTS(Op, DAG); 10882 case ISD::SRL_PARTS: return LowerSRL_PARTS(Op, DAG); 10883 case ISD::SRA_PARTS: return LowerSRA_PARTS(Op, DAG); 10884 10885 // Vector-related lowering. 10886 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG); 10887 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG); 10888 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG); 10889 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG); 10890 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG); 10891 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG); 10892 case ISD::MUL: return LowerMUL(Op, DAG); 10893 case ISD::ABS: return LowerABS(Op, DAG); 10894 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG); 10895 10896 // For counter-based loop handling. 10897 case ISD::INTRINSIC_W_CHAIN: return SDValue(); 10898 10899 case ISD::BITCAST: return LowerBITCAST(Op, DAG); 10900 10901 // Frame & Return address. 10902 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG); 10903 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG); 10904 10905 case ISD::INTRINSIC_VOID: 10906 return LowerINTRINSIC_VOID(Op, DAG); 10907 case ISD::SREM: 10908 case ISD::UREM: 10909 return LowerREM(Op, DAG); 10910 case ISD::BSWAP: 10911 return LowerBSWAP(Op, DAG); 10912 case ISD::ATOMIC_CMP_SWAP: 10913 return LowerATOMIC_CMP_SWAP(Op, DAG); 10914 } 10915 } 10916 10917 void PPCTargetLowering::ReplaceNodeResults(SDNode *N, 10918 SmallVectorImpl<SDValue>&Results, 10919 SelectionDAG &DAG) const { 10920 SDLoc dl(N); 10921 switch (N->getOpcode()) { 10922 default: 10923 llvm_unreachable("Do not know how to custom type legalize this operation!"); 10924 case ISD::READCYCLECOUNTER: { 10925 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other); 10926 SDValue RTB = DAG.getNode(PPCISD::READ_TIME_BASE, dl, VTs, N->getOperand(0)); 10927 10928 Results.push_back( 10929 DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, RTB, RTB.getValue(1))); 10930 Results.push_back(RTB.getValue(2)); 10931 break; 10932 } 10933 case ISD::INTRINSIC_W_CHAIN: { 10934 if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 10935 Intrinsic::loop_decrement) 10936 break; 10937 10938 assert(N->getValueType(0) == MVT::i1 && 10939 "Unexpected result type for CTR decrement intrinsic"); 10940 EVT SVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 10941 N->getValueType(0)); 10942 SDVTList VTs = DAG.getVTList(SVT, MVT::Other); 10943 SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0), 10944 N->getOperand(1)); 10945 10946 Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewInt)); 10947 Results.push_back(NewInt.getValue(1)); 10948 break; 10949 } 10950 case ISD::VAARG: { 10951 if (!Subtarget.isSVR4ABI() || Subtarget.isPPC64()) 10952 return; 10953 10954 EVT VT = N->getValueType(0); 10955 10956 if (VT == MVT::i64) { 10957 SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG); 10958 10959 Results.push_back(NewNode); 10960 Results.push_back(NewNode.getValue(1)); 10961 } 10962 return; 10963 } 10964 case ISD::FP_TO_SINT: 10965 case ISD::FP_TO_UINT: 10966 // LowerFP_TO_INT() can only handle f32 and f64. 10967 if (N->getOperand(0).getValueType() == MVT::ppcf128) 10968 return; 10969 Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl)); 10970 return; 10971 case ISD::TRUNCATE: { 10972 EVT TrgVT = N->getValueType(0); 10973 EVT OpVT = N->getOperand(0).getValueType(); 10974 if (TrgVT.isVector() && 10975 isOperationCustom(N->getOpcode(), TrgVT) && 10976 OpVT.getSizeInBits() <= 128 && 10977 isPowerOf2_32(OpVT.getVectorElementType().getSizeInBits())) 10978 Results.push_back(LowerTRUNCATEVector(SDValue(N, 0), DAG)); 10979 return; 10980 } 10981 case ISD::BITCAST: 10982 // Don't handle bitcast here. 10983 return; 10984 case ISD::FP_EXTEND: 10985 SDValue Lowered = LowerFP_EXTEND(SDValue(N, 0), DAG); 10986 if (Lowered) 10987 Results.push_back(Lowered); 10988 return; 10989 } 10990 } 10991 10992 //===----------------------------------------------------------------------===// 10993 // Other Lowering Code 10994 //===----------------------------------------------------------------------===// 10995 10996 static Instruction* callIntrinsic(IRBuilder<> &Builder, Intrinsic::ID Id) { 10997 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 10998 Function *Func = Intrinsic::getDeclaration(M, Id); 10999 return Builder.CreateCall(Func, {}); 11000 } 11001 11002 // The mappings for emitLeading/TrailingFence is taken from 11003 // http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html 11004 Instruction *PPCTargetLowering::emitLeadingFence(IRBuilder<> &Builder, 11005 Instruction *Inst, 11006 AtomicOrdering Ord) const { 11007 if (Ord == AtomicOrdering::SequentiallyConsistent) 11008 return callIntrinsic(Builder, Intrinsic::ppc_sync); 11009 if (isReleaseOrStronger(Ord)) 11010 return callIntrinsic(Builder, Intrinsic::ppc_lwsync); 11011 return nullptr; 11012 } 11013 11014 Instruction *PPCTargetLowering::emitTrailingFence(IRBuilder<> &Builder, 11015 Instruction *Inst, 11016 AtomicOrdering Ord) const { 11017 if (Inst->hasAtomicLoad() && isAcquireOrStronger(Ord)) { 11018 // See http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html and 11019 // http://www.rdrop.com/users/paulmck/scalability/paper/N2745r.2011.03.04a.html 11020 // and http://www.cl.cam.ac.uk/~pes20/cppppc/ for justification. 11021 if (isa<LoadInst>(Inst) && Subtarget.isPPC64()) 11022 return Builder.CreateCall( 11023 Intrinsic::getDeclaration( 11024 Builder.GetInsertBlock()->getParent()->getParent(), 11025 Intrinsic::ppc_cfence, {Inst->getType()}), 11026 {Inst}); 11027 // FIXME: Can use isync for rmw operation. 11028 return callIntrinsic(Builder, Intrinsic::ppc_lwsync); 11029 } 11030 return nullptr; 11031 } 11032 11033 MachineBasicBlock * 11034 PPCTargetLowering::EmitAtomicBinary(MachineInstr &MI, MachineBasicBlock *BB, 11035 unsigned AtomicSize, 11036 unsigned BinOpcode, 11037 unsigned CmpOpcode, 11038 unsigned CmpPred) const { 11039 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0. 11040 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 11041 11042 auto LoadMnemonic = PPC::LDARX; 11043 auto StoreMnemonic = PPC::STDCX; 11044 switch (AtomicSize) { 11045 default: 11046 llvm_unreachable("Unexpected size of atomic entity"); 11047 case 1: 11048 LoadMnemonic = PPC::LBARX; 11049 StoreMnemonic = PPC::STBCX; 11050 assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4"); 11051 break; 11052 case 2: 11053 LoadMnemonic = PPC::LHARX; 11054 StoreMnemonic = PPC::STHCX; 11055 assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4"); 11056 break; 11057 case 4: 11058 LoadMnemonic = PPC::LWARX; 11059 StoreMnemonic = PPC::STWCX; 11060 break; 11061 case 8: 11062 LoadMnemonic = PPC::LDARX; 11063 StoreMnemonic = PPC::STDCX; 11064 break; 11065 } 11066 11067 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 11068 MachineFunction *F = BB->getParent(); 11069 MachineFunction::iterator It = ++BB->getIterator(); 11070 11071 Register dest = MI.getOperand(0).getReg(); 11072 Register ptrA = MI.getOperand(1).getReg(); 11073 Register ptrB = MI.getOperand(2).getReg(); 11074 Register incr = MI.getOperand(3).getReg(); 11075 DebugLoc dl = MI.getDebugLoc(); 11076 11077 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB); 11078 MachineBasicBlock *loop2MBB = 11079 CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr; 11080 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 11081 F->insert(It, loopMBB); 11082 if (CmpOpcode) 11083 F->insert(It, loop2MBB); 11084 F->insert(It, exitMBB); 11085 exitMBB->splice(exitMBB->begin(), BB, 11086 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 11087 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 11088 11089 MachineRegisterInfo &RegInfo = F->getRegInfo(); 11090 Register TmpReg = (!BinOpcode) ? incr : 11091 RegInfo.createVirtualRegister( AtomicSize == 8 ? &PPC::G8RCRegClass 11092 : &PPC::GPRCRegClass); 11093 11094 // thisMBB: 11095 // ... 11096 // fallthrough --> loopMBB 11097 BB->addSuccessor(loopMBB); 11098 11099 // loopMBB: 11100 // l[wd]arx dest, ptr 11101 // add r0, dest, incr 11102 // st[wd]cx. r0, ptr 11103 // bne- loopMBB 11104 // fallthrough --> exitMBB 11105 11106 // For max/min... 11107 // loopMBB: 11108 // l[wd]arx dest, ptr 11109 // cmpl?[wd] incr, dest 11110 // bgt exitMBB 11111 // loop2MBB: 11112 // st[wd]cx. dest, ptr 11113 // bne- loopMBB 11114 // fallthrough --> exitMBB 11115 11116 BB = loopMBB; 11117 BuildMI(BB, dl, TII->get(LoadMnemonic), dest) 11118 .addReg(ptrA).addReg(ptrB); 11119 if (BinOpcode) 11120 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest); 11121 if (CmpOpcode) { 11122 // Signed comparisons of byte or halfword values must be sign-extended. 11123 if (CmpOpcode == PPC::CMPW && AtomicSize < 4) { 11124 Register ExtReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass); 11125 BuildMI(BB, dl, TII->get(AtomicSize == 1 ? PPC::EXTSB : PPC::EXTSH), 11126 ExtReg).addReg(dest); 11127 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0) 11128 .addReg(incr).addReg(ExtReg); 11129 } else 11130 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0) 11131 .addReg(incr).addReg(dest); 11132 11133 BuildMI(BB, dl, TII->get(PPC::BCC)) 11134 .addImm(CmpPred).addReg(PPC::CR0).addMBB(exitMBB); 11135 BB->addSuccessor(loop2MBB); 11136 BB->addSuccessor(exitMBB); 11137 BB = loop2MBB; 11138 } 11139 BuildMI(BB, dl, TII->get(StoreMnemonic)) 11140 .addReg(TmpReg).addReg(ptrA).addReg(ptrB); 11141 BuildMI(BB, dl, TII->get(PPC::BCC)) 11142 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB); 11143 BB->addSuccessor(loopMBB); 11144 BB->addSuccessor(exitMBB); 11145 11146 // exitMBB: 11147 // ... 11148 BB = exitMBB; 11149 return BB; 11150 } 11151 11152 MachineBasicBlock *PPCTargetLowering::EmitPartwordAtomicBinary( 11153 MachineInstr &MI, MachineBasicBlock *BB, 11154 bool is8bit, // operation 11155 unsigned BinOpcode, unsigned CmpOpcode, unsigned CmpPred) const { 11156 // If we support part-word atomic mnemonics, just use them 11157 if (Subtarget.hasPartwordAtomics()) 11158 return EmitAtomicBinary(MI, BB, is8bit ? 1 : 2, BinOpcode, CmpOpcode, 11159 CmpPred); 11160 11161 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0. 11162 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 11163 // In 64 bit mode we have to use 64 bits for addresses, even though the 11164 // lwarx/stwcx are 32 bits. With the 32-bit atomics we can use address 11165 // registers without caring whether they're 32 or 64, but here we're 11166 // doing actual arithmetic on the addresses. 11167 bool is64bit = Subtarget.isPPC64(); 11168 bool isLittleEndian = Subtarget.isLittleEndian(); 11169 unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO; 11170 11171 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 11172 MachineFunction *F = BB->getParent(); 11173 MachineFunction::iterator It = ++BB->getIterator(); 11174 11175 Register dest = MI.getOperand(0).getReg(); 11176 Register ptrA = MI.getOperand(1).getReg(); 11177 Register ptrB = MI.getOperand(2).getReg(); 11178 Register incr = MI.getOperand(3).getReg(); 11179 DebugLoc dl = MI.getDebugLoc(); 11180 11181 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB); 11182 MachineBasicBlock *loop2MBB = 11183 CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr; 11184 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 11185 F->insert(It, loopMBB); 11186 if (CmpOpcode) 11187 F->insert(It, loop2MBB); 11188 F->insert(It, exitMBB); 11189 exitMBB->splice(exitMBB->begin(), BB, 11190 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 11191 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 11192 11193 MachineRegisterInfo &RegInfo = F->getRegInfo(); 11194 const TargetRegisterClass *RC = 11195 is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 11196 const TargetRegisterClass *GPRC = &PPC::GPRCRegClass; 11197 11198 Register PtrReg = RegInfo.createVirtualRegister(RC); 11199 Register Shift1Reg = RegInfo.createVirtualRegister(GPRC); 11200 Register ShiftReg = 11201 isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC); 11202 Register Incr2Reg = RegInfo.createVirtualRegister(GPRC); 11203 Register MaskReg = RegInfo.createVirtualRegister(GPRC); 11204 Register Mask2Reg = RegInfo.createVirtualRegister(GPRC); 11205 Register Mask3Reg = RegInfo.createVirtualRegister(GPRC); 11206 Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC); 11207 Register Tmp3Reg = RegInfo.createVirtualRegister(GPRC); 11208 Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC); 11209 Register TmpDestReg = RegInfo.createVirtualRegister(GPRC); 11210 Register Ptr1Reg; 11211 Register TmpReg = 11212 (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(GPRC); 11213 11214 // thisMBB: 11215 // ... 11216 // fallthrough --> loopMBB 11217 BB->addSuccessor(loopMBB); 11218 11219 // The 4-byte load must be aligned, while a char or short may be 11220 // anywhere in the word. Hence all this nasty bookkeeping code. 11221 // add ptr1, ptrA, ptrB [copy if ptrA==0] 11222 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27] 11223 // xori shift, shift1, 24 [16] 11224 // rlwinm ptr, ptr1, 0, 0, 29 11225 // slw incr2, incr, shift 11226 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535] 11227 // slw mask, mask2, shift 11228 // loopMBB: 11229 // lwarx tmpDest, ptr 11230 // add tmp, tmpDest, incr2 11231 // andc tmp2, tmpDest, mask 11232 // and tmp3, tmp, mask 11233 // or tmp4, tmp3, tmp2 11234 // stwcx. tmp4, ptr 11235 // bne- loopMBB 11236 // fallthrough --> exitMBB 11237 // srw dest, tmpDest, shift 11238 if (ptrA != ZeroReg) { 11239 Ptr1Reg = RegInfo.createVirtualRegister(RC); 11240 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg) 11241 .addReg(ptrA) 11242 .addReg(ptrB); 11243 } else { 11244 Ptr1Reg = ptrB; 11245 } 11246 // We need use 32-bit subregister to avoid mismatch register class in 64-bit 11247 // mode. 11248 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg) 11249 .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0) 11250 .addImm(3) 11251 .addImm(27) 11252 .addImm(is8bit ? 28 : 27); 11253 if (!isLittleEndian) 11254 BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg) 11255 .addReg(Shift1Reg) 11256 .addImm(is8bit ? 24 : 16); 11257 if (is64bit) 11258 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg) 11259 .addReg(Ptr1Reg) 11260 .addImm(0) 11261 .addImm(61); 11262 else 11263 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg) 11264 .addReg(Ptr1Reg) 11265 .addImm(0) 11266 .addImm(0) 11267 .addImm(29); 11268 BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg).addReg(incr).addReg(ShiftReg); 11269 if (is8bit) 11270 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255); 11271 else { 11272 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0); 11273 BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg) 11274 .addReg(Mask3Reg) 11275 .addImm(65535); 11276 } 11277 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg) 11278 .addReg(Mask2Reg) 11279 .addReg(ShiftReg); 11280 11281 BB = loopMBB; 11282 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg) 11283 .addReg(ZeroReg) 11284 .addReg(PtrReg); 11285 if (BinOpcode) 11286 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg) 11287 .addReg(Incr2Reg) 11288 .addReg(TmpDestReg); 11289 BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg) 11290 .addReg(TmpDestReg) 11291 .addReg(MaskReg); 11292 BuildMI(BB, dl, TII->get(PPC::AND), Tmp3Reg).addReg(TmpReg).addReg(MaskReg); 11293 if (CmpOpcode) { 11294 // For unsigned comparisons, we can directly compare the shifted values. 11295 // For signed comparisons we shift and sign extend. 11296 Register SReg = RegInfo.createVirtualRegister(GPRC); 11297 BuildMI(BB, dl, TII->get(PPC::AND), SReg) 11298 .addReg(TmpDestReg) 11299 .addReg(MaskReg); 11300 unsigned ValueReg = SReg; 11301 unsigned CmpReg = Incr2Reg; 11302 if (CmpOpcode == PPC::CMPW) { 11303 ValueReg = RegInfo.createVirtualRegister(GPRC); 11304 BuildMI(BB, dl, TII->get(PPC::SRW), ValueReg) 11305 .addReg(SReg) 11306 .addReg(ShiftReg); 11307 Register ValueSReg = RegInfo.createVirtualRegister(GPRC); 11308 BuildMI(BB, dl, TII->get(is8bit ? PPC::EXTSB : PPC::EXTSH), ValueSReg) 11309 .addReg(ValueReg); 11310 ValueReg = ValueSReg; 11311 CmpReg = incr; 11312 } 11313 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0) 11314 .addReg(CmpReg) 11315 .addReg(ValueReg); 11316 BuildMI(BB, dl, TII->get(PPC::BCC)) 11317 .addImm(CmpPred) 11318 .addReg(PPC::CR0) 11319 .addMBB(exitMBB); 11320 BB->addSuccessor(loop2MBB); 11321 BB->addSuccessor(exitMBB); 11322 BB = loop2MBB; 11323 } 11324 BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg).addReg(Tmp3Reg).addReg(Tmp2Reg); 11325 BuildMI(BB, dl, TII->get(PPC::STWCX)) 11326 .addReg(Tmp4Reg) 11327 .addReg(ZeroReg) 11328 .addReg(PtrReg); 11329 BuildMI(BB, dl, TII->get(PPC::BCC)) 11330 .addImm(PPC::PRED_NE) 11331 .addReg(PPC::CR0) 11332 .addMBB(loopMBB); 11333 BB->addSuccessor(loopMBB); 11334 BB->addSuccessor(exitMBB); 11335 11336 // exitMBB: 11337 // ... 11338 BB = exitMBB; 11339 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest) 11340 .addReg(TmpDestReg) 11341 .addReg(ShiftReg); 11342 return BB; 11343 } 11344 11345 llvm::MachineBasicBlock * 11346 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr &MI, 11347 MachineBasicBlock *MBB) const { 11348 DebugLoc DL = MI.getDebugLoc(); 11349 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 11350 const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo(); 11351 11352 MachineFunction *MF = MBB->getParent(); 11353 MachineRegisterInfo &MRI = MF->getRegInfo(); 11354 11355 const BasicBlock *BB = MBB->getBasicBlock(); 11356 MachineFunction::iterator I = ++MBB->getIterator(); 11357 11358 Register DstReg = MI.getOperand(0).getReg(); 11359 const TargetRegisterClass *RC = MRI.getRegClass(DstReg); 11360 assert(TRI->isTypeLegalForClass(*RC, MVT::i32) && "Invalid destination!"); 11361 Register mainDstReg = MRI.createVirtualRegister(RC); 11362 Register restoreDstReg = MRI.createVirtualRegister(RC); 11363 11364 MVT PVT = getPointerTy(MF->getDataLayout()); 11365 assert((PVT == MVT::i64 || PVT == MVT::i32) && 11366 "Invalid Pointer Size!"); 11367 // For v = setjmp(buf), we generate 11368 // 11369 // thisMBB: 11370 // SjLjSetup mainMBB 11371 // bl mainMBB 11372 // v_restore = 1 11373 // b sinkMBB 11374 // 11375 // mainMBB: 11376 // buf[LabelOffset] = LR 11377 // v_main = 0 11378 // 11379 // sinkMBB: 11380 // v = phi(main, restore) 11381 // 11382 11383 MachineBasicBlock *thisMBB = MBB; 11384 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB); 11385 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB); 11386 MF->insert(I, mainMBB); 11387 MF->insert(I, sinkMBB); 11388 11389 MachineInstrBuilder MIB; 11390 11391 // Transfer the remainder of BB and its successor edges to sinkMBB. 11392 sinkMBB->splice(sinkMBB->begin(), MBB, 11393 std::next(MachineBasicBlock::iterator(MI)), MBB->end()); 11394 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB); 11395 11396 // Note that the structure of the jmp_buf used here is not compatible 11397 // with that used by libc, and is not designed to be. Specifically, it 11398 // stores only those 'reserved' registers that LLVM does not otherwise 11399 // understand how to spill. Also, by convention, by the time this 11400 // intrinsic is called, Clang has already stored the frame address in the 11401 // first slot of the buffer and stack address in the third. Following the 11402 // X86 target code, we'll store the jump address in the second slot. We also 11403 // need to save the TOC pointer (R2) to handle jumps between shared 11404 // libraries, and that will be stored in the fourth slot. The thread 11405 // identifier (R13) is not affected. 11406 11407 // thisMBB: 11408 const int64_t LabelOffset = 1 * PVT.getStoreSize(); 11409 const int64_t TOCOffset = 3 * PVT.getStoreSize(); 11410 const int64_t BPOffset = 4 * PVT.getStoreSize(); 11411 11412 // Prepare IP either in reg. 11413 const TargetRegisterClass *PtrRC = getRegClassFor(PVT); 11414 Register LabelReg = MRI.createVirtualRegister(PtrRC); 11415 Register BufReg = MI.getOperand(1).getReg(); 11416 11417 if (Subtarget.is64BitELFABI()) { 11418 setUsesTOCBasePtr(*MBB->getParent()); 11419 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD)) 11420 .addReg(PPC::X2) 11421 .addImm(TOCOffset) 11422 .addReg(BufReg) 11423 .cloneMemRefs(MI); 11424 } 11425 11426 // Naked functions never have a base pointer, and so we use r1. For all 11427 // other functions, this decision must be delayed until during PEI. 11428 unsigned BaseReg; 11429 if (MF->getFunction().hasFnAttribute(Attribute::Naked)) 11430 BaseReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1; 11431 else 11432 BaseReg = Subtarget.isPPC64() ? PPC::BP8 : PPC::BP; 11433 11434 MIB = BuildMI(*thisMBB, MI, DL, 11435 TII->get(Subtarget.isPPC64() ? PPC::STD : PPC::STW)) 11436 .addReg(BaseReg) 11437 .addImm(BPOffset) 11438 .addReg(BufReg) 11439 .cloneMemRefs(MI); 11440 11441 // Setup 11442 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB); 11443 MIB.addRegMask(TRI->getNoPreservedMask()); 11444 11445 BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1); 11446 11447 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup)) 11448 .addMBB(mainMBB); 11449 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB); 11450 11451 thisMBB->addSuccessor(mainMBB, BranchProbability::getZero()); 11452 thisMBB->addSuccessor(sinkMBB, BranchProbability::getOne()); 11453 11454 // mainMBB: 11455 // mainDstReg = 0 11456 MIB = 11457 BuildMI(mainMBB, DL, 11458 TII->get(Subtarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg); 11459 11460 // Store IP 11461 if (Subtarget.isPPC64()) { 11462 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD)) 11463 .addReg(LabelReg) 11464 .addImm(LabelOffset) 11465 .addReg(BufReg); 11466 } else { 11467 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW)) 11468 .addReg(LabelReg) 11469 .addImm(LabelOffset) 11470 .addReg(BufReg); 11471 } 11472 MIB.cloneMemRefs(MI); 11473 11474 BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0); 11475 mainMBB->addSuccessor(sinkMBB); 11476 11477 // sinkMBB: 11478 BuildMI(*sinkMBB, sinkMBB->begin(), DL, 11479 TII->get(PPC::PHI), DstReg) 11480 .addReg(mainDstReg).addMBB(mainMBB) 11481 .addReg(restoreDstReg).addMBB(thisMBB); 11482 11483 MI.eraseFromParent(); 11484 return sinkMBB; 11485 } 11486 11487 MachineBasicBlock * 11488 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr &MI, 11489 MachineBasicBlock *MBB) const { 11490 DebugLoc DL = MI.getDebugLoc(); 11491 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 11492 11493 MachineFunction *MF = MBB->getParent(); 11494 MachineRegisterInfo &MRI = MF->getRegInfo(); 11495 11496 MVT PVT = getPointerTy(MF->getDataLayout()); 11497 assert((PVT == MVT::i64 || PVT == MVT::i32) && 11498 "Invalid Pointer Size!"); 11499 11500 const TargetRegisterClass *RC = 11501 (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 11502 Register Tmp = MRI.createVirtualRegister(RC); 11503 // Since FP is only updated here but NOT referenced, it's treated as GPR. 11504 unsigned FP = (PVT == MVT::i64) ? PPC::X31 : PPC::R31; 11505 unsigned SP = (PVT == MVT::i64) ? PPC::X1 : PPC::R1; 11506 unsigned BP = 11507 (PVT == MVT::i64) 11508 ? PPC::X30 11509 : (Subtarget.isSVR4ABI() && isPositionIndependent() ? PPC::R29 11510 : PPC::R30); 11511 11512 MachineInstrBuilder MIB; 11513 11514 const int64_t LabelOffset = 1 * PVT.getStoreSize(); 11515 const int64_t SPOffset = 2 * PVT.getStoreSize(); 11516 const int64_t TOCOffset = 3 * PVT.getStoreSize(); 11517 const int64_t BPOffset = 4 * PVT.getStoreSize(); 11518 11519 Register BufReg = MI.getOperand(0).getReg(); 11520 11521 // Reload FP (the jumped-to function may not have had a 11522 // frame pointer, and if so, then its r31 will be restored 11523 // as necessary). 11524 if (PVT == MVT::i64) { 11525 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP) 11526 .addImm(0) 11527 .addReg(BufReg); 11528 } else { 11529 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP) 11530 .addImm(0) 11531 .addReg(BufReg); 11532 } 11533 MIB.cloneMemRefs(MI); 11534 11535 // Reload IP 11536 if (PVT == MVT::i64) { 11537 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp) 11538 .addImm(LabelOffset) 11539 .addReg(BufReg); 11540 } else { 11541 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp) 11542 .addImm(LabelOffset) 11543 .addReg(BufReg); 11544 } 11545 MIB.cloneMemRefs(MI); 11546 11547 // Reload SP 11548 if (PVT == MVT::i64) { 11549 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP) 11550 .addImm(SPOffset) 11551 .addReg(BufReg); 11552 } else { 11553 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP) 11554 .addImm(SPOffset) 11555 .addReg(BufReg); 11556 } 11557 MIB.cloneMemRefs(MI); 11558 11559 // Reload BP 11560 if (PVT == MVT::i64) { 11561 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP) 11562 .addImm(BPOffset) 11563 .addReg(BufReg); 11564 } else { 11565 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP) 11566 .addImm(BPOffset) 11567 .addReg(BufReg); 11568 } 11569 MIB.cloneMemRefs(MI); 11570 11571 // Reload TOC 11572 if (PVT == MVT::i64 && Subtarget.isSVR4ABI()) { 11573 setUsesTOCBasePtr(*MBB->getParent()); 11574 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2) 11575 .addImm(TOCOffset) 11576 .addReg(BufReg) 11577 .cloneMemRefs(MI); 11578 } 11579 11580 // Jump 11581 BuildMI(*MBB, MI, DL, 11582 TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp); 11583 BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR)); 11584 11585 MI.eraseFromParent(); 11586 return MBB; 11587 } 11588 11589 MachineBasicBlock * 11590 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI, 11591 MachineBasicBlock *BB) const { 11592 if (MI.getOpcode() == TargetOpcode::STACKMAP || 11593 MI.getOpcode() == TargetOpcode::PATCHPOINT) { 11594 if (Subtarget.is64BitELFABI() && 11595 MI.getOpcode() == TargetOpcode::PATCHPOINT && 11596 !Subtarget.isUsingPCRelativeCalls()) { 11597 // Call lowering should have added an r2 operand to indicate a dependence 11598 // on the TOC base pointer value. It can't however, because there is no 11599 // way to mark the dependence as implicit there, and so the stackmap code 11600 // will confuse it with a regular operand. Instead, add the dependence 11601 // here. 11602 MI.addOperand(MachineOperand::CreateReg(PPC::X2, false, true)); 11603 } 11604 11605 return emitPatchPoint(MI, BB); 11606 } 11607 11608 if (MI.getOpcode() == PPC::EH_SjLj_SetJmp32 || 11609 MI.getOpcode() == PPC::EH_SjLj_SetJmp64) { 11610 return emitEHSjLjSetJmp(MI, BB); 11611 } else if (MI.getOpcode() == PPC::EH_SjLj_LongJmp32 || 11612 MI.getOpcode() == PPC::EH_SjLj_LongJmp64) { 11613 return emitEHSjLjLongJmp(MI, BB); 11614 } 11615 11616 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 11617 11618 // To "insert" these instructions we actually have to insert their 11619 // control-flow patterns. 11620 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 11621 MachineFunction::iterator It = ++BB->getIterator(); 11622 11623 MachineFunction *F = BB->getParent(); 11624 11625 if (MI.getOpcode() == PPC::SELECT_CC_I4 || 11626 MI.getOpcode() == PPC::SELECT_CC_I8 || MI.getOpcode() == PPC::SELECT_I4 || 11627 MI.getOpcode() == PPC::SELECT_I8) { 11628 SmallVector<MachineOperand, 2> Cond; 11629 if (MI.getOpcode() == PPC::SELECT_CC_I4 || 11630 MI.getOpcode() == PPC::SELECT_CC_I8) 11631 Cond.push_back(MI.getOperand(4)); 11632 else 11633 Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET)); 11634 Cond.push_back(MI.getOperand(1)); 11635 11636 DebugLoc dl = MI.getDebugLoc(); 11637 TII->insertSelect(*BB, MI, dl, MI.getOperand(0).getReg(), Cond, 11638 MI.getOperand(2).getReg(), MI.getOperand(3).getReg()); 11639 } else if (MI.getOpcode() == PPC::SELECT_CC_F4 || 11640 MI.getOpcode() == PPC::SELECT_CC_F8 || 11641 MI.getOpcode() == PPC::SELECT_CC_F16 || 11642 MI.getOpcode() == PPC::SELECT_CC_QFRC || 11643 MI.getOpcode() == PPC::SELECT_CC_QSRC || 11644 MI.getOpcode() == PPC::SELECT_CC_QBRC || 11645 MI.getOpcode() == PPC::SELECT_CC_VRRC || 11646 MI.getOpcode() == PPC::SELECT_CC_VSFRC || 11647 MI.getOpcode() == PPC::SELECT_CC_VSSRC || 11648 MI.getOpcode() == PPC::SELECT_CC_VSRC || 11649 MI.getOpcode() == PPC::SELECT_CC_SPE4 || 11650 MI.getOpcode() == PPC::SELECT_CC_SPE || 11651 MI.getOpcode() == PPC::SELECT_F4 || 11652 MI.getOpcode() == PPC::SELECT_F8 || 11653 MI.getOpcode() == PPC::SELECT_F16 || 11654 MI.getOpcode() == PPC::SELECT_QFRC || 11655 MI.getOpcode() == PPC::SELECT_QSRC || 11656 MI.getOpcode() == PPC::SELECT_QBRC || 11657 MI.getOpcode() == PPC::SELECT_SPE || 11658 MI.getOpcode() == PPC::SELECT_SPE4 || 11659 MI.getOpcode() == PPC::SELECT_VRRC || 11660 MI.getOpcode() == PPC::SELECT_VSFRC || 11661 MI.getOpcode() == PPC::SELECT_VSSRC || 11662 MI.getOpcode() == PPC::SELECT_VSRC) { 11663 // The incoming instruction knows the destination vreg to set, the 11664 // condition code register to branch on, the true/false values to 11665 // select between, and a branch opcode to use. 11666 11667 // thisMBB: 11668 // ... 11669 // TrueVal = ... 11670 // cmpTY ccX, r1, r2 11671 // bCC copy1MBB 11672 // fallthrough --> copy0MBB 11673 MachineBasicBlock *thisMBB = BB; 11674 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB); 11675 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 11676 DebugLoc dl = MI.getDebugLoc(); 11677 F->insert(It, copy0MBB); 11678 F->insert(It, sinkMBB); 11679 11680 // Transfer the remainder of BB and its successor edges to sinkMBB. 11681 sinkMBB->splice(sinkMBB->begin(), BB, 11682 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 11683 sinkMBB->transferSuccessorsAndUpdatePHIs(BB); 11684 11685 // Next, add the true and fallthrough blocks as its successors. 11686 BB->addSuccessor(copy0MBB); 11687 BB->addSuccessor(sinkMBB); 11688 11689 if (MI.getOpcode() == PPC::SELECT_I4 || MI.getOpcode() == PPC::SELECT_I8 || 11690 MI.getOpcode() == PPC::SELECT_F4 || MI.getOpcode() == PPC::SELECT_F8 || 11691 MI.getOpcode() == PPC::SELECT_F16 || 11692 MI.getOpcode() == PPC::SELECT_SPE4 || 11693 MI.getOpcode() == PPC::SELECT_SPE || 11694 MI.getOpcode() == PPC::SELECT_QFRC || 11695 MI.getOpcode() == PPC::SELECT_QSRC || 11696 MI.getOpcode() == PPC::SELECT_QBRC || 11697 MI.getOpcode() == PPC::SELECT_VRRC || 11698 MI.getOpcode() == PPC::SELECT_VSFRC || 11699 MI.getOpcode() == PPC::SELECT_VSSRC || 11700 MI.getOpcode() == PPC::SELECT_VSRC) { 11701 BuildMI(BB, dl, TII->get(PPC::BC)) 11702 .addReg(MI.getOperand(1).getReg()) 11703 .addMBB(sinkMBB); 11704 } else { 11705 unsigned SelectPred = MI.getOperand(4).getImm(); 11706 BuildMI(BB, dl, TII->get(PPC::BCC)) 11707 .addImm(SelectPred) 11708 .addReg(MI.getOperand(1).getReg()) 11709 .addMBB(sinkMBB); 11710 } 11711 11712 // copy0MBB: 11713 // %FalseValue = ... 11714 // # fallthrough to sinkMBB 11715 BB = copy0MBB; 11716 11717 // Update machine-CFG edges 11718 BB->addSuccessor(sinkMBB); 11719 11720 // sinkMBB: 11721 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ] 11722 // ... 11723 BB = sinkMBB; 11724 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::PHI), MI.getOperand(0).getReg()) 11725 .addReg(MI.getOperand(3).getReg()) 11726 .addMBB(copy0MBB) 11727 .addReg(MI.getOperand(2).getReg()) 11728 .addMBB(thisMBB); 11729 } else if (MI.getOpcode() == PPC::ReadTB) { 11730 // To read the 64-bit time-base register on a 32-bit target, we read the 11731 // two halves. Should the counter have wrapped while it was being read, we 11732 // need to try again. 11733 // ... 11734 // readLoop: 11735 // mfspr Rx,TBU # load from TBU 11736 // mfspr Ry,TB # load from TB 11737 // mfspr Rz,TBU # load from TBU 11738 // cmpw crX,Rx,Rz # check if 'old'='new' 11739 // bne readLoop # branch if they're not equal 11740 // ... 11741 11742 MachineBasicBlock *readMBB = F->CreateMachineBasicBlock(LLVM_BB); 11743 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 11744 DebugLoc dl = MI.getDebugLoc(); 11745 F->insert(It, readMBB); 11746 F->insert(It, sinkMBB); 11747 11748 // Transfer the remainder of BB and its successor edges to sinkMBB. 11749 sinkMBB->splice(sinkMBB->begin(), BB, 11750 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 11751 sinkMBB->transferSuccessorsAndUpdatePHIs(BB); 11752 11753 BB->addSuccessor(readMBB); 11754 BB = readMBB; 11755 11756 MachineRegisterInfo &RegInfo = F->getRegInfo(); 11757 Register ReadAgainReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass); 11758 Register LoReg = MI.getOperand(0).getReg(); 11759 Register HiReg = MI.getOperand(1).getReg(); 11760 11761 BuildMI(BB, dl, TII->get(PPC::MFSPR), HiReg).addImm(269); 11762 BuildMI(BB, dl, TII->get(PPC::MFSPR), LoReg).addImm(268); 11763 BuildMI(BB, dl, TII->get(PPC::MFSPR), ReadAgainReg).addImm(269); 11764 11765 Register CmpReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass); 11766 11767 BuildMI(BB, dl, TII->get(PPC::CMPW), CmpReg) 11768 .addReg(HiReg) 11769 .addReg(ReadAgainReg); 11770 BuildMI(BB, dl, TII->get(PPC::BCC)) 11771 .addImm(PPC::PRED_NE) 11772 .addReg(CmpReg) 11773 .addMBB(readMBB); 11774 11775 BB->addSuccessor(readMBB); 11776 BB->addSuccessor(sinkMBB); 11777 } else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I8) 11778 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4); 11779 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I16) 11780 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4); 11781 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I32) 11782 BB = EmitAtomicBinary(MI, BB, 4, PPC::ADD4); 11783 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I64) 11784 BB = EmitAtomicBinary(MI, BB, 8, PPC::ADD8); 11785 11786 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I8) 11787 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND); 11788 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I16) 11789 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND); 11790 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I32) 11791 BB = EmitAtomicBinary(MI, BB, 4, PPC::AND); 11792 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I64) 11793 BB = EmitAtomicBinary(MI, BB, 8, PPC::AND8); 11794 11795 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I8) 11796 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR); 11797 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I16) 11798 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR); 11799 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I32) 11800 BB = EmitAtomicBinary(MI, BB, 4, PPC::OR); 11801 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I64) 11802 BB = EmitAtomicBinary(MI, BB, 8, PPC::OR8); 11803 11804 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I8) 11805 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR); 11806 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I16) 11807 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR); 11808 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I32) 11809 BB = EmitAtomicBinary(MI, BB, 4, PPC::XOR); 11810 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I64) 11811 BB = EmitAtomicBinary(MI, BB, 8, PPC::XOR8); 11812 11813 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I8) 11814 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::NAND); 11815 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I16) 11816 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::NAND); 11817 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I32) 11818 BB = EmitAtomicBinary(MI, BB, 4, PPC::NAND); 11819 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I64) 11820 BB = EmitAtomicBinary(MI, BB, 8, PPC::NAND8); 11821 11822 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I8) 11823 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF); 11824 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I16) 11825 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF); 11826 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I32) 11827 BB = EmitAtomicBinary(MI, BB, 4, PPC::SUBF); 11828 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I64) 11829 BB = EmitAtomicBinary(MI, BB, 8, PPC::SUBF8); 11830 11831 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I8) 11832 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_GE); 11833 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I16) 11834 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_GE); 11835 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I32) 11836 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_GE); 11837 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I64) 11838 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_GE); 11839 11840 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I8) 11841 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_LE); 11842 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I16) 11843 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_LE); 11844 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I32) 11845 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_LE); 11846 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I64) 11847 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_LE); 11848 11849 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I8) 11850 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_GE); 11851 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I16) 11852 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_GE); 11853 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I32) 11854 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_GE); 11855 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I64) 11856 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_GE); 11857 11858 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I8) 11859 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_LE); 11860 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I16) 11861 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_LE); 11862 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I32) 11863 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_LE); 11864 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I64) 11865 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_LE); 11866 11867 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I8) 11868 BB = EmitPartwordAtomicBinary(MI, BB, true, 0); 11869 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I16) 11870 BB = EmitPartwordAtomicBinary(MI, BB, false, 0); 11871 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I32) 11872 BB = EmitAtomicBinary(MI, BB, 4, 0); 11873 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I64) 11874 BB = EmitAtomicBinary(MI, BB, 8, 0); 11875 else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 || 11876 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64 || 11877 (Subtarget.hasPartwordAtomics() && 11878 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8) || 11879 (Subtarget.hasPartwordAtomics() && 11880 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16)) { 11881 bool is64bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64; 11882 11883 auto LoadMnemonic = PPC::LDARX; 11884 auto StoreMnemonic = PPC::STDCX; 11885 switch (MI.getOpcode()) { 11886 default: 11887 llvm_unreachable("Compare and swap of unknown size"); 11888 case PPC::ATOMIC_CMP_SWAP_I8: 11889 LoadMnemonic = PPC::LBARX; 11890 StoreMnemonic = PPC::STBCX; 11891 assert(Subtarget.hasPartwordAtomics() && "No support partword atomics."); 11892 break; 11893 case PPC::ATOMIC_CMP_SWAP_I16: 11894 LoadMnemonic = PPC::LHARX; 11895 StoreMnemonic = PPC::STHCX; 11896 assert(Subtarget.hasPartwordAtomics() && "No support partword atomics."); 11897 break; 11898 case PPC::ATOMIC_CMP_SWAP_I32: 11899 LoadMnemonic = PPC::LWARX; 11900 StoreMnemonic = PPC::STWCX; 11901 break; 11902 case PPC::ATOMIC_CMP_SWAP_I64: 11903 LoadMnemonic = PPC::LDARX; 11904 StoreMnemonic = PPC::STDCX; 11905 break; 11906 } 11907 Register dest = MI.getOperand(0).getReg(); 11908 Register ptrA = MI.getOperand(1).getReg(); 11909 Register ptrB = MI.getOperand(2).getReg(); 11910 Register oldval = MI.getOperand(3).getReg(); 11911 Register newval = MI.getOperand(4).getReg(); 11912 DebugLoc dl = MI.getDebugLoc(); 11913 11914 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB); 11915 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB); 11916 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB); 11917 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 11918 F->insert(It, loop1MBB); 11919 F->insert(It, loop2MBB); 11920 F->insert(It, midMBB); 11921 F->insert(It, exitMBB); 11922 exitMBB->splice(exitMBB->begin(), BB, 11923 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 11924 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 11925 11926 // thisMBB: 11927 // ... 11928 // fallthrough --> loopMBB 11929 BB->addSuccessor(loop1MBB); 11930 11931 // loop1MBB: 11932 // l[bhwd]arx dest, ptr 11933 // cmp[wd] dest, oldval 11934 // bne- midMBB 11935 // loop2MBB: 11936 // st[bhwd]cx. newval, ptr 11937 // bne- loopMBB 11938 // b exitBB 11939 // midMBB: 11940 // st[bhwd]cx. dest, ptr 11941 // exitBB: 11942 BB = loop1MBB; 11943 BuildMI(BB, dl, TII->get(LoadMnemonic), dest).addReg(ptrA).addReg(ptrB); 11944 BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0) 11945 .addReg(oldval) 11946 .addReg(dest); 11947 BuildMI(BB, dl, TII->get(PPC::BCC)) 11948 .addImm(PPC::PRED_NE) 11949 .addReg(PPC::CR0) 11950 .addMBB(midMBB); 11951 BB->addSuccessor(loop2MBB); 11952 BB->addSuccessor(midMBB); 11953 11954 BB = loop2MBB; 11955 BuildMI(BB, dl, TII->get(StoreMnemonic)) 11956 .addReg(newval) 11957 .addReg(ptrA) 11958 .addReg(ptrB); 11959 BuildMI(BB, dl, TII->get(PPC::BCC)) 11960 .addImm(PPC::PRED_NE) 11961 .addReg(PPC::CR0) 11962 .addMBB(loop1MBB); 11963 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB); 11964 BB->addSuccessor(loop1MBB); 11965 BB->addSuccessor(exitMBB); 11966 11967 BB = midMBB; 11968 BuildMI(BB, dl, TII->get(StoreMnemonic)) 11969 .addReg(dest) 11970 .addReg(ptrA) 11971 .addReg(ptrB); 11972 BB->addSuccessor(exitMBB); 11973 11974 // exitMBB: 11975 // ... 11976 BB = exitMBB; 11977 } else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 || 11978 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) { 11979 // We must use 64-bit registers for addresses when targeting 64-bit, 11980 // since we're actually doing arithmetic on them. Other registers 11981 // can be 32-bit. 11982 bool is64bit = Subtarget.isPPC64(); 11983 bool isLittleEndian = Subtarget.isLittleEndian(); 11984 bool is8bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8; 11985 11986 Register dest = MI.getOperand(0).getReg(); 11987 Register ptrA = MI.getOperand(1).getReg(); 11988 Register ptrB = MI.getOperand(2).getReg(); 11989 Register oldval = MI.getOperand(3).getReg(); 11990 Register newval = MI.getOperand(4).getReg(); 11991 DebugLoc dl = MI.getDebugLoc(); 11992 11993 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB); 11994 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB); 11995 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB); 11996 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 11997 F->insert(It, loop1MBB); 11998 F->insert(It, loop2MBB); 11999 F->insert(It, midMBB); 12000 F->insert(It, exitMBB); 12001 exitMBB->splice(exitMBB->begin(), BB, 12002 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 12003 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 12004 12005 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12006 const TargetRegisterClass *RC = 12007 is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 12008 const TargetRegisterClass *GPRC = &PPC::GPRCRegClass; 12009 12010 Register PtrReg = RegInfo.createVirtualRegister(RC); 12011 Register Shift1Reg = RegInfo.createVirtualRegister(GPRC); 12012 Register ShiftReg = 12013 isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC); 12014 Register NewVal2Reg = RegInfo.createVirtualRegister(GPRC); 12015 Register NewVal3Reg = RegInfo.createVirtualRegister(GPRC); 12016 Register OldVal2Reg = RegInfo.createVirtualRegister(GPRC); 12017 Register OldVal3Reg = RegInfo.createVirtualRegister(GPRC); 12018 Register MaskReg = RegInfo.createVirtualRegister(GPRC); 12019 Register Mask2Reg = RegInfo.createVirtualRegister(GPRC); 12020 Register Mask3Reg = RegInfo.createVirtualRegister(GPRC); 12021 Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC); 12022 Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC); 12023 Register TmpDestReg = RegInfo.createVirtualRegister(GPRC); 12024 Register Ptr1Reg; 12025 Register TmpReg = RegInfo.createVirtualRegister(GPRC); 12026 Register ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO; 12027 // thisMBB: 12028 // ... 12029 // fallthrough --> loopMBB 12030 BB->addSuccessor(loop1MBB); 12031 12032 // The 4-byte load must be aligned, while a char or short may be 12033 // anywhere in the word. Hence all this nasty bookkeeping code. 12034 // add ptr1, ptrA, ptrB [copy if ptrA==0] 12035 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27] 12036 // xori shift, shift1, 24 [16] 12037 // rlwinm ptr, ptr1, 0, 0, 29 12038 // slw newval2, newval, shift 12039 // slw oldval2, oldval,shift 12040 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535] 12041 // slw mask, mask2, shift 12042 // and newval3, newval2, mask 12043 // and oldval3, oldval2, mask 12044 // loop1MBB: 12045 // lwarx tmpDest, ptr 12046 // and tmp, tmpDest, mask 12047 // cmpw tmp, oldval3 12048 // bne- midMBB 12049 // loop2MBB: 12050 // andc tmp2, tmpDest, mask 12051 // or tmp4, tmp2, newval3 12052 // stwcx. tmp4, ptr 12053 // bne- loop1MBB 12054 // b exitBB 12055 // midMBB: 12056 // stwcx. tmpDest, ptr 12057 // exitBB: 12058 // srw dest, tmpDest, shift 12059 if (ptrA != ZeroReg) { 12060 Ptr1Reg = RegInfo.createVirtualRegister(RC); 12061 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg) 12062 .addReg(ptrA) 12063 .addReg(ptrB); 12064 } else { 12065 Ptr1Reg = ptrB; 12066 } 12067 12068 // We need use 32-bit subregister to avoid mismatch register class in 64-bit 12069 // mode. 12070 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg) 12071 .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0) 12072 .addImm(3) 12073 .addImm(27) 12074 .addImm(is8bit ? 28 : 27); 12075 if (!isLittleEndian) 12076 BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg) 12077 .addReg(Shift1Reg) 12078 .addImm(is8bit ? 24 : 16); 12079 if (is64bit) 12080 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg) 12081 .addReg(Ptr1Reg) 12082 .addImm(0) 12083 .addImm(61); 12084 else 12085 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg) 12086 .addReg(Ptr1Reg) 12087 .addImm(0) 12088 .addImm(0) 12089 .addImm(29); 12090 BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg) 12091 .addReg(newval) 12092 .addReg(ShiftReg); 12093 BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg) 12094 .addReg(oldval) 12095 .addReg(ShiftReg); 12096 if (is8bit) 12097 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255); 12098 else { 12099 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0); 12100 BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg) 12101 .addReg(Mask3Reg) 12102 .addImm(65535); 12103 } 12104 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg) 12105 .addReg(Mask2Reg) 12106 .addReg(ShiftReg); 12107 BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg) 12108 .addReg(NewVal2Reg) 12109 .addReg(MaskReg); 12110 BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg) 12111 .addReg(OldVal2Reg) 12112 .addReg(MaskReg); 12113 12114 BB = loop1MBB; 12115 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg) 12116 .addReg(ZeroReg) 12117 .addReg(PtrReg); 12118 BuildMI(BB, dl, TII->get(PPC::AND), TmpReg) 12119 .addReg(TmpDestReg) 12120 .addReg(MaskReg); 12121 BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0) 12122 .addReg(TmpReg) 12123 .addReg(OldVal3Reg); 12124 BuildMI(BB, dl, TII->get(PPC::BCC)) 12125 .addImm(PPC::PRED_NE) 12126 .addReg(PPC::CR0) 12127 .addMBB(midMBB); 12128 BB->addSuccessor(loop2MBB); 12129 BB->addSuccessor(midMBB); 12130 12131 BB = loop2MBB; 12132 BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg) 12133 .addReg(TmpDestReg) 12134 .addReg(MaskReg); 12135 BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg) 12136 .addReg(Tmp2Reg) 12137 .addReg(NewVal3Reg); 12138 BuildMI(BB, dl, TII->get(PPC::STWCX)) 12139 .addReg(Tmp4Reg) 12140 .addReg(ZeroReg) 12141 .addReg(PtrReg); 12142 BuildMI(BB, dl, TII->get(PPC::BCC)) 12143 .addImm(PPC::PRED_NE) 12144 .addReg(PPC::CR0) 12145 .addMBB(loop1MBB); 12146 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB); 12147 BB->addSuccessor(loop1MBB); 12148 BB->addSuccessor(exitMBB); 12149 12150 BB = midMBB; 12151 BuildMI(BB, dl, TII->get(PPC::STWCX)) 12152 .addReg(TmpDestReg) 12153 .addReg(ZeroReg) 12154 .addReg(PtrReg); 12155 BB->addSuccessor(exitMBB); 12156 12157 // exitMBB: 12158 // ... 12159 BB = exitMBB; 12160 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest) 12161 .addReg(TmpReg) 12162 .addReg(ShiftReg); 12163 } else if (MI.getOpcode() == PPC::FADDrtz) { 12164 // This pseudo performs an FADD with rounding mode temporarily forced 12165 // to round-to-zero. We emit this via custom inserter since the FPSCR 12166 // is not modeled at the SelectionDAG level. 12167 Register Dest = MI.getOperand(0).getReg(); 12168 Register Src1 = MI.getOperand(1).getReg(); 12169 Register Src2 = MI.getOperand(2).getReg(); 12170 DebugLoc dl = MI.getDebugLoc(); 12171 12172 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12173 Register MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass); 12174 12175 // Save FPSCR value. 12176 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg); 12177 12178 // Set rounding mode to round-to-zero. 12179 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1)).addImm(31); 12180 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0)).addImm(30); 12181 12182 // Perform addition. 12183 BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest).addReg(Src1).addReg(Src2); 12184 12185 // Restore FPSCR value. 12186 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSFb)).addImm(1).addReg(MFFSReg); 12187 } else if (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT || 12188 MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT || 12189 MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8 || 12190 MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT8) { 12191 unsigned Opcode = (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8 || 12192 MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT8) 12193 ? PPC::ANDI8_rec 12194 : PPC::ANDI_rec; 12195 bool IsEQ = (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT || 12196 MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8); 12197 12198 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12199 Register Dest = RegInfo.createVirtualRegister( 12200 Opcode == PPC::ANDI_rec ? &PPC::GPRCRegClass : &PPC::G8RCRegClass); 12201 12202 DebugLoc Dl = MI.getDebugLoc(); 12203 BuildMI(*BB, MI, Dl, TII->get(Opcode), Dest) 12204 .addReg(MI.getOperand(1).getReg()) 12205 .addImm(1); 12206 BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY), 12207 MI.getOperand(0).getReg()) 12208 .addReg(IsEQ ? PPC::CR0EQ : PPC::CR0GT); 12209 } else if (MI.getOpcode() == PPC::TCHECK_RET) { 12210 DebugLoc Dl = MI.getDebugLoc(); 12211 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12212 Register CRReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass); 12213 BuildMI(*BB, MI, Dl, TII->get(PPC::TCHECK), CRReg); 12214 BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY), 12215 MI.getOperand(0).getReg()) 12216 .addReg(CRReg); 12217 } else if (MI.getOpcode() == PPC::TBEGIN_RET) { 12218 DebugLoc Dl = MI.getDebugLoc(); 12219 unsigned Imm = MI.getOperand(1).getImm(); 12220 BuildMI(*BB, MI, Dl, TII->get(PPC::TBEGIN)).addImm(Imm); 12221 BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY), 12222 MI.getOperand(0).getReg()) 12223 .addReg(PPC::CR0EQ); 12224 } else if (MI.getOpcode() == PPC::SETRNDi) { 12225 DebugLoc dl = MI.getDebugLoc(); 12226 Register OldFPSCRReg = MI.getOperand(0).getReg(); 12227 12228 // Save FPSCR value. 12229 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg); 12230 12231 // The floating point rounding mode is in the bits 62:63 of FPCSR, and has 12232 // the following settings: 12233 // 00 Round to nearest 12234 // 01 Round to 0 12235 // 10 Round to +inf 12236 // 11 Round to -inf 12237 12238 // When the operand is immediate, using the two least significant bits of 12239 // the immediate to set the bits 62:63 of FPSCR. 12240 unsigned Mode = MI.getOperand(1).getImm(); 12241 BuildMI(*BB, MI, dl, TII->get((Mode & 1) ? PPC::MTFSB1 : PPC::MTFSB0)) 12242 .addImm(31); 12243 12244 BuildMI(*BB, MI, dl, TII->get((Mode & 2) ? PPC::MTFSB1 : PPC::MTFSB0)) 12245 .addImm(30); 12246 } else if (MI.getOpcode() == PPC::SETRND) { 12247 DebugLoc dl = MI.getDebugLoc(); 12248 12249 // Copy register from F8RCRegClass::SrcReg to G8RCRegClass::DestReg 12250 // or copy register from G8RCRegClass::SrcReg to F8RCRegClass::DestReg. 12251 // If the target doesn't have DirectMove, we should use stack to do the 12252 // conversion, because the target doesn't have the instructions like mtvsrd 12253 // or mfvsrd to do this conversion directly. 12254 auto copyRegFromG8RCOrF8RC = [&] (unsigned DestReg, unsigned SrcReg) { 12255 if (Subtarget.hasDirectMove()) { 12256 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), DestReg) 12257 .addReg(SrcReg); 12258 } else { 12259 // Use stack to do the register copy. 12260 unsigned StoreOp = PPC::STD, LoadOp = PPC::LFD; 12261 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12262 const TargetRegisterClass *RC = RegInfo.getRegClass(SrcReg); 12263 if (RC == &PPC::F8RCRegClass) { 12264 // Copy register from F8RCRegClass to G8RCRegclass. 12265 assert((RegInfo.getRegClass(DestReg) == &PPC::G8RCRegClass) && 12266 "Unsupported RegClass."); 12267 12268 StoreOp = PPC::STFD; 12269 LoadOp = PPC::LD; 12270 } else { 12271 // Copy register from G8RCRegClass to F8RCRegclass. 12272 assert((RegInfo.getRegClass(SrcReg) == &PPC::G8RCRegClass) && 12273 (RegInfo.getRegClass(DestReg) == &PPC::F8RCRegClass) && 12274 "Unsupported RegClass."); 12275 } 12276 12277 MachineFrameInfo &MFI = F->getFrameInfo(); 12278 int FrameIdx = MFI.CreateStackObject(8, 8, false); 12279 12280 MachineMemOperand *MMOStore = F->getMachineMemOperand( 12281 MachinePointerInfo::getFixedStack(*F, FrameIdx, 0), 12282 MachineMemOperand::MOStore, MFI.getObjectSize(FrameIdx), 12283 MFI.getObjectAlign(FrameIdx)); 12284 12285 // Store the SrcReg into the stack. 12286 BuildMI(*BB, MI, dl, TII->get(StoreOp)) 12287 .addReg(SrcReg) 12288 .addImm(0) 12289 .addFrameIndex(FrameIdx) 12290 .addMemOperand(MMOStore); 12291 12292 MachineMemOperand *MMOLoad = F->getMachineMemOperand( 12293 MachinePointerInfo::getFixedStack(*F, FrameIdx, 0), 12294 MachineMemOperand::MOLoad, MFI.getObjectSize(FrameIdx), 12295 MFI.getObjectAlign(FrameIdx)); 12296 12297 // Load from the stack where SrcReg is stored, and save to DestReg, 12298 // so we have done the RegClass conversion from RegClass::SrcReg to 12299 // RegClass::DestReg. 12300 BuildMI(*BB, MI, dl, TII->get(LoadOp), DestReg) 12301 .addImm(0) 12302 .addFrameIndex(FrameIdx) 12303 .addMemOperand(MMOLoad); 12304 } 12305 }; 12306 12307 Register OldFPSCRReg = MI.getOperand(0).getReg(); 12308 12309 // Save FPSCR value. 12310 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg); 12311 12312 // When the operand is gprc register, use two least significant bits of the 12313 // register and mtfsf instruction to set the bits 62:63 of FPSCR. 12314 // 12315 // copy OldFPSCRTmpReg, OldFPSCRReg 12316 // (INSERT_SUBREG ExtSrcReg, (IMPLICIT_DEF ImDefReg), SrcOp, 1) 12317 // rldimi NewFPSCRTmpReg, ExtSrcReg, OldFPSCRReg, 0, 62 12318 // copy NewFPSCRReg, NewFPSCRTmpReg 12319 // mtfsf 255, NewFPSCRReg 12320 MachineOperand SrcOp = MI.getOperand(1); 12321 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12322 Register OldFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 12323 12324 copyRegFromG8RCOrF8RC(OldFPSCRTmpReg, OldFPSCRReg); 12325 12326 Register ImDefReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 12327 Register ExtSrcReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 12328 12329 // The first operand of INSERT_SUBREG should be a register which has 12330 // subregisters, we only care about its RegClass, so we should use an 12331 // IMPLICIT_DEF register. 12332 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::IMPLICIT_DEF), ImDefReg); 12333 BuildMI(*BB, MI, dl, TII->get(PPC::INSERT_SUBREG), ExtSrcReg) 12334 .addReg(ImDefReg) 12335 .add(SrcOp) 12336 .addImm(1); 12337 12338 Register NewFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 12339 BuildMI(*BB, MI, dl, TII->get(PPC::RLDIMI), NewFPSCRTmpReg) 12340 .addReg(OldFPSCRTmpReg) 12341 .addReg(ExtSrcReg) 12342 .addImm(0) 12343 .addImm(62); 12344 12345 Register NewFPSCRReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass); 12346 copyRegFromG8RCOrF8RC(NewFPSCRReg, NewFPSCRTmpReg); 12347 12348 // The mask 255 means that put the 32:63 bits of NewFPSCRReg to the 32:63 12349 // bits of FPSCR. 12350 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSF)) 12351 .addImm(255) 12352 .addReg(NewFPSCRReg) 12353 .addImm(0) 12354 .addImm(0); 12355 } else { 12356 llvm_unreachable("Unexpected instr type to insert"); 12357 } 12358 12359 MI.eraseFromParent(); // The pseudo instruction is gone now. 12360 return BB; 12361 } 12362 12363 //===----------------------------------------------------------------------===// 12364 // Target Optimization Hooks 12365 //===----------------------------------------------------------------------===// 12366 12367 static int getEstimateRefinementSteps(EVT VT, const PPCSubtarget &Subtarget) { 12368 // For the estimates, convergence is quadratic, so we essentially double the 12369 // number of digits correct after every iteration. For both FRE and FRSQRTE, 12370 // the minimum architected relative accuracy is 2^-5. When hasRecipPrec(), 12371 // this is 2^-14. IEEE float has 23 digits and double has 52 digits. 12372 int RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3; 12373 if (VT.getScalarType() == MVT::f64) 12374 RefinementSteps++; 12375 return RefinementSteps; 12376 } 12377 12378 SDValue PPCTargetLowering::getSqrtEstimate(SDValue Operand, SelectionDAG &DAG, 12379 int Enabled, int &RefinementSteps, 12380 bool &UseOneConstNR, 12381 bool Reciprocal) const { 12382 EVT VT = Operand.getValueType(); 12383 if ((VT == MVT::f32 && Subtarget.hasFRSQRTES()) || 12384 (VT == MVT::f64 && Subtarget.hasFRSQRTE()) || 12385 (VT == MVT::v4f32 && Subtarget.hasAltivec()) || 12386 (VT == MVT::v2f64 && Subtarget.hasVSX()) || 12387 (VT == MVT::v4f32 && Subtarget.hasQPX()) || 12388 (VT == MVT::v4f64 && Subtarget.hasQPX())) { 12389 if (RefinementSteps == ReciprocalEstimate::Unspecified) 12390 RefinementSteps = getEstimateRefinementSteps(VT, Subtarget); 12391 12392 // The Newton-Raphson computation with a single constant does not provide 12393 // enough accuracy on some CPUs. 12394 UseOneConstNR = !Subtarget.needsTwoConstNR(); 12395 return DAG.getNode(PPCISD::FRSQRTE, SDLoc(Operand), VT, Operand); 12396 } 12397 return SDValue(); 12398 } 12399 12400 SDValue PPCTargetLowering::getRecipEstimate(SDValue Operand, SelectionDAG &DAG, 12401 int Enabled, 12402 int &RefinementSteps) const { 12403 EVT VT = Operand.getValueType(); 12404 if ((VT == MVT::f32 && Subtarget.hasFRES()) || 12405 (VT == MVT::f64 && Subtarget.hasFRE()) || 12406 (VT == MVT::v4f32 && Subtarget.hasAltivec()) || 12407 (VT == MVT::v2f64 && Subtarget.hasVSX()) || 12408 (VT == MVT::v4f32 && Subtarget.hasQPX()) || 12409 (VT == MVT::v4f64 && Subtarget.hasQPX())) { 12410 if (RefinementSteps == ReciprocalEstimate::Unspecified) 12411 RefinementSteps = getEstimateRefinementSteps(VT, Subtarget); 12412 return DAG.getNode(PPCISD::FRE, SDLoc(Operand), VT, Operand); 12413 } 12414 return SDValue(); 12415 } 12416 12417 unsigned PPCTargetLowering::combineRepeatedFPDivisors() const { 12418 // Note: This functionality is used only when unsafe-fp-math is enabled, and 12419 // on cores with reciprocal estimates (which are used when unsafe-fp-math is 12420 // enabled for division), this functionality is redundant with the default 12421 // combiner logic (once the division -> reciprocal/multiply transformation 12422 // has taken place). As a result, this matters more for older cores than for 12423 // newer ones. 12424 12425 // Combine multiple FDIVs with the same divisor into multiple FMULs by the 12426 // reciprocal if there are two or more FDIVs (for embedded cores with only 12427 // one FP pipeline) for three or more FDIVs (for generic OOO cores). 12428 switch (Subtarget.getCPUDirective()) { 12429 default: 12430 return 3; 12431 case PPC::DIR_440: 12432 case PPC::DIR_A2: 12433 case PPC::DIR_E500: 12434 case PPC::DIR_E500mc: 12435 case PPC::DIR_E5500: 12436 return 2; 12437 } 12438 } 12439 12440 // isConsecutiveLSLoc needs to work even if all adds have not yet been 12441 // collapsed, and so we need to look through chains of them. 12442 static void getBaseWithConstantOffset(SDValue Loc, SDValue &Base, 12443 int64_t& Offset, SelectionDAG &DAG) { 12444 if (DAG.isBaseWithConstantOffset(Loc)) { 12445 Base = Loc.getOperand(0); 12446 Offset += cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue(); 12447 12448 // The base might itself be a base plus an offset, and if so, accumulate 12449 // that as well. 12450 getBaseWithConstantOffset(Loc.getOperand(0), Base, Offset, DAG); 12451 } 12452 } 12453 12454 static bool isConsecutiveLSLoc(SDValue Loc, EVT VT, LSBaseSDNode *Base, 12455 unsigned Bytes, int Dist, 12456 SelectionDAG &DAG) { 12457 if (VT.getSizeInBits() / 8 != Bytes) 12458 return false; 12459 12460 SDValue BaseLoc = Base->getBasePtr(); 12461 if (Loc.getOpcode() == ISD::FrameIndex) { 12462 if (BaseLoc.getOpcode() != ISD::FrameIndex) 12463 return false; 12464 const MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 12465 int FI = cast<FrameIndexSDNode>(Loc)->getIndex(); 12466 int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex(); 12467 int FS = MFI.getObjectSize(FI); 12468 int BFS = MFI.getObjectSize(BFI); 12469 if (FS != BFS || FS != (int)Bytes) return false; 12470 return MFI.getObjectOffset(FI) == (MFI.getObjectOffset(BFI) + Dist*Bytes); 12471 } 12472 12473 SDValue Base1 = Loc, Base2 = BaseLoc; 12474 int64_t Offset1 = 0, Offset2 = 0; 12475 getBaseWithConstantOffset(Loc, Base1, Offset1, DAG); 12476 getBaseWithConstantOffset(BaseLoc, Base2, Offset2, DAG); 12477 if (Base1 == Base2 && Offset1 == (Offset2 + Dist * Bytes)) 12478 return true; 12479 12480 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 12481 const GlobalValue *GV1 = nullptr; 12482 const GlobalValue *GV2 = nullptr; 12483 Offset1 = 0; 12484 Offset2 = 0; 12485 bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1); 12486 bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2); 12487 if (isGA1 && isGA2 && GV1 == GV2) 12488 return Offset1 == (Offset2 + Dist*Bytes); 12489 return false; 12490 } 12491 12492 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does 12493 // not enforce equality of the chain operands. 12494 static bool isConsecutiveLS(SDNode *N, LSBaseSDNode *Base, 12495 unsigned Bytes, int Dist, 12496 SelectionDAG &DAG) { 12497 if (LSBaseSDNode *LS = dyn_cast<LSBaseSDNode>(N)) { 12498 EVT VT = LS->getMemoryVT(); 12499 SDValue Loc = LS->getBasePtr(); 12500 return isConsecutiveLSLoc(Loc, VT, Base, Bytes, Dist, DAG); 12501 } 12502 12503 if (N->getOpcode() == ISD::INTRINSIC_W_CHAIN) { 12504 EVT VT; 12505 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 12506 default: return false; 12507 case Intrinsic::ppc_qpx_qvlfd: 12508 case Intrinsic::ppc_qpx_qvlfda: 12509 VT = MVT::v4f64; 12510 break; 12511 case Intrinsic::ppc_qpx_qvlfs: 12512 case Intrinsic::ppc_qpx_qvlfsa: 12513 VT = MVT::v4f32; 12514 break; 12515 case Intrinsic::ppc_qpx_qvlfcd: 12516 case Intrinsic::ppc_qpx_qvlfcda: 12517 VT = MVT::v2f64; 12518 break; 12519 case Intrinsic::ppc_qpx_qvlfcs: 12520 case Intrinsic::ppc_qpx_qvlfcsa: 12521 VT = MVT::v2f32; 12522 break; 12523 case Intrinsic::ppc_qpx_qvlfiwa: 12524 case Intrinsic::ppc_qpx_qvlfiwz: 12525 case Intrinsic::ppc_altivec_lvx: 12526 case Intrinsic::ppc_altivec_lvxl: 12527 case Intrinsic::ppc_vsx_lxvw4x: 12528 case Intrinsic::ppc_vsx_lxvw4x_be: 12529 VT = MVT::v4i32; 12530 break; 12531 case Intrinsic::ppc_vsx_lxvd2x: 12532 case Intrinsic::ppc_vsx_lxvd2x_be: 12533 VT = MVT::v2f64; 12534 break; 12535 case Intrinsic::ppc_altivec_lvebx: 12536 VT = MVT::i8; 12537 break; 12538 case Intrinsic::ppc_altivec_lvehx: 12539 VT = MVT::i16; 12540 break; 12541 case Intrinsic::ppc_altivec_lvewx: 12542 VT = MVT::i32; 12543 break; 12544 } 12545 12546 return isConsecutiveLSLoc(N->getOperand(2), VT, Base, Bytes, Dist, DAG); 12547 } 12548 12549 if (N->getOpcode() == ISD::INTRINSIC_VOID) { 12550 EVT VT; 12551 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 12552 default: return false; 12553 case Intrinsic::ppc_qpx_qvstfd: 12554 case Intrinsic::ppc_qpx_qvstfda: 12555 VT = MVT::v4f64; 12556 break; 12557 case Intrinsic::ppc_qpx_qvstfs: 12558 case Intrinsic::ppc_qpx_qvstfsa: 12559 VT = MVT::v4f32; 12560 break; 12561 case Intrinsic::ppc_qpx_qvstfcd: 12562 case Intrinsic::ppc_qpx_qvstfcda: 12563 VT = MVT::v2f64; 12564 break; 12565 case Intrinsic::ppc_qpx_qvstfcs: 12566 case Intrinsic::ppc_qpx_qvstfcsa: 12567 VT = MVT::v2f32; 12568 break; 12569 case Intrinsic::ppc_qpx_qvstfiw: 12570 case Intrinsic::ppc_qpx_qvstfiwa: 12571 case Intrinsic::ppc_altivec_stvx: 12572 case Intrinsic::ppc_altivec_stvxl: 12573 case Intrinsic::ppc_vsx_stxvw4x: 12574 VT = MVT::v4i32; 12575 break; 12576 case Intrinsic::ppc_vsx_stxvd2x: 12577 VT = MVT::v2f64; 12578 break; 12579 case Intrinsic::ppc_vsx_stxvw4x_be: 12580 VT = MVT::v4i32; 12581 break; 12582 case Intrinsic::ppc_vsx_stxvd2x_be: 12583 VT = MVT::v2f64; 12584 break; 12585 case Intrinsic::ppc_altivec_stvebx: 12586 VT = MVT::i8; 12587 break; 12588 case Intrinsic::ppc_altivec_stvehx: 12589 VT = MVT::i16; 12590 break; 12591 case Intrinsic::ppc_altivec_stvewx: 12592 VT = MVT::i32; 12593 break; 12594 } 12595 12596 return isConsecutiveLSLoc(N->getOperand(3), VT, Base, Bytes, Dist, DAG); 12597 } 12598 12599 return false; 12600 } 12601 12602 // Return true is there is a nearyby consecutive load to the one provided 12603 // (regardless of alignment). We search up and down the chain, looking though 12604 // token factors and other loads (but nothing else). As a result, a true result 12605 // indicates that it is safe to create a new consecutive load adjacent to the 12606 // load provided. 12607 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) { 12608 SDValue Chain = LD->getChain(); 12609 EVT VT = LD->getMemoryVT(); 12610 12611 SmallSet<SDNode *, 16> LoadRoots; 12612 SmallVector<SDNode *, 8> Queue(1, Chain.getNode()); 12613 SmallSet<SDNode *, 16> Visited; 12614 12615 // First, search up the chain, branching to follow all token-factor operands. 12616 // If we find a consecutive load, then we're done, otherwise, record all 12617 // nodes just above the top-level loads and token factors. 12618 while (!Queue.empty()) { 12619 SDNode *ChainNext = Queue.pop_back_val(); 12620 if (!Visited.insert(ChainNext).second) 12621 continue; 12622 12623 if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(ChainNext)) { 12624 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG)) 12625 return true; 12626 12627 if (!Visited.count(ChainLD->getChain().getNode())) 12628 Queue.push_back(ChainLD->getChain().getNode()); 12629 } else if (ChainNext->getOpcode() == ISD::TokenFactor) { 12630 for (const SDUse &O : ChainNext->ops()) 12631 if (!Visited.count(O.getNode())) 12632 Queue.push_back(O.getNode()); 12633 } else 12634 LoadRoots.insert(ChainNext); 12635 } 12636 12637 // Second, search down the chain, starting from the top-level nodes recorded 12638 // in the first phase. These top-level nodes are the nodes just above all 12639 // loads and token factors. Starting with their uses, recursively look though 12640 // all loads (just the chain uses) and token factors to find a consecutive 12641 // load. 12642 Visited.clear(); 12643 Queue.clear(); 12644 12645 for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(), 12646 IE = LoadRoots.end(); I != IE; ++I) { 12647 Queue.push_back(*I); 12648 12649 while (!Queue.empty()) { 12650 SDNode *LoadRoot = Queue.pop_back_val(); 12651 if (!Visited.insert(LoadRoot).second) 12652 continue; 12653 12654 if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(LoadRoot)) 12655 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG)) 12656 return true; 12657 12658 for (SDNode::use_iterator UI = LoadRoot->use_begin(), 12659 UE = LoadRoot->use_end(); UI != UE; ++UI) 12660 if (((isa<MemSDNode>(*UI) && 12661 cast<MemSDNode>(*UI)->getChain().getNode() == LoadRoot) || 12662 UI->getOpcode() == ISD::TokenFactor) && !Visited.count(*UI)) 12663 Queue.push_back(*UI); 12664 } 12665 } 12666 12667 return false; 12668 } 12669 12670 /// This function is called when we have proved that a SETCC node can be replaced 12671 /// by subtraction (and other supporting instructions) so that the result of 12672 /// comparison is kept in a GPR instead of CR. This function is purely for 12673 /// codegen purposes and has some flags to guide the codegen process. 12674 static SDValue generateEquivalentSub(SDNode *N, int Size, bool Complement, 12675 bool Swap, SDLoc &DL, SelectionDAG &DAG) { 12676 assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected."); 12677 12678 // Zero extend the operands to the largest legal integer. Originally, they 12679 // must be of a strictly smaller size. 12680 auto Op0 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(0), 12681 DAG.getConstant(Size, DL, MVT::i32)); 12682 auto Op1 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1), 12683 DAG.getConstant(Size, DL, MVT::i32)); 12684 12685 // Swap if needed. Depends on the condition code. 12686 if (Swap) 12687 std::swap(Op0, Op1); 12688 12689 // Subtract extended integers. 12690 auto SubNode = DAG.getNode(ISD::SUB, DL, MVT::i64, Op0, Op1); 12691 12692 // Move the sign bit to the least significant position and zero out the rest. 12693 // Now the least significant bit carries the result of original comparison. 12694 auto Shifted = DAG.getNode(ISD::SRL, DL, MVT::i64, SubNode, 12695 DAG.getConstant(Size - 1, DL, MVT::i32)); 12696 auto Final = Shifted; 12697 12698 // Complement the result if needed. Based on the condition code. 12699 if (Complement) 12700 Final = DAG.getNode(ISD::XOR, DL, MVT::i64, Shifted, 12701 DAG.getConstant(1, DL, MVT::i64)); 12702 12703 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Final); 12704 } 12705 12706 SDValue PPCTargetLowering::ConvertSETCCToSubtract(SDNode *N, 12707 DAGCombinerInfo &DCI) const { 12708 assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected."); 12709 12710 SelectionDAG &DAG = DCI.DAG; 12711 SDLoc DL(N); 12712 12713 // Size of integers being compared has a critical role in the following 12714 // analysis, so we prefer to do this when all types are legal. 12715 if (!DCI.isAfterLegalizeDAG()) 12716 return SDValue(); 12717 12718 // If all users of SETCC extend its value to a legal integer type 12719 // then we replace SETCC with a subtraction 12720 for (SDNode::use_iterator UI = N->use_begin(), 12721 UE = N->use_end(); UI != UE; ++UI) { 12722 if (UI->getOpcode() != ISD::ZERO_EXTEND) 12723 return SDValue(); 12724 } 12725 12726 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 12727 auto OpSize = N->getOperand(0).getValueSizeInBits(); 12728 12729 unsigned Size = DAG.getDataLayout().getLargestLegalIntTypeSizeInBits(); 12730 12731 if (OpSize < Size) { 12732 switch (CC) { 12733 default: break; 12734 case ISD::SETULT: 12735 return generateEquivalentSub(N, Size, false, false, DL, DAG); 12736 case ISD::SETULE: 12737 return generateEquivalentSub(N, Size, true, true, DL, DAG); 12738 case ISD::SETUGT: 12739 return generateEquivalentSub(N, Size, false, true, DL, DAG); 12740 case ISD::SETUGE: 12741 return generateEquivalentSub(N, Size, true, false, DL, DAG); 12742 } 12743 } 12744 12745 return SDValue(); 12746 } 12747 12748 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N, 12749 DAGCombinerInfo &DCI) const { 12750 SelectionDAG &DAG = DCI.DAG; 12751 SDLoc dl(N); 12752 12753 assert(Subtarget.useCRBits() && "Expecting to be tracking CR bits"); 12754 // If we're tracking CR bits, we need to be careful that we don't have: 12755 // trunc(binary-ops(zext(x), zext(y))) 12756 // or 12757 // trunc(binary-ops(binary-ops(zext(x), zext(y)), ...) 12758 // such that we're unnecessarily moving things into GPRs when it would be 12759 // better to keep them in CR bits. 12760 12761 // Note that trunc here can be an actual i1 trunc, or can be the effective 12762 // truncation that comes from a setcc or select_cc. 12763 if (N->getOpcode() == ISD::TRUNCATE && 12764 N->getValueType(0) != MVT::i1) 12765 return SDValue(); 12766 12767 if (N->getOperand(0).getValueType() != MVT::i32 && 12768 N->getOperand(0).getValueType() != MVT::i64) 12769 return SDValue(); 12770 12771 if (N->getOpcode() == ISD::SETCC || 12772 N->getOpcode() == ISD::SELECT_CC) { 12773 // If we're looking at a comparison, then we need to make sure that the 12774 // high bits (all except for the first) don't matter the result. 12775 ISD::CondCode CC = 12776 cast<CondCodeSDNode>(N->getOperand( 12777 N->getOpcode() == ISD::SETCC ? 2 : 4))->get(); 12778 unsigned OpBits = N->getOperand(0).getValueSizeInBits(); 12779 12780 if (ISD::isSignedIntSetCC(CC)) { 12781 if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits || 12782 DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits) 12783 return SDValue(); 12784 } else if (ISD::isUnsignedIntSetCC(CC)) { 12785 if (!DAG.MaskedValueIsZero(N->getOperand(0), 12786 APInt::getHighBitsSet(OpBits, OpBits-1)) || 12787 !DAG.MaskedValueIsZero(N->getOperand(1), 12788 APInt::getHighBitsSet(OpBits, OpBits-1))) 12789 return (N->getOpcode() == ISD::SETCC ? ConvertSETCCToSubtract(N, DCI) 12790 : SDValue()); 12791 } else { 12792 // This is neither a signed nor an unsigned comparison, just make sure 12793 // that the high bits are equal. 12794 KnownBits Op1Known = DAG.computeKnownBits(N->getOperand(0)); 12795 KnownBits Op2Known = DAG.computeKnownBits(N->getOperand(1)); 12796 12797 // We don't really care about what is known about the first bit (if 12798 // anything), so clear it in all masks prior to comparing them. 12799 Op1Known.Zero.clearBit(0); Op1Known.One.clearBit(0); 12800 Op2Known.Zero.clearBit(0); Op2Known.One.clearBit(0); 12801 12802 if (Op1Known.Zero != Op2Known.Zero || Op1Known.One != Op2Known.One) 12803 return SDValue(); 12804 } 12805 } 12806 12807 // We now know that the higher-order bits are irrelevant, we just need to 12808 // make sure that all of the intermediate operations are bit operations, and 12809 // all inputs are extensions. 12810 if (N->getOperand(0).getOpcode() != ISD::AND && 12811 N->getOperand(0).getOpcode() != ISD::OR && 12812 N->getOperand(0).getOpcode() != ISD::XOR && 12813 N->getOperand(0).getOpcode() != ISD::SELECT && 12814 N->getOperand(0).getOpcode() != ISD::SELECT_CC && 12815 N->getOperand(0).getOpcode() != ISD::TRUNCATE && 12816 N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND && 12817 N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND && 12818 N->getOperand(0).getOpcode() != ISD::ANY_EXTEND) 12819 return SDValue(); 12820 12821 if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) && 12822 N->getOperand(1).getOpcode() != ISD::AND && 12823 N->getOperand(1).getOpcode() != ISD::OR && 12824 N->getOperand(1).getOpcode() != ISD::XOR && 12825 N->getOperand(1).getOpcode() != ISD::SELECT && 12826 N->getOperand(1).getOpcode() != ISD::SELECT_CC && 12827 N->getOperand(1).getOpcode() != ISD::TRUNCATE && 12828 N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND && 12829 N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND && 12830 N->getOperand(1).getOpcode() != ISD::ANY_EXTEND) 12831 return SDValue(); 12832 12833 SmallVector<SDValue, 4> Inputs; 12834 SmallVector<SDValue, 8> BinOps, PromOps; 12835 SmallPtrSet<SDNode *, 16> Visited; 12836 12837 for (unsigned i = 0; i < 2; ++i) { 12838 if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND || 12839 N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND || 12840 N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) && 12841 N->getOperand(i).getOperand(0).getValueType() == MVT::i1) || 12842 isa<ConstantSDNode>(N->getOperand(i))) 12843 Inputs.push_back(N->getOperand(i)); 12844 else 12845 BinOps.push_back(N->getOperand(i)); 12846 12847 if (N->getOpcode() == ISD::TRUNCATE) 12848 break; 12849 } 12850 12851 // Visit all inputs, collect all binary operations (and, or, xor and 12852 // select) that are all fed by extensions. 12853 while (!BinOps.empty()) { 12854 SDValue BinOp = BinOps.back(); 12855 BinOps.pop_back(); 12856 12857 if (!Visited.insert(BinOp.getNode()).second) 12858 continue; 12859 12860 PromOps.push_back(BinOp); 12861 12862 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) { 12863 // The condition of the select is not promoted. 12864 if (BinOp.getOpcode() == ISD::SELECT && i == 0) 12865 continue; 12866 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3) 12867 continue; 12868 12869 if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND || 12870 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND || 12871 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) && 12872 BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) || 12873 isa<ConstantSDNode>(BinOp.getOperand(i))) { 12874 Inputs.push_back(BinOp.getOperand(i)); 12875 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND || 12876 BinOp.getOperand(i).getOpcode() == ISD::OR || 12877 BinOp.getOperand(i).getOpcode() == ISD::XOR || 12878 BinOp.getOperand(i).getOpcode() == ISD::SELECT || 12879 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC || 12880 BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE || 12881 BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND || 12882 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND || 12883 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) { 12884 BinOps.push_back(BinOp.getOperand(i)); 12885 } else { 12886 // We have an input that is not an extension or another binary 12887 // operation; we'll abort this transformation. 12888 return SDValue(); 12889 } 12890 } 12891 } 12892 12893 // Make sure that this is a self-contained cluster of operations (which 12894 // is not quite the same thing as saying that everything has only one 12895 // use). 12896 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 12897 if (isa<ConstantSDNode>(Inputs[i])) 12898 continue; 12899 12900 for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(), 12901 UE = Inputs[i].getNode()->use_end(); 12902 UI != UE; ++UI) { 12903 SDNode *User = *UI; 12904 if (User != N && !Visited.count(User)) 12905 return SDValue(); 12906 12907 // Make sure that we're not going to promote the non-output-value 12908 // operand(s) or SELECT or SELECT_CC. 12909 // FIXME: Although we could sometimes handle this, and it does occur in 12910 // practice that one of the condition inputs to the select is also one of 12911 // the outputs, we currently can't deal with this. 12912 if (User->getOpcode() == ISD::SELECT) { 12913 if (User->getOperand(0) == Inputs[i]) 12914 return SDValue(); 12915 } else if (User->getOpcode() == ISD::SELECT_CC) { 12916 if (User->getOperand(0) == Inputs[i] || 12917 User->getOperand(1) == Inputs[i]) 12918 return SDValue(); 12919 } 12920 } 12921 } 12922 12923 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) { 12924 for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(), 12925 UE = PromOps[i].getNode()->use_end(); 12926 UI != UE; ++UI) { 12927 SDNode *User = *UI; 12928 if (User != N && !Visited.count(User)) 12929 return SDValue(); 12930 12931 // Make sure that we're not going to promote the non-output-value 12932 // operand(s) or SELECT or SELECT_CC. 12933 // FIXME: Although we could sometimes handle this, and it does occur in 12934 // practice that one of the condition inputs to the select is also one of 12935 // the outputs, we currently can't deal with this. 12936 if (User->getOpcode() == ISD::SELECT) { 12937 if (User->getOperand(0) == PromOps[i]) 12938 return SDValue(); 12939 } else if (User->getOpcode() == ISD::SELECT_CC) { 12940 if (User->getOperand(0) == PromOps[i] || 12941 User->getOperand(1) == PromOps[i]) 12942 return SDValue(); 12943 } 12944 } 12945 } 12946 12947 // Replace all inputs with the extension operand. 12948 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 12949 // Constants may have users outside the cluster of to-be-promoted nodes, 12950 // and so we need to replace those as we do the promotions. 12951 if (isa<ConstantSDNode>(Inputs[i])) 12952 continue; 12953 else 12954 DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0)); 12955 } 12956 12957 std::list<HandleSDNode> PromOpHandles; 12958 for (auto &PromOp : PromOps) 12959 PromOpHandles.emplace_back(PromOp); 12960 12961 // Replace all operations (these are all the same, but have a different 12962 // (i1) return type). DAG.getNode will validate that the types of 12963 // a binary operator match, so go through the list in reverse so that 12964 // we've likely promoted both operands first. Any intermediate truncations or 12965 // extensions disappear. 12966 while (!PromOpHandles.empty()) { 12967 SDValue PromOp = PromOpHandles.back().getValue(); 12968 PromOpHandles.pop_back(); 12969 12970 if (PromOp.getOpcode() == ISD::TRUNCATE || 12971 PromOp.getOpcode() == ISD::SIGN_EXTEND || 12972 PromOp.getOpcode() == ISD::ZERO_EXTEND || 12973 PromOp.getOpcode() == ISD::ANY_EXTEND) { 12974 if (!isa<ConstantSDNode>(PromOp.getOperand(0)) && 12975 PromOp.getOperand(0).getValueType() != MVT::i1) { 12976 // The operand is not yet ready (see comment below). 12977 PromOpHandles.emplace_front(PromOp); 12978 continue; 12979 } 12980 12981 SDValue RepValue = PromOp.getOperand(0); 12982 if (isa<ConstantSDNode>(RepValue)) 12983 RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue); 12984 12985 DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue); 12986 continue; 12987 } 12988 12989 unsigned C; 12990 switch (PromOp.getOpcode()) { 12991 default: C = 0; break; 12992 case ISD::SELECT: C = 1; break; 12993 case ISD::SELECT_CC: C = 2; break; 12994 } 12995 12996 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) && 12997 PromOp.getOperand(C).getValueType() != MVT::i1) || 12998 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) && 12999 PromOp.getOperand(C+1).getValueType() != MVT::i1)) { 13000 // The to-be-promoted operands of this node have not yet been 13001 // promoted (this should be rare because we're going through the 13002 // list backward, but if one of the operands has several users in 13003 // this cluster of to-be-promoted nodes, it is possible). 13004 PromOpHandles.emplace_front(PromOp); 13005 continue; 13006 } 13007 13008 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(), 13009 PromOp.getNode()->op_end()); 13010 13011 // If there are any constant inputs, make sure they're replaced now. 13012 for (unsigned i = 0; i < 2; ++i) 13013 if (isa<ConstantSDNode>(Ops[C+i])) 13014 Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]); 13015 13016 DAG.ReplaceAllUsesOfValueWith(PromOp, 13017 DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops)); 13018 } 13019 13020 // Now we're left with the initial truncation itself. 13021 if (N->getOpcode() == ISD::TRUNCATE) 13022 return N->getOperand(0); 13023 13024 // Otherwise, this is a comparison. The operands to be compared have just 13025 // changed type (to i1), but everything else is the same. 13026 return SDValue(N, 0); 13027 } 13028 13029 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N, 13030 DAGCombinerInfo &DCI) const { 13031 SelectionDAG &DAG = DCI.DAG; 13032 SDLoc dl(N); 13033 13034 // If we're tracking CR bits, we need to be careful that we don't have: 13035 // zext(binary-ops(trunc(x), trunc(y))) 13036 // or 13037 // zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...) 13038 // such that we're unnecessarily moving things into CR bits that can more 13039 // efficiently stay in GPRs. Note that if we're not certain that the high 13040 // bits are set as required by the final extension, we still may need to do 13041 // some masking to get the proper behavior. 13042 13043 // This same functionality is important on PPC64 when dealing with 13044 // 32-to-64-bit extensions; these occur often when 32-bit values are used as 13045 // the return values of functions. Because it is so similar, it is handled 13046 // here as well. 13047 13048 if (N->getValueType(0) != MVT::i32 && 13049 N->getValueType(0) != MVT::i64) 13050 return SDValue(); 13051 13052 if (!((N->getOperand(0).getValueType() == MVT::i1 && Subtarget.useCRBits()) || 13053 (N->getOperand(0).getValueType() == MVT::i32 && Subtarget.isPPC64()))) 13054 return SDValue(); 13055 13056 if (N->getOperand(0).getOpcode() != ISD::AND && 13057 N->getOperand(0).getOpcode() != ISD::OR && 13058 N->getOperand(0).getOpcode() != ISD::XOR && 13059 N->getOperand(0).getOpcode() != ISD::SELECT && 13060 N->getOperand(0).getOpcode() != ISD::SELECT_CC) 13061 return SDValue(); 13062 13063 SmallVector<SDValue, 4> Inputs; 13064 SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps; 13065 SmallPtrSet<SDNode *, 16> Visited; 13066 13067 // Visit all inputs, collect all binary operations (and, or, xor and 13068 // select) that are all fed by truncations. 13069 while (!BinOps.empty()) { 13070 SDValue BinOp = BinOps.back(); 13071 BinOps.pop_back(); 13072 13073 if (!Visited.insert(BinOp.getNode()).second) 13074 continue; 13075 13076 PromOps.push_back(BinOp); 13077 13078 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) { 13079 // The condition of the select is not promoted. 13080 if (BinOp.getOpcode() == ISD::SELECT && i == 0) 13081 continue; 13082 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3) 13083 continue; 13084 13085 if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE || 13086 isa<ConstantSDNode>(BinOp.getOperand(i))) { 13087 Inputs.push_back(BinOp.getOperand(i)); 13088 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND || 13089 BinOp.getOperand(i).getOpcode() == ISD::OR || 13090 BinOp.getOperand(i).getOpcode() == ISD::XOR || 13091 BinOp.getOperand(i).getOpcode() == ISD::SELECT || 13092 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) { 13093 BinOps.push_back(BinOp.getOperand(i)); 13094 } else { 13095 // We have an input that is not a truncation or another binary 13096 // operation; we'll abort this transformation. 13097 return SDValue(); 13098 } 13099 } 13100 } 13101 13102 // The operands of a select that must be truncated when the select is 13103 // promoted because the operand is actually part of the to-be-promoted set. 13104 DenseMap<SDNode *, EVT> SelectTruncOp[2]; 13105 13106 // Make sure that this is a self-contained cluster of operations (which 13107 // is not quite the same thing as saying that everything has only one 13108 // use). 13109 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 13110 if (isa<ConstantSDNode>(Inputs[i])) 13111 continue; 13112 13113 for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(), 13114 UE = Inputs[i].getNode()->use_end(); 13115 UI != UE; ++UI) { 13116 SDNode *User = *UI; 13117 if (User != N && !Visited.count(User)) 13118 return SDValue(); 13119 13120 // If we're going to promote the non-output-value operand(s) or SELECT or 13121 // SELECT_CC, record them for truncation. 13122 if (User->getOpcode() == ISD::SELECT) { 13123 if (User->getOperand(0) == Inputs[i]) 13124 SelectTruncOp[0].insert(std::make_pair(User, 13125 User->getOperand(0).getValueType())); 13126 } else if (User->getOpcode() == ISD::SELECT_CC) { 13127 if (User->getOperand(0) == Inputs[i]) 13128 SelectTruncOp[0].insert(std::make_pair(User, 13129 User->getOperand(0).getValueType())); 13130 if (User->getOperand(1) == Inputs[i]) 13131 SelectTruncOp[1].insert(std::make_pair(User, 13132 User->getOperand(1).getValueType())); 13133 } 13134 } 13135 } 13136 13137 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) { 13138 for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(), 13139 UE = PromOps[i].getNode()->use_end(); 13140 UI != UE; ++UI) { 13141 SDNode *User = *UI; 13142 if (User != N && !Visited.count(User)) 13143 return SDValue(); 13144 13145 // If we're going to promote the non-output-value operand(s) or SELECT or 13146 // SELECT_CC, record them for truncation. 13147 if (User->getOpcode() == ISD::SELECT) { 13148 if (User->getOperand(0) == PromOps[i]) 13149 SelectTruncOp[0].insert(std::make_pair(User, 13150 User->getOperand(0).getValueType())); 13151 } else if (User->getOpcode() == ISD::SELECT_CC) { 13152 if (User->getOperand(0) == PromOps[i]) 13153 SelectTruncOp[0].insert(std::make_pair(User, 13154 User->getOperand(0).getValueType())); 13155 if (User->getOperand(1) == PromOps[i]) 13156 SelectTruncOp[1].insert(std::make_pair(User, 13157 User->getOperand(1).getValueType())); 13158 } 13159 } 13160 } 13161 13162 unsigned PromBits = N->getOperand(0).getValueSizeInBits(); 13163 bool ReallyNeedsExt = false; 13164 if (N->getOpcode() != ISD::ANY_EXTEND) { 13165 // If all of the inputs are not already sign/zero extended, then 13166 // we'll still need to do that at the end. 13167 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 13168 if (isa<ConstantSDNode>(Inputs[i])) 13169 continue; 13170 13171 unsigned OpBits = 13172 Inputs[i].getOperand(0).getValueSizeInBits(); 13173 assert(PromBits < OpBits && "Truncation not to a smaller bit count?"); 13174 13175 if ((N->getOpcode() == ISD::ZERO_EXTEND && 13176 !DAG.MaskedValueIsZero(Inputs[i].getOperand(0), 13177 APInt::getHighBitsSet(OpBits, 13178 OpBits-PromBits))) || 13179 (N->getOpcode() == ISD::SIGN_EXTEND && 13180 DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) < 13181 (OpBits-(PromBits-1)))) { 13182 ReallyNeedsExt = true; 13183 break; 13184 } 13185 } 13186 } 13187 13188 // Replace all inputs, either with the truncation operand, or a 13189 // truncation or extension to the final output type. 13190 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 13191 // Constant inputs need to be replaced with the to-be-promoted nodes that 13192 // use them because they might have users outside of the cluster of 13193 // promoted nodes. 13194 if (isa<ConstantSDNode>(Inputs[i])) 13195 continue; 13196 13197 SDValue InSrc = Inputs[i].getOperand(0); 13198 if (Inputs[i].getValueType() == N->getValueType(0)) 13199 DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc); 13200 else if (N->getOpcode() == ISD::SIGN_EXTEND) 13201 DAG.ReplaceAllUsesOfValueWith(Inputs[i], 13202 DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0))); 13203 else if (N->getOpcode() == ISD::ZERO_EXTEND) 13204 DAG.ReplaceAllUsesOfValueWith(Inputs[i], 13205 DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0))); 13206 else 13207 DAG.ReplaceAllUsesOfValueWith(Inputs[i], 13208 DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0))); 13209 } 13210 13211 std::list<HandleSDNode> PromOpHandles; 13212 for (auto &PromOp : PromOps) 13213 PromOpHandles.emplace_back(PromOp); 13214 13215 // Replace all operations (these are all the same, but have a different 13216 // (promoted) return type). DAG.getNode will validate that the types of 13217 // a binary operator match, so go through the list in reverse so that 13218 // we've likely promoted both operands first. 13219 while (!PromOpHandles.empty()) { 13220 SDValue PromOp = PromOpHandles.back().getValue(); 13221 PromOpHandles.pop_back(); 13222 13223 unsigned C; 13224 switch (PromOp.getOpcode()) { 13225 default: C = 0; break; 13226 case ISD::SELECT: C = 1; break; 13227 case ISD::SELECT_CC: C = 2; break; 13228 } 13229 13230 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) && 13231 PromOp.getOperand(C).getValueType() != N->getValueType(0)) || 13232 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) && 13233 PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) { 13234 // The to-be-promoted operands of this node have not yet been 13235 // promoted (this should be rare because we're going through the 13236 // list backward, but if one of the operands has several users in 13237 // this cluster of to-be-promoted nodes, it is possible). 13238 PromOpHandles.emplace_front(PromOp); 13239 continue; 13240 } 13241 13242 // For SELECT and SELECT_CC nodes, we do a similar check for any 13243 // to-be-promoted comparison inputs. 13244 if (PromOp.getOpcode() == ISD::SELECT || 13245 PromOp.getOpcode() == ISD::SELECT_CC) { 13246 if ((SelectTruncOp[0].count(PromOp.getNode()) && 13247 PromOp.getOperand(0).getValueType() != N->getValueType(0)) || 13248 (SelectTruncOp[1].count(PromOp.getNode()) && 13249 PromOp.getOperand(1).getValueType() != N->getValueType(0))) { 13250 PromOpHandles.emplace_front(PromOp); 13251 continue; 13252 } 13253 } 13254 13255 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(), 13256 PromOp.getNode()->op_end()); 13257 13258 // If this node has constant inputs, then they'll need to be promoted here. 13259 for (unsigned i = 0; i < 2; ++i) { 13260 if (!isa<ConstantSDNode>(Ops[C+i])) 13261 continue; 13262 if (Ops[C+i].getValueType() == N->getValueType(0)) 13263 continue; 13264 13265 if (N->getOpcode() == ISD::SIGN_EXTEND) 13266 Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); 13267 else if (N->getOpcode() == ISD::ZERO_EXTEND) 13268 Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); 13269 else 13270 Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); 13271 } 13272 13273 // If we've promoted the comparison inputs of a SELECT or SELECT_CC, 13274 // truncate them again to the original value type. 13275 if (PromOp.getOpcode() == ISD::SELECT || 13276 PromOp.getOpcode() == ISD::SELECT_CC) { 13277 auto SI0 = SelectTruncOp[0].find(PromOp.getNode()); 13278 if (SI0 != SelectTruncOp[0].end()) 13279 Ops[0] = DAG.getNode(ISD::TRUNCATE, dl, SI0->second, Ops[0]); 13280 auto SI1 = SelectTruncOp[1].find(PromOp.getNode()); 13281 if (SI1 != SelectTruncOp[1].end()) 13282 Ops[1] = DAG.getNode(ISD::TRUNCATE, dl, SI1->second, Ops[1]); 13283 } 13284 13285 DAG.ReplaceAllUsesOfValueWith(PromOp, 13286 DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops)); 13287 } 13288 13289 // Now we're left with the initial extension itself. 13290 if (!ReallyNeedsExt) 13291 return N->getOperand(0); 13292 13293 // To zero extend, just mask off everything except for the first bit (in the 13294 // i1 case). 13295 if (N->getOpcode() == ISD::ZERO_EXTEND) 13296 return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0), 13297 DAG.getConstant(APInt::getLowBitsSet( 13298 N->getValueSizeInBits(0), PromBits), 13299 dl, N->getValueType(0))); 13300 13301 assert(N->getOpcode() == ISD::SIGN_EXTEND && 13302 "Invalid extension type"); 13303 EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0), DAG.getDataLayout()); 13304 SDValue ShiftCst = 13305 DAG.getConstant(N->getValueSizeInBits(0) - PromBits, dl, ShiftAmountTy); 13306 return DAG.getNode( 13307 ISD::SRA, dl, N->getValueType(0), 13308 DAG.getNode(ISD::SHL, dl, N->getValueType(0), N->getOperand(0), ShiftCst), 13309 ShiftCst); 13310 } 13311 13312 SDValue PPCTargetLowering::combineSetCC(SDNode *N, 13313 DAGCombinerInfo &DCI) const { 13314 assert(N->getOpcode() == ISD::SETCC && 13315 "Should be called with a SETCC node"); 13316 13317 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 13318 if (CC == ISD::SETNE || CC == ISD::SETEQ) { 13319 SDValue LHS = N->getOperand(0); 13320 SDValue RHS = N->getOperand(1); 13321 13322 // If there is a '0 - y' pattern, canonicalize the pattern to the RHS. 13323 if (LHS.getOpcode() == ISD::SUB && isNullConstant(LHS.getOperand(0)) && 13324 LHS.hasOneUse()) 13325 std::swap(LHS, RHS); 13326 13327 // x == 0-y --> x+y == 0 13328 // x != 0-y --> x+y != 0 13329 if (RHS.getOpcode() == ISD::SUB && isNullConstant(RHS.getOperand(0)) && 13330 RHS.hasOneUse()) { 13331 SDLoc DL(N); 13332 SelectionDAG &DAG = DCI.DAG; 13333 EVT VT = N->getValueType(0); 13334 EVT OpVT = LHS.getValueType(); 13335 SDValue Add = DAG.getNode(ISD::ADD, DL, OpVT, LHS, RHS.getOperand(1)); 13336 return DAG.getSetCC(DL, VT, Add, DAG.getConstant(0, DL, OpVT), CC); 13337 } 13338 } 13339 13340 return DAGCombineTruncBoolExt(N, DCI); 13341 } 13342 13343 // Is this an extending load from an f32 to an f64? 13344 static bool isFPExtLoad(SDValue Op) { 13345 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op.getNode())) 13346 return LD->getExtensionType() == ISD::EXTLOAD && 13347 Op.getValueType() == MVT::f64; 13348 return false; 13349 } 13350 13351 /// Reduces the number of fp-to-int conversion when building a vector. 13352 /// 13353 /// If this vector is built out of floating to integer conversions, 13354 /// transform it to a vector built out of floating point values followed by a 13355 /// single floating to integer conversion of the vector. 13356 /// Namely (build_vector (fptosi $A), (fptosi $B), ...) 13357 /// becomes (fptosi (build_vector ($A, $B, ...))) 13358 SDValue PPCTargetLowering:: 13359 combineElementTruncationToVectorTruncation(SDNode *N, 13360 DAGCombinerInfo &DCI) const { 13361 assert(N->getOpcode() == ISD::BUILD_VECTOR && 13362 "Should be called with a BUILD_VECTOR node"); 13363 13364 SelectionDAG &DAG = DCI.DAG; 13365 SDLoc dl(N); 13366 13367 SDValue FirstInput = N->getOperand(0); 13368 assert(FirstInput.getOpcode() == PPCISD::MFVSR && 13369 "The input operand must be an fp-to-int conversion."); 13370 13371 // This combine happens after legalization so the fp_to_[su]i nodes are 13372 // already converted to PPCSISD nodes. 13373 unsigned FirstConversion = FirstInput.getOperand(0).getOpcode(); 13374 if (FirstConversion == PPCISD::FCTIDZ || 13375 FirstConversion == PPCISD::FCTIDUZ || 13376 FirstConversion == PPCISD::FCTIWZ || 13377 FirstConversion == PPCISD::FCTIWUZ) { 13378 bool IsSplat = true; 13379 bool Is32Bit = FirstConversion == PPCISD::FCTIWZ || 13380 FirstConversion == PPCISD::FCTIWUZ; 13381 EVT SrcVT = FirstInput.getOperand(0).getValueType(); 13382 SmallVector<SDValue, 4> Ops; 13383 EVT TargetVT = N->getValueType(0); 13384 for (int i = 0, e = N->getNumOperands(); i < e; ++i) { 13385 SDValue NextOp = N->getOperand(i); 13386 if (NextOp.getOpcode() != PPCISD::MFVSR) 13387 return SDValue(); 13388 unsigned NextConversion = NextOp.getOperand(0).getOpcode(); 13389 if (NextConversion != FirstConversion) 13390 return SDValue(); 13391 // If we are converting to 32-bit integers, we need to add an FP_ROUND. 13392 // This is not valid if the input was originally double precision. It is 13393 // also not profitable to do unless this is an extending load in which 13394 // case doing this combine will allow us to combine consecutive loads. 13395 if (Is32Bit && !isFPExtLoad(NextOp.getOperand(0).getOperand(0))) 13396 return SDValue(); 13397 if (N->getOperand(i) != FirstInput) 13398 IsSplat = false; 13399 } 13400 13401 // If this is a splat, we leave it as-is since there will be only a single 13402 // fp-to-int conversion followed by a splat of the integer. This is better 13403 // for 32-bit and smaller ints and neutral for 64-bit ints. 13404 if (IsSplat) 13405 return SDValue(); 13406 13407 // Now that we know we have the right type of node, get its operands 13408 for (int i = 0, e = N->getNumOperands(); i < e; ++i) { 13409 SDValue In = N->getOperand(i).getOperand(0); 13410 if (Is32Bit) { 13411 // For 32-bit values, we need to add an FP_ROUND node (if we made it 13412 // here, we know that all inputs are extending loads so this is safe). 13413 if (In.isUndef()) 13414 Ops.push_back(DAG.getUNDEF(SrcVT)); 13415 else { 13416 SDValue Trunc = DAG.getNode(ISD::FP_ROUND, dl, 13417 MVT::f32, In.getOperand(0), 13418 DAG.getIntPtrConstant(1, dl)); 13419 Ops.push_back(Trunc); 13420 } 13421 } else 13422 Ops.push_back(In.isUndef() ? DAG.getUNDEF(SrcVT) : In.getOperand(0)); 13423 } 13424 13425 unsigned Opcode; 13426 if (FirstConversion == PPCISD::FCTIDZ || 13427 FirstConversion == PPCISD::FCTIWZ) 13428 Opcode = ISD::FP_TO_SINT; 13429 else 13430 Opcode = ISD::FP_TO_UINT; 13431 13432 EVT NewVT = TargetVT == MVT::v2i64 ? MVT::v2f64 : MVT::v4f32; 13433 SDValue BV = DAG.getBuildVector(NewVT, dl, Ops); 13434 return DAG.getNode(Opcode, dl, TargetVT, BV); 13435 } 13436 return SDValue(); 13437 } 13438 13439 /// Reduce the number of loads when building a vector. 13440 /// 13441 /// Building a vector out of multiple loads can be converted to a load 13442 /// of the vector type if the loads are consecutive. If the loads are 13443 /// consecutive but in descending order, a shuffle is added at the end 13444 /// to reorder the vector. 13445 static SDValue combineBVOfConsecutiveLoads(SDNode *N, SelectionDAG &DAG) { 13446 assert(N->getOpcode() == ISD::BUILD_VECTOR && 13447 "Should be called with a BUILD_VECTOR node"); 13448 13449 SDLoc dl(N); 13450 13451 // Return early for non byte-sized type, as they can't be consecutive. 13452 if (!N->getValueType(0).getVectorElementType().isByteSized()) 13453 return SDValue(); 13454 13455 bool InputsAreConsecutiveLoads = true; 13456 bool InputsAreReverseConsecutive = true; 13457 unsigned ElemSize = N->getValueType(0).getScalarType().getStoreSize(); 13458 SDValue FirstInput = N->getOperand(0); 13459 bool IsRoundOfExtLoad = false; 13460 13461 if (FirstInput.getOpcode() == ISD::FP_ROUND && 13462 FirstInput.getOperand(0).getOpcode() == ISD::LOAD) { 13463 LoadSDNode *LD = dyn_cast<LoadSDNode>(FirstInput.getOperand(0)); 13464 IsRoundOfExtLoad = LD->getExtensionType() == ISD::EXTLOAD; 13465 } 13466 // Not a build vector of (possibly fp_rounded) loads. 13467 if ((!IsRoundOfExtLoad && FirstInput.getOpcode() != ISD::LOAD) || 13468 N->getNumOperands() == 1) 13469 return SDValue(); 13470 13471 for (int i = 1, e = N->getNumOperands(); i < e; ++i) { 13472 // If any inputs are fp_round(extload), they all must be. 13473 if (IsRoundOfExtLoad && N->getOperand(i).getOpcode() != ISD::FP_ROUND) 13474 return SDValue(); 13475 13476 SDValue NextInput = IsRoundOfExtLoad ? N->getOperand(i).getOperand(0) : 13477 N->getOperand(i); 13478 if (NextInput.getOpcode() != ISD::LOAD) 13479 return SDValue(); 13480 13481 SDValue PreviousInput = 13482 IsRoundOfExtLoad ? N->getOperand(i-1).getOperand(0) : N->getOperand(i-1); 13483 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(PreviousInput); 13484 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(NextInput); 13485 13486 // If any inputs are fp_round(extload), they all must be. 13487 if (IsRoundOfExtLoad && LD2->getExtensionType() != ISD::EXTLOAD) 13488 return SDValue(); 13489 13490 if (!isConsecutiveLS(LD2, LD1, ElemSize, 1, DAG)) 13491 InputsAreConsecutiveLoads = false; 13492 if (!isConsecutiveLS(LD1, LD2, ElemSize, 1, DAG)) 13493 InputsAreReverseConsecutive = false; 13494 13495 // Exit early if the loads are neither consecutive nor reverse consecutive. 13496 if (!InputsAreConsecutiveLoads && !InputsAreReverseConsecutive) 13497 return SDValue(); 13498 } 13499 13500 assert(!(InputsAreConsecutiveLoads && InputsAreReverseConsecutive) && 13501 "The loads cannot be both consecutive and reverse consecutive."); 13502 13503 SDValue FirstLoadOp = 13504 IsRoundOfExtLoad ? FirstInput.getOperand(0) : FirstInput; 13505 SDValue LastLoadOp = 13506 IsRoundOfExtLoad ? N->getOperand(N->getNumOperands()-1).getOperand(0) : 13507 N->getOperand(N->getNumOperands()-1); 13508 13509 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(FirstLoadOp); 13510 LoadSDNode *LDL = dyn_cast<LoadSDNode>(LastLoadOp); 13511 if (InputsAreConsecutiveLoads) { 13512 assert(LD1 && "Input needs to be a LoadSDNode."); 13513 return DAG.getLoad(N->getValueType(0), dl, LD1->getChain(), 13514 LD1->getBasePtr(), LD1->getPointerInfo(), 13515 LD1->getAlignment()); 13516 } 13517 if (InputsAreReverseConsecutive) { 13518 assert(LDL && "Input needs to be a LoadSDNode."); 13519 SDValue Load = DAG.getLoad(N->getValueType(0), dl, LDL->getChain(), 13520 LDL->getBasePtr(), LDL->getPointerInfo(), 13521 LDL->getAlignment()); 13522 SmallVector<int, 16> Ops; 13523 for (int i = N->getNumOperands() - 1; i >= 0; i--) 13524 Ops.push_back(i); 13525 13526 return DAG.getVectorShuffle(N->getValueType(0), dl, Load, 13527 DAG.getUNDEF(N->getValueType(0)), Ops); 13528 } 13529 return SDValue(); 13530 } 13531 13532 // This function adds the required vector_shuffle needed to get 13533 // the elements of the vector extract in the correct position 13534 // as specified by the CorrectElems encoding. 13535 static SDValue addShuffleForVecExtend(SDNode *N, SelectionDAG &DAG, 13536 SDValue Input, uint64_t Elems, 13537 uint64_t CorrectElems) { 13538 SDLoc dl(N); 13539 13540 unsigned NumElems = Input.getValueType().getVectorNumElements(); 13541 SmallVector<int, 16> ShuffleMask(NumElems, -1); 13542 13543 // Knowing the element indices being extracted from the original 13544 // vector and the order in which they're being inserted, just put 13545 // them at element indices required for the instruction. 13546 for (unsigned i = 0; i < N->getNumOperands(); i++) { 13547 if (DAG.getDataLayout().isLittleEndian()) 13548 ShuffleMask[CorrectElems & 0xF] = Elems & 0xF; 13549 else 13550 ShuffleMask[(CorrectElems & 0xF0) >> 4] = (Elems & 0xF0) >> 4; 13551 CorrectElems = CorrectElems >> 8; 13552 Elems = Elems >> 8; 13553 } 13554 13555 SDValue Shuffle = 13556 DAG.getVectorShuffle(Input.getValueType(), dl, Input, 13557 DAG.getUNDEF(Input.getValueType()), ShuffleMask); 13558 13559 EVT VT = N->getValueType(0); 13560 SDValue Conv = DAG.getBitcast(VT, Shuffle); 13561 13562 EVT ExtVT = EVT::getVectorVT(*DAG.getContext(), 13563 Input.getValueType().getVectorElementType(), 13564 VT.getVectorNumElements()); 13565 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, VT, Conv, 13566 DAG.getValueType(ExtVT)); 13567 } 13568 13569 // Look for build vector patterns where input operands come from sign 13570 // extended vector_extract elements of specific indices. If the correct indices 13571 // aren't used, add a vector shuffle to fix up the indices and create 13572 // SIGN_EXTEND_INREG node which selects the vector sign extend instructions 13573 // during instruction selection. 13574 static SDValue combineBVOfVecSExt(SDNode *N, SelectionDAG &DAG) { 13575 // This array encodes the indices that the vector sign extend instructions 13576 // extract from when extending from one type to another for both BE and LE. 13577 // The right nibble of each byte corresponds to the LE incides. 13578 // and the left nibble of each byte corresponds to the BE incides. 13579 // For example: 0x3074B8FC byte->word 13580 // For LE: the allowed indices are: 0x0,0x4,0x8,0xC 13581 // For BE: the allowed indices are: 0x3,0x7,0xB,0xF 13582 // For example: 0x000070F8 byte->double word 13583 // For LE: the allowed indices are: 0x0,0x8 13584 // For BE: the allowed indices are: 0x7,0xF 13585 uint64_t TargetElems[] = { 13586 0x3074B8FC, // b->w 13587 0x000070F8, // b->d 13588 0x10325476, // h->w 13589 0x00003074, // h->d 13590 0x00001032, // w->d 13591 }; 13592 13593 uint64_t Elems = 0; 13594 int Index; 13595 SDValue Input; 13596 13597 auto isSExtOfVecExtract = [&](SDValue Op) -> bool { 13598 if (!Op) 13599 return false; 13600 if (Op.getOpcode() != ISD::SIGN_EXTEND && 13601 Op.getOpcode() != ISD::SIGN_EXTEND_INREG) 13602 return false; 13603 13604 // A SIGN_EXTEND_INREG might be fed by an ANY_EXTEND to produce a value 13605 // of the right width. 13606 SDValue Extract = Op.getOperand(0); 13607 if (Extract.getOpcode() == ISD::ANY_EXTEND) 13608 Extract = Extract.getOperand(0); 13609 if (Extract.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 13610 return false; 13611 13612 ConstantSDNode *ExtOp = dyn_cast<ConstantSDNode>(Extract.getOperand(1)); 13613 if (!ExtOp) 13614 return false; 13615 13616 Index = ExtOp->getZExtValue(); 13617 if (Input && Input != Extract.getOperand(0)) 13618 return false; 13619 13620 if (!Input) 13621 Input = Extract.getOperand(0); 13622 13623 Elems = Elems << 8; 13624 Index = DAG.getDataLayout().isLittleEndian() ? Index : Index << 4; 13625 Elems |= Index; 13626 13627 return true; 13628 }; 13629 13630 // If the build vector operands aren't sign extended vector extracts, 13631 // of the same input vector, then return. 13632 for (unsigned i = 0; i < N->getNumOperands(); i++) { 13633 if (!isSExtOfVecExtract(N->getOperand(i))) { 13634 return SDValue(); 13635 } 13636 } 13637 13638 // If the vector extract indicies are not correct, add the appropriate 13639 // vector_shuffle. 13640 int TgtElemArrayIdx; 13641 int InputSize = Input.getValueType().getScalarSizeInBits(); 13642 int OutputSize = N->getValueType(0).getScalarSizeInBits(); 13643 if (InputSize + OutputSize == 40) 13644 TgtElemArrayIdx = 0; 13645 else if (InputSize + OutputSize == 72) 13646 TgtElemArrayIdx = 1; 13647 else if (InputSize + OutputSize == 48) 13648 TgtElemArrayIdx = 2; 13649 else if (InputSize + OutputSize == 80) 13650 TgtElemArrayIdx = 3; 13651 else if (InputSize + OutputSize == 96) 13652 TgtElemArrayIdx = 4; 13653 else 13654 return SDValue(); 13655 13656 uint64_t CorrectElems = TargetElems[TgtElemArrayIdx]; 13657 CorrectElems = DAG.getDataLayout().isLittleEndian() 13658 ? CorrectElems & 0x0F0F0F0F0F0F0F0F 13659 : CorrectElems & 0xF0F0F0F0F0F0F0F0; 13660 if (Elems != CorrectElems) { 13661 return addShuffleForVecExtend(N, DAG, Input, Elems, CorrectElems); 13662 } 13663 13664 // Regular lowering will catch cases where a shuffle is not needed. 13665 return SDValue(); 13666 } 13667 13668 SDValue PPCTargetLowering::DAGCombineBuildVector(SDNode *N, 13669 DAGCombinerInfo &DCI) const { 13670 assert(N->getOpcode() == ISD::BUILD_VECTOR && 13671 "Should be called with a BUILD_VECTOR node"); 13672 13673 SelectionDAG &DAG = DCI.DAG; 13674 SDLoc dl(N); 13675 13676 if (!Subtarget.hasVSX()) 13677 return SDValue(); 13678 13679 // The target independent DAG combiner will leave a build_vector of 13680 // float-to-int conversions intact. We can generate MUCH better code for 13681 // a float-to-int conversion of a vector of floats. 13682 SDValue FirstInput = N->getOperand(0); 13683 if (FirstInput.getOpcode() == PPCISD::MFVSR) { 13684 SDValue Reduced = combineElementTruncationToVectorTruncation(N, DCI); 13685 if (Reduced) 13686 return Reduced; 13687 } 13688 13689 // If we're building a vector out of consecutive loads, just load that 13690 // vector type. 13691 SDValue Reduced = combineBVOfConsecutiveLoads(N, DAG); 13692 if (Reduced) 13693 return Reduced; 13694 13695 // If we're building a vector out of extended elements from another vector 13696 // we have P9 vector integer extend instructions. The code assumes legal 13697 // input types (i.e. it can't handle things like v4i16) so do not run before 13698 // legalization. 13699 if (Subtarget.hasP9Altivec() && !DCI.isBeforeLegalize()) { 13700 Reduced = combineBVOfVecSExt(N, DAG); 13701 if (Reduced) 13702 return Reduced; 13703 } 13704 13705 13706 if (N->getValueType(0) != MVT::v2f64) 13707 return SDValue(); 13708 13709 // Looking for: 13710 // (build_vector ([su]int_to_fp (extractelt 0)), [su]int_to_fp (extractelt 1)) 13711 if (FirstInput.getOpcode() != ISD::SINT_TO_FP && 13712 FirstInput.getOpcode() != ISD::UINT_TO_FP) 13713 return SDValue(); 13714 if (N->getOperand(1).getOpcode() != ISD::SINT_TO_FP && 13715 N->getOperand(1).getOpcode() != ISD::UINT_TO_FP) 13716 return SDValue(); 13717 if (FirstInput.getOpcode() != N->getOperand(1).getOpcode()) 13718 return SDValue(); 13719 13720 SDValue Ext1 = FirstInput.getOperand(0); 13721 SDValue Ext2 = N->getOperand(1).getOperand(0); 13722 if(Ext1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 13723 Ext2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 13724 return SDValue(); 13725 13726 ConstantSDNode *Ext1Op = dyn_cast<ConstantSDNode>(Ext1.getOperand(1)); 13727 ConstantSDNode *Ext2Op = dyn_cast<ConstantSDNode>(Ext2.getOperand(1)); 13728 if (!Ext1Op || !Ext2Op) 13729 return SDValue(); 13730 if (Ext1.getOperand(0).getValueType() != MVT::v4i32 || 13731 Ext1.getOperand(0) != Ext2.getOperand(0)) 13732 return SDValue(); 13733 13734 int FirstElem = Ext1Op->getZExtValue(); 13735 int SecondElem = Ext2Op->getZExtValue(); 13736 int SubvecIdx; 13737 if (FirstElem == 0 && SecondElem == 1) 13738 SubvecIdx = Subtarget.isLittleEndian() ? 1 : 0; 13739 else if (FirstElem == 2 && SecondElem == 3) 13740 SubvecIdx = Subtarget.isLittleEndian() ? 0 : 1; 13741 else 13742 return SDValue(); 13743 13744 SDValue SrcVec = Ext1.getOperand(0); 13745 auto NodeType = (N->getOperand(1).getOpcode() == ISD::SINT_TO_FP) ? 13746 PPCISD::SINT_VEC_TO_FP : PPCISD::UINT_VEC_TO_FP; 13747 return DAG.getNode(NodeType, dl, MVT::v2f64, 13748 SrcVec, DAG.getIntPtrConstant(SubvecIdx, dl)); 13749 } 13750 13751 SDValue PPCTargetLowering::combineFPToIntToFP(SDNode *N, 13752 DAGCombinerInfo &DCI) const { 13753 assert((N->getOpcode() == ISD::SINT_TO_FP || 13754 N->getOpcode() == ISD::UINT_TO_FP) && 13755 "Need an int -> FP conversion node here"); 13756 13757 if (useSoftFloat() || !Subtarget.has64BitSupport()) 13758 return SDValue(); 13759 13760 SelectionDAG &DAG = DCI.DAG; 13761 SDLoc dl(N); 13762 SDValue Op(N, 0); 13763 13764 // Don't handle ppc_fp128 here or conversions that are out-of-range capable 13765 // from the hardware. 13766 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64) 13767 return SDValue(); 13768 if (Op.getOperand(0).getValueType().getSimpleVT() <= MVT(MVT::i1) || 13769 Op.getOperand(0).getValueType().getSimpleVT() > MVT(MVT::i64)) 13770 return SDValue(); 13771 13772 SDValue FirstOperand(Op.getOperand(0)); 13773 bool SubWordLoad = FirstOperand.getOpcode() == ISD::LOAD && 13774 (FirstOperand.getValueType() == MVT::i8 || 13775 FirstOperand.getValueType() == MVT::i16); 13776 if (Subtarget.hasP9Vector() && Subtarget.hasP9Altivec() && SubWordLoad) { 13777 bool Signed = N->getOpcode() == ISD::SINT_TO_FP; 13778 bool DstDouble = Op.getValueType() == MVT::f64; 13779 unsigned ConvOp = Signed ? 13780 (DstDouble ? PPCISD::FCFID : PPCISD::FCFIDS) : 13781 (DstDouble ? PPCISD::FCFIDU : PPCISD::FCFIDUS); 13782 SDValue WidthConst = 13783 DAG.getIntPtrConstant(FirstOperand.getValueType() == MVT::i8 ? 1 : 2, 13784 dl, false); 13785 LoadSDNode *LDN = cast<LoadSDNode>(FirstOperand.getNode()); 13786 SDValue Ops[] = { LDN->getChain(), LDN->getBasePtr(), WidthConst }; 13787 SDValue Ld = DAG.getMemIntrinsicNode(PPCISD::LXSIZX, dl, 13788 DAG.getVTList(MVT::f64, MVT::Other), 13789 Ops, MVT::i8, LDN->getMemOperand()); 13790 13791 // For signed conversion, we need to sign-extend the value in the VSR 13792 if (Signed) { 13793 SDValue ExtOps[] = { Ld, WidthConst }; 13794 SDValue Ext = DAG.getNode(PPCISD::VEXTS, dl, MVT::f64, ExtOps); 13795 return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ext); 13796 } else 13797 return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ld); 13798 } 13799 13800 13801 // For i32 intermediate values, unfortunately, the conversion functions 13802 // leave the upper 32 bits of the value are undefined. Within the set of 13803 // scalar instructions, we have no method for zero- or sign-extending the 13804 // value. Thus, we cannot handle i32 intermediate values here. 13805 if (Op.getOperand(0).getValueType() == MVT::i32) 13806 return SDValue(); 13807 13808 assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) && 13809 "UINT_TO_FP is supported only with FPCVT"); 13810 13811 // If we have FCFIDS, then use it when converting to single-precision. 13812 // Otherwise, convert to double-precision and then round. 13813 unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 13814 ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS 13815 : PPCISD::FCFIDS) 13816 : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU 13817 : PPCISD::FCFID); 13818 MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 13819 ? MVT::f32 13820 : MVT::f64; 13821 13822 // If we're converting from a float, to an int, and back to a float again, 13823 // then we don't need the store/load pair at all. 13824 if ((Op.getOperand(0).getOpcode() == ISD::FP_TO_UINT && 13825 Subtarget.hasFPCVT()) || 13826 (Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT)) { 13827 SDValue Src = Op.getOperand(0).getOperand(0); 13828 if (Src.getValueType() == MVT::f32) { 13829 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src); 13830 DCI.AddToWorklist(Src.getNode()); 13831 } else if (Src.getValueType() != MVT::f64) { 13832 // Make sure that we don't pick up a ppc_fp128 source value. 13833 return SDValue(); 13834 } 13835 13836 unsigned FCTOp = 13837 Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT ? PPCISD::FCTIDZ : 13838 PPCISD::FCTIDUZ; 13839 13840 SDValue Tmp = DAG.getNode(FCTOp, dl, MVT::f64, Src); 13841 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Tmp); 13842 13843 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) { 13844 FP = DAG.getNode(ISD::FP_ROUND, dl, 13845 MVT::f32, FP, DAG.getIntPtrConstant(0, dl)); 13846 DCI.AddToWorklist(FP.getNode()); 13847 } 13848 13849 return FP; 13850 } 13851 13852 return SDValue(); 13853 } 13854 13855 // expandVSXLoadForLE - Convert VSX loads (which may be intrinsics for 13856 // builtins) into loads with swaps. 13857 SDValue PPCTargetLowering::expandVSXLoadForLE(SDNode *N, 13858 DAGCombinerInfo &DCI) const { 13859 SelectionDAG &DAG = DCI.DAG; 13860 SDLoc dl(N); 13861 SDValue Chain; 13862 SDValue Base; 13863 MachineMemOperand *MMO; 13864 13865 switch (N->getOpcode()) { 13866 default: 13867 llvm_unreachable("Unexpected opcode for little endian VSX load"); 13868 case ISD::LOAD: { 13869 LoadSDNode *LD = cast<LoadSDNode>(N); 13870 Chain = LD->getChain(); 13871 Base = LD->getBasePtr(); 13872 MMO = LD->getMemOperand(); 13873 // If the MMO suggests this isn't a load of a full vector, leave 13874 // things alone. For a built-in, we have to make the change for 13875 // correctness, so if there is a size problem that will be a bug. 13876 if (MMO->getSize() < 16) 13877 return SDValue(); 13878 break; 13879 } 13880 case ISD::INTRINSIC_W_CHAIN: { 13881 MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N); 13882 Chain = Intrin->getChain(); 13883 // Similarly to the store case below, Intrin->getBasePtr() doesn't get 13884 // us what we want. Get operand 2 instead. 13885 Base = Intrin->getOperand(2); 13886 MMO = Intrin->getMemOperand(); 13887 break; 13888 } 13889 } 13890 13891 MVT VecTy = N->getValueType(0).getSimpleVT(); 13892 13893 // Do not expand to PPCISD::LXVD2X + PPCISD::XXSWAPD when the load is 13894 // aligned and the type is a vector with elements up to 4 bytes 13895 if (Subtarget.needsSwapsForVSXMemOps() && MMO->getAlign() >= Align(16) && 13896 VecTy.getScalarSizeInBits() <= 32) { 13897 return SDValue(); 13898 } 13899 13900 SDValue LoadOps[] = { Chain, Base }; 13901 SDValue Load = DAG.getMemIntrinsicNode(PPCISD::LXVD2X, dl, 13902 DAG.getVTList(MVT::v2f64, MVT::Other), 13903 LoadOps, MVT::v2f64, MMO); 13904 13905 DCI.AddToWorklist(Load.getNode()); 13906 Chain = Load.getValue(1); 13907 SDValue Swap = DAG.getNode( 13908 PPCISD::XXSWAPD, dl, DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Load); 13909 DCI.AddToWorklist(Swap.getNode()); 13910 13911 // Add a bitcast if the resulting load type doesn't match v2f64. 13912 if (VecTy != MVT::v2f64) { 13913 SDValue N = DAG.getNode(ISD::BITCAST, dl, VecTy, Swap); 13914 DCI.AddToWorklist(N.getNode()); 13915 // Package {bitcast value, swap's chain} to match Load's shape. 13916 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VecTy, MVT::Other), 13917 N, Swap.getValue(1)); 13918 } 13919 13920 return Swap; 13921 } 13922 13923 // expandVSXStoreForLE - Convert VSX stores (which may be intrinsics for 13924 // builtins) into stores with swaps. 13925 SDValue PPCTargetLowering::expandVSXStoreForLE(SDNode *N, 13926 DAGCombinerInfo &DCI) const { 13927 SelectionDAG &DAG = DCI.DAG; 13928 SDLoc dl(N); 13929 SDValue Chain; 13930 SDValue Base; 13931 unsigned SrcOpnd; 13932 MachineMemOperand *MMO; 13933 13934 switch (N->getOpcode()) { 13935 default: 13936 llvm_unreachable("Unexpected opcode for little endian VSX store"); 13937 case ISD::STORE: { 13938 StoreSDNode *ST = cast<StoreSDNode>(N); 13939 Chain = ST->getChain(); 13940 Base = ST->getBasePtr(); 13941 MMO = ST->getMemOperand(); 13942 SrcOpnd = 1; 13943 // If the MMO suggests this isn't a store of a full vector, leave 13944 // things alone. For a built-in, we have to make the change for 13945 // correctness, so if there is a size problem that will be a bug. 13946 if (MMO->getSize() < 16) 13947 return SDValue(); 13948 break; 13949 } 13950 case ISD::INTRINSIC_VOID: { 13951 MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N); 13952 Chain = Intrin->getChain(); 13953 // Intrin->getBasePtr() oddly does not get what we want. 13954 Base = Intrin->getOperand(3); 13955 MMO = Intrin->getMemOperand(); 13956 SrcOpnd = 2; 13957 break; 13958 } 13959 } 13960 13961 SDValue Src = N->getOperand(SrcOpnd); 13962 MVT VecTy = Src.getValueType().getSimpleVT(); 13963 13964 // Do not expand to PPCISD::XXSWAPD and PPCISD::STXVD2X when the load is 13965 // aligned and the type is a vector with elements up to 4 bytes 13966 if (Subtarget.needsSwapsForVSXMemOps() && MMO->getAlign() >= Align(16) && 13967 VecTy.getScalarSizeInBits() <= 32) { 13968 return SDValue(); 13969 } 13970 13971 // All stores are done as v2f64 and possible bit cast. 13972 if (VecTy != MVT::v2f64) { 13973 Src = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Src); 13974 DCI.AddToWorklist(Src.getNode()); 13975 } 13976 13977 SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl, 13978 DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Src); 13979 DCI.AddToWorklist(Swap.getNode()); 13980 Chain = Swap.getValue(1); 13981 SDValue StoreOps[] = { Chain, Swap, Base }; 13982 SDValue Store = DAG.getMemIntrinsicNode(PPCISD::STXVD2X, dl, 13983 DAG.getVTList(MVT::Other), 13984 StoreOps, VecTy, MMO); 13985 DCI.AddToWorklist(Store.getNode()); 13986 return Store; 13987 } 13988 13989 // Handle DAG combine for STORE (FP_TO_INT F). 13990 SDValue PPCTargetLowering::combineStoreFPToInt(SDNode *N, 13991 DAGCombinerInfo &DCI) const { 13992 13993 SelectionDAG &DAG = DCI.DAG; 13994 SDLoc dl(N); 13995 unsigned Opcode = N->getOperand(1).getOpcode(); 13996 13997 assert((Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT) 13998 && "Not a FP_TO_INT Instruction!"); 13999 14000 SDValue Val = N->getOperand(1).getOperand(0); 14001 EVT Op1VT = N->getOperand(1).getValueType(); 14002 EVT ResVT = Val.getValueType(); 14003 14004 // Floating point types smaller than 32 bits are not legal on Power. 14005 if (ResVT.getScalarSizeInBits() < 32) 14006 return SDValue(); 14007 14008 // Only perform combine for conversion to i64/i32 or power9 i16/i8. 14009 bool ValidTypeForStoreFltAsInt = 14010 (Op1VT == MVT::i32 || Op1VT == MVT::i64 || 14011 (Subtarget.hasP9Vector() && (Op1VT == MVT::i16 || Op1VT == MVT::i8))); 14012 14013 if (ResVT == MVT::ppcf128 || !Subtarget.hasP8Vector() || 14014 cast<StoreSDNode>(N)->isTruncatingStore() || !ValidTypeForStoreFltAsInt) 14015 return SDValue(); 14016 14017 // Extend f32 values to f64 14018 if (ResVT.getScalarSizeInBits() == 32) { 14019 Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val); 14020 DCI.AddToWorklist(Val.getNode()); 14021 } 14022 14023 // Set signed or unsigned conversion opcode. 14024 unsigned ConvOpcode = (Opcode == ISD::FP_TO_SINT) ? 14025 PPCISD::FP_TO_SINT_IN_VSR : 14026 PPCISD::FP_TO_UINT_IN_VSR; 14027 14028 Val = DAG.getNode(ConvOpcode, 14029 dl, ResVT == MVT::f128 ? MVT::f128 : MVT::f64, Val); 14030 DCI.AddToWorklist(Val.getNode()); 14031 14032 // Set number of bytes being converted. 14033 unsigned ByteSize = Op1VT.getScalarSizeInBits() / 8; 14034 SDValue Ops[] = { N->getOperand(0), Val, N->getOperand(2), 14035 DAG.getIntPtrConstant(ByteSize, dl, false), 14036 DAG.getValueType(Op1VT) }; 14037 14038 Val = DAG.getMemIntrinsicNode(PPCISD::ST_VSR_SCAL_INT, dl, 14039 DAG.getVTList(MVT::Other), Ops, 14040 cast<StoreSDNode>(N)->getMemoryVT(), 14041 cast<StoreSDNode>(N)->getMemOperand()); 14042 14043 DCI.AddToWorklist(Val.getNode()); 14044 return Val; 14045 } 14046 14047 SDValue PPCTargetLowering::combineVReverseMemOP(ShuffleVectorSDNode *SVN, 14048 LSBaseSDNode *LSBase, 14049 DAGCombinerInfo &DCI) const { 14050 assert((ISD::isNormalLoad(LSBase) || ISD::isNormalStore(LSBase)) && 14051 "Not a reverse memop pattern!"); 14052 14053 auto IsElementReverse = [](const ShuffleVectorSDNode *SVN) -> bool { 14054 auto Mask = SVN->getMask(); 14055 int i = 0; 14056 auto I = Mask.rbegin(); 14057 auto E = Mask.rend(); 14058 14059 for (; I != E; ++I) { 14060 if (*I != i) 14061 return false; 14062 i++; 14063 } 14064 return true; 14065 }; 14066 14067 SelectionDAG &DAG = DCI.DAG; 14068 EVT VT = SVN->getValueType(0); 14069 14070 if (!isTypeLegal(VT) || !Subtarget.isLittleEndian() || !Subtarget.hasVSX()) 14071 return SDValue(); 14072 14073 // Before P9, we have PPCVSXSwapRemoval pass to hack the element order. 14074 // See comment in PPCVSXSwapRemoval.cpp. 14075 // It is conflict with PPCVSXSwapRemoval opt. So we don't do it. 14076 if (!Subtarget.hasP9Vector()) 14077 return SDValue(); 14078 14079 if(!IsElementReverse(SVN)) 14080 return SDValue(); 14081 14082 if (LSBase->getOpcode() == ISD::LOAD) { 14083 SDLoc dl(SVN); 14084 SDValue LoadOps[] = {LSBase->getChain(), LSBase->getBasePtr()}; 14085 return DAG.getMemIntrinsicNode( 14086 PPCISD::LOAD_VEC_BE, dl, DAG.getVTList(VT, MVT::Other), LoadOps, 14087 LSBase->getMemoryVT(), LSBase->getMemOperand()); 14088 } 14089 14090 if (LSBase->getOpcode() == ISD::STORE) { 14091 SDLoc dl(LSBase); 14092 SDValue StoreOps[] = {LSBase->getChain(), SVN->getOperand(0), 14093 LSBase->getBasePtr()}; 14094 return DAG.getMemIntrinsicNode( 14095 PPCISD::STORE_VEC_BE, dl, DAG.getVTList(MVT::Other), StoreOps, 14096 LSBase->getMemoryVT(), LSBase->getMemOperand()); 14097 } 14098 14099 llvm_unreachable("Expected a load or store node here"); 14100 } 14101 14102 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N, 14103 DAGCombinerInfo &DCI) const { 14104 SelectionDAG &DAG = DCI.DAG; 14105 SDLoc dl(N); 14106 switch (N->getOpcode()) { 14107 default: break; 14108 case ISD::ADD: 14109 return combineADD(N, DCI); 14110 case ISD::SHL: 14111 return combineSHL(N, DCI); 14112 case ISD::SRA: 14113 return combineSRA(N, DCI); 14114 case ISD::SRL: 14115 return combineSRL(N, DCI); 14116 case ISD::MUL: 14117 return combineMUL(N, DCI); 14118 case PPCISD::SHL: 14119 if (isNullConstant(N->getOperand(0))) // 0 << V -> 0. 14120 return N->getOperand(0); 14121 break; 14122 case PPCISD::SRL: 14123 if (isNullConstant(N->getOperand(0))) // 0 >>u V -> 0. 14124 return N->getOperand(0); 14125 break; 14126 case PPCISD::SRA: 14127 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) { 14128 if (C->isNullValue() || // 0 >>s V -> 0. 14129 C->isAllOnesValue()) // -1 >>s V -> -1. 14130 return N->getOperand(0); 14131 } 14132 break; 14133 case ISD::SIGN_EXTEND: 14134 case ISD::ZERO_EXTEND: 14135 case ISD::ANY_EXTEND: 14136 return DAGCombineExtBoolTrunc(N, DCI); 14137 case ISD::TRUNCATE: 14138 return combineTRUNCATE(N, DCI); 14139 case ISD::SETCC: 14140 if (SDValue CSCC = combineSetCC(N, DCI)) 14141 return CSCC; 14142 LLVM_FALLTHROUGH; 14143 case ISD::SELECT_CC: 14144 return DAGCombineTruncBoolExt(N, DCI); 14145 case ISD::SINT_TO_FP: 14146 case ISD::UINT_TO_FP: 14147 return combineFPToIntToFP(N, DCI); 14148 case ISD::VECTOR_SHUFFLE: 14149 if (ISD::isNormalLoad(N->getOperand(0).getNode())) { 14150 LSBaseSDNode* LSBase = cast<LSBaseSDNode>(N->getOperand(0)); 14151 return combineVReverseMemOP(cast<ShuffleVectorSDNode>(N), LSBase, DCI); 14152 } 14153 break; 14154 case ISD::STORE: { 14155 14156 EVT Op1VT = N->getOperand(1).getValueType(); 14157 unsigned Opcode = N->getOperand(1).getOpcode(); 14158 14159 if (Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT) { 14160 SDValue Val= combineStoreFPToInt(N, DCI); 14161 if (Val) 14162 return Val; 14163 } 14164 14165 if (Opcode == ISD::VECTOR_SHUFFLE && ISD::isNormalStore(N)) { 14166 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N->getOperand(1)); 14167 SDValue Val= combineVReverseMemOP(SVN, cast<LSBaseSDNode>(N), DCI); 14168 if (Val) 14169 return Val; 14170 } 14171 14172 // Turn STORE (BSWAP) -> sthbrx/stwbrx. 14173 if (cast<StoreSDNode>(N)->isUnindexed() && Opcode == ISD::BSWAP && 14174 N->getOperand(1).getNode()->hasOneUse() && 14175 (Op1VT == MVT::i32 || Op1VT == MVT::i16 || 14176 (Subtarget.hasLDBRX() && Subtarget.isPPC64() && Op1VT == MVT::i64))) { 14177 14178 // STBRX can only handle simple types and it makes no sense to store less 14179 // two bytes in byte-reversed order. 14180 EVT mVT = cast<StoreSDNode>(N)->getMemoryVT(); 14181 if (mVT.isExtended() || mVT.getSizeInBits() < 16) 14182 break; 14183 14184 SDValue BSwapOp = N->getOperand(1).getOperand(0); 14185 // Do an any-extend to 32-bits if this is a half-word input. 14186 if (BSwapOp.getValueType() == MVT::i16) 14187 BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp); 14188 14189 // If the type of BSWAP operand is wider than stored memory width 14190 // it need to be shifted to the right side before STBRX. 14191 if (Op1VT.bitsGT(mVT)) { 14192 int Shift = Op1VT.getSizeInBits() - mVT.getSizeInBits(); 14193 BSwapOp = DAG.getNode(ISD::SRL, dl, Op1VT, BSwapOp, 14194 DAG.getConstant(Shift, dl, MVT::i32)); 14195 // Need to truncate if this is a bswap of i64 stored as i32/i16. 14196 if (Op1VT == MVT::i64) 14197 BSwapOp = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BSwapOp); 14198 } 14199 14200 SDValue Ops[] = { 14201 N->getOperand(0), BSwapOp, N->getOperand(2), DAG.getValueType(mVT) 14202 }; 14203 return 14204 DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other), 14205 Ops, cast<StoreSDNode>(N)->getMemoryVT(), 14206 cast<StoreSDNode>(N)->getMemOperand()); 14207 } 14208 14209 // STORE Constant:i32<0> -> STORE<trunc to i32> Constant:i64<0> 14210 // So it can increase the chance of CSE constant construction. 14211 if (Subtarget.isPPC64() && !DCI.isBeforeLegalize() && 14212 isa<ConstantSDNode>(N->getOperand(1)) && Op1VT == MVT::i32) { 14213 // Need to sign-extended to 64-bits to handle negative values. 14214 EVT MemVT = cast<StoreSDNode>(N)->getMemoryVT(); 14215 uint64_t Val64 = SignExtend64(N->getConstantOperandVal(1), 14216 MemVT.getSizeInBits()); 14217 SDValue Const64 = DAG.getConstant(Val64, dl, MVT::i64); 14218 14219 // DAG.getTruncStore() can't be used here because it doesn't accept 14220 // the general (base + offset) addressing mode. 14221 // So we use UpdateNodeOperands and setTruncatingStore instead. 14222 DAG.UpdateNodeOperands(N, N->getOperand(0), Const64, N->getOperand(2), 14223 N->getOperand(3)); 14224 cast<StoreSDNode>(N)->setTruncatingStore(true); 14225 return SDValue(N, 0); 14226 } 14227 14228 // For little endian, VSX stores require generating xxswapd/lxvd2x. 14229 // Not needed on ISA 3.0 based CPUs since we have a non-permuting store. 14230 if (Op1VT.isSimple()) { 14231 MVT StoreVT = Op1VT.getSimpleVT(); 14232 if (Subtarget.needsSwapsForVSXMemOps() && 14233 (StoreVT == MVT::v2f64 || StoreVT == MVT::v2i64 || 14234 StoreVT == MVT::v4f32 || StoreVT == MVT::v4i32)) 14235 return expandVSXStoreForLE(N, DCI); 14236 } 14237 break; 14238 } 14239 case ISD::LOAD: { 14240 LoadSDNode *LD = cast<LoadSDNode>(N); 14241 EVT VT = LD->getValueType(0); 14242 14243 // For little endian, VSX loads require generating lxvd2x/xxswapd. 14244 // Not needed on ISA 3.0 based CPUs since we have a non-permuting load. 14245 if (VT.isSimple()) { 14246 MVT LoadVT = VT.getSimpleVT(); 14247 if (Subtarget.needsSwapsForVSXMemOps() && 14248 (LoadVT == MVT::v2f64 || LoadVT == MVT::v2i64 || 14249 LoadVT == MVT::v4f32 || LoadVT == MVT::v4i32)) 14250 return expandVSXLoadForLE(N, DCI); 14251 } 14252 14253 // We sometimes end up with a 64-bit integer load, from which we extract 14254 // two single-precision floating-point numbers. This happens with 14255 // std::complex<float>, and other similar structures, because of the way we 14256 // canonicalize structure copies. However, if we lack direct moves, 14257 // then the final bitcasts from the extracted integer values to the 14258 // floating-point numbers turn into store/load pairs. Even with direct moves, 14259 // just loading the two floating-point numbers is likely better. 14260 auto ReplaceTwoFloatLoad = [&]() { 14261 if (VT != MVT::i64) 14262 return false; 14263 14264 if (LD->getExtensionType() != ISD::NON_EXTLOAD || 14265 LD->isVolatile()) 14266 return false; 14267 14268 // We're looking for a sequence like this: 14269 // t13: i64,ch = load<LD8[%ref.tmp]> t0, t6, undef:i64 14270 // t16: i64 = srl t13, Constant:i32<32> 14271 // t17: i32 = truncate t16 14272 // t18: f32 = bitcast t17 14273 // t19: i32 = truncate t13 14274 // t20: f32 = bitcast t19 14275 14276 if (!LD->hasNUsesOfValue(2, 0)) 14277 return false; 14278 14279 auto UI = LD->use_begin(); 14280 while (UI.getUse().getResNo() != 0) ++UI; 14281 SDNode *Trunc = *UI++; 14282 while (UI.getUse().getResNo() != 0) ++UI; 14283 SDNode *RightShift = *UI; 14284 if (Trunc->getOpcode() != ISD::TRUNCATE) 14285 std::swap(Trunc, RightShift); 14286 14287 if (Trunc->getOpcode() != ISD::TRUNCATE || 14288 Trunc->getValueType(0) != MVT::i32 || 14289 !Trunc->hasOneUse()) 14290 return false; 14291 if (RightShift->getOpcode() != ISD::SRL || 14292 !isa<ConstantSDNode>(RightShift->getOperand(1)) || 14293 RightShift->getConstantOperandVal(1) != 32 || 14294 !RightShift->hasOneUse()) 14295 return false; 14296 14297 SDNode *Trunc2 = *RightShift->use_begin(); 14298 if (Trunc2->getOpcode() != ISD::TRUNCATE || 14299 Trunc2->getValueType(0) != MVT::i32 || 14300 !Trunc2->hasOneUse()) 14301 return false; 14302 14303 SDNode *Bitcast = *Trunc->use_begin(); 14304 SDNode *Bitcast2 = *Trunc2->use_begin(); 14305 14306 if (Bitcast->getOpcode() != ISD::BITCAST || 14307 Bitcast->getValueType(0) != MVT::f32) 14308 return false; 14309 if (Bitcast2->getOpcode() != ISD::BITCAST || 14310 Bitcast2->getValueType(0) != MVT::f32) 14311 return false; 14312 14313 if (Subtarget.isLittleEndian()) 14314 std::swap(Bitcast, Bitcast2); 14315 14316 // Bitcast has the second float (in memory-layout order) and Bitcast2 14317 // has the first one. 14318 14319 SDValue BasePtr = LD->getBasePtr(); 14320 if (LD->isIndexed()) { 14321 assert(LD->getAddressingMode() == ISD::PRE_INC && 14322 "Non-pre-inc AM on PPC?"); 14323 BasePtr = 14324 DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, 14325 LD->getOffset()); 14326 } 14327 14328 auto MMOFlags = 14329 LD->getMemOperand()->getFlags() & ~MachineMemOperand::MOVolatile; 14330 SDValue FloatLoad = DAG.getLoad(MVT::f32, dl, LD->getChain(), BasePtr, 14331 LD->getPointerInfo(), LD->getAlignment(), 14332 MMOFlags, LD->getAAInfo()); 14333 SDValue AddPtr = 14334 DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), 14335 BasePtr, DAG.getIntPtrConstant(4, dl)); 14336 SDValue FloatLoad2 = DAG.getLoad( 14337 MVT::f32, dl, SDValue(FloatLoad.getNode(), 1), AddPtr, 14338 LD->getPointerInfo().getWithOffset(4), 14339 MinAlign(LD->getAlignment(), 4), MMOFlags, LD->getAAInfo()); 14340 14341 if (LD->isIndexed()) { 14342 // Note that DAGCombine should re-form any pre-increment load(s) from 14343 // what is produced here if that makes sense. 14344 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), BasePtr); 14345 } 14346 14347 DCI.CombineTo(Bitcast2, FloatLoad); 14348 DCI.CombineTo(Bitcast, FloatLoad2); 14349 14350 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, LD->isIndexed() ? 2 : 1), 14351 SDValue(FloatLoad2.getNode(), 1)); 14352 return true; 14353 }; 14354 14355 if (ReplaceTwoFloatLoad()) 14356 return SDValue(N, 0); 14357 14358 EVT MemVT = LD->getMemoryVT(); 14359 Type *Ty = MemVT.getTypeForEVT(*DAG.getContext()); 14360 unsigned ABIAlignment = DAG.getDataLayout().getABITypeAlignment(Ty); 14361 Type *STy = MemVT.getScalarType().getTypeForEVT(*DAG.getContext()); 14362 unsigned ScalarABIAlignment = DAG.getDataLayout().getABITypeAlignment(STy); 14363 if (LD->isUnindexed() && VT.isVector() && 14364 ((Subtarget.hasAltivec() && ISD::isNON_EXTLoad(N) && 14365 // P8 and later hardware should just use LOAD. 14366 !Subtarget.hasP8Vector() && (VT == MVT::v16i8 || VT == MVT::v8i16 || 14367 VT == MVT::v4i32 || VT == MVT::v4f32)) || 14368 (Subtarget.hasQPX() && (VT == MVT::v4f64 || VT == MVT::v4f32) && 14369 LD->getAlignment() >= ScalarABIAlignment)) && 14370 LD->getAlignment() < ABIAlignment) { 14371 // This is a type-legal unaligned Altivec or QPX load. 14372 SDValue Chain = LD->getChain(); 14373 SDValue Ptr = LD->getBasePtr(); 14374 bool isLittleEndian = Subtarget.isLittleEndian(); 14375 14376 // This implements the loading of unaligned vectors as described in 14377 // the venerable Apple Velocity Engine overview. Specifically: 14378 // https://developer.apple.com/hardwaredrivers/ve/alignment.html 14379 // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html 14380 // 14381 // The general idea is to expand a sequence of one or more unaligned 14382 // loads into an alignment-based permutation-control instruction (lvsl 14383 // or lvsr), a series of regular vector loads (which always truncate 14384 // their input address to an aligned address), and a series of 14385 // permutations. The results of these permutations are the requested 14386 // loaded values. The trick is that the last "extra" load is not taken 14387 // from the address you might suspect (sizeof(vector) bytes after the 14388 // last requested load), but rather sizeof(vector) - 1 bytes after the 14389 // last requested vector. The point of this is to avoid a page fault if 14390 // the base address happened to be aligned. This works because if the 14391 // base address is aligned, then adding less than a full vector length 14392 // will cause the last vector in the sequence to be (re)loaded. 14393 // Otherwise, the next vector will be fetched as you might suspect was 14394 // necessary. 14395 14396 // We might be able to reuse the permutation generation from 14397 // a different base address offset from this one by an aligned amount. 14398 // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this 14399 // optimization later. 14400 Intrinsic::ID Intr, IntrLD, IntrPerm; 14401 MVT PermCntlTy, PermTy, LDTy; 14402 if (Subtarget.hasAltivec()) { 14403 Intr = isLittleEndian ? Intrinsic::ppc_altivec_lvsr : 14404 Intrinsic::ppc_altivec_lvsl; 14405 IntrLD = Intrinsic::ppc_altivec_lvx; 14406 IntrPerm = Intrinsic::ppc_altivec_vperm; 14407 PermCntlTy = MVT::v16i8; 14408 PermTy = MVT::v4i32; 14409 LDTy = MVT::v4i32; 14410 } else { 14411 Intr = MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlpcld : 14412 Intrinsic::ppc_qpx_qvlpcls; 14413 IntrLD = MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlfd : 14414 Intrinsic::ppc_qpx_qvlfs; 14415 IntrPerm = Intrinsic::ppc_qpx_qvfperm; 14416 PermCntlTy = MVT::v4f64; 14417 PermTy = MVT::v4f64; 14418 LDTy = MemVT.getSimpleVT(); 14419 } 14420 14421 SDValue PermCntl = BuildIntrinsicOp(Intr, Ptr, DAG, dl, PermCntlTy); 14422 14423 // Create the new MMO for the new base load. It is like the original MMO, 14424 // but represents an area in memory almost twice the vector size centered 14425 // on the original address. If the address is unaligned, we might start 14426 // reading up to (sizeof(vector)-1) bytes below the address of the 14427 // original unaligned load. 14428 MachineFunction &MF = DAG.getMachineFunction(); 14429 MachineMemOperand *BaseMMO = 14430 MF.getMachineMemOperand(LD->getMemOperand(), 14431 -(long)MemVT.getStoreSize()+1, 14432 2*MemVT.getStoreSize()-1); 14433 14434 // Create the new base load. 14435 SDValue LDXIntID = 14436 DAG.getTargetConstant(IntrLD, dl, getPointerTy(MF.getDataLayout())); 14437 SDValue BaseLoadOps[] = { Chain, LDXIntID, Ptr }; 14438 SDValue BaseLoad = 14439 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl, 14440 DAG.getVTList(PermTy, MVT::Other), 14441 BaseLoadOps, LDTy, BaseMMO); 14442 14443 // Note that the value of IncOffset (which is provided to the next 14444 // load's pointer info offset value, and thus used to calculate the 14445 // alignment), and the value of IncValue (which is actually used to 14446 // increment the pointer value) are different! This is because we 14447 // require the next load to appear to be aligned, even though it 14448 // is actually offset from the base pointer by a lesser amount. 14449 int IncOffset = VT.getSizeInBits() / 8; 14450 int IncValue = IncOffset; 14451 14452 // Walk (both up and down) the chain looking for another load at the real 14453 // (aligned) offset (the alignment of the other load does not matter in 14454 // this case). If found, then do not use the offset reduction trick, as 14455 // that will prevent the loads from being later combined (as they would 14456 // otherwise be duplicates). 14457 if (!findConsecutiveLoad(LD, DAG)) 14458 --IncValue; 14459 14460 SDValue Increment = 14461 DAG.getConstant(IncValue, dl, getPointerTy(MF.getDataLayout())); 14462 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment); 14463 14464 MachineMemOperand *ExtraMMO = 14465 MF.getMachineMemOperand(LD->getMemOperand(), 14466 1, 2*MemVT.getStoreSize()-1); 14467 SDValue ExtraLoadOps[] = { Chain, LDXIntID, Ptr }; 14468 SDValue ExtraLoad = 14469 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl, 14470 DAG.getVTList(PermTy, MVT::Other), 14471 ExtraLoadOps, LDTy, ExtraMMO); 14472 14473 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 14474 BaseLoad.getValue(1), ExtraLoad.getValue(1)); 14475 14476 // Because vperm has a big-endian bias, we must reverse the order 14477 // of the input vectors and complement the permute control vector 14478 // when generating little endian code. We have already handled the 14479 // latter by using lvsr instead of lvsl, so just reverse BaseLoad 14480 // and ExtraLoad here. 14481 SDValue Perm; 14482 if (isLittleEndian) 14483 Perm = BuildIntrinsicOp(IntrPerm, 14484 ExtraLoad, BaseLoad, PermCntl, DAG, dl); 14485 else 14486 Perm = BuildIntrinsicOp(IntrPerm, 14487 BaseLoad, ExtraLoad, PermCntl, DAG, dl); 14488 14489 if (VT != PermTy) 14490 Perm = Subtarget.hasAltivec() ? 14491 DAG.getNode(ISD::BITCAST, dl, VT, Perm) : 14492 DAG.getNode(ISD::FP_ROUND, dl, VT, Perm, // QPX 14493 DAG.getTargetConstant(1, dl, MVT::i64)); 14494 // second argument is 1 because this rounding 14495 // is always exact. 14496 14497 // The output of the permutation is our loaded result, the TokenFactor is 14498 // our new chain. 14499 DCI.CombineTo(N, Perm, TF); 14500 return SDValue(N, 0); 14501 } 14502 } 14503 break; 14504 case ISD::INTRINSIC_WO_CHAIN: { 14505 bool isLittleEndian = Subtarget.isLittleEndian(); 14506 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 14507 Intrinsic::ID Intr = (isLittleEndian ? Intrinsic::ppc_altivec_lvsr 14508 : Intrinsic::ppc_altivec_lvsl); 14509 if ((IID == Intr || 14510 IID == Intrinsic::ppc_qpx_qvlpcld || 14511 IID == Intrinsic::ppc_qpx_qvlpcls) && 14512 N->getOperand(1)->getOpcode() == ISD::ADD) { 14513 SDValue Add = N->getOperand(1); 14514 14515 int Bits = IID == Intrinsic::ppc_qpx_qvlpcld ? 14516 5 /* 32 byte alignment */ : 4 /* 16 byte alignment */; 14517 14518 if (DAG.MaskedValueIsZero(Add->getOperand(1), 14519 APInt::getAllOnesValue(Bits /* alignment */) 14520 .zext(Add.getScalarValueSizeInBits()))) { 14521 SDNode *BasePtr = Add->getOperand(0).getNode(); 14522 for (SDNode::use_iterator UI = BasePtr->use_begin(), 14523 UE = BasePtr->use_end(); 14524 UI != UE; ++UI) { 14525 if (UI->getOpcode() == ISD::INTRINSIC_WO_CHAIN && 14526 cast<ConstantSDNode>(UI->getOperand(0))->getZExtValue() == IID) { 14527 // We've found another LVSL/LVSR, and this address is an aligned 14528 // multiple of that one. The results will be the same, so use the 14529 // one we've just found instead. 14530 14531 return SDValue(*UI, 0); 14532 } 14533 } 14534 } 14535 14536 if (isa<ConstantSDNode>(Add->getOperand(1))) { 14537 SDNode *BasePtr = Add->getOperand(0).getNode(); 14538 for (SDNode::use_iterator UI = BasePtr->use_begin(), 14539 UE = BasePtr->use_end(); UI != UE; ++UI) { 14540 if (UI->getOpcode() == ISD::ADD && 14541 isa<ConstantSDNode>(UI->getOperand(1)) && 14542 (cast<ConstantSDNode>(Add->getOperand(1))->getZExtValue() - 14543 cast<ConstantSDNode>(UI->getOperand(1))->getZExtValue()) % 14544 (1ULL << Bits) == 0) { 14545 SDNode *OtherAdd = *UI; 14546 for (SDNode::use_iterator VI = OtherAdd->use_begin(), 14547 VE = OtherAdd->use_end(); VI != VE; ++VI) { 14548 if (VI->getOpcode() == ISD::INTRINSIC_WO_CHAIN && 14549 cast<ConstantSDNode>(VI->getOperand(0))->getZExtValue() == IID) { 14550 return SDValue(*VI, 0); 14551 } 14552 } 14553 } 14554 } 14555 } 14556 } 14557 14558 // Combine vmaxsw/h/b(a, a's negation) to abs(a) 14559 // Expose the vabsduw/h/b opportunity for down stream 14560 if (!DCI.isAfterLegalizeDAG() && Subtarget.hasP9Altivec() && 14561 (IID == Intrinsic::ppc_altivec_vmaxsw || 14562 IID == Intrinsic::ppc_altivec_vmaxsh || 14563 IID == Intrinsic::ppc_altivec_vmaxsb)) { 14564 SDValue V1 = N->getOperand(1); 14565 SDValue V2 = N->getOperand(2); 14566 if ((V1.getSimpleValueType() == MVT::v4i32 || 14567 V1.getSimpleValueType() == MVT::v8i16 || 14568 V1.getSimpleValueType() == MVT::v16i8) && 14569 V1.getSimpleValueType() == V2.getSimpleValueType()) { 14570 // (0-a, a) 14571 if (V1.getOpcode() == ISD::SUB && 14572 ISD::isBuildVectorAllZeros(V1.getOperand(0).getNode()) && 14573 V1.getOperand(1) == V2) { 14574 return DAG.getNode(ISD::ABS, dl, V2.getValueType(), V2); 14575 } 14576 // (a, 0-a) 14577 if (V2.getOpcode() == ISD::SUB && 14578 ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()) && 14579 V2.getOperand(1) == V1) { 14580 return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1); 14581 } 14582 // (x-y, y-x) 14583 if (V1.getOpcode() == ISD::SUB && V2.getOpcode() == ISD::SUB && 14584 V1.getOperand(0) == V2.getOperand(1) && 14585 V1.getOperand(1) == V2.getOperand(0)) { 14586 return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1); 14587 } 14588 } 14589 } 14590 } 14591 14592 break; 14593 case ISD::INTRINSIC_W_CHAIN: 14594 // For little endian, VSX loads require generating lxvd2x/xxswapd. 14595 // Not needed on ISA 3.0 based CPUs since we have a non-permuting load. 14596 if (Subtarget.needsSwapsForVSXMemOps()) { 14597 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 14598 default: 14599 break; 14600 case Intrinsic::ppc_vsx_lxvw4x: 14601 case Intrinsic::ppc_vsx_lxvd2x: 14602 return expandVSXLoadForLE(N, DCI); 14603 } 14604 } 14605 break; 14606 case ISD::INTRINSIC_VOID: 14607 // For little endian, VSX stores require generating xxswapd/stxvd2x. 14608 // Not needed on ISA 3.0 based CPUs since we have a non-permuting store. 14609 if (Subtarget.needsSwapsForVSXMemOps()) { 14610 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 14611 default: 14612 break; 14613 case Intrinsic::ppc_vsx_stxvw4x: 14614 case Intrinsic::ppc_vsx_stxvd2x: 14615 return expandVSXStoreForLE(N, DCI); 14616 } 14617 } 14618 break; 14619 case ISD::BSWAP: 14620 // Turn BSWAP (LOAD) -> lhbrx/lwbrx. 14621 if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) && 14622 N->getOperand(0).hasOneUse() && 14623 (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 || 14624 (Subtarget.hasLDBRX() && Subtarget.isPPC64() && 14625 N->getValueType(0) == MVT::i64))) { 14626 SDValue Load = N->getOperand(0); 14627 LoadSDNode *LD = cast<LoadSDNode>(Load); 14628 // Create the byte-swapping load. 14629 SDValue Ops[] = { 14630 LD->getChain(), // Chain 14631 LD->getBasePtr(), // Ptr 14632 DAG.getValueType(N->getValueType(0)) // VT 14633 }; 14634 SDValue BSLoad = 14635 DAG.getMemIntrinsicNode(PPCISD::LBRX, dl, 14636 DAG.getVTList(N->getValueType(0) == MVT::i64 ? 14637 MVT::i64 : MVT::i32, MVT::Other), 14638 Ops, LD->getMemoryVT(), LD->getMemOperand()); 14639 14640 // If this is an i16 load, insert the truncate. 14641 SDValue ResVal = BSLoad; 14642 if (N->getValueType(0) == MVT::i16) 14643 ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad); 14644 14645 // First, combine the bswap away. This makes the value produced by the 14646 // load dead. 14647 DCI.CombineTo(N, ResVal); 14648 14649 // Next, combine the load away, we give it a bogus result value but a real 14650 // chain result. The result value is dead because the bswap is dead. 14651 DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1)); 14652 14653 // Return N so it doesn't get rechecked! 14654 return SDValue(N, 0); 14655 } 14656 break; 14657 case PPCISD::VCMP: 14658 // If a VCMPo node already exists with exactly the same operands as this 14659 // node, use its result instead of this node (VCMPo computes both a CR6 and 14660 // a normal output). 14661 // 14662 if (!N->getOperand(0).hasOneUse() && 14663 !N->getOperand(1).hasOneUse() && 14664 !N->getOperand(2).hasOneUse()) { 14665 14666 // Scan all of the users of the LHS, looking for VCMPo's that match. 14667 SDNode *VCMPoNode = nullptr; 14668 14669 SDNode *LHSN = N->getOperand(0).getNode(); 14670 for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end(); 14671 UI != E; ++UI) 14672 if (UI->getOpcode() == PPCISD::VCMPo && 14673 UI->getOperand(1) == N->getOperand(1) && 14674 UI->getOperand(2) == N->getOperand(2) && 14675 UI->getOperand(0) == N->getOperand(0)) { 14676 VCMPoNode = *UI; 14677 break; 14678 } 14679 14680 // If there is no VCMPo node, or if the flag value has a single use, don't 14681 // transform this. 14682 if (!VCMPoNode || VCMPoNode->hasNUsesOfValue(0, 1)) 14683 break; 14684 14685 // Look at the (necessarily single) use of the flag value. If it has a 14686 // chain, this transformation is more complex. Note that multiple things 14687 // could use the value result, which we should ignore. 14688 SDNode *FlagUser = nullptr; 14689 for (SDNode::use_iterator UI = VCMPoNode->use_begin(); 14690 FlagUser == nullptr; ++UI) { 14691 assert(UI != VCMPoNode->use_end() && "Didn't find user!"); 14692 SDNode *User = *UI; 14693 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) { 14694 if (User->getOperand(i) == SDValue(VCMPoNode, 1)) { 14695 FlagUser = User; 14696 break; 14697 } 14698 } 14699 } 14700 14701 // If the user is a MFOCRF instruction, we know this is safe. 14702 // Otherwise we give up for right now. 14703 if (FlagUser->getOpcode() == PPCISD::MFOCRF) 14704 return SDValue(VCMPoNode, 0); 14705 } 14706 break; 14707 case ISD::BRCOND: { 14708 SDValue Cond = N->getOperand(1); 14709 SDValue Target = N->getOperand(2); 14710 14711 if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN && 14712 cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() == 14713 Intrinsic::loop_decrement) { 14714 14715 // We now need to make the intrinsic dead (it cannot be instruction 14716 // selected). 14717 DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0)); 14718 assert(Cond.getNode()->hasOneUse() && 14719 "Counter decrement has more than one use"); 14720 14721 return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other, 14722 N->getOperand(0), Target); 14723 } 14724 } 14725 break; 14726 case ISD::BR_CC: { 14727 // If this is a branch on an altivec predicate comparison, lower this so 14728 // that we don't have to do a MFOCRF: instead, branch directly on CR6. This 14729 // lowering is done pre-legalize, because the legalizer lowers the predicate 14730 // compare down to code that is difficult to reassemble. 14731 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get(); 14732 SDValue LHS = N->getOperand(2), RHS = N->getOperand(3); 14733 14734 // Sometimes the promoted value of the intrinsic is ANDed by some non-zero 14735 // value. If so, pass-through the AND to get to the intrinsic. 14736 if (LHS.getOpcode() == ISD::AND && 14737 LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN && 14738 cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() == 14739 Intrinsic::loop_decrement && 14740 isa<ConstantSDNode>(LHS.getOperand(1)) && 14741 !isNullConstant(LHS.getOperand(1))) 14742 LHS = LHS.getOperand(0); 14743 14744 if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN && 14745 cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() == 14746 Intrinsic::loop_decrement && 14747 isa<ConstantSDNode>(RHS)) { 14748 assert((CC == ISD::SETEQ || CC == ISD::SETNE) && 14749 "Counter decrement comparison is not EQ or NE"); 14750 14751 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue(); 14752 bool isBDNZ = (CC == ISD::SETEQ && Val) || 14753 (CC == ISD::SETNE && !Val); 14754 14755 // We now need to make the intrinsic dead (it cannot be instruction 14756 // selected). 14757 DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0)); 14758 assert(LHS.getNode()->hasOneUse() && 14759 "Counter decrement has more than one use"); 14760 14761 return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other, 14762 N->getOperand(0), N->getOperand(4)); 14763 } 14764 14765 int CompareOpc; 14766 bool isDot; 14767 14768 if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN && 14769 isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) && 14770 getVectorCompareInfo(LHS, CompareOpc, isDot, Subtarget)) { 14771 assert(isDot && "Can't compare against a vector result!"); 14772 14773 // If this is a comparison against something other than 0/1, then we know 14774 // that the condition is never/always true. 14775 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue(); 14776 if (Val != 0 && Val != 1) { 14777 if (CC == ISD::SETEQ) // Cond never true, remove branch. 14778 return N->getOperand(0); 14779 // Always !=, turn it into an unconditional branch. 14780 return DAG.getNode(ISD::BR, dl, MVT::Other, 14781 N->getOperand(0), N->getOperand(4)); 14782 } 14783 14784 bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0); 14785 14786 // Create the PPCISD altivec 'dot' comparison node. 14787 SDValue Ops[] = { 14788 LHS.getOperand(2), // LHS of compare 14789 LHS.getOperand(3), // RHS of compare 14790 DAG.getConstant(CompareOpc, dl, MVT::i32) 14791 }; 14792 EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue }; 14793 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops); 14794 14795 // Unpack the result based on how the target uses it. 14796 PPC::Predicate CompOpc; 14797 switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) { 14798 default: // Can't happen, don't crash on invalid number though. 14799 case 0: // Branch on the value of the EQ bit of CR6. 14800 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE; 14801 break; 14802 case 1: // Branch on the inverted value of the EQ bit of CR6. 14803 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ; 14804 break; 14805 case 2: // Branch on the value of the LT bit of CR6. 14806 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE; 14807 break; 14808 case 3: // Branch on the inverted value of the LT bit of CR6. 14809 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT; 14810 break; 14811 } 14812 14813 return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0), 14814 DAG.getConstant(CompOpc, dl, MVT::i32), 14815 DAG.getRegister(PPC::CR6, MVT::i32), 14816 N->getOperand(4), CompNode.getValue(1)); 14817 } 14818 break; 14819 } 14820 case ISD::BUILD_VECTOR: 14821 return DAGCombineBuildVector(N, DCI); 14822 case ISD::ABS: 14823 return combineABS(N, DCI); 14824 case ISD::VSELECT: 14825 return combineVSelect(N, DCI); 14826 } 14827 14828 return SDValue(); 14829 } 14830 14831 SDValue 14832 PPCTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor, 14833 SelectionDAG &DAG, 14834 SmallVectorImpl<SDNode *> &Created) const { 14835 // fold (sdiv X, pow2) 14836 EVT VT = N->getValueType(0); 14837 if (VT == MVT::i64 && !Subtarget.isPPC64()) 14838 return SDValue(); 14839 if ((VT != MVT::i32 && VT != MVT::i64) || 14840 !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2())) 14841 return SDValue(); 14842 14843 SDLoc DL(N); 14844 SDValue N0 = N->getOperand(0); 14845 14846 bool IsNegPow2 = (-Divisor).isPowerOf2(); 14847 unsigned Lg2 = (IsNegPow2 ? -Divisor : Divisor).countTrailingZeros(); 14848 SDValue ShiftAmt = DAG.getConstant(Lg2, DL, VT); 14849 14850 SDValue Op = DAG.getNode(PPCISD::SRA_ADDZE, DL, VT, N0, ShiftAmt); 14851 Created.push_back(Op.getNode()); 14852 14853 if (IsNegPow2) { 14854 Op = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Op); 14855 Created.push_back(Op.getNode()); 14856 } 14857 14858 return Op; 14859 } 14860 14861 //===----------------------------------------------------------------------===// 14862 // Inline Assembly Support 14863 //===----------------------------------------------------------------------===// 14864 14865 void PPCTargetLowering::computeKnownBitsForTargetNode(const SDValue Op, 14866 KnownBits &Known, 14867 const APInt &DemandedElts, 14868 const SelectionDAG &DAG, 14869 unsigned Depth) const { 14870 Known.resetAll(); 14871 switch (Op.getOpcode()) { 14872 default: break; 14873 case PPCISD::LBRX: { 14874 // lhbrx is known to have the top bits cleared out. 14875 if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16) 14876 Known.Zero = 0xFFFF0000; 14877 break; 14878 } 14879 case ISD::INTRINSIC_WO_CHAIN: { 14880 switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) { 14881 default: break; 14882 case Intrinsic::ppc_altivec_vcmpbfp_p: 14883 case Intrinsic::ppc_altivec_vcmpeqfp_p: 14884 case Intrinsic::ppc_altivec_vcmpequb_p: 14885 case Intrinsic::ppc_altivec_vcmpequh_p: 14886 case Intrinsic::ppc_altivec_vcmpequw_p: 14887 case Intrinsic::ppc_altivec_vcmpequd_p: 14888 case Intrinsic::ppc_altivec_vcmpgefp_p: 14889 case Intrinsic::ppc_altivec_vcmpgtfp_p: 14890 case Intrinsic::ppc_altivec_vcmpgtsb_p: 14891 case Intrinsic::ppc_altivec_vcmpgtsh_p: 14892 case Intrinsic::ppc_altivec_vcmpgtsw_p: 14893 case Intrinsic::ppc_altivec_vcmpgtsd_p: 14894 case Intrinsic::ppc_altivec_vcmpgtub_p: 14895 case Intrinsic::ppc_altivec_vcmpgtuh_p: 14896 case Intrinsic::ppc_altivec_vcmpgtuw_p: 14897 case Intrinsic::ppc_altivec_vcmpgtud_p: 14898 Known.Zero = ~1U; // All bits but the low one are known to be zero. 14899 break; 14900 } 14901 } 14902 } 14903 } 14904 14905 Align PPCTargetLowering::getPrefLoopAlignment(MachineLoop *ML) const { 14906 switch (Subtarget.getCPUDirective()) { 14907 default: break; 14908 case PPC::DIR_970: 14909 case PPC::DIR_PWR4: 14910 case PPC::DIR_PWR5: 14911 case PPC::DIR_PWR5X: 14912 case PPC::DIR_PWR6: 14913 case PPC::DIR_PWR6X: 14914 case PPC::DIR_PWR7: 14915 case PPC::DIR_PWR8: 14916 case PPC::DIR_PWR9: 14917 case PPC::DIR_PWR10: 14918 case PPC::DIR_PWR_FUTURE: { 14919 if (!ML) 14920 break; 14921 14922 if (!DisableInnermostLoopAlign32) { 14923 // If the nested loop is an innermost loop, prefer to a 32-byte alignment, 14924 // so that we can decrease cache misses and branch-prediction misses. 14925 // Actual alignment of the loop will depend on the hotness check and other 14926 // logic in alignBlocks. 14927 if (ML->getLoopDepth() > 1 && ML->getSubLoops().empty()) 14928 return Align(32); 14929 } 14930 14931 const PPCInstrInfo *TII = Subtarget.getInstrInfo(); 14932 14933 // For small loops (between 5 and 8 instructions), align to a 32-byte 14934 // boundary so that the entire loop fits in one instruction-cache line. 14935 uint64_t LoopSize = 0; 14936 for (auto I = ML->block_begin(), IE = ML->block_end(); I != IE; ++I) 14937 for (auto J = (*I)->begin(), JE = (*I)->end(); J != JE; ++J) { 14938 LoopSize += TII->getInstSizeInBytes(*J); 14939 if (LoopSize > 32) 14940 break; 14941 } 14942 14943 if (LoopSize > 16 && LoopSize <= 32) 14944 return Align(32); 14945 14946 break; 14947 } 14948 } 14949 14950 return TargetLowering::getPrefLoopAlignment(ML); 14951 } 14952 14953 /// getConstraintType - Given a constraint, return the type of 14954 /// constraint it is for this target. 14955 PPCTargetLowering::ConstraintType 14956 PPCTargetLowering::getConstraintType(StringRef Constraint) const { 14957 if (Constraint.size() == 1) { 14958 switch (Constraint[0]) { 14959 default: break; 14960 case 'b': 14961 case 'r': 14962 case 'f': 14963 case 'd': 14964 case 'v': 14965 case 'y': 14966 return C_RegisterClass; 14967 case 'Z': 14968 // FIXME: While Z does indicate a memory constraint, it specifically 14969 // indicates an r+r address (used in conjunction with the 'y' modifier 14970 // in the replacement string). Currently, we're forcing the base 14971 // register to be r0 in the asm printer (which is interpreted as zero) 14972 // and forming the complete address in the second register. This is 14973 // suboptimal. 14974 return C_Memory; 14975 } 14976 } else if (Constraint == "wc") { // individual CR bits. 14977 return C_RegisterClass; 14978 } else if (Constraint == "wa" || Constraint == "wd" || 14979 Constraint == "wf" || Constraint == "ws" || 14980 Constraint == "wi" || Constraint == "ww") { 14981 return C_RegisterClass; // VSX registers. 14982 } 14983 return TargetLowering::getConstraintType(Constraint); 14984 } 14985 14986 /// Examine constraint type and operand type and determine a weight value. 14987 /// This object must already have been set up with the operand type 14988 /// and the current alternative constraint selected. 14989 TargetLowering::ConstraintWeight 14990 PPCTargetLowering::getSingleConstraintMatchWeight( 14991 AsmOperandInfo &info, const char *constraint) const { 14992 ConstraintWeight weight = CW_Invalid; 14993 Value *CallOperandVal = info.CallOperandVal; 14994 // If we don't have a value, we can't do a match, 14995 // but allow it at the lowest weight. 14996 if (!CallOperandVal) 14997 return CW_Default; 14998 Type *type = CallOperandVal->getType(); 14999 15000 // Look at the constraint type. 15001 if (StringRef(constraint) == "wc" && type->isIntegerTy(1)) 15002 return CW_Register; // an individual CR bit. 15003 else if ((StringRef(constraint) == "wa" || 15004 StringRef(constraint) == "wd" || 15005 StringRef(constraint) == "wf") && 15006 type->isVectorTy()) 15007 return CW_Register; 15008 else if (StringRef(constraint) == "wi" && type->isIntegerTy(64)) 15009 return CW_Register; // just hold 64-bit integers data. 15010 else if (StringRef(constraint) == "ws" && type->isDoubleTy()) 15011 return CW_Register; 15012 else if (StringRef(constraint) == "ww" && type->isFloatTy()) 15013 return CW_Register; 15014 15015 switch (*constraint) { 15016 default: 15017 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint); 15018 break; 15019 case 'b': 15020 if (type->isIntegerTy()) 15021 weight = CW_Register; 15022 break; 15023 case 'f': 15024 if (type->isFloatTy()) 15025 weight = CW_Register; 15026 break; 15027 case 'd': 15028 if (type->isDoubleTy()) 15029 weight = CW_Register; 15030 break; 15031 case 'v': 15032 if (type->isVectorTy()) 15033 weight = CW_Register; 15034 break; 15035 case 'y': 15036 weight = CW_Register; 15037 break; 15038 case 'Z': 15039 weight = CW_Memory; 15040 break; 15041 } 15042 return weight; 15043 } 15044 15045 std::pair<unsigned, const TargetRegisterClass *> 15046 PPCTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, 15047 StringRef Constraint, 15048 MVT VT) const { 15049 if (Constraint.size() == 1) { 15050 // GCC RS6000 Constraint Letters 15051 switch (Constraint[0]) { 15052 case 'b': // R1-R31 15053 if (VT == MVT::i64 && Subtarget.isPPC64()) 15054 return std::make_pair(0U, &PPC::G8RC_NOX0RegClass); 15055 return std::make_pair(0U, &PPC::GPRC_NOR0RegClass); 15056 case 'r': // R0-R31 15057 if (VT == MVT::i64 && Subtarget.isPPC64()) 15058 return std::make_pair(0U, &PPC::G8RCRegClass); 15059 return std::make_pair(0U, &PPC::GPRCRegClass); 15060 // 'd' and 'f' constraints are both defined to be "the floating point 15061 // registers", where one is for 32-bit and the other for 64-bit. We don't 15062 // really care overly much here so just give them all the same reg classes. 15063 case 'd': 15064 case 'f': 15065 if (Subtarget.hasSPE()) { 15066 if (VT == MVT::f32 || VT == MVT::i32) 15067 return std::make_pair(0U, &PPC::GPRCRegClass); 15068 if (VT == MVT::f64 || VT == MVT::i64) 15069 return std::make_pair(0U, &PPC::SPERCRegClass); 15070 } else { 15071 if (VT == MVT::f32 || VT == MVT::i32) 15072 return std::make_pair(0U, &PPC::F4RCRegClass); 15073 if (VT == MVT::f64 || VT == MVT::i64) 15074 return std::make_pair(0U, &PPC::F8RCRegClass); 15075 if (VT == MVT::v4f64 && Subtarget.hasQPX()) 15076 return std::make_pair(0U, &PPC::QFRCRegClass); 15077 if (VT == MVT::v4f32 && Subtarget.hasQPX()) 15078 return std::make_pair(0U, &PPC::QSRCRegClass); 15079 } 15080 break; 15081 case 'v': 15082 if (VT == MVT::v4f64 && Subtarget.hasQPX()) 15083 return std::make_pair(0U, &PPC::QFRCRegClass); 15084 if (VT == MVT::v4f32 && Subtarget.hasQPX()) 15085 return std::make_pair(0U, &PPC::QSRCRegClass); 15086 if (Subtarget.hasAltivec()) 15087 return std::make_pair(0U, &PPC::VRRCRegClass); 15088 break; 15089 case 'y': // crrc 15090 return std::make_pair(0U, &PPC::CRRCRegClass); 15091 } 15092 } else if (Constraint == "wc" && Subtarget.useCRBits()) { 15093 // An individual CR bit. 15094 return std::make_pair(0U, &PPC::CRBITRCRegClass); 15095 } else if ((Constraint == "wa" || Constraint == "wd" || 15096 Constraint == "wf" || Constraint == "wi") && 15097 Subtarget.hasVSX()) { 15098 return std::make_pair(0U, &PPC::VSRCRegClass); 15099 } else if ((Constraint == "ws" || Constraint == "ww") && Subtarget.hasVSX()) { 15100 if (VT == MVT::f32 && Subtarget.hasP8Vector()) 15101 return std::make_pair(0U, &PPC::VSSRCRegClass); 15102 else 15103 return std::make_pair(0U, &PPC::VSFRCRegClass); 15104 } 15105 15106 // If we name a VSX register, we can't defer to the base class because it 15107 // will not recognize the correct register (their names will be VSL{0-31} 15108 // and V{0-31} so they won't match). So we match them here. 15109 if (Constraint.size() > 3 && Constraint[1] == 'v' && Constraint[2] == 's') { 15110 int VSNum = atoi(Constraint.data() + 3); 15111 assert(VSNum >= 0 && VSNum <= 63 && 15112 "Attempted to access a vsr out of range"); 15113 if (VSNum < 32) 15114 return std::make_pair(PPC::VSL0 + VSNum, &PPC::VSRCRegClass); 15115 return std::make_pair(PPC::V0 + VSNum - 32, &PPC::VSRCRegClass); 15116 } 15117 std::pair<unsigned, const TargetRegisterClass *> R = 15118 TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 15119 15120 // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers 15121 // (which we call X[0-9]+). If a 64-bit value has been requested, and a 15122 // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent 15123 // register. 15124 // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use 15125 // the AsmName field from *RegisterInfo.td, then this would not be necessary. 15126 if (R.first && VT == MVT::i64 && Subtarget.isPPC64() && 15127 PPC::GPRCRegClass.contains(R.first)) 15128 return std::make_pair(TRI->getMatchingSuperReg(R.first, 15129 PPC::sub_32, &PPC::G8RCRegClass), 15130 &PPC::G8RCRegClass); 15131 15132 // GCC accepts 'cc' as an alias for 'cr0', and we need to do the same. 15133 if (!R.second && StringRef("{cc}").equals_lower(Constraint)) { 15134 R.first = PPC::CR0; 15135 R.second = &PPC::CRRCRegClass; 15136 } 15137 15138 return R; 15139 } 15140 15141 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops 15142 /// vector. If it is invalid, don't add anything to Ops. 15143 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op, 15144 std::string &Constraint, 15145 std::vector<SDValue>&Ops, 15146 SelectionDAG &DAG) const { 15147 SDValue Result; 15148 15149 // Only support length 1 constraints. 15150 if (Constraint.length() > 1) return; 15151 15152 char Letter = Constraint[0]; 15153 switch (Letter) { 15154 default: break; 15155 case 'I': 15156 case 'J': 15157 case 'K': 15158 case 'L': 15159 case 'M': 15160 case 'N': 15161 case 'O': 15162 case 'P': { 15163 ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op); 15164 if (!CST) return; // Must be an immediate to match. 15165 SDLoc dl(Op); 15166 int64_t Value = CST->getSExtValue(); 15167 EVT TCVT = MVT::i64; // All constants taken to be 64 bits so that negative 15168 // numbers are printed as such. 15169 switch (Letter) { 15170 default: llvm_unreachable("Unknown constraint letter!"); 15171 case 'I': // "I" is a signed 16-bit constant. 15172 if (isInt<16>(Value)) 15173 Result = DAG.getTargetConstant(Value, dl, TCVT); 15174 break; 15175 case 'J': // "J" is a constant with only the high-order 16 bits nonzero. 15176 if (isShiftedUInt<16, 16>(Value)) 15177 Result = DAG.getTargetConstant(Value, dl, TCVT); 15178 break; 15179 case 'L': // "L" is a signed 16-bit constant shifted left 16 bits. 15180 if (isShiftedInt<16, 16>(Value)) 15181 Result = DAG.getTargetConstant(Value, dl, TCVT); 15182 break; 15183 case 'K': // "K" is a constant with only the low-order 16 bits nonzero. 15184 if (isUInt<16>(Value)) 15185 Result = DAG.getTargetConstant(Value, dl, TCVT); 15186 break; 15187 case 'M': // "M" is a constant that is greater than 31. 15188 if (Value > 31) 15189 Result = DAG.getTargetConstant(Value, dl, TCVT); 15190 break; 15191 case 'N': // "N" is a positive constant that is an exact power of two. 15192 if (Value > 0 && isPowerOf2_64(Value)) 15193 Result = DAG.getTargetConstant(Value, dl, TCVT); 15194 break; 15195 case 'O': // "O" is the constant zero. 15196 if (Value == 0) 15197 Result = DAG.getTargetConstant(Value, dl, TCVT); 15198 break; 15199 case 'P': // "P" is a constant whose negation is a signed 16-bit constant. 15200 if (isInt<16>(-Value)) 15201 Result = DAG.getTargetConstant(Value, dl, TCVT); 15202 break; 15203 } 15204 break; 15205 } 15206 } 15207 15208 if (Result.getNode()) { 15209 Ops.push_back(Result); 15210 return; 15211 } 15212 15213 // Handle standard constraint letters. 15214 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 15215 } 15216 15217 // isLegalAddressingMode - Return true if the addressing mode represented 15218 // by AM is legal for this target, for a load/store of the specified type. 15219 bool PPCTargetLowering::isLegalAddressingMode(const DataLayout &DL, 15220 const AddrMode &AM, Type *Ty, 15221 unsigned AS, Instruction *I) const { 15222 // PPC does not allow r+i addressing modes for vectors! 15223 if (Ty->isVectorTy() && AM.BaseOffs != 0) 15224 return false; 15225 15226 // PPC allows a sign-extended 16-bit immediate field. 15227 if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1) 15228 return false; 15229 15230 // No global is ever allowed as a base. 15231 if (AM.BaseGV) 15232 return false; 15233 15234 // PPC only support r+r, 15235 switch (AM.Scale) { 15236 case 0: // "r+i" or just "i", depending on HasBaseReg. 15237 break; 15238 case 1: 15239 if (AM.HasBaseReg && AM.BaseOffs) // "r+r+i" is not allowed. 15240 return false; 15241 // Otherwise we have r+r or r+i. 15242 break; 15243 case 2: 15244 if (AM.HasBaseReg || AM.BaseOffs) // 2*r+r or 2*r+i is not allowed. 15245 return false; 15246 // Allow 2*r as r+r. 15247 break; 15248 default: 15249 // No other scales are supported. 15250 return false; 15251 } 15252 15253 return true; 15254 } 15255 15256 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op, 15257 SelectionDAG &DAG) const { 15258 MachineFunction &MF = DAG.getMachineFunction(); 15259 MachineFrameInfo &MFI = MF.getFrameInfo(); 15260 MFI.setReturnAddressIsTaken(true); 15261 15262 if (verifyReturnAddressArgumentIsConstant(Op, DAG)) 15263 return SDValue(); 15264 15265 SDLoc dl(Op); 15266 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 15267 15268 // Make sure the function does not optimize away the store of the RA to 15269 // the stack. 15270 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 15271 FuncInfo->setLRStoreRequired(); 15272 bool isPPC64 = Subtarget.isPPC64(); 15273 auto PtrVT = getPointerTy(MF.getDataLayout()); 15274 15275 if (Depth > 0) { 15276 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG); 15277 SDValue Offset = 15278 DAG.getConstant(Subtarget.getFrameLowering()->getReturnSaveOffset(), dl, 15279 isPPC64 ? MVT::i64 : MVT::i32); 15280 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), 15281 DAG.getNode(ISD::ADD, dl, PtrVT, FrameAddr, Offset), 15282 MachinePointerInfo()); 15283 } 15284 15285 // Just load the return address off the stack. 15286 SDValue RetAddrFI = getReturnAddrFrameIndex(DAG); 15287 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), RetAddrFI, 15288 MachinePointerInfo()); 15289 } 15290 15291 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op, 15292 SelectionDAG &DAG) const { 15293 SDLoc dl(Op); 15294 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 15295 15296 MachineFunction &MF = DAG.getMachineFunction(); 15297 MachineFrameInfo &MFI = MF.getFrameInfo(); 15298 MFI.setFrameAddressIsTaken(true); 15299 15300 EVT PtrVT = getPointerTy(MF.getDataLayout()); 15301 bool isPPC64 = PtrVT == MVT::i64; 15302 15303 // Naked functions never have a frame pointer, and so we use r1. For all 15304 // other functions, this decision must be delayed until during PEI. 15305 unsigned FrameReg; 15306 if (MF.getFunction().hasFnAttribute(Attribute::Naked)) 15307 FrameReg = isPPC64 ? PPC::X1 : PPC::R1; 15308 else 15309 FrameReg = isPPC64 ? PPC::FP8 : PPC::FP; 15310 15311 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, 15312 PtrVT); 15313 while (Depth--) 15314 FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(), 15315 FrameAddr, MachinePointerInfo()); 15316 return FrameAddr; 15317 } 15318 15319 // FIXME? Maybe this could be a TableGen attribute on some registers and 15320 // this table could be generated automatically from RegInfo. 15321 Register PPCTargetLowering::getRegisterByName(const char* RegName, LLT VT, 15322 const MachineFunction &MF) const { 15323 bool isPPC64 = Subtarget.isPPC64(); 15324 15325 bool is64Bit = isPPC64 && VT == LLT::scalar(64); 15326 if (!is64Bit && VT != LLT::scalar(32)) 15327 report_fatal_error("Invalid register global variable type"); 15328 15329 Register Reg = StringSwitch<Register>(RegName) 15330 .Case("r1", is64Bit ? PPC::X1 : PPC::R1) 15331 .Case("r2", isPPC64 ? Register() : PPC::R2) 15332 .Case("r13", (is64Bit ? PPC::X13 : PPC::R13)) 15333 .Default(Register()); 15334 15335 if (Reg) 15336 return Reg; 15337 report_fatal_error("Invalid register name global variable"); 15338 } 15339 15340 bool PPCTargetLowering::isAccessedAsGotIndirect(SDValue GA) const { 15341 // 32-bit SVR4 ABI access everything as got-indirect. 15342 if (Subtarget.is32BitELFABI()) 15343 return true; 15344 15345 // AIX accesses everything indirectly through the TOC, which is similar to 15346 // the GOT. 15347 if (Subtarget.isAIXABI()) 15348 return true; 15349 15350 CodeModel::Model CModel = getTargetMachine().getCodeModel(); 15351 // If it is small or large code model, module locals are accessed 15352 // indirectly by loading their address from .toc/.got. 15353 if (CModel == CodeModel::Small || CModel == CodeModel::Large) 15354 return true; 15355 15356 // JumpTable and BlockAddress are accessed as got-indirect. 15357 if (isa<JumpTableSDNode>(GA) || isa<BlockAddressSDNode>(GA)) 15358 return true; 15359 15360 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(GA)) 15361 return Subtarget.isGVIndirectSymbol(G->getGlobal()); 15362 15363 return false; 15364 } 15365 15366 bool 15367 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 15368 // The PowerPC target isn't yet aware of offsets. 15369 return false; 15370 } 15371 15372 bool PPCTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 15373 const CallInst &I, 15374 MachineFunction &MF, 15375 unsigned Intrinsic) const { 15376 switch (Intrinsic) { 15377 case Intrinsic::ppc_qpx_qvlfd: 15378 case Intrinsic::ppc_qpx_qvlfs: 15379 case Intrinsic::ppc_qpx_qvlfcd: 15380 case Intrinsic::ppc_qpx_qvlfcs: 15381 case Intrinsic::ppc_qpx_qvlfiwa: 15382 case Intrinsic::ppc_qpx_qvlfiwz: 15383 case Intrinsic::ppc_altivec_lvx: 15384 case Intrinsic::ppc_altivec_lvxl: 15385 case Intrinsic::ppc_altivec_lvebx: 15386 case Intrinsic::ppc_altivec_lvehx: 15387 case Intrinsic::ppc_altivec_lvewx: 15388 case Intrinsic::ppc_vsx_lxvd2x: 15389 case Intrinsic::ppc_vsx_lxvw4x: { 15390 EVT VT; 15391 switch (Intrinsic) { 15392 case Intrinsic::ppc_altivec_lvebx: 15393 VT = MVT::i8; 15394 break; 15395 case Intrinsic::ppc_altivec_lvehx: 15396 VT = MVT::i16; 15397 break; 15398 case Intrinsic::ppc_altivec_lvewx: 15399 VT = MVT::i32; 15400 break; 15401 case Intrinsic::ppc_vsx_lxvd2x: 15402 VT = MVT::v2f64; 15403 break; 15404 case Intrinsic::ppc_qpx_qvlfd: 15405 VT = MVT::v4f64; 15406 break; 15407 case Intrinsic::ppc_qpx_qvlfs: 15408 VT = MVT::v4f32; 15409 break; 15410 case Intrinsic::ppc_qpx_qvlfcd: 15411 VT = MVT::v2f64; 15412 break; 15413 case Intrinsic::ppc_qpx_qvlfcs: 15414 VT = MVT::v2f32; 15415 break; 15416 default: 15417 VT = MVT::v4i32; 15418 break; 15419 } 15420 15421 Info.opc = ISD::INTRINSIC_W_CHAIN; 15422 Info.memVT = VT; 15423 Info.ptrVal = I.getArgOperand(0); 15424 Info.offset = -VT.getStoreSize()+1; 15425 Info.size = 2*VT.getStoreSize()-1; 15426 Info.align = Align(1); 15427 Info.flags = MachineMemOperand::MOLoad; 15428 return true; 15429 } 15430 case Intrinsic::ppc_qpx_qvlfda: 15431 case Intrinsic::ppc_qpx_qvlfsa: 15432 case Intrinsic::ppc_qpx_qvlfcda: 15433 case Intrinsic::ppc_qpx_qvlfcsa: 15434 case Intrinsic::ppc_qpx_qvlfiwaa: 15435 case Intrinsic::ppc_qpx_qvlfiwza: { 15436 EVT VT; 15437 switch (Intrinsic) { 15438 case Intrinsic::ppc_qpx_qvlfda: 15439 VT = MVT::v4f64; 15440 break; 15441 case Intrinsic::ppc_qpx_qvlfsa: 15442 VT = MVT::v4f32; 15443 break; 15444 case Intrinsic::ppc_qpx_qvlfcda: 15445 VT = MVT::v2f64; 15446 break; 15447 case Intrinsic::ppc_qpx_qvlfcsa: 15448 VT = MVT::v2f32; 15449 break; 15450 default: 15451 VT = MVT::v4i32; 15452 break; 15453 } 15454 15455 Info.opc = ISD::INTRINSIC_W_CHAIN; 15456 Info.memVT = VT; 15457 Info.ptrVal = I.getArgOperand(0); 15458 Info.offset = 0; 15459 Info.size = VT.getStoreSize(); 15460 Info.align = Align(1); 15461 Info.flags = MachineMemOperand::MOLoad; 15462 return true; 15463 } 15464 case Intrinsic::ppc_qpx_qvstfd: 15465 case Intrinsic::ppc_qpx_qvstfs: 15466 case Intrinsic::ppc_qpx_qvstfcd: 15467 case Intrinsic::ppc_qpx_qvstfcs: 15468 case Intrinsic::ppc_qpx_qvstfiw: 15469 case Intrinsic::ppc_altivec_stvx: 15470 case Intrinsic::ppc_altivec_stvxl: 15471 case Intrinsic::ppc_altivec_stvebx: 15472 case Intrinsic::ppc_altivec_stvehx: 15473 case Intrinsic::ppc_altivec_stvewx: 15474 case Intrinsic::ppc_vsx_stxvd2x: 15475 case Intrinsic::ppc_vsx_stxvw4x: { 15476 EVT VT; 15477 switch (Intrinsic) { 15478 case Intrinsic::ppc_altivec_stvebx: 15479 VT = MVT::i8; 15480 break; 15481 case Intrinsic::ppc_altivec_stvehx: 15482 VT = MVT::i16; 15483 break; 15484 case Intrinsic::ppc_altivec_stvewx: 15485 VT = MVT::i32; 15486 break; 15487 case Intrinsic::ppc_vsx_stxvd2x: 15488 VT = MVT::v2f64; 15489 break; 15490 case Intrinsic::ppc_qpx_qvstfd: 15491 VT = MVT::v4f64; 15492 break; 15493 case Intrinsic::ppc_qpx_qvstfs: 15494 VT = MVT::v4f32; 15495 break; 15496 case Intrinsic::ppc_qpx_qvstfcd: 15497 VT = MVT::v2f64; 15498 break; 15499 case Intrinsic::ppc_qpx_qvstfcs: 15500 VT = MVT::v2f32; 15501 break; 15502 default: 15503 VT = MVT::v4i32; 15504 break; 15505 } 15506 15507 Info.opc = ISD::INTRINSIC_VOID; 15508 Info.memVT = VT; 15509 Info.ptrVal = I.getArgOperand(1); 15510 Info.offset = -VT.getStoreSize()+1; 15511 Info.size = 2*VT.getStoreSize()-1; 15512 Info.align = Align(1); 15513 Info.flags = MachineMemOperand::MOStore; 15514 return true; 15515 } 15516 case Intrinsic::ppc_qpx_qvstfda: 15517 case Intrinsic::ppc_qpx_qvstfsa: 15518 case Intrinsic::ppc_qpx_qvstfcda: 15519 case Intrinsic::ppc_qpx_qvstfcsa: 15520 case Intrinsic::ppc_qpx_qvstfiwa: { 15521 EVT VT; 15522 switch (Intrinsic) { 15523 case Intrinsic::ppc_qpx_qvstfda: 15524 VT = MVT::v4f64; 15525 break; 15526 case Intrinsic::ppc_qpx_qvstfsa: 15527 VT = MVT::v4f32; 15528 break; 15529 case Intrinsic::ppc_qpx_qvstfcda: 15530 VT = MVT::v2f64; 15531 break; 15532 case Intrinsic::ppc_qpx_qvstfcsa: 15533 VT = MVT::v2f32; 15534 break; 15535 default: 15536 VT = MVT::v4i32; 15537 break; 15538 } 15539 15540 Info.opc = ISD::INTRINSIC_VOID; 15541 Info.memVT = VT; 15542 Info.ptrVal = I.getArgOperand(1); 15543 Info.offset = 0; 15544 Info.size = VT.getStoreSize(); 15545 Info.align = Align(1); 15546 Info.flags = MachineMemOperand::MOStore; 15547 return true; 15548 } 15549 default: 15550 break; 15551 } 15552 15553 return false; 15554 } 15555 15556 /// It returns EVT::Other if the type should be determined using generic 15557 /// target-independent logic. 15558 EVT PPCTargetLowering::getOptimalMemOpType( 15559 const MemOp &Op, const AttributeList &FuncAttributes) const { 15560 if (getTargetMachine().getOptLevel() != CodeGenOpt::None) { 15561 // When expanding a memset, require at least two QPX instructions to cover 15562 // the cost of loading the value to be stored from the constant pool. 15563 if (Subtarget.hasQPX() && Op.size() >= 32 && 15564 (Op.isMemcpy() || Op.size() >= 64) && Op.isAligned(Align(32)) && 15565 !FuncAttributes.hasFnAttribute(Attribute::NoImplicitFloat)) { 15566 return MVT::v4f64; 15567 } 15568 15569 // We should use Altivec/VSX loads and stores when available. For unaligned 15570 // addresses, unaligned VSX loads are only fast starting with the P8. 15571 if (Subtarget.hasAltivec() && Op.size() >= 16 && 15572 (Op.isAligned(Align(16)) || 15573 ((Op.isMemset() && Subtarget.hasVSX()) || Subtarget.hasP8Vector()))) 15574 return MVT::v4i32; 15575 } 15576 15577 if (Subtarget.isPPC64()) { 15578 return MVT::i64; 15579 } 15580 15581 return MVT::i32; 15582 } 15583 15584 /// Returns true if it is beneficial to convert a load of a constant 15585 /// to just the constant itself. 15586 bool PPCTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 15587 Type *Ty) const { 15588 assert(Ty->isIntegerTy()); 15589 15590 unsigned BitSize = Ty->getPrimitiveSizeInBits(); 15591 return !(BitSize == 0 || BitSize > 64); 15592 } 15593 15594 bool PPCTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const { 15595 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy()) 15596 return false; 15597 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits(); 15598 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits(); 15599 return NumBits1 == 64 && NumBits2 == 32; 15600 } 15601 15602 bool PPCTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const { 15603 if (!VT1.isInteger() || !VT2.isInteger()) 15604 return false; 15605 unsigned NumBits1 = VT1.getSizeInBits(); 15606 unsigned NumBits2 = VT2.getSizeInBits(); 15607 return NumBits1 == 64 && NumBits2 == 32; 15608 } 15609 15610 bool PPCTargetLowering::isZExtFree(SDValue Val, EVT VT2) const { 15611 // Generally speaking, zexts are not free, but they are free when they can be 15612 // folded with other operations. 15613 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Val)) { 15614 EVT MemVT = LD->getMemoryVT(); 15615 if ((MemVT == MVT::i1 || MemVT == MVT::i8 || MemVT == MVT::i16 || 15616 (Subtarget.isPPC64() && MemVT == MVT::i32)) && 15617 (LD->getExtensionType() == ISD::NON_EXTLOAD || 15618 LD->getExtensionType() == ISD::ZEXTLOAD)) 15619 return true; 15620 } 15621 15622 // FIXME: Add other cases... 15623 // - 32-bit shifts with a zext to i64 15624 // - zext after ctlz, bswap, etc. 15625 // - zext after and by a constant mask 15626 15627 return TargetLowering::isZExtFree(Val, VT2); 15628 } 15629 15630 bool PPCTargetLowering::isFPExtFree(EVT DestVT, EVT SrcVT) const { 15631 assert(DestVT.isFloatingPoint() && SrcVT.isFloatingPoint() && 15632 "invalid fpext types"); 15633 // Extending to float128 is not free. 15634 if (DestVT == MVT::f128) 15635 return false; 15636 return true; 15637 } 15638 15639 bool PPCTargetLowering::isLegalICmpImmediate(int64_t Imm) const { 15640 return isInt<16>(Imm) || isUInt<16>(Imm); 15641 } 15642 15643 bool PPCTargetLowering::isLegalAddImmediate(int64_t Imm) const { 15644 return isInt<16>(Imm) || isUInt<16>(Imm); 15645 } 15646 15647 bool PPCTargetLowering::allowsMisalignedMemoryAccesses(EVT VT, 15648 unsigned, 15649 unsigned, 15650 MachineMemOperand::Flags, 15651 bool *Fast) const { 15652 if (DisablePPCUnaligned) 15653 return false; 15654 15655 // PowerPC supports unaligned memory access for simple non-vector types. 15656 // Although accessing unaligned addresses is not as efficient as accessing 15657 // aligned addresses, it is generally more efficient than manual expansion, 15658 // and generally only traps for software emulation when crossing page 15659 // boundaries. 15660 15661 if (!VT.isSimple()) 15662 return false; 15663 15664 if (VT.isFloatingPoint() && !VT.isVector() && 15665 !Subtarget.allowsUnalignedFPAccess()) 15666 return false; 15667 15668 if (VT.getSimpleVT().isVector()) { 15669 if (Subtarget.hasVSX()) { 15670 if (VT != MVT::v2f64 && VT != MVT::v2i64 && 15671 VT != MVT::v4f32 && VT != MVT::v4i32) 15672 return false; 15673 } else { 15674 return false; 15675 } 15676 } 15677 15678 if (VT == MVT::ppcf128) 15679 return false; 15680 15681 if (Fast) 15682 *Fast = true; 15683 15684 return true; 15685 } 15686 15687 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, 15688 EVT VT) const { 15689 return isFMAFasterThanFMulAndFAdd( 15690 MF.getFunction(), VT.getTypeForEVT(MF.getFunction().getContext())); 15691 } 15692 15693 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(const Function &F, 15694 Type *Ty) const { 15695 switch (Ty->getScalarType()->getTypeID()) { 15696 case Type::FloatTyID: 15697 case Type::DoubleTyID: 15698 return true; 15699 case Type::FP128TyID: 15700 return EnableQuadPrecision && Subtarget.hasP9Vector(); 15701 default: 15702 return false; 15703 } 15704 } 15705 15706 // Currently this is a copy from AArch64TargetLowering::isProfitableToHoist. 15707 // FIXME: add more patterns which are profitable to hoist. 15708 bool PPCTargetLowering::isProfitableToHoist(Instruction *I) const { 15709 if (I->getOpcode() != Instruction::FMul) 15710 return true; 15711 15712 if (!I->hasOneUse()) 15713 return true; 15714 15715 Instruction *User = I->user_back(); 15716 assert(User && "A single use instruction with no uses."); 15717 15718 if (User->getOpcode() != Instruction::FSub && 15719 User->getOpcode() != Instruction::FAdd) 15720 return true; 15721 15722 const TargetOptions &Options = getTargetMachine().Options; 15723 const Function *F = I->getFunction(); 15724 const DataLayout &DL = F->getParent()->getDataLayout(); 15725 Type *Ty = User->getOperand(0)->getType(); 15726 15727 return !( 15728 isFMAFasterThanFMulAndFAdd(*F, Ty) && 15729 isOperationLegalOrCustom(ISD::FMA, getValueType(DL, Ty)) && 15730 (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath)); 15731 } 15732 15733 const MCPhysReg * 15734 PPCTargetLowering::getScratchRegisters(CallingConv::ID) const { 15735 // LR is a callee-save register, but we must treat it as clobbered by any call 15736 // site. Hence we include LR in the scratch registers, which are in turn added 15737 // as implicit-defs for stackmaps and patchpoints. The same reasoning applies 15738 // to CTR, which is used by any indirect call. 15739 static const MCPhysReg ScratchRegs[] = { 15740 PPC::X12, PPC::LR8, PPC::CTR8, 0 15741 }; 15742 15743 return ScratchRegs; 15744 } 15745 15746 Register PPCTargetLowering::getExceptionPointerRegister( 15747 const Constant *PersonalityFn) const { 15748 return Subtarget.isPPC64() ? PPC::X3 : PPC::R3; 15749 } 15750 15751 Register PPCTargetLowering::getExceptionSelectorRegister( 15752 const Constant *PersonalityFn) const { 15753 return Subtarget.isPPC64() ? PPC::X4 : PPC::R4; 15754 } 15755 15756 bool 15757 PPCTargetLowering::shouldExpandBuildVectorWithShuffles( 15758 EVT VT , unsigned DefinedValues) const { 15759 if (VT == MVT::v2i64) 15760 return Subtarget.hasDirectMove(); // Don't need stack ops with direct moves 15761 15762 if (Subtarget.hasVSX() || Subtarget.hasQPX()) 15763 return true; 15764 15765 return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues); 15766 } 15767 15768 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const { 15769 if (DisableILPPref || Subtarget.enableMachineScheduler()) 15770 return TargetLowering::getSchedulingPreference(N); 15771 15772 return Sched::ILP; 15773 } 15774 15775 // Create a fast isel object. 15776 FastISel * 15777 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo, 15778 const TargetLibraryInfo *LibInfo) const { 15779 return PPC::createFastISel(FuncInfo, LibInfo); 15780 } 15781 15782 // Override to enable LOAD_STACK_GUARD lowering on Linux. 15783 bool PPCTargetLowering::useLoadStackGuardNode() const { 15784 if (!Subtarget.isTargetLinux()) 15785 return TargetLowering::useLoadStackGuardNode(); 15786 return true; 15787 } 15788 15789 // Override to disable global variable loading on Linux. 15790 void PPCTargetLowering::insertSSPDeclarations(Module &M) const { 15791 if (!Subtarget.isTargetLinux()) 15792 return TargetLowering::insertSSPDeclarations(M); 15793 } 15794 15795 bool PPCTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT, 15796 bool ForCodeSize) const { 15797 if (!VT.isSimple() || !Subtarget.hasVSX()) 15798 return false; 15799 15800 switch(VT.getSimpleVT().SimpleTy) { 15801 default: 15802 // For FP types that are currently not supported by PPC backend, return 15803 // false. Examples: f16, f80. 15804 return false; 15805 case MVT::f32: 15806 case MVT::f64: 15807 case MVT::ppcf128: 15808 return Imm.isPosZero(); 15809 } 15810 } 15811 15812 // For vector shift operation op, fold 15813 // (op x, (and y, ((1 << numbits(x)) - 1))) -> (target op x, y) 15814 static SDValue stripModuloOnShift(const TargetLowering &TLI, SDNode *N, 15815 SelectionDAG &DAG) { 15816 SDValue N0 = N->getOperand(0); 15817 SDValue N1 = N->getOperand(1); 15818 EVT VT = N0.getValueType(); 15819 unsigned OpSizeInBits = VT.getScalarSizeInBits(); 15820 unsigned Opcode = N->getOpcode(); 15821 unsigned TargetOpcode; 15822 15823 switch (Opcode) { 15824 default: 15825 llvm_unreachable("Unexpected shift operation"); 15826 case ISD::SHL: 15827 TargetOpcode = PPCISD::SHL; 15828 break; 15829 case ISD::SRL: 15830 TargetOpcode = PPCISD::SRL; 15831 break; 15832 case ISD::SRA: 15833 TargetOpcode = PPCISD::SRA; 15834 break; 15835 } 15836 15837 if (VT.isVector() && TLI.isOperationLegal(Opcode, VT) && 15838 N1->getOpcode() == ISD::AND) 15839 if (ConstantSDNode *Mask = isConstOrConstSplat(N1->getOperand(1))) 15840 if (Mask->getZExtValue() == OpSizeInBits - 1) 15841 return DAG.getNode(TargetOpcode, SDLoc(N), VT, N0, N1->getOperand(0)); 15842 15843 return SDValue(); 15844 } 15845 15846 SDValue PPCTargetLowering::combineSHL(SDNode *N, DAGCombinerInfo &DCI) const { 15847 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG)) 15848 return Value; 15849 15850 SDValue N0 = N->getOperand(0); 15851 ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N->getOperand(1)); 15852 if (!Subtarget.isISA3_0() || 15853 N0.getOpcode() != ISD::SIGN_EXTEND || 15854 N0.getOperand(0).getValueType() != MVT::i32 || 15855 CN1 == nullptr || N->getValueType(0) != MVT::i64) 15856 return SDValue(); 15857 15858 // We can't save an operation here if the value is already extended, and 15859 // the existing shift is easier to combine. 15860 SDValue ExtsSrc = N0.getOperand(0); 15861 if (ExtsSrc.getOpcode() == ISD::TRUNCATE && 15862 ExtsSrc.getOperand(0).getOpcode() == ISD::AssertSext) 15863 return SDValue(); 15864 15865 SDLoc DL(N0); 15866 SDValue ShiftBy = SDValue(CN1, 0); 15867 // We want the shift amount to be i32 on the extswli, but the shift could 15868 // have an i64. 15869 if (ShiftBy.getValueType() == MVT::i64) 15870 ShiftBy = DCI.DAG.getConstant(CN1->getZExtValue(), DL, MVT::i32); 15871 15872 return DCI.DAG.getNode(PPCISD::EXTSWSLI, DL, MVT::i64, N0->getOperand(0), 15873 ShiftBy); 15874 } 15875 15876 SDValue PPCTargetLowering::combineSRA(SDNode *N, DAGCombinerInfo &DCI) const { 15877 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG)) 15878 return Value; 15879 15880 return SDValue(); 15881 } 15882 15883 SDValue PPCTargetLowering::combineSRL(SDNode *N, DAGCombinerInfo &DCI) const { 15884 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG)) 15885 return Value; 15886 15887 return SDValue(); 15888 } 15889 15890 // Transform (add X, (zext(setne Z, C))) -> (addze X, (addic (addi Z, -C), -1)) 15891 // Transform (add X, (zext(sete Z, C))) -> (addze X, (subfic (addi Z, -C), 0)) 15892 // When C is zero, the equation (addi Z, -C) can be simplified to Z 15893 // Requirement: -C in [-32768, 32767], X and Z are MVT::i64 types 15894 static SDValue combineADDToADDZE(SDNode *N, SelectionDAG &DAG, 15895 const PPCSubtarget &Subtarget) { 15896 if (!Subtarget.isPPC64()) 15897 return SDValue(); 15898 15899 SDValue LHS = N->getOperand(0); 15900 SDValue RHS = N->getOperand(1); 15901 15902 auto isZextOfCompareWithConstant = [](SDValue Op) { 15903 if (Op.getOpcode() != ISD::ZERO_EXTEND || !Op.hasOneUse() || 15904 Op.getValueType() != MVT::i64) 15905 return false; 15906 15907 SDValue Cmp = Op.getOperand(0); 15908 if (Cmp.getOpcode() != ISD::SETCC || !Cmp.hasOneUse() || 15909 Cmp.getOperand(0).getValueType() != MVT::i64) 15910 return false; 15911 15912 if (auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1))) { 15913 int64_t NegConstant = 0 - Constant->getSExtValue(); 15914 // Due to the limitations of the addi instruction, 15915 // -C is required to be [-32768, 32767]. 15916 return isInt<16>(NegConstant); 15917 } 15918 15919 return false; 15920 }; 15921 15922 bool LHSHasPattern = isZextOfCompareWithConstant(LHS); 15923 bool RHSHasPattern = isZextOfCompareWithConstant(RHS); 15924 15925 // If there is a pattern, canonicalize a zext operand to the RHS. 15926 if (LHSHasPattern && !RHSHasPattern) 15927 std::swap(LHS, RHS); 15928 else if (!LHSHasPattern && !RHSHasPattern) 15929 return SDValue(); 15930 15931 SDLoc DL(N); 15932 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Glue); 15933 SDValue Cmp = RHS.getOperand(0); 15934 SDValue Z = Cmp.getOperand(0); 15935 auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1)); 15936 15937 assert(Constant && "Constant Should not be a null pointer."); 15938 int64_t NegConstant = 0 - Constant->getSExtValue(); 15939 15940 switch(cast<CondCodeSDNode>(Cmp.getOperand(2))->get()) { 15941 default: break; 15942 case ISD::SETNE: { 15943 // when C == 0 15944 // --> addze X, (addic Z, -1).carry 15945 // / 15946 // add X, (zext(setne Z, C))-- 15947 // \ when -32768 <= -C <= 32767 && C != 0 15948 // --> addze X, (addic (addi Z, -C), -1).carry 15949 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z, 15950 DAG.getConstant(NegConstant, DL, MVT::i64)); 15951 SDValue AddOrZ = NegConstant != 0 ? Add : Z; 15952 SDValue Addc = DAG.getNode(ISD::ADDC, DL, DAG.getVTList(MVT::i64, MVT::Glue), 15953 AddOrZ, DAG.getConstant(-1ULL, DL, MVT::i64)); 15954 return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64), 15955 SDValue(Addc.getNode(), 1)); 15956 } 15957 case ISD::SETEQ: { 15958 // when C == 0 15959 // --> addze X, (subfic Z, 0).carry 15960 // / 15961 // add X, (zext(sete Z, C))-- 15962 // \ when -32768 <= -C <= 32767 && C != 0 15963 // --> addze X, (subfic (addi Z, -C), 0).carry 15964 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z, 15965 DAG.getConstant(NegConstant, DL, MVT::i64)); 15966 SDValue AddOrZ = NegConstant != 0 ? Add : Z; 15967 SDValue Subc = DAG.getNode(ISD::SUBC, DL, DAG.getVTList(MVT::i64, MVT::Glue), 15968 DAG.getConstant(0, DL, MVT::i64), AddOrZ); 15969 return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64), 15970 SDValue(Subc.getNode(), 1)); 15971 } 15972 } 15973 15974 return SDValue(); 15975 } 15976 15977 // Transform 15978 // (add C1, (MAT_PCREL_ADDR GlobalAddr+C2)) to 15979 // (MAT_PCREL_ADDR GlobalAddr+(C1+C2)) 15980 // In this case both C1 and C2 must be known constants. 15981 // C1+C2 must fit into a 34 bit signed integer. 15982 static SDValue combineADDToMAT_PCREL_ADDR(SDNode *N, SelectionDAG &DAG, 15983 const PPCSubtarget &Subtarget) { 15984 if (!Subtarget.isUsingPCRelativeCalls()) 15985 return SDValue(); 15986 15987 // Check both Operand 0 and Operand 1 of the ADD node for the PCRel node. 15988 // If we find that node try to cast the Global Address and the Constant. 15989 SDValue LHS = N->getOperand(0); 15990 SDValue RHS = N->getOperand(1); 15991 15992 if (LHS.getOpcode() != PPCISD::MAT_PCREL_ADDR) 15993 std::swap(LHS, RHS); 15994 15995 if (LHS.getOpcode() != PPCISD::MAT_PCREL_ADDR) 15996 return SDValue(); 15997 15998 // Operand zero of PPCISD::MAT_PCREL_ADDR is the GA node. 15999 GlobalAddressSDNode *GSDN = dyn_cast<GlobalAddressSDNode>(LHS.getOperand(0)); 16000 ConstantSDNode* ConstNode = dyn_cast<ConstantSDNode>(RHS); 16001 16002 // Check that both casts succeeded. 16003 if (!GSDN || !ConstNode) 16004 return SDValue(); 16005 16006 int64_t NewOffset = GSDN->getOffset() + ConstNode->getSExtValue(); 16007 SDLoc DL(GSDN); 16008 16009 // The signed int offset needs to fit in 34 bits. 16010 if (!isInt<34>(NewOffset)) 16011 return SDValue(); 16012 16013 // The new global address is a copy of the old global address except 16014 // that it has the updated Offset. 16015 SDValue GA = 16016 DAG.getTargetGlobalAddress(GSDN->getGlobal(), DL, GSDN->getValueType(0), 16017 NewOffset, GSDN->getTargetFlags()); 16018 SDValue MatPCRel = 16019 DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, GSDN->getValueType(0), GA); 16020 return MatPCRel; 16021 } 16022 16023 SDValue PPCTargetLowering::combineADD(SDNode *N, DAGCombinerInfo &DCI) const { 16024 if (auto Value = combineADDToADDZE(N, DCI.DAG, Subtarget)) 16025 return Value; 16026 16027 if (auto Value = combineADDToMAT_PCREL_ADDR(N, DCI.DAG, Subtarget)) 16028 return Value; 16029 16030 return SDValue(); 16031 } 16032 16033 // Detect TRUNCATE operations on bitcasts of float128 values. 16034 // What we are looking for here is the situtation where we extract a subset 16035 // of bits from a 128 bit float. 16036 // This can be of two forms: 16037 // 1) BITCAST of f128 feeding TRUNCATE 16038 // 2) BITCAST of f128 feeding SRL (a shift) feeding TRUNCATE 16039 // The reason this is required is because we do not have a legal i128 type 16040 // and so we want to prevent having to store the f128 and then reload part 16041 // of it. 16042 SDValue PPCTargetLowering::combineTRUNCATE(SDNode *N, 16043 DAGCombinerInfo &DCI) const { 16044 // If we are using CRBits then try that first. 16045 if (Subtarget.useCRBits()) { 16046 // Check if CRBits did anything and return that if it did. 16047 if (SDValue CRTruncValue = DAGCombineTruncBoolExt(N, DCI)) 16048 return CRTruncValue; 16049 } 16050 16051 SDLoc dl(N); 16052 SDValue Op0 = N->getOperand(0); 16053 16054 // Looking for a truncate of i128 to i64. 16055 if (Op0.getValueType() != MVT::i128 || N->getValueType(0) != MVT::i64) 16056 return SDValue(); 16057 16058 int EltToExtract = DCI.DAG.getDataLayout().isBigEndian() ? 1 : 0; 16059 16060 // SRL feeding TRUNCATE. 16061 if (Op0.getOpcode() == ISD::SRL) { 16062 ConstantSDNode *ConstNode = dyn_cast<ConstantSDNode>(Op0.getOperand(1)); 16063 // The right shift has to be by 64 bits. 16064 if (!ConstNode || ConstNode->getZExtValue() != 64) 16065 return SDValue(); 16066 16067 // Switch the element number to extract. 16068 EltToExtract = EltToExtract ? 0 : 1; 16069 // Update Op0 past the SRL. 16070 Op0 = Op0.getOperand(0); 16071 } 16072 16073 // BITCAST feeding a TRUNCATE possibly via SRL. 16074 if (Op0.getOpcode() == ISD::BITCAST && 16075 Op0.getValueType() == MVT::i128 && 16076 Op0.getOperand(0).getValueType() == MVT::f128) { 16077 SDValue Bitcast = DCI.DAG.getBitcast(MVT::v2i64, Op0.getOperand(0)); 16078 return DCI.DAG.getNode( 16079 ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Bitcast, 16080 DCI.DAG.getTargetConstant(EltToExtract, dl, MVT::i32)); 16081 } 16082 return SDValue(); 16083 } 16084 16085 SDValue PPCTargetLowering::combineMUL(SDNode *N, DAGCombinerInfo &DCI) const { 16086 SelectionDAG &DAG = DCI.DAG; 16087 16088 ConstantSDNode *ConstOpOrElement = isConstOrConstSplat(N->getOperand(1)); 16089 if (!ConstOpOrElement) 16090 return SDValue(); 16091 16092 // An imul is usually smaller than the alternative sequence for legal type. 16093 if (DAG.getMachineFunction().getFunction().hasMinSize() && 16094 isOperationLegal(ISD::MUL, N->getValueType(0))) 16095 return SDValue(); 16096 16097 auto IsProfitable = [this](bool IsNeg, bool IsAddOne, EVT VT) -> bool { 16098 switch (this->Subtarget.getCPUDirective()) { 16099 default: 16100 // TODO: enhance the condition for subtarget before pwr8 16101 return false; 16102 case PPC::DIR_PWR8: 16103 // type mul add shl 16104 // scalar 4 1 1 16105 // vector 7 2 2 16106 return true; 16107 case PPC::DIR_PWR9: 16108 case PPC::DIR_PWR10: 16109 case PPC::DIR_PWR_FUTURE: 16110 // type mul add shl 16111 // scalar 5 2 2 16112 // vector 7 2 2 16113 16114 // The cycle RATIO of related operations are showed as a table above. 16115 // Because mul is 5(scalar)/7(vector), add/sub/shl are all 2 for both 16116 // scalar and vector type. For 2 instrs patterns, add/sub + shl 16117 // are 4, it is always profitable; but for 3 instrs patterns 16118 // (mul x, -(2^N + 1)) => -(add (shl x, N), x), sub + add + shl are 6. 16119 // So we should only do it for vector type. 16120 return IsAddOne && IsNeg ? VT.isVector() : true; 16121 } 16122 }; 16123 16124 EVT VT = N->getValueType(0); 16125 SDLoc DL(N); 16126 16127 const APInt &MulAmt = ConstOpOrElement->getAPIntValue(); 16128 bool IsNeg = MulAmt.isNegative(); 16129 APInt MulAmtAbs = MulAmt.abs(); 16130 16131 if ((MulAmtAbs - 1).isPowerOf2()) { 16132 // (mul x, 2^N + 1) => (add (shl x, N), x) 16133 // (mul x, -(2^N + 1)) => -(add (shl x, N), x) 16134 16135 if (!IsProfitable(IsNeg, true, VT)) 16136 return SDValue(); 16137 16138 SDValue Op0 = N->getOperand(0); 16139 SDValue Op1 = 16140 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0), 16141 DAG.getConstant((MulAmtAbs - 1).logBase2(), DL, VT)); 16142 SDValue Res = DAG.getNode(ISD::ADD, DL, VT, Op0, Op1); 16143 16144 if (!IsNeg) 16145 return Res; 16146 16147 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Res); 16148 } else if ((MulAmtAbs + 1).isPowerOf2()) { 16149 // (mul x, 2^N - 1) => (sub (shl x, N), x) 16150 // (mul x, -(2^N - 1)) => (sub x, (shl x, N)) 16151 16152 if (!IsProfitable(IsNeg, false, VT)) 16153 return SDValue(); 16154 16155 SDValue Op0 = N->getOperand(0); 16156 SDValue Op1 = 16157 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0), 16158 DAG.getConstant((MulAmtAbs + 1).logBase2(), DL, VT)); 16159 16160 if (!IsNeg) 16161 return DAG.getNode(ISD::SUB, DL, VT, Op1, Op0); 16162 else 16163 return DAG.getNode(ISD::SUB, DL, VT, Op0, Op1); 16164 16165 } else { 16166 return SDValue(); 16167 } 16168 } 16169 16170 bool PPCTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 16171 // Only duplicate to increase tail-calls for the 64bit SysV ABIs. 16172 if (!Subtarget.is64BitELFABI()) 16173 return false; 16174 16175 // If not a tail call then no need to proceed. 16176 if (!CI->isTailCall()) 16177 return false; 16178 16179 // If sibling calls have been disabled and tail-calls aren't guaranteed 16180 // there is no reason to duplicate. 16181 auto &TM = getTargetMachine(); 16182 if (!TM.Options.GuaranteedTailCallOpt && DisableSCO) 16183 return false; 16184 16185 // Can't tail call a function called indirectly, or if it has variadic args. 16186 const Function *Callee = CI->getCalledFunction(); 16187 if (!Callee || Callee->isVarArg()) 16188 return false; 16189 16190 // Make sure the callee and caller calling conventions are eligible for tco. 16191 const Function *Caller = CI->getParent()->getParent(); 16192 if (!areCallingConvEligibleForTCO_64SVR4(Caller->getCallingConv(), 16193 CI->getCallingConv())) 16194 return false; 16195 16196 // If the function is local then we have a good chance at tail-calling it 16197 return getTargetMachine().shouldAssumeDSOLocal(*Caller->getParent(), Callee); 16198 } 16199 16200 bool PPCTargetLowering::hasBitPreservingFPLogic(EVT VT) const { 16201 if (!Subtarget.hasVSX()) 16202 return false; 16203 if (Subtarget.hasP9Vector() && VT == MVT::f128) 16204 return true; 16205 return VT == MVT::f32 || VT == MVT::f64 || 16206 VT == MVT::v4f32 || VT == MVT::v2f64; 16207 } 16208 16209 bool PPCTargetLowering:: 16210 isMaskAndCmp0FoldingBeneficial(const Instruction &AndI) const { 16211 const Value *Mask = AndI.getOperand(1); 16212 // If the mask is suitable for andi. or andis. we should sink the and. 16213 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Mask)) { 16214 // Can't handle constants wider than 64-bits. 16215 if (CI->getBitWidth() > 64) 16216 return false; 16217 int64_t ConstVal = CI->getZExtValue(); 16218 return isUInt<16>(ConstVal) || 16219 (isUInt<16>(ConstVal >> 16) && !(ConstVal & 0xFFFF)); 16220 } 16221 16222 // For non-constant masks, we can always use the record-form and. 16223 return true; 16224 } 16225 16226 // Transform (abs (sub (zext a), (zext b))) to (vabsd a b 0) 16227 // Transform (abs (sub (zext a), (zext_invec b))) to (vabsd a b 0) 16228 // Transform (abs (sub (zext_invec a), (zext_invec b))) to (vabsd a b 0) 16229 // Transform (abs (sub (zext_invec a), (zext b))) to (vabsd a b 0) 16230 // Transform (abs (sub a, b) to (vabsd a b 1)) if a & b of type v4i32 16231 SDValue PPCTargetLowering::combineABS(SDNode *N, DAGCombinerInfo &DCI) const { 16232 assert((N->getOpcode() == ISD::ABS) && "Need ABS node here"); 16233 assert(Subtarget.hasP9Altivec() && 16234 "Only combine this when P9 altivec supported!"); 16235 EVT VT = N->getValueType(0); 16236 if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8) 16237 return SDValue(); 16238 16239 SelectionDAG &DAG = DCI.DAG; 16240 SDLoc dl(N); 16241 if (N->getOperand(0).getOpcode() == ISD::SUB) { 16242 // Even for signed integers, if it's known to be positive (as signed 16243 // integer) due to zero-extended inputs. 16244 unsigned SubOpcd0 = N->getOperand(0)->getOperand(0).getOpcode(); 16245 unsigned SubOpcd1 = N->getOperand(0)->getOperand(1).getOpcode(); 16246 if ((SubOpcd0 == ISD::ZERO_EXTEND || 16247 SubOpcd0 == ISD::ZERO_EXTEND_VECTOR_INREG) && 16248 (SubOpcd1 == ISD::ZERO_EXTEND || 16249 SubOpcd1 == ISD::ZERO_EXTEND_VECTOR_INREG)) { 16250 return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(), 16251 N->getOperand(0)->getOperand(0), 16252 N->getOperand(0)->getOperand(1), 16253 DAG.getTargetConstant(0, dl, MVT::i32)); 16254 } 16255 16256 // For type v4i32, it can be optimized with xvnegsp + vabsduw 16257 if (N->getOperand(0).getValueType() == MVT::v4i32 && 16258 N->getOperand(0).hasOneUse()) { 16259 return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(), 16260 N->getOperand(0)->getOperand(0), 16261 N->getOperand(0)->getOperand(1), 16262 DAG.getTargetConstant(1, dl, MVT::i32)); 16263 } 16264 } 16265 16266 return SDValue(); 16267 } 16268 16269 // For type v4i32/v8ii16/v16i8, transform 16270 // from (vselect (setcc a, b, setugt), (sub a, b), (sub b, a)) to (vabsd a, b) 16271 // from (vselect (setcc a, b, setuge), (sub a, b), (sub b, a)) to (vabsd a, b) 16272 // from (vselect (setcc a, b, setult), (sub b, a), (sub a, b)) to (vabsd a, b) 16273 // from (vselect (setcc a, b, setule), (sub b, a), (sub a, b)) to (vabsd a, b) 16274 SDValue PPCTargetLowering::combineVSelect(SDNode *N, 16275 DAGCombinerInfo &DCI) const { 16276 assert((N->getOpcode() == ISD::VSELECT) && "Need VSELECT node here"); 16277 assert(Subtarget.hasP9Altivec() && 16278 "Only combine this when P9 altivec supported!"); 16279 16280 SelectionDAG &DAG = DCI.DAG; 16281 SDLoc dl(N); 16282 SDValue Cond = N->getOperand(0); 16283 SDValue TrueOpnd = N->getOperand(1); 16284 SDValue FalseOpnd = N->getOperand(2); 16285 EVT VT = N->getOperand(1).getValueType(); 16286 16287 if (Cond.getOpcode() != ISD::SETCC || TrueOpnd.getOpcode() != ISD::SUB || 16288 FalseOpnd.getOpcode() != ISD::SUB) 16289 return SDValue(); 16290 16291 // ABSD only available for type v4i32/v8i16/v16i8 16292 if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8) 16293 return SDValue(); 16294 16295 // At least to save one more dependent computation 16296 if (!(Cond.hasOneUse() || TrueOpnd.hasOneUse() || FalseOpnd.hasOneUse())) 16297 return SDValue(); 16298 16299 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get(); 16300 16301 // Can only handle unsigned comparison here 16302 switch (CC) { 16303 default: 16304 return SDValue(); 16305 case ISD::SETUGT: 16306 case ISD::SETUGE: 16307 break; 16308 case ISD::SETULT: 16309 case ISD::SETULE: 16310 std::swap(TrueOpnd, FalseOpnd); 16311 break; 16312 } 16313 16314 SDValue CmpOpnd1 = Cond.getOperand(0); 16315 SDValue CmpOpnd2 = Cond.getOperand(1); 16316 16317 // SETCC CmpOpnd1 CmpOpnd2 cond 16318 // TrueOpnd = CmpOpnd1 - CmpOpnd2 16319 // FalseOpnd = CmpOpnd2 - CmpOpnd1 16320 if (TrueOpnd.getOperand(0) == CmpOpnd1 && 16321 TrueOpnd.getOperand(1) == CmpOpnd2 && 16322 FalseOpnd.getOperand(0) == CmpOpnd2 && 16323 FalseOpnd.getOperand(1) == CmpOpnd1) { 16324 return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(1).getValueType(), 16325 CmpOpnd1, CmpOpnd2, 16326 DAG.getTargetConstant(0, dl, MVT::i32)); 16327 } 16328 16329 return SDValue(); 16330 } 16331